diff --git a/src/calibre/utils/windows/common.h b/src/calibre/utils/windows/common.h index ee903c805b..3b5dcdf632 100644 --- a/src/calibre/utils/windows/common.h +++ b/src/calibre/utils/windows/common.h @@ -59,11 +59,36 @@ class scoped_com_initializer { // {{{ #define INITIALIZE_COM_IN_FUNCTION scoped_com_initializer com; if (!com) return com.set_python_error(); static inline void co_task_mem_free(void* m) { CoTaskMemFree(m); } -typedef generic_raii(NULL)> com_wchar_raii; -static inline void handle_destructor(HANDLE p) { CloseHandle(p); } -typedef generic_raii handle_raii; +typedef generic_raii com_wchar_raii; static inline void mapping_destructor(void *p) { UnmapViewOfFile(p); } -typedef generic_raii(NULL)> mapping_raii; +typedef generic_raii mapping_raii; + +class handle_raii { + private: + handle_raii( const handle_raii & ) noexcept; + handle_raii & operator=( const handle_raii & ) noexcept ; + + protected: + HANDLE handle; + + public: + explicit handle_raii(HANDLE h = INVALID_HANDLE_VALUE) noexcept : handle(h) {} + ~handle_raii() noexcept { release(); } + + void release() noexcept { + if (handle != INVALID_HANDLE_VALUE) { + HANDLE temp = handle; + handle = INVALID_HANDLE_VALUE; + CloseHandle(temp); + } + } + + HANDLE ptr() noexcept { return handle; } + HANDLE detach() noexcept { HANDLE ans = handle; handle = INVALID_HANDLE_VALUE; return ans; } + void attach(HANDLE val) noexcept { release(); handle = val; } + explicit operator bool() const noexcept { return handle != INVALID_HANDLE_VALUE; } +}; + struct prop_variant : PROPVARIANT { prop_variant(VARTYPE vt=VT_EMPTY) noexcept : PROPVARIANT{} { PropVariantInit(this); this->vt = vt; }