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
/// This macro defines a data layout. Given such a layout, the [Field](crate::Field) or [FieldView](crate::FieldView) APIs can be used to access data based on it.
///
/// Data layouts define
/// - a name for the layout
/// - and endianness for its fields ([BigEndian](crate::BigEndian) or [LittleEndian](crate::LittleEndian))
/// - and an ordered collection of typed fields.
///
/// See [supported field types](crate#supported-field-types) for a list of supported field types.
///
/// # API
/// ```text
/// define_layout!(<<Name>>, <<Endianness>>, {
///   <<FieldName>>: <<FieldType>>,
///   <<FieldName>>: <<FieldType>>,
///   ...
/// });
/// ```
///
/// ## Field names
/// Field names can be any valid Rust identifiers, but it is recommended to avoid names that contain `storage`, `into_` or `_mut`.
/// This is because the [define_layout!](crate::define_layout!) macro creates a [View class with several accessors](#struct-view) for each field that contain those identifier parts.
///
/// ## Example
/// ```
/// use binary_layout::prelude::*;
///
/// define_layout!(icmp_packet, BigEndian, {
///   packet_type: u8,
///   code: u8,
///   checksum: u16,
///   rest_of_header: [u8; 4],
///   data_section: [u8], // open ended byte array, matches until the end of the packet
/// });
/// ```
///
/// # Generated code
/// See [icmp_packet](crate::example::icmp_packet) for an example.
///
/// This macro will define a module for you with several members:
/// - For each field, there will be a struct containing
///   - metadata like [OFFSET](crate::Field::OFFSET) and [SIZE](crate::Field::SIZE) as rust `const`s
///   - data accessors for the [Field](crate::Field) API
/// - The module will also contain a `View` struct that offers the [FieldView](crate::FieldView) API.
///
/// This macro will also generate rustdoc documentation for everything it generates. One of the best ways to figure out
/// how to use the generated layouts is to read the rustdoc documentation that was generated for them.
///
/// ## Metadata Example
/// ```
/// use binary_layout::prelude::*;
///
/// define_layout!(my_layout, LittleEndian, {
///   field1: u16,
///   field2: u32,
/// });
/// assert_eq!(2, my_layout::field2::OFFSET);
/// assert_eq!(Some(4), my_layout::field2::SIZE);
/// ```
///
/// ## struct View
/// See [icmp_packet::View](crate::example::icmp_packet::View) for an example.
///
/// You can create views over a storage by calling `View::new`. Views can be created based on
/// - Immutable borrowed storage: `&[u8]`
/// - Mutable borrowed storage: `&mut [u8]`
/// - Owning storage: impl `AsRef<u8>` (for example: `Vec<u8>`)
///
/// The generated `View` struct will offer
/// - `View::new(storage)` to create a `View`
/// - `View::into_storage(self)` to destroy a `View` and return the storage held
///
/// and it will offer the following accessors for each field
/// - `${field_name}()`: Read access. This returns a [FieldView](crate::FieldView) instance with read access.
/// - `${field_name}_mut()`: Read access. This returns a [FieldView](crate::FieldView) instance with write access.
/// - `into_${field_name}`: Extract access. This destroys the `View` and returns a [FieldView](crate::FieldView) instance owning the storage. Mostly useful for slice fields when you want to return an owning slice.
#[macro_export]
macro_rules! define_layout {
    ($name: ident, $endianness: ident, {$($field_name: ident : $field_type: ty $(as $underlying_type: ty)?),* $(,)?}) => {
        $crate::internal::doc_comment!{
            concat!{"
            This module is autogenerated. It defines a layout using the [binary_layout] crate based on the following definition:
            ```ignore
            define_layout!(", stringify!($name), ", ", stringify!($endianness), ", {", $("
                ", stringify!($field_name), ": ", stringify!($field_type), $(" as ", stringify!($underlying_type), )? ",", )* "
            });
            ```
            "},
            #[allow(dead_code)]
            pub mod $name {
                #[allow(unused_imports)]
                use super::*;

                $crate::define_layout!(@impl_fields $crate::$endianness, Some(0), {$($field_name : $field_type $(as $underlying_type)?),*});

                $crate::internal::doc_comment!{
                    concat!{"
                    The [View] struct defines the [FieldView](crate::FieldView) API.
                    An instance of [View] wraps a storage (either borrowed or owned)
                    and allows accessors for the layout fields.

                    This view is based on the following layout definition:
                    ```ignore
                    define_layout!(", stringify!($name), ", ", stringify!($endianness), ", {", $("
                        ", stringify!($field_name), ": ", stringify!($field_type), $(" as ", stringify!($underlying_type), )? ",",)* "
                    });
                    ```
                    "},
                    pub struct View<S: AsRef<[u8]>> {
                        storage: S,
                    }
                }
                impl <S: AsRef<[u8]>> View<S> {
                    /// You can create views over a storage by calling [View::new].
                    ///
                    /// `S` is the type of underlying storage. It can be
                    /// - Immutable borrowed storage: `&[u8]`
                    /// - Mutable borrowed storage: `&mut [u8]`
                    /// - Owning storage: impl `AsRef<u8>` (for example: `Vec<u8>`)
                    #[inline]
                    pub fn new(storage: S) -> Self {
                        Self {storage}
                    }

                    /// This destroys the view and returns the underlying storage back to you.
                    /// This is useful if you created an owning view (e.g. based on `Vec<u8>`)
                    /// and now need the underlying `Vec<u8>` back.
                    #[inline]
                    pub fn into_storage(self) -> S {
                        self.storage
                    }

                    $crate::define_layout!(@impl_view_into {$($field_name),*});
                }
                impl <S: AsRef<[u8]>> View<S> {
                    $crate::define_layout!(@impl_view_asref {$($field_name),*});
                }
                impl <S: AsRef<[u8]> + AsMut<[u8]>> View<S> {
                    $crate::define_layout!(@impl_view_asmut {$($field_name),*});
                }

                /// Use this as a marker type for using this layout as a nested field within another layout.
                ///
                /// # Example
                /// ```
                /// use binary_layout::prelude::*;
                ///
                /// define_layout!(icmp_header, BigEndian, {
                ///   packet_type: u8,
                ///   code: u8,
                ///   checksum: u16,
                ///   rest_of_header: [u8; 4],
                /// });
                /// define_layout!(icmp_packet, BigEndian, {
                ///   header: icmp_header::NestedView,
                ///   data_section: [u8], // open ended byte array, matches until the end of the packet
                /// });
                /// # fn main() {}
                /// ```
                pub struct NestedView;
                impl <S: AsRef<[u8]>> $crate::internal::OwningNestedView<$crate::Data<S>> for NestedView where S: AsRef<[u8]> {
                    type View = View<$crate::Data<S>>;

                    #[inline(always)]
                    fn into_view(storage: $crate::Data<S>) -> Self::View {
                        Self::View {storage}
                    }
                }
                impl <S: AsRef<[u8]>> $crate::internal::BorrowingNestedView<S> for NestedView {
                    type View = View<S>;

                    #[inline(always)]
                    fn view(storage: S) -> Self::View {
                        Self::View {storage: storage.into()}
                    }
                }

                impl $crate::internal::NestedViewInfo for NestedView {
                    const SIZE: Option<usize> = SIZE;
                }
            }
        }
    };

    (@impl_fields $endianness: ty, $offset_accumulator: expr, {}) => {
        /// Total size of the layout in number of bytes.
        /// This can be None if the layout ends with an open ended field like a byte slice.
        pub const SIZE: Option<usize> = $offset_accumulator;
    };
    (@impl_fields $endianness: ty, $offset_accumulator: expr, {$name: ident : $type: ty as $underlying_type: ty $(, $($tail:tt)*)?}) => {
        $crate::internal::doc_comment!{
            concat!("Metadata and [Field](crate::Field) API accessors for the `", stringify!($name), "` field"),
            #[allow(non_camel_case_types)]
            pub type $name = $crate::WrappedField::<$underlying_type, $type, $crate::PrimitiveField::<$underlying_type, $endianness, {$crate::internal::unwrap_field_size($offset_accumulator)}>>;
        }
        $crate::define_layout!(@impl_fields $endianness, ($crate::internal::option_usize_add(<$name as $crate::Field>::OFFSET, <$name as $crate::Field>::SIZE)), {$($($tail)*)?});
    };
    (@impl_fields $endianness: ty, $offset_accumulator: expr, {$name: ident : $type: ty $(, $($tail:tt)*)?}) => {
        $crate::internal::doc_comment!{
            concat!("Metadata and [Field](crate::Field) API accessors for the `", stringify!($name), "` field"),
            #[allow(non_camel_case_types)]
            pub type $name = $crate::PrimitiveField::<$type, $endianness, {$crate::internal::unwrap_field_size($offset_accumulator)}>;
        }
        $crate::define_layout!(@impl_fields $endianness, ($crate::internal::option_usize_add(<$name as $crate::Field>::OFFSET, <$name as $crate::Field>::SIZE)), {$($($tail)*)?});
    };

    (@impl_view_asref {}) => {};
    (@impl_view_asref {$name: ident $(, $name_tail: ident)*}) => {
        $crate::internal::doc_comment!{
            concat!("Return a [FieldView](crate::FieldView) with read access to the `", stringify!($name), "` field"),
            #[inline]
            pub fn $name(&self) -> <$name as $crate::internal::StorageToFieldView<&[u8]>>::View {
                <$name as $crate::internal::StorageToFieldView<&[u8]>>::view(self.storage.as_ref())
            }
        }
        $crate::define_layout!(@impl_view_asref {$($name_tail),*});
    };

    (@impl_view_asmut {}) => {};
    (@impl_view_asmut {$name: ident $(, $name_tail: ident)*}) => {
        $crate::internal::paste!{
            $crate::internal::doc_comment!{
                concat!("Return a [FieldView](crate::FieldView) with write access to the `", stringify!($name), "` field"),
                #[inline]
                pub fn [<$name _mut>](&mut self) -> <$name as $crate::internal::StorageToFieldView<&mut [u8]>>::View {
                    <$name as $crate::internal::StorageToFieldView<&mut [u8]>>::view(self.storage.as_mut())
                }
            }
        }
        $crate::define_layout!(@impl_view_asmut {$($name_tail),*});
    };

    (@impl_view_into {}) => {};
    (@impl_view_into {$name: ident $(, $name_tail: ident)*}) => {
        $crate::internal::paste!{
            $crate::internal::doc_comment!{
                concat!("Destroy the [View] and return a field accessor to the `", stringify!($name), "` field owning the storage. This is mostly useful for [FieldView::extract](crate::FieldView::extract)"),
                #[inline]
                pub fn [<into_ $name>](self) -> <$name as $crate::internal::StorageIntoFieldView<S>>::View {
                    <$name as $crate::internal::StorageIntoFieldView<S>>::into_view(self.storage)
                }
            }
        }
        $crate::define_layout!(@impl_view_into {$($name_tail),*});
    };
}

// TODO This only exists because Option<usize>::unwrap() isn't const. Remove this once it is.
/// Internal function, don't use!
/// Unwraps an option<usize>
#[inline(always)]
pub const fn unwrap_field_size(opt: Option<usize>) -> usize {
    match opt {
        Some(x) => x,
        None => {
            #[allow(unconditional_panic)]
            #[allow(clippy::no_effect)]
            ["Error: Fields without a static size (e.g. open-ended byte arrays) can only be used at the end of a layout"][10];
            #[allow(clippy::empty_loop)]
            loop {}
        }
    }
}

/// Internal function, don't use!
#[inline(always)]
pub const fn option_usize_add(lhs: usize, rhs: Option<usize>) -> Option<usize> {
    match (lhs, rhs) {
        (lhs, Some(rhs)) => Some(lhs + rhs),
        (_, None) => None,
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    use rand::{rngs::StdRng, RngCore, SeedableRng};

    fn data_region(size: usize, seed: u64) -> Vec<u8> {
        let mut rng = StdRng::seed_from_u64(seed);
        let mut res = vec![0; size];
        rng.fill_bytes(&mut res);
        res
    }

    define_layout!(module_level_layout, LittleEndian, {
        first: i8,
        second: i64,
        third: u16,
    });

    #[test]
    fn layouts_can_be_defined_at_module_level() {
        let storage: [u8; 1024] = [0; 1024];
        let view = module_level_layout::View::new(storage);
        assert_eq!(0, view.third().read());
    }

    #[test]
    fn layouts_can_be_defined_at_function_level() {
        define_layout!(function_level_layout, LittleEndian, {
            first: i8,
            second: i64,
            third: u16,
        });

        let storage: [u8; 1024] = [0; 1024];
        let view = function_level_layout::View::new(storage);
        assert_eq!(0, view.third().read());
    }

    #[test]
    fn can_be_created_with_and_without_trailing_comma() {
        define_layout!(first, LittleEndian, { field: u8 });
        define_layout!(second, LittleEndian, {
            field: u8,
            second: u16
        });
        define_layout!(third, LittleEndian, {
            field: u8,
        });
        define_layout!(fourth, LittleEndian, {
            field: u8,
            second: u16,
        });
    }

    #[test]
    fn there_can_be_multiple_views_if_readonly() {
        define_layout!(my_layout, BigEndian, {
            field1: u16,
            field2: i64,
        });

        let storage = data_region(1024, 0);
        let view1 = my_layout::View::new(&storage);
        let view2 = my_layout::View::new(&storage);
        view1.field1().read();
        view2.field1().read();
    }

    #[test]
    fn size_of_sized_layout() {
        define_layout!(my_layout, LittleEndian, {
            field1: u16,
            field2: i64,
        });
        assert_eq!(Some(10), my_layout::SIZE);
    }

    #[test]
    fn size_of_unsized_layout() {
        define_layout!(my_layout, LittleEndian, {
            field: u16,
            tail: [u8],
        });
        assert_eq!(None, my_layout::SIZE);
    }
}