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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
//! Length calculations for encoded ASN.1 DER values

use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Result};
use core::{convert::{TryFrom, TryInto}, fmt, ops::Add};

/// SIMPLE-TLV-encoded length.
///
/// By definition, in the range `0..=65535`
///
/// The length field consists of one or three consecutive bytes.
/// - If the first byte is not `0xFF`, then the length field consists of a single byte encoding a number from
///   zero to 254.
/// - If the first byte is `0xFF`, then the length field consists of the subsequent two bytes interpreted as
///   big-endian integer, with any value from zero to 65,535.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct Length(u16);

impl Length {
    /// Return a length of `0`.
    pub const fn zero() -> Self {
        Length(0)
    }

    /// Get the maximum length supported by SIMPLE-TLV: 65,535.
    pub const fn max() -> usize {
        u16::MAX as usize
    }

    /// Convert length to `usize`.
    pub fn to_usize(self) -> usize {
        self.0.into()
    }
}

/// Calculate the sum of the encoded lengths of the encodables.
impl<'a> TryFrom<&'a [&'a dyn Encodable]> for Length {
    type Error = Error;
    fn try_from(encodables: &[&dyn Encodable]) -> Result<Length> {
        encodables
            .iter()
            .fold(Ok(Length::zero()), |sum, encodable| {
                sum + encodable.encoded_length()?
            })
    }
}

impl Add for Length {
    type Output = Result<Self>;

    fn add(self, other: Self) -> Result<Self> {
        self.0
            .checked_add(other.0)
            .map(Length)
            .ok_or_else(|| ErrorKind::Overflow.into())
    }
}

impl Add<u8> for Length {
    type Output = Result<Self>;

    fn add(self, other: u8) -> Result<Self> {
        self + Length::from(other)
    }
}

impl Add<u16> for Length {
    type Output = Result<Self>;

    fn add(self, other: u16) -> Result<Self> {
        self + Length::from(other)
    }
}

impl Add<usize> for Length {
    type Output = Result<Self>;

    fn add(self, other: usize) -> Result<Self> {
        self + Length::try_from(other)?
    }
}

impl Add<Length> for Result<Length> {
    type Output = Self;

    fn add(self, other: Length) -> Self {
        self? + other
    }
}

impl From<u8> for Length {
    fn from(len: u8) -> Length {
        Length(len as u16)
    }
}

impl From<u16> for Length {
    fn from(len: u16) -> Length {
        Length(len)
    }
}

impl From<Length> for u16 {
    fn from(len: Length) -> u16 {
        len.0
    }
}

impl From<Length> for usize {
    fn from(len: Length) -> usize {
        len.0 as usize
    }
}

impl TryFrom<usize> for Length {
    type Error = Error;

    fn try_from(len: usize) -> Result<Length> {
        u16::try_from(len)
            .map(Length)
            .map_err(|_| ErrorKind::Overflow.into())
    }
}

impl Decodable<'_> for Length {
    fn decode(decoder: &mut Decoder<'_>) -> Result<Length> {
        match decoder.byte()? {
            0xFF => {
                let be_len = decoder.bytes(2u8)?;
                Ok(Length::from(u16::from_be_bytes(be_len.try_into().unwrap())))
            }
            len => Ok(len.into()),
        }
    }
}

impl Encodable for Length {
    fn encoded_length(&self) -> Result<Length> {
        match self.0 {
            0..=0xFE => Ok(Length(1)),
            _ => Ok(Length(3)),
        }
    }

    fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> {
        match self.0 {
            0..=0xFE => encoder.byte(self.0 as u8),
            _ => {
                encoder.byte(0xFF)?;
                encoder.bytes(&self.0.to_be_bytes())
            }
        }
    }
}

impl fmt::Display for Length {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::Length;
    use crate::{Decodable, Encodable, Error, ErrorKind};

    #[test]
    fn decode() {
        assert_eq!(Length::zero(), Length::from_bytes(&[0x00]).unwrap());

        assert_eq!(Length::from(0x7Fu8), Length::from_bytes(&[0x7F]).unwrap());
        assert_eq!(Length::from(0x7Fu8), Length::from_bytes(&[0xFF, 0x00, 0x7F]).unwrap());
        assert_eq!(Length::from(0xFEu8), Length::from_bytes(&[0xFE]).unwrap());
        assert_eq!(Length::from(0xFEu8), Length::from_bytes(&[0xFF, 0x00, 0xFE]).unwrap());

        // these are the current errors, do we want them?
        assert_eq!(Length::from_bytes(&[0xFF]).unwrap_err(), Error::from(ErrorKind::Truncated));
        assert_eq!(Length::from_bytes(&[0xFF, 0x12]).unwrap_err(), Error::from(ErrorKind::Truncated));
        // this is a bit clumsy to express
        assert!(Length::from_bytes(&[0xFF, 0x12, 0x34, 0x56]).is_err());


        assert_eq!(
            Length::from(0xFFu8),
            Length::from_bytes(&[0xFF, 0x00, 0xFF]).unwrap()
        );

        assert_eq!(
            Length::from(0x100u16),
            Length::from_bytes(&[0xFF, 0x01, 0x00]).unwrap()
        );

        assert_eq!(
            Length::from(0xFFFFu16),
            Length::from_bytes(&[0xFF, 0xFF, 0xFF]).unwrap()
        );
    }

    #[test]
    fn encode() {
        let mut buffer = [0u8; 3];

        assert_eq!(
            &[0x00],
            Length::zero().encode_to_slice(&mut buffer).unwrap()
        );

        assert_eq!(
            &[0x7F],
            Length::from(0x7Fu8).encode_to_slice(&mut buffer).unwrap()
        );

        assert_eq!(
            &[0xFE],
            Length::from(0xFEu8).encode_to_slice(&mut buffer).unwrap()
        );

        assert_eq!(
            &[0xFF, 0x00, 0xFF],
            Length::from(0xFFu8).encode_to_slice(&mut buffer).unwrap()
        );

        assert_eq!(
            &[0xFF, 0x01, 0x00],
            Length::from(0x100u16).encode_to_slice(&mut buffer).unwrap()
        );

        assert_eq!(
            &[0xFF, 0xFF, 0xFF],
            Length::from(0xFFFFu16).encode_to_slice(&mut buffer).unwrap()
        );
    }
}