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
//! A crate for quick and easy format structure definitions for use in binary file parsing.
//!
//! # Usage
//!
//! This crate should be used by invoking the provided [`format_struct`] macro like this:
//!
//! ```rust
//! use format_struct::{format_struct, FromByteSlice};
//!
//! // Here we define a small structure.
//! format_struct! {
//!     struct little Test {
//!         foo: u8,
//!         bar: u32,
//!         baz: [u8; 2],
//!     }
//! }
//!
//! # pub fn main() {
//! // This is the data we want to parse:
//! let data = &[
//!     0x42u8, // this goes into foo
//!     0x39, 0x05, 0x00, 0x00, // this goes into bar
//!     0xaa, 0x55, // this goes into baz
//! ][..];
//!
//! // This is completely zero-cost since the implementation is just a transmute.
//! let s = Test::from_byte_slice(data).unwrap();
//!
//! // Each integer field access compiles to a single unaligned memory access instruction.
//! assert_eq!(s.foo, 0x42);
//! assert_eq!(s.bar.get(), 1337);
//! assert_eq!(&s.baz, &[0xaa, 0x55]);
//! # }
//! ```

#![no_std]
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(rust_2018_idioms)]
#![deny(unreachable_pub)]

#[cfg(feature = "std")]
extern crate std;

pub mod endian;

use endian::FixedEndian;
pub use endian::{BigEndian, Endian, LittleEndian};

macro_rules! define_int_wrapper {
    ($ty:ident, $name:ident) => {
        #[doc = concat!(
            "A type that wraps a byte array to be decoded into a `", stringify!($ty), "`.\n\n"
        )]
        /// The generic parameter represents the endianness used to decode the wrapped value. In
        /// case the value is expected to have fixed endianness, either [`BigEndian`] or
        /// [`LittleEndian`] types should be used, otherwise the [`Endian`] type.
        #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
        #[repr(C)]
        pub struct $name<E>([u8; ($ty::BITS as usize) / 8], ::core::marker::PhantomData<E>);

        impl<E> $name<E> {
            #[doc = concat!("Converts a byte array into a [`", stringify!($name), "`].")]
            pub fn from_bytes(bytes: [u8; ($ty::BITS as usize) / 8]) -> Self {
                Self(bytes, ::core::marker::PhantomData)
            }
        }

        $crate::format_struct!(@impl_conv $name<E>);

        impl $name<Endian> {
            #[doc = concat!(
                "Constructs a [`", stringify!($name), "`] wrapper type from a `", stringify!($ty),
                "` value using the specified endianness."
            )]
            #[inline]
            pub fn new_with_endian(value: $ty, endian: Endian) -> Self {
                let bytes = match endian {
                    Endian::Little => value.to_le_bytes(),
                    Endian::Big => value.to_be_bytes(),
                };

                Self(bytes, ::core::marker::PhantomData)
            }

            #[doc = concat!(
                "Extracts a `", stringify!($ty), "` value from a [`", stringify!($name),
                "`] wrapper using the specified endianness."
            )]
            #[inline]
            pub fn get_with_endian(self, endian: Endian) -> $ty {
                match endian {
                    Endian::Little => $ty::from_le_bytes(self.0),
                    Endian::Big => $ty::from_be_bytes(self.0),
                }
            }
        }

        impl<E: FixedEndian> $name<E> {
            #[doc = concat!(
                "Constructs a [`", stringify!($name), "`] wrapper type from a `", stringify!($ty),
                "` value using the type's fixed endianness."
            )]
            #[inline]
            pub fn new(value: $ty) -> Self {
                let bytes = match E::ENDIAN {
                    Endian::Little => value.to_le_bytes(),
                    Endian::Big => value.to_be_bytes(),
                };

                Self(bytes, ::core::marker::PhantomData)
            }

            #[doc = concat!(
                "Extracts a `", stringify!($ty), "` value from a [`", stringify!($name),
                "`] wrapper using the type's fixed endianness."
            )]
            #[inline]
            pub fn get(self) -> $ty {
                match E::ENDIAN {
                    Endian::Little => $ty::from_le_bytes(self.0),
                    Endian::Big => $ty::from_be_bytes(self.0),
                }
            }
        }

        impl<E> ::core::default::Default for $name<E> {
            fn default() -> Self {
                Self(Default::default(), ::core::marker::PhantomData)
            }
        }

        impl<E: FixedEndian> From<$ty> for $name<E> {
            fn from(value: $ty) -> Self {
                Self::new(value)
            }
        }

        unsafe impl<E> FromByteSlice for $name<E> {
            fn from_byte_slice(s: &[u8]) -> ::core::result::Result<&Self, $crate::InvalidSizeError> {
                let s: &[u8; ($ty::BITS as usize) / 8] = ::core::convert::TryInto::try_into(s).map_err(|_| InvalidSizeError)?;
                Ok(unsafe { &*(s.as_ptr() as *const Self) })
            }

            fn from_byte_slice_mut(s: &mut [u8]) -> ::core::result::Result<&mut Self, $crate::InvalidSizeError> {
                let s: &mut [u8; ($ty::BITS as usize) / 8] = ::core::convert::TryInto::try_into(s).map_err(|_| InvalidSizeError)?;
                Ok(unsafe { &mut *(s.as_mut_ptr() as *mut Self) })
            }

            fn slice_from_byte_slice(s: &[u8]) -> ::core::result::Result<&[Self], $crate::InvalidSizeError> {
                if s.is_empty() {
                    return ::core::result::Result::Ok(&[])
                } else if s.len() % ::core::mem::size_of::<Self>() != 0 {
                    return ::core::result::Result::Err($crate::InvalidSizeError);
                }

                let size = s.len() / ::core::mem::size_of::<Self>();
                let ptr = s.as_ptr() as *const Self;

                ::core::result::Result::Ok(unsafe { ::core::slice::from_raw_parts(ptr, size) })
            }

            fn slice_from_byte_slice_mut(s: &mut [u8]) -> ::core::result::Result<&mut [Self], $crate::InvalidSizeError> {
                if s.is_empty() {
                    return ::core::result::Result::Ok(&mut [])
                } else if s.len() % ::core::mem::size_of::<Self>() != 0 {
                    return ::core::result::Result::Err($crate::InvalidSizeError);
                }

                let size = s.len() / ::core::mem::size_of::<Self>();
                let ptr = s.as_mut_ptr() as *mut Self;

                ::core::result::Result::Ok(unsafe { ::core::slice::from_raw_parts_mut(ptr, size) })
            }
        }
    };
}

