nodedb_types/
calvin_passive.rs1use serde::{Deserialize, Serialize};
14
15use crate::QualifiedCollection;
16
17#[derive(
19 Debug,
20 Clone,
21 PartialEq,
22 Eq,
23 PartialOrd,
24 Ord,
25 Hash,
26 Serialize,
27 Deserialize,
28 zerompk::ToMessagePack,
29 zerompk::FromMessagePack,
30)]
31pub enum PassiveKey {
32 Surrogate { surrogate: u32 },
34 Kv { key: Vec<u8> },
36}
37
38#[derive(
43 Debug,
44 Clone,
45 PartialEq,
46 Eq,
47 PartialOrd,
48 Ord,
49 Hash,
50 Serialize,
51 Deserialize,
52 zerompk::ToMessagePack,
53 zerompk::FromMessagePack,
54)]
55pub struct PassiveReadKeyId {
56 pub collection: QualifiedCollection,
58 pub key: PassiveKey,
60}
61
62impl PassiveReadKeyId {
63 pub fn surrogate(collection: QualifiedCollection, surrogate: u32) -> Self {
65 Self {
66 collection,
67 key: PassiveKey::Surrogate { surrogate },
68 }
69 }
70
71 pub fn kv(collection: QualifiedCollection, key: Vec<u8>) -> Self {
73 Self {
74 collection,
75 key: PassiveKey::Kv { key },
76 }
77 }
78
79 pub fn serialized_size_hint(&self) -> usize {
81 let key = match &self.key {
82 PassiveKey::Surrogate { .. } => 4,
83 PassiveKey::Kv { key } => key.len(),
84 };
85 self.collection.as_str().len() + key
86 }
87}
88
89#[cfg(test)]
90mod tests {
91 use super::*;
92
93 #[test]
95 fn kv_rows_keep_distinct_identities() {
96 let collection = QualifiedCollection::from_stored("items".to_owned());
97 let a = PassiveReadKeyId::kv(collection.clone(), b"alice:sword".to_vec());
98 let b = PassiveReadKeyId::kv(collection, b"alice:shield".to_vec());
99 assert_ne!(a, b);
100 }
101
102 #[test]
104 fn identity_round_trips_through_msgpack() {
105 let id = PassiveReadKeyId::surrogate(QualifiedCollection::from_stored("o".to_owned()), 9);
106 let bytes = zerompk::to_msgpack_vec(&id).expect("encode");
107 let back: PassiveReadKeyId = zerompk::from_msgpack(&bytes).expect("decode");
108 assert_eq!(back, id);
109 }
110}