nk 1.0.0
C++ Numerical Computing Runtime
Loading...
Searching...
No Matches
data_buffer.hpp
1// core/include/nk/value/data_buffer.hpp
2#pragma once
3
4#include <atomic>
5#include <cstddef>
6#include <memory_resource>
7
8namespace nk {
9
10// ============================================================
11// DataBuffer — raw memory block with ref-counting
12//
13// Allocated via a std::pmr::memory_resource passed in at construction.
14// The same resource is used for deallocation in the destructor — caller
15// must keep it alive while the DataBuffer (and any cloned chain) lives.
16//
17// nullptr `mr` is mapped to std::pmr::get_default_resource() so the
18// "engine-free" Value path (Value::matrix(..., nullptr)) keeps working
19// without callers having to look up the default resource themselves.
20//
21// Non-owning mode: construct via the ViewTag ctor to wrap an external
22// pointer without ownership; destructor will not deallocate. Used by
23// Value::view() for zero-copy borrowing of caller-managed buffers.
24// ============================================================
25class DataBuffer
26{
27public:
28 struct ViewTag {};
29
30 DataBuffer(size_t bytes, std::pmr::memory_resource *mr);
33 DataBuffer(ViewTag, void *external, size_t bytes) noexcept;
34 ~DataBuffer();
35
36 DataBuffer(const DataBuffer &) = delete;
37 DataBuffer &operator=(const DataBuffer &) = delete;
38
39 void *data() { return data_; }
40 const void *data() const { return data_; }
41 size_t bytes() const { return bytes_; }
42 std::pmr::memory_resource *resource() const { return mr_; }
43 bool owns() const { return owns_; }
44
45 void addRef();
46 bool release();
47 int refCount() const;
48
49private:
50 void *data_ = nullptr;
51 size_t bytes_ = 0;
52 std::atomic<int> refCount_{1};
53 std::pmr::memory_resource *mr_ = nullptr;
54 bool owns_ = true;
55};
56
57} // namespace nk
DataBuffer(ViewTag, void *external, size_t bytes) noexcept
Non-owning ctor: wraps external for bytes bytes.