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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! Partial implementation of the IEEE 802.15.4 Frame
//!
//! The main type in this module is [Frame], a type that represents an IEEE
//! 802.15.4 MAC frame. The other types in this module are supporting types
//! that are either part of [Frame] or are required to support its API.
//!
//! [Frame]: struct.Frame.html

// TODO:
// - change &mut [u8] -> bytes::BufMut
// - change &[u8] => bytes::Buf
// - remove one variant enums

use crate::mac::beacon::Beacon;
use crate::mac::command::Command;

mod frame_control;
pub mod header;
pub mod security;
use byte::{ctx::Bytes, BytesExt, TryRead, TryWrite, LE};
use ccm::aead::generic_array::typenum::consts::U16;
use cipher::{BlockCipher, BlockEncrypt, NewBlockCipher};
use header::FrameType;
pub use header::Header;

use self::security::{
    default::Unimplemented, DeviceDescriptorLookup, KeyDescriptorLookup,
    SecurityContext, SecurityError,
};

/// An IEEE 802.15.4 MAC frame
///
/// Represents a MAC frame. Can be used to [decode] a frame from bytes, or
/// [encode] a frame to bytes.
///
///
/// # Decode Errors
///
/// This function returns an error, if the bytes either don't encode a valid
/// IEEE 802.15.4 frame, or encode a frame that is not fully supported by
/// this implementation. Please refer to [`DecodeError`] for details.
///
/// # Example
///
/// ``` rust
/// use ieee802154::mac::{
///     Frame,
///     Address,
///     ShortAddress,
///     FrameType,
///     FooterMode,
///     PanId,
///     FrameSerDesContext,
/// };
/// use byte::BytesExt;
///
/// # fn main() -> Result<(), ::ieee802154::mac::frame::DecodeError> {
/// // Construct a simple MAC frame. The CRC checksum (the last 2 bytes) is
/// // invalid, for the sake of convenience.
/// let bytes = [
///     0x01u8, 0x98,           // frame control
///     0x00,                   // sequence number
///     0x12, 0x34, 0x56, 0x78, // PAN identifier and address of destination
///     0x12, 0x34, 0x9a, 0xbc, // PAN identifier and address of source
///     0xde, 0xf0,             // payload
///     0x12, 0x34,             // payload
/// ];
///
/// let frame: Frame = bytes.read_with(&mut 0, FooterMode::Explicit).unwrap();
/// let header = frame.header;
///
/// assert_eq!(frame.header.seq,       0x00);
/// assert_eq!(header.frame_type,      FrameType::Data);
/// assert_eq!(header.has_security(),  false);
/// assert_eq!(header.frame_pending,   false);
/// assert_eq!(header.ack_request,     false);
/// assert_eq!(header.pan_id_compress, false);
///
/// assert_eq!(
///     frame.header.destination,
///     Some(Address::Short(PanId(0x3412), ShortAddress(0x7856)))
/// );
/// assert_eq!(
///     frame.header.source,
///     Some(Address::Short(PanId(0x3412), ShortAddress(0xbc9a)))
/// );
///
/// assert_eq!(frame.payload, &[0xde, 0xf0]);
///
/// assert_eq!(frame.footer, [0x12, 0x34]);
/// #
/// # Ok(())
/// # }
/// ```
/// Encodes the frame into a buffer
///
/// # Example
///
/// ## allocation allowed
/// ``` rust
/// use ieee802154::mac::{
///   Frame,
///   FrameContent,
///   FooterMode,
///   Address,
///   ShortAddress,
///   FrameType,
///   FrameVersion,
///   Header,
///   PanId,
///   FrameSerDesContext,
/// };
/// use byte::BytesExt;
///
/// let frame = Frame {
///     header: Header {
///         ie_present:      false,
///         seq_no_suppress: false,
///         frame_type:      FrameType::Data,
///         frame_pending:   false,
///         ack_request:     false,
///         pan_id_compress: false,
///         version:         FrameVersion::Ieee802154_2006,
///
///         seq:             0x00,
///         destination: Some(Address::Short(PanId(0x1234), ShortAddress(0x5678))),
///         source:      Some(Address::Short(PanId(0x1234), ShortAddress(0x9abc))),
///         auxiliary_security_header: None,
///     },
///     content: FrameContent::Data,
///     payload: &[0xde, 0xf0],
///     footer:  [0x12, 0x34]
/// };
///
/// // Work also with `let mut bytes = Vec::new()`;
/// let mut bytes = [0u8; 32];
/// let mut len = 0usize;
///
/// bytes.write_with(&mut len, frame, &mut FrameSerDesContext::no_security(FooterMode::Explicit)).unwrap();
///
/// let expected_bytes = [
///     0x01, 0x98,             // frame control
///     0x00,                   // sequence number
///     0x34, 0x12, 0x78, 0x56, // PAN identifier and address of destination
///     0x34, 0x12, 0xbc, 0x9a, // PAN identifier and address of source
///     0xde, 0xf0,             // payload
///     0x12, 0x34              // footer
/// ];
/// assert_eq!(bytes[..len], expected_bytes);
/// ```
///
/// [decode]: #method.try_read
/// [encode]: #method.try_write
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Frame<'p> {
    /// Header
    pub header: Header,

    /// Content
    pub content: FrameContent,

    /// Payload
    pub payload: &'p [u8],

    /// Footer
    ///
    /// This is a 2-byte CRC checksum.
    ///
    /// When creating an instance of this struct for encoding, you don't
    /// necessarily need to write an actual CRC checksum here. [`Frame::try_write`]
    /// can omit writing this checksum, for example if the transceiver hardware
    /// automatically adds the checksum for you.
    pub footer: [u8; 2],
}

