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
extern crate proc_macro;
mod utils;
use crate::utils::{
extract_formatting_positions, generate_intermediate_bytestrings,
FormatArgs,
};
use proc_macro2::TokenStream;
use proc_macro_hack::proc_macro_hack;
use quote::quote;
use syn::parse_macro_input;
#[proc_macro_hack]
pub fn format_bytes(
input: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let args = parse_macro_input!(input as FormatArgs);
inner_format_bytes(&args).into()
}
fn inner_format_bytes(args: &FormatArgs) -> TokenStream {
let format_string = &args.format_string;
let input = format_string.value();
let positions = match extract_formatting_positions(&input) {
Ok(pos) => pos,
Err(_) => {
return quote! {compile_error!("unclosed formatting delimiter")}
}
};
if positions.len() > args.positional_args.len() {
return quote! {compile_error!("not enough arguments for formatting")};
}
if positions.len() < args.positional_args.len() {
return quote! {compile_error!("too many arguments for formatting")};
}
if positions.is_empty() {
return quote! {#format_string.to_vec()};
}
let parts = generate_intermediate_bytestrings(args, &input, &positions);
quote! (
{
let mut res: Vec<u8> = vec![];
#(res.extend(#parts);)*
res
}
)
}