hyperlit_model/
file_source.rs1use hyperlit_base::err;
2use hyperlit_base::result::HyperlitResult;
3use hyperlit_base::shared_string::SharedString;
4use std::path::Path;
5
6pub trait FileSource {
7 fn filepath(&self) -> HyperlitResult<SharedString>;
8 fn open(&self) -> HyperlitResult<Box<dyn std::io::Read>>;
9}
10
11impl<T: AsRef<Path>> FileSource for T {
12 fn filepath(&self) -> HyperlitResult<SharedString> {
13 Ok(self
14 .as_ref()
15 .to_str()
16 .ok_or_else(|| err!("Invalid filepath"))?
17 .to_string()
18 .into())
19 }
20 fn open(&self) -> HyperlitResult<Box<dyn std::io::Read>> {
21 Ok(Box::new(std::fs::File::open(self)?))
22 }
23}
24
25pub struct InMemoryFileSource {
26 pub data: SharedString,
27 pub filepath: SharedString,
28}
29
30impl InMemoryFileSource {
31 pub fn new<P: Into<SharedString>, T: Into<SharedString>>(filepath: P, data: T) -> Self {
32 Self {
33 data: data.into(),
34 filepath: filepath.into(),
35 }
36 }
37}
38
39impl FileSource for InMemoryFileSource {
40 fn filepath(&self) -> HyperlitResult<SharedString> {
41 Ok(self.filepath.clone())
42 }
43
44 fn open(&self) -> HyperlitResult<Box<dyn std::io::Read>> {
45 Ok(Box::new(std::io::Cursor::new(self.data.clone())))
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use crate::file_source::{FileSource, InMemoryFileSource};
52 use std::io::Read;
53 use std::path::PathBuf;
54
55 #[test]
56 fn test_in_memory() {
57 let source = InMemoryFileSource::new("foo", "bar");
58 assert_eq!(source.filepath().unwrap(), "foo");
59 let mut content = String::new();
60 source.open().unwrap().read_to_string(&mut content).unwrap();
61 assert_eq!(content, "bar");
62 }
63
64 #[test]
65 fn test_file_path() {
66 let source = PathBuf::from("test/file_source_sample.txt");
67 let mut content = String::new();
68 source.open().unwrap().read_to_string(&mut content).unwrap();
69 assert_eq!(content, "asdf");
70 }
71}