/// A context that is used for serializing and deserializing frames, which also
/// stores the frame counter
pub struct FrameSerDesContext<'a, AEADBLKCIPH, KEYDESCLO>
where
    AEADBLKCIPH: NewBlockCipher + BlockCipher<BlockSize = U16>,
    KEYDESCLO: KeyDescriptorLookup<AEADBLKCIPH::KeySize>,
{
    /// The footer mode to use when handling frames
    footer_mode: FooterMode,
    /// The security context for handling frames (if any)
    security_ctx: Option<&'a mut SecurityContext<AEADBLKCIPH, KEYDESCLO>>,
}

impl<'a, AEADBLKCIPH, KEYDESCLO> FrameSerDesContext<'a, AEADBLKCIPH, KEYDESCLO>
where
    AEADBLKCIPH: NewBlockCipher + BlockCipher<BlockSize = U16>,
    KEYDESCLO: KeyDescriptorLookup<AEADBLKCIPH::KeySize>,
{
    /// Create a new frame serialization/deserialization context with the specified footer mode
    /// and security context
    pub fn new(
        mode: FooterMode,
        security_ctx: Option<&'a mut SecurityContext<AEADBLKCIPH, KEYDESCLO>>,
    ) -> Self {
        FrameSerDesContext {
            footer_mode: mode,
            security_ctx,
        }
    }
}

impl FrameSerDesContext<'_, Unimplemented, Unimplemented> {
    /// Create a new frame serialization/deserialization context with the specified footer mode,
    /// that does not facilitate any security functionality
    pub fn no_security(mode: FooterMode) -> Self {
        FrameSerDesContext {
            footer_mode: mode,
            security_ctx: None,
        }
    }
}

impl<AEADBLKCIPH, KEYDESCLO>
    TryWrite<&mut FrameSerDesContext<'_, AEADBLKCIPH, KEYDESCLO>> for Frame<'_>
