Mercurial > foo_out_sdl
comparison foosdk/sdk/pfc/mem_block.h @ 1:20d02a178406 default tip
*: check in everything else
yay
| author | Paper <paper@tflc.us> |
|---|---|
| date | Mon, 05 Jan 2026 02:15:46 -0500 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 0:e9bb126753e7 | 1:20d02a178406 |
|---|---|
| 1 #pragma once | |
| 2 | |
| 3 namespace pfc { | |
| 4 //! Manages a malloc()'d memory block. Most methods are self explanatory. | |
| 5 class mem_block { | |
| 6 public: | |
| 7 mem_block( ) noexcept { _clear(); } | |
| 8 ~mem_block() noexcept { clear(); } | |
| 9 void resize(size_t); | |
| 10 void clear() noexcept; | |
| 11 size_t size() const noexcept { return m_size;} | |
| 12 void * ptr() noexcept { return m_ptr; } | |
| 13 const void * ptr() const noexcept { return m_ptr; } | |
| 14 void move( mem_block & other ) noexcept; | |
| 15 void copy( mem_block const & other ); | |
| 16 mem_block(const mem_block & other) { _clear(); copy(other); } | |
| 17 mem_block(mem_block && other) noexcept { _clear(); move(other); } | |
| 18 mem_block const & operator=( const mem_block & other ) { copy(other); return *this; } | |
| 19 mem_block const & operator=( mem_block && other ) noexcept { move(other); return *this; } | |
| 20 | |
| 21 void set(const void* ptr, size_t size) {set_data_fromptr(ptr, size); } | |
| 22 void set_data_fromptr(const void* p, size_t size) { resize(size); memcpy(ptr(), p, size); | |
| 23 } | |
| 24 void append_fromptr(const void* p, size_t size) { | |
| 25 const size_t base = this->size(); | |
| 26 resize(base + size); | |
| 27 memcpy((uint8_t*)ptr() + base, p, size); | |
| 28 } | |
| 29 | |
| 30 void* detach() noexcept { | |
| 31 void* ret = m_ptr; _clear(); return ret; | |
| 32 } | |
| 33 | |
| 34 void* get_ptr() noexcept { return m_ptr; } | |
| 35 const void* get_ptr() const noexcept { return m_ptr; } | |
| 36 size_t get_size() const noexcept { return m_size; } | |
| 37 | |
| 38 //! Attaches an existing memory block, allocated with malloc(), to this object. After this call, the memory becomes managed by this mem_block instance. | |
| 39 void attach(void* ptr, size_t size) noexcept { | |
| 40 clear(); | |
| 41 m_ptr = ptr; m_size = size; | |
| 42 } | |
| 43 //! Turns existing memory block, allocated with malloc(), to a mem_block object. After this call, the memory becomes managed by this mem_block instance. | |
| 44 static mem_block takeOwnership(void* ptr, size_t size) { | |
| 45 mem_block ret(noinit{}); | |
| 46 ret.m_ptr = ptr; ret.m_size = size; | |
| 47 return ret; | |
| 48 } | |
| 49 private: | |
| 50 struct noinit {}; mem_block(noinit) {} | |
| 51 void _clear() noexcept { m_ptr = nullptr; m_size = 0; } | |
| 52 void * m_ptr; | |
| 53 size_t m_size; | |
| 54 }; | |
| 55 } | |
| 56 |
