| 52 | |
| 53 | template <typename Data> |
| 54 | bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data) |
| 55 | { |
| 56 | // Generate random temporary filename |
| 57 | const uint16_t randv{FastRandomContext().rand<uint16_t>()}; |
| 58 | std::string tmpfn = strprintf("%s.%04x", prefix, randv); |
| 59 | |
| 60 | // open temp output file |
| 61 | fs::path pathTmp = gArgs.GetDataDirNet() / fs::u8path(tmpfn); |
| 62 | FILE *file = fsbridge::fopen(pathTmp, "wb"); |
| 63 | AutoFile fileout{file}; |
| 64 | if (fileout.IsNull()) { |
| 65 | remove(pathTmp); |
| 66 | LogError("%s: Failed to open file %s\n", __func__, fs::PathToString(pathTmp)); |
| 67 | return false; |
| 68 | } |
| 69 | |
| 70 | // Serialize |
| 71 | if (!SerializeDB(fileout, data)) { |
| 72 | (void)fileout.fclose(); |
| 73 | remove(pathTmp); |
| 74 | return false; |
| 75 | } |
| 76 | if (!fileout.Commit()) { |
| 77 | (void)fileout.fclose(); |
| 78 | remove(pathTmp); |
| 79 | LogError("%s: Failed to flush file %s\n", __func__, fs::PathToString(pathTmp)); |
| 80 | return false; |
| 81 | } |
| 82 | if (fileout.fclose() != 0) { |
| 83 | const int errno_save{errno}; |
| 84 | remove(pathTmp); |
| 85 | LogError("Failed to close file %s after commit: %s", fs::PathToString(pathTmp), SysErrorString(errno_save)); |
| 86 | return false; |
| 87 | } |
| 88 | |
| 89 | // replace existing file, if any, with new file |
| 90 | if (!RenameOver(pathTmp, path)) { |
| 91 | remove(pathTmp); |
| 92 | LogError("%s: Rename-into-place failed\n", __func__); |
| 93 | return false; |
| 94 | } |
| 95 | |
| 96 | return true; |
| 97 | } |
| 98 | |
| 99 | template <typename Stream, typename Data> |
| 100 | void DeserializeDB(Stream& stream, Data&& data, bool fCheckSum = true) |
no test coverage detected