beet_utils/path_utils/
read_file.rs

1use super::FsError;
2use super::FsResult;
3use std::fs;
4use std::hash::DefaultHasher;
5use std::hash::Hash;
6use std::hash::Hasher;
7use std::path::Path;
8
9
10/// A nicer read file that actually outputs the missing path
11pub struct ReadFile;
12
13impl ReadFile {
14	pub fn to_string(path: impl AsRef<Path>) -> FsResult<String> {
15		std::fs::read_to_string(&path).map_err(|e| FsError::io(path, e))
16	}
17	pub fn to_bytes(path: impl AsRef<Path>) -> FsResult<Vec<u8>> {
18		std::fs::read(&path).map_err(|e| FsError::io(path, e))
19	}
20
21
22	pub fn hash_file(path: impl AsRef<Path>) -> FsResult<u64> {
23		let bytes = Self::to_bytes(path)?;
24		let hash = Self::hash_bytes(&bytes);
25		Ok(hash)
26	}
27
28	pub fn hash_bytes(bytes: &[u8]) -> u64 {
29		let mut hasher = DefaultHasher::new();
30		bytes.hash(&mut hasher);
31		hasher.finish()
32	}
33	pub fn hash_string(str: &str) -> u64 {
34		let bytes = str.as_bytes();
35		Self::hash_bytes(bytes)
36	}
37
38	pub fn exists(path: impl AsRef<Path>) -> bool {
39		match fs::exists(path) {
40			Ok(true) => true,
41			_ => false,
42		}
43	}
44}
45
46
47#[cfg(test)]
48#[cfg(not(target_arch = "wasm32"))]
49mod test {
50	use crate::prelude::*;
51
52	#[test]
53	fn to_string() {
54		let content =
55			ReadFile::to_string(FsExt::test_dir().join("mod.rs")).unwrap();
56		assert!(content.contains("pub mod included_dir;"));
57
58		assert!(ReadFile::to_string(FsExt::test_dir().join("foo.rs")).is_err());
59	}
60
61	#[test]
62	fn to_bytes() {
63		let bytes =
64			ReadFile::to_bytes(FsExt::test_dir().join("mod.rs")).unwrap();
65		assert!(bytes.len() > 10);
66
67		assert!(ReadFile::to_bytes(FsExt::test_dir().join("foo.rs")).is_err());
68	}
69
70	#[test]
71	fn hash() {
72		let hash1 =
73			ReadFile::hash_file(FsExt::test_dir().join("mod.rs")).unwrap();
74		let hash2 =
75			ReadFile::hash_file(FsExt::test_dir().join("included_file.rs"))
76				.unwrap();
77		assert_ne!(hash1, hash2);
78
79		let str =
80			ReadFile::to_string(FsExt::test_dir().join("mod.rs")).unwrap();
81		let hash3 = ReadFile::hash_string(&str);
82		assert_eq!(hash3, hash1);
83	}
84}