Skip to main content

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    fs::read_to_string(&path).map_err(|e| format!("Failed to read '{}': {}", path, e))
63}
64
65/// Writes a string to a file.
66///
67/// Creates the file if it doesn't exist, truncates it if it does.
68/// Parent directories must already exist.
69///
70/// # Arguments
71///
72/// * `path` - Path to the file (relative or absolute)
73/// * `content` - Content to write
74///
75/// # Errors
76///
77/// Returns an error if:
78/// - Parent directory doesn't exist
79/// - File can't be created or written (permissions, I/O error)
80///
81/// # Example
82///
83/// ```no_run
84/// use logicaffeine_system::file;
85///
86/// # fn main() -> Result<(), String> {
87/// file::write("output.txt".to_string(), "Result: 42".to_string())?;
88/// # Ok(())
89/// # }
90/// ```
91pub fn write(path: String, content: String) -> Result<(), String> {
92    fs::write(&path, &content).map_err(|e| format!("Failed to write '{}': {}", path, e))
93}