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
//! This crate provides macros for working with bytes and hexadecimal values.
//!
//! # `hex!`
//!
//! [`hex!`](hex!) is a macro which converts string literals (`"7D2B"`) to byte arrays (`[0x7D, 0x2B]`) or match patterns at compile time.
//!
//! ```
//! assert_eq!(hex!("01020304"), [1, 2, 3, 4]);
//! ```
//! # `parse_struct!`
//!
//! [`parse_struct!`](parse_struct!) is a macro for parsing bytes from [`Read`](std::io::Read) readers
//! into structs (or enums), with the ability to skip padding bytes.
//! It returns a `Result<Struct, std::io::Error>` value.
//!
//! ```
//! use hex_magic::parse_struct;
//! use std::io::{Read, Result};
//!
//! #[derive(Debug)]
//! struct Data {
//!     a: [u8; 2],
//!     b: u32,
//! }
//!
//! fn main() -> Result<()> {
//!     let bytes = [
//!         0x48, 0x45, 0x58, 0x00, 0x01, 0x02, 0x00, 0xAA, 0xBB, 0xCC, 0xDD,
//!     ];
//!     let data = parse_struct!(bytes.as_ref() => Data {
//!         _: b"HEX",
//!         _: [0],
//!         a: [0x01, _],
//!         _: "00",
//!         b: buf @ "AABB ____" => u32::from_le_bytes(*buf),
//!     })?;
//!     println!("{:X?}", data); // Data { a: [1, 2], b: DDCCBBAA }
//!     Ok(())
//! }
//! ```
use proc_macro::TokenStream;
use quote::quote;
use syn::parse_macro_input;

mod hex_string;
mod parse_struct;
use hex_string::HexString;
use parse_struct::HexStruct;

