Skip to main content

wellfare_core/
qualia_bindings.rs

1#[cfg(target_arch = "wasm32")]
2use js_sys::Float64Array;
3/// QualiaStore — in-memory quint store exposed to WASM.
4///
5/// A quint is a 5-tuple (Subject, Predicate, Object, Context, Metadata) of u64 IDs.
6/// IDs are assigned by the JS-side Lexicon (vault-wasm.js); this module is the
7/// storage layer only.
8///
9/// Full qualia-core-db wiring (W10) is deferred: the `qualia` Cargo feature gates
10/// that dependency to avoid pulling wgpu into the default WASM binary.
11
12#[cfg(target_arch = "wasm32")]
13use wasm_bindgen::prelude::*;
14
15#[cfg(target_arch = "wasm32")]
16#[wasm_bindgen]
17pub struct QualiaStore {
18    quins: Vec<[u64; 5]>,
19}
20
21#[cfg(target_arch = "wasm32")]
22#[wasm_bindgen]
23impl QualiaStore {
24    #[wasm_bindgen(constructor)]
25    /// Creates a new instance.
26    pub fn new() -> Self {
27        Self { quins: Vec::new() }
28    }
29
30    /// Insert a quint (s, p, o, c, m).  Returns true on success.
31    pub fn insert_quin(&mut self, s: u64, p: u64, o: u64, c: u64, m: u64) -> bool {
32        self.quins.push([s, p, o, c, m]);
33        true
34    }
35
36    /// Return all quints with the given subject as a flat Float64Array
37    /// (groups of 5: [s,p,o,c,m, s,p,o,c,m, ...]).
38    pub fn query_subject(&self, s: u64) -> Float64Array {
39        let matches: Vec<f64> = self
40            .quins
41            .iter()
42            .filter(|q| q[0] == s)
43            .flat_map(|q| q.iter().map(|&x| x as f64))
44            .collect();
45        Float64Array::from(matches.as_slice())
46    }
47
48    /// Return all quints with the given predicate as a flat Float64Array.
49    pub fn query_predicate(&self, p: u64) -> Float64Array {
50        let matches: Vec<f64> = self
51            .quins
52            .iter()
53            .filter(|q| q[1] == p)
54            .flat_map(|q| q.iter().map(|&x| x as f64))
55            .collect();
56        Float64Array::from(matches.as_slice())
57    }
58
59    /// Return all quints in the given context as a flat Float64Array.
60    pub fn query_context(&self, c: u64) -> Float64Array {
61        let matches: Vec<f64> = self
62            .quins
63            .iter()
64            .filter(|q| q[3] == c)
65            .flat_map(|q| q.iter().map(|&x| x as f64))
66            .collect();
67        Float64Array::from(matches.as_slice())
68    }
69
70    /// Total number of quints stored.
71    pub fn len(&self) -> u32 {
72        self.quins.len() as u32
73    }
74
75    /// Clear all stored quints.
76    pub fn clear(&mut self) {
77        self.quins.clear();
78    }
79
80    /// Parse a CBOR-LD byte array (CBOR array of 4 or 5 unsigned integers) and
81    /// insert the resulting quin. Returns true on success, false on parse error.
82    ///
83    /// The qualiaDB binary gatekeeper (cbor_compiler.rs) requires this format:
84    ///   CBOR array header (0x84 or 0x85) followed by 4–5 CBOR unsigned integers.
85    /// All values are Lexicon-compressed u64 IDs assigned by the JS Lexicon.
86    pub fn insert_from_cbor_ld(&mut self, data: &[u8]) -> bool {
87        match Self::parse_cbor_quin(data) {
88            Ok(q) => {
89                self.quins.push(q);
90                true
91            }
92            Err(_) => false,
93        }
94    }
95
96    /// Parse one CBOR-LD quin from raw bytes.
97    /// Accepts CBOR arrays of 4 or 5 unsigned integers (major type 0).
98    fn parse_cbor_quin(payload: &[u8]) -> Result<[u64; 5], &'static str> {
99        if payload.is_empty() {
100            return Err("empty");
101        }
102        let header = payload[0];
103        // Must be a CBOR array (major type 4 = 0x80..0x9F)
104        if (header >> 5) != 4 {
105            return Err("not a CBOR array");
106        }
107        let count = (header & 0x1F) as usize;
108        if count < 4 || count > 5 {
109            return Err("quin needs 4 or 5 elements");
110        }
111        let mut cur = 1usize;
112        let mut vals = [0u64; 5];
113        for i in 0..count {
114            if cur >= payload.len() {
115                return Err("buffer underflow");
116            }
117            let b = payload[cur];
118            // Major type 0 = unsigned integer
119            if (b >> 5) != 0 {
120                return Err("element is not uint");
121            }
122            let add = b & 0x1F;
123            cur += 1;
124            vals[i] = match add {
125                0..=23 => add as u64,
126                24 => {
127                    if cur + 1 > payload.len() {
128                        return Err("overflow u8");
129                    }
130                    let v = payload[cur] as u64;
131                    cur += 1;
132                    v
133                }
134                25 => {
135                    if cur + 2 > payload.len() {
136                        return Err("overflow u16");
137                    }
138                    let v = u16::from_be_bytes([payload[cur], payload[cur + 1]]) as u64;
139                    cur += 2;
140                    v
141                }
142                26 => {
143                    if cur + 4 > payload.len() {
144                        return Err("overflow u32");
145                    }
146                    let mut b4 = [0u8; 4];
147                    b4.copy_from_slice(&payload[cur..cur + 4]);
148                    cur += 4;
149                    u32::from_be_bytes(b4) as u64
150                }
151                27 => {
152                    if cur + 8 > payload.len() {
153                        return Err("overflow u64");
154                    }
155                    let mut b8 = [0u8; 8];
156                    b8.copy_from_slice(&payload[cur..cur + 8]);
157                    cur += 8;
158                    u64::from_be_bytes(b8)
159                }
160                _ => return Err("unsupported additional info"),
161            };
162        }
163        Ok(vals)
164    }
165}