nodedb_types/
surrogate.rs1use std::fmt;
15
16use serde::{Deserialize, Serialize};
17
18#[derive(
24 Debug,
25 Clone,
26 Copy,
27 PartialEq,
28 Eq,
29 PartialOrd,
30 Ord,
31 Hash,
32 Serialize,
33 Deserialize,
34 zerompk::ToMessagePack,
35 zerompk::FromMessagePack,
36)]
37pub struct Surrogate(pub u32);
38
39impl Surrogate {
40 pub const ZERO: Surrogate = Surrogate(0);
42
43 pub const fn new(value: u32) -> Self {
45 Self(value)
46 }
47
48 pub const fn as_u32(self) -> u32 {
50 self.0
51 }
52}
53
54impl fmt::Display for Surrogate {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 write!(f, "sur:{}", self.0)
57 }
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn ordering_matches_u32() {
66 let a = Surrogate::new(1);
67 let b = Surrogate::new(2);
68 assert!(a < b);
69 assert_eq!(a.as_u32(), 1);
70 }
71
72 #[test]
73 fn display_renders_sur_prefix() {
74 assert_eq!(Surrogate::new(42).to_string(), "sur:42");
75 }
76
77 #[test]
78 fn msgpack_roundtrip() {
79 let s = Surrogate::new(0xDEAD_BEEF);
80 let bytes = zerompk::to_msgpack_vec(&s).unwrap();
81 let back: Surrogate = zerompk::from_msgpack(&bytes).unwrap();
82 assert_eq!(s, back);
83 }
84
85 #[test]
86 fn zero_sentinel() {
87 assert_eq!(Surrogate::ZERO.as_u32(), 0);
88 }
89}