where
    AEADBLKCIPH: NewBlockCipher + BlockCipher<BlockSize = U16> + BlockEncrypt,
    KEYDESCLO: KeyDescriptorLookup<AEADBLKCIPH::KeySize>,
{
    fn try_write(
        self,
        bytes: &mut [u8],
        context: &mut FrameSerDesContext<AEADBLKCIPH, KEYDESCLO>,
    ) -> byte::Result<usize> {
        let mode = &context.footer_mode;
        let offset = &mut 0;

        bytes.write_with(offset, self.header, &context.security_ctx)?;
        bytes.write(offset, self.content)?;

        let mut security_enabled = false;

        if let Some(ctx) = context.security_ctx.as_mut() {
            let write_secured = security::secure_frame(
                self,
                ctx,
                context.footer_mode,
                &mut bytes[*offset..],
            );
            match write_secured {
                Ok(len) => {
                    security_enabled = true;
                    *offset += len
                }
                Err(e) => match e {
                    SecurityError::SecurityNotEnabled => {}
                    _ => return Err(e)?,
                },
            }
        }

        if !security_enabled {
            bytes.write(offset, self.payload.as_ref())?;
        }

        match mode {
            FooterMode::None => {}
            // TODO: recalculate the footer after encryption?
            FooterMode::Explicit => bytes.write(offset, &self.footer[..])?,
        }

        Ok(*offset)
    }
}

impl<'a> Frame<'a> {
    /// Try to read a frame. If the frame is secured, it will be unsecured
    ///
    /// Currently, this function does not support the explicit footer mode,
    /// as the FCS has to be calculated over the payload before it is unsecured,
    /// which isn't implemented yet
    ///
    /// Use [`FrameSerDesContext::no_security`] and/or [`Unimplemented`] if you
    /// do not want to use any security, or simply [`Frame::try_read`]
    pub fn try_read_and_unsecure<AEADBLKCIPH, KEYDESCLO, DEVDESCLO>(
        buf: &'a mut [u8],
        ctx: &mut FrameSerDesContext<'_, AEADBLKCIPH, KEYDESCLO>,
        dev_desc_lo: &mut DEVDESCLO,
    ) -> Result<(Frame<'a>, usize), SecurityError>
    where
        AEADBLKCIPH:
            NewBlockCipher + BlockCipher<BlockSize = U16> + BlockEncrypt,
        KEYDESCLO: KeyDescriptorLookup<AEADBLKCIPH::KeySize>,
        DEVDESCLO: DeviceDescriptorLookup,
    {
        let offset = &mut 0;
        let header: Header = buf.read(offset)?;
        let content = buf.read_with(offset, &header)?;

        let mut tag_size = 0;

        if header.has_security() {
            if let Some(sec_ctx) = ctx.security_ctx.as_mut() {
                tag_size = match security::unsecure_frame(
                    &header,
                    &mut buf[*offset..],
                    sec_ctx,
                    ctx.footer_mode,
                    dev_desc_lo,
                ) {
                    Ok(size) => size,
                    Err(e) => match e {
                        SecurityError::SecurityNotEnabled => 0,
                        _ => return Err(e),
                    },
                };
            } else {
                return Err(SecurityError::InvalidSecContext);
            }
        }
        let payload =
            buf.read_with(offset, Bytes::Len(buf.len() - *offset - tag_size))?;

        let frame = Frame {
            header,
            content,
            payload,
            footer: [0, 0],
        };

        Ok((frame, *offset))
    }
}

impl<'a> TryRead<'a, FooterMode> for Frame<'a> {
    /// Try to read a frame
    ///
    /// Frames that have security enabled can not be processed by this function, and an
    /// error will be returned if the frame contained in `bytes` does have it enabled.
    ///
    /// If you expect to receive secured frames, use [`Frame::try_read_and_unsecure`] instead,
    fn try_read(
        bytes: &'a [u8],
        mode: FooterMode,
    ) -> byte::Result<(Self, usize)> {
        let offset = &mut 0;
        let header: Header = bytes.read(offset)?;
        let content = bytes.read_with(offset, &header)?;

        if header.has_security() {
            return Err(DecodeError::SecurityEnabled)?;
        }

        let (payload, footer) = match mode {
            FooterMode::None => (
                bytes.read_with(offset, Bytes::Len(bytes.len() - *offset))?,
                0u16,
            ),
            FooterMode::Explicit => (
                bytes
                    .read_with(offset, Bytes::Len(bytes.len() - *offset - 2))?,
                bytes.read_with(offset, LE)?,
            ),
        };

        let frame = Frame {
            header,
            content,
            payload,
            footer: footer.to_le_bytes(),
        };
        Ok((frame, *offset))
    }
}

