#ifndef UTIL_H #define UTIL_H #include #include #include #include #define CONCAT_IMPL(a, b) a##b #define CONCAT(a, b) CONCAT_IMPL(a, b) #define _ CONCAT(unused_, __LINE__) #define SET_TERMINATE \ std::set_terminate([]() noexcept \ { \ ShowException( \ L"Episode Browser was terminated due to an error: %s", \ L"Fatal Error", MB_ICONERROR); \ _Exit(1); \ }) template struct Finally { F f; inline Finally(F f) : f(f) {} inline ~Finally() { f(); } }; #define FINALLY Finally _ = [=]() template inline void Delete(T v) { delete v; } template > struct Unique { T v; bool ok = true; Unique() : ok(false) {} Unique(T v) : v(v) {} Unique& operator =(T v_) { if (ok) F(v); v = v_; ok = true; return *this; } Unique(Unique&& other) { v = std::move(other.v); other.ok = false; } Unique& operator =(Unique&& other) { if (ok) F(v); v = std::move(other.v); ok = other.ok; other.ok = false; return *this; } bool Not(T u) { if (v == u) return ok = false; else return true; } ~Unique() { if (ok) F(v); } }; /* Buf is a span-like structure of a buffer and its size. */ template struct Buf { T* data; size_t c; Buf(T* data, size_t c) : data(data), c(c) {} Buf(std::basic_string& s) : data(s.data()), c(s.capacity()) {} template Buf(T (&data)[N]) : data(data), c(N) {} operator T*() { return data; } T& operator *() { return *data; } T& operator [](size_t i) { return data[i]; } Buf operator +(size_t i) { return {data+i, c-i}; } //T operator -(size_t i) { return {data-i, c+i}; } }; inline int Cmp(const int a, const int b) { if (a == b) return 0; if (a > b) return 1; return -1; } inline size_t Min(size_t a, size_t b) { return a < b? a: b; } template inline size_t Len(T (&)[N]) { return N-1; } /* Format wide string. */ template inline int Swprintf(Buf buf, const wchar_t* const fmt, T... xs) { return _snwprintf_s(buf, buf.c, _TRUNCATE, fmt, xs...); } /* Format static narrow string. */ template inline int Sprintf(Buf buf, const char* const fmt, T... xs) { return _snprintf_s(buf, buf.c, _TRUNCATE, fmt, xs...); } /* Copy to static wide string buffer. */ inline wchar_t* Wcscpy(Buf dst, const wchar_t* const src) { const size_t len = Min(dst.c, wcslen(src)+1); memcpy(dst, src, len*sizeof(wchar_t)); dst[len-1] = 0; return dst; } /* Copy to static narrow string buffer. */ inline char* Strcpy(Buf dst, const char* const src) { const size_t len = Min(dst.c, strlen(src)+1); memcpy(dst, src, len); dst[len-1] = 0; return dst; } #endif