logicaffeine_system/file.rs
1//! Simple File I/O Operations
2//!
3//! Provides synchronous file read/write operations for simple use cases.
4//! For async operations or more advanced file handling, use the [`fs`](crate::fs)
5//! module with the [`Vfs`](crate::fs::Vfs) trait.
6//!
7//! # Features
8//!
9//! Requires the `persistence` feature.
10//!
11//! # Platform Support
12//!
13//! - **Native**: Full support via `std::fs`
14//! - **WASM**: Not available (use OPFS via the `fs` module instead)
15//!
16//! # Example
17//!
18//! ```no_run
19//! use logicaffeine_system::file;
20//!
21//! # fn main() -> Result<(), String> {
22//! // Write a file
23//! file::write("data.txt".to_string(), "Hello, World!".to_string())?;
24//!
25//! // Read it back
26//! let content = file::read("data.txt".to_string())?;
27//! assert_eq!(content, "Hello, World!");
28//! # Ok(())
29//! # }
30//! ```
31
32use std::fs;
33
34/// Reads a file as a UTF-8 string.
35///
36/// # Arguments
37///
38/// * `path` - Path to the file (relative or absolute)
39///
40/// # Returns
41///
42/// The file contents as a string, or an error message describing the failure.
43///
44/// # Errors
45///
46/// Returns an error if:
47/// - The file doesn't exist
48/// - The file can't be read (permissions, I/O error)
49/// - The file contents aren't valid UTF-8
50///
51/// # Example
52///
53/// ```no_run
54/// use logicaffeine_system::file;
55///
56/// match file::read("config.json".to_string()) {
57/// Ok(content) => println!("Config: {}", content),
58/// Err(e) => eprintln!("Error: {}", e),
59/// }
60/// ```
61pub fn read(path: String) -> Result<String, String> {
62 if let Some(sealed) = crate::testworld::intercept_read(&path) {
63 return sealed;
64 }
65 fs::read_to_string(&path).map_err(|e| format!("Failed to read '{}': {}", path, e))
66}
67
68/// Reads a file's raw bytes. The total counterpart of the trapping `readBytes` builtin.
69///
70/// ★ ONE IMPLEMENTATION AND ONE MESSAGE, so the tiers cannot drift. The interpreter and the
71/// AOT-Rust lowering both call THIS — the alternative was two `std::fs::read` calls with two
72/// hand-written format strings, which is how an error message comes to differ between the tier
73/// an author tests on and the tier they ship.
74pub fn read_bytes(path: String) -> Result<Vec<u8>, String> {
75 fs::read(&path).map_err(|e| format!("cannot read '{}': {}", path, e))
76}
77
78/// Reads a file of little-endian IEEE-754 binary64 values, eight bytes a value in order: the numbers a program reads
79/// at run time rather than carries as code (`readReals`; a model's weights). The interpreter and the AOT-Rust lowering
80/// both call this, so the read and its refusals are one. A file that is not a whole number of values is refused.
81pub fn read_reals(path: String) -> Result<Vec<f64>, String> {
82 let bytes = fs::read(&path).map_err(|e| format!("readReals: cannot read '{}': {}", path, e))?;
83 if bytes.len() % 8 != 0 {
84 return Err(format!("readReals: '{}' holds {} bytes, not a whole number of 8-byte Reals", path, bytes.len()));
85 }
86 Ok(bytes.chunks_exact(8).map(|b| f64::from_le_bytes(b.try_into().expect("an 8-byte chunk"))).collect())
87}
88
89/// Writes a string to a file.
90///
91/// Creates the file if it doesn't exist, truncates it if it does.
92/// Parent directories must already exist.
93///
94/// # Arguments
95///
96/// * `path` - Path to the file (relative or absolute)
97/// * `content` - Content to write
98///
99/// # Errors
100///
101/// Returns an error if:
102/// - Parent directory doesn't exist
103/// - File can't be created or written (permissions, I/O error)
104///
105/// # Example
106///
107/// ```no_run
108/// use logicaffeine_system::file;
109///
110/// # fn main() -> Result<(), String> {
111/// file::write("output.txt".to_string(), "Result: 42".to_string())?;
112/// # Ok(())
113/// # }
114/// ```
115pub fn write(path: String, content: String) -> Result<(), String> {
116 if let Some(sealed) = crate::testworld::intercept_write(&path, &content) {
117 return sealed;
118 }
119 fs::write(&path, &content).map_err(|e| format!("Failed to write '{}': {}", path, e))
120}