binary-layout 0.1.0

The binary-layout library allows type-safe, inplace, zero-copy access to structured binary data. You define a custom data layout and give it a slice of binary data, and it will allow you to read and write the fields defined in the layout from the binary data without having to copy any of the data. It's similar to transmuting to/from a `#[repr(packed)]` struct, but much safer.
Documentation
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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
use std::convert::TryFrom;
use std::marker::PhantomData;

// TODO With const_evaluatable_checked, FieldSize and Field could be merged by adding a size() function to Field,
// but we'd need https://github.com/rust-lang/rust/issues/76560 first.
pub trait FieldSize {
    const SIZE: usize;
}

/// An enum representing the endianness used in a layout for accessing primitive integer fields.
pub enum EndianKind {
    Big,
    Little,
}

/// This marker trait represents the endianness used in a layout for accessing primitive integer fields.
pub trait Endianness {
    const KIND: EndianKind;
}

/// This is a marker type to mark layouts using big endian encoding
pub struct BigEndian {}
impl Endianness for BigEndian {
    const KIND: EndianKind = EndianKind::Big;
}

/// This is a marker type to mark layouts using little endian encoding
pub struct LittleEndian {}
impl Endianness for LittleEndian {
    const KIND: EndianKind = EndianKind::Little;
}

/// This trait offers access to the metadata of a field in a layout
pub trait FieldMetadata {
    /// The data type of the field, e.g. [u8], [i32], ...
    type Type: ?Sized;

    /// The offset of the field in the layout.
    ///
    /// # Example
    /// ```
    /// use binary_layout::prelude::*;
    ///
    /// define_layout!(my_layout, LittleEndian, {
    ///   field1: u16,
    ///   field2: i32,
    ///   field3: u8,
    /// });
    ///
    /// fn main() {
    ///     assert_eq!(0, my_layout::field1::OFFSET);
    ///     assert_eq!(2, my_layout::field2::OFFSET);
    ///     assert_eq!(6, my_layout::field3::OFFSET);
    /// }
    /// ```
    const OFFSET: usize;
}

/// This trait offers access to the metadata of a sized field in a layout.
/// Sized fields are all fields with a defined size. This is almost all fields.
/// The only exception is an unsized array field that can be used to match
/// tail data, i.e. any data at the end of the storage after all other fields
/// were defined and until the storage ends.
pub trait SizedFieldMetadata {
    /// The size of the field in the layout.
    ///
    /// # Example
    /// ```
    /// use binary_layout::prelude::*;
    ///
    /// define_layout!(my_layout, LittleEndian, {
    ///   field1: u16,
    ///   field2: i32,
    ///   field3: u8,
    /// });
    ///
    /// fn main() {
    ///     assert_eq!(2, my_layout::field1::SIZE);
    ///     assert_eq!(4, my_layout::field2::SIZE);
    ///     assert_eq!(1, my_layout::field3::SIZE);
    /// }
    /// ```
    const SIZE: usize;
}

/// A field represents one of the fields in the data layout and offers accessors
/// for it. It remembers the offset of the field in its const generic parameter
/// and the accessors use that to access the field.
///
/// A field does not hold any data storage, so if you use this API directly, you have to pass in
/// the storage pointer for each call. If you want an API object that remembers the storage,
/// take a look at the [FieldView] based API instead.
///
/// # Example:
/// ```
/// use binary_layout::prelude::*;
///
/// define_layout!(my_layout, LittleEndian, {
///   field_one: u16,
///   another_field: [u8; 16],
///   something_else: u32,
///   tail_data: [u8],
/// });
///
/// fn func(storage_data: &mut [u8]) {
///   // read some data
///   let format_version_header: u16 = my_layout::field_one::read(storage_data);
///   // equivalent: let format_version_header = u16::from_le_bytes((&storage_data[0..2]).try_into().unwrap());
///
///   // write some data
///   my_layout::something_else::write(storage_data, 10);
///   // equivalent: data_slice[18..22].copy_from_slice(&10u32.to_le_bytes());
///
///   // access a data region
///   let tail_data: &[u8] = my_layout::tail_data::data(storage_data);
///   // equivalent: let tail_data: &[u8] = &data_slice[22..];
///
///   // and modify it
///   my_layout::tail_data::data_mut(storage_data)[..5].copy_from_slice(&[1, 2, 3, 4, 5]);
///   // equivalent: data_slice[18..22].copy_from_slice(&[1, 2, 3, 4, 5]);
/// }
/// ```
pub struct Field<T: ?Sized, E: Endianness, const OFFSET_: usize> {
    _p1: PhantomData<T>,
    _p2: PhantomData<E>,
}