define_int_wrapper!(u16, U16);
define_int_wrapper!(i16, I16);
define_int_wrapper!(u32, U32);
define_int_wrapper!(i32, I32);
define_int_wrapper!(u64, U64);
define_int_wrapper!(i64, I64);
define_int_wrapper!(u128, U128);
define_int_wrapper!(i128, I128);

/// The error type returned when a slice provided to any of the [`FromByteSlice`] methods didn't meet their size
/// constraints.
#[derive(Copy, Clone, Debug)]
pub struct InvalidSizeError;

impl core::fmt::Display for InvalidSizeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("byte slice is not aligned to the structure's size")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for InvalidSizeError {}

/// An **unsafe** trait for types that byte slices may be transmuted into.
///
/// This trait is usually automatically implemented by the [`format_struct`] macro so there is no need to implement it
/// manually.
///
/// All the trait's methods could be implemented automatically but are not due to limitations of the Rust's generics:
/// using `Self` in a const context (array size on our case) isn't possible in traits. Since the trait isn't meant to
/// be implemented manually that is considered a non-issue.
///
/// # Safety
///
/// Types implementing the trait must be safe to transmute from an arbitrary byte slice that has proper size. That means
/// their alignment must be 1.
pub unsafe trait FromByteSlice: Sized {
    /// Transmutes an immutable byte slice reference into an immutable `Self` reference.
    ///
    /// # Errors
    ///
    /// Returns an error in case the size doesn't match the type's size.
    fn from_byte_slice(s: &[u8]) -> Result<&Self, InvalidSizeError>;

