file_io/
load.rs

1use std::path::Path;
2
3/// Loads the content of a file as a string.
4///
5/// # Arguments
6///
7/// * `path` - The path to the file to load (can be a `&str`, [`String`], [`Path`], or
8///   [`std::path::PathBuf`]).
9///
10/// # Returns
11///
12/// The contents of the file as a string.
13///
14/// # Panics
15///
16/// If the file cannot be read.
17///
18/// # Examples
19///
20/// ## Using a string literal
21///
22/// ```
23/// use file_io::{load_file_as_string, save_string_to_file};
24///
25/// // Define the content and the path.
26/// let content: &str = "Hello, world!";
27/// let path: &str = "folder/subfolder_6/file_3.txt";
28///
29/// // First, save the content to the file.
30/// save_string_to_file(content, path);
31///
32/// // Now, load the content back from the file.
33/// let loaded_content = load_file_as_string(path);
34///
35/// // Verify that the loaded content matches the original content.
36/// assert_eq!(loaded_content, content);
37/// ```
38///
39/// ## Using a `Path` reference
40///
41/// ```
42/// use file_io::{load_file_as_string, save_string_to_file};
43/// use std::path::Path;
44///
45/// // Define the content and the path.
46/// let content: &str = "Hello, world!";
47/// let path: &Path = Path::new("folder/subfolder_7/file_4.txt");
48///
49/// // First, save the content to the file.
50/// save_string_to_file(content, path);
51///
52/// // Now, load the content back from the file.
53/// let loaded_content = load_file_as_string(path);
54///
55/// // Verify that the loaded content matches the original content.
56/// assert_eq!(loaded_content, content);
57/// ```
58pub fn load_file_as_string<P: AsRef<Path>>(path: P) -> String {
59    let path = path.as_ref();
60    std::fs::read_to_string(path).unwrap_or_else(|_| panic!("Failed to read file at '{path:?}'."))
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use crate::save::save_string_to_file;
67    use crate::test_utils::get_temp_dir_path;
68    use tempfile::tempdir;
69
70    #[test]
71    fn test_save_load_file_string() {
72        // Create a temporary directory.
73        let temp_dir = tempdir().unwrap();
74
75        // Get the path to the temporary directory.
76        let temp_dir_path = get_temp_dir_path(&temp_dir);
77
78        // Path to the file.
79        let file_path = temp_dir_path.join("test_file.txt");
80
81        // File path in different formats.
82        let file_paths: Vec<Box<dyn AsRef<Path>>> = vec![
83            Box::new(file_path.to_str().unwrap()),             // &str
84            Box::new(file_path.to_str().unwrap().to_string()), // String
85            Box::new(file_path.as_path()),                     // Path
86            Box::new(file_path.clone()),                       // PathBuf
87        ];
88
89        // Test with all different path formats.
90        for file_path in file_paths {
91            // Get a reference to this path representation (i.e. "unbox").
92            let file_path = file_path.as_ref();
93
94            // Content to save in the file.
95            let content = "Hello, world!";
96
97            // Save the content to the file.
98            save_string_to_file(content, file_path);
99
100            // Load the content from the file.
101            let loaded_content = load_file_as_string(file_path);
102
103            // Verify that the loaded content matches the original content.
104            assert_eq!(loaded_content, content);
105        }
106    }
107}