/// A field view represents the field metadata stored in a [Field] plus it stores the underlying
/// storage data it operates on, either as a reference to a slice `&[u8]`, `&mut [u8]`, or as
/// an owning [Vec<u8>].
///
/// Since this API remembers the underlying storage data in a view object, you don't have to pass it
/// in each time you're accessing a field. If you rather prefer an API that does not do that,
/// take a look at the [Field] API.
///
/// # Example:
/// ```
/// use binary_layout::prelude::*;
///
/// define_layout!(my_layout, LittleEndian, {
///   field_one: u16,
///   another_field: [u8; 16],
///   something_else: u32,
///   tail_data: [u8],
/// });
///
/// fn func(storage_data: &mut [u8]) {
///   let mut view = my_layout::View::new(storage_data);
///
///   // read some data
///   let format_version_header: u16 = view.field_one().read();
///   // equivalent: let format_version_header = u16::from_le_bytes((&storage_data[0..2]).try_into().unwrap());
///
///   // write some data
///   view.something_else_mut().write(10);
///   // equivalent: data_slice[18..22].copy_from_slice(&10u32.to_le_bytes());
///
///   // access a data region
///   let tail_data: &[u8] = view.tail_data().data();
///   // equivalent: let tail_data: &[u8] = &data_slice[22..];
///
///   // and modify it
///   view.tail_data_mut().data_mut()[..5].copy_from_slice(&[1, 2, 3, 4, 5]);
///   // equivalent: data_slice[18..22].copy_from_slice(&[1, 2, 3, 4, 5]);
/// }
/// ```
pub struct FieldView<S, F: FieldMetadata> {
    storage: S,
    _p: PhantomData<F>,
}

impl<S, F: FieldMetadata> FieldView<S, F> {
    /// Create a new view for a field over a given storage.
    /// You probably shouldn't call this directly but should instead call
    /// `your_layout::View::new()`, which is generated by the
    /// [define_layout!] macro for you.
    pub fn new(storage: S) -> Self {
        Self {
            storage,
            _p: PhantomData,
        }
    }
}

trait FieldTypeAccessor {
    type Field;
}
impl<S, F: FieldMetadata> FieldTypeAccessor for FieldView<S, F> {
    type Field = F;
}

impl<T: ?Sized, E: Endianness, const OFFSET_: usize> FieldMetadata for Field<T, E, OFFSET_> {
    type Type = T;
    const OFFSET: usize = OFFSET_;
}

impl<T: FieldSize, E: Endianness, const OFFSET_: usize> SizedFieldMetadata
    for Field<T, E, OFFSET_>
{
    const SIZE: usize = <T as FieldSize>::SIZE;
}

