MCPcopy Create free account
hub / github.com/crosspoint-reader/crosspoint-reader / writeAtomic

Function writeAtomic

src/activities/reader/ProgressFile.h:32–62  ·  view source on GitHub ↗

Writes `len` bytes of reader progress to ` /progress.bin` without ever leaving the canonical file half-written. The bytes go to a temporary `progress.bin.tmp` first; only once that is fully written and closed is it renamed over progress.bin. An interrupted write (power loss or a crash mid-SPI) therefore damages only the throwaway temp file. Previously a truncate-in-place write that was

Source from the content-addressed store, hash-verified

30//
31// Returns true only if the new progress.bin is fully in place.
32inline bool writeAtomic(const std::string& cachePath, const uint8_t* data, size_t len) {
33 const std::string finalPath = cachePath + "/progress.bin";
34 const std::string tmpPath = cachePath + "/progress.bin.tmp";
35
36 {
37 HalFile f;
38 if (!Storage.openFileForWrite("PRG", tmpPath, f)) {
39 LOG_ERR("PRG", "Could not open temp progress file for write: %s", tmpPath.c_str());
40 return false;
41 }
42 const size_t written = f.write(data, len);
43 if (written != len) {
44 LOG_ERR("PRG", "Short write saving progress to %s: %u/%u bytes", tmpPath.c_str(), (unsigned)written,
45 (unsigned)len);
46 return false;
47 }
48 f.flush();
49 // f (the temp file) is closed at scope exit (DESTRUCTOR_CLOSES_FILE=1) before
50 // the rename below -- SdFat must not rename a path that still has an open FsFile.
51 }
52
53 // SdFat's rename does not overwrite an existing destination, so drop the old
54 // canonical file first. The brief window where neither file exists reads as
55 // "no saved progress" on next launch -- never a corrupt, unclearable file.
56 Storage.remove(finalPath.c_str());
57 if (!Storage.rename(tmpPath.c_str(), finalPath.c_str())) {
58 LOG_ERR("PRG", "Failed to rename temp progress into place: %s", finalPath.c_str());
59 return false;
60 }
61 return true;
62}
63
64} // namespace ProgressFile

Callers 3

saveProgressFunction · 0.85
saveProgressMethod · 0.85
saveProgressMethod · 0.85

Calls 5

openFileForWriteMethod · 0.80
removeMethod · 0.80
renameMethod · 0.80
writeMethod · 0.45
flushMethod · 0.45

Tested by

no test coverage detected