ThinSQLite++
A thin, safe and convenient modern C++ wrapper for SQLite API.
Loading...
Searching...
No Matches
memory_iface.hpp
1/*
2 Copyright 2019 Eugene Gershnik
3
4 Use of this source code is governed by a BSD-style
5 license that can be found in the LICENSE file or at
6 https://github.com/gershnik/thinsqlitepp/blob/main/LICENSE
7*/
8
9#ifndef HEADER_SQLITEPP_MEMORY_IFACE_INCLUDED
10#define HEADER_SQLITEPP_MEMORY_IFACE_INCLUDED
11
12#include "config.hpp"
13
14#include <memory>
15#include <limits>
16
17namespace thinsqlitepp
18{
29 template<class T>
31 {
32 public:
33 void operator()(T * mem) const noexcept
34 { sqlite3_free(const_cast<std::remove_const_t<T> *>(mem)); }
35 };
36
38 template<class T>
39 using deleter [[deprecated]] = sqlite_deleter<T>;
41
48
55
56
58 inline void * sqlite_allocate_nothrow(std::size_t size) noexcept
59 {
60 if (size == 0)
61 return sqlite3_malloc(1);
62
63 #if SQLITE_VERSION_NUMBER >= SQLITEPP_SQLITE_VERSION(3, 8, 7)
64 if constexpr (sizeof(size_t) > sizeof(sqlite3_uint64))
65 {
67 return nullptr;
68 }
69 return sqlite3_malloc64(size);
70 #else
72 return nullptr;
73 return sqlite3_malloc(int(size));
74 #endif
75 }
76
77 inline void * sqlite_allocate(std::size_t size)
78 {
79 if (auto ret = sqlite_allocate_nothrow(size))
80 return ret;
81 throw std::bad_alloc();
82 }
83
84
85
87
100 {
101 void * operator new(std::size_t size, const std::nothrow_t &) noexcept
102 { return sqlite_allocate_nothrow(size); }
103
104 void* operator new[](std::size_t size, const std::nothrow_t &) noexcept
105 { return sqlite_allocate_nothrow(size); }
106
107 void * operator new(size_t size)
108 { return sqlite_allocate(size); }
109
110 void * operator new[](size_t size)
111 { return sqlite_allocate(size); }
112
113
114 void operator delete (void * ptr) noexcept
115 { sqlite3_free(ptr); }
116 void operator delete[](void * ptr) noexcept
117 { sqlite3_free(ptr); }
118 };
119
120
125 template<class T>
127 {
128 using value_type = T;
129
130 sqlite_allocator() = default;
131
132 template<class U>
133 constexpr sqlite_allocator(const sqlite_allocator <U>&) noexcept {}
134
135 T * allocate(std::size_t n)
136 {
137 if (std::numeric_limits<std::size_t>::max() / sizeof(T) < n)
139 return sqlite_allocate(n * sizeof(T));
140 }
141
142 void deallocate(T * ptr, std::size_t /*n*/) noexcept
143 { sqlite3_free(ptr); }
144
145 template<class U>
146 friend bool operator==(const sqlite_allocator<T> &, const sqlite_allocator<U> &) noexcept { return true; }
147
148 template<class U>
149 friend bool operator!=(const sqlite_allocator<T> &, const sqlite_allocator<U> &) noexcept { return false; }
150 };
151
153}
154
155#endif
156
157
158
Memory deleter that uses sqlite3_free.
Definition memory_iface.hpp:31
sqlite3_free
ThinSQLite++ namespace.
Definition backup_iface.hpp:17
Base class that makes derived classes be allocated using SQLite.
Definition memory_iface.hpp:100
A C++ Allocator that uses SQLite memory allocation functions.
Definition memory_iface.hpp:127