about summary refs log tree commit diff
path: root/splorm/src/fs/mod.rs
blob: ada2c01b6d99f68bd5075e43568cd9bac3da1273 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//! Filesystem functions and structures
//!
//! Code related to safe handling of paths form requests and reading data
//! from the filesystem.
//!
//! In order to get a safe path, that the top-level functions in this module
//! want, call [`RequestPath::verify_safe()`]

mod request_path;

use camino::Utf8PathBuf;
pub use request_path::{Mime, Mimetype, RequestPath, SafePath, SafePathBuf};
use tokio::fs::File;

use crate::RuntimeError;

pub async fn open_file<'p>(path: SafePath<'p>) -> Result<File, RuntimeError> {
	File::open(*path)
		.await
		.map_err(|err| RuntimeError::file_error(err, path.to_path_buf()))
}

pub async fn read_file<'p>(path: SafePath<'p>) -> Result<Vec<u8>, RuntimeError> {
	let system_path = *path;
	unsafe_read_file(system_path.to_owned()).await
}

pub async fn unsafe_read_file(path: Utf8PathBuf) -> Result<Vec<u8>, RuntimeError> {
	match tokio::fs::read(&path).await {
		Err(err) => Err(RuntimeError::file_error(err, path)),
		Ok(vec) => Ok(vec),
	}
}

pub async fn read_file_to_string<'p>(path: SafePath<'p>) -> Result<String, RuntimeError> {
	let system_path = *path;
	unsafe_read_file_to_string(system_path.to_path_buf()).await
}

pub async fn unsafe_read_file_to_string(path: Utf8PathBuf) -> Result<String, RuntimeError> {
	match tokio::fs::read_to_string(&path).await {
		Err(err) => Err(RuntimeError::file_error(err, path)),
		Ok(str) => Ok(str),
	}
}