| | |
| | | #ifndef BH_UTIL_SOXWOK67 |
| | | #define BH_UTIL_SOXWOK67 |
| | | |
| | | #include "macro.h" |
| | | #include <functional> |
| | | #include <mutex> |
| | | #include <stdint.h> |
| | |
| | | inline void PutInt(void *p, uint32_t u) { Put32(p, u); } |
| | | inline void PutInt(void *p, uint64_t u) { Put64(p, u); } |
| | | |
| | | constexpr uint64_t MaskBits(int nbits) { return (uint64_t(1) << nbits) - 1; } |
| | | |
| | | class ExitCall |
| | | { |
| | | typedef std::function<void(void)> func_t; |
| | |
| | | D &operator*() const { return *p_; } |
| | | }; |
| | | |
| | | template <class T, class Mutex = std::mutex, class Lock = std::unique_lock<Mutex>> |
| | | template <class T, class TMutex = std::mutex, class Lock = std::unique_lock<TMutex>> |
| | | class Synced |
| | | { |
| | | typedef T Data; |
| | | Mutex mutex_; |
| | | TMutex mutex_; |
| | | Data data_; |
| | | typedef SyncedPtr<Data, Mutex, Lock> Ptr; |
| | | typedef SyncedPtr<Data, TMutex, Lock> Ptr; |
| | | |
| | | public: |
| | | template <class... P> |
| | |
| | | } |
| | | }; |
| | | |
| | | // macro helper |
| | | #define JOIN_IMPL(a, b) a##b |
| | | #define JOIN(a, b) JOIN_IMPL(a, b) |
| | | // defer function / lambda. |
| | | #define DEFERF(func) ExitCall JOIN(defer_, __LINE__)(func) |
| | | // defer simple expression |
| | | #define DEFER1(expr) DEFERF([&]() { expr; }) |
| | | template <class T, class Tag> |
| | | class StaticDataRef |
| | | { |
| | | typedef T *Ptr; |
| | | static inline Ptr &ptr() |
| | | { |
| | | static Ptr sp(nullptr); |
| | | return sp; |
| | | } |
| | | |
| | | protected: |
| | | static inline T &GetData(const std::string &msg = "Must set data before use!") |
| | | { |
| | | if (!ptr()) { throw std::logic_error(msg); } |
| | | return *ptr(); |
| | | } |
| | | |
| | | public: |
| | | static bool SetData(T &t) |
| | | { |
| | | auto Bind = [&]() { ptr() = &t; return true; }; |
| | | return ptr() ? false : Bind(); |
| | | } |
| | | }; |
| | | |
| | | #endif /* end of include guard: BH_UTIL_SOXWOK67 */ |