react-native-mmkv 1.6.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/MMKV/CHANGELOG.md +30 -0
  2. package/MMKV/Core/CMakeLists.txt +2 -1
  3. package/MMKV/Core/CodedInputDataCrypt.cpp +1 -1
  4. package/MMKV/Core/Core.xcodeproj/project.pbxproj +7 -4
  5. package/MMKV/Core/InterProcessLock_Win32.cpp +10 -5
  6. package/MMKV/Core/MMBuffer.h +1 -0
  7. package/MMKV/Core/MMKV.cpp +359 -17
  8. package/MMKV/Core/MMKV.h +29 -4
  9. package/MMKV/Core/MMKVLog.cpp +11 -10
  10. package/MMKV/Core/MMKVLog.h +1 -1
  11. package/MMKV/Core/MMKVPredef.h +6 -4
  12. package/MMKV/Core/MMKV_Android.cpp +2 -6
  13. package/MMKV/Core/MMKV_IO.cpp +1 -3
  14. package/MMKV/Core/MMKV_IO.h +3 -3
  15. package/MMKV/Core/MemoryFile.cpp +276 -43
  16. package/MMKV/Core/MemoryFile.h +85 -9
  17. package/MMKV/Core/MemoryFile_Android.cpp +37 -18
  18. package/MMKV/Core/MemoryFile_Linux.cpp +120 -0
  19. package/MMKV/Core/MemoryFile_OSX.cpp +92 -2
  20. package/MMKV/Core/MemoryFile_Win32.cpp +254 -34
  21. package/MMKV/Core/aes/openssl/openssl_aes.h +2 -2
  22. package/MMKV/Core/aes/openssl/openssl_aes_core.cpp +4 -4
  23. package/MMKV/README.md +4 -4
  24. package/README.md +11 -15
  25. package/android/CMakeLists.txt +1 -6
  26. package/android/build.gradle +41 -9
  27. package/android/src/main/java/com/reactnativemmkv/MmkvModule.java +33 -8
  28. package/android/src/main/java/com/reactnativemmkv/MmkvPackage.java +1 -2
  29. package/ios/{Mmkv.h → MmkvModule.h} +1 -1
  30. package/ios/MmkvModule.mm +70 -0
  31. package/lib/commonjs/createMMKV.js +50 -2
  32. package/lib/commonjs/createMMKV.js.map +1 -1
  33. package/lib/commonjs/hooks.js +8 -2
  34. package/lib/commonjs/hooks.js.map +1 -1
  35. package/lib/module/createMMKV.js +48 -2
  36. package/lib/module/createMMKV.js.map +1 -1
  37. package/lib/module/hooks.js +8 -2
  38. package/lib/module/hooks.js.map +1 -1
  39. package/lib/typescript/createMMKV.d.ts +1 -0
  40. package/lib/typescript/hooks.d.ts +1 -1
  41. package/package.json +1 -1
  42. package/react-native-mmkv.podspec +1 -1
  43. package/android/src/main/java/com/reactnativemmkv/MmkvModulePackage.java +0 -16
  44. package/ios/Mmkv.mm +0 -76
@@ -28,6 +28,7 @@
28
28
  # include "ScopedLock.hpp"
29
29
  # include "ThreadLock.h"
30
30
  # include <cassert>
31
+ # include <strsafe.h>
31
32
 
32
33
  using namespace std;
33
34
 