    /// Transmutes a mutable byte slice reference into a mutable `Self` reference.
    ///
    /// # Errors
    ///
    /// Returns an error in case the size doesn't match the type's size.
    fn from_byte_slice_mut(s: &mut [u8]) -> Result<&mut Self, InvalidSizeError>;

    /// Transmutes an immutable byte slice reference into an immutable to a slice of `Self`.
    ///
    /// # Errors
    ///
    /// Returns an error in case the size isn't a multiple of the type's size.
    fn slice_from_byte_slice(s: &[u8]) -> Result<&[Self], InvalidSizeError>;

    /// Transmutes a mutable byte slice reference into a mutable to a slice of `Self`.
    ///
    /// # Errors
    ///
    /// Returns an error in case the size isn't a multiple of the type's size.
    fn slice_from_byte_slice_mut(s: &mut [u8]) -> Result<&mut [Self], InvalidSizeError>;
}

/// Defines a structure that can be transmuted from/into a byte slice for parsing/constructing binary formats in a
/// zero-copy way.
///
/// The macro achieves this by replacing all multibyte integers with wrapper types that are byte
/// arrays internally and only allowing integer and fixed size array fields in a structure.
///
/// Accepted syntax is similar to a standard structure definition in Rust with some differences:
///
/// * The `struct` keyword is followed by either `little` or `big` keywords if you want fixed
/// endianness or `dynamic` keyword if you want dynamic endianness.
/// * Fields of the generated structure may only have documentation meta, other meta types are
/// disallowed.
///
/// # Examples
///
/// ```rust
/// # use format_struct::format_struct;
/// format_struct! {
///     /// A little-endian test structure.
///     #[derive(Default, Clone)]
///     pub struct little Test {
///         /// this byte is public
///         pub byte: u8,
///         short: u16,
///         word: i32,
///         dword: i64,
///         qword: u128,
///         byte_arr: [u8; 16],
///     }
/// }
/// ```
///
/// It is also possible to define multiple structures in one macro invocation:
///
/// ```rust
/// # use format_struct::format_struct;
/// format_struct! {
///     struct little Foo {
///         byte: u8,
///     }
///
///     struct big Bar {
///         a: u64,
///     }
///
///     pub struct little Baz {
///         z: [u8; 33],
///     }
/// }
/// ```
///
/// # Allowed field types
///
/// Currently only integer types (`u8`, `u16`, `u32`, `u64`, `u128` and their signed counterparts) are allowed and
/// statically sized integer arrays (`[u8; N]`).
///
/// # Layout
///
/// The fields in the structure are laid out in declaration order without any padding. That means that the following
/// structure will take 7 bytes instead of 16 you might expect:
///
/// ```rust
/// # use format_struct::format_struct;
/// format_struct! {
///     struct little SmallStruct {
///         byte: u8,
///         dword: u64,
///     }
/// }
/// ```
#[macro_export]
macro_rules! format_struct {
    ($($(#[$m:meta])* $vis:vis struct $endian:tt $name:ident {
        $($(#[doc = $field_doc:literal])* $field_vis:vis $field_name:ident: $ty:tt),*,
    })+) => {
        $(
            #[repr(C)]
            $(#[$m])*
            $vis struct $name {
                $($(#[doc = $field_doc])*
                $field_vis $field_name: format_struct!(@wrapper_type $ty $endian)),*
            }

            impl $name {
                #[doc = concat!("Converts a byte array into a [`", stringify!($name), "`].")]
                pub fn from_bytes(bytes: [u8; ::core::mem::size_of::<Self>()]) -> Self {
                    unsafe { ::core::mem::transmute(bytes) }
                }
            }

            $crate::format_struct!(@impl_conv $name);

            impl AsRef<[u8]> for $name {
                fn as_ref(&self) -> &[u8] {
                    let ptr = self as *const Self as *const u8;
                    unsafe { ::core::slice::from_raw_parts(ptr, ::core::mem::size_of::<Self>()) }
                }
            }

            impl AsMut<[u8]> for $name {
                fn as_mut(&mut self) -> &mut [u8] {
                    let ptr = self as *mut Self as *mut u8;
                    unsafe { ::core::slice::from_raw_parts_mut(ptr, ::core::mem::size_of::<Self>()) }
                }
            }

            unsafe impl $crate::FromByteSlice for $name {
                fn from_byte_slice(s: &[u8]) -> ::core::result::Result<&Self, $crate::InvalidSizeError> {
                    let bytes: &[u8; ::core::mem::size_of::<Self>()] = ::core::convert::TryInto::try_into(s).map_err(|_| $crate::InvalidSizeError)?;

                    Ok(unsafe { ::core::mem::transmute(bytes) })
                }

                fn from_byte_slice_mut(s: &mut [u8]) -> ::core::result::Result<&mut Self, $crate::InvalidSizeError> {
                    let bytes: &mut [u8; ::core::mem::size_of::<Self>()] = ::core::convert::TryInto::try_into(s).map_err(|_| $crate::InvalidSizeError)?;

                    Ok(unsafe { ::core::mem::transmute(bytes) })
                }

                fn slice_from_byte_slice(s: &[u8]) -> ::core::result::Result<&[Self], $crate::InvalidSizeError> {
                    if s.is_empty() {
                        return Ok(&[]);
                    } else if s.len() % ::core::mem::size_of::<Self>() != 0 {
                        return ::core::result::Result::Err($crate::InvalidSizeError);
                    }

                    let size = s.len() / ::core::mem::size_of::<Self>();
                    let ptr = s.as_ptr() as *const Self;

                    ::core::result::Result::Ok(unsafe { ::core::slice::from_raw_parts(ptr, size) })
                }

                fn slice_from_byte_slice_mut(s: &mut [u8]) -> ::core::result::Result<&mut [Self], $crate::InvalidSizeError> {
                    if s.is_empty() {
                        return Ok(&mut []);
                    } else if s.len() % ::core::mem::size_of::<Self>() != 0 {
                        return ::core::result::Result::Err($crate::InvalidSizeError);
                    }

                    let size = s.len() / ::core::mem::size_of::<Self>();
                    let ptr = s.as_mut_ptr() as *mut Self;

                    ::core::result::Result::Ok(unsafe { ::core::slice::from_raw_parts_mut(ptr, size) })
                }
            }

            impl ::core::fmt::Debug for $name {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    f.debug_struct(stringify!($name))
                        $(.field(stringify!($field_name), &self.$field_name))*
                        .finish()
                }
            }
        )+
    };
    (@impl_conv $name:ident$(<$gen:ident>)?) => {
        impl$(<$gen>)? $name$(<$gen>)? {
            #[doc = concat!(
                "Converts an immutable slice of [`", stringify!($name),
                "`] into an immutable byte slice."
            )]
            pub fn slice_as_byte_slice(slice: &[Self]) -> &[u8] {
                if slice.is_empty() {
                    &[]
                } else {
                    let data = slice.as_ptr() as *const u8;
                    let len = (slice.len() as isize)
                        .checked_mul(::core::mem::size_of::<Self>() as isize)
                        .unwrap() as usize;

                    unsafe { ::core::slice::from_raw_parts(data, len) }
                }
            }

            #[doc = concat!(
                "Converts a mutable slice of [`", stringify!($name), "`] into a mutable byte slice."
            )]
            pub fn slice_as_byte_slice_mut(slice: &mut [Self]) -> &mut [u8] {
                if slice.is_empty() {
                    &mut []
                } else {
                    let data = slice.as_mut_ptr() as *mut u8;
                    let len = (slice.len() as isize)
                        .checked_mul(::core::mem::size_of::<Self>() as isize)
                        .unwrap() as usize;

                    unsafe { ::core::slice::from_raw_parts_mut(data, len) }
                }
            }
        }
    };
    (@endian_type little) => {$crate::LittleEndian};
    (@endian_type big) => {$crate::BigEndian};
    (@endian_type dynamic) => {$crate::Endian};
    (@wrapper_type [$ty:ident; $n:literal] $endian:tt) => {
        [$crate::format_struct!(@wrapper_type $ty $endian); $n]
    };
    (@wrapper_type u8 $endian:tt) => {u8};
    (@wrapper_type i8 $endian:tt) => {i8};
    (@wrapper_type u16 $endian:tt) => {$crate::U16<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type i16 $endian:tt) => {$crate::I16<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type u32 $endian:tt) => {$crate::U32<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type i32 $endian:tt) => {$crate::I32<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type u64 $endian:tt) => {$crate::U64<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type i64 $endian:tt) => {$crate::I64<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type u128 $endian:tt) => {$crate::U128<$crate::format_struct!(@endian_type $endian)>};
    (@wrapper_type i128 $endian:tt) => {$crate::I128<$crate::format_struct!(@endian_type $endian)>};
}

