| 58 | namespace mmkv { |
| 59 | |
| 60 | bool tryAtomicRename(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) { |
| 61 | if (srcPath.empty() || dstPath.empty()) { |
| 62 | return false; |
| 63 | } |
| 64 | bool renamed = false; |
| 65 | |
| 66 | // try atomic swap first |
| 67 | if (@available(iOS 10.0, watchOS 3.0, macOS 10.12, *)) { |
| 68 | // renameat2() equivalent |
| 69 | if (renamex_np(srcPath.c_str(), dstPath.c_str(), RENAME_SWAP) == 0) { |
| 70 | renamed = true; |
| 71 | if (srcPath != dstPath) { |
| 72 | ::unlink(srcPath.c_str()); |
| 73 | } |
| 74 | } else if (errno != ENOENT) { |
| 75 | MMKVError("fail to renamex_np %s to %s, %s", srcPath.c_str(), dstPath.c_str(), strerror(errno)); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | if (!renamed) { |
| 80 | // try old style rename |
| 81 | if (rename(srcPath.c_str(), dstPath.c_str()) != 0) { |
| 82 | MMKVError("fail to rename %s to %s, %s", srcPath.c_str(), dstPath.c_str(), strerror(errno)); |
| 83 | return false; |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | return true; |
| 88 | } |
| 89 | |
| 90 | bool copyFile(const MMKVPath_t &srcPath, const MMKVPath_t &dstPath) { |
| 91 | // prepare a temp file for atomic rename, avoid data corruption of sudden crash |