crystal_cif_io/grammar/numeric_values/
unsigned_integer.rs

1use std::fmt::Display;
2
3use winnow::{ascii::digit1, error::StrContext, Parser};
4
5use crate::grammar::{SyntacticUnit, Value};
6
7use super::{Integer, Number, Numeric};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
10pub struct UnsignedInteger(pub u32);
11
12impl std::ops::Deref for UnsignedInteger {
13    type Target = u32;
14
15    fn deref(&self) -> &Self::Target {
16        &self.0
17    }
18}
19
20impl SyntacticUnit for UnsignedInteger {
21    type ParseResult = Self;
22
23    type FormatOutput = u32;
24
25    fn parser(input: &mut &str) -> winnow::prelude::PResult<Self::ParseResult> {
26        digit1
27            .map(|n: &str| {
28                n.parse::<u32>()
29                    .map(UnsignedInteger)
30                    .expect("Failed to parse as u32")
31            })
32            .context(StrContext::Label("<UnsignedInteger> as u32"))
33            .parse_next(input)
34    }
35
36    fn formatted_output(&self) -> Self::FormatOutput {
37        self.0
38    }
39}
40
41impl Display for UnsignedInteger {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "{}", self.formatted_output())
44    }
45}
46
47impl From<UnsignedInteger> for Integer {
48    fn from(value: UnsignedInteger) -> Self {
49        Integer(value.0 as i32)
50    }
51}
52
53impl From<UnsignedInteger> for Value {
54    fn from(value: UnsignedInteger) -> Self {
55        Value::Numeric(Numeric::new(Number::Integer(value.into()), None))
56    }
57}