cbor_next/content/simple.rs
1use std::fmt::{Debug, Formatter, Result as FmtResult};
2
3use crate::error::Error;
4
5/// A simple value of `CBOR` major type 7 which has no dedicated variant.
6///
7/// The values 20 to 23 are `false`, `true`, `null` and `undefined`, and the
8/// values 24 to 31 are reserved by RFC 8949, so this wrapper only accepts a
9/// number in the range 0 to 19 or 32 to 255.
10///
11/// # Example
12/// ```rust
13/// use cbor_next::Simple;
14///
15/// assert_eq!(Simple::try_from(10).unwrap().value(), 10);
16/// assert!(Simple::try_from(255).is_ok());
17/// assert!(Simple::try_from(24).is_err());
18/// assert!(Simple::try_from(29).is_err());
19/// ```
20#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
21pub struct Simple(u8);
22
23impl Simple {
24 /// The number of the simple value.
25 #[must_use]
26 pub fn value(self) -> u8 {
27 self.0
28 }
29}
30
31impl TryFrom<u8> for Simple {
32 type Error = Error;
33
34 /// Create a simple value.
35 ///
36 /// # Errors
37 /// If the number is between 20 and 31, which RFC 8949 either assigns to a
38 /// dedicated data item or reserves
39 fn try_from(value: u8) -> Result<Self, Self::Error> {
40 match value {
41 0..=19 | 32..=u8::MAX => Ok(Self(value)),
42 _ => Err(Error::InvalidSimpleValue(value)),
43 }
44 }
45}
46
47impl From<Simple> for u8 {
48 fn from(value: Simple) -> Self {
49 value.0
50 }
51}
52
53impl Debug for Simple {
54 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
55 write!(f, "simple({})", self.0)
56 }
57}