Skip to main content

kmip_protocol/ttlv/
types.rs

1use core::fmt;
2
3use enum_ordinalize::Ordinalize;
4
5//----------- Tag ------------------------------------------------------------
6
7/// A TTLV tag.
8#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
9pub struct Tag(u32);
10
11impl Tag {
12    /// Construct a new [`Tag`].
13    ///
14    /// ## Panics
15    ///
16    /// Panics if the value does not fit within 24 bits.
17    pub const fn new(value: u32) -> Self {
18        assert!(value < (1u32 << 24));
19        Self(value << 8)
20    }
21
22    /// The value of this tag.
23    pub const fn value(self) -> u32 {
24        self.0 >> 8
25    }
26
27    /// The wire-format bytes of this tag.
28    pub const fn bytes(self) -> [u8; 3] {
29        let [a, b, c, _] = self.0.to_be_bytes();
30        [a, b, c]
31    }
32
33    /// Attach a type to this tag.
34    pub const fn with_type(self, r#type: Type) -> TagType {
35        TagType::new(self, r#type)
36    }
37}
38
39impl From<TagType> for Tag {
40    fn from(value: TagType) -> Self {
41        value.tag()
42    }
43}
44
45impl fmt::Display for Tag {
46    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47        write!(f, "0x{:06X}", self.value())
48    }
49}
50
51impl fmt::Debug for Tag {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(f, "Tag(0x{:06X})", self.value())
54    }
55}
56
57//----------- Type -----------------------------------------------------------
58
59/// A TTLV type.
60#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Ordinalize)]
61#[repr(u8)]
62pub enum Type {
63    /// A TTLV structure.
64    ///
65    /// This corresponds to a user-defined `struct`.
66    Structure = 0x01,
67
68    /// A TTLV integer.
69    ///
70    /// This corresponds to `i32`.
71    Integer = 0x02,
72
73    /// A TTLV long integer.
74    ///
75    /// This corresponds to `i64`.
76    LongInteger = 0x03,
77
78    /// A TTLV big integer.
79    ///
80    /// This is a variable-length signed integer type.
81    BigInteger = 0x04,
82
83    /// A TTLV enumeration.
84    ///
85    /// This corresponds to [`u32`], but in practice it may be represented by
86    /// a user-defined `enum`.
87    Enumeration = 0x05,
88
89    /// A TTLV boolean.
90    ///
91    /// This corresponds to `bool`.
92    Boolean = 0x06,
93
94    /// A TTLV text string.
95    ///
96    /// This corresponds to `str`.
97    TextString = 0x07,
98
99    /// A TTLV byte string.
100    ///
101    /// This corresponds to `[u8]` -- a slice of bytes.
102    ByteString = 0x08,
103
104    /// A TTLV date-time.
105    ///
106    /// This is a 64-bit signed UNIX time value, in units of seconds.
107    DateTime = 0x09,
108
109    /// A TTLV interval.
110    ///
111    /// This corresponds to [`Duration`], but has a limited range and a
112    /// granularity of seconds.
113    ///
114    /// [`Duration`]: std::time::Duration
115    Interval = 0x0A,
116}
117
118impl From<TagType> for Type {
119    fn from(value: TagType) -> Self {
120        value.r#type()
121    }
122}
123
124impl std::fmt::Display for Type {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        write!(f, "{self:?}")
127    }
128}
129
130//----------- TagType --------------------------------------------------------
131
132/// A TTLV tag-type pair.
133#[derive(Copy, Clone, PartialEq, Eq, Hash)]
134pub struct TagType(u32);
135
136impl TagType {
137    /// Construct a new [`TagType`].
138    pub const fn new(tag: Tag, r#type: Type) -> Self {
139        Self(tag.0 | r#type as u32)
140    }
141
142    /// Split this into a tag-type tuple.
143    pub const fn split(self) -> (Tag, Type) {
144        (self.tag(), self.r#type())
145    }
146
147    /// The contained tag.
148    pub const fn tag(self) -> Tag {
149        Tag(self.0 & 0xFFFFFF00)
150    }
151
152    /// The contained type.
153    pub const fn r#type(self) -> Type {
154        // SAFETY: 'self.0' always contains a valid tag and type.
155        unsafe { core::mem::transmute(self.0 as u8) }
156    }
157
158    /// The value of this pair as a native-endian integer.
159    pub const fn value(self) -> u32 {
160        self.0
161    }
162
163    /// The wire-format bytes of this tag-type pair.
164    pub const fn bytes(self) -> [u8; 4] {
165        self.0.to_be_bytes()
166    }
167
168    /// Parse a tag-type pair from bytes.
169    pub const fn parse(bytes: [u8; 4]) -> Self {
170        Self(u32::from_be_bytes(bytes))
171    }
172}
173
174impl From<(Tag, Type)> for TagType {
175    fn from((tag, r#type): (Tag, Type)) -> Self {
176        Self::new(tag, r#type)
177    }
178}
179
180impl From<TagType> for (Tag, Type) {
181    fn from(value: TagType) -> Self {
182        value.split()
183    }
184}
185
186impl fmt::Display for TagType {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        write!(f, "{} {}", self.r#type(), self.tag())
189    }
190}
191
192impl fmt::Debug for TagType {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        write!(f, "TagType({:?}, {:?})", self.tag(), self.r#type())
195    }
196}
197
198//============ Property-based Testing ========================================
199
200#[cfg(feature = "proptest")]
201mod proptest {
202    use std::ops::Range;
203
204    use proptest::prelude::*;
205
206    use super::{Tag, Type};
207
208    impl Arbitrary for Tag {
209        type Parameters = ();
210        type Strategy = prop::strategy::Map<Range<u32>, fn(u32) -> Tag>;
211
212        fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
213            (0..1 << 24).prop_map(Tag::new)
214        }
215    }
216
217    impl Arbitrary for Type {
218        type Parameters = ();
219        type Strategy = prop::strategy::Map<Range<u8>, fn(u8) -> Type>;
220
221        fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
222            (0x01..0x0B).prop_map(|x| unsafe { core::mem::transmute(x) })
223        }
224    }
225}