ocl_include/source/
mem.rs1use std::{
2 collections::hash_map::{Entry, HashMap},
3 io,
4 path::{Path, PathBuf},
5};
6
7use super::Source;
8
9#[derive(Default)]
11pub struct Mem {
12 files: HashMap<PathBuf, String>,
13}
14
15impl Mem {
16 pub fn new() -> Self {
17 Self::default()
18 }
19
20 pub fn builder() -> MemBuilder {
21 MemBuilder {
22 source: Self::new(),
23 }
24 }
25
26 pub fn add_file<P: AsRef<Path>>(&mut self, name: &P, data: String) -> io::Result<()> {
27 match self.files.entry(name.as_ref().to_path_buf()) {
28 Entry::Occupied(_) => Err(io::ErrorKind::AlreadyExists.into()),
29 Entry::Vacant(v) => {
30 v.insert(data);
31 Ok(())
32 }
33 }
34 }
35
36 fn read_file<P: AsRef<Path>>(&self, path: &P) -> Option<String> {
37 self.files.get(path.as_ref()).cloned()
38 }
39}
40
41pub struct MemBuilder {
42 source: Mem,
43}
44
45impl MemBuilder {
46 pub fn add_file<P: AsRef<Path>>(mut self, name: &P, data: String) -> io::Result<Self> {
47 self.source.add_file(name, data).map(|()| self)
48 }
49
50 pub fn build(self) -> Mem {
51 self.source
52 }
53}
54
55impl Source for Mem {
56 fn read(&self, path: &Path, dir: Option<&Path>) -> io::Result<(PathBuf, String)> {
57 dir.and_then(|dir| {
58 let path = dir.join(path);
59 self.read_file(&path).map(|data| (path, data))
60 })
61 .or_else(|| {
62 self.files
63 .get(path)
64 .map(|data| (path.to_path_buf(), data.clone()))
65 })
66 .ok_or_else(|| {
67 io::Error::new(
68 io::ErrorKind::NotFound,
69 format!("path: {:?}, dir: {:?}", path, dir),
70 )
71 })
72 }
73}