Cotton code
51 lines · 2.7 KB · RustRaw
//! A small file a phone keeps beside its copy (the view stood on, the player, a look, a journal), replaced whole://! written beside under a name no other write shares, then renamed over. A shared temporary name raced: two writes at//! once (the shell's refresh and its home after a sign-out, launch-story walk, 22 Nov 2026) both wrote `fan.json.new`,//! the first rename took it, the second found it gone, and the person read "That didn't work. Try again.".use std::path::Path;use std::sync::atomic::{AtomicU64, Ordering};static NEXT: AtomicU64 = AtomicU64::new(0);/// Replace `path` with `bytes`, making its folder if need be. A reader sees the old file or the new one, never a/// part; two writes at once both land, the later rename standing.pub fn replace(path: &Path, bytes: &[u8]) -> std::io::Result<()> {    let parent = path.parent().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "the file has no folder"))?;    std::fs::create_dir_all(parent)?;    let name = path.file_name().and_then(|name| name.to_str()).unwrap_or("file");    let fresh = parent.join(format!(".{name}.{}.{}.new", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));    // not a copy: a small file replaced whole beside a copy, never the copy.    let written = std::fs::write(&fresh, bytes).and_then(|_| std::fs::rename(&fresh, path));    if written.is_err() {        // not a copy: a small file replaced whole beside a copy, never the copy.        let _ = std::fs::remove_file(&fresh);    }    written}#[cfg(test)]mod tests {    use super::*;    /// RULE: writes of one file at once all land, and the file is always one whole write.    #[test]    fn writes_at_once_all_land_and_the_file_stays_whole() {        let dir = tempfile::tempdir().unwrap();        let path = dir.path().join("kept").join("fan.json");        std::thread::scope(|scope| {            let writers: Vec<_> = (0..8)                .map(|n| {                    let path = &path;                    scope.spawn(move || (0..40).filter(|i| replace(path, format!("{{\"n\":{n},\"i\":{i}}}").as_bytes()).is_err()).count())                })                .collect();            let failed: usize = writers.into_iter().map(|writer| writer.join().unwrap()).sum();            assert_eq!(failed, 0, "every write lands");        });        let whole: serde_json::Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).expect("one whole write");        assert!(whole["n"].is_u64());        let left: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().map(|entry| entry.unwrap().file_name()).collect();        assert_eq!(left.len(), 1, "no temporary file is left behind: {left:?}");    }}