boost_sqlite 1
A sqlite C++ library
Loading...
Searching...
No Matches
memory.hpp
1// Copyright (c) 2023 Klemens D. Morgenstern
2//
3// Distributed under the Boost Software License, Version 1.0. (See accompanying
4// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5#ifndef BOOST_SQLITE_MEMORY_HPP
6#define BOOST_SQLITE_MEMORY_HPP
7
8#include <boost/sqlite/detail/config.hpp>
9
10#include <memory>
11
12BOOST_SQLITE_BEGIN_NAMESPACE
15struct memory_tag {};
16BOOST_SQLITE_END_NAMESPACE
17
18
19inline void *operator new ( std::size_t size, boost::sqlite::memory_tag) noexcept
20{
21 using namespace boost::sqlite;
22 return sqlite3_malloc64(size);
23}
24inline void *operator new[]( std::size_t size, boost::sqlite::memory_tag) noexcept
25{
26 using namespace boost::sqlite;
27 return sqlite3_malloc64(size);
28}
29
30inline void operator delete ( void* ptr, boost::sqlite::memory_tag) noexcept
31{
32 using namespace boost::sqlite;
33 return sqlite3_free(ptr);
34}
35
36BOOST_SQLITE_BEGIN_NAMESPACE
37
38template<typename T>
39void delete_(T * t)
40{
41 struct scoped_free
42 {
43 void * p;
44 ~scoped_free()
45 {
46 sqlite3_free(p);
47 }
48 };
49 scoped_free _{t};
50 t->~T();
51}
52
53namespace detail
54{
55
56template<typename T>
57struct deleter
58{
59 void operator()(T* t)
60 {
61 delete_(t);
62 }
63};
64
65template<typename T>
66struct deleter<T[]>
67{
68 static_assert(std::is_trivially_destructible<T>::value, "T[] needs to be trivially destructible");
69 void operator()(T* t)
70 {
71 sqlite3_free(t);
72 }
73};
74
75template<>
76struct deleter<void>
77{
78 void operator()(void* t)
79 {
80 sqlite3_free(t);
81 }
82};
83}
84
85template<typename T>
86using unique_ptr = std::unique_ptr<T, detail::deleter<T>>;
87
88template<typename T>
89inline std::size_t msize(const unique_ptr<T> & ptr)
90{
91 return sqlite3_msize(ptr.get());
92}
93
94template<typename T, typename ... Args>
95unique_ptr<T> make_unique(Args && ... args)
96{
97 unique_ptr<void> up{sqlite3_malloc64(sizeof(T))};
98 unique_ptr<T> res{new (up.get()) T(std::forward<Args>(args)...)};
99 up.release();
100 return res;
101}
102
103BOOST_SQLITE_END_NAMESPACE
104
105#endif //BOOST_SQLITE_MEMORY_HPP