pathfinder/resources/src/fs.rs

63 lines
2.0 KiB
Rust
Raw Normal View History

// pathfinder/resources/src/fs.rs
2019-03-08 19:52:47 -05:00
//
// Copyright © 2020 The Pathfinder Project Developers.
2019-03-08 19:52:47 -05:00
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Reads resources from the filesystem.
2019-03-08 19:52:47 -05:00
use crate::ResourceLoader;
2019-03-08 19:52:47 -05:00
use std::env;
use std::fs::File;
use std::io::{Error as IOError, Read};
use std::path::PathBuf;
pub struct FilesystemResourceLoader {
pub directory: PathBuf,
}
impl FilesystemResourceLoader {
pub fn locate() -> FilesystemResourceLoader {
2019-03-08 19:52:47 -05:00
let mut parent_directory = env::current_dir().unwrap();
loop {
// So ugly :(
let mut resources_directory = parent_directory.clone();
resources_directory.push("resources");
if resources_directory.is_dir() {
let mut shaders_directory = resources_directory.clone();
let mut textures_directory = resources_directory.clone();
shaders_directory.push("shaders");
textures_directory.push("textures");
if shaders_directory.is_dir() && textures_directory.is_dir() {
2019-04-29 19:57:56 -04:00
return FilesystemResourceLoader {
directory: resources_directory,
};
2019-03-08 19:52:47 -05:00
}
}
if !parent_directory.pop() {
break;
}
}
panic!("No suitable `resources/` directory found!");
}
}
impl ResourceLoader for FilesystemResourceLoader {
fn slurp(&self, virtual_path: &str) -> Result<Vec<u8>, IOError> {
let mut path = self.directory.clone();
2019-04-29 19:57:56 -04:00
virtual_path
.split('/')
.for_each(|segment| path.push(segment));
2019-03-08 19:52:47 -05:00
let mut data = vec![];
File::open(&path)?.read_to_end(&mut data)?;
Ok(data)
}
}