Skip to main content

burn_central_core/bundle/memory/
reader.rs

1use std::collections::BTreeMap;
2use std::io::Read;
3
4use crate::bundle::{BundleSource, normalize_bundle_path};
5
6/// In-memory reader for synthetic or cached bundles.
7pub struct InMemoryBundleReader {
8    files: BTreeMap<String, Vec<u8>>, // rel_path -> bytes
9}
10
11impl InMemoryBundleReader {
12    pub fn new(files: BTreeMap<String, Vec<u8>>) -> Self {
13        Self { files }
14    }
15
16    /// Get the files in this bundle
17    pub fn files(&self) -> &BTreeMap<String, Vec<u8>> {
18        &self.files
19    }
20
21    /// Check if a file exists in the bundle
22    pub fn contains_file(&self, path: &str) -> bool {
23        let normalized = normalize_bundle_path(path);
24        self.files.contains_key(&normalized)
25    }
26
27    /// Get the size of a file in the bundle
28    pub fn file_size(&self, path: &str) -> Option<usize> {
29        let normalized = normalize_bundle_path(path);
30        self.files.get(&normalized).map(|bytes| bytes.len())
31    }
32
33    /// Get all file paths in the bundle
34    pub fn file_paths(&self) -> Vec<String> {
35        self.files.keys().cloned().collect()
36    }
37}
38
39impl BundleSource for InMemoryBundleReader {
40    fn open(&self, path: &str) -> Result<Box<dyn Read + Send>, String> {
41        let rel = normalize_bundle_path(path);
42        let bytes = self
43            .files
44            .get(&rel)
45            .ok_or_else(|| format!("File not found in bundle: {}", rel))?;
46        Ok(Box::new(std::io::Cursor::new(bytes.clone())))
47    }
48
49    fn list(&self) -> Result<Vec<String>, String> {
50        Ok(self.files.keys().cloned().collect())
51    }
52}