physis/resource/
unpacked.rs

1// SPDX-FileCopyrightText: 2025 Joshua Goins <josh@redstrate.com>
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4use std::path::PathBuf;
5
6use crate::ByteBuffer;
7
8use super::Resource;
9
10/// Used to read unpacked files from a directory.
11pub struct UnpackedResource {
12    base_directory: String,
13}
14
15impl UnpackedResource {
16    pub fn from_existing(base_directory: &str) -> Self {
17        Self {
18            base_directory: base_directory.to_string(),
19        }
20    }
21}
22
23impl Resource for UnpackedResource {
24    fn read(&mut self, path: &str) -> Option<ByteBuffer> {
25        let mut new_path = PathBuf::from(&self.base_directory);
26        new_path.push(path.to_lowercase());
27
28        std::fs::read(new_path).ok()
29    }
30
31    fn exists(&mut self, path: &str) -> bool {
32        let mut new_path = PathBuf::from(&self.base_directory);
33        new_path.push(path.to_lowercase());
34
35        std::fs::exists(new_path).unwrap_or_default()
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    fn common_setup_data() -> UnpackedResource {
44        let mut d = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
45        d.push("resources/tests");
46
47        UnpackedResource::from_existing(d.to_str().unwrap())
48    }
49
50    #[test]
51    fn read_files() {
52        let mut data = common_setup_data();
53
54        assert!(data.read("empty_planlive.lgb").is_some());
55        assert!(data.read("non_existent.lgb").is_none());
56    }
57
58    #[test]
59    fn exist_files() {
60        let mut data = common_setup_data();
61
62        assert_eq!(data.exists("empty_planlive.lgb"), true);
63        assert_eq!(data.exists("non_existent.lgb"), false);
64    }
65}