#[cfg(test)]
#[allow(unused, unreachable_pub)]
mod tests {
    use super::*;
    use core::marker::PhantomData;

    format_struct! {
        #[derive(Default, Clone)]
        struct little TestLe {
            /// this is a byte
            /// this is a multiline comment
            #[doc = "this is the third line"]
            byte: u8,
            short: u16,
            word: u32,
            dword: u64,
            qword: u128,
            byte_arr: [u8; 16],
            short_arr: [u16; 16],
        }

        #[derive(Default, Clone)]
        struct big TestBe {
            pub byte: u8,
            short: u16,
            word: u32,
            dword: u64,
            qword: u128,
            byte_arr: [u8; 16],
            short_arr: [u16; 16],
        }

        #[derive(Default, Clone)]
        struct dynamic TestDyn {
            byte: u8,
            short: u16,
            word: u32,
            dword: u64,
            qword: u128,
            byte_arr: [u8; 16],
            short_arr: [u16; 16],
        }
    }

    #[test]
    fn test_access_short_arr() {
        let mut test_le = TestLe::default();

        for (i, s) in test_le.short_arr.iter_mut().enumerate() {
            *s = U16((i as u16).to_le_bytes(), PhantomData);
        }

        assert_eq!(test_le.short_arr[5].get(), 5);
    }

