qualia_core_db/entity_view/
entity_id.rs1use crate::hypermedia::fnv60;
7use crate::q_hash;
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
12#[repr(transparent)]
13pub struct EntityId(pub u64);
14
15impl EntityId {
16 pub const fn from_raw(id: u64) -> Self {
18 Self(id)
19 }
20
21 pub const fn from_u64(id: u64) -> Self {
23 Self(id)
24 }
25
26 pub const fn raw(self) -> u64 {
28 self.0
29 }
30
31 pub fn is_unset(self) -> bool {
33 self.0 == 0
34 }
35
36 pub fn from_bytes(bytes: &[u8]) -> Self {
38 Self(fnv60(bytes))
39 }
40
41 pub fn from_uri(uri: &str) -> Self {
43 Self::from_bytes(uri.trim().as_bytes())
44 }
45
46 pub fn from_iri_q_hash(iri: &str) -> Self {
49 Self(q_hash(iri))
50 }
51
52 pub fn from_did(did: &str) -> Self {
54 Self::from_uri(did)
55 }
56
57 pub fn from_fragment(parent_uri: &str, fragment_key: &str) -> Self {
59 let mut buf = Vec::with_capacity(parent_uri.len() + fragment_key.len() + 1);
60 buf.extend_from_slice(parent_uri.as_bytes());
61 buf.push(0x1f);
62 buf.extend_from_slice(fragment_key.as_bytes());
63 Self::from_bytes(&buf)
64 }
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
69#[serde(rename_all = "snake_case")]
70#[repr(u8)]
71pub enum EntityKind {
72 #[default]
73 Unknown = 0,
74 Agent = 1,
76 Instrument = 2,
78 Asset = 3,
80 WebLocus = 4,
82 Fragment = 5,
84 Commitment = 6,
86 Layer = 7,
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn uri_ids_are_stable_and_distinct() {
96 let a = EntityId::from_uri("https://example.org/a");
97 let b = EntityId::from_uri("https://example.org/b");
98 assert_eq!(a, EntityId::from_uri("https://example.org/a"));
99 assert_ne!(a, b);
100 assert!(!a.is_unset());
101 }
102
103 #[test]
104 fn fragment_differs_from_parent() {
105 let parent = EntityId::from_uri("urn:doc:lesson");
106 let frag = EntityId::from_fragment("urn:doc:lesson", "span:10-40");
107 assert_ne!(parent, frag);
108 }
109}