openbim_ifcx/layers/
memory.rs

1use std::collections::HashMap;
2use std::convert::Infallible;
3
4use super::LayerResolver;
5use crate::json::WriteError;
6use crate::model::IfcxFile;
7
8/// Serves layers held in memory, keyed by the exact import `uri`, like
9/// upstream's `InMemoryLayerProvider`.
10#[derive(Debug, Clone, Default)]
11pub struct MemoryResolver {
12    layers: HashMap<String, Vec<u8>>,
13}
14
15impl MemoryResolver {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Serves `bytes` for `uri`, replacing and returning any earlier entry.
21    pub fn insert(&mut self, uri: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Option<Vec<u8>> {
22        self.layers.insert(uri.into(), bytes.into())
23    }
24
25    /// Serves `file` under its `header.id`, as upstream's in-memory provider
26    /// does. An `integrity` check on such a layer hashes the JSON this crate
27    /// writes, not any original bytes.
28    pub fn insert_file(&mut self, file: &IfcxFile) -> Result<Option<Vec<u8>>, WriteError> {
29        Ok(self.insert(file.header.id.clone(), file.to_json_string()?))
30    }
31}
32
33impl LayerResolver for MemoryResolver {
34    type Error = Infallible;
35
36    fn load(&mut self, key: &str) -> Result<Option<Vec<u8>>, Self::Error> {
37        Ok(self.layers.get(key).cloned())
38    }
39}