1pub mod native {
2 use std::{
3 fs,
4 path::{Path, PathBuf},
5 };
6
7 use crate::error::{PlatformError, Result};
8
9 pub fn read_to_string(file_path: &str) -> Result<String> {
10 fs::read_to_string(file_path)
11 .map_err(|e| PlatformError::GeneralError(format!("Failed to read the file '{file_path}' with error: {e}")))
12 }
13
14 pub fn read_file(file_path: &str) -> Result<Box<[u8]>> {
15 match fs::read(file_path) {
16 Ok(buf) => Ok(Box::from(buf)),
17 Err(e) => Err(PlatformError::GeneralError(format!(
18 "Failed to read the file '{file_path}' with error: {e}"
19 ))),
20 }
21 }
22
23 pub fn join(components: &[&str]) -> Result<String> {
24 let mut path = PathBuf::new();
25
26 for component in components.iter() {
27 path.push(component);
28 }
29
30 match path.to_str().map(|p| p.to_owned()) {
31 Some(p) => Ok(p),
32 None => Err(PlatformError::GeneralError("Failed to stringify path".into())),
33 }
34 }
35
36 pub fn remove_dir_all(path: &std::path::Path) -> Result<()> {
37 fs::remove_dir_all(path).map_err(|e| PlatformError::GeneralError(e.to_string()))
38 }
39
40 pub fn write<R>(path: &str, contents: R) -> Result<()>
41 where
42 R: AsRef<[u8]>,
43 {
44 if let Some(parent_dir_path) = Path::new(path).parent() {
45 if !parent_dir_path.is_dir() {
46 fs::create_dir_all(parent_dir_path)
47 .map_err(|e| PlatformError::GeneralError(format!("Failed to create dir '{path}': {e}")))?
48 }
49 }
50 fs::write(path, contents)
51 .map_err(|e| PlatformError::GeneralError(format!("Failed to write to file '{path}': {e}")))
52 }
53
54 pub fn metadata(path: &str) -> Result<()> {
55 match fs::metadata(path) {
56 Ok(_) => Ok(()), Err(e) => Err(PlatformError::GeneralError(e.to_string())),
58 }
59 }
60}