ndn_tlv/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4pub use ::bytes;
5pub use ::ndn_tlv_derive::Tlv;
6use bytes::{Buf, BufMut, Bytes, BytesMut};
7pub use error::TlvError;
8pub use tlv::{tlv_critical, tlv_typ_critical, GenericTlv, Tlv};
9pub use varnum::VarNum;
10
11mod error;
12mod tlv;
13mod varnum;
14
15/// Common result type for library functions
16pub type Result<T> = std::result::Result<T, TlvError>;
17
18/// Encode data in TLV format
19///
20/// The value is a TLV record, or part of one
21pub trait TlvEncode {
22    /// Encode the value as a TLV record or part of one
23    fn encode(&self) -> Bytes;
24    /// The size of the encoded data in bytes
25    fn size(&self) -> usize;
26}
27
28/// Decode data in TLV format
29///
30/// The value is a TLV record, or part of one
31pub trait TlvDecode: Sized {
32    /// Decode the value from a `bytes::Buf`
33    ///
34    /// The internal cursor of `bytes` must be advanced to point behind the used data
35    /// The implementation may choose to consume a part, or the entire buffer. If the length of the
36    /// data is known at the call site, restrict the size of `bytes` to prevent the entire buffer
37    /// being consumed.
38    fn decode(bytes: &mut Bytes) -> Result<Self>;
39}
40
41/// A non-negative integer, not encoded using `VarNum`
42#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
43pub enum NonNegativeInteger {
44    /// An 8-bit integer
45    U8(u8),
46    /// A 16-bit integer
47    U16(u16),
48    /// A 32-bit integer
49    U32(u32),
50    /// A 64-bit integer
51    U64(u64),
52}
53
54impl Default for NonNegativeInteger {
55    fn default() -> Self {
56        NonNegativeInteger::U8(0)
57    }
58}
59
60/// Advance `bytes` until a valid TLV record of type `T` is found
61///
62/// In `error_on_critical` is true, any unexpected critical TLV records of a different type will lead to an error.
63/// Unexpected non-critical TLV records will always be ignored.
64pub fn find_tlv<T: Tlv>(bytes: &mut Bytes, error_on_critical: bool) -> Result<()> {
65    let mut cur = bytes.clone();
66
67    while cur.has_remaining() {
68        let found_typ = VarNum::decode(&mut cur)?;
69        if usize::from(found_typ) == T::TYP {
70            return Ok(());
71        }
72
73        // Wrong type
74        if error_on_critical && tlv_typ_critical(found_typ.into()) {
75            return Err(TlvError::TypeMismatch {
76                expected: T::TYP,
77                found: found_typ.into(),
78            });
79        }
80
81        // non-critical
82        let length = VarNum::decode(&mut cur)?;
83        cur.advance(length.into());
84        bytes.advance(bytes.remaining() - cur.remaining());
85    }
86
87    Err(TlvError::UnexpectedEndOfStream)
88}
89
90impl TlvEncode for NonNegativeInteger {
91    fn encode(&self) -> Bytes {
92        let mut bytes = BytesMut::with_capacity(self.size());
93        match *self {
94            NonNegativeInteger::U8(n) => {
95                bytes.put_u8(n);
96            }
97            NonNegativeInteger::U16(n) => {
98                bytes.put_u16(n);
99            }
100            NonNegativeInteger::U32(n) => {
101                bytes.put_u32(n);
102            }
103            NonNegativeInteger::U64(n) => {
104                bytes.put_u64(n);
105            }
106        }
107        bytes.freeze()
108    }
109
110    fn size(&self) -> usize {
111        match *self {
112            NonNegativeInteger::U8(_) => 1,
113            NonNegativeInteger::U16(_) => 2,
114            NonNegativeInteger::U32(_) => 4,
115            NonNegativeInteger::U64(_) => 8,
116        }
117    }
118}
119
120impl TlvDecode for NonNegativeInteger {
121    fn decode(bytes: &mut Bytes) -> Result<Self> {
122        match bytes.remaining() {
123            1 => Ok(Self::U8(bytes.get_u8())),
124            2 => Ok(Self::U16(bytes.get_u16())),
125            4 => Ok(Self::U32(bytes.get_u32())),
126            8 => Ok(Self::U64(bytes.get_u64())),
127            _ => Err(TlvError::UnexpectedLength),
128        }
129    }
130}
131
132impl From<u8> for NonNegativeInteger {
133    fn from(value: u8) -> Self {
134        Self::new(value as u64)
135    }
136}
137
138impl From<u16> for NonNegativeInteger {
139    fn from(value: u16) -> Self {
140        Self::new(value as u64)
141    }
142}
143
144impl From<u32> for NonNegativeInteger {
145    fn from(value: u32) -> Self {
146        Self::new(value as u64)
147    }
148}
149
150impl From<u64> for NonNegativeInteger {
151    fn from(value: u64) -> Self {
152        Self::new(value as u64)
153    }
154}
155
156impl From<usize> for NonNegativeInteger {
157    fn from(value: usize) -> Self {
158        Self::new(value as u64)
159    }
160}
161
162impl From<NonNegativeInteger> for u64 {
163    fn from(value: NonNegativeInteger) -> Self {
164        match value {
165            NonNegativeInteger::U8(n) => n as u64,
166            NonNegativeInteger::U16(n) => n as u64,
167            NonNegativeInteger::U32(n) => n as u64,
168            NonNegativeInteger::U64(n) => n,
169        }
170    }
171}
172
173impl NonNegativeInteger {
174    /// Create a `NonNegativeInteger` using the smallest possible representation to fit the given
175    /// value
176    pub const fn new(value: u64) -> Self {
177        if value <= 0xFF {
178            NonNegativeInteger::U8(value as u8)
179        } else if value <= 0xFFFF {
180            NonNegativeInteger::U16(value as u16)
181        } else if value <= 0xFFFF_FFFF {
182            NonNegativeInteger::U32(value as u32)
183        } else {
184            NonNegativeInteger::U64(value as u64)
185        }
186    }
187
188    /// Return the value of this `NonNegativeInteger` as u64
189    pub const fn as_u64(&self) -> u64 {
190        match *self {
191            NonNegativeInteger::U8(value) => value as u64,
192            NonNegativeInteger::U16(value) => value as u64,
193            NonNegativeInteger::U32(value) => value as u64,
194            NonNegativeInteger::U64(value) => value as u64,
195        }
196    }
197
198    /// Return the value of this `NonNegativeInteger` as usize
199    pub const fn as_usize(&self) -> usize {
200        match *self {
201            NonNegativeInteger::U8(value) => value as usize,
202            NonNegativeInteger::U16(value) => value as usize,
203            NonNegativeInteger::U32(value) => value as usize,
204            NonNegativeInteger::U64(value) => value as usize,
205        }
206    }
207}
208
209impl std::fmt::Display for NonNegativeInteger {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        u64::from(*self).fmt(f)
212    }
213}
214
215impl TlvEncode for Bytes {
216    fn encode(&self) -> Bytes {
217        self.clone()
218    }
219
220    fn size(&self) -> usize {
221        self.len()
222    }
223}
224
225impl TlvDecode for Bytes {
226    fn decode(bytes: &mut Bytes) -> Result<Self> {
227        Ok(bytes.copy_to_bytes(bytes.remaining()))
228    }
229}
230
231impl<const N: usize> TlvEncode for [u8; N] {
232    fn encode(&self) -> Bytes {
233        Bytes::copy_from_slice(&self[..])
234    }
235
236    fn size(&self) -> usize {
237        N
238    }
239}
240
241impl<const N: usize> TlvDecode for [u8; N] {
242    fn decode(bytes: &mut Bytes) -> Result<Self> {
243        if bytes.remaining() < N {
244            return Err(TlvError::UnexpectedEndOfStream);
245        }
246        let mut buf = [0; N];
247        bytes.copy_to_slice(&mut buf);
248        Ok(buf)
249    }
250}
251
252impl TlvEncode for u8 {
253    fn encode(&self) -> Bytes {
254        Bytes::copy_from_slice(&[*self][..])
255    }
256
257    fn size(&self) -> usize {
258        1
259    }
260}
261
262impl TlvDecode for u8 {
263    fn decode(bytes: &mut Bytes) -> Result<Self> {
264        if bytes.remaining() < 1 {
265            return Err(TlvError::UnexpectedEndOfStream);
266        }
267        Ok(bytes.get_u8())
268    }
269}
270
271impl TlvEncode for i8 {
272    fn encode(&self) -> Bytes {
273        Bytes::copy_from_slice(&[*self as u8][..])
274    }
275
276    fn size(&self) -> usize {
277        1
278    }
279}
280
281impl TlvDecode for i8 {
282    fn decode(bytes: &mut Bytes) -> Result<Self> {
283        if bytes.remaining() < 1 {
284            return Err(TlvError::UnexpectedEndOfStream);
285        }
286        Ok(bytes.get_i8())
287    }
288}
289
290impl TlvEncode for u16 {
291    fn encode(&self) -> Bytes {
292        let mut bytes = BytesMut::with_capacity(self.size());
293        bytes.put_u16(*self);
294        bytes.freeze()
295    }
296
297    fn size(&self) -> usize {
298        2
299    }
300}
301
302impl TlvDecode for u16 {
303    fn decode(bytes: &mut Bytes) -> Result<Self> {
304        if bytes.remaining() < 2 {
305            return Err(TlvError::UnexpectedEndOfStream);
306        }
307        Ok(bytes.get_u16())
308    }
309}
310
311impl TlvEncode for i16 {
312    fn encode(&self) -> Bytes {
313        let mut bytes = BytesMut::with_capacity(self.size());
314        bytes.put_i16(*self);
315        bytes.freeze()
316    }
317
318    fn size(&self) -> usize {
319        2
320    }
321}
322
323impl TlvDecode for i16 {
324    fn decode(bytes: &mut Bytes) -> Result<Self> {
325        if bytes.remaining() < 2 {
326            return Err(TlvError::UnexpectedEndOfStream);
327        }
328        Ok(bytes.get_i16())
329    }
330}
331
332impl TlvEncode for u32 {
333    fn encode(&self) -> Bytes {
334        let mut bytes = BytesMut::with_capacity(self.size());
335        bytes.put_u32(*self);
336        bytes.freeze()
337    }
338
339    fn size(&self) -> usize {
340        4
341    }
342}
343
344impl TlvDecode for u32 {
345    fn decode(bytes: &mut Bytes) -> Result<Self> {
346        if bytes.remaining() < 4 {
347            return Err(TlvError::UnexpectedEndOfStream);
348        }
349        Ok(bytes.get_u32())
350    }
351}
352
353impl TlvEncode for i32 {
354    fn encode(&self) -> Bytes {
355        let mut bytes = BytesMut::with_capacity(self.size());
356        bytes.put_i32(*self);
357        bytes.freeze()
358    }
359
360    fn size(&self) -> usize {
361        4
362    }
363}
364
365impl TlvDecode for i32 {
366    fn decode(bytes: &mut Bytes) -> Result<Self> {
367        if bytes.remaining() < 4 {
368            return Err(TlvError::UnexpectedEndOfStream);
369        }
370        Ok(bytes.get_i32())
371    }
372}
373
374impl TlvEncode for u64 {
375    fn encode(&self) -> Bytes {
376        let mut bytes = BytesMut::with_capacity(self.size());
377        bytes.put_u64(*self);
378        bytes.freeze()
379    }
380
381    fn size(&self) -> usize {
382        8
383    }
384}
385
386impl TlvDecode for u64 {
387    fn decode(bytes: &mut Bytes) -> Result<Self> {
388        if bytes.remaining() < 8 {
389            return Err(TlvError::UnexpectedEndOfStream);
390        }
391        Ok(bytes.get_u64())
392    }
393}
394
395impl TlvEncode for i64 {
396    fn encode(&self) -> Bytes {
397        let mut bytes = BytesMut::with_capacity(self.size());
398        bytes.put_i64(*self);
399        bytes.freeze()
400    }
401
402    fn size(&self) -> usize {
403        8
404    }
405}
406
407impl TlvDecode for i64 {
408    fn decode(bytes: &mut Bytes) -> Result<Self> {
409        if bytes.remaining() < 8 {
410            return Err(TlvError::UnexpectedEndOfStream);
411        }
412        Ok(bytes.get_i64())
413    }
414}
415
416impl TlvEncode for u128 {
417    fn encode(&self) -> Bytes {
418        let mut bytes = BytesMut::with_capacity(self.size());
419        bytes.put_u128(*self);
420        bytes.freeze()
421    }
422
423    fn size(&self) -> usize {
424        16
425    }
426}
427
428impl TlvDecode for u128 {
429    fn decode(bytes: &mut Bytes) -> Result<Self> {
430        if bytes.remaining() < 16 {
431            return Err(TlvError::UnexpectedEndOfStream);
432        }
433        Ok(bytes.get_u128())
434    }
435}
436
437impl TlvEncode for i128 {
438    fn encode(&self) -> Bytes {
439        let mut bytes = BytesMut::with_capacity(self.size());
440        bytes.put_i128(*self);
441        bytes.freeze()
442    }
443
444    fn size(&self) -> usize {
445        16
446    }
447}
448
449impl TlvDecode for i128 {
450    fn decode(bytes: &mut Bytes) -> Result<Self> {
451        if bytes.remaining() < 16 {
452            return Err(TlvError::UnexpectedEndOfStream);
453        }
454        Ok(bytes.get_i128())
455    }
456}
457
458impl<T: TlvEncode> TlvEncode for Vec<T> {
459    fn encode(&self) -> Bytes {
460        let mut bytes = BytesMut::with_capacity(self.size());
461        for item in self {
462            bytes.put(item.encode());
463        }
464        bytes.freeze()
465    }
466
467    fn size(&self) -> usize {
468        self.iter()
469            .map(TlvEncode::size)
470            .reduce(|x, y| x + y)
471            .unwrap_or(0)
472    }
473}
474
475impl<T: TlvDecode> TlvDecode for Vec<T> {
476    fn decode(bytes: &mut Bytes) -> Result<Self> {
477        let mut ret = Vec::new();
478        while bytes.has_remaining() {
479            let remaining = bytes.remaining();
480            let mut bytes_clone = bytes.clone();
481            let t = T::decode(&mut bytes_clone);
482            match t {
483                Ok(t) => {
484                    ret.push(t);
485                    bytes.advance(remaining - bytes_clone.remaining());
486                }
487                Err(TlvError::TypeMismatch {
488                    expected: _,
489                    found: _,
490                }) => {
491                    // Different TLV than what we expected - Vec ended
492                    return Ok(ret);
493                }
494                // End of stream should not be possible unless the data is malformed
495                Err(e) => return Err(e),
496            }
497        }
498        Ok(ret)
499    }
500}
501
502impl<T: TlvEncode> TlvEncode for Option<T> {
503    fn encode(&self) -> Bytes {
504        match self {
505            None => Bytes::new(),
506            Some(value) => value.encode(),
507        }
508    }
509
510    fn size(&self) -> usize {
511        match self {
512            None => 0,
513            Some(value) => value.size(),
514        }
515    }
516}
517
518impl<T: TlvDecode> TlvDecode for Option<T> {
519    fn decode(bytes: &mut Bytes) -> Result<Self> {
520        let remaining = bytes.remaining();
521        let mut bytes_clone = bytes.clone();
522        let t = T::decode(&mut bytes_clone);
523        match t {
524            Ok(value) => {
525                bytes.advance(remaining - bytes_clone.remaining());
526                Ok(Some(value))
527            }
528            // Different Type - probably what is next to parse
529            Err(TlvError::TypeMismatch {
530                expected: _,
531                found: _,
532            }) => Ok(None),
533            // End of stream - no data here
534            Err(TlvError::UnexpectedEndOfStream) => Ok(None),
535            Err(e) => Err(e),
536        }
537    }
538}
539
540impl TlvEncode for () {
541    fn encode(&self) -> Bytes {
542        Bytes::new()
543    }
544
545    fn size(&self) -> usize {
546        0
547    }
548}
549
550impl TlvDecode for () {
551    fn decode(_: &mut Bytes) -> Result<Self> {
552        Ok(())
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    #[derive(Debug, Eq, PartialEq, Tlv)]
561    #[tlv(8, internal = true)]
562    pub(crate) struct GenericNameComponent {
563        pub(crate) name: Bytes,
564    }
565
566    #[derive(Debug, Tlv, PartialEq)]
567    #[tlv(7, internal = true)]
568    struct Name {
569        components: Vec<GenericNameComponent>,
570    }
571
572    #[derive(Debug, PartialEq, Eq, Tlv)]
573    #[tlv(33, internal = true)]
574    struct CanBePrefix;
575
576    #[derive(Debug, PartialEq, Eq, Tlv)]
577    #[tlv(129, internal = true)]
578    struct VecPartial {
579        components: Vec<GenericNameComponent>,
580        can_be_prefix: CanBePrefix,
581    }
582
583    #[derive(Tlv)]
584    #[tlv(143, internal = true)]
585    struct HasOption {
586        component: Option<GenericNameComponent>,
587        can_be_prefix: CanBePrefix,
588    }
589
590    #[derive(Tlv)]
591    #[tlv(8, internal = true)]
592    struct TupleStruct(Bytes);
593
594    #[derive(Debug, Tlv)]
595    #[tlv(0, internal = true)]
596    enum EnumTest {
597        GenericNameComponent(GenericNameComponent),
598        CanBePrefix(CanBePrefix),
599    }
600
601    #[derive(Debug, Tlv)]
602    #[tlv(130, internal = true)]
603    struct HasGeneric<T> {
604        data: T,
605    }
606
607    #[derive(Debug, Tlv)]
608    #[tlv(0, internal = true)]
609    struct Sequence {
610        name1: Name,
611        name2: Name,
612    }
613
614    #[test]
615    fn generic_name_component() {
616        let mut data = Bytes::from(&[8, 5, b'h', b'e', b'l', b'l', b'o', 255, 255, 255][..]);
617        let component = GenericNameComponent::decode(&mut data).unwrap();
618
619        assert_eq!(data.remaining(), 3);
620        assert_eq!(component.name, &b"hello"[..]);
621    }
622
623    #[test]
624    fn vec_partial() {
625        let mut data = Bytes::from(
626            &[
627                129, 16, 8, 5, b'h', b'e', b'l', b'l', b'o', 8, 5, b'w', b'o', b'r', b'l', b'd',
628                33, 0, 255, 255, 255,
629            ][..],
630        );
631
632        let partial = VecPartial::decode(&mut data).unwrap();
633        assert_eq!(data.remaining(), 3);
634        assert_eq!(partial.components.len(), 2);
635        assert_eq!(partial.components[0].name, &b"hello"[..]);
636        assert_eq!(partial.components[1].name, &b"world"[..]);
637        assert_eq!(partial.can_be_prefix, CanBePrefix);
638    }
639
640    #[test]
641    fn option_some() {
642        let mut data = Bytes::from(
643            &[
644                143, 9, 8, 5, b'h', b'e', b'l', b'l', b'o', 33, 0, 255, 255, 255,
645            ][..],
646        );
647
648        let option = HasOption::decode(&mut data).unwrap();
649        assert_eq!(data.remaining(), 3);
650        assert!(option.component.is_some());
651        assert_eq!(option.component.unwrap().name, &b"hello"[..]);
652    }
653
654    #[test]
655    fn option_none() {
656        let mut data = Bytes::from(&[143, 2, 33, 0, 255, 255, 255][..]);
657
658        let option = HasOption::decode(&mut data).unwrap();
659        assert_eq!(data.remaining(), 3);
660        assert!(option.component.is_none());
661    }
662
663    #[test]
664    fn unknown_critical() {
665        let mut data = Bytes::from(
666            &[
667                129, 18, 8, 5, b'h', b'e', b'l', b'l', b'o', 8, 5, b'w', b'o', b'r', b'l', b'd',
668                127, 0, 33, 0, 255, 255, 255,
669            ][..],
670        );
671
672        let partial = VecPartial::decode(&mut data);
673        assert_eq!(data.remaining(), 3);
674        assert!(partial.is_err());
675        assert_eq!(
676            partial.unwrap_err(),
677            TlvError::TypeMismatch {
678                expected: 33,
679                found: 127
680            }
681        );
682    }
683
684    #[test]
685    fn unknown_non_critical() {
686        let mut data = Bytes::from(
687            &[
688                129, 18, 8, 5, b'h', b'e', b'l', b'l', b'o', 8, 5, b'w', b'o', b'r', b'l', b'd',
689                126, 0, 33, 0, 255, 255, 255,
690            ][..],
691        );
692
693        let partial = VecPartial::decode(&mut data).unwrap();
694        assert_eq!(data.remaining(), 3);
695        assert_eq!(partial.components.len(), 2);
696        assert_eq!(partial.components[0].name, &b"hello"[..]);
697        assert_eq!(partial.components[1].name, &b"world"[..]);
698        assert_eq!(partial.can_be_prefix, CanBePrefix);
699    }
700
701    #[test]
702    fn tuple_struct() {
703        let mut data = Bytes::from(&[8, 5, b'h', b'e', b'l', b'l', b'o', 255, 255, 255][..]);
704        let initial_data = data.clone();
705        let component = TupleStruct::decode(&mut data).unwrap();
706
707        assert_eq!(data.remaining(), 3);
708        assert_eq!(component.0, &b"hello"[..]);
709
710        let new_data = component.encode();
711        assert_eq!(new_data, initial_data[0..7]);
712    }
713
714    #[test]
715    fn enum_test() {
716        let mut data = Bytes::from(&[8, 5, b'h', b'e', b'l', b'l', b'o', 255, 255, 255][..]);
717        let initial_data = data.clone();
718        let etest = EnumTest::decode(&mut data).unwrap();
719
720        assert_eq!(data.remaining(), 3);
721        match etest {
722            EnumTest::GenericNameComponent(ref component) => {
723                assert_eq!(component.name, &b"hello"[..]);
724            }
725            _ => panic!("Wrong variant"),
726        }
727
728        let new_data = etest.encode();
729        assert_eq!(new_data, initial_data[0..7]);
730    }
731
732    #[test]
733    fn overlength() {
734        // Inner TLV escapes the outer TLV
735        let mut data = Bytes::from(&[7, 7, 8, 6, b'h', b'e', b'l', b'l', b'o', 255, 255][..]);
736
737        let name = Name::decode(&mut data);
738        assert!(name.is_err());
739        assert_eq!(name.unwrap_err(), TlvError::UnexpectedEndOfStream);
740    }
741
742    #[test]
743    fn generic() {
744        let mut data = Bytes::from(&[130, 3, 1, 2, 3][..]);
745
746        let decoded = <HasGeneric<Bytes>>::decode(&mut data).unwrap();
747        assert_eq!(decoded.data, &[1, 2, 3][..]);
748    }
749
750    #[test]
751    fn sequence() {
752        let mut data = Bytes::from(
753            &[
754                7, 11, 8, 5, b'h', b'e', b'l', b'l', b'o', 8, 2, b'a', b'b', 7, 5, 8, 3, b'a',
755                b's', b'd',
756            ][..],
757        );
758
759        let sequence = Sequence::decode(&mut data).unwrap();
760        assert_eq!(
761            sequence.name1,
762            Name {
763                components: vec![
764                    GenericNameComponent {
765                        name: Bytes::from_static(b"hello")
766                    },
767                    GenericNameComponent {
768                        name: Bytes::from_static(b"ab")
769                    },
770                ]
771            }
772        );
773        assert_eq!(
774            sequence.name2,
775            Name {
776                components: vec![GenericNameComponent {
777                    name: Bytes::from_static(b"asd")
778                },]
779            }
780        );
781    }
782}