@@ -36,13 +37,73 @@ namespace mmkv {
36
37
  static bool getFileSize(MMKVFileHandle_t fd, size_t &size);
37
38
  static bool ftruncate(MMKVFileHandle_t file, size_t size);
38
39
 
39
- MemoryFile::MemoryFile(const MMKVPath_t &path)
40
- : m_name(path), m_fd(INVALID_HANDLE_VALUE), m_fileMapping(nullptr), m_ptr(nullptr), m_size(0) {
40
+ File::File(MMKVPath_t path, OpenFlag flag) : m_path(std::move(path)), m_fd(INVALID_HANDLE_VALUE), m_flag(flag) {
41
+ open();
42
+ }
43
+
44
+ static pair<int, int> OpenFlag2NativeFlag(OpenFlag flag) {
45
+ int access = 0, create = OPEN_EXISTING;
46
+ if (flag & OpenFlag::ReadWrite) {
47
+ access = (GENERIC_READ | GENERIC_WRITE);
48
+ } else if (flag & OpenFlag::ReadOnly) {
49
+ access |= GENERIC_READ;
50
+ } else if (flag & OpenFlag::WriteOnly) {
51
+ access |= GENERIC_WRITE;
52
+ }
53
+ if (flag & OpenFlag::Create) {
54
+ create = OPEN_ALWAYS;
55
+ }
56
+ if (flag & OpenFlag::Excel) {
57
+ access = CREATE_NEW;
58
+ }
59
+ if (flag & OpenFlag::Truncate) {
60
+ access = CREATE_ALWAYS;
61
+ }
62
+ return {access, create};
63
+ }
64
+
65
+ bool File::open() {
66
+ if (isFileValid()) {
67
+ return true;
68
+ }
69
+ auto pair = OpenFlag2NativeFlag(m_flag);
70
+ m_fd = CreateFile(m_path.c_str(), pair.first, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
71
+ pair.second, FILE_ATTRIBUTE_NORMAL, nullptr);
72
+ if (!isFileValid()) {
73
+ MMKVError("fail to open:[%ws], %d", m_path.c_str(), GetLastError());
74
+ return false;
75
+ }
76
+ MMKVInfo("open fd[%p], %ws", m_fd, m_path.c_str());
77
+ return true;
78
+ }
79
+
80
+ void File::close() {
81
+ if (isFileValid()) {
82
+ MMKVInfo("closing fd[%p], %ws", m_fd, m_path.c_str());
83
+ if (CloseHandle(m_fd)) {
84
+ m_fd = INVALID_HANDLE_VALUE;
85
+ } else {
86
+ MMKVError("fail to close [%ws], %d", m_path.c_str(), GetLastError());
87
+ }
88
+ }
89
+ }
90
+
91
+ size_t File::getActualFileSize() const {
92
+ size_t size = 0;
93
+ mmkv::getFileSize(m_fd, size);
94
+ return size;
95
+ }
96
+
97
+ MemoryFile::MemoryFile(MMKVPath_t path)
98
+ : m_diskFile(std::move(path), OpenFlag::ReadWrite | OpenFlag::Create)
99
+ , m_fileMapping(nullptr)
100
+ , m_ptr(nullptr)
101
+ , m_size(0) {
41
102
  reloadFromFile();
42
103
  }
43
104
 
44
105
  bool MemoryFile::truncate(size_t size) {
45
- if (m_fd < 0) {
106
+ if (!m_diskFile.isFileValid()) {
46
107
  return false;
47
108
  }
48
109
  if (size == m_size) {
@@ -56,14 +117,14 @@ bool MemoryFile::truncate(size_t size) {
56
117
  m_size = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
57
118
  }
58
119
 
59
- if (!ftruncate(m_fd, m_size)) {
60
- MMKVError("fail to truncate [%ws] to size %zu", m_name.c_str(), m_size);
120
+ if (!ftruncate(m_diskFile.getFd(), m_size)) {
121
+ MMKVError("fail to truncate [%ws] to size %zu", m_diskFile.m_path.c_str(), m_size);
61
122
  m_size = oldSize;
62
123
  return false;
63
124
  }
64
125
  if (m_size > oldSize) {
65
- if (!zeroFillFile(m_fd, oldSize, m_size - oldSize)) {
66
- MMKVError("fail to zeroFile [%ws] to size %zu", m_name.c_str(), m_size);
126
+ if (!zeroFillFile(m_diskFile.getFd(), oldSize, m_size - oldSize)) {
127
+ MMKVError("fail to zeroFile [%ws] to size %zu", m_diskFile.m_path.c_str(), m_size);
67
128
  m_size = oldSize;
68
129
  return false;
69
130
  }
@@ -71,7 +132,7 @@ bool MemoryFile::truncate(size_t size) {
71
132
 
72
133
  if (m_ptr) {
73
134
  if (!UnmapViewOfFile(m_ptr)) {
74
- MMKVError("fail to munmap [%ws], %d", m_name.c_str(), GetLastError());
135
+ MMKVError("fail to munmap [%ws], %d", m_diskFile.m_path.c_str(), GetLastError());
75
136
  }
76
137
  m_ptr = nullptr;
77
138
  }
@@ -90,28 +151,28 @@ bool MemoryFile::msync(SyncFlag syncFlag) {
90
151
  if (m_ptr) {
91
152
  if (FlushViewOfFile(m_ptr, m_size)) {
92
153
  if (syncFlag == MMKV_SYNC) {
93
- if (!FlushFileBuffers(m_fd)) {
94
- MMKVError("fail to FlushFileBuffers [%ws]:%d", m_name.c_str(), GetLastError());
154
+ if (!FlushFileBuffers(m_diskFile.getFd())) {
155
+ MMKVError("fail to FlushFileBuffers [%ws]:%d", m_diskFile.m_path.c_str(), GetLastError());
95
156
  return false;
96
157
  }
97
158
  }
98
159
  return true;
99
160
  }
100
- MMKVError("fail to FlushViewOfFile [%ws]:%d", m_name.c_str(), GetLastError());
161
+ MMKVError("fail to FlushViewOfFile [%ws]:%d", m_diskFile.m_path.c_str(), GetLastError());
101
162
  return false;
102
163
  }
103
164
  return false;
104
165
  }
105
166
 
106
167
  bool MemoryFile::mmap() {
107
- m_fileMapping = CreateFileMapping(m_fd, nullptr, PAGE_READWRITE, 0, 0, nullptr);
168
+ m_fileMapping = CreateFileMapping(m_diskFile.getFd(), nullptr, PAGE_READWRITE, 0, 0, nullptr);
108
169
  if (!m_fileMapping) {
109
- MMKVError("fail to CreateFileMapping [%ws], %d", m_name.c_str(), GetLastError());
170
+ MMKVError("fail to CreateFileMapping [%ws], %d", m_diskFile.m_path.c_str(), GetLastError());
110
171
  return false;
111
172
  } else {
112
173
  m_ptr = (char *) MapViewOfFile(m_fileMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
113
174
  if (!m_ptr) {
114
- MMKVError("fail to mmap [%ws], %d", m_name.c_str(), GetLastError());
175
+ MMKVError("fail to mmap [%ws], %d", m_diskFile.m_path.c_str(), GetLastError());
115
176
  return false;
116
177
  }
117
178
  }
@@ -121,22 +182,17 @@ bool MemoryFile::mmap() {
121
182
 
122
183
  void MemoryFile::reloadFromFile() {
123
184
  if (isFileValid()) {
124
- MMKVWarning("calling reloadFromFile while the cache [%ws] is still valid", m_name.c_str());
185
+ MMKVWarning("calling reloadFromFile while the cache [%ws] is still valid", m_diskFile.m_path.c_str());
125
186
  assert(0);
126
187
  clearMemoryCache();
127
188
  }
128
-
129
- m_fd =
130
- CreateFile(m_name.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
131
- nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
132
- if (m_fd == INVALID_HANDLE_VALUE) {
133
- MMKVError("fail to open:%ws, %d", m_name.c_str(), GetLastError());
134
- } else {
135
- FileLock fileLock(m_fd);
189
+ m_diskFile.open();
190
+ if (m_diskFile.isFileValid()) {
191
+ FileLock fileLock(m_diskFile.getFd());
136
192
  InterProcessLock lock(&fileLock, ExclusiveLockType);
137
193
  SCOPED_LOCK(&lock);
138
194
 
139
- mmkv::getFileSize(m_fd, m_size);
195
+ mmkv::getFileSize(m_diskFile.getFd(), m_size);
140
196
  // round up to (n * pagesize)
141
197
  if (m_size < DEFAULT_MMAP_SIZE || (m_size % DEFAULT_MMAP_SIZE != 0)) {
142
198
  size_t roundSize = ((m_size / DEFAULT_MMAP_SIZE) + 1) * DEFAULT_MMAP_SIZE;
@@ -159,16 +215,7 @@ void MemoryFile::doCleanMemoryCache(bool forceClean) {
159
215
  CloseHandle(m_fileMapping);
160
216
  m_fileMapping = nullptr;
161
217
  }
162
- if (m_fd != INVALID_HANDLE_VALUE) {
163
- CloseHandle(m_fd);
164
- m_fd = INVALID_HANDLE_VALUE;
165
- }
166
- }
167
-
168
- size_t MemoryFile::getActualFileSize() {
169
- size_t size = 0;
170
- mmkv::getFileSize(m_fd, size);
171
- return size;
218
+ m_diskFile.close();
172
219
  }
173
220
 
174
221
  size_t getPageSize() {
@@ -302,6 +349,170 @@ static bool getFileSize(MMKVFileHandle_t fd, size_t &size) {
302
349
  return false;
303
350
  }
304
351
 
352
+ static pair<MMKVPath_t, MMKVFileHandle_t> createUniqueTempFile(const wchar_t *prefix) {
353
+ wchar_t lpTempPathBuffer[MAX_PATH];
354
+ // Gets the temp path env string (no guarantee it's a valid path).
355
+ auto dwRetVal = GetTempPath(MAX_PATH, lpTempPathBuffer);
356
+ if (dwRetVal > MAX_PATH || (dwRetVal == 0)) {
357
+ MMKVError("GetTempPath failed %d", GetLastError());
358
+ return {L"", INVALID_HANDLE_VALUE};
359
+ }
360
+ // Generates a temporary file name.
361
+ wchar_t szTempFileName[MAX_PATH];
362
+ if (!GetTempFileName(lpTempPathBuffer, prefix, 0, szTempFileName)) {
363
+ MMKVError("GetTempFileName failed %d", GetLastError());
364
+ return {L"", INVALID_HANDLE_VALUE};
365
+ }
366
+ auto hTempFile = CreateFile(szTempFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
367
+ if (hTempFile == INVALID_HANDLE_VALUE) {
368
+ MMKVError("fail to create unique temp file [%ws], %d", szTempFileName, GetLastError());
369
+ return {L"", INVALID_HANDLE_VALUE};
370
+ }
371
+ MMKVDebug("create unique temp file [%ws] with fd[%p]", szTempFileName, hTempFile);
372
+ return {MMKVPath_t(szTempFileName), hTempFile};
373
+ }
374
+
375
+ bool tryAtomicRename(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
376
+ if (MoveFileEx(srcPath.c_str(), dstPath.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED) == 0) {
377
+ MMKVError("MoveFileEx [%ws] to [%ws] failed %d", srcPath.c_str(), dstPath.c_str(), GetLastError());
378
+ return false;
379
+ }
380
+ return true;
381
+ }
382
+
383
+ bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD, bool needTruncate) {
384
+ if (dstFD == INVALID_HANDLE_VALUE) {
385
+ return false;
386
+ }
387
+ bool ret = false;
388
+ File srcFile(srcPath, OpenFlag::ReadOnly);
389
+ if (!srcFile.isFileValid()) {
390
+ return false;
391
+ }
392
+ auto bufferSize = getPageSize();
393
+ auto buffer = (char *) malloc(bufferSize);
394
+ if (!buffer) {
395
+ MMKVError("fail to malloc size %zu, %d(%s)", bufferSize, errno, strerror(errno));
396
+ goto errorOut;
397
+ }
398
+ SetFilePointer(dstFD, 0, 0, FILE_BEGIN);
399
+
400
+ // the Win32 platform don't have sendfile()/fcopyfile() equivalent, do it the hard way
401
+ while (true) {
402
+ DWORD sizeRead = 0;
403
+ if (!ReadFile(srcFile.getFd(), buffer, bufferSize, &sizeRead, nullptr)) {
404
+ MMKVError("fail to read %ws: %d", srcPath.c_str(), GetLastError());
405
+ goto errorOut;
406
+ }
407
+
408
+ DWORD sizeWrite = 0;
409
+ if (!WriteFile(dstFD, buffer, sizeRead, &sizeWrite, nullptr)) {
410
+ MMKVError("fail to write fd [%d], %d", dstFD, GetLastError());
411
+ goto errorOut;
412
+ }
413
+
414
+ if (sizeRead < bufferSize) {
415
+ break;
416
+ }
417
+ }
418
+ if (needTruncate) {
419
+ size_t dstFileSize = 0;
420
+ getFileSize(dstFD, dstFileSize);
421
+ auto srcFileSize = srcFile.getActualFileSize();
422
+ if ((dstFileSize != srcFileSize) && !ftruncate(dstFD, static_cast<off_t>(srcFileSize))) {
423
+ MMKVError("fail to truncate [%d] to size [%zu]", dstFD, srcFileSize);
424
+ goto errorOut;
425
+ }
426
+ }
427
+
428
+ ret = true;
429
+ MMKVInfo("copy content from %ws to fd[%d] finish", srcPath.c_str(), dstFD);
430
+
431
+ errorOut:
432
+ free(buffer);
433
+ return ret;
434
+ }
435
+
436
+ // copy to a temp file then rename it
437
+ // this is the best we can do on Win32
438
+ bool copyFile(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
439
+ auto pair = createUniqueTempFile(L"MMKV");
440
+ auto tmpFD = pair.second;
441
+ auto &tmpPath = pair.first;
442
+ if (tmpFD == INVALID_HANDLE_VALUE) {
443
+ return false;
444
+ }
445
+
446
+ bool renamed = false;
447
+ if (copyFileContent(srcPath, tmpFD, false)) {
448
+ MMKVInfo("copyed file [%ws] to [%ws]", srcPath.c_str(), tmpPath.c_str());
449
+ CloseHandle(tmpFD);
450
+ renamed = tryAtomicRename(tmpPath.c_str(), dstPath.c_str());
451
+ if (renamed) {
452
+ MMKVInfo("copyfile [%ws] to [%ws] finish.", srcPath.c_str(), dstPath.c_str());
453
+ }
454
+ } else {
455
+ CloseHandle(tmpFD);
456
+ }
457
+
458
+ if (!renamed) {
459
+ DeleteFile(tmpPath.c_str());
460
+ }
461
+ return renamed;
462
+ }
463
+
464
+ bool copyFileContent(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) {
465
+ File dstFile(dstPath, OpenFlag::WriteOnly | OpenFlag::Create | OpenFlag::Truncate);
466
+ if (!dstFile.isFileValid()) {
467
+ return false;
468
+ }
469
+ auto ret = copyFileContent(srcPath, dstFile.getFd(), false);
470
+ if (!ret) {
471
+ MMKVError("fail to copyfile(): target file %ws", dstPath.c_str());
472
+ } else {
473
+ MMKVInfo("copy content from %ws to [%ws] finish", srcPath.c_str(), dstPath.c_str());
474
+ }
475
+ return ret;
476
+ }
477
+
478
+ bool copyFileContent(const MMKVPath_t &srcPath, MMKVFileHandle_t dstFD) {
479
+ return copyFileContent(srcPath, dstFD, true);
480
+ }
481
+
482
+ void walkInDir(const MMKVPath_t &dirPath,
483
+ WalkType type,
484
+ const std::function<void(const MMKVPath_t &, WalkType)> &walker) {
485
+ wchar_t szDir[MAX_PATH];
486
+ StringCchCopy(szDir, MAX_PATH, dirPath.c_str());
487
+ StringCchCat(szDir, MAX_PATH, L"\\*");
488
+
489
+ WIN32_FIND_DATA ffd;
490
+ auto hFind = FindFirstFile(szDir, &ffd);
491
+ if (hFind == INVALID_HANDLE_VALUE) {
492
+ return;
493
+ }
494
+
495
+ do {
496
+ if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
497
+ if (type & WalkFolder) {
498
+ if (wcscmp(ffd.cFileName, L".") == 0 || wcscmp(ffd.cFileName, L"..") == 0) {
499
+ continue;
500
+ }
501
+ walker(dirPath + L"\\" + ffd.cFileName, WalkFolder);
502
+ }
503
+ } else if (type & WalkFile) {
504
+ walker(dirPath + L"\\" + ffd.cFileName, WalkFile);
505
+ }
506
+ } while (FindNextFile(hFind, &ffd) != 0);
507
+
508
+ auto dwError = GetLastError();
509
+ if (dwError != ERROR_NO_MORE_FILES) {
510
+ MMKVError("WalkInDir fail %d", dwError);
511
+ }
512
+
513
+ FindClose(hFind);
514
+ }
515
+
305
516
  } // namespace mmkv
306
517
 
307
518
  std::wstring string2MMKVPath_t(const std::string &str) {
@@ -313,4 +524,13 @@ std::wstring string2MMKVPath_t(const std::string &str) {
313
524
  return result;
314
525
  }
315
526
 
527
+ std::string MMKVPath_t2String(const MMKVPath_t &str) {
528
+ auto length = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, nullptr, 0, 0, 0);
529
+ auto buffer = new char[length];
530
+ WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, buffer, length, 0, 0);
531
+ string result(buffer);
532
+ delete[] buffer;
533
+ return result;
534
+ }
535
+
316
536
  #endif // MMKV_WIN32
@@ -89,13 +89,13 @@ int AES_C_set_decrypt_key(const uint8_t *userKey, const int bits, void *key);
89
89
  void AES_C_encrypt(const uint8_t *in, uint8_t *out, const void *key);
90
90
  void AES_C_decrypt(const uint8_t *in, uint8_t *out, const void *key);
91
91
 
92
- } // namespace openssl
93
-
94
92
  extern aes_set_encrypt_t AES_set_encrypt_key;
95
93
  extern aes_set_decrypt_t AES_set_decrypt_key;
96
94
  extern aes_encrypt_t AES_encrypt;
97
95
  extern aes_decrypt_t AES_decrypt;
98
96
 
97
+ } // namespace openssl
98
+
99
99
  #endif // __ARM_MAX_ARCH__ <= 7
100
100
 
101
101
  #endif // __linux__
@@ -43,6 +43,8 @@
43
43
 
44
44
  #ifndef MMKV_DISABLE_CRYPT
45
45
 
46
+ namespace openssl {
47
+
46
48
  #if (__ARM_MAX_ARCH__ > 7) && defined(__linux__)
47
49
 
48
50
  aes_set_encrypt_t AES_set_encrypt_key = openssl::AES_C_set_encrypt_key;
@@ -54,8 +56,6 @@ aes_encrypt_t AES_decrypt = openssl::AES_C_decrypt;
54
56
 
55
57
  #if (__ARM_MAX_ARCH__ <= 0) || (__ARM_MAX_ARCH__ > 7 && defined(__linux__))
56
58
 
57
- namespace openssl {
58
-
59
59
  /*-
60
60
  Te0[x] = S [x].[02, 01, 01, 03];
61
61
  Te1[x] = S [x].[03, 02, 01, 01];
@@ -1037,8 +1037,8 @@ void AES_C_decrypt(const uint8_t *in, uint8_t *out, const void *k) {
1037
1037
  PUTU32(out + 12, s3);
1038
1038
  }
1039
1039
 
1040
- } // namespace openssl
1041
-
1042
1040
  #endif // (__ARM_MAX_ARCH__ < 0) || (__ARM_MAX_ARCH__ > 7 && defined(__linux__))
1043
1041
 
1042
+ } // namespace openssl
1043
+
1044
1044
  #endif // MMKV_DISABLE_CRYPT
package/MMKV/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  [![license](https://img.shields.io/badge/license-BSD_3-brightgreen.svg?style=flat)](https://github.com/Tencent/MMKV/blob/master/LICENSE.TXT)
2
2
  [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/Tencent/MMKV/pulls)
3
- [![Release Version](https://img.shields.io/badge/release-1.2.10-brightgreen.svg)](https://github.com/Tencent/MMKV/releases)
3
+ [![Release Version](https://img.shields.io/badge/release-1.2.12-brightgreen.svg)](https://github.com/Tencent/MMKV/releases)
4
4
  [![Platform](https://img.shields.io/badge/Platform-%20Android%20%7C%20iOS%2FmacOS%20%7C%20Win32%20%7C%20POSIX-brightgreen.svg)](https://github.com/Tencent/MMKV/wiki/home)
5
5
 
6
6
  中文版本请参看[这里](./README_CN.md)
@@ -28,12 +28,12 @@ Add the following lines to `build.gradle` on your app module:
28
28
 
29
29
  ```gradle
30
30
  dependencies {
31
- implementation 'com.tencent:mmkv-static:1.2.10'
32
- // replace "1.2.10" with any available version
31
+ implementation 'com.tencent:mmkv:1.2.12'
32
+ // replace "1.2.12" with any available version
33
33
  }
34
34
  ```
35
35
 
36
- Starting from v1.2.8, MMKV has been **migrated to Maven Central**. Older versions (<= v1.2.7) are still available on JCenter.
36
+ Starting from v1.2.8, MMKV has been **migrated to Maven Central**.
37
37
  For other installation options, see [Android Setup](https://github.com/Tencent/MMKV/wiki/android_setup).
38
38
 
39
39
  ### Quick Tutorial
package/README.md CHANGED
@@ -37,13 +37,13 @@
37
37
  ## Sponsors
38
38
 
39
39
  <div align="right">
40
- <a href="https://getstream.io/chat/react-native-chat/tutorial/?utm_source=github&utm_medium=github_repo_content_ad&utm_content=developer&utm_campaign=github_sept2021_reactnativechat">
40
+ <a href="https://getstream.io/chat/react-native-chat/tutorial/?utm_source=Github&utm_medium=Github_Repo_Content_Ad&utm_content=Developer&utm_campaign=Github_Jan2022_ReactNative&utm_term=react-native-mmkv">
41
41
  <img align="right" src="https://theme.zdassets.com/theme_assets/9442057/efc3820e436f9150bc8cf34267fff4df052a1f9c.png" height="40" />
42
42
  </a>
43
43
  </div>
44
44
 
45
45
  react-native-mmkv is sponsored by **getstream.io**. <br/>
46
- [Try the React Native Chat tutorial 💬](https://getstream.io/chat/react-native-chat/tutorial/?utm_source=github&utm_medium=github_repo_content_ad&utm_content=developer&utm_campaign=github_sept2021_reactnativechat)
46
+ [Try the React Native Chat tutorial 💬](https://getstream.io/chat/react-native-chat/tutorial/?utm_source=Github&utm_medium=Github_Repo_Content_Ad&utm_content=Developer&utm_campaign=Github_Jan2022_ReactNative&utm_term=react-native-mmkv)
47
47
 
48
48
  ## Benchmark
49
49
 
@@ -57,25 +57,19 @@ react-native-mmkv is sponsored by **getstream.io**. <br/>
57
57
 
58
58
  ## Installation
59
59
 
60
- ```sh
61
- npm install react-native-mmkv
62
- ```
63
-
64
- ### iOS
65
-
66
- iOS installation is automatic, just run:
60
+ ### React Native
67
61
 
68
62
  ```sh
63
+ yarn add react-native-mmkv
69
64
  cd ios && pod install
70
65
  ```
71
66
 
72
- ### Android
73
-
74
- To correctly initialize MMKV on Android, please follow the [Installation guide](./INSTALL.md).
75
-
76
67
  ### Expo
77
68
 
78
- See this comment for more information: [mrousavy/react-native-mmkv#157 (comment)](https://github.com/mrousavy/react-native-mmkv/issues/157#issuecomment-960647481).
69
+ ```sh
70
+ expo install react-native-mmkv
71
+ expo prebuild
72
+ ```
79
73
 
80
74
  ## Usage
81
75
 
@@ -166,8 +160,10 @@ const userObject = JSON.parse(jsonUser)
166
160
  * [Hooks](./docs/HOOKS.md)
167
161
  * [Value-change Listeners](./docs/LISTENERS.md)
168
162
  * [Migrate from AsyncStorage](./docs/MIGRATE_FROM_ASYNC_STORAGE.md)
169
- * [Using MMKV with redux-persis](./docs/WRAPPER_REDUX.md)
163
+ * [Using MMKV with redux-persist](./docs/WRAPPER_REDUX.md)
170
164
  * [Using MMKV with mobx-persist-storage](./docs/WRAPPER_MOBX.md)
165
+ * [Using MMKV with mobx-persist](./docs/WRAPPER_MOBXPERSIST.md)
166
+ * [How is this library different from **react-native-mmkv-storage**?](https://github.com/mrousavy/react-native-mmkv/issues/100#issuecomment-886477361)
171
167
 
172
168
  ## Limitations
173
169
 
@@ -17,10 +17,6 @@ if(${REACT_NATIVE_VERSION} LESS 66)
17
17
  INCLUDE_JSI_CPP
18
18
  "${NODE_MODULES_DIR}/react-native/ReactCommon/jsi/jsi/jsi.cpp"
19
19
  )
20
- set (
21
- INCLUDE_JSIDYNAMIC_CPP
22
- "${NODE_MODULES_DIR}/react-native/ReactCommon/jsi/jsi/JSIDynamic.cpp"
23
- )
24
20
  endif()
25
21
 
26
22
  add_library(reactnativemmkv # <-- Library name
@@ -28,7 +24,6 @@ add_library(reactnativemmkv # <-- Library name
28
24
  src/main/cpp/cpp-adapter.cpp
29
25
  src/main/cpp/MmkvHostObject.cpp
30
26
  ${INCLUDE_JSI_CPP} # only on older RN versions
31
- ${INCLUDE_JSIDYNAMIC_CPP} # only on older RN versions
32
27
  )
33
28
 
34
29
  set_target_properties(
@@ -38,7 +33,7 @@ set_target_properties(
38
33
  POSITION_INDEPENDENT_CODE ON
39
34
  )
40
35
 
41
- file (GLOB LIBRN_DIR "${BUILD_DIR}/react-native-0*/jni/${ANDROID_ABI}")
36
+ file (GLOB LIBRN_DIR "${PREBUILT_DIR}/${ANDROID_ABI}")
42
37
 
43
38
  find_library(
44
39
  log-lib
@@ -46,6 +46,12 @@ def getExtOrIntegerDefault(name) {
46
46
  return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['Mmkv_' + name]).toInteger()
47
47
  }
48
48
 
49
+ def reactNativeArchitectures() {
50
+ def value = project.getProperties().get("reactNativeArchitectures")
51
+ return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
52
+ }
53
+
54
+ def sourceBuild = false
49
55
  def defaultDir = null
50
56
  def androidSourcesDir = null
51
57
  def androidSourcesName = 'React Native sources'
@@ -53,6 +59,10 @@ def androidSourcesName = 'React Native sources'
53
59
  if (rootProject.ext.has('reactNativeAndroidRoot')) {
54
60
  defaultDir = rootProject.ext.get('reactNativeAndroidRoot')
55
61
  androidSourcesDir = defaultDir.parentFile.toString()
62
+ } else if (findProject(':ReactAndroid') != null) {
63
+ sourceBuild = true
64
+ defaultDir = project(':ReactAndroid').projectDir
65
+ androidSourcesDir = defaultDir.parentFile.toString()
56
66
  } else {
57
67
  defaultDir = file("$nodeModules/react-native/android")
58
68
  androidSourcesDir = defaultDir.parentFile.toString()
@@ -64,6 +74,11 @@ if (!defaultDir.exists()) {
64
74
  )
65
75
  }
66
76
 
77
+ def prebuiltDir = sourceBuild
78
+ ? "$nodeModules/react-native/ReactAndroid/src/main/jni/prebuilt/lib"
79
+ : "$buildDir/react-native-0*/jni"
80
+
81
+
67
82
  def reactProperties = new Properties()
68
83
  file("$nodeModules/react-native/ReactAndroid/gradle.properties").withInputStream { reactProperties.load(it) }
69
84
  def REACT_NATIVE_VERSION = reactProperties.getProperty("VERSION_NAME").split("\\.")[1].toInteger()
@@ -81,12 +96,15 @@ android {
81
96
  externalNativeBuild {
82
97
  cmake {
83
98
  cppFlags "-fexceptions", "-frtti", "-std=c++1y", "-DONANDROID"
84
- abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
85
99
  arguments '-DANDROID_STL=c++_shared',
86
100
  "-DREACT_NATIVE_VERSION=${REACT_NATIVE_VERSION}",
87
- "-DNODE_MODULES_DIR=${nodeModules}"
101
+ "-DNODE_MODULES_DIR=${nodeModules}",
102
+ "-DPREBUILT_DIR=${prebuiltDir}"
88
103
  }
89
104
  }
105
+ ndk {
106
+ abiFilters (*reactNativeArchitectures())
107
+ }
90
108
  }
91
109
 
92
110
  dexOptions {
@@ -141,8 +159,10 @@ dependencies {
141
159
  //noinspection GradleDynamicVersion
142
160
  extractJNI("com.facebook.fbjni:fbjni:+")
143
161
 
144
- def rnAAR = fileTree("${defaultDir.toString()}").matching({ it.include "**/**/*.aar" }).singleFile
145
- extractJNI(files(rnAAR))
162
+ if (!sourceBuild) {
163
+ def rnAAR = fileTree("${defaultDir.toString()}").matching({ it.include "**/**/*.aar" }).singleFile
164
+ extractJNI(files(rnAAR))
165
+ }
146
166
  }
147
167
 
148
168
  // third-party-ndk deps headers
@@ -311,10 +331,22 @@ task extractJNIFiles {
311
331
  }
312
332
  extractJNIFiles.mustRunAfter extractAARHeaders
313
333
 
314
- tasks.whenTaskAdded { task ->
315
- if (!task.name.contains('Clean') && (task.name.contains('externalNative') || task.name.contains('CMake'))) {
316
- task.dependsOn(extractAARHeaders)
317
- task.dependsOn(extractJNIFiles)
318
- task.dependsOn(prepareThirdPartyNdkHeaders)
334
+ def nativeBuildDependsOn(dependsOnTask, variant) {
335
+ def buildTasks = tasks.findAll({ task ->
336
+ !task.name.contains("Clean") && (task.name.contains("externalNative") || task.name.contains("CMake")) })
337
+ if (variant != null) {
338
+ buildTasks = buildTasks.findAll({ task -> task.name.contains(variant) })
339
+ }
340
+ buildTasks.forEach { task -> task.dependsOn(dependsOnTask) }
341
+ }
342
+
343
+ afterEvaluate {
344
+ if (sourceBuild) {
345
+ nativeBuildDependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck", "Debug")
346
+ nativeBuildDependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck", "Rel")
347
+ } else {
348
+ nativeBuildDependsOn(extractAARHeaders, null)
349
+ nativeBuildDependsOn(extractJNIFiles, null)
350
+ nativeBuildDependsOn(prepareThirdPartyNdkHeaders, null)
319
351
  }
320
352
  }
@@ -1,24 +1,49 @@
1
1
  package com.reactnativemmkv;
2
2
 
3
+ import android.util.Log;
4
+
3
5
  import androidx.annotation.NonNull;
6
+ import androidx.annotation.Nullable;
4
7
 
5
8
  import com.facebook.react.bridge.JavaScriptContextHolder;
6
9
  import com.facebook.react.bridge.ReactContextBaseJavaModule;
10
+ import com.facebook.react.bridge.ReactApplicationContext;
11
+ import com.facebook.react.bridge.ReactMethod;
12
+ import com.facebook.react.module.annotations.ReactModule;
7
13
 
14
+ @ReactModule(name = MmkvModule.NAME)
8
15
  public class MmkvModule extends ReactContextBaseJavaModule {
9
- static {
10
- System.loadLibrary("reactnativemmkv");
11
- }
16
+ public static final String NAME = "MMKV";
12
17
 
13
- private static native void nativeInstall(long jsiPtr, String path);
14
-
15
- public static void install(JavaScriptContextHolder jsContext, String storageDirectory) {
16
- nativeInstall(jsContext.get(), storageDirectory);
18
+ public MmkvModule(ReactApplicationContext reactContext) {
19
+ super(reactContext);
17
20
  }
18
21
 
19
22
  @NonNull
20
23
  @Override
21
24
  public String getName() {
22
- return "MMKV";
25
+ return NAME;
23
26
  }
27
+
28
+ @ReactMethod(isBlockingSynchronousMethod = true)
29
+ public boolean install(@Nullable String rootDirectory) {
30
+ try {
31
+ Log.i(NAME, "Loading C++ library...");
32
+ System.loadLibrary("reactnativemmkv");
33
+
34
+ JavaScriptContextHolder jsContext = getReactApplicationContext().getJavaScriptContextHolder();
35
+ if (rootDirectory == null) {
36
+ rootDirectory = getReactApplicationContext().getFilesDir().getAbsolutePath() + "/mmkv";
37
+ }
38
+ Log.i(NAME, "Installing MMKV JSI Bindings for MMKV root directory: " + rootDirectory);
39
+ nativeInstall(jsContext.get(), rootDirectory);
40
+ Log.i(NAME, "Successfully installed MMKV JSI Bindings!");
41
+ return true;
42
+ } catch (Exception exception) {
43
+ Log.e(NAME, "Failed to install MMKV JSI Bindings!", exception);
44
+ return false;
45
+ }
46
+ }
47
+
48
+ private static native void nativeInstall(long jsiPtr, String path);
24
49
  }