1use std::fs::{self, File, OpenOptions};
19use std::io::Write as _;
20use std::path::{Path, PathBuf};
21
22pub fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), AtomicError> {
39 AtomicWrite::new(bytes).write(path)
40}
41
42pub(crate) fn validate_unix_mode(mode: Option<u32>) -> std::io::Result<()> {
43 if let Some(mode) = mode
44 && mode & !0o777 != 0
45 {
46 return Err(std::io::Error::new(
47 std::io::ErrorKind::InvalidInput,
48 format!("unix mode {mode:o} contains bits outside 0o777"),
49 ));
50 }
51 Ok(())
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum InstallMode {
57 Replace,
60 NewOnly,
63}
64
65#[derive(Debug, Clone)]
96pub struct AtomicWrite<'a> {
97 bytes: &'a [u8],
98 install_mode: InstallMode,
99 unix_mode: Option<u32>,
100 caller_guarded: Option<Option<fs::Metadata>>,
104}
105
106impl<'a> AtomicWrite<'a> {
107 pub fn new(bytes: &'a [u8]) -> Self {
109 Self {
110 bytes,
111 install_mode: InstallMode::Replace,
112 unix_mode: None,
113 caller_guarded: None,
114 }
115 }
116
117 #[cfg(unix)]
120 #[must_use]
121 pub fn mode(mut self, bits: u32) -> Self {
122 self.unix_mode = Some(bits);
123 self
124 }
125
126 #[must_use]
130 pub fn new_only(mut self) -> Self {
131 self.install_mode = InstallMode::NewOnly;
132 self
133 }
134
135 pub fn write(self, path: &Path) -> Result<(), AtomicError> {
141 self.write_with(path, |file, bytes| file.write_all(bytes))
142 }
143
144 pub(crate) fn with_unix_mode(mut self, unix_mode: Option<u32>) -> Self {
147 self.unix_mode = unix_mode;
148 self
149 }
150
151 pub(crate) fn with_target_metadata(mut self, metadata: Option<fs::Metadata>) -> Self {
155 self.caller_guarded = Some(metadata);
156 self
157 }
158
159 fn write_with(
160 mut self,
161 path: &Path,
162 write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
163 ) -> Result<(), AtomicError> {
164 validate_unix_mode(self.unix_mode)
165 .map_err(|error| AtomicError::at(AtomicStep::Guard, path, error))?;
166 if let Some(metadata) = self.caller_guarded.take() {
167 return install_with_writer(path, &self, metadata, write);
168 }
169 let metadata = if self.install_mode == InstallMode::NewOnly {
172 None
173 } else {
174 match fs::symlink_metadata(path) {
175 Ok(metadata) if metadata.file_type().is_file() => Some(metadata),
176 Ok(_) => {
177 return Err(AtomicError::at(
178 AtomicStep::Guard,
179 path,
180 std::io::Error::new(
181 std::io::ErrorKind::InvalidInput,
182 "atomic target must be a regular file, not a symlink, directory, or special file",
183 ),
184 ));
185 }
186 Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
187 Err(error) => return Err(AtomicError::at(AtomicStep::Guard, path, error)),
188 }
189 };
190 install_with_writer(path, &self, metadata, write)
191 }
192}
193
194#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum AtomicStep {
197 Guard,
199 NoParent,
201 NonUtf8Name,
203 Temp,
205 TempExhausted,
207 Write,
209 PreservePermissions,
211 #[cfg(unix)]
214 PreserveOwnership,
215 #[cfg(unix)]
220 SetPermissions,
221 Sync,
223 Install,
225 SyncParent,
227}
228
229#[derive(Debug)]
231pub struct AtomicError {
232 pub step: AtomicStep,
234 pub path: PathBuf,
237 pub source: Option<std::io::Error>,
239}
240
241impl AtomicError {
242 fn at(step: AtomicStep, path: &Path, source: std::io::Error) -> Self {
243 Self {
244 step,
245 path: path.to_path_buf(),
246 source: Some(source),
247 }
248 }
249
250 pub fn target_exists(&self) -> bool {
254 self.step == AtomicStep::Install
255 && self
256 .source
257 .as_ref()
258 .is_some_and(|error| error.kind() == std::io::ErrorKind::AlreadyExists)
259 }
260
261 pub fn commit_uncertain(&self) -> bool {
268 self.step == AtomicStep::SyncParent
269 }
270}
271
272impl std::fmt::Display for AtomicError {
273 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274 let path = self.path.display();
275 let phrase = match self.step {
276 AtomicStep::Guard => "inspect",
277 AtomicStep::NoParent => {
278 return write!(formatter, "has no parent directory for `{path}`");
279 }
280 AtomicStep::NonUtf8Name => {
281 return write!(formatter, "path is not valid UTF-8: `{path}`");
282 }
283 AtomicStep::TempExhausted => {
284 return write!(formatter, "could not allocate temporary file in `{path}`");
285 }
286 AtomicStep::Temp => "temporary file in",
287 AtomicStep::Write => "write",
288 #[cfg(unix)]
289 AtomicStep::PreserveOwnership => "preserve owner and group of",
290 AtomicStep::PreservePermissions => "preserve permissions",
291 #[cfg(unix)]
292 AtomicStep::SetPermissions => "set permissions on",
293 AtomicStep::Sync => "fsync",
294 AtomicStep::Install => "install",
295 AtomicStep::SyncParent => "fsync parent directory",
296 };
297 write!(formatter, "{phrase} `{path}`")?;
298 match &self.source {
299 Some(source) => write!(formatter, ": {source}"),
300 None => Ok(()),
301 }
302 }
303}
304
305const MAX_NAME_BYTES: usize = 255;
307
308fn temp_file_name(file_name: &str, pid: u32, attempt: u32) -> String {
317 let suffix = format!(".afdata.{pid}.{attempt}.tmp");
318 let budget = MAX_NAME_BYTES.saturating_sub(suffix.len() + 1);
320 let stem = &file_name[..file_name.floor_char_boundary(budget)];
321 format!(".{stem}{suffix}")
322}
323
324fn parent_and_name(path: &Path) -> Result<(&Path, String), AtomicError> {
328 let parent = match path.parent() {
329 Some(parent) if parent.as_os_str().is_empty() => Path::new("."),
330 Some(parent) => parent,
331 None => {
332 return Err(AtomicError {
333 step: AtomicStep::NoParent,
334 path: path.to_path_buf(),
335 source: None,
336 });
337 }
338 };
339 let file_name = path
340 .file_name()
341 .and_then(|name| name.to_str())
342 .ok_or_else(|| AtomicError {
343 step: AtomicStep::NonUtf8Name,
344 path: path.to_path_buf(),
345 source: None,
346 })?
347 .to_string();
348 Ok((parent, file_name))
349}
350
351fn allocate_private_temp(parent: &Path, file_name: &str) -> Result<(PathBuf, File), AtomicError> {
352 let pid = std::process::id();
353 for attempt in 0..32_u32 {
354 let candidate = parent.join(temp_file_name(file_name, pid, attempt));
355 let mut options = OpenOptions::new();
356 options.write(true).create_new(true);
357 #[cfg(unix)]
358 {
359 use std::os::unix::fs::OpenOptionsExt as _;
360 options.mode(0o600);
363 }
364 match options.open(&candidate) {
365 Ok(file) => return Ok((candidate, file)),
366 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
367 Err(error) => return Err(AtomicError::at(AtomicStep::Temp, parent, error)),
368 }
369 }
370 Err(AtomicError {
371 step: AtomicStep::TempExhausted,
372 path: parent.to_path_buf(),
373 source: None,
374 })
375}
376
377#[cfg(unix)]
378fn sync_parent(parent: &Path) -> Result<(), AtomicError> {
379 File::open(parent)
380 .and_then(|directory| directory.sync_all())
381 .map_err(|error| AtomicError::at(AtomicStep::SyncParent, parent, error))
382}
383
384#[cfg(not(unix))]
385fn sync_parent(_parent: &Path) -> Result<(), AtomicError> {
386 Ok(())
389}
390
391#[cfg(unix)]
401fn preserve_ownership(file: &File, target: &fs::Metadata, mode: u32) -> std::io::Result<()> {
402 use std::os::unix::fs::{MetadataExt as _, fchown};
403 let current = file.metadata()?;
404 let uid = (current.uid() != target.uid()).then_some(target.uid());
405 let gid = (current.gid() != target.gid()).then_some(target.gid());
406 if uid.is_none() && gid.is_none() {
407 return Ok(());
408 }
409 let denied = |error: &std::io::Error| error.kind() == std::io::ErrorKind::PermissionDenied;
410 let result = match fchown(file, uid, gid) {
411 Err(error) if uid.is_some() && gid.is_some() && denied(&error) => fchown(file, None, gid),
412 Err(error) if uid.is_some() && gid.is_none() && denied(&error) => Ok(()),
413 other => other,
414 };
415 match result {
416 Err(error) if mode & 0o070 == 0 && denied(&error) => Ok(()),
417 other => other,
418 }
419}
420
421fn write_temp(
422 mut temp_file: File,
423 temp_path: &Path,
424 target: &Path,
425 request: &AtomicWrite<'_>,
426 metadata: Option<fs::Metadata>,
427 write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
428) -> Result<(), AtomicError> {
429 write(&mut temp_file, request.bytes)
430 .map_err(|error| AtomicError::at(AtomicStep::Write, target, error))?;
431 if let Some(metadata) = metadata {
432 #[cfg(unix)]
433 {
434 use std::os::unix::fs::PermissionsExt as _;
435 let mode = request
436 .unix_mode
437 .unwrap_or_else(|| metadata.permissions().mode());
438 preserve_ownership(&temp_file, &metadata, mode)
439 .map_err(|error| AtomicError::at(AtomicStep::PreserveOwnership, target, error))?;
440 }
441 if request.unix_mode.is_none() {
442 temp_file
443 .set_permissions(metadata.permissions())
444 .map_err(|error| AtomicError::at(AtomicStep::PreservePermissions, target, error))?;
445 }
446 }
447 #[cfg(unix)]
448 if let Some(unix_mode) = request.unix_mode {
449 use std::os::unix::fs::PermissionsExt as _;
450 temp_file
451 .set_permissions(fs::Permissions::from_mode(unix_mode))
452 .map_err(|error| AtomicError::at(AtomicStep::SetPermissions, target, error))?;
453 }
454 temp_file
455 .sync_all()
456 .map_err(|error| AtomicError::at(AtomicStep::Sync, temp_path, error))
457}
458
459fn install_with_writer(
466 path: &Path,
467 request: &AtomicWrite<'_>,
468 metadata: Option<fs::Metadata>,
469 write: impl FnOnce(&mut File, &[u8]) -> std::io::Result<()>,
470) -> Result<(), AtomicError> {
471 let (parent, file_name) = parent_and_name(path)?;
472 let (temp_path, temp_file) = allocate_private_temp(parent, &file_name)?;
473 let result = (|| -> Result<(), AtomicError> {
474 write_temp(temp_file, &temp_path, path, request, metadata, write)?;
475 match request.install_mode {
476 InstallMode::Replace => {
477 fs::rename(&temp_path, path)
478 .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
479 }
480 InstallMode::NewOnly => {
481 fs::hard_link(&temp_path, path)
482 .map_err(|error| AtomicError::at(AtomicStep::Install, path, error))?;
483 let _ = fs::remove_file(&temp_path);
488 }
489 }
490 sync_parent(parent)?;
491 Ok(())
492 })();
493 if let Err(error) = &result {
494 if !error.commit_uncertain() {
497 let _ = fs::remove_file(&temp_path);
498 }
499 }
500 result
501}
502
503impl std::error::Error for AtomicError {
504 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
505 self.source.as_ref().map(|error| error as _)
506 }
507}
508
509#[cfg(test)]
510mod tests {
511 #![allow(clippy::unwrap_used, clippy::panic, clippy::expect_used)]
512 use super::*;
513
514 #[test]
515 fn temp_name_stays_within_one_path_component() {
516 let long = "x".repeat(400);
517 let name = temp_file_name(&long, 1234, 0);
518 assert!(name.len() <= MAX_NAME_BYTES, "{} bytes", name.len());
519 assert!(name.starts_with('.'));
520 assert!(name.ends_with(".tmp"));
521 }
522
523 #[test]
524 fn temp_name_truncates_on_a_character_boundary() {
525 let long = "é".repeat(300);
526 let name = temp_file_name(&long, 1234, 0);
527 assert!(name.is_char_boundary(name.len()));
528 assert!(name.len() <= MAX_NAME_BYTES);
529 }
530
531 #[test]
532 fn bare_relative_paths_use_the_current_directory() {
533 let (parent, file_name) = parent_and_name(Path::new("config.json")).unwrap();
534
535 assert_eq!(parent, Path::new("."));
536 assert_eq!(file_name, "config.json");
537 }
538
539 #[test]
540 fn replace_installs_new_bytes_and_leaves_no_temporary_file() {
541 let dir = tempfile::tempdir().unwrap();
542 let path = dir.path().join("config.json");
543 fs::write(&path, b"old").unwrap();
544
545 AtomicWrite::new(b"new").write(&path).unwrap();
546
547 assert_eq!(fs::read(&path).unwrap(), b"new");
548 let strays: Vec<_> = fs::read_dir(dir.path())
549 .unwrap()
550 .filter_map(Result::ok)
551 .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
552 .collect();
553 assert!(strays.is_empty(), "temporary files left behind");
554 }
555
556 #[test]
557 fn new_only_refuses_an_existing_target_without_touching_it() {
558 let dir = tempfile::tempdir().unwrap();
559 let path = dir.path().join("config.json");
560 fs::write(&path, b"original").unwrap();
561
562 let error = AtomicWrite::new(b"new")
563 .new_only()
564 .write(&path)
565 .unwrap_err();
566
567 assert!(error.target_exists());
568 assert_eq!(fs::read(&path).unwrap(), b"original");
569 }
570
571 #[cfg(unix)]
572 #[test]
573 fn replace_swaps_a_symlink_rather_than_following_it() {
574 use std::os::unix::fs::symlink;
575
576 let dir = tempfile::tempdir().unwrap();
577 let outside = dir.path().join("outside.txt");
578 fs::write(&outside, b"untouched").unwrap();
579 let link = dir.path().join("link.txt");
580 symlink(&outside, &link).unwrap();
581
582 AtomicWrite::new(b"new")
583 .with_target_metadata(None)
584 .write(&link)
585 .unwrap();
586
587 assert_eq!(fs::read(&outside).unwrap(), b"untouched");
588 assert!(
589 !fs::symlink_metadata(&link)
590 .unwrap()
591 .file_type()
592 .is_symlink()
593 );
594 assert_eq!(fs::read(&link).unwrap(), b"new");
595 }
596
597 #[cfg(unix)]
598 #[test]
599 fn explicit_unix_mode_wins_over_the_private_temporary_mode() {
600 use std::os::unix::fs::PermissionsExt as _;
601
602 let dir = tempfile::tempdir().unwrap();
603 let path = dir.path().join("readable.md");
604
605 AtomicWrite::new(b"body").mode(0o644).write(&path).unwrap();
606
607 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
608 assert_eq!(mode, 0o644);
609 }
610
611 #[test]
612 fn a_missing_parent_directory_fails_before_any_write() {
613 let dir = tempfile::tempdir().unwrap();
614 let path = dir.path().join("absent").join("config.json");
615
616 let error = AtomicWrite::new(b"new").write(&path).unwrap_err();
617
618 assert_eq!(error.step, AtomicStep::Temp);
619 assert!(!error.commit_uncertain());
620 assert!(!path.exists());
621 }
622 #[test]
623 fn failed_writes_preserve_previous_bytes_and_remove_temporary_file() {
624 let dir = tempfile::tempdir().unwrap();
625 let path = dir.path().join("state.json");
626 fs::write(&path, b"old complete value").unwrap();
627 for error in [
628 std::io::Error::from_raw_os_error(28),
629 std::io::Error::from(std::io::ErrorKind::Interrupted),
630 std::io::Error::from(std::io::ErrorKind::WriteZero),
631 ] {
632 let error = AtomicWrite::new(b"new")
633 .write_with(&path, |file, _| {
634 file.write_all(b"partial")?;
635 Err(error)
636 })
637 .unwrap_err();
638 assert_eq!(error.step, AtomicStep::Write);
639 assert!(!error.commit_uncertain());
640 assert_eq!(fs::read(&path).unwrap(), b"old complete value");
641 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
642 }
643 }
644
645 #[cfg(unix)]
648 fn foreign_ownership(probe: &Path) -> Option<fs::Metadata> {
649 use std::os::unix::fs::MetadataExt as _;
650 let foreign = fs::metadata("/").unwrap();
651 if fs::metadata(probe).unwrap().uid() == foreign.uid()
652 || std::os::unix::fs::chown(probe, None, Some(foreign.gid())).is_ok()
653 {
654 return None;
655 }
656 Some(foreign)
657 }
658
659 #[cfg(unix)]
660 #[test]
661 fn refused_ownership_change_does_not_install_the_temporary_file() {
662 let dir = tempfile::tempdir().unwrap();
663 let path = dir.path().join("state.json");
664 fs::write(&path, b"old complete value").unwrap();
665 let Some(foreign) = foreign_ownership(&path) else {
666 return;
667 };
668 let error = AtomicWrite::new(b"new complete value")
671 .with_target_metadata(Some(foreign))
672 .write(&path)
673 .unwrap_err();
674 assert_eq!(error.step, AtomicStep::PreserveOwnership);
675 assert!(!error.commit_uncertain());
676 assert_eq!(fs::read(&path).unwrap(), b"old complete value");
677 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
678 }
679
680 #[cfg(unix)]
681 #[test]
682 fn unkeepable_ownership_is_accepted_when_the_mode_grants_the_group_nothing() {
683 use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
684
685 let dir = tempfile::tempdir().unwrap();
686 let path = dir.path().join("state.json");
687 fs::write(&path, b"old complete value").unwrap();
688 let Some(foreign) = foreign_ownership(&path) else {
689 return;
690 };
691 let before = fs::metadata(&path).unwrap();
692 AtomicWrite::new(b"new complete value")
693 .with_target_metadata(Some(foreign))
694 .mode(0o600)
695 .write(&path)
696 .unwrap();
697 let after = fs::metadata(&path).unwrap();
698 assert_eq!(fs::read(&path).unwrap(), b"new complete value");
699 assert_eq!((after.uid(), after.gid()), (before.uid(), before.gid()));
700 assert_eq!(after.permissions().mode() & 0o777, 0o600);
701 }
702
703 #[test]
704 fn write_all_retries_short_writes_and_interruptions_before_publish() {
705 struct ShortWriter<'a> {
706 file: &'a mut File,
707 interrupted: bool,
708 }
709 impl std::io::Write for ShortWriter<'_> {
710 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
711 if !self.interrupted {
712 self.interrupted = true;
713 return Err(std::io::ErrorKind::Interrupted.into());
714 }
715 self.file.write(&bytes[..bytes.len().min(2)])
716 }
717 fn flush(&mut self) -> std::io::Result<()> {
718 self.file.flush()
719 }
720 }
721 let dir = tempfile::tempdir().unwrap();
722 let path = dir.path().join("state.json");
723 let bytes = b"new complete value";
724 AtomicWrite::new(bytes)
725 .write_with(&path, |file, bytes| {
726 ShortWriter {
727 file,
728 interrupted: false,
729 }
730 .write_all(bytes)
731 })
732 .unwrap();
733 assert_eq!(fs::read(&path).unwrap(), bytes);
734 }
735
736 #[test]
737 fn interrupted_process_leaves_uncommitted_temporary_file_not_target() {
738 const CHILD_PATH: &str = "AFDATA_TEST_INTERRUPTED_ATOMIC_PATH";
739 if let Some(path) = std::env::var_os(CHILD_PATH) {
740 let _ = AtomicWrite::new(b"new").write_with(Path::new(&path), |file, _| {
741 file.write_all(b"partial")?;
742 file.sync_all()?;
743 std::process::exit(86);
744 });
745 panic!("child did not reach the interrupted write");
746 }
747 let dir = tempfile::tempdir().unwrap();
748 let path = dir.path().join("state.json");
749 write_atomic(&path, b"old complete value").unwrap();
750 let status = std::process::Command::new(std::env::current_exe().unwrap())
751 .args(["--exact", "atomic_file::tests::interrupted_process_leaves_uncommitted_temporary_file_not_target"])
752 .env(CHILD_PATH, &path).status().unwrap();
753 assert_eq!(status.code(), Some(86));
754 assert_eq!(fs::read(&path).unwrap(), b"old complete value");
755 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 2);
756 write_atomic(&path, b"new complete value").unwrap();
757 assert_eq!(fs::read(&path).unwrap(), b"new complete value");
758 }
759
760 #[cfg(unix)]
761 #[test]
762 fn public_write_refuses_a_symlink_target() {
763 let dir = tempfile::tempdir().unwrap();
764 let outside = dir.path().join("outside");
765 fs::write(&outside, b"untouched").unwrap();
766 let link = dir.path().join("link");
767 std::os::unix::fs::symlink(&outside, &link).unwrap();
768 let error = AtomicWrite::new(b"x").write(&link).unwrap_err();
769 assert_eq!(error.step, AtomicStep::Guard);
770 assert_eq!(fs::read(&outside).unwrap(), b"untouched");
771 }
772
773 #[cfg(unix)]
774 fn mode_of(path: &Path) -> u32 {
775 use std::os::unix::fs::PermissionsExt as _;
776 fs::metadata(path).unwrap().permissions().mode() & 0o777
777 }
778
779 #[cfg(unix)]
780 #[test]
781 fn mode_applies_to_a_new_file_and_overrides_an_existing_one() {
782 let dir = tempfile::tempdir().unwrap();
783 let fresh = dir.path().join("fresh");
784 AtomicWrite::new(b"x").mode(0o640).write(&fresh).unwrap();
785 assert_eq!(mode_of(&fresh), 0o640);
786
787 let existing = dir.path().join("existing");
788 write_atomic(&existing, b"old").unwrap();
789 AtomicWrite::new(b"new")
790 .mode(0o604)
791 .write(&existing)
792 .unwrap();
793 assert_eq!(mode_of(&existing), 0o604);
794 assert_eq!(fs::read(&existing).unwrap(), b"new");
795 }
796
797 #[cfg(unix)]
798 #[test]
799 fn default_write_keeps_existing_mode_and_starts_new_files_private() {
800 use std::os::unix::fs::PermissionsExt as _;
801 let dir = tempfile::tempdir().unwrap();
802 let existing = dir.path().join("existing");
803 fs::write(&existing, b"old").unwrap();
804 fs::set_permissions(&existing, fs::Permissions::from_mode(0o644)).unwrap();
805 write_atomic(&existing, b"new").unwrap();
806 assert_eq!(mode_of(&existing), 0o644);
807
808 let fresh = dir.path().join("fresh");
809 write_atomic(&fresh, b"x").unwrap();
810 assert_eq!(mode_of(&fresh), 0o600);
811 }
812
813 #[test]
814 fn new_only_creates_an_absent_target_and_leaves_no_temporary_file() {
815 let dir = tempfile::tempdir().unwrap();
816 let path = dir.path().join("fresh.json");
817 AtomicWrite::new(b"created")
818 .new_only()
819 .write(&path)
820 .unwrap();
821 assert_eq!(fs::read(&path).unwrap(), b"created");
822 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
823 }
824
825 #[test]
826 fn public_new_only_refuses_an_existing_target_byte_identical() {
827 let dir = tempfile::tempdir().unwrap();
828 let path = dir.path().join("keep.json");
829 fs::write(&path, b"original").unwrap();
830 let error = AtomicWrite::new(b"other")
831 .new_only()
832 .write(&path)
833 .unwrap_err();
834 assert!(error.target_exists());
835 assert!(!error.commit_uncertain());
836 assert_eq!(fs::read(&path).unwrap(), b"original");
837 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
838 }
839}