    #[test]
    fn test_access_u8() {
        let mut test = TestLe::default();

        test.byte = 42;
        assert_eq!(test.byte, 42);
    }

    #[test]
    fn test_access_u16() {
        let mut test_le = TestLe::default();
        test_le.short = U16::new(1337);
        assert_eq!(test_le.short.get(), 1337);
        assert_eq!(test_le.short.0, 1337u16.to_le_bytes());

        let mut test_be = TestBe::default();
        test_be.short = U16::new(1337);
        assert_eq!(test_be.short.get(), 1337);
        assert_eq!(test_be.short.0, 1337u16.to_be_bytes());
    }

    #[test]
    fn test_access_u32() {
        let mut test_le = TestLe::default();
        test_le.word = U32::new(13371337);
        assert_eq!(test_le.word.get(), 13371337);
        assert_eq!(test_le.word.0, 13371337u32.to_le_bytes());

        let mut test_be = TestBe::default();
        test_be.word = U32::new(13371337);
        assert_eq!(test_be.word.get(), 13371337);
        assert_eq!(test_be.word.0, 13371337u32.to_be_bytes());
    }

    #[test]
    fn test_access_u64() {
        let mut test_le = TestLe::default();
        test_le.dword = U64::new(1337133713371337);
        assert_eq!(test_le.dword.get(), 1337133713371337);
        assert_eq!(test_le.dword.0, 1337133713371337u64.to_le_bytes());

        let mut test_be = TestBe::default();
        test_be.dword = U64::new(1337133713371337);
        assert_eq!(test_be.dword.get(), 1337133713371337);
        assert_eq!(test_be.dword.0, 1337133713371337u64.to_be_bytes());
    }

    #[test]
    fn test_access_u128() {
        let mut test_le = TestLe::default();
        test_le.qword = U128::new(13371337133713371337133713371337);
        assert_eq!(test_le.qword.get(), 13371337133713371337133713371337u128);
        assert_eq!(
            test_le.qword.0,
            13371337133713371337133713371337u128.to_le_bytes()
        );

        let mut test_be = TestBe::default();
        test_be.qword = U128::new(13371337133713371337133713371337u128);
        assert_eq!(test_be.qword.get(), 13371337133713371337133713371337);
        assert_eq!(
            test_be.qword.0,
            13371337133713371337133713371337u128.to_be_bytes()
        );
    }
}