From 26e0848fa15b954ece22f305a7351a1192486150 Mon Sep 17 00:00:00 2001 From: heck Date: Wed, 9 Mar 2022 15:45:37 +0100 Subject: [PATCH] prototype: pEp::PODStruct - created default alloc/free, and a constructor to provide custom alloc/free --- test/test_nr1.cc | 57 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/test/test_nr1.cc b/test/test_nr1.cc index 2972e29..5b2c4a5 100644 --- a/test/test_nr1.cc +++ b/test/test_nr1.cc @@ -432,24 +432,23 @@ namespace pEp { PODStruct() = delete; // Creates a new instance or binds an existing one + PODStruct(bool is_owner, T** c_struct_pp = nullptr) + { + pEpLogClass("called"); + _init(is_owner, c_struct_pp); + } + + // Creates a new instance or binds an existing one + // but takes custom alloc/free functions PODStruct( bool is_owner, std::function alloc, std::function free, T** c_struct_pp = nullptr) : - _alloc(std::move(alloc)), - _free(std::move(free)) + _effective_alloc(std::move(alloc)), + _effective_free(std::move(free)) { - pEpLogClass("called"); - - // if no pp is given, alloc new, - // otherwise bind to it - if (!c_struct_pp) { - _c_struct_p = _alloc(); - bind(is_owner, &_c_struct_p); - } else { - bind(is_owner, c_struct_pp); - } + _init(is_owner, c_struct_pp); } void bind(bool is_owner, T** c_struct_pp) @@ -473,7 +472,7 @@ namespace pEp { ~PODStruct() { if (_is_owner) { - _free(_c_struct_p); + _effective_free(_c_struct_p); } } @@ -501,9 +500,9 @@ namespace pEp { static bool log_enabled; - protected: - const std::function _alloc; - const std::function _free; + private: + const std::function _effective_alloc{ _alloc }; + const std::function _effective_free{ _free }; bool _is_bound{ false }; bool _is_owner{ false }; @@ -517,6 +516,32 @@ namespace pEp { public: explicit Exception(const std::string& msg) : std::runtime_error(msg) {} }; + + void _init(bool is_owner, T** c_struct_pp) + { + // if no pp is given, alloc new, + // otherwise bind to it + if (!c_struct_pp) { + _c_struct_p = _effective_alloc(); + bind(is_owner, &_c_struct_p); + } else { + bind(is_owner, c_struct_pp); + } + } + + // default alloc/free + static T* _alloc() + { + T* ret = (T*)calloc(1, sizeof(T)); + pEpLog(CXX::Inspect::all(ret)); + return ret; + } + + static void _free(T* ptr) + { + pEpLog(CXX::Inspect::all(ptr)); + free(ptr); + } }; // TOOD: