### Complete FileTime Usage Example Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/file-time-functions.md Demonstrates reading metadata, updating file timestamps, modifying via file handles, and handling symbolic links. ```rust use filetime::FileTime; use std::fs; fn main() -> std::io::Result<()> { // Read timestamps from one file let source_meta = fs::metadata("source.txt")?; let mtime = FileTime::from_last_modification_time(&source_meta); let atime = FileTime::from_last_access_time(&source_meta); // Apply to another file filetime::set_file_times("destination.txt", atime, mtime)?; // Modify only mtime filetime::set_file_mtime("destination.txt", FileTime::now())?; // Modify via file handle let file = fs::File::open("destination.txt")?; filetime::set_file_handle_times(&file, Some(FileTime::now()), None)?; // Handle symlinks properly filetime::set_symlink_file_times("link.txt", FileTime::from_unix_time(1000, 0), FileTime::from_unix_time(2000, 0) )?; Ok(()) } ``` -------------------------------- ### Set Symlink File Times Usage Example Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/file-time-functions.md Demonstrates creating a symlink and updating its timestamps independently of the target file. ```rust use filetime::FileTime; use std::fs; use std::os::unix::fs::symlink; // Create a file and a symlink to it fs::File::create("target.txt")?; symlink("target.txt", "link.txt")?; let new_time = FileTime::from_unix_time(10_000, 0); // This modifies the symlink's times, not the target's filetime::set_symlink_file_times("link.txt", new_time, new_time)?; // Verify: the target is unchanged let target_meta = fs::metadata("target.txt")?; let target_time = FileTime::from_last_modification_time(&target_meta); let link_meta = fs::symlink_metadata("link.txt")?; let link_time = FileTime::from_last_modification_time(&link_meta); println!("Target time: {:?}", target_time); println!("Link time: {:?}", link_time); ``` -------------------------------- ### Create and use FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Demonstrates creating FileTime instances from various sources and performing comparisons or conversions. ```rust use filetime::FileTime; use std::fs; use std::time::SystemTime; // From file metadata let meta = fs::metadata("file.txt")?; let mtime = FileTime::from_last_modification_time(&meta); let atime = FileTime::from_last_access_time(&meta); let ctime = FileTime::from_creation_time(&meta); // Option on Unix, Some on Windows // From Unix epoch time let time1 = FileTime::from_unix_time(1609459200, 0); // From SystemTime let sys_time = SystemTime::now(); let time2 = FileTime::from_system_time(sys_time); // Current time let time3 = FileTime::now(); // Comparison and ordering if mtime > atime { println!("File was modified after it was accessed"); } // Convert to SystemTime let sys_time: SystemTime = mtime.into(); // Extract components let unix_seconds = mtime.unix_seconds(); let nanos = mtime.nanoseconds(); let platform_seconds = mtime.seconds(); // May differ from unix_seconds on Windows ``` -------------------------------- ### Build the project in release mode Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Standard command to compile the library with production optimizations. ```bash cargo build --release ``` -------------------------------- ### Emulate Second-Only Filesystems Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Configure the build to simulate filesystems with only second-level precision for testing purposes. ```bash RUSTFLAGS=--cfg emulate_second_only_system cargo build ``` -------------------------------- ### Configure emulate_second_only_system via config.toml Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Set the configuration flag permanently in the project's .cargo/config.toml file. ```toml [build] rustflags = ["--cfg", "emulate_second_only_system"] ``` -------------------------------- ### View File Manifest Structure Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/INDEX.md Displays the directory structure and file sizes of the documentation project. ```text output/ ├── README.md (11 KB) - Main entry point and overview ├── INDEX.md (this file) - Documentation structure │ ├── api-reference/ │ ├── filetime-struct.md (10 KB) - FileTime type and all methods │ └── file-time-functions.md (9.4 KB) - File modification functions │ ├── errors.md (9.3 KB) - Error types and handling ├── types.md (8.4 KB) - Type reference and conversions ├── configuration.md (7.1 KB) - Build-time configuration ├── platform-implementations.md (14 KB) - Platform-specific details ├── module-structure.md (10 KB) - Module organization └── usage-patterns.md (14 KB) - Practical examples ``` -------------------------------- ### Initialize FileTime with Zero Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Shows how to use the FileTime::zero() constant constructor to create a FileTime instance with zeroed seconds and nanoseconds. ```rust use filetime::FileTime; const ZERO: FileTime = FileTime::zero(); ``` -------------------------------- ### Build and Test with Emulation Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Enable second-only filesystem precision emulation using RUSTFLAGS during build and test commands. ```bash # Build the library RUSTFLAGS=--cfg emulate_second_only_system cargo build # Run tests with emulation RUSTFLAGS=--cfg emulate_second_only_system cargo test # Create a binary that uses the emulation RUSTFLAGS=--cfg emulate_second_only_system cargo build --release ``` -------------------------------- ### Configure emulate_second_only_system via CLI Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Set the configuration flag using RUSTFLAGS during cargo commands. ```bash RUSTFLAGS=--cfg emulate_second_only_system cargo build RUSTFLAGS=--cfg emulate_second_only_system cargo test RUSTFLAGS=--cfg emulate_second_only_system cargo run ``` -------------------------------- ### Create from SystemTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Convert a standard library SystemTime into a FileTime instance. ```rust use filetime::FileTime; use std::time::{SystemTime, Duration, UNIX_EPOCH}; let sys_time = UNIX_EPOCH + Duration::from_secs(12345); let file_time = FileTime::from_system_time(sys_time); assert_eq!(12345, file_time.unix_seconds()); ``` -------------------------------- ### Build and test filetime in production Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Use standard Cargo commands for production builds and tests. The library automatically handles platform-specific timestamp precision. ```bash # Normal build - uses nanosecond precision where available cargo build --release # Normal tests cargo test --release ``` -------------------------------- ### Perform typical file time operations Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md Demonstrates reading metadata and setting modification times using standard library fs and filetime types. ```rust use filetime::FileTime; use std::fs; // Read times let meta = fs::metadata("file.txt")?; let mtime = FileTime::from_last_modification_time(&meta); // Set times filetime::set_file_mtime("file.txt", mtime)?; ``` -------------------------------- ### Convert SystemTime to FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Demonstrates converting a standard library SystemTime into a FileTime instance. ```rust use filetime::FileTime; use std::time::{SystemTime, Duration, UNIX_EPOCH}; let sys_time = UNIX_EPOCH + Duration::from_secs(100); let file_time: FileTime = sys_time.into(); ``` -------------------------------- ### Convert FileTime to SystemTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Demonstrates converting a FileTime instance into a standard library SystemTime. ```rust use filetime::FileTime; use std::time::SystemTime; let file_time = FileTime::from_unix_time(1000, 0); let sys_time: SystemTime = file_time.into(); ``` -------------------------------- ### Crate dependency and platform implementation map Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md A structural representation of the crate's internal function call hierarchy and the organization of platform-specific implementation files. ```text lib.rs (crate root) ├── FileTime struct ├── set_file_times() → imp::open() → File::set_times() ├── set_file_handle_times() → File::set_times() ├── set_symlink_file_times() → imp::set_symlink_file_times() ├── set_file_mtime() → imp::open() → File::set_times() ├── set_file_atime() → imp::open() → File::set_times() ├── FileTime::from_system_time() → internal conversion ├── FileTime::from_unix_time() → internal conversion ├── FileTime::from_last_modification_time() → imp::from_last_modification_time() ├── FileTime::from_last_access_time() → imp::from_last_access_time() └── FileTime::from_creation_time() → imp::from_creation_time() Platform Implementations: ├── windows.rs │ ├── open() │ ├── set_symlink_file_times() │ ├── from_last_modification_time() │ ├── from_last_access_time() │ ├── from_creation_time() │ └── from_intervals() [internal] ├── unix/mod.rs [common] │ ├── to_timespec() [internal] │ └── open() ├── unix/linux.rs │ ├── set_symlink_file_times() │ ├── set_times() [internal] │ └── Uses: utimensat or utimes module ├── unix/macos.rs │ ├── set_symlink_file_times() │ ├── set_times() [internal] │ ├── utimensat() [internal] │ ├── fetch() [internal] │ └── Uses: utimes module as fallback ├── unix/android.rs │ ├── set_symlink_file_times() │ └── set_times() [internal] ├── unix/utimensat.rs │ ├── set_symlink_file_times() │ └── set_times() [internal] ├── unix/utimes.rs │ ├── set_symlink_file_times() │ ├── set_times() [internal] │ ├── get_times() [internal] │ └── to_timeval() [internal] ├── redox.rs │ ├── set_symlink_file_times() │ ├── from_last_modification_time() │ ├── from_last_access_time() │ ├── from_creation_time() │ └── open() └── wasm.rs ├── set_symlink_file_times() [error] ├── from_last_modification_time() [unimplemented] ├── from_last_access_time() [unimplemented] ├── from_creation_time() [unimplemented] └── open() ``` -------------------------------- ### Create from Unix epoch Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Construct a FileTime instance using seconds and nanoseconds relative to the Unix epoch. ```rust use filetime::FileTime; // Create a time 10 seconds after Unix epoch let time = FileTime::from_unix_time(10, 100_000_000); assert_eq!(10, time.unix_seconds()); assert_eq!(100_000_000, time.nanoseconds()); ``` -------------------------------- ### Perform Round-Trip Conversion in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/usage-patterns.md Shows the conversion process from SystemTime to FileTime and back to SystemTime, verifying data integrity. ```rust use filetime::FileTime; use std::time::SystemTime; fn roundtrip_conversion() { let original = SystemTime::now(); let file_time = FileTime::from_system_time(original); let recovered: SystemTime = file_time.into(); // recovered should equal original (or be very close) println!("Original: {:?}", original); println!("Recovered: {:?}", recovered); } ``` -------------------------------- ### Use minimal imports Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md Shows a concise way to set file modification time using only the FileTime type. ```rust use filetime::FileTime; let time = FileTime::now(); filetime::set_file_mtime("file.txt", time)?; ``` -------------------------------- ### Use filetime with various path types Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Demonstrates passing different path-like types to filetime functions. ```rust use filetime::FileTime;\nuse std::path::Path;\n\nlet time = FileTime::now();\n\n// String slice\nfiletime::set_file_mtime("file.txt", time)?;\n\n// String\nlet path = String::from("file.txt");\nfiletime::set_file_mtime(&path, time)?;\n\n// Path\nlet path = Path::new("file.txt");\nfiletime::set_file_mtime(path, time)?;\n\n// PathBuf\nlet path = std::path::PathBuf::from("file.txt");\nfiletime::set_file_mtime(path, time)?; ``` -------------------------------- ### Use FileTime::zero() for Comparisons Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Illustrates using FileTime::zero() as a base value when calculating the maximum of multiple FileTime instances. ```rust use filetime::FileTime; use std::cmp; let time1 = FileTime::from_unix_time(100, 0); let time2 = FileTime::from_unix_time(50, 0); let max = cmp::max(cmp::max(FileTime::zero(), time1), time2); ``` -------------------------------- ### Implementation of emulate_second_only_system Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Internal implementation logic for handling the emulation flag. ```rust const fn emulate_second_only_system(self) -> FileTime { if cfg!(emulate_second_only_system) { FileTime { seconds: self.seconds, nanos: 0, } } else { self } } ``` -------------------------------- ### Configure Linting for Unexpected CFGs Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Register the emulate_second_only_system attribute to prevent compiler warnings during build. ```toml [lints.rust.unexpected_cfgs] level = "warn" check-cfg = [ 'cfg(emulate_second_only_system)', ] ``` -------------------------------- ### Create from file metadata Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Extract the modification time from existing file metadata. ```rust use filetime::FileTime; use std::fs; let metadata = fs::metadata("foo.txt")?; let mtime = FileTime::from_last_modification_time(&metadata); println!("Last modified: {} seconds since epoch", mtime.unix_seconds()); ``` -------------------------------- ### Implement Platform Selection Logic Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Internal module selection logic that determines the appropriate platform implementation at compile time. ```rust cfg_if::cfg_if! { if #[cfg(target_os = "redox")] { #[path = "redox.rs"] mod imp; } else if #[cfg(windows)] { #[path = "windows.rs"] mod imp; } else if #[cfg(all(target_family = "wasm", not(target_os = "emscripten")))] { #[path = "wasm.rs"] mod imp; } else { #[path = "unix/mod.rs"] mod imp; } } ``` -------------------------------- ### WebAssembly FileTime Implementation Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Provides a stub implementation for WebAssembly where most file timestamp operations are unimplemented or return errors. ```rust pub fn set_symlink_file_times(_p: &Path, _atime: FileTime, _mtime: FileTime) -> io::Result<()> { Err(io::Error::new(io::ErrorKind::Other, "Wasm not implemented")) } pub fn from_last_modification_time(_meta: &fs::Metadata) -> FileTime { unimplemented!() } pub fn from_last_access_time(_meta: &fs::Metadata) -> FileTime { unimplemented!() } pub fn from_creation_time(_meta: &fs::Metadata) -> Option { unimplemented!() } pub fn open(path: &Path) -> io::Result { fs::File::open(path) } ``` -------------------------------- ### Create current system time Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Generate a FileTime instance representing the current system time. ```rust use filetime::FileTime; use std::fs; // Set a file's modification time to the current moment filetime::set_file_mtime("myfile.txt", FileTime::now())?; ``` -------------------------------- ### FileTime::now() Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Returns a FileTime representing the current system time. ```APIDOC ## FileTime::now() ### Description Returns a FileTime representing the current system time. Supported on all platforms. ### Signature `pub fn now() -> FileTime` ``` -------------------------------- ### Test with second-only precision Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Enables HFS emulation by rounding nanoseconds to zero during test execution. ```bash RUSTFLAGS=--cfg emulate_second_only_system cargo test ``` -------------------------------- ### Define Direct Dependencies Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Required dependencies for the library, including platform-specific requirements for Unix targets. ```toml [dependencies] cfg-if = "1.0.0" [target.'cfg(unix)'.dependencies] libc = "0.2.27" ``` -------------------------------- ### Common Unix Timestamp Helpers Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Standard functions for reading file metadata and opening files with read/write permission fallbacks. ```rust pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime { FileTime { seconds: meta.mtime(), nanos: meta.mtime_nsec() as u32, } } pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime { FileTime { seconds: meta.atime(), nanos: meta.atime_nsec() as u32, } } pub fn from_creation_time(meta: &fs::Metadata) -> Option { meta.created().map(|i| i.into()).ok() } pub fn open(path: &Path) -> io::Result { fs::File::open(path).or_else(|_| fs::OpenOptions::new().write(true).open(path)) } ``` -------------------------------- ### Conditional logic for emulate_second_only_system Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Demonstrates how the flag affects nanosecond precision in FileTime objects. ```rust use filetime::FileTime; let time = FileTime::from_unix_time(1000, 500_000_000); #[cfg(not(emulate_second_only_system))] assert_eq!(500_000_000, time.nanoseconds()); #[cfg(emulate_second_only_system)] assert_eq!(0, time.nanoseconds()); ``` -------------------------------- ### Import filetime crate Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Include the necessary modules to access file timestamp functionality. ```rust use filetime::FileTime; use std::fs; ``` -------------------------------- ### Add filetime dependency to Cargo.toml Source: https://github.com/alexcrichton/filetime/blob/main/README.md Include this dependency in your Cargo.toml file to use the filetime crate. ```toml # Cargo.toml [dependencies] filetime = "0.2" ``` -------------------------------- ### Retrieve creation time from metadata Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Extracts the creation time from file metadata. Returns None if the platform does not support or provide creation time information. ```rust use filetime::FileTime; use std::fs; let metadata = fs::metadata("foo.txt")?; if let Some(ctime) = FileTime::from_creation_time(&metadata) { println!("Created: {} seconds since epoch", ctime.unix_seconds()); } else { println!("Creation time not available on this platform"); } ``` -------------------------------- ### fn from_creation_time(meta: &fs::Metadata) -> Option Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Creates a new FileTime timestamp from the creation time listed in the specified metadata, if available. ```APIDOC ## fn from_creation_time(meta: &fs::Metadata) -> Option ### Description Creates a new timestamp from the creation time listed in the specified metadata. ### Parameters - **meta** (&fs::Metadata) - Required - Metadata obtained from fs::metadata() or File::metadata(). ### Returns - **Option** - Some(FileTime) if the creation time is available, None otherwise. ### Platform Notes - Unix: Corresponds to the birthtime field of stat. Not all Unix platforms have this field available; may return None in some circumstances. - Windows: Corresponds to the ftCreationTime field. Always available and returns Some. - Redox: Not supported, always returns None. ``` -------------------------------- ### Implement OS Error Handling in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Standard pattern for wrapping libc syscall results into Rust io::Error types. ```rust let rc = unsafe { libc::syscall(...) }; if rc == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } ``` -------------------------------- ### Display FileTime as a string Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Formats the FileTime instance as a string in the format {seconds}.{nanos:09}s. ```rust use filetime::FileTime; let time = FileTime::from_unix_time(1234, 567_890_123); println!("{}", time); // Output: 1234.567890123s ``` -------------------------------- ### Define Dev Dependencies Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Dependencies used exclusively for running tests. ```toml [dev-dependencies] tempfile = "3" ``` -------------------------------- ### Set file timestamps in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/file-time-functions.md Demonstrates copying access and modification times from a source file to a destination file using set_file_times. ```rust use filetime::FileTime; use std::fs; fn copy_file_times(src: &str, dst: &str) -> std::io::Result<()> { let meta = fs::metadata(src)?; let mtime = FileTime::from_last_modification_time(&meta); let atime = FileTime::from_last_access_time(&meta); filetime::set_file_times(dst, atime, mtime)?; Ok(()) } ``` -------------------------------- ### Compare FileTime ordering Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Performs relational comparisons between two FileTime instances. ```rust use filetime::FileTime; use std::cmp::Ordering; let time1 = FileTime::from_unix_time(100, 0); let time2 = FileTime::from_unix_time(200, 0); assert!(time1 < time2); assert_eq!(time1.cmp(&time2), Ordering::Less); ``` -------------------------------- ### Compare FileTime timestamps Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Shows how to compare two FileTime instances to determine which file modification time is more recent. ```rust use filetime::FileTime; use std::fs; let meta1 = fs::metadata("file1.txt")?; let meta2 = fs::metadata("file2.txt")?; let time1 = FileTime::from_last_modification_time(&meta1); let time2 = FileTime::from_last_modification_time(&meta2); if time1 > time2 { println!("file1 is newer"); } ``` -------------------------------- ### Access optional creation time Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Retrieves creation time which may return None on platforms where it is unsupported. ```rust use filetime::FileTime; use std::fs; let meta = fs::metadata("file.txt")?; // Returns Option because creation time is not available on all platforms if let Some(ctime) = FileTime::from_creation_time(&meta) { println!("File created: {}", ctime.unix_seconds()); } else { println!("Creation time not available"); } ``` -------------------------------- ### Display FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Formats the FileTime instance as a string with seconds and nanoseconds. ```rust use filetime::FileTime; let time = FileTime::from_unix_time(1234, 567_890_123); println!("{}", time); // Output: "1234.567890123s" ``` -------------------------------- ### Define Windows backup semantics flag Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Constant used to open files for metadata-only operations without requiring standard read/write permissions. ```rust const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x2000000; ``` -------------------------------- ### Retrieve Available File Time in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/usage-patterns.md Attempts to fetch creation time, falling back to modification time if unavailable. ```rust use filetime::FileTime; use std::fs; use std::io; fn get_any_available_time(path: &str) -> io::Result { let meta = fs::metadata(path)?; // Try creation time first if let Some(ctime) = FileTime::from_creation_time(&meta) { return Ok(ctime); } // Fall back to modification time Ok(FileTime::from_last_modification_time(&meta)) } fn main() -> io::Result<()> { let time = get_any_available_time("myfile.txt")?; println!("File time: {}", time.unix_seconds()); Ok(()) } ``` -------------------------------- ### Convert Windows intervals to FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Converts 100-nanosecond interval ticks into seconds and nanoseconds for internal representation. ```rust fn from_intervals(ticks: u64) -> FileTime { // Windows times are in 100ns intervals FileTime { seconds: (ticks / (1_000_000_000 / 100)) as i64, nanos: ((ticks % (1_000_000_000 / 100)) * 100) as u32, } } ``` -------------------------------- ### FileTime::from_unix_time(s, ns) Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Creates a FileTime from Unix epoch seconds and nanoseconds. ```APIDOC ## FileTime::from_unix_time(s, ns) ### Description Creates a FileTime from Unix epoch seconds and nanoseconds. Supported on all platforms. ### Signature `pub fn from_unix_time(s: i64, ns: u32) -> FileTime` ``` -------------------------------- ### Define crate metadata Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md Provides the package configuration for the filetime crate in Cargo.toml format. ```toml [package] name = "filetime" version = "0.2.29" edition = "2018" rust-version = "1.75.0" authors = ["Alex Crichton "] documentation = "https://docs.rs/filetime" ``` -------------------------------- ### Standard IO Result Aliases Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Demonstrates the equivalence between the standard io::Result type and the explicit Result<(), io::Error> type. ```rust use std::io; // These are equivalent: fn example1() -> io::Result<()> { ... } fn example2() -> Result<(), io::Error> { ... } ``` -------------------------------- ### Clone FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Demonstrates explicit cloning of the FileTime struct. ```rust use filetime::FileTime; let time1 = FileTime::from_unix_time(100, 0); let time2 = time1.clone(); // Explicit clone (rarely needed since Copy) ``` -------------------------------- ### Structure Unix Sub-Modules Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md Selects specific Unix-like implementation modules based on the target operating system. ```rust cfg_if::cfg_if! { if #[cfg(target_os = "linux")] { mod utimes; mod linux; pub use self::linux::*; } else if #[cfg(target_os = "android")] { mod android; pub use self::android::*; } else if #[cfg(target_os = "macos")] { mod utimes; mod macos; pub use self::macos::*; } else if #[cfg(any(target_os = "aix", target_os = "nto", ...))] { mod utimensat; pub use self::utimensat::*; } else { mod utimes; pub use self::utimes::*; } } ``` -------------------------------- ### Convert SystemTime to FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Perform conversion from standard library SystemTime to FileTime using the into trait. ```rust use filetime::FileTime;\nuse std::time::SystemTime;\n\nlet sys_time = SystemTime::now();\nlet file_time: FileTime = sys_time.into(); ``` -------------------------------- ### Convert FileTime to SystemTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Perform conversion from FileTime to standard library SystemTime using the into trait. ```rust use filetime::FileTime;\nuse std::time::SystemTime;\n\nlet file_time = FileTime::from_unix_time(1000, 0);\nlet sys_time: SystemTime = file_time.into(); ``` -------------------------------- ### Define set_file_times with AsRef Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Generic function signature for setting file times using any type that implements AsRef. ```rust pub fn set_file_times

(p: P, atime: FileTime, mtime: FileTime) -> io::Result<()>\nwhere\n P: AsRef, ``` -------------------------------- ### Compare FileTime equality Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Checks for equality between two FileTime instances. ```rust use filetime::FileTime; let time1 = FileTime::from_unix_time(100, 0); let time2 = FileTime::from_unix_time(100, 0); assert_eq!(time1, time2); ``` -------------------------------- ### Graceful Fallback on Timestamp Setting Failure Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/usage-patterns.md Demonstrates how to ignore specific errors like PermissionDenied while propagating others like NotFound. ```rust use filetime::FileTime; use std::io; fn try_set_times_with_fallback(path: &str, mtime: FileTime) -> io::Result<()> { match filetime::set_file_mtime(path, mtime) { Ok(()) => { println!("Successfully set modification time"); Ok(()) } Err(e) => match e.kind() { io::ErrorKind::NotFound => { eprintln!("File not found: {}", path); Err(e) } io::ErrorKind::PermissionDenied => { eprintln!("Permission denied. Skipping timestamp update for {}", path); Ok(()) // Continue despite the error } _ => { eprintln!("Unexpected error: {}", e); Err(e) } } } } ``` -------------------------------- ### macOS Dynamic Symbol Lookup Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Uses dlsym to detect utimensat availability at runtime, caching the result in an AtomicUsize. ```rust fn utimensat() -> Option c_int> { static ADDR: AtomicUsize = AtomicUsize::new(0); unsafe { fetch(&ADDR, CStr::from_bytes_with_nul_unchecked(b"utimensat\0")) .map(|sym| mem::transmute(sym)) } } fn fetch(cache: &AtomicUsize, name: &CStr) -> Option { match cache.load(SeqCst) { 0 => {} // Not checked yet 1 => return None, // Not found n => return Some(n), // Found } let sym = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) }; let (val, ret) = if sym.is_null() { (1, None) } else { (sym as usize, Some(sym as usize)) }; cache.store(val, SeqCst); return ret; } ``` -------------------------------- ### Unwrap filetime results Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Use unwrap to panic on error; recommended only for tests or when success is guaranteed. ```rust use filetime::FileTime; // Only use in tests or when you're certain the operation will succeed filetime::set_file_mtime("file.txt", FileTime::now()).unwrap(); ``` -------------------------------- ### Define Minimum Supported Rust Version Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/configuration.md Specify the minimum required Rust compiler version in the package manifest. ```toml [package] rust-version = "1.75.0" ``` -------------------------------- ### Test with Second-Only Precision in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/usage-patterns.md Configures test environments to emulate filesystems with limited timestamp precision. ```bash RUSTFLAGS=--cfg emulate_second_only_system cargo test ``` ```rust #[test] fn test_timestamp_precision() { use filetime::FileTime; let time = FileTime::from_unix_time(100, 500_000_000); #[cfg(emulate_second_only_system)] assert_eq!(0, time.nanoseconds()); #[cfg(not(emulate_second_only_system))] assert_eq!(500_000_000, time.nanoseconds()); } ``` -------------------------------- ### Create zero timestamp Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Initialize a FileTime instance representing zero time, useful for comparison operations. ```rust use filetime::FileTime; let zero_time = FileTime::zero(); let max_time = std::cmp::max(zero_time, other_time); ``` -------------------------------- ### Implement utimensat for file timestamps Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Uses the utimensat syscall to set file timestamps. Emscripten is explicitly handled to return an error for symlink operations. ```rust pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { set_times(p, Some(atime), Some(mtime), true) } fn set_times( p: &Path, atime: Option, mtime: Option, symlink: bool, ) -> io::Result<()> { let flags = if symlink { if cfg!(target_os = "emscripten") { return Err(io::Error::new( io::ErrorKind::Other, "emscripten does not support utimensat for symlinks", )); } libc::AT_SYMLINK_NOFOLLOW } else { 0 }; let p = CString::new(p.as_os_str().as_bytes())?; let times = [super::to_timespec(&atime), super::to_timespec(&mtime)]; let rc = unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) }; if rc == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } ``` -------------------------------- ### Define Platform Implementation Interface Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md The private imp module provides these platform-specific functions for file time manipulation. ```rust fn from_last_modification_time(meta: &fs::Metadata) -> FileTime fn from_last_access_time(meta: &fs::Metadata) -> FileTime fn from_creation_time(meta: &fs::Metadata) -> Option fn open(path: &Path) -> io::Result fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> ``` -------------------------------- ### Detailed Error Reporting Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/usage-patterns.md Wraps filetime operations to provide context-specific error messages based on the I/O error kind. ```rust use filetime::FileTime; use std::io; fn set_times_with_details(path: &str, atime: FileTime, mtime: FileTime) -> io::Result<()> { filetime::set_file_times(path, atime, mtime).map_err(|e| { let msg = match e.kind() { io::ErrorKind::NotFound => { format!("File not found: {}", path) } io::ErrorKind::PermissionDenied => { format!("Permission denied when modifying {}", path) } io::ErrorKind::InvalidInput => { format!("Invalid timestamp for system (before 1601 on Windows?)") } _ => { format!("OS error {}: {}", e.raw_os_error().unwrap_or(-1), e) } }; io::Error::new(e.kind(), msg) }) } ``` -------------------------------- ### Public API functions Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md Functions for setting file access and modification times on paths or file handles. ```rust pub fn set_file_times

(p: P, atime: FileTime, mtime: FileTime) -> io::Result<()>\nwhere\n P: AsRef\n\npub fn set_file_handle_times(\n f: &fs::File,\n atime: Option,\n mtime: Option,\n) -> io::Result<()>\n\npub fn set_symlink_file_times

(p: P, atime: FileTime, mtime: FileTime) -> io::Result<()>\nwhere\n P: AsRef\n\npub fn set_file_mtime

(p: P, mtime: FileTime) -> io::Result<()>\nwhere\n P: AsRef\n\npub fn set_file_atime

(p: P, atime: FileTime) -> io::Result<()>\nwhere\n P: AsRef ``` -------------------------------- ### Redox FileTime Implementation Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Handles file timestamp operations on Redox using custom syscall flags. Creation time is not supported. ```rust const O_NOFOLLOW: i32 = 0x20000; pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { let file = std::fs::OpenOptions::new() .read(true) .custom_flags(O_NOFOLLOW) .open(p)?; crate::set_file_handle_times(&file, Some(atime), Some(mtime)) } pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime { FileTime { seconds: meta.mtime(), nanos: meta.mtime_nsec() as u32, } } pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime { FileTime { seconds: meta.atime(), nanos: meta.atime_nsec() as u32, } } pub fn from_creation_time(_meta: &fs::Metadata) -> Option { None } pub fn open(path: &Path) -> io::Result { fs::File::open(path) } ``` -------------------------------- ### Retry with Second-Level Precision Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Fallback to second-level precision if nanosecond precision is unsupported by the target filesystem. ```rust use filetime::FileTime; let full_time = FileTime::from_unix_time(1000, 500_000_000); let result = filetime::set_file_mtime("file.txt", full_time); if result.is_err() { // Try with just seconds (no nanoseconds) let second_only = FileTime::from_unix_time(1000, 0); filetime::set_file_mtime("file.txt", second_only)?; } ``` -------------------------------- ### Update All Files in Directory Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Iterates through a directory and updates the modification time of every file to the current time. ```rust let now = FileTime::now(); for entry in fs::read_dir(".")? { let path = entry?.path(); if path.is_file() { let _ = filetime::set_file_mtime(&path, now); } } ``` -------------------------------- ### fn from_last_access_time(meta: &fs::Metadata) -> FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Creates a new FileTime timestamp from the last access time listed in the specified metadata. ```APIDOC ## fn from_last_access_time(meta: &fs::Metadata) -> FileTime ### Description Creates a new timestamp from the last access time listed in the specified metadata. ### Parameters - **meta** (&fs::Metadata) - Required - Metadata obtained from fs::metadata() or File::metadata(). ### Returns - **FileTime** - Represents the access time. ### Platform Notes - Unix: Corresponds to the atime field of stat. - Windows: Corresponds to the ftLastAccessTime field. ``` -------------------------------- ### Android utimensat Implementation Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Directly invokes the utimensat syscall for setting file times on Android. ```rust pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { set_times(p, Some(atime), Some(mtime), true) } fn set_times(...) { let flags = if symlink { libc::AT_SYMLINK_NOFOLLOW } else { 0 }; let p = CString::new(p.as_os_str().as_bytes())?; let times = [super::to_timespec(&atime), super::to_timespec(&mtime)]; let rc = unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) }; if rc == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } ``` -------------------------------- ### Compare File Modification Times Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Compares the modification times of two files to determine which is newer. ```rust let meta1 = fs::metadata("file1.txt")?; let meta2 = fs::metadata("file2.txt")?; let time1 = FileTime::from_last_modification_time(&meta1); let time2 = FileTime::from_last_modification_time(&meta2); if time1 > time2 { println!("file1 is newer"); } ``` -------------------------------- ### Define public platform interface Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md The standard interface required for all platform-specific implementations in the library. ```rust pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime; pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime; pub fn from_creation_time(meta: &fs::Metadata) -> Option; pub fn open(path: &Path) -> io::Result; pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()>; ``` -------------------------------- ### Implement FileTime Traits Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md Standard trait implementations for the FileTime struct, including display and conversion to/from SystemTime. ```rust impl Display for FileTime { ... } impl From for FileTime { ... } impl From for SystemTime { ... } ``` -------------------------------- ### seconds() Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/filetime-struct.md Returns the whole number of seconds represented by this timestamp, with platform-specific epoch bases. ```APIDOC ## const fn seconds(&self) -> i64 ### Description Returns the whole number of seconds represented by this timestamp. Note that the epoch base is platform-specific: Unix platforms use January 1, 1970, while Windows platforms use January 1, 1601. ### Returns - **i64** - Platform-specific seconds value ``` -------------------------------- ### Hash FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Enables the use of FileTime within collections like HashSet. ```rust use filetime::FileTime; use std::collections::HashSet; let mut times = HashSet::new(); let time = FileTime::from_unix_time(100, 0); times.insert(time); ``` -------------------------------- ### Platform-specific re-exports in the unix module Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/module-structure.md These re-exports consolidate platform-specific implementation functions into the unix module scope for internal crate usage. ```rust pub use self::linux::*; // Linux pub use self::android::*; // Android pub use self::macos::*; // macOS pub use self::utimensat::*; // FreeBSD, NetBSD, OpenBSD, etc. pub use self::utimes::*; // Generic fallback ``` -------------------------------- ### Linux Runtime Fallback Logic Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/platform-implementations.md Attempts utimensat and falls back to utimes if ENOSYS is encountered, caching the failure state. ```rust static INVALID: AtomicBool = AtomicBool::new(false); if !INVALID.load(SeqCst) { let rc = unsafe { libc::utimensat(...) }; if rc == 0 { return Ok(()); } let err = io::Error::last_os_error(); if err.raw_os_error() == Some(libc::ENOSYS) { INVALID.store(true, SeqCst); // Remember for next time } else { return Err(err); } } super::utimes::set_times(p, atime, mtime, symlink) ``` -------------------------------- ### Function signature for set_file_atime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Sets the access time for a file at a given path. ```rust pub fn set_file_atime

(p: P, atime: FileTime) -> io::Result<()> where P: AsRef, ``` -------------------------------- ### Function signature for set_file_handle_times Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Sets the access and modification times for an open file handle. ```rust pub fn set_file_handle_times( f: &fs::File, atime: Option, mtime: Option, ) -> io::Result<()> ``` -------------------------------- ### Copy timestamps between files Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/README.md Extract access and modification times from a source file and apply them to a destination file. ```rust let src_meta = fs::metadata("source.txt")?; let mtime = FileTime::from_last_modification_time(&src_meta); let atime = FileTime::from_last_access_time(&src_meta); filetime::set_file_times("dest.txt", atime, mtime)?; ``` -------------------------------- ### Copy File Contents and Timestamps in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/usage-patterns.md Performs a full file copy followed by an explicit application of the source file's timestamps to the new destination file. ```rust use filetime::FileTime; use std::fs; use std::io; use std::path::Path; fn copy_file_with_times>(src: P, dst: P) -> io::Result<()> { let src_path = src.as_ref(); let dst_path = dst.as_ref(); // Copy file contents fs::copy(src_path, dst_path)?; // Copy timestamps let meta = fs::metadata(src_path)?; let mtime = FileTime::from_last_modification_time(&meta); let atime = FileTime::from_last_access_time(&meta); filetime::set_file_times(dst_path, atime, mtime)?; Ok(()) } fn main() -> io::Result<()> { copy_file_with_times("original.txt", "backup.txt")?; println!("File copied with timestamps preserved"); Ok(()) } ``` -------------------------------- ### Function signature for set_symlink_file_times Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Sets the access and modification times for a symlink at a given path. ```rust pub fn set_symlink_file_times

(p: P, atime: FileTime, mtime: FileTime) -> io::Result<()> where P: AsRef, ``` -------------------------------- ### Copy FileTime Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/types.md Shows implicit copying of the FileTime struct, which is cheap to perform. ```rust use filetime::FileTime; let time1 = FileTime::from_unix_time(100, 0); let time2 = time1; // Implicit copy, not move ``` -------------------------------- ### Set file handle times in Rust Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/api-reference/file-time-functions.md Updates access and modification times for an existing file handle. Requires an open std::fs::File and FileTime instances. ```rust use filetime::FileTime; use std::fs::File; let file = File::open("myfile.txt")?; // Update only the modification time, leaving access time unchanged filetime::set_file_handle_times(&file, None, Some(FileTime::now()))?; // Update only the access time filetime::set_file_handle_times(&file, Some(FileTime::now()), None)?; // Update both filetime::set_file_handle_times( &file, Some(FileTime::from_unix_time(1000, 0)), Some(FileTime::from_unix_time(2000, 0)), )?; ``` -------------------------------- ### Perform Infallible FileTime Conversions Source: https://github.com/alexcrichton/filetime/blob/main/_autodocs/errors.md Demonstrates read-only operations for extracting time data from file metadata that do not return errors. ```rust use filetime::FileTime; use std::fs; use std::time::SystemTime; // These always succeed: let meta = fs::metadata("file.txt").unwrap(); let mtime = FileTime::from_last_modification_time(&meta); // Never fails let atime = FileTime::from_last_access_time(&meta); // Never fails if let Some(ctime) = FileTime::from_creation_time(&meta) // Returns Option, not Result { let unix_secs = ctime.unix_seconds(); // Never fails let nanos = ctime.nanoseconds(); // Never fails } let sys_time: SystemTime = mtime.into(); // Never fails ```