bnr_xfs/cash_unit/
unit_id.rs1use std::fmt;
2
3use crate::xfs::{value::XfsValue, xfs_struct::XfsMember};
4use crate::{Error, Result};
5
6pub const UNIT_ID_LEN: usize = 20;
7
8#[repr(C)]
10#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Deserialize, serde::Serialize)]
11pub struct UnitId(u64);
12
13impl UnitId {
14 pub const fn new() -> Self {
16 Self(0)
17 }
18
19 pub const fn create(id: u64) -> Self {
21 Self(id)
22 }
23
24 pub const fn xfs_name() -> &'static str {
26 "unitId"
27 }
28
29 pub const fn inner(&self) -> u64 {
31 self.0
32 }
33
34 pub fn set_inner(&mut self, val: u64) {
36 self.0 = val;
37 }
38
39 pub fn into_inner(self) -> u64 {
41 self.0
42 }
43}
44
45impl fmt::Display for UnitId {
46 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47 write!(f, "{}", self.inner())
48 }
49}
50
51impl From<u64> for UnitId {
52 fn from(val: u64) -> Self {
53 Self::create(val)
54 }
55}
56
57impl From<&UnitId> for XfsValue {
58 fn from(val: &UnitId) -> Self {
59 Self::new().with_string(format!("{val}"))
60 }
61}
62
63impl From<UnitId> for XfsValue {
64 fn from(val: UnitId) -> Self {
65 (&val).into()
66 }
67}
68
69impl TryFrom<&str> for UnitId {
70 type Error = Error;
71
72 fn try_from(val: &str) -> Result<Self> {
73 Ok(val
74 .parse::<u64>()
75 .map_err(|_| Error::Xfs(format!("Expected UnitId string, have: {val}")))?
76 .into())
77 }
78}
79
80impl TryFrom<&XfsValue> for UnitId {
81 type Error = Error;
82
83 fn try_from(val: &XfsValue) -> Result<Self> {
84 val.string()
85 .ok_or(Error::Xfs(format!("Expected UnitId XfsValue, have: {val}")))?
86 .try_into()
87 }
88}
89
90impl TryFrom<XfsValue> for UnitId {
91 type Error = Error;
92
93 fn try_from(val: XfsValue) -> Result<Self> {
94 (&val).try_into()
95 }
96}
97
98impl From<&UnitId> for XfsMember {
99 fn from(val: &UnitId) -> Self {
100 Self::create(UnitId::xfs_name(), val.into())
101 }
102}
103
104impl From<UnitId> for XfsMember {
105 fn from(val: UnitId) -> Self {
106 (&val).into()
107 }
108}
109
110impl TryFrom<&XfsMember> for UnitId {
111 type Error = Error;
112
113 fn try_from(val: &XfsMember) -> Result<Self> {
114 match (val.name(), val.value().string()) {
115 (n, Some(s)) if n == Self::xfs_name() => s.try_into(),
116 _ => Err(Error::Xfs(format!(
117 "Expected UnitId XfsMember, have: {val}"
118 ))),
119 }
120 }
121}
122
123impl TryFrom<XfsMember> for UnitId {
124 type Error = Error;
125
126 fn try_from(val: XfsMember) -> Result<Self> {
127 (&val).try_into()
128 }
129}