Jazz2::Utils::AtomicFile class

Writes a file so that a failed write never damages the file that was there.

The content goes into a temporary file next to the target first. Every write is checked, the file is flushed to the device, and only then it replaces the target in one step. If anything fails, the target is left untouched and the temporary file is removed.

Public static functions

static auto Write(StringView path, Function<bool(Stream&)>&& write, bool keepBackup = false) -> bool
Writes a file through a temporary file.
static auto Write(StringView path, const void* data, std::int64_t size, bool keepBackup = false) -> bool
Writes a block of bytes into a file through a temporary file.
static auto Stage(StringView path, Function<bool(Stream&)>&& write) -> bool
Writes the content only into the temporary file of path, the target isn't touched yet.
static auto Commit(StringView path, bool keepBackup = false) -> bool
Replaces path with its temporary file written by Stage().
static void Discard(StringView path)
Removes the temporary file of path written by Stage().
static auto RestoreBackup(StringView path, bool existedBefore) -> bool
Puts back the file kept by Commit() as <path>.bak.

Constructors, destructors, conversion operators

AtomicFile() deleted

Function documentation

static bool Jazz2::Utils::AtomicFile::Write(StringView path, Function<bool(Stream&)>&& write, bool keepBackup = false)

Writes a file through a temporary file.

Parameters
path Target file
write Writes the content, returns false if it failed
keepBackup Whether the previous file is kept as <path>.bak
Returns true if the target holds the new content

static bool Jazz2::Utils::AtomicFile::Stage(StringView path, Function<bool(Stream&)>&& write)

Writes the content only into the temporary file of path, the target isn't touched yet.

For several files that change together: all of them are staged first, and only if every one was written, they're committed (see Commit()), otherwise discarded (see Discard()). Returns false if the temporary file couldn't be written whole, it's removed then.

static bool Jazz2::Utils::AtomicFile::Commit(StringView path, bool keepBackup = false)

Replaces path with its temporary file written by Stage().

With keepBackup, the previous file is kept as <path>.bak, so the change can be reverted by RestoreBackup(). Returns false if the target couldn't be replaced, it stays as it was then.

static bool Jazz2::Utils::AtomicFile::RestoreBackup(StringView path, bool existedBefore)

Puts back the file kept by Commit() as <path>.bak.

If there was no file before, the file is removed. Returns false if it couldn't be put back.