///
/// Controls whether the footer is read/written with the frame
///
/// Eventually, this should support three options:
/// 1. Don't read or write the footer
/// 2. Calculate the 2-byte CRC checksum and write that as the footer or check against read value
/// 3. Read into or write the footer from the `footer` field
///
/// For now, only 1 and 3 are supported.
///
/// [`Frame::try_write`](Frame::try_write)
#[derive(Clone, Copy)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FooterMode {
    /// Don't read/write the footer
    None,
    /// Read into or write the footer from the `footer` field
    Explicit,
}

impl Default for FooterMode {
    fn default() -> Self {
        Self::None
    }
}

/// Content of a frame
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum FrameContent {
    /// Beacon frame content
    Beacon(Beacon),
    /// Data frame
    Data,
    /// Acknowledgement frame
    Acknowledgement,
    /// MAC command frame
    Command(Command),
    /// Multipurpose frame
    Multipurpose,

    /// Fragment of Fragment Ack frame
    FragOrFragAck,

    /// Extended frame
    Extended,
}

impl TryWrite for FrameContent {
    fn try_write(self, bytes: &mut [u8], _ctx: ()) -> byte::Result<usize> {
        let offset = &mut 0;
        match self {
            FrameContent::Beacon(beacon) => bytes.write(offset, beacon)?,
            FrameContent::Command(command) => bytes.write(offset, command)?,
            _ => (),
        };
        Ok(*offset)
    }
}

impl TryRead<'_, &Header> for FrameContent {
    fn try_read(bytes: &[u8], header: &Header) -> byte::Result<(Self, usize)> {
        let offset = &mut 0;
        Ok((
            match header.frame_type {
                FrameType::Beacon => FrameContent::Beacon(bytes.read(offset)?),
                FrameType::Data => FrameContent::Data,
                FrameType::Acknowledgement => FrameContent::Acknowledgement,
                FrameType::MacCommand => {
                    FrameContent::Command(bytes.read(offset)?)
                }
                FrameType::Multipurpose => FrameContent::Multipurpose,
                FrameType::FragOrFragAck => FrameContent::FragOrFragAck,
                FrameType::Extended => FrameContent::Extended,
            },
            *offset,
        ))
    }
}

/// Signals an error that occured while decoding bytes
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DecodeError {
    /// Buffer does not contain enough bytes
    NotEnoughBytes,

    /// The frame type is invalid
    InvalidFrameType(u8),

    /// Security is enabled on the frame, and `try_read` is called. [`Frame::try_read_and_unsecure`] should be called instead.
    SecurityEnabled,

    /// The frame's address mode is invalid
    InvalidAddressMode(u8),

    /// The frame's version is invalid or not supported
    InvalidFrameVersion(u8),

    /// The auxiliary security header's security level is invalid
    InvalidSecurityLevel(u8),

    /// The auxiliary security header's key identifier mode is invalid
    InvalidKeyIdentifierMode(u8),

    /// Security is enabled, but no Securty Context is provided
    MissingSecurityCtx,

    /// Security is enabled, but no Auxiliary Security Header is present
    AuxSecHeaderAbsent,

    /// The data stream contains an invalid value
    InvalidValue,
}

