Skip to main content

nervusdb_core/
triple.rs

1//! Basic triple/fact representation helpers.
2
3use crate::StringId;
4use serde::{Deserialize, Serialize};
5
6/// Fully encoded triple referencing dictionary identifiers.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8pub struct Triple {
9    pub subject_id: StringId,
10    pub predicate_id: StringId,
11    pub object_id: StringId,
12}
13
14impl Triple {
15    pub fn new(subject_id: StringId, predicate_id: StringId, object_id: StringId) -> Self {
16        Self {
17            subject_id,
18            predicate_id,
19            object_id,
20        }
21    }
22
23    /// Serialises the triple into a fixed-width 24 byte representation.
24    pub fn to_bytes(self) -> [u8; 24] {
25        let mut buf = [0u8; 24];
26        buf[0..8].copy_from_slice(&self.subject_id.to_le_bytes());
27        buf[8..16].copy_from_slice(&self.predicate_id.to_le_bytes());
28        buf[16..24].copy_from_slice(&self.object_id.to_le_bytes());
29        buf
30    }
31
32    /// Reconstructs a triple from the 24 byte representation.
33    pub fn from_bytes(buf: [u8; 24]) -> Self {
34        let subject_id = StringId::from_le_bytes(buf[0..8].try_into().unwrap());
35        let predicate_id = StringId::from_le_bytes(buf[8..16].try_into().unwrap());
36        let object_id = StringId::from_le_bytes(buf[16..24].try_into().unwrap());
37        Self::new(subject_id, predicate_id, object_id)
38    }
39}
40
41/// User-facing fact used when inserting new data.
42#[derive(Debug, Clone, Copy)]
43pub struct Fact<'a> {
44    pub subject: &'a str,
45    pub predicate: &'a str,
46    pub object: &'a str,
47}
48
49impl<'a> Fact<'a> {
50    pub fn new(subject: &'a str, predicate: &'a str, object: &'a str) -> Self {
51        Self {
52            subject,
53            predicate,
54            object,
55        }
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn roundtrip_bytes() {
65        let triple = Triple::new(1, 2, 3);
66        let buf = triple.to_bytes();
67        let restored = Triple::from_bytes(buf);
68        assert_eq!(triple, restored);
69    }
70}