macro_rules! int_field {
    ($type:ident) => {
        doc_comment::doc_comment! {
            concat! {
                "Field type [", stringify!($type), "]: ",
                "This field represents a primitive integer. In this impl, we define read accessors for such integer fields. See [supported primitive integer types](crate#primitive-integer-types)."
            },
            impl<E: Endianness, const OFFSET_: usize> Field<$type, E, OFFSET_> {
                doc_comment::doc_comment! {
                    concat! {"
                    Read the integer field from a given data region, assuming the defined layout, using the [Field] API.
                    
                    # Example:
                    
                    ```
                    use binary_layout::prelude::*;
                        
                    define_layout!(my_layout, LittleEndian, {
                       //... other fields ...
                       some_integer_field: ", stringify!($type), "
                       //... other fields ...
                    });

                    fn func(storage_data: &[u8]) {
                        let read: ", stringify!($type), " = my_layout::some_integer_field::read(storage_data);
                    }
                    ```
                    "},
                    #[allow(dead_code)]
                    pub fn read(storage: &[u8]) -> $type {
                        let mut value = [0; std::mem::size_of::<$type>()];
                        value.copy_from_slice(
                            &storage.as_ref()[Self::OFFSET..(Self::OFFSET + std::mem::size_of::<$type>())],
                        );
                        match E::KIND {
                            EndianKind::Big => $type::from_be_bytes(value),
                            EndianKind::Little => $type::from_le_bytes(value),
                        }
                    }
                }
            }
        }
        impl FieldSize for $type {
            const SIZE: usize = std::mem::size_of::<$type>();
        }
        doc_comment::doc_comment! {
            concat! {
                "Field type [", stringify!($type), "]: ",
                "This field represents a little endian integer. In this impl, we define write accessors for such integer fields. See [supported primitive integer types](crate#primitive-integer-types).",
            },
            impl<E: Endianness, const OFFSET_: usize> Field<$type, E, OFFSET_> {
                doc_comment::doc_comment! {
                    concat! {"
                    Write the integer field to a given data region, assuming the defined layout, using the [Field] API.
                    
                    # Example:
                    
                    ```
                    use binary_layout::prelude::*;
                        
                    define_layout!(my_layout, LittleEndian, {
                       //... other fields ...
                       some_integer_field: ", stringify!($type), "
                       //... other fields ...
                    });

                    fn func(storage_data: &mut [u8]) {
                        my_layout::some_integer_field::write(storage_data, 10);
                    }
                    ```
                    "},
                    #[allow(dead_code)]
                    pub fn write(storage: &mut [u8], value: $type) {
                        let value_as_bytes = match E::KIND {
                            EndianKind::Big => value.to_be_bytes(),
                            EndianKind::Little => value.to_le_bytes(),
                        };
                        storage.as_mut()[Self::OFFSET..(Self::OFFSET + std::mem::size_of::<$type>())]
                            .copy_from_slice(&value_as_bytes);
                    }
                }
            }
        }
        doc_comment::doc_comment! {
            concat! {
                "Field type [", stringify!($type), "]: ",
                "This field represents a little endian integer. In this impl, we define read accessors for such integer fields. See [supported primitive integer types](crate#primitive-integer-types).",
            },
            impl<S: AsRef<[u8]>, E: Endianness, const OFFSET_: usize> FieldView<S, Field<$type, E, OFFSET_>> {
                doc_comment::doc_comment! {
                    concat! {"
                    Read the integer field from a given data region, assuming the defined layout, using the [FieldView] API.
                    
                    # Example:
                    
                    ```
                    use binary_layout::prelude::*;
                        
                    define_layout!(my_layout, LittleEndian, {
                       //... other fields ...
                       some_integer_field: ", stringify!($type), "
                       //... other fields ...
                    });

                    fn func(storage_data: &[u8]) {
                        let view = my_layout::View::new(storage_data);
                        let read: ", stringify!($type), " = view.some_integer_field().read();
                    }
                    ```
                    "},
                    #[allow(dead_code)]
                    pub fn read(&self) -> $type {
                        <Self as FieldTypeAccessor>::Field::read(self.storage.as_ref())
                    }
                }
            }
        }
        doc_comment::doc_comment! {
            concat! {
                "Field type [", stringify!($type), "]: ",
                "This field represents a little endian integer. In this impl, we define write accessors for such integer fields. See [supported primitive integer types](crate#primitive-integer-types).",
            },
            impl<S: AsMut<[u8]>, E: Endianness, const OFFSET_: usize> FieldView<S, Field<$type, E, OFFSET_>> {
                doc_comment::doc_comment! {
                    concat! {"
                    Write the integer field to a given data region, assuming the defined layout, using the [Field] API.
                    
                    # Example:
                    
                    ```
                    use binary_layout::prelude::*;
                        
                    define_layout!(my_layout, LittleEndian, {
                       //... other fields ...
                       some_integer_field: ", stringify!($type), "
                       //... other fields ...
                    });

                    fn func(storage_data: &mut [u8]) {
                        let mut view = my_layout::View::new(storage_data);
                        view.some_integer_field_mut().write(10);
                    }
                    ```
                    "},
                    #[allow(dead_code)]
                    pub fn write(&mut self, value: $type) {
                        <Self as FieldTypeAccessor>::Field::write(self.storage.as_mut(), value);
                    }
                }
            }
        }
    };
}

int_field!(i8);
int_field!(i16);
int_field!(i32);
int_field!(i64);
int_field!(u8);
int_field!(u16);
int_field!(u32);
int_field!(u64);

/// Field type `[u8]`:
/// This field represents an [open ended byte array](crate#open-ended-byte-arrays-u8).
/// In this impl, we define read accessors for such fields.
impl<E: Endianness, const OFFSET_: usize> Field<[u8], E, OFFSET_> {
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with read access using the [Field] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           tail_data: [u8],
        });

        fn func(storage_data: &[u8]) {
            let tail_data: &[u8] = my_layout::tail_data::data(storage_data);
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data(storage: &[u8]) -> &[u8] {
            &storage.as_ref()[Self::OFFSET..]
        }
    }
}
/// Field type `[u8]`:
/// This field represents an [open ended byte array](crate#open-ended-byte-arrays-u8).
/// In this impl, we define read accessors for such fields.
impl<E: Endianness, const OFFSET_: usize> Field<[u8], E, OFFSET_> {
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with write access using the [Field] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           tail_data: [u8],
        });

        fn func(storage_data: &mut [u8]) {
            let tail_data: &mut [u8] = my_layout::tail_data::data_mut(storage_data);
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data_mut(storage: &mut [u8]) -> &mut [u8] {
            &mut storage.as_mut()[Self::OFFSET..]
        }
    }
}
/// Field type `[u8]`:
/// This field represents an [open ended byte array](crate#open-ended-byte-arrays-u8).
/// In this impl, we define accessors that transfer ownership of the underlying immutable package data for such fields.
impl<S: AsRef<[u8]>, E: Endianness, const OFFSET_: usize> FieldView<S, Field<[u8], E, OFFSET_>> {
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with read access using the [FieldView] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           tail_data: [u8],
        });

        fn func(storage_data: &[u8]) {
            let view = my_layout::View::new(storage_data);
            let tail_data: &[u8] = view.tail_data().data();
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data(&self) -> &[u8] {
            <Self as FieldTypeAccessor>::Field::data(self.storage.as_ref())
        }
    }
}
/// Field type `[u8]`:
/// This field represents an [open ended byte array](crate#open-ended-byte-arrays-u8).
/// In this impl, we define write accessors for such fields.
impl<S: AsMut<[u8]>, E: Endianness, const OFFSET_: usize> FieldView<S, Field<[u8], E, OFFSET_>> {
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with write access using the [FieldView] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           tail_data: [u8],
        });

        fn func(storage_data: &mut [u8]) {
            let mut view = my_layout::View::new(storage_data);
            let tail_data: &mut [u8] = view.tail_data_mut().data_mut();
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data_mut(&mut self) -> &mut [u8] {
            <Self as FieldTypeAccessor>::Field::data_mut(self.storage.as_mut())
        }
    }
}
/// Field type `[u8]`:
/// This field represents an [open ended byte array](crate#open-ended-byte-arrays-u8).
/// In this impl, we define read accessors for such fields.
impl<'a, S: AsRef<[u8]> + ?Sized, E: Endianness, const OFFSET_: usize>
    FieldView<&'a S, Field<[u8], E, OFFSET_>>
{
    doc_comment::doc_comment! {
        concat! {"
        Similar to [FieldView::data], but this also extracts the lifetime. The reference returned by [FieldView::data] can only life as long as the [FieldView] object lives.
        The reference returned by this function can live for as long as the original `packed_data` reference that as put into the [FieldView] lives.
        However, you can only call this if you let the [FieldView] die, it takes the `self` parameter by value.
        Also note that this function can only be called when the [FieldView] was constructed with either a `&[u8]` or a `&mut [u8]` as underlying storage for the `storage_data`.
        If the [FieldView] was constructed based on `Vec<u8>` storage, then this function semantically would have to return an owning subvector, but such a thing doesn't exist in Rust.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           another_field: u64,
           tail_data: [u8],
        });

        fn func(storage_data: &[u8]) -> &[u8] {
            let view = my_layout::View::new(storage_data);
            let tail_data: &[u8] = view.into_tail_data().extract();
            // Now we return tail_data. Note that the view object doesn't survive
            // this function but we can still return the `tail_data` reference.
            // This wouldn't be possible with `FieldView::data`.
            tail_data
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn extract(self) -> &'a [u8] {
            <Self as FieldTypeAccessor>::Field::data(self.storage.as_ref())
        }
    }
}
/// Field type `[u8]`:
/// This field represents an [open ended byte array](crate#open-ended-byte-arrays-u8).
/// In this impl, we define accessors that transfer ownership of the underlying mutable package data for such fields.
impl<'a, S: AsMut<[u8]> + ?Sized, E: Endianness, const OFFSET_: usize>
    FieldView<&'a mut S, Field<[u8], E, OFFSET_>>
{
    doc_comment::doc_comment! {
        concat! {"
        Similar to [FieldView::data], but this also extracts the lifetime. The reference returned by [FieldView::data] can only life as long as the [FieldView] object lives.
        The reference returned by this function can live for as long as the original `packed_data` reference that as put into the [FieldView] lives.
        However, you can only call this if you let the [FieldView] die, it takes the `self` parameter by value.
        Also note that this function can only be called when the [FieldView] was constructed with either a `&[u8]` or a `&mut [u8]` as underlying storage for the `storage_data`.
        If the [FieldView] was constructed based on `Vec<u8>` storage, then this function semantically would have to return an owning subvector, but such a thing doesn't exist in Rust.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           another_field: u64,
           tail_data: [u8],
        });

        fn func(storage_data: &[u8]) -> &[u8] {
            let view = my_layout::View::new(storage_data);
            let tail_data: &[u8] = view.into_tail_data().extract();
            // Now we return tail_data. Note that the view object doesn't survive
            // this function but we can still return the `tail_data` reference.
            // This wouldn't be possible with `FieldView::data`.
            tail_data
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn extract(self) -> &'a mut [u8] {
            <Self as FieldTypeAccessor>::Field::data_mut(self.storage.as_mut())
        }
    }
}