impl From<DecodeError> for byte::Error {
    fn from(e: DecodeError) -> Self {
        match e {
            DecodeError::NotEnoughBytes => byte::Error::Incomplete,
            DecodeError::InvalidFrameType(_) => byte::Error::BadInput {
                err: "InvalidFrameType",
            },
            DecodeError::InvalidAddressMode(_) => byte::Error::BadInput {
                err: "InvalidAddressMode",
            },
            DecodeError::InvalidFrameVersion(_) => byte::Error::BadInput {
                err: "InvalidFrameVersion",
            },
            DecodeError::InvalidValue => byte::Error::BadInput {
                err: "InvalidValue",
            },
            DecodeError::InvalidSecurityLevel(_) => byte::Error::BadInput {
                err: "InvalidSecurityLevel",
            },
            DecodeError::InvalidKeyIdentifierMode(_) => byte::Error::BadInput {
                err: "InvalidKeyIdentifierMode",
            },
            DecodeError::MissingSecurityCtx => byte::Error::BadInput {
                err: "MissingSecurityCtx",
            },
            DecodeError::AuxSecHeaderAbsent => byte::Error::BadInput {
                err: "AuxSecHeaderAbsent",
            },
            DecodeError::SecurityEnabled => byte::Error::BadInput {
                err: "SecurityEnabled (use Frame::try_read_and_unsecure)",
            },
        }
    }
}

/// Errors that can occur while securing or unsecuring a frame
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum EncodeError {
    /// Something went wrong while writing a frame's bytes to the destination
    WriteError,
    /// Security is enabled but no security context is specified
    MissingSecurityCtx,
    /// The `pan_id_compress` flag is set, but either the destination address
    /// or source address is not present.
    DisallowedPanIdCompress,
    /// Something went wrong, but it is unclear what/how it did
    UnknownError,
}

