Skip to main content

qualia_core_db/storage/
mmap.rs

1use crate::NQuin;
2#[cfg(not(target_arch = "wasm32"))]
3use memmap2::MmapMut;
4#[cfg(not(target_arch = "wasm32"))]
5use std::fs::OpenOptions;
6
7#[cfg(not(target_arch = "wasm32"))]
8pub struct MmapStore {
9    mmap: MmapMut,
10    capacity_quins: usize,
11    active_quins: usize,
12}
13
14#[cfg(not(target_arch = "wasm32"))]
15impl MmapStore {
16    // Opens or creates a file of exactly `capacity_quins * 48` bytes.
17    /// Opens.
18    pub fn open(path: &str, capacity_quins: usize) -> Result<Self, std::io::Error> {
19        let file = OpenOptions::new()
20            .read(true)
21            .write(true)
22            .create(true)
23            .open(path)?;
24
25        let required_len = (capacity_quins * 48) as u64;
26        file.set_len(required_len)?;
27
28        let mmap = unsafe { MmapMut::map_mut(&file)? };
29
30        Ok(Self {
31            mmap,
32            capacity_quins,
33            active_quins: 0,
34        })
35    }
36
37    // Appends a Quin. Returns error if capacity exceeded.
38    /// Appends `quin` to the store; `io::Error` on write failure (cfg-gated mmap/vec backends share the signature).
39    pub fn append(&mut self, quin: &NQuin) -> Result<(), std::io::Error> {
40        if self.active_quins >= self.capacity_quins {
41            return Err(std::io::Error::new(
42                std::io::ErrorKind::WriteZero,
43                "MmapStore capacity exceeded",
44            ));
45        }
46
47        let offset = self.active_quins * 48;
48        let bytes = bytemuck::bytes_of(quin);
49        self.mmap[offset..offset + 48].copy_from_slice(bytes);
50
51        self.active_quins += 1;
52        Ok(())
53    }
54
55    // Returns a zero-copy slice of all active Quins.
56    /// Live NQuin slice.
57    pub fn as_slice(&self) -> &[NQuin] {
58        let active_bytes = self.active_quins * 48;
59        let slice = &self.mmap[..active_bytes];
60        bytemuck::cast_slice(slice)
61    }
62}
63
64#[cfg(target_arch = "wasm32")]
65pub struct MmapStore {
66    data: Vec<NQuin>,
67    capacity_quins: usize,
68}
69
70#[cfg(target_arch = "wasm32")]
71impl MmapStore {
72    /// Opens.
73    pub fn open(_path: &str, capacity_quins: usize) -> Result<Self, std::io::Error> {
74        Ok(Self {
75            data: Vec::with_capacity(capacity_quins),
76            capacity_quins,
77        })
78    }
79
80    /// Appends `quin` to the store; `io::Error` on write failure (cfg-gated mmap/vec backends share the signature).
81    pub fn append(&mut self, quin: &NQuin) -> Result<(), std::io::Error> {
82        if self.data.len() >= self.capacity_quins {
83            return Err(std::io::Error::new(
84                std::io::ErrorKind::WriteZero,
85                "MmapStore capacity exceeded",
86            ));
87        }
88
89        self.data.push(*quin);
90        Ok(())
91    }
92
93    /// Live NQuin slice.
94    pub fn as_slice(&self) -> &[NQuin] {
95        &self.data
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use tempfile::NamedTempFile;
103
104    #[test]
105    fn test_mmap_store_open() {
106        let temp_file = NamedTempFile::new().unwrap();
107        let path = temp_file.path().to_str().unwrap();
108        let store = MmapStore::open(path, 10).unwrap();
109        assert_eq!(store.capacity_quins, 10);
110        assert_eq!(store.active_quins, 0);
111    }
112
113    #[test]
114    fn test_mmap_store_append_and_slice() {
115        let temp_file = NamedTempFile::new().unwrap();
116        let path = temp_file.path().to_str().unwrap();
117        let mut store = MmapStore::open(path, 10).unwrap();
118
119        let quin = NQuin {
120            subject: 1,
121            predicate: 2,
122            object: 3,
123            context: 4,
124            metadata: 5,
125            parity: 6,
126        };
127
128        store.append(&quin).unwrap();
129        assert_eq!(store.active_quins, 1);
130
131        let slice = store.as_slice();
132        assert_eq!(slice.len(), 1);
133        assert_eq!(slice[0].subject, 1);
134        assert_eq!(slice[0].predicate, 2);
135        assert_eq!(slice[0].object, 3);
136        assert_eq!(slice[0].context, 4);
137        assert_eq!(slice[0].metadata, 5);
138        assert_eq!(slice[0].parity, 6);
139    }
140}