1use crate::{Decode, DerOrd, Encode, Error, ErrorKind, Reader, Result, SliceWriter, Writer};
4use core::{
5 cmp::Ordering,
6 fmt,
7 ops::{Add, Sub},
8};
9
10const MAX_DER_OCTETS: usize = 5;
13
14const MAX_U32: u32 = 0xfff_ffff;
16
17const INDEFINITE_LENGTH_OCTET: u8 = 0b10000000; #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
28pub struct Length(u32);
29
30impl Length {
31 pub const ZERO: Self = Self(0);
33
34 pub const ONE: Self = Self(1);
36
37 pub const MAX: Self = Self(MAX_U32);
39
40 pub const fn new(value: u16) -> Self {
44 Self(value as u32)
45 }
46
47 pub fn is_zero(self) -> bool {
49 self == Self::ZERO
50 }
51
52 pub fn for_tlv(self) -> Result<Self> {
55 Self::ONE + self.encoded_len()? + self
56 }
57
58 pub fn saturating_add(self, rhs: Self) -> Self {
60 Self(self.0.saturating_add(rhs.0))
61 }
62
63 pub fn saturating_sub(self, rhs: Self) -> Self {
65 Self(self.0.saturating_sub(rhs.0))
66 }
67
68 fn initial_octet(self) -> Option<u8> {
81 match self.0 {
82 0x80..=0xFF => Some(0x81),
83 0x100..=0xFFFF => Some(0x82),
84 0x10000..=0xFFFFFF => Some(0x83),
85 0x1000000..=MAX_U32 => Some(0x84),
86 _ => None,
87 }
88 }
89}
90
91impl Add for Length {
92 type Output = Result<Self>;
93
94 fn add(self, other: Self) -> Result<Self> {
95 self.0
96 .checked_add(other.0)
97 .ok_or_else(|| ErrorKind::Overflow.into())
98 .and_then(TryInto::try_into)
99 }
100}
101
102impl Add<u8> for Length {
103 type Output = Result<Self>;
104
105 fn add(self, other: u8) -> Result<Self> {
106 self + Length::from(other)
107 }
108}
109
110impl Add<u16> for Length {
111 type Output = Result<Self>;
112
113 fn add(self, other: u16) -> Result<Self> {
114 self + Length::from(other)
115 }
116}
117
118impl Add<u32> for Length {
119 type Output = Result<Self>;
120
121 fn add(self, other: u32) -> Result<Self> {
122 self + Length::try_from(other)?
123 }
124}
125
126impl Add<usize> for Length {
127 type Output = Result<Self>;
128
129 fn add(self, other: usize) -> Result<Self> {
130 self + Length::try_from(other)?
131 }
132}
133
134impl Add<Length> for Result<Length> {
135 type Output = Self;
136
137 fn add(self, other: Length) -> Self {
138 self? + other
139 }
140}
141
142impl Sub for Length {
143 type Output = Result<Self>;
144
145 fn sub(self, other: Length) -> Result<Self> {
146 self.0
147 .checked_sub(other.0)
148 .ok_or_else(|| ErrorKind::Overflow.into())
149 .and_then(TryInto::try_into)
150 }
151}
152
153impl Sub<Length> for Result<Length> {
154 type Output = Self;
155
156 fn sub(self, other: Length) -> Self {
157 self? - other
158 }
159}
160
161impl From<u8> for Length {
162 fn from(len: u8) -> Length {
163 Length(len.into())
164 }
165}
166
167impl From<u16> for Length {
168 fn from(len: u16) -> Length {
169 Length(len.into())
170 }
171}
172
173impl From<Length> for u32 {
174 fn from(length: Length) -> u32 {
175 length.0
176 }
177}
178
179impl TryFrom<u32> for Length {
180 type Error = Error;
181
182 fn try_from(len: u32) -> Result<Length> {
183 if len <= Self::MAX.0 {
184 Ok(Length(len))
185 } else {
186 Err(ErrorKind::Overflow.into())
187 }
188 }
189}
190
191impl TryFrom<usize> for Length {
192 type Error = Error;
193
194 fn try_from(len: usize) -> Result<Length> {
195 u32::try_from(len)
196 .map_err(|_| ErrorKind::Overflow)?
197 .try_into()
198 }
199}
200
201impl TryFrom<Length> for usize {
202 type Error = Error;
203
204 fn try_from(len: Length) -> Result<usize> {
205 len.0.try_into().map_err(|_| ErrorKind::Overflow.into())
206 }
207}
208
209impl<'a> Decode<'a> for Length {
210 fn decode<R: Reader<'a>>(reader: &mut R) -> Result<Length> {
211 match reader.read_byte()? {
212 len if len < INDEFINITE_LENGTH_OCTET => Ok(len.into()),
215 INDEFINITE_LENGTH_OCTET => Err(ErrorKind::IndefiniteLength.into()),
216 tag @ 0x81..=0x84 => {
218 let nbytes = tag.checked_sub(0x80).ok_or(ErrorKind::Overlength)? as usize;
219 debug_assert!(nbytes <= 4);
220
221 let mut decoded_len = 0u32;
222 for _ in 0..nbytes {
223 decoded_len = decoded_len.checked_shl(8).ok_or(ErrorKind::Overflow)?
224 | u32::from(reader.read_byte()?);
225 }
226
227 let length = Length::try_from(decoded_len)?;
228
229 if length.initial_octet() == Some(tag) {
232 Ok(length)
233 } else {
234 Err(ErrorKind::Overlength.into())
235 }
236 }
237 _ => {
238 Err(ErrorKind::Overlength.into())
240 }
241 }
242 }
243}
244
245impl Encode for Length {
246 fn encoded_len(&self) -> Result<Length> {
247 match self.0 {
248 0..=0x7F => Ok(Length(1)),
249 0x80..=0xFF => Ok(Length(2)),
250 0x100..=0xFFFF => Ok(Length(3)),
251 0x10000..=0xFFFFFF => Ok(Length(4)),
252 0x1000000..=MAX_U32 => Ok(Length(5)),
253 _ => Err(ErrorKind::Overflow.into()),
254 }
255 }
256
257 fn encode(&self, writer: &mut impl Writer) -> Result<()> {
258 match self.initial_octet() {
259 Some(tag_byte) => {
260 writer.write_byte(tag_byte)?;
261
262 match self.0.to_be_bytes() {
264 [0, 0, 0, byte] => writer.write_byte(byte),
265 [0, 0, bytes @ ..] => writer.write(&bytes),
266 [0, bytes @ ..] => writer.write(&bytes),
267 bytes => writer.write(&bytes),
268 }
269 }
270 #[allow(clippy::cast_possible_truncation)]
271 None => writer.write_byte(self.0 as u8),
272 }
273 }
274}
275
276impl DerOrd for Length {
277 fn der_cmp(&self, other: &Self) -> Result<Ordering> {
278 let mut buf1 = [0u8; MAX_DER_OCTETS];
279 let mut buf2 = [0u8; MAX_DER_OCTETS];
280
281 let mut encoder1 = SliceWriter::new(&mut buf1);
282 encoder1.encode(self)?;
283
284 let mut encoder2 = SliceWriter::new(&mut buf2);
285 encoder2.encode(other)?;
286
287 Ok(encoder1.finish()?.cmp(encoder2.finish()?))
288 }
289}
290
291impl fmt::Display for Length {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 self.0.fmt(f)
294 }
295}
296
297#[cfg(feature = "arbitrary")]
300impl<'a> arbitrary::Arbitrary<'a> for Length {
301 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
302 Ok(Self(u.int_in_range(0..=MAX_U32)?))
303 }
304
305 fn size_hint(depth: usize) -> (usize, Option<usize>) {
306 u32::size_hint(depth)
307 }
308}
309
310#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
328pub struct IndefiniteLength(Option<Length>);
329
330impl IndefiniteLength {
331 pub const ZERO: Self = Self(Some(Length::ZERO));
333
334 pub const ONE: Self = Self(Some(Length::ONE));
336
337 pub const INDEFINITE: Self = Self(None);
339}
340
341impl IndefiniteLength {
342 pub fn new(length: impl Into<Length>) -> Self {
345 Self(Some(length.into()))
346 }
347
348 pub fn is_definite(self) -> bool {
350 self.0.is_some()
351 }
352 pub fn is_indefinite(self) -> bool {
354 self.0.is_none()
355 }
356}
357
358impl<'a> Decode<'a> for IndefiniteLength {
359 fn decode<R: Reader<'a>>(reader: &mut R) -> Result<IndefiniteLength> {
360 if reader.peek_byte() == Some(INDEFINITE_LENGTH_OCTET) {
361 let byte = reader.read_byte()?;
363 debug_assert_eq!(byte, INDEFINITE_LENGTH_OCTET);
364
365 Ok(Self::INDEFINITE)
366 } else {
367 Length::decode(reader).map(Into::into)
368 }
369 }
370}
371
372impl Encode for IndefiniteLength {
373 fn encoded_len(&self) -> Result<Length> {
374 match self.0 {
375 Some(length) => length.encoded_len(),
376 None => Ok(Length::ONE),
377 }
378 }
379
380 fn encode(&self, writer: &mut impl Writer) -> Result<()> {
381 match self.0 {
382 Some(length) => length.encode(writer),
383 None => writer.write_byte(INDEFINITE_LENGTH_OCTET),
384 }
385 }
386}
387
388impl From<Length> for IndefiniteLength {
389 fn from(length: Length) -> IndefiniteLength {
390 Self(Some(length))
391 }
392}
393
394impl From<Option<Length>> for IndefiniteLength {
395 fn from(length: Option<Length>) -> IndefiniteLength {
396 IndefiniteLength(length)
397 }
398}
399
400impl From<IndefiniteLength> for Option<Length> {
401 fn from(length: IndefiniteLength) -> Option<Length> {
402 length.0
403 }
404}
405
406impl TryFrom<IndefiniteLength> for Length {
407 type Error = Error;
408
409 fn try_from(length: IndefiniteLength) -> Result<Length> {
410 length.0.ok_or_else(|| ErrorKind::IndefiniteLength.into())
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::{IndefiniteLength, Length};
417 use crate::{Decode, DerOrd, Encode, ErrorKind};
418 use core::cmp::Ordering;
419
420 #[test]
421 fn decode() {
422 assert_eq!(Length::ZERO, Length::from_der(&[0x00]).unwrap());
423
424 assert_eq!(Length::from(0x7Fu8), Length::from_der(&[0x7F]).unwrap());
425
426 assert_eq!(
427 Length::from(0x80u8),
428 Length::from_der(&[0x81, 0x80]).unwrap()
429 );
430
431 assert_eq!(
432 Length::from(0xFFu8),
433 Length::from_der(&[0x81, 0xFF]).unwrap()
434 );
435
436 assert_eq!(
437 Length::from(0x100u16),
438 Length::from_der(&[0x82, 0x01, 0x00]).unwrap()
439 );
440
441 assert_eq!(
442 Length::try_from(0x10000u32).unwrap(),
443 Length::from_der(&[0x83, 0x01, 0x00, 0x00]).unwrap()
444 );
445 }
446
447 #[test]
448 fn encode() {
449 let mut buffer = [0u8; 4];
450
451 assert_eq!(&[0x00], Length::ZERO.encode_to_slice(&mut buffer).unwrap());
452
453 assert_eq!(
454 &[0x7F],
455 Length::from(0x7Fu8).encode_to_slice(&mut buffer).unwrap()
456 );
457
458 assert_eq!(
459 &[0x81, 0x80],
460 Length::from(0x80u8).encode_to_slice(&mut buffer).unwrap()
461 );
462
463 assert_eq!(
464 &[0x81, 0xFF],
465 Length::from(0xFFu8).encode_to_slice(&mut buffer).unwrap()
466 );
467
468 assert_eq!(
469 &[0x82, 0x01, 0x00],
470 Length::from(0x100u16).encode_to_slice(&mut buffer).unwrap()
471 );
472
473 assert_eq!(
474 &[0x83, 0x01, 0x00, 0x00],
475 Length::try_from(0x10000u32)
476 .unwrap()
477 .encode_to_slice(&mut buffer)
478 .unwrap()
479 );
480 }
481
482 #[test]
483 fn indefinite_lengths() {
484 assert!(Length::from_der(&[0x80]).is_err());
486
487 let indefinite_length = IndefiniteLength::from_der(&[0x80]).unwrap();
489 assert!(indefinite_length.is_indefinite());
490 assert_eq!(indefinite_length, IndefiniteLength::INDEFINITE);
491
492 let length = IndefiniteLength::from_der(&[0x83, 0x01, 0x00, 0x00]).unwrap();
494 assert!(length.is_definite());
495 assert_eq!(
496 Length::try_from(0x10000u32).unwrap(),
497 length.try_into().unwrap()
498 );
499 }
500
501 #[test]
502 fn add_overflows_when_max_length_exceeded() {
503 let result = Length::MAX + Length::ONE;
504 assert_eq!(
505 result.err().map(|err| err.kind()),
506 Some(ErrorKind::Overflow)
507 );
508 }
509
510 #[test]
511 fn der_ord() {
512 assert_eq!(Length::ONE.der_cmp(&Length::MAX).unwrap(), Ordering::Less);
513 }
514}