-
-
Notifications
You must be signed in to change notification settings - Fork 339
Expand file tree
/
Copy pathHybridMMKV.cpp
More file actions
284 lines (242 loc) · 9.12 KB
/
Copy pathHybridMMKV.cpp
File metadata and controls
284 lines (242 loc) · 9.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
//
// HybridMMKV.cpp
// react-native-mmkv
//
// Created by Marc Rousavy on 21.08.2025.
//
#include "HybridMMKV.hpp"
#include "MMKVTypes.hpp"
#include "MMKVValueChangedListenerRegistry.hpp"
#include "ManagedMMBuffer.hpp"
#include <NitroModules/NitroLogger.hpp>
namespace margelo::nitro::mmkv {
HybridMMKV::HybridMMKV(const Configuration& config) : HybridObject(TAG) {
MMKVMode mmkvMode = getMMKVMode(config);
if (config.readOnly.value_or(false)) {
mmkvMode = mmkvMode | MMKVMode::MMKV_READ_ONLY;
}
bool useAes256Encryption = config.encryptionType.value_or(EncryptionType::AES_128) == EncryptionType::AES_256;
std::string encryptionKey = config.encryptionKey.value_or("");
std::string* encryptionKeyPtr = encryptionKey.size() > 0 ? &encryptionKey : nullptr;
std::string rootPath = config.path.value_or("");
std::string* rootPathPtr = rootPath.size() > 0 ? &rootPath : nullptr;
bool compareBeforeSet = config.compareBeforeSet.value_or(false);
MMKVConfig mmkvConfig{.mode = mmkvMode,
.aes256 = useAes256Encryption,
.cryptKey = encryptionKeyPtr,
.rootPath = rootPathPtr,
.enableCompareBeforeSet = compareBeforeSet,
.recover = getRecoveryStrategy(config)};
bool hasEncryptionKey = encryptionKey.size() > 0;
Logger::log(LogLevel::Info, TAG, "Creating MMKV instance \"%s\"... (Path: %s, Encrypted: %s)", config.id.c_str(), rootPath.c_str(),
hasEncryptionKey ? "true" : "false");
instance = MMKV::mmkvWithID(config.id, mmkvConfig);
if (instance == nullptr) [[unlikely]] {
// Check if instanceId is invalid
if (config.id.empty()) {
throw std::runtime_error("Failed to create MMKV instance! `id` cannot be empty!");
}
if (useAes256Encryption) {
// With AES-256, the max key length is 32 bytes.
if (encryptionKey.size() > 32) [[unlikely]] {
throw std::runtime_error("Failed to create MMKV instance! `encryptionKey` cannot be longer "
"than 32 bytes with AES-256 encryption!");
}
} else {
// With AES-128, the max key length is 16 bytes.
if (encryptionKey.size() > 16) [[unlikely]] {
throw std::runtime_error("Failed to create MMKV instance! `encryptionKey` cannot be longer "
"than 16 bytes with AES-128 encryption!");
}
}
// Check if path is maybe invalid
if (rootPath.empty()) [[unlikely]] {
throw std::runtime_error("Failed to create MMKV instance! `path` cannot be empty!");
}
throw std::runtime_error("Failed to create MMKV instance!");
}
}
std::string HybridMMKV::getId() {
return instance->mmapID();
}
double HybridMMKV::getLength() {
return instance->count();
}
double HybridMMKV::getSize() {
return getByteSize();
}
double HybridMMKV::getByteSize() {
return instance->actualSize();
}
size_t HybridMMKV::getExternalMemorySize() noexcept {
return instance != nullptr ? instance->actualSize() : 0;
}
bool HybridMMKV::getIsReadOnly() {
return instance->isReadOnly();
}
bool HybridMMKV::getIsEncrypted() {
return instance->isEncryptionEnabled();
}
// helper: overload pattern matching for lambdas
template <class... Ts>
struct overloaded : Ts... {
using Ts::operator()...;
};
template <class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
void HybridMMKV::set(const std::string& key, const std::variant<bool, std::shared_ptr<ArrayBuffer>, std::string, double>& value) {
if (key.empty()) [[unlikely]] {
throw std::runtime_error("Cannot set a value for an empty key!");
}
// Pattern-match each potential value in std::variant
bool successful = std::visit(overloaded{[&](bool b) {
// boolean
return instance->set(b, key);
},
[&](const std::shared_ptr<ArrayBuffer>& buf) {
// ArrayBuffer
MMBuffer buffer(buf->data(), buf->size(), MMBufferCopyFlag::MMBufferNoCopy);
return instance->set(std::move(buffer), key);
},
[&](const std::string& string) {
// string
return instance->set(string, key);
},
[&](double number) {
// number
return instance->set(number, key);
}},
value);
if (!successful) [[unlikely]] {
throw std::runtime_error("Failed to set value for key \"" + key + "\"!");
}
// Notify on changed
MMKVValueChangedListenerRegistry::notifyOnValueChanged(instance->mmapID(), key);
}
std::optional<bool> HybridMMKV::getBoolean(const std::string& key) {
bool hasValue;
bool result = instance->getBool(key, /* defaultValue */ false, &hasValue);
if (hasValue) {
return result;
} else {
return std::nullopt;
}
}
std::optional<std::string> HybridMMKV::getString(const std::string& key) {
std::string result;
bool hasValue = instance->getString(key, result, /* inplaceModification */ true);
if (hasValue) {
return result;
} else {
return std::nullopt;
}
}
std::optional<double> HybridMMKV::getNumber(const std::string& key) {
bool hasValue;
double result = instance->getDouble(key, /* defaultValue */ 0.0, &hasValue);
if (hasValue) {
return result;
} else {
return std::nullopt;
}
}
std::optional<std::shared_ptr<ArrayBuffer>> HybridMMKV::getBuffer(const std::string& key) {
MMBuffer result;
bool hasValue = instance->getBytes(key, result);
if (hasValue) {
return std::make_shared<ManagedMMBuffer>(std::move(result));
} else {
return std::nullopt;
}
}
bool HybridMMKV::contains(const std::string& key) {
return instance->containsKey(key);
}
bool HybridMMKV::remove(const std::string& key) {
bool wasRemoved = instance->removeValueForKey(key);
if (wasRemoved) {
// Notify on changed
MMKVValueChangedListenerRegistry::notifyOnValueChanged(instance->mmapID(), key);
}
return wasRemoved;
}
std::vector<std::string> HybridMMKV::getAllKeys() {
return instance->allKeys();
}
void HybridMMKV::clearAll() {
auto keysBefore = getAllKeys();
instance->clearAll();
for (const auto& key : keysBefore) {
// Notify on changed
MMKVValueChangedListenerRegistry::notifyOnValueChanged(instance->mmapID(), key);
}
}
void HybridMMKV::recrypt(const std::optional<std::string>& key) {
if (key.has_value()) {
encrypt(key.value(), std::nullopt);
} else {
decrypt();
}
}
void HybridMMKV::encrypt(const std::string& key, std::optional<EncryptionType> encryptionType) {
bool isAes256Encryption = encryptionType == EncryptionType::AES_256;
bool successful = instance->reKey(key, isAes256Encryption);
if (!successful) {
throw std::runtime_error("Failed to encrypt MMKV instance!");
}
}
void HybridMMKV::decrypt() {
bool successful = instance->reKey("");
if (!successful) [[unlikely]] {
throw std::runtime_error("Failed to decrypt MMKV instance!");
}
}
void HybridMMKV::trim() {
instance->trim();
instance->clearMemoryCache();
}
void HybridMMKV::checkContentChanged() {
instance->checkContentChanged();
}
Listener HybridMMKV::addOnValueChangedListener(const std::function<void(const std::string& /* key */)>& onValueChanged) {
// Add listener
auto mmkvID = instance->mmapID();
auto listenerID = MMKVValueChangedListenerRegistry::addListener(mmkvID, onValueChanged);
return Listener([=]() {
// remove()
MMKVValueChangedListenerRegistry::removeListener(mmkvID, listenerID);
});
}
MMKVMode HybridMMKV::getMMKVMode(const Configuration& config) {
if (!config.mode.has_value()) {
return ::mmkv::MMKV_SINGLE_PROCESS;
}
switch (config.mode.value()) {
case Mode::SINGLE_PROCESS:
return ::mmkv::MMKV_SINGLE_PROCESS;
case Mode::MULTI_PROCESS:
return ::mmkv::MMKV_MULTI_PROCESS;
}
throw std::runtime_error("Invalid MMKV Mode value!");
}
std::optional<MMKVRecoverStrategic> HybridMMKV::getRecoveryStrategy(const Configuration& config) {
if (!config.recoveryStrategy.has_value()) {
return std::nullopt;
}
switch (config.recoveryStrategy.value()) {
case RecoveryStrategy::DISCARD_ON_ERROR:
return MMKVRecoverStrategic::OnErrorDiscard;
case RecoveryStrategy::RECOVER_ON_ERROR:
return MMKVRecoverStrategic::OnErrorRecover;
}
throw std::runtime_error("Invalid MMKV RecoveryStrategy value!");
}
double HybridMMKV::importAllFrom(const std::shared_ptr<HybridMMKVSpec>& other) {
auto hybridMMKV = std::dynamic_pointer_cast<HybridMMKV>(other);
if (hybridMMKV == nullptr) [[unlikely]] {
throw std::runtime_error("The given `MMKV` instance is not of type `HybridMMKV`!");
}
size_t importedCount = instance->importFrom(hybridMMKV->instance);
return static_cast<double>(importedCount);
}
} // namespace margelo::nitro::mmkv