/// Macro which converts string literals (`"7D2B"`) to byte arrays (`[0x7D, 0x2B]`) at compile time.
///
/// It's a rewrite of the `hex!` macro provided by the [`hex-literal`](https://docs.rs/hex-literal/) crate
/// with stricter rules requiring bytes to come in pairs (so `"12 34"` is allowed but `"1 2 3 4"` is
/// not) and with the addition of being able to parse `__` and `..` to create match patterns.
///
/// It accepts the following characters in the input string:
///
/// - `'0'...'9'`, `'a'...'f'`, `'A'...'F'` -- hex characters which will be used
///     in construction of the output byte array
/// - `' '`, `'\r'`, `'\n'`, `'\t'` -- formatting characters which will be
///     ignored
/// - `'_'`, `'.'` -- formatting characters which will be used to create match patterns
///
/// # Example
///
/// ```
/// use hex_magic::hex;
///
/// const BYTES: [u8; 3] = hex!("DEAD AF");
///
/// fn main() {
///     assert_eq!(BYTES, [0xDE, 0xAD, 0xAF]);
///     assert_eq!(hex!("aA aa aA Aa aa"), [0xAA; 5]);
///
///     match [1, 2, 3, 4] {
///         hex!("AABBCCDD") => panic!("bytes don't match at all"),
///         hex!("01__FF__") => panic!("[1, _, 0xFF, _] does not match"),
///         hex!("01..04") => println!("[1, .., 4] would match"),
///         hex!("..") => unreachable!("[..] would match"),
///     }
/// }
/// ```
#[proc_macro]
pub fn hex(stream: TokenStream) -> TokenStream {
    let input = parse_macro_input!(stream as HexString);
    TokenStream::from(quote!(#input))
}

/// Macro for parsing bytes from [`Read`](std::io::Read) readers into structs
/// with the ability to skip padding bytes.
///
/// # Syntax
///
/// ```
/// parse_struct!(READER => STRUCT {
///     ...
///     FIELD: [BINDING @] BYTE_PATTERN [=> EXPRESSION],
///     ...
/// })
/// ```
///
/// First, the macro expects a reader or an expression the result of which would be a reader.
/// The reader is followed by `=>` and then by a modified form of struct instantiation.
///
/// The basic syntax of struct instantiation takes the form of `FIELD: BYTE_PATTERN`. This will assign
/// the read bytes (`[u8; N]`) to the given field if it matches the pattern.
/// For more advanced scenarios, such as for converting the bytes to other types,
/// bindings and expressions can be used:
/// `FIELD: BINDING @ BYTE_PATTERN => EXPRESSION`.
/// In this case, the result of `EXPRESSION` will be assigned to `FIELD`.
///
/// A special `_` field is available for matching against bytes without including them in the
/// struct. `_` fields can be specified multiple times and
/// can be used for skipping padding bytes or for matching against bytes without including them in
/// the struct. Bindings and expressions can be used with these fields as well but expressions must
/// evaluate to ().
///
/// Patterns can be any of:
/// - `[1, 2, 3, _, 5]` - standard byte array patterns
/// - `b"byte string!"` - byte strings
/// - `"FF00FF 00FF00"` - hex strings usable with the [`hex!`](hex!) macro
///
/// Patterns can include `_` but not `..` wildcards since the length of the pattern is
/// used to determine the amount of bytes to read.
///
/// Structs or enum variants with unnamed members (`Item(A, B)`) can be used with the
/// `Struct { 0: ..., 1: ... }` syntax.
///
/// This macro returns `Result` containing either the resulting struct
/// or [`std::io::Error`](std::io::Error) if an error occurred while reading or matching the bytes.
/// [`std::io::ErrorKind::InvalidData`](std::io::ErrorKind::InvalidData)
/// if the bytes were not matched successfully.
///
/// # Example
///
/// ```
/// use hex_magic::parse_struct;
/// use std::io::{Read, Result};
///
/// #[derive(Debug)]
/// struct Data {
///     a: [u8; 2],
///     b: u32,
/// }
///
/// fn main() -> Result<()> {
///     let bytes = [
///         0x48, 0x45, 0x58, 0x00, 0x01, 0x02, 0x00, 0xAA, 0xBB, 0xCC, 0xDD,
///     ];
///     let data = parse_struct!(bytes.as_ref() => Data {
///         _: b"HEX",
///         _: [0],
///         a: [0x01, _],
///         _: "00",
///         b: buf @ "AABB ____" => u32::from_le_bytes(*buf),
///     })?;
///     println!("{:X?}", data); // Data { a: [1, 2], b: DDCCBBAA }
///     Ok(())
/// }
/// ```
///
/// # Details
///
/// This macro would be parsed into a closure which is instantly called so that any
/// potential errors caused by `Read` can be handled explicitly by the user.
///
/// The macro in the example above would be parsed into the following code
/// (internal variable names prefixed with `_` changed for clarity):
///
/// ```
/// (|| {
///     use std::convert::TryInto;
///     #[allow(non_snake_case)]
///     let mut _READER = bytes.as_ref();
///     #[allow(non_snake_case)]
///     let mut _ARRAY: [u8; 4usize] = [0; 4usize]; // length of the longest pattern
///     let _: () = {
///         _READER.read_exact(&mut _ARRAY[0..3usize])?;
///         #[allow(non_snake_case)]
///         let _BUFFER: &[u8; 3usize] = _ARRAY[0..3usize].try_into().unwrap();
///         #[allow(dead_code)]
///         match _BUFFER {
///             [72u8, 69u8, 88u8] => (), // b"HEX"
///             _ => {
///                 return Err(std::io::Error::new(
///                     std::io::ErrorKind::InvalidData,
///                     format!("expected `{}`, got `{:02X?}`", "b\"HEX\"", _BUFFER),
///                 ))
///             }
///         }
///     };
///     let _: () = {
///         _READER.read_exact(&mut _ARRAY[0..1usize])?;
///         #[allow(non_snake_case)]
///         let _BUFFER: &[u8; 1usize] = _ARRAY[0..1usize].try_into().unwrap();
///         #[allow(dead_code)]
///         match _BUFFER {
///             [0] => (),
///             _ => {
///                 return Err(std::io::Error::new(
///                     std::io::ErrorKind::InvalidData,
///                     format!("expected `{}`, got `{:02X?}`", "[0]", _BUFFER),
///                 ))
///             }
///         }
///     };
///     let _a = {
///         _READER.read_exact(&mut _ARRAY[0..2usize])?;
///         #[allow(non_snake_case)]
///         let _BUFFER: &[u8; 2usize] = _ARRAY[0..2usize].try_into().unwrap();
///         #[allow(dead_code)]
///         match _BUFFER {
///             [0x01, _] => (),
///             _ => {
///                 return Err(std::io::Error::new(
///                     std::io::ErrorKind::InvalidData,
///                     format!("expected `{}`, got `{:02X?}`", "[0x01, _]", _BUFFER),
///                 ))
///             }
///         }
///         *_BUFFER // [u8; 2] as the result if no expression given
///     };
///     let _: () = {
///         _READER.read_exact(&mut _ARRAY[0..1usize])?;
///         #[allow(non_snake_case)]
///         let _BUFFER: &[u8; 1usize] = _ARRAY[0..1usize].try_into().unwrap();
///         #[allow(dead_code)]
///         match _BUFFER {
///             [0u8] => (),
///             _ => {
///                 return Err(std::io::Error::new(
///                     std::io::ErrorKind::InvalidData,
///                     format!("expected `{}`, got `{:02X?}`", "[0x00]", _BUFFER),
///                 ))
///             }
///         }
///     };
///     let _b = {
///         _READER.read_exact(&mut _ARRAY[0..4usize])?;
///         #[allow(non_snake_case)]
///         let buf: &[u8; 4usize] = _ARRAY[0..4usize].try_into().unwrap(); // assign binding
///         #[allow(dead_code)]
///         match buf {
///             [170u8, 187u8, _, _] => (), // "AABB ____"
///             _ => {
///                 return Err(std::io::Error::new(
///                     std::io::ErrorKind::InvalidData,
///                     format!("expected `{}`, got `{:02X?}`", "[0xAA, 0xBB, _, _]", buf),
///                 ))
///             }
///         }
///         u32::from_le_bytes(*buf) // provided expression
///     };
///     Ok(Data { a: _a, b: _b }) // `_` fields are not included in the resulting struct
/// })()
/// ```
#[proc_macro]
pub fn parse_struct(stream: TokenStream) -> TokenStream {
    let input = parse_macro_input!(stream as HexStruct);
    TokenStream::from(quote!(#input))
}