impl From<EncodeError> for byte::Error {
    fn from(e: EncodeError) -> Self {
        match e {
            EncodeError::WriteError => {
                byte::Error::BadInput { err: "WriteError" }
            }
            EncodeError::MissingSecurityCtx => byte::Error::BadInput {
                err: "MissingSecurityCtx",
            },
            EncodeError::DisallowedPanIdCompress => byte::Error::BadInput {
                err: "DisallowedPanIdCompress",
            },
            EncodeError::UnknownError => byte::Error::BadInput {
                err: "UnknownError",
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::mac::beacon;
    use crate::mac::command;
    use crate::mac::frame::*;
    use crate::mac::{
        Address, ExtendedAddress, FrameVersion, PanId, ShortAddress,
    };

    #[test]
    fn decode_ver0_pan_id_compression() {
        let data = [
            0x41, 0x88, 0x91, 0x8f, 0x20, 0xff, 0xff, 0x33, 0x44, 0x00, 0x00,
        ];

        let frame: Frame = data.read_with(&mut 0, FooterMode::None).unwrap();
        let hdr = frame.header;
        assert_eq!(hdr.frame_type, FrameType::Data);
        assert_eq!(hdr.has_security(), false);
        assert_eq!(hdr.frame_pending, false);
        assert_eq!(hdr.ack_request, false);
        assert_eq!(hdr.pan_id_compress, true);
        assert_eq!(hdr.version, FrameVersion::Ieee802154_2003);
        assert_eq!(
            frame.header.destination,
            Some(Address::Short(PanId(0x208f), ShortAddress(0xffff)))
        );
        assert_eq!(
            frame.header.source,
            Some(Address::Short(PanId(0x208f), ShortAddress(0x4433)))
        );
        assert_eq!(frame.header.seq, 145);
    }

    #[test]
    fn decode_ver0_pan_id_compression_bad() {
        let data = [
            0x41, 0x80, 0x91, 0x8f, 0x20, 0xff, 0xff, 0x33, 0x44, 0x00, 0x00,
        ];
        let frame = data.read_with::<Frame>(&mut 0, FooterMode::None);
        assert!(frame.is_err());
        if let Err(e) = frame {
            assert_eq!(e, DecodeError::InvalidAddressMode(0).into())
        }
    }

    #[test]
    fn decode_ver0_extended() {
        let data = [
            0x21, 0xc8, 0x8b, 0xff, 0xff, 0x02, 0x00, 0x23, 0x00, 0x60, 0xe2,
            0x16, 0x21, 0x1c, 0x4a, 0xc2, 0xae, 0xaa, 0xbb, 0xcc,
        ];
        let frame: Frame = data.read_with(&mut 0, FooterMode::None).unwrap();
        let hdr = frame.header;
        assert_eq!(hdr.frame_type, FrameType::Data);
        assert_eq!(hdr.has_security(), false);
        assert_eq!(hdr.frame_pending, false);
        assert_eq!(hdr.ack_request, true);
        assert_eq!(hdr.pan_id_compress, false);
        assert_eq!(hdr.version, FrameVersion::Ieee802154_2003);
        assert_eq!(
            frame.header.destination,
            Some(Address::Short(PanId(0xffff), ShortAddress(0x0002)))
        );
        assert_eq!(
            frame.header.source,
            Some(Address::Extended(
                PanId(0x0023),
                ExtendedAddress(0xaec24a1c2116e260)
            ))
        );
        assert_eq!(frame.header.seq, 139);
    }

    #[test]
    fn encode_ver0_short() {
        let frame = Frame {
            header: Header {
                ie_present: false,
                seq_no_suppress: false,
                frame_type: FrameType::Data,
                frame_pending: false,
                ack_request: false,
                pan_id_compress: false,
                version: FrameVersion::Ieee802154_2003,
                destination: Some(Address::Short(
                    PanId(0x1234),
                    ShortAddress(0x5678),
                )),
                source: Some(Address::Short(
                    PanId(0x4321),
                    ShortAddress(0x9abc),
                )),
                seq: 0x01,
                auxiliary_security_header: None,
            },
            content: FrameContent::Data,
            payload: &[0xde, 0xf0],
            footer: [0x00, 0x00],
        };
        let mut buf = [0u8; 32];
        let mut len = 0usize;
        buf.write_with(
            &mut len,
            frame,
            &mut FrameSerDesContext::no_security(FooterMode::None),
        )
        .unwrap();
        assert_eq!(len, 13);
        assert_eq!(
            buf[..len],
            [
                0x01, 0x88, 0x01, 0x34, 0x12, 0x78, 0x56, 0x21, 0x43, 0xbc,
                0x9a, 0xde, 0xf0
            ]
        );
    }

    #[test]
    fn encode_ver1_extended() {
        let frame = Frame {
            header: Header {
                ie_present: false,
                seq_no_suppress: false,
                frame_type: FrameType::Beacon,
                frame_pending: true,
                ack_request: false,
                pan_id_compress: false,
                version: FrameVersion::Ieee802154_2006,
                destination: Some(Address::Extended(
                    PanId(0x1234),
                    ExtendedAddress(0x1122334455667788),
                )),
                source: Some(Address::Short(
                    PanId(0x4321),
                    ShortAddress(0x9abc),
                )),
                seq: 0xff,
                auxiliary_security_header: None,
            },
            content: FrameContent::Beacon(beacon::Beacon {
                superframe_spec: beacon::SuperframeSpecification {
                    beacon_order: beacon::BeaconOrder::OnDemand,
                    superframe_order: beacon::SuperframeOrder::Inactive,
                    final_cap_slot: 15,
                    battery_life_extension: false,
                    pan_coordinator: false,
                    association_permit: false,
                },
                guaranteed_time_slot_info:
                    beacon::GuaranteedTimeSlotInformation::new(),
                pending_address: beacon::PendingAddress::new(),
            }),
            payload: &[0xde, 0xf0],
            footer: [0x00, 0x00],
        };
        let mut buf = [0u8; 32];
        let mut len = 0usize;
        buf.write_with(
            &mut len,
            frame,
            &mut FrameSerDesContext::no_security(FooterMode::None),
        )
        .unwrap();
        assert_eq!(len, 23);
        assert_eq!(
            buf[..len],
            [
                0x10, 0x9c, 0xff, 0x34, 0x12, 0x88, 0x77, 0x66, 0x55, 0x44,
                0x33, 0x22, 0x11, 0x21, 0x43, 0xbc, 0x9a, 0xff, 0x0f, 0x00,
                0x00, 0xde, 0xf0
            ]
        );
    }

    #[test]
    fn encode_ver0_pan_compress() {
        let frame = Frame {
            header: Header {
                ie_present: false,
                seq_no_suppress: false,
                frame_type: FrameType::Acknowledgement,
                frame_pending: false,
                ack_request: false,
                pan_id_compress: true,
                version: FrameVersion::Ieee802154_2003,
                destination: Some(Address::Extended(
                    PanId(0x1234),
                    ExtendedAddress(0x1122334455667788),
                )),
                source: Some(Address::Short(
                    PanId(0x1234),
                    ShortAddress(0x9abc),
                )),
                seq: 0xff,
                auxiliary_security_header: None,
            },
            content: FrameContent::Acknowledgement,
            payload: &[],
            footer: [0x00, 0x00],
        };
        let mut buf = [0u8; 32];
        let mut len = 0usize;
        buf.write_with(
            &mut len,
            frame,
            &mut FrameSerDesContext::no_security(FooterMode::None),
        )
        .unwrap();
        assert_eq!(len, 15);
        assert_eq!(
            buf[..len],
            [
                0x42, 0x8c, 0xff, 0x34, 0x12, 0x88, 0x77, 0x66, 0x55, 0x44,
                0x33, 0x22, 0x11, 0xbc, 0x9a
            ]
        );
    }

    #[test]
    fn encode_ver2_none() {
        let frame = Frame {
            header: Header {
                ie_present: false,
                seq_no_suppress: false,
                frame_type: FrameType::MacCommand,
                frame_pending: false,
                ack_request: true,
                pan_id_compress: false,
                version: FrameVersion::Ieee802154,
                destination: None,
                source: Some(Address::Short(
                    PanId(0x1234),
                    ShortAddress(0x9abc),
                )),
                seq: 0xff,
                auxiliary_security_header: None,
            },
            content: FrameContent::Command(command::Command::DataRequest),
            payload: &[],
            footer: [0x00, 0x00],
        };
        let mut buf = [0u8; 32];
        let mut len = 0usize;
        buf.write_with(
            &mut len,
            frame,
            &mut FrameSerDesContext::no_security(FooterMode::None),
        )
        .unwrap();
        assert_eq!(len, 8);
        assert_eq!(
            buf[..len],
            [0x23, 0xa0, 0xff, 0x34, 0x12, 0xbc, 0x9a, 0x04]
        );
    }

    #[test]
    fn empty_addressing_and_panid_compress() {
        let mut frame_data = [0u8; 127];
        let mut offset = 0;

        let mut header = Header {
            frame_type: FrameType::Data,
            version: FrameVersion::Ieee802154_2006,
            frame_pending: false,
            ack_request: false,
            pan_id_compress: true,
            destination: None,
            source: Some(Address::Extended(
                PanId(0xABCD),
                ExtendedAddress(0xFF),
            )),
            seq: 1,
            seq_no_suppress: false,
            ie_present: false,
            auxiliary_security_header: None,
        };

        assert!(frame_data
            .write_with(
                &mut offset,
                header,
                &Some(&mut SecurityContext::no_security()),
            )
            .is_err());

        header.destination =
            Some(Address::Extended(PanId(0xABCD), ExtendedAddress(0xFF)));
        header.source = None;
        header.source =
            Some(Address::Extended(PanId(0xABCD), ExtendedAddress(0xFF)));
        offset = 0;

        assert!(frame_data
            .write_with(
                &mut offset,
                header,
                &Some(&mut SecurityContext::no_security()),
            )
            .is_ok());
    }
}