/// Field type `[u8; N]`:
/// This field represents a [fixed size byte array](crate#fixed-size-byte-arrays-u8-n).
/// In this impl, we define read accessors for such fields.
impl<E: Endianness, const N: usize, const OFFSET_: usize> Field<[u8; N], E, OFFSET_> {
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with read access using the [Field] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           some_field: [u8; 5],
           //... other fields
        });

        fn func(storage_data: &[u8]) {
            let some_field: &[u8; 5] = my_layout::some_field::data(storage_data);
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data(storage: &[u8]) -> &[u8; N] {
            <&[u8; N]>::try_from(&storage.as_ref()[Self::OFFSET..(Self::OFFSET + N)]).unwrap()
        }
    }
}
/// Field type `[u8; N]`:
/// This field represents a [fixed size byte array](crate#fixed-size-byte-arrays-u8-n).
/// In this impl, we define write accessors for such fields.
impl<E: Endianness, const N: usize, const OFFSET_: usize> Field<[u8; N], E, OFFSET_> {
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with write access using the [Field] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           some_field: [u8; 5],
           //... other fields
        });

        fn func(storage_data: &mut [u8]) {
            let some_field: &mut [u8; 5] = my_layout::some_field::data_mut(storage_data);
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data_mut(storage: &mut [u8]) -> &mut [u8; N] {
            <&mut [u8; N]>::try_from(&mut storage.as_mut()[Self::OFFSET..(Self::OFFSET + N)]).unwrap()
        }
    }
}
impl<const N: usize> FieldSize for [u8; N] {
    const SIZE: usize = N;
}
/// Field type `[u8; N]`:
/// This field represents a [fixed size byte array](crate#fixed-size-byte-arrays-u8-n).
/// In this impl, we define read accessors for such fields.
impl<S: AsRef<[u8]>, E: Endianness, const N: usize, const OFFSET_: usize>
    FieldView<S, Field<[u8; N], E, OFFSET_>>
{
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with read access using the [FieldView] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           some_field: [u8; 5],
           //... other fields
        });

        fn func(storage_data: &[u8]) {
            let view = my_layout::View::new(storage_data);
            let some_field: &[u8; 5] = view.some_field().data();
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data(&self) -> &[u8; N] {
            <Self as FieldTypeAccessor>::Field::data(self.storage.as_ref())
        }
    }
}
/// Field type `[u8; N]`:
/// This field represents a [fixed size byte array](crate#fixed-size-byte-arrays-u8-n).
/// In this impl, we define write accessors for such fields.
impl<S: AsMut<[u8]>, E: Endianness, const N: usize, const OFFSET_: usize>
    FieldView<S, Field<[u8; N], E, OFFSET_>>
{
    doc_comment::doc_comment! {
        concat! {"
        Borrow the data in the byte array with write access using the [FieldView] API.
        
        # Example:
        
        ```
        use binary_layout::prelude::*;
            
        define_layout!(my_layout, LittleEndian, {
           //... other fields ...
           some_field: [u8; 5],
           //... other fields
        });

        fn func(storage_data: &mut [u8]) {
            let mut view = my_layout::View::new(storage_data);
            let some_field: &mut [u8; 5] = view.some_field_mut().data_mut();
        }
        ```
        "},
        #[allow(dead_code)]
        pub fn data_mut(&mut self) -> &mut [u8; N] {
            <Self as FieldTypeAccessor>::Field::data_mut(self.storage.as_mut())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::convert::TryInto;

    #[test]
    fn test_i8_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i8, LittleEndian, 5>;
        type Field2 = Field<i8, LittleEndian, 20>;

        Field1::write(&mut storage, 50);
        Field2::write(&mut storage, -20);

        assert_eq!(50, Field1::read(&storage));
        assert_eq!(-20, Field2::read(&storage));

        assert_eq!(50, i8::from_le_bytes((&storage[5..6]).try_into().unwrap()));
        assert_eq!(
            -20,
            i8::from_le_bytes((&storage[20..21]).try_into().unwrap())
        );

        assert_eq!(1, Field::<i8, LittleEndian, 5>::SIZE);
        assert_eq!(1, Field::<i8, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_i8_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i8, BigEndian, 5>;
        type Field2 = Field<i8, BigEndian, 20>;

        Field1::write(&mut storage, 50);
        Field2::write(&mut storage, -20);

        assert_eq!(50, Field1::read(&storage));
        assert_eq!(-20, Field2::read(&storage));

        assert_eq!(50, i8::from_be_bytes((&storage[5..6]).try_into().unwrap()));
        assert_eq!(
            -20,
            i8::from_be_bytes((&storage[20..21]).try_into().unwrap())
        );

        assert_eq!(1, Field::<i8, BigEndian, 5>::SIZE);
        assert_eq!(1, Field::<i8, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_i16_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i16, LittleEndian, 5>;
        type Field2 = Field<i16, LittleEndian, 20>;

        Field1::write(&mut storage, 500);
        Field2::write(&mut storage, -2000);

        assert_eq!(
            500,
            i16::from_le_bytes((&storage[5..7]).try_into().unwrap())
        );
        assert_eq!(
            -2000,
            i16::from_le_bytes((&storage[20..22]).try_into().unwrap())
        );

        assert_eq!(500, Field1::read(&storage));
        assert_eq!(-2000, Field2::read(&storage));

        assert_eq!(2, Field::<i16, LittleEndian, 5>::SIZE);
        assert_eq!(2, Field::<i16, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_i16_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i16, BigEndian, 5>;
        type Field2 = Field<i16, BigEndian, 20>;

        Field1::write(&mut storage, 500);
        Field2::write(&mut storage, -2000);

        assert_eq!(
            500,
            i16::from_be_bytes((&storage[5..7]).try_into().unwrap())
        );
        assert_eq!(
            -2000,
            i16::from_be_bytes((&storage[20..22]).try_into().unwrap())
        );

        assert_eq!(500, Field1::read(&storage));
        assert_eq!(-2000, Field2::read(&storage));

        assert_eq!(2, Field::<i16, BigEndian, 5>::SIZE);
        assert_eq!(2, Field::<i16, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_i32_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i32, LittleEndian, 5>;
        type Field2 = Field<i32, LittleEndian, 20>;

        Field1::write(&mut storage, 10i32.pow(8));
        Field2::write(&mut storage, -(10i32.pow(7)));

        assert_eq!(
            10i32.pow(8),
            i32::from_le_bytes((&storage[5..9]).try_into().unwrap())
        );
        assert_eq!(
            -(10i32.pow(7)),
            i32::from_le_bytes((&storage[20..24]).try_into().unwrap())
        );

        assert_eq!(10i32.pow(8), Field1::read(&storage));
        assert_eq!(-10i32.pow(7), Field2::read(&storage));

        assert_eq!(4, Field::<i32, LittleEndian, 5>::SIZE);
        assert_eq!(4, Field::<i32, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_i32_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i32, BigEndian, 5>;
        type Field2 = Field<i32, BigEndian, 20>;

        Field1::write(&mut storage, 10i32.pow(8));
        Field2::write(&mut storage, -(10i32.pow(7)));

        assert_eq!(
            10i32.pow(8),
            i32::from_be_bytes((&storage[5..9]).try_into().unwrap())
        );
        assert_eq!(
            -(10i32.pow(7)),
            i32::from_be_bytes((&storage[20..24]).try_into().unwrap())
        );

        assert_eq!(10i32.pow(8), Field1::read(&storage));
        assert_eq!(-10i32.pow(7), Field2::read(&storage));

        assert_eq!(4, Field::<i32, BigEndian, 5>::SIZE);
        assert_eq!(4, Field::<i32, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_i64_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i64, LittleEndian, 5>;
        type Field2 = Field<i64, LittleEndian, 20>;

        Field1::write(&mut storage, 10i64.pow(15));
        Field2::write(&mut storage, -(10i64.pow(14)));

        assert_eq!(
            10i64.pow(15),
            i64::from_le_bytes((&storage[5..13]).try_into().unwrap())
        );
        assert_eq!(
            -(10i64.pow(14)),
            i64::from_le_bytes((&storage[20..28]).try_into().unwrap())
        );

        assert_eq!(10i64.pow(15), Field1::read(&storage));
        assert_eq!(-10i64.pow(14), Field2::read(&storage));

        assert_eq!(8, Field::<i64, LittleEndian, 5>::SIZE);
        assert_eq!(8, Field::<i64, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_i64_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<i64, BigEndian, 5>;
        type Field2 = Field<i64, BigEndian, 20>;

        Field1::write(&mut storage, 10i64.pow(15));
        Field2::write(&mut storage, -(10i64.pow(14)));

        assert_eq!(
            10i64.pow(15),
            i64::from_be_bytes((&storage[5..13]).try_into().unwrap())
        );
        assert_eq!(
            -(10i64.pow(14)),
            i64::from_be_bytes((&storage[20..28]).try_into().unwrap())
        );

        assert_eq!(10i64.pow(15), Field1::read(&storage));
        assert_eq!(-10i64.pow(14), Field2::read(&storage));

        assert_eq!(8, Field::<i64, BigEndian, 5>::SIZE);
        assert_eq!(8, Field::<i64, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_u8_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u8, LittleEndian, 5>;
        type Field2 = Field<u8, LittleEndian, 20>;

        Field1::write(&mut storage, 50);
        Field2::write(&mut storage, 20);

        assert_eq!(50, Field1::read(&storage));
        assert_eq!(20, Field2::read(&storage));

        assert_eq!(50, u8::from_le_bytes((&storage[5..6]).try_into().unwrap()));
        assert_eq!(
            20,
            u8::from_le_bytes((&storage[20..21]).try_into().unwrap())
        );

        assert_eq!(1, Field::<u8, LittleEndian, 5>::SIZE);
        assert_eq!(1, Field::<u8, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_u8_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u8, BigEndian, 5>;
        type Field2 = Field<u8, BigEndian, 20>;

        Field1::write(&mut storage, 50);
        Field2::write(&mut storage, 20);

        assert_eq!(50, Field1::read(&storage));
        assert_eq!(20, Field2::read(&storage));

        assert_eq!(50, u8::from_be_bytes((&storage[5..6]).try_into().unwrap()));
        assert_eq!(
            20,
            u8::from_be_bytes((&storage[20..21]).try_into().unwrap())
        );

        assert_eq!(1, Field::<u8, BigEndian, 5>::SIZE);
        assert_eq!(1, Field::<u8, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_u16_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u16, LittleEndian, 5>;
        type Field2 = Field<u16, LittleEndian, 20>;

        Field1::write(&mut storage, 500);
        Field2::write(&mut storage, 2000);

        assert_eq!(
            500,
            u16::from_le_bytes((&storage[5..7]).try_into().unwrap())
        );
        assert_eq!(
            2000,
            u16::from_le_bytes((&storage[20..22]).try_into().unwrap())
        );

        assert_eq!(500, Field1::read(&storage));
        assert_eq!(2000, Field2::read(&storage));

        assert_eq!(2, Field::<u16, LittleEndian, 5>::SIZE);
        assert_eq!(2, Field::<u16, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_u16_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u16, BigEndian, 5>;
        type Field2 = Field<u16, BigEndian, 20>;

        Field1::write(&mut storage, 500);
        Field2::write(&mut storage, 2000);

        assert_eq!(
            500,
            u16::from_be_bytes((&storage[5..7]).try_into().unwrap())
        );
        assert_eq!(
            2000,
            u16::from_be_bytes((&storage[20..22]).try_into().unwrap())
        );

        assert_eq!(500, Field1::read(&storage));
        assert_eq!(2000, Field2::read(&storage));

        assert_eq!(2, Field::<u16, BigEndian, 5>::SIZE);
        assert_eq!(2, Field::<u16, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_u32_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u32, LittleEndian, 5>;
        type Field2 = Field<u32, LittleEndian, 20>;

        Field1::write(&mut storage, 10u32.pow(8));
        Field2::write(&mut storage, 10u32.pow(7));

        assert_eq!(
            10u32.pow(8),
            u32::from_le_bytes((&storage[5..9]).try_into().unwrap())
        );
        assert_eq!(
            10u32.pow(7),
            u32::from_le_bytes((&storage[20..24]).try_into().unwrap())
        );

        assert_eq!(10u32.pow(8), Field1::read(&storage));
        assert_eq!(10u32.pow(7), Field2::read(&storage));

        assert_eq!(4, Field::<u32, LittleEndian, 5>::SIZE);
        assert_eq!(4, Field::<u32, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_u32_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u32, BigEndian, 5>;
        type Field2 = Field<u32, BigEndian, 20>;

        Field1::write(&mut storage, 10u32.pow(8));
        Field2::write(&mut storage, 10u32.pow(7));

        assert_eq!(
            10u32.pow(8),
            u32::from_be_bytes((&storage[5..9]).try_into().unwrap())
        );
        assert_eq!(
            10u32.pow(7),
            u32::from_be_bytes((&storage[20..24]).try_into().unwrap())
        );

        assert_eq!(10u32.pow(8), Field1::read(&storage));
        assert_eq!(10u32.pow(7), Field2::read(&storage));

        assert_eq!(4, Field::<u32, BigEndian, 5>::SIZE);
        assert_eq!(4, Field::<u32, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_u64_littleendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u64, LittleEndian, 5>;
        type Field2 = Field<u64, LittleEndian, 20>;

        Field1::write(&mut storage, 10u64.pow(15));
        Field2::write(&mut storage, 10u64.pow(14));

        assert_eq!(
            10u64.pow(15),
            u64::from_le_bytes((&storage[5..13]).try_into().unwrap())
        );
        assert_eq!(
            10u64.pow(14),
            u64::from_le_bytes((&storage[20..28]).try_into().unwrap())
        );

        assert_eq!(10u64.pow(15), Field1::read(&storage));
        assert_eq!(10u64.pow(14), Field2::read(&storage));

        assert_eq!(8, Field::<u64, LittleEndian, 5>::SIZE);
        assert_eq!(8, Field::<u64, LittleEndian, 5>::SIZE);
    }

    #[test]
    fn test_u64_bigendian() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<u64, BigEndian, 5>;
        type Field2 = Field<u64, BigEndian, 20>;

        Field1::write(&mut storage, 10u64.pow(15));
        Field2::write(&mut storage, 10u64.pow(14));

        assert_eq!(
            10u64.pow(15),
            u64::from_be_bytes((&storage[5..13]).try_into().unwrap())
        );
        assert_eq!(
            10u64.pow(14),
            u64::from_be_bytes((&storage[20..28]).try_into().unwrap())
        );

        assert_eq!(10u64.pow(15), Field1::read(&storage));
        assert_eq!(10u64.pow(14), Field2::read(&storage));

        assert_eq!(8, Field::<u64, BigEndian, 5>::SIZE);
        assert_eq!(8, Field::<u64, BigEndian, 5>::SIZE);
    }

    #[test]
    fn test_slice() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<[u8], LittleEndian, 5>;
        type Field2 = Field<[u8], BigEndian, 7>;

        Field1::data_mut(&mut storage)[..5].copy_from_slice(&[10, 20, 30, 40, 50]);
        Field2::data_mut(&mut storage)[..5].copy_from_slice(&[60, 70, 80, 90, 100]);

        assert_eq!(&[10, 20, 60, 70, 80], &Field1::data(&storage)[..5]);
        assert_eq!(&[60, 70, 80, 90, 100], &Field2::data(&storage)[..5]);
    }

    #[test]
    fn test_array() {
        let mut storage = vec![0; 1024];

        type Field1 = Field<[u8; 2], LittleEndian, 5>;
        type Field2 = Field<[u8; 5], BigEndian, 6>;

        Field1::data_mut(&mut storage).copy_from_slice(&[10, 20]);
        Field2::data_mut(&mut storage).copy_from_slice(&[60, 70, 80, 90, 100]);

        assert_eq!(&[10, 60], Field1::data(&storage));
        assert_eq!(&[60, 70, 80, 90, 100], Field2::data(&storage));

        assert_eq!(2, Field::<[u8; 2], LittleEndian, 5>::SIZE);
        assert_eq!(5, Field::<[u8; 5], BigEndian, 5>::SIZE);
    }
}