libpressio 0.93.0
Loading...
Searching...
No Matches
userptr.h
1#ifndef PRESSIO_OPTIONS_USERPTR_CPP
2#define PRESSIO_OPTIONS_USERPTR_CPP
3#include <std_compat/utility.h>
4
5extern "C" {
6void static_deleter(void*, void*);
7void static_copy(void**, void**, const void*, const void*);
8}
9
10using userdata_deleter_t = void(*)(void*, void*);
11template <class T>
12userdata_deleter_t newdelete_deleter() {
13 return [](void* ptr, void*) {
14 T* ptr_typed = static_cast<T*>(ptr);
15 delete ptr_typed;
16 };
17}
18
19using userdata_copy_t = void(*)(void** dst, void**, const void* src, const void*);
20template <class T>
21userdata_copy_t newdelete_copy() {
22 return [](void** dst, void**, const void* src, const void*) {
23 T const* src_typed = static_cast<T const*>(src);
24 T** dst_typed = reinterpret_cast<T**>(dst);
25 *dst_typed = new T(*src_typed);
26 };
27}
28
29class userdata {
30 public:
31 userdata():
32 ptr(nullptr), metadata(nullptr), deleter(nullptr), copy(nullptr) {}
33
34 userdata(void* ptr): ptr(ptr), metadata(nullptr), deleter(static_deleter), copy(static_copy) {}
35
36 userdata(void *ptr, void *metadata, void (*deleter)(void *, void *),
37 void (*copy)(void **, void **, const void *, const void *))
38 : ptr(ptr), metadata(metadata), deleter(deleter), copy(copy) {}
39 userdata(userdata const &data): ptr(nullptr), metadata(nullptr), deleter(data.deleter), copy(data.copy) {
40 if(data.copy) {
41 data.copy(&ptr, &metadata, data.ptr, data.metadata);
42 }
43 }
44 userdata(userdata &&data) noexcept:
45 ptr(compat::exchange(data.ptr,nullptr)),
46 metadata(compat::exchange(data.metadata,nullptr)),
47 deleter(compat::exchange(data.deleter, nullptr)),
48 copy(compat::exchange(data.copy, nullptr)) {}
49 userdata &operator=(userdata const &data) {
50 if (&data == this) return *this;
51 if(deleter) {
52 deleter(ptr, metadata);
53 }
54 if(data.copy) {
55 data.copy(&ptr, &metadata, &data.ptr, &data.metadata);
56 }
57 copy = data.copy;
58 deleter = data.deleter;
59 return *this;
60 }
61 userdata& operator=(userdata&& data) noexcept {
62 if (&data == this) return *this;
63 ptr = compat::exchange(data.ptr, nullptr);
64 metadata = compat::exchange(data.metadata, nullptr);
65 copy = compat::exchange(data.copy, nullptr);
66 deleter = compat::exchange(data.deleter, nullptr);
67 return *this;
68 }
69 operator bool() const noexcept {
70 return ptr;
71 }
72 bool operator==(userdata const& data) const noexcept {
73 return ptr == data.ptr;
74 }
75
76 ~userdata() {
77 if(deleter != nullptr) {
78 deleter(ptr, metadata);
79 }
80 }
81
82 void* get() const {
83 return ptr;
84 }
85
86 private:
87 void* ptr;
88 void* metadata;
89 void(*deleter)(void*, void*);
90 void(*copy)(void**, void**, const void*, const void*);
91};
92#endif
Definition: userptr.h:29