1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use std::{
    convert::Infallible,
    fmt::{self, Display, Formatter},
    str::FromStr,
};

use str_reader::StringReader;

use crate::ParseError;

/// Bandwidth type.
#[derive(Clone)]
pub enum BandwidthType {
    AS,
    CT,
    Other(String),
}

impl Display for BandwidthType {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let s = match self {
            Self::AS => "AS",
            Self::CT => "CT",
            Self::Other(t) => t.as_str(),
        };

        f.write_str(s)
    }
}

impl FromStr for BandwidthType {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let res = match s {
            "AS" => Self::AS,
            "CT" => Self::CT,
            _ => Self::Other(s.to_string()),
        };

        Ok(res)
    }
}

/// Bandwidth field.
#[derive(Clone)]
pub struct Bandwidth {
    bandwidth_type: BandwidthType,
    bandwidth: u32,
}

impl Bandwidth {
    /// Create a new bandwidth field with a given type and bandwidth.
    #[inline]
    pub fn new(bandwidth_type: BandwidthType, bandwidth: u32) -> Self {
        Self {
            bandwidth_type,
            bandwidth,
        }
    }

    /// Get the type of the bandwidth.
    #[inline]
    pub fn bandwidth_type(&self) -> &BandwidthType {
        &self.bandwidth_type
    }

    /// Get the bandwidth.
    #[inline]
    pub fn bandwidth(&self) -> u32 {
        self.bandwidth
    }
}

impl Display for Bandwidth {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "{}:{}", self.bandwidth_type, self.bandwidth)
    }
}

impl FromStr for Bandwidth {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut reader = StringReader::new(s);

        let bandwidth_type = reader.read_until(|c| c == ':').trim().parse()?;

        reader.match_char(':')?;

        let bandwidth = reader.read_u32()?;

        reader.skip_whitespace();

        if !reader.is_empty() {
            return Err(ParseError::plain());
        }

        Ok(Self::new(bandwidth_type, bandwidth))
    }
}