From: 박종현/동작제어Lab(SR)/Staff Engineer/삼성전자 Date: Thu, 19 Jul 2018 10:21:33 +0000 (+0900) Subject: [coco] Add 'PtrManager' class (#724) X-Git-Tag: nncc_backup~2374 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=7b0b426e9d1cb2176b2f67ed9af813d051696d8b;p=platform%2Fcore%2Fml%2Fnnfw.git [coco] Add 'PtrManager' class (#724) This commit adds 'PtrManager' class which automatically manages a set of allocated objects (which is passed via take method). Signed-off-by: Jonghyun Park --- diff --git a/contrib/coco/core/include/coco/ADT/PtrManager.h b/contrib/coco/core/include/coco/ADT/PtrManager.h new file mode 100644 index 0000000..fc94745 --- /dev/null +++ b/contrib/coco/core/include/coco/ADT/PtrManager.h @@ -0,0 +1,34 @@ +#ifndef __COCO_ADT_PTR_MANAGER_H__ +#define __COCO_ADT_PTR_MANAGER_H__ + +#include + +#include + +namespace coco +{ + +template class PtrManager +{ +public: + /// @breif Return the number of managed objects + uint32_t size(void) const { return _ptrs.size(); } + +public: + T *at(uint32_t n) const { return _ptrs.at(n).get(); } + +protected: + template U *take(std::unique_ptr &&o) + { + auto res = o.get(); + _ptrs.emplace_back(std::move(o)); + return res; + } + +private: + std::vector> _ptrs; +}; + +} // namespace coco + +#endif // __COCO_ADT_PTR_MANAGER_H__ diff --git a/contrib/coco/core/src/ADT/PtrManager.test.cpp b/contrib/coco/core/src/ADT/PtrManager.test.cpp new file mode 100644 index 0000000..422c3e7 --- /dev/null +++ b/contrib/coco/core/src/ADT/PtrManager.test.cpp @@ -0,0 +1,78 @@ +#include "coco/ADT/PtrManager.h" + +#include + +#include + +namespace +{ +struct Count +{ + uint32_t allocated; + uint32_t freed; + + Count() : allocated{0}, freed{0} + { + // DO NOTHING + } +}; + +class Object +{ +public: + Object(Count *count, uint32_t value) : _count{count}, _value{value} + { + _count->allocated += 1; + } + +public: + ~Object() + { + _count->freed += 1; + } + +public: + uint32_t value(void) const { return _value; } + +private: + Count * const _count; + +private: + uint32_t _value; +}; + +struct ObjectManager final : public coco::PtrManager +{ + Object *alloc(Count *count, uint32_t value) + { + std::unique_ptr o{new Object{count, value}}; + return take(std::move(o)); + } +}; +} + +TEST(ADT_PTR_MANAGER, usecase) +{ + Count c; + + ASSERT_EQ(c.allocated, 0); + ASSERT_EQ(c.freed, 0); + + { + ::ObjectManager mgr; + + auto obj_1 = mgr.alloc(&c, 3); + auto obj_2 = mgr.alloc(&c, 4); + + EXPECT_EQ(c.allocated, 2); + ASSERT_EQ(c.freed, 0); + + EXPECT_EQ(mgr.size(), 2); + EXPECT_EQ(mgr.at(0), obj_1); + EXPECT_EQ(mgr.at(1), obj_2); + } + + // PtrManger SHOULD destruct all of the allocated object when it is destructed. + ASSERT_EQ(c.allocated, 2); + ASSERT_EQ(c.freed, 2); +}