Made NBEngine installable + CMake restruct

This commit is contained in:
NaifBanana
2026-07-19 22:19:50 -05:00
parent abbae156a2
commit 5415a01885
26 changed files with 159 additions and 78 deletions
+214
View File
@@ -0,0 +1,214 @@
#pragma once
#ifndef _NB_ANSI_TERM
#define _NB_ANSI_TERM
#include <iostream>
#include <string>
#include <type_traits>
/*
----------- TECH DEBT ------------
Idk wtf to do here. This was originally to allow me to print
to terminal easily, but it's becoming too much of an investment.
For the time being, drop it.
*/
namespace nb {
template <typename ST, typename U>
struct SmartText {
using Type = ST;
using ValType = U;
static constexpr bool HasChild = Type::HasChild;
SmartText() = default;
};
template <typename Type, typename U>
struct StyleFormatter : SmartText<StyleFormatter<Type, U>, U> {
using Base = SmartText<StyleFormatter<Type, U>, U>;
using typename Base::ValType;
static constexpr bool HasChild = true;
StyleFormatter(const std::string& _fmt, const ValType& _val, const std::string& _closing) :
fmt{_fmt}, val{_val}, closing{_closing} {}
std::string fmt;
ValType val;
std::string closing;
};
template <typename Child>
struct StyleFormatter<Child, void> : SmartText<StyleFormatter<Child, void>, void>{
using Base = SmartText<StyleFormatter<Child, void>, void>;
using Base::ValType;
static constexpr bool HasChild = false;
StyleFormatter(const std::string& _fmt) : fmt{_fmt} {}
std::string fmt;
};
template <typename U=void>
struct ANSITextColor;
template <typename U>
struct ANSITextColor : StyleFormatter<ANSITextColor<U>, U> {
using Base = StyleFormatter<ANSITextColor, U>;
using typename Base::ValType;
using Base::HasChild;
template <typename = typename std::enable_if<HasChild, U>::type>
ANSITextColor(const U& _val) : Base{"\x1b[39m", _val, "\x1b[39m"} {}
template <typename = typename std::enable_if<!HasChild, U>>
ANSITextColor() : Base{"\x1b[92m"} {}
};
template <>
struct ANSITextColor<std::string> : StyleFormatter<ANSITextColor<std::string>, std::string> {
using Base = StyleFormatter<ANSITextColor<std::string>, std::string>;
static constexpr bool HasChild = Base::HasChild;
template <std::size_t N>
ANSITextColor(char const(&_val) [N]) : Base{"\x1b[92m", _val, "\x1b[39m"} {}
ANSITextColor(const char* _val) : Base{"\x1b[92m", _val, "\x1b[39m"} {}
ANSITextColor(const std::string& _val) : Base{"\x1b[92m", _val, "\x1b[39m"} {}
};
} // namespace nb
template<typename Type, typename U>
std::ostream& operator<<(std::ostream& stream, const nb::StyleFormatter<Type, U>& msg) {
if (&stream == &std::cout) {
stream << msg.fmt;
if (msg.HasChild) {
stream << msg.val << msg.closing;
}
} else {
if (msg.HasChild) { stream << msg.val; }
}
stream << std::flush;
return stream;
}
/* struct CellBase {
uint8_t width;
uint8_t height;
};
template <typename T>
struct Cell : SmartText<Cell<T>, T> {
using Base = SmartText<Cell<T>, T>;
using typename Base::ValType;
using Base::HasChild;
Cell(const ValType& _val, const uint8_t& w, const uint8_t& h=1)
: val(_val), width(w), height(h) {}
ValType val;
uint8_t width;
uint8_t height;
};
template <>
struct Cell<std::string> : SmartText<Cell<std::string>, std::string> {
using Base = SmartText<Cell<std::string>, std::string>;
using typename Base::ValType;
using Base::HasChild;
template <std::size_t N>
Cell( const(&_val) [N], const uint8_t& w, const uint8_t& h=0) : Cell(std::string(_val), w, h) {}
Cell(char* _val, const uint8_t& w, const uint8_t& h=0) : Cell(std::string(_val), w, h) {}
Cell(const ValType& _val, const uint8_t& w, const uint8_t& h=0)
: val(_val), width(w) {
unsigned int strsize = _val.size();
height = strsize / width;
height += (strsize % width) ? 1 : 0;
}
ValType val;
uint8_t width;
uint8_t height;
};
template <typename T>
std::ostream& operator<<(std::ostream& stream, const Cell<T>& cll) {
if (&stream == &std::cout) {
stream << "\x1b[s" << cll.val << "\x1b[u\x1b[" << 1+cll.width << "C\x1b[" << 1+cll.height;
}
return stream;
}
template <typename T>
void ChangeCellHeight(int i, Cell<T>& cll, const unsigned int& h) {
if (h < cll.height) { cll.height=h; }
}
template <typename T>
void GetTallestCell(int i, Cell<T>& cll, unsigned int& h) {
if (cll.height > h) { h = cll.height; }
}
template <typename... Pack>
struct TableRow {
using RowCells = std::tuple<Cell<Pack>...>;
using CellWidths = std::array<int, sizeof...(Pack)>;
using DelimiterArray = std::array<std::string, sizeof...(Pack)+1>;
TableRow(CellWidths&& widths_, DelimiterArray&& delims_, const Pack&... vals_)
: widths(widths_), delimiters(delims_), topBorder("") {
nb::ForEach(_cells, GetTallestCell, _height);
}
static constexpr int num_columns = sizeof...(Pack);
int height() const { return height; }
inline int height(const unsigned int newh) {
nb::ForEach(_cells, ChangeCellHeight, newh);
return (_height=newh);
}
const CellWidths widths;
const DelimiterArray delimiters;
const std::string topBorder;
const std::string bottomBorder;
protected:
RowCells _cells;
int _height;
};
template <typename... Pack>
std::ostream& operator<<(std::ostream& stream, const TableRow<Pack...>& row) {
}
template<typename... Pack>
class Table {
public:
Table(const Pack&... _vals) : row(std::array<int, sizeof...(Pack)>(10),
std::array<std::string, sizeof...(Pack)>(""), _vals...) {}
private:
TableRow<Pack...> row;
};
} // namespace nb
#ifdef _NB_TARGET_WINDOWS
template<typename... Types>
std::ostream& operator<<(std::ostream& stream, const nb::TableRow<Types...>& row) {
using PosType = decltype(stream.tellp());
constexpr int num_cells = sizeof...(Types);
int col_num = 0;
int col_start = 0;
return stream;
}
#endif // _NB_TARGET_WINDOWS */
#endif // _NB_ANSI_TERM
+134
View File
@@ -0,0 +1,134 @@
#pragma once
#ifndef _NB_DATASINK
#define _NB_DATASINK
#include <atomic>
#include <thread>
#include <NBCore/ThreadSafeQueue.hpp>
namespace nb {
template<typename DataType>
class DataSink {
public:
DataSink(const DataSink&) = delete;
DataSink(DataSink&&) = delete;
DataSink& operator=(const DataSink&) = delete;
virtual bool isRunning() const noexcept {
return _running;
}
virtual bool stop() noexcept = 0;
virtual bool run() = 0;
virtual bool in(const DataType&) = 0;
protected:
DataSink() = default;
std::atomic<bool> _running;
};
template<typename DataType, typename BufferType, typename ProcessorType>
class BufferedDataProcessor : public DataSink<DataType> {
using Base = DataSink<DataType>;
public:
using Base::Base;
virtual bool stop() noexcept override { return type_ptr->stop(); }
virtual bool run() override { return type_ptr->run(); }
virtual bool in(const DataType& val) override { return type_ptr->in(val); }
protected:
unsigned int count() const {
return type_ptr->count();
}
void push(const DataType& val) {
type_ptr->push(val);
}
DataType pop() {
return type_ptr->pop();
}
void flush() {
type_ptr->flush();
}
void clear() {
type_ptr->clear();
}
bool process(const DataType& val) {
return type_ptr->process(val);
}
using Base::_running;
BufferType _buffer;
private:
ProcessorType* const type_ptr = static_cast<ProcessorType*>(this);
};
template<typename DataType, typename ProcessorType>
class MultithreadedDataProcessor
: public BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType> {
using Base = BufferedDataProcessor<DataType, ThreadsafeQueue<DataType>, ProcessorType>;
public:
~MultithreadedDataProcessor() { type_ptr->stop(); }
bool isRunning() const noexcept override {
return this->_running;
}
bool run() override {
if (!type_ptr->isRunning()) {
this->_running = true;
_runningThread = std::make_shared<std::thread>([&]{
while(type_ptr->isRunning()) {
flush();
}
});
}
return this->isRunning();
}
bool stop() noexcept override {
if (type_ptr->isRunning()) {
this->_running = false;
_runningThread->join();
_runningThread = nullptr;
}
return !type_ptr->isRunning();
}
protected:
using Base::Base;
unsigned int count() const {
return this->_buffer.size();
}
void push(const DataType& val) {
this->_buffer.push(val);
};
DataType pop() {
std::shared_ptr<DataType> event;
this->_buffer.pop(event);
this->process(*event);
return *event;
}
void flush() {
while(type_ptr->count()) {
pop();
}
}
void clear() {
this->_buffer.empty();
}
std::shared_ptr<std::thread> _runningThread;
private:
ProcessorType* type_ptr = static_cast<ProcessorType*>(this);
};
} // namespace nb
#endif // _NB_DATASINK
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#ifndef _NB_ERROR
#define _NB_ERROR
#include <NBCore/ErrorsImpl.hpp>
#include <NBCore/Logger.hpp>
namespace nb {
#ifdef _NB_AUTOLOG
#ifdef _NB_CODE_ERROR_LOCATIONS
#ifndef LOG
#define LOG(args...) nb::logger.log(args, __FILE__, __LINE__)
#endif // LOG
#ifndef WARN
#define WARN(args...) nb::logger.warn(args, __FILE__, __LINE__)
#endif // WARN
#ifndef ERROR
#define ERROR(args...) nb::logger.error(args, __FILE__, __LINE__)
#endif // ERROR
#else
#ifndef LOG
#define LOG(args...) nb::logger.log(args)
#endif // LOG
#ifndef WARN
#define WARN(args...) nb::logger.warn(args)
#endif // WARN
#ifndef ERROR
#define ERROR(args...) nb::logger.error(args)
#endif // ERROR
#endif // _NB_CODE_ERROR_LOCATIONS
#endif // _NB_AUTOLOG
#ifndef THROW
#ifdef _NB_AUTOLOG
#define THROW(args...) ERROR(args); nb::logger.stop(); throw args
#else
#define THROW(args...) throw args
#endif // _NB_CODE_ERROR_LOCATIONS
#endif // THROW
} // namespace nb
#endif // _NB_ERROR
+176
View File
@@ -0,0 +1,176 @@
#pragma once
#ifndef _NB_ERRORS_IMPL
#define _NB_ERRORS_IMPL
#include <exception>
#include <memory>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <NBCore/StringUtils.hpp>
namespace nb {
typedef std::unordered_map<unsigned int, std::string> ErrorCodeMap;
class ErrorBase {
protected:
public:
const unsigned int code;
const std::string msg;
const std::string type;
const std::shared_ptr<ErrorBase> trace;
ErrorBase(const ErrorBase&) = default;
ErrorBase(const std::exception&) noexcept;
ErrorBase(const std::string&) noexcept;
virtual std::string what() const noexcept {
std::string ret = msg;
if (trace) {
std::string trace_msg = msg;
ret += NEWLINE + indent_strblock(
trace_msg,
TABOVER,
TABOVER+"Trace: "
);
}
return ret;
}
protected:
ErrorBase(
unsigned int code_,
std::string msg_,
std::string type_,
std::shared_ptr<ErrorBase> trace_
) noexcept :
code(code_),
msg(msg_),
type(type_),
trace{trace_}
{}
};
template <class ErrorType=NoneType>
class Error : public ErrorBase {
private:
void inline check_asserts() {
static_assert(std::is_same<const ErrorCodeMap, decltype(ErrorType::ErrorMessages)>::value,
"const std::unordered_map<unsigned int, const char*> ErrorMessages must be "
"a class member."
);
static_assert(std::is_enum_v<typename ErrorType::Codes>, "enum Codes must be a class member.");
static_assert(std::is_same<std::underlying_type_t<typename ErrorType::Codes>, unsigned int>::value,
"enum Codes must be of underlying type unsigned int."
);
static_assert(std::is_same<const std::string, decltype(ErrorType::type)>::value,
"const std::string type must be a class member."
);
}
protected:
using ErrorBase::ErrorBase;
public:
Error(
unsigned int code_,
const ErrorBase& trace_
) noexcept : ErrorBase(
code_,
ErrorType::ErrorMessages.at(code_),
ErrorType::type,
std::make_shared<ErrorBase>(trace_)
) { check_asserts(); }
Error(
std::string msg_,
const ErrorBase& trace_
) noexcept : ErrorBase(
0,
msg_,
ErrorType::type,
std::make_shared<ErrorBase>(trace_)
) { check_asserts(); }
Error(unsigned int code_) noexcept : ErrorBase(
code_,
ErrorType::ErrorMessages.at(code_),
ErrorType::type,
nullptr
) { check_asserts(); }
Error(std::string msg_) noexcept : ErrorBase(
0,
msg_,
ErrorType::type,
nullptr
) { check_asserts(); }
Error(
unsigned int code_,
const std::string& note_,
const ErrorBase& trace_
) noexcept : ErrorBase(
code_,
ErrorType::ErrorMessages.at(code_) + " (" + note_ + ")",
ErrorType::type,
std::make_shared<ErrorBase>(trace_)
) { check_asserts(); }
Error(unsigned int code_, const std::string& note_) noexcept : ErrorBase(
code_,
ErrorType::ErrorMessages.at(code_) + " (" + note_ + ")",
ErrorType::type,
nullptr
) { check_asserts(); }
using ErrorBase::what;
using ErrorBase::code;
using ErrorBase::msg;
using ErrorBase::trace;
using ErrorBase::type;
};
template<>
class Error<NoneType> : public Error<Error<NoneType>> {
protected:
using Base = Error<Error<NoneType>>;
public:
using Base::what;
using Base::code;
using Base::trace;
enum Codes : unsigned int {
STANDARD, UNDEFINED, INDEX_ERROR
};
inline static const std::string type = "nb::Error";
inline static const ErrorCodeMap ErrorMessages = {
{STANDARD, "std::exception"},
{UNDEFINED, "Error"},
{INDEX_ERROR, "Indexing error"}
};
Error(unsigned int code_=1) noexcept : Base(code_) {}
Error(const std::exception& err) : Base(
STANDARD,
std::string(err.what()),
"std::exception",
nullptr
) {}
Error(const std::string& msg_) noexcept : Base(
Codes::UNDEFINED,
msg_,
type,
nullptr
) {}
};
template<typename... Args>
Error(Args...) -> Error<NoneType>;
} // namespace nb
#endif // _NB_ERRORS_IMPL
+193
View File
@@ -0,0 +1,193 @@
#pragma once
#ifndef _NB_LOGGER
#define _NB_LOGGER
#include <chrono>
#include <ostream>
#include <thread>
#include <unordered_map>
#include <vector>
#include <NBCore/DataSink.hpp>
#include <NBCore/ErrorsImpl.hpp>
#include <NBCore/Processes.hpp>
#include <NBCore/ThreadSafeQueue.hpp>
#include <NBCore/TypeTraits.hpp>
namespace nb {
class ErrorBase;
typedef std::chrono::time_point<
std::chrono::system_clock,
std::chrono::nanoseconds
> LoggerTimePoint;
typedef std::string (*LogProcessFunction)(const LoggerTimePoint&, const std::string&);
typedef std::unordered_map<uint8_t, LogProcessFunction> LogProcessFunctionMap;
template<typename LogType, typename Logger, typename ST=std::ostream*>
class LoggerBase
: public MultithreadedDataProcessor<LogType, Logger>{
using StreamType = ST;
using LoggerType = Logger;
using Base = MultithreadedDataProcessor<LogType, LoggerType>;
public:
bool run() override {
if (!static_cast<LoggerType*>(this)->isRunning()) {
this->_running = true;
this->_runningThread = std::make_shared<std::thread>([&]{
while(static_cast<LoggerType*>(this)->isRunning()) {
static_cast<LoggerType*>(this)->flush();
}
static_cast<LoggerType*>(this)->flush();
});
}
return static_cast<LoggerType*>(this)->isRunning();
}
using Base::flush;
protected:
LoggerBase() = default;
StreamType _ostream;
};
struct LogEvent{
const LoggerTimePoint time;
const unsigned char lvl;
const std::string msg;
const std::thread::id tid;
const uint64_t pid;
const std::string file="";
const unsigned int line=0;
};
template <typename LT>
class DebugLogger : public LoggerBase<LogEvent, LT, std::vector<std::ostream*>>{
using StreamType = std::vector<std::ostream*>;
using LoggerType = LT;
using Base = LoggerBase<LogEvent, LoggerType, StreamType>;
public:
template<typename... ST>
DebugLogger(ST&... streams) : _ostream(nb::RefPackToPtrVec<std::ostream, ST...>(streams...).vec) {}
~DebugLogger() { static_cast<LoggerType*>(this)->stop(); }
template<typename U>
void log(
U val,
std::string file="",
unsigned int line=0
) { static_cast<LoggerType*>(this)->write_message(val, 0x00, file, line); }
template<typename U>
void warn(
U val,
uint8_t lvl=0x01,
std::string file="",
unsigned int line=0
) { static_cast<LoggerType*>(this)->write_message(val, lvl, file, line); }
void error(
const ErrorBase& val,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(val, 0xFF, file, line);
static_cast<LoggerType*>(this)->flush();
}
void error(
const std::string& val,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(Error(val), 0xFF, file, line);
static_cast<LoggerType*>(this)->flush();
}
protected:
std::vector<std::ostream*> _ostream;
void write_message(
std::string msg,
uint8_t lvl=0x00,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->push(LogEvent{
std::chrono::system_clock::now(),
lvl,
msg,
std::this_thread::get_id(),
GetPID(),
file,
line
});
}
template <size_t N>
void write_message(
char const(&msg) [N],
uint8_t lvl=0x00,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(std::string(msg), lvl, file, line);
}
void write_message(
const ErrorBase& err,
uint8_t lvl=0x00,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(err.what(), lvl, file, line);
}
template<typename U>
std::enable_if_t<std::is_integral_v<U>, void> write_message(
const U& val,
uint8_t lvl=0x00,
std::string file="",
unsigned int line=0
) {
static_cast<LoggerType*>(this)->write_message(std::to_string(val), lvl, file, line);
}
};
class DefaultDebugLogger : public DebugLogger<DefaultDebugLogger> {
using LoggerType = DefaultDebugLogger;
using Base = DebugLogger<DefaultDebugLogger>;
template <typename... Ts>
struct LogRow;
public:
using Base::Base;
~DefaultDebugLogger() { stop(); }
friend class BufferedDataProcessor<LogEvent, ThreadsafeQueue<LogEvent>, DefaultDebugLogger>;
template <typename STR, typename... Ts>
friend STR& operator<<(STR&, const DefaultDebugLogger::LogRow<Ts...>&);
protected:
using Base::_ostream;
bool process(const LogEvent& msg);
};
extern const bool LOGGER_RUNNING;
#ifndef _NB_NO_LOGGER
extern DefaultDebugLogger logger;
#endif // _NB_NO_LOGGER
// Taking Charge of Adult ADHD by Russell Barkley
} // namespace nb
#endif // _NB_LOGGER
@@ -0,0 +1,16 @@
#pragma once
#ifndef _NB_PROCESSES
#define _NB_PROCESSES
#include <cstdint>
namespace nb {
uint64_t GetPID();
uint64_t getTID();
} // namespace nb
#endif // _NB_PROCESSES
@@ -0,0 +1,79 @@
#pragma once
#ifndef _NB_STRING_UTILS
#define _NB_STRING_UTILS
#include <iostream>
#include <string>
#include <string_view>
#include <NBCore/TypeTraits.hpp>
namespace nb {
#ifdef _NB_TARGET_WINDOWS
inline static const std::string NEWLINE = "\n";
inline static const std::wstring WNEWLINE = L"\n";
#endif // _NB_TARGET_WINDOWS
#ifdef _NB_TARGET_LINUX
inline const std::string NEWLINE = "\n";
inline const std::wstring WNEWLINE = L"\n";
#endif // _NB_TARGET_LINUX
const std::string TABOVER = " ";
// std::wstring str_to_wstr(std::string in);
// std::string wstr_to_str(std::wstring in);
template <typename Stream, typename... Args>
void stream(const Stream& s, Args&&... args);
template <typename Stream, typename... Args>
void stream(const Stream& s, Args&&... args) {
(s << ... << args);
}
template<typename... Args>
void term(Args&&... args) { stream(std::cout, args..., NEWLINE); }
template<typename... Args>
void wterm(Args&&... args) { stream(std::wcout, args..., nb::WNEWLINE); }
template <typename T = char>
std::basic_string<T> find_and_replace(
ExplicitType_t<std::basic_string<T>> original,
ExplicitType_t<std::basic_string_view<T>> find,
ExplicitType_t<std::basic_string_view<T>> replace
) {
using StringType = std::basic_string<T>;
StringType ret(original);
std::size_t find_len = find.length();
std::size_t replace_len = replace.length();
std::size_t currpos = 0;
while(true) {
currpos = ret.find(find, currpos);
if (currpos == StringType::npos) {
break;
}
ret = ret.erase(currpos, find_len);
ret = ret.insert(currpos, replace);
currpos += replace_len;
}
return ret;
}
std::string indent_strblock(
std::string block,
std::string prepend,
std::string topIndent
);
std::string indent_strblock(
std::string block,
std::string prepend
);
} // namespace nb
#endif // _NB_STRING_UTILS
@@ -0,0 +1,123 @@
#pragma once
#ifndef _NB_UTIL_THREADSAFE_QUEUE
#define _NB_UTIL_THREADSAFE_QUEUE
#include <condition_variable>
#include <memory>
#include <mutex>
#include <queue>
#include <type_traits>
namespace nb {
template<typename T, bool isPoly>
class ThreadsafeQueue_impl;
// Non-polymorphic
template<typename T>
class ThreadsafeQueue_impl<T, false> {
public:
bool empty() const {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.empty();
}
unsigned int size() const {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.size();
}
template<typename U>
void push(U&& val) {
std::lock_guard<std::mutex> lock(_mutex);
_queue.push(std::forward<U>(val));
_cond.notify_one();
}
bool pop(std::shared_ptr<T>& dest) {
std::lock_guard<std::mutex> lock(_mutex);
if (_queue.empty()) { return false; }
dest = std::make_shared<T>(std::move(_queue.front()));
_queue.pop();
return true;
}
std::shared_ptr<T> popBlock() {
std::unique_lock<std::mutex> lock(_mutex);
_cond.wait(lock, [&]{ return !_queue.empty(); });
auto ret = std::make_shared<T>(std::move(_queue.front()));
_queue.pop();
return ret;
}
protected:
ThreadsafeQueue_impl() {}
std::queue<T> _queue;
std::condition_variable _cond;
mutable std::mutex _mutex;
};
// Polymorphic
template<typename T>
class ThreadsafeQueue_impl<T, true> {
public:
bool empty() const {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.empty();
}
unsigned int size() const {
std::lock_guard<std::mutex> lock(_mutex);
return _queue.size();
}
template<typename U>
void push(U&& val) {
std::lock_guard<std::mutex> lock(_mutex);
std::shared_ptr<T> newval = std::make_shared<T>(std::forward<U>(val));
_queue.push(newval);
_cond.notify_one();
}
bool pop(std::shared_ptr<T>& dest) {
std::lock_guard<std::mutex> lock(_mutex);
if (_queue.empty()) { return false; }
dest = std::move(_queue.front());
_queue.pop();
return true;
}
std::shared_ptr<T> popBlock() {
std::unique_lock<std::mutex> lock(_mutex);
_cond.wait(lock, [&]{ return !_queue.empty(); });
auto ret = std::move(_queue.front());
_queue.pop();
return ret;
}
protected:
ThreadsafeQueue_impl() {}
std::queue<std::shared_ptr<T>> _queue;
std::condition_variable _cond;
mutable std::mutex _mutex;
};
template<typename T>
class ThreadsafeQueue : public ThreadsafeQueue_impl<T, std::is_polymorphic<T>::value> {
public:
using Implementation = ThreadsafeQueue_impl<T, std::is_polymorphic<T>::value>;
ThreadsafeQueue() = default;
~ThreadsafeQueue() = default;
ThreadsafeQueue(ThreadsafeQueue& rhs) = delete;
ThreadsafeQueue& operator=(ThreadsafeQueue& rhs) = delete;
ThreadsafeQueue(ThreadsafeQueue&& rhs) = delete;
ThreadsafeQueue& operator=(ThreadsafeQueue&& rhs) = delete;
operator bool() const { return !Implementation::empty(); }
};
} // namespace nb
#endif // _NB_UTIL_THREADSAFE_QUEUE
+194
View File
@@ -0,0 +1,194 @@
#pragma once
#ifndef _NB_TYPE_TRAITS
#define _NB_TYPE_TRAITS
#include <tuple>
#include <type_traits>
#include <vector>
namespace nb {
namespace detail {
template <
class Default,
class AlwaysVoid,
template <class...> class Op,
class... Args
>
struct detector {
using value = std::false_type;
using type = Default;
};
template <
class Default,
template <class...> class Op,
class... Args
>
struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> {
using value = std::true_type;
using type = Op<Args...>;
};
} // namespace detail
struct NoneType{};
template<typename T, unsigned int Arg>
using Const_t = std::integral_constant<T, Arg>;
template <
template <class...> class Op,
class... Args
>
using is_detected = typename detail::detector<NoneType, void, Op, Args...>::value;
template <typename... Types>
struct ValidConversion;
template <typename To, typename A, typename B, typename... Rest>
struct ValidConversion<To, A, B, Rest...> {
typedef std::conjunction<
std::is_constructible<To, A>, std::is_constructible<To, A>, std::conjunction<std::is_constructible<To, Rest>...>
> value_type;
static constexpr bool value = value_type::value;
typedef std::enable_if_t<value, To> to;
};
template <typename To, typename From>
struct ValidConversion<To, From> {
typedef std::is_constructible<To, From> value_type;
static constexpr bool value = value_type::value;
typedef std::enable_if_t<value, To> to;
typedef std::enable_if_t<value, From> from;
};
template<typename... Types>
using ValidConversion_v = typename ValidConversion<Types...>::value;
template<typename... Types>
using ValidConversion_to = typename ValidConversion<Types...>::to;
template<typename To, typename From>
using ValidConversion_from = typename ValidConversion<To, From>::from;
template <typename T>
struct ExplicitType { using type=T; };
template <typename T>
using ExplicitType_t = typename ExplicitType<T>::type;
template <typename T>
T* NULLPTR = static_cast<T*>(nullptr);
template <typename Func, typename T>
struct RunAndOutput {
using type = T;
T value;
RunAndOutput(Func func, T val) : value(val) {
func();
}
};
template<typename Func, std::size_t N=0, typename... Pack>
inline typename std::enable_if<N==sizeof...(Pack), void>::type
ForEach(std::tuple<Pack...>&, Func) {}
template<typename Func, std::size_t N=0, typename... Pack>
inline typename std::enable_if<N < sizeof...(Pack), void>::type
ForEach(std::tuple<Pack...>& tup, Func f) {
f(N, std::get<N>(tup));
ForEach<N+1, Func, Pack...>(tup, f);
}
template<std::size_t N=0, typename Func, typename Args, typename... Pack>
inline typename std::enable_if<N==sizeof...(Pack), void>::type
ForEach(std::tuple<Pack...>&, Func, const Args&) {}
template<std::size_t N=0, typename Func, typename Args, typename... Pack>
inline typename std::enable_if<N < sizeof...(Pack), void>::type
ForEach(std::tuple<Pack...>& tup, Func f, const Args& arg) {
f(N, std::get<N>(tup), arg);
ForEach<N+1, Func, Args, Pack...>(tup, f, arg);
}
template<typename T, typename... Pack>
struct Find;
template<typename T, typename U, typename... Pack>
struct Find<T, U, Pack...> {
protected:
using here = Find<T, U>;
static constexpr unsigned int downstream = std::conditional_t<
here::value,
Const_t<unsigned int, 0>,
Find<T, Pack...>
>::value;
public:
static constexpr unsigned int value = std::conditional_t<
here::value,
Const_t<unsigned int, 1>,
std::conditional_t<
downstream,
Const_t<unsigned int, 1+downstream>,
Const_t<unsigned int, 0>
>
>::value;
};
template<typename T, typename U>
struct Find<T, U> {
public:
static constexpr unsigned int value = std::conditional_t<
std::is_base_of<T, U>::value,
std::integral_constant<unsigned int, 1>,
std::integral_constant<unsigned int, 0>
>::value;
};
template <typename T, typename Pack1, typename... Pack>
struct RefPackToPtrVec {
RefPackToPtrVec(std::vector<T*> _vec, Pack1& p1, Pack&... packs)
: vec(_vec) {
static_assert(std::is_base_of<T, Pack1>::value);
vec.push_back(&p1);
vec = RefPackToPtrVec<T, Pack...>(vec, packs...).vec;
}
RefPackToPtrVec(Pack1& p1, Pack&... packs)
: RefPackToPtrVec({}, p1, packs...) {}
std::vector<T*> vec;
};
template <typename T, typename Pack>
struct RefPackToPtrVec<T, Pack> {
RefPackToPtrVec(std::vector<T*> _vec, Pack& p1)
: vec(_vec) {
static_assert(std::is_base_of<T, Pack>::value);
vec.push_back(&p1);
}
RefPackToPtrVec(Pack& p1)
: RefPackToPtrVec({}, p1) {}
std::vector<T*> vec;
};
template <typename T, typename... Pack>
struct PackIsSameType;
template <typename T, typename PackType>
struct PackIsSameType<T, PackType> {
const bool value = std::is_base_of<T, PackType>::value;
};
template <typename T, typename FirstPack, typename... Pack>
struct PackIsSameType<T, FirstPack, Pack...> {
const bool value = std::is_base_of<T, FirstPack>::value && PackIsSameType<T, Pack...>::value;
};
} // namespace nb
#endif // _NB_TYPE_TRAITS
+120
View File
@@ -0,0 +1,120 @@
#pragma once
#ifndef _NB_CORE_TYPES
#define _NB_CORE_TYPES
#include <mutex>
#include <vector>
#include <NBCore/Errors.hpp>
namespace nb {
template<typename T>
using SharedVector = std::vector<std::shared_ptr<T>>;
template<typename T>
using RValueVector = std::vector<T&&>;
using ByteVector = std::vector<uint8_t>;
class ObjectManagerError : public Error<ObjectManagerError> {
using Base = Error<ObjectManagerError>;
public:
using Base::Base;
enum Codes : unsigned int {
UNDEFINED, NO_MANAGER, MANAGER_MISMATCH, LOCK_OVERFLOW, BAD_THREAD
};
static const std::string type;
static const ErrorCodeMap ErrorMessages;
};
template<typename T>
ByteVector vectorToBytes(const std::vector<T>& vec) {
unsigned int num_bytes = vec.size() * sizeof(T);
ByteVector ret(num_bytes);
memcpy(ret.data(), vec.data(), num_bytes);
return ret;
}
template<typename T, typename S>
ByteVector concatVectorBytes(const std::vector<T>& vec1, const std::vector<S>& vec2) {
ByteVector vec1_raw = vectorToBytes<T>(vec1);
ByteVector vec2_raw = vectorToBytes<S>(vec2);
unsigned int vec1_raw_size = vec1_raw.size();
unsigned int vec2_raw_size = vec2_raw.size();
ByteVector ret(vec1_raw_size + vec2_raw_size);
memcpy(ret.data(), vec1_raw.data(), vec1_raw_size);
memcpy(ret.data() + vec1_raw_size, vec2_raw.data(), vec2_raw_size);
return ret;
}
template<typename T>
std::vector<T> bytesToVector(const ByteVector& vec) {
if (vec.size() % sizeof(T) != 0) {
THROW(Error<NoneType>(
std::runtime_error("Data size does not align to std::vector<" + std::string(typeid(T).name()) + ">.")
));
}
unsigned int num_elmts = vec.size() / sizeof(T);
std::vector<T> ret(num_elmts);
memcpy(ret.data(), vec.data(), vec.size());
return ret;
}
template <typename T>
class ThreadsafeObjectLock;
template <typename T>
class ThreadsafeObject {
using Codes = ObjectManagerError::Codes;
public:
ThreadsafeObject(T&& obj)
: _obj(std::make_shared<T>(obj)) {}
ThreadsafeObjectLock<T> lock() {
return ThreadsafeObjectLock<T>(this);
}
friend ThreadsafeObjectLock<T>;
protected:
std::shared_ptr<T> _obj;
mutable std::recursive_mutex _mutex;
};
template <typename T>
class ThreadsafeObjectLock {
public:
ThreadsafeObjectLock(const ThreadsafeObjectLock&) = delete;
ThreadsafeObjectLock operator=(const ThreadsafeObjectLock&) = delete;
~ThreadsafeObjectLock() {
_manager->_mutex.unlock();
}
T* operator->() {
return _manager->_obj.get();
}
friend ThreadsafeObject<T>;
protected:
ThreadsafeObjectLock(
ThreadsafeObject<T>* const manager_
) : _manager(manager_) {
if (!_manager) {
using Codes = ObjectManagerError::Codes;
THROW(ObjectManagerError(Codes::NO_MANAGER));
}
_manager->_mutex.lock();
}
ThreadsafeObject<T>* const _manager;
};
} // namespace nb
#endif // _NB_CORE_TYPES