writeBytes method

  1. @override
Future<void> writeBytes(
  1. String path,
  2. Uint8List bytes
)
override

Writes through a sibling temp file and renames it over the target.

The rename is what makes the write atomic (see TomBundleMedium): it is a single directory operation on every filesystem a desktop or server runs, so a reader sees the old file or the new one and never a prefix. A sibling rather than a system temp directory, because rename is only atomic — and on POSIX only possible — within one filesystem, and the platform's temp directory is routinely on another.

flush: true is the strongest durability Dart offers here: it fsyncs the file before the rename, so the bytes are on the device before anything points at them. It is expected-green under mutation — its effect is observable only after a power loss, which no in-process test can stage — and it is not decoration: without it the rename can publish a file whose contents the device has not yet written. What is not available is an fsync of the directory itself, so a power loss in the window after the rename can still lose the rename on some filesystems. That is a smaller hole than the one this closes — it loses the new content rather than corrupting the file — and closing it needs an API dart:io does not expose.

Implementation

@override
Future<void> writeBytes(String path, Uint8List bytes) async {
  final file = _file(path);
  file.parent.createSync(recursive: true);
  _sweepStaleTemps(file);
  final temp = File('${file.path}.$_pid.${_counter++}$tempSuffix');
  temp.writeAsBytesSync(bytes, flush: true);
  temp.renameSync(file.path);
}