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
extern crate proc_macro;
use proc_macro::{TokenStream};
use quote::{__private::Span, quote, quote_spanned};
use syn::{
parenthesized, parse_macro_input, spanned::Spanned, AngleBracketedGenericArguments, Data,
DeriveInput, Fields, LitInt,
};
#[proc_macro_derive(BeBytes, attributes(U8))]
pub fn derive_be_bytes(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident.clone();
let my_trait_path: syn::Path = syn::parse_str("BeBytes").unwrap();
let mut field_limit_check = Vec::new();
let mut errors = Vec::new();
let mut field_parsing = Vec::new();
let mut field_writing = Vec::new();
// initialize the bit sum to 0
match input.data {
Data::Struct(data) => match data.fields {
Fields::Named(fields) => {
let mut total_size: usize = 0;
let mut non_bit_fields = 0;
// let mut u8_bit_sum = 0;
let last_field = fields.named.last();
let mut is_last_field = false;
for field in fields.named.clone().into_iter() {
if let Some(last_field) = last_field {
is_last_field = last_field.ident == field.ident;
}
// initialize u8 flag to false
let mut u8_attribute_present = false;
// get the attributes of the field
let attributes = field.attrs.clone();
// get the name of the field
let field_name = field.ident.clone().unwrap();
// get the type of the field
let field_type = &field.ty;
let (pos, size) = parse_u8_attribute(
attributes,
&mut u8_attribute_present,
&mut errors,
&mut non_bit_fields,
);
// check if the U8 attribute is present
if u8_attribute_present {
let number_length = get_number_size(field_type, &field, &mut errors)
.unwrap_or_else(|| {
let error =
syn::Error::new(field_type.span(), "Type not supported'");
errors.push(error.to_compile_error());
0
}); // retrieve position and size from attributes
if pos.is_none() && size.is_none() {
let error = syn::Error::new(
field.span(),
"U8 attribute must have a size and a position",
);
errors.push(error.to_compile_error());
continue;
}
// Deal with the position and size
if let (Some(pos), Some(size)) = (pos, size) {
// set the bit mask
let mask = (1 << size) - 1;
// add runtime check if the value requested is in the valid range for that type
field_limit_check.push(quote! {
if #field_name > #mask as #field_type {
let err_msg = format!(
"Value of field {} is out of range (max value: {})",
stringify!(#field_name),
#mask
);
let err = std::io::Error::new(std::io::ErrorKind::Other, err_msg);
return Err(std::boxed::Box::new(err));
}
});
// increase the bit sum by the size requested
// u8_bit_sum += size;
// check which byte we're in
let u8_byte_index = total_size / 8;
// check if the position is in sequence
if pos != total_size {
let message = format!(
"U8 attributes must obey the sequence specified by the previous attributes. Expected position {} but got {}",
total_size, pos
);
errors.push(
syn::Error::new_spanned(&field, message).to_compile_error(),
);
}
// add the parsing code for the field
if number_length > 1 {
let chunks = generate_chunks(number_length, syn::Ident::new("chunk", Span::call_site()));
field_parsing.push(quote! {
let mut inner_total_size = #total_size;
// Initialize the field
let mut #field_name: #field_type = 0;
// In order to use the mask, we need to reset the multi-byte
// field to it's original position
// To do that, we can iterate over chunks of the bytes array
bytes.chunks(#number_length).for_each(|chunk| {
// First we parse the chunk into the field type
let u_type = #field_type::from_be_bytes(#chunks);
// println!("{}: {:016b}", stringify!(#field_name), u_type);
// Then we shift the u_type to the right based on its actual size
// If the field size attribute is 14, we need to shift 2 bytes to the right
// If the field size attribute is 16, we need to shift 0 bytes to the right
let shift_left = bit_sum % 8;
let left_shifted_u_type = u_type << shift_left;
// println!("Shifted u_type: {:016b}", left_shifted_u_type);
let shift_right = 8 * #number_length - #size;
// println!("Shift right: {}", shift_right);
let shifted_u_type = left_shifted_u_type >> shift_right;
// println!("Shifted u_type: {:016b}", shifted_u_type);
// Then we mask the shifted value to delete unwanted bits
// and that becomes the field value
#field_name = shifted_u_type & #mask as #field_type;
// println!("{}: {:016b}", stringify!(#field_name), #field_name);
bit_sum += #size;
});
});
field_writing.push(quote! {
if (#field_name) & !(#mask as #field_type) != 0 {
panic!(
"Value {} for field {} exceeds the maximum allowed value {}.",
#field_name,
stringify!(#field_name),
#mask
);
}
let mut inner_total_size = #total_size;
// println!("{}: {:016b}", stringify!(#field_name), #field_name);
let masked_value = #field_name & #mask as #field_type;
// The shift factor tells us about the current position in the byte
// It's the size of the number in bits minus the size requested in bits
// plus the current position in the byte
// println!("Number size {}, Requested size {}, Position {}", #number_length * 8, #size, #pos%8);
let shift_left = (#number_length * 8) - #size;
let shift_right = (#pos % 8);
// println!("Shift left {}, Shift right {}", shift_left, shift_right);
// The shifted value aligns the value with the current position in the byte
let shifted_masked_value = (masked_value << shift_left) >> shift_right;
// println!("Shifted value: {:016b}", shifted_masked_value);
// We split the value into bytes
let byte_values = #field_type::to_be_bytes(shifted_masked_value);
// Iterating over the bytes. The first byte always fills a byte completely.
// The following bytes will fill the second, third, ... byte and so on. So,
// we need to increase the index value in the bytes array by the index of the
// current byte in the input sequence.
// The last byte may or may not fill the byte completely.
for i in 0..#number_length {
if bytes.len() <= #u8_byte_index + i {
bytes.resize(#u8_byte_index + i + 1, 0);
}
// println!("Bytes len {}, resize {}", bytes.len(), #u8_byte_index + i);
// println!("Byte value: {:08b}", byte_values[i]);
bytes[#u8_byte_index + i] |= byte_values[i];
// println!("Byte: {:08b}", bytes[#u8_byte_index + i]);
inner_total_size = inner_total_size + (8 - shift_right);
}
});
} else {
field_parsing.push(quote! {
bit_sum += #size;
let shift_factor = 8 - #total_size % 8;
let #field_name = (bytes[#u8_byte_index] >> (7 - (#size + #pos % 8 - 1) as #field_type )) & (#mask as #field_type);
});
// add the writing code for the field
field_writing.push(quote! {
if (#field_name) & !(#mask as #field_type) != 0 {
panic!(
"Value {} for field {} exceeds the maximum allowed value {}.",
#field_name,
stringify!(#field_name),
#mask
);
}
if bytes.len() <= #u8_byte_index {
bytes.resize(#u8_byte_index + 1, 0);
}
bytes[#u8_byte_index] |= (#field_name as u8) << (7 - (#size - 1) - #pos % 8 );
// println!("Value: {:08b}, Size: {}, Pos: {}, Shift: {}", #field_name, #size, #pos, 7 - (#size - 1) - #pos);
});
}
// println!("total_size {}, size {}", total_size, size);
total_size += size;
}
} else {
// if field is not U8, total_size has to be a multiple of 8
if total_size % 8 != 0 {
errors.push(
syn::Error::new_spanned(
&field,
"U8 attributes must add up to 8 before any other field",
)
.to_compile_error(),
);
}
// supported types
match field_type {
// if field is number type, we apply be bytes conversion
syn::Type::Path(tp)
if tp.path.is_ident("i8")
|| tp.path.is_ident("u8")
|| tp.path.is_ident("i16")
|| tp.path.is_ident("u16")
|| tp.path.is_ident("i32")
|| tp.path.is_ident("u32")
|| tp.path.is_ident("f32")
|| tp.path.is_ident("i64")
|| tp.path.is_ident("u64")
|| tp.path.is_ident("f64")
|| tp.path.is_ident("i128")
|| tp.path.is_ident("u128") =>
{
// get the size of the number in bytes
let field_size =
match get_number_size(field_type, &field, &mut errors) {
Some(value) => value,
None => continue,
};
// write the parse and writing code for the field
parse_write_number(
field_size,
&mut field_parsing,
&field_name,
field_type,
&mut field_writing,
);
}
// if field is an Array
syn::Type::Array(tp) => {
// get the size of the array
let array_length: usize;
let len = tp.len.clone();
match len {
syn::Expr::Lit(expr_lit) => {
if let syn::Lit::Int(token) = expr_lit.lit {
array_length = token.base10_parse().unwrap();
} else {
let error = syn::Error::new(
field.ty.span(),
"Expected integer type for N",
);
errors.push(error.to_compile_error());
continue;
}
}
_ => {
let error = syn::Error::new(
tp.span(),
"Unsupported type for [T; N]",
);
errors.push(error.to_compile_error());
continue;
}
}
if let syn::Type::Path(elem) = *tp.elem.clone() {
// Retrieve type segments
let syn::TypePath {
path: syn::Path { segments, .. },
..
} = elem;
match &segments[0] {
syn::PathSegment {
ident,
arguments: syn::PathArguments::None,
} if ident == "u8" => {
field_parsing.push(quote! {
byte_index = bit_sum / 8;
// println!("{} by te_index: {} bit_sum: {}", stringify!(#field_name), byte_index, bit_sum);
let mut #field_name = [0u8; #array_length];
#field_name.copy_from_slice(&bytes[byte_index..#array_length]);
bit_sum += 8 * #array_length;
});
field_writing.push(quote! {
// Vec type
bytes.extend_from_slice(&#field_name);
});
}
_ => {
let error = syn::Error::new(
field.ty.span(),
"Unsupported type for [T; N]",
);
errors.push(error.to_compile_error());
continue;
}
};
}
}
// if field is a non-empty Vec
syn::Type::Path(tp)
if !tp.path.segments.is_empty()
&& tp.path.segments[0].ident == "Vec" =>
{
let inner_type = match solve_for_inner_type(tp, "Vec") {
Some(t) => t,
None => {
let error = syn::Error::new(
field.ty.span(),
"Unsupported type for Vec<T>",
);
errors.push(error.to_compile_error());
continue;
}
};
if let syn::Type::Path(inner_tp) = &inner_type {
if inner_tp.path.is_ident("i8")
|| inner_tp.path.is_ident("u8")
|| inner_tp.path.is_ident("i16")
|| inner_tp.path.is_ident("u16")
|| inner_tp.path.is_ident("i32")
|| inner_tp.path.is_ident("u32")
|| inner_tp.path.is_ident("f32")
|| inner_tp.path.is_ident("i64")
|| inner_tp.path.is_ident("u64")
|| inner_tp.path.is_ident("f64")
|| inner_tp.path.is_ident("i128")
|| inner_tp.path.is_ident("u128")
{
field_parsing.push(quote! {
// Vec type
byte_index = bit_sum / 8;
// println!("{} byte_index: {} bit_sum: {}", stringify!(#field_name), byte_index, bit_sum);
let #field_name = Vec::from(&bytes[byte_index..]);
});
field_writing.push(quote! {
// Vec type
bytes.extend_from_slice(&#field_name);
});
// If the current field is not the last field, raise an error
if !is_last_field {
let error = syn::Error::new(
field.ty.span(),
"Vectors can only be used for padding the end of a struct",
);
errors.push(error.to_compile_error());
}
} else {
let error = syn::Error::new(
inner_type.span(),
"Unsupported type for Vec<T>",
);
errors.push(error.to_compile_error());
continue;
}
}
}
syn::Type::Path(tp)
if !tp.path.segments.is_empty()
&& tp.path.segments[0].ident == "Option" =>
{
// if field is a non-empty Option
if !tp.path.segments.is_empty()
&& tp.path.segments[0].ident == "Option"
{
let inner_type = match solve_for_inner_type(tp, "Option") {
Some(t) => t,
None => {
let error = syn::Error::new(
field.ty.span(),
"Unsupported type for Option<T>",
);
errors.push(error.to_compile_error());
continue;
}
};
if let syn::Type::Path(inner_tp) = &inner_type {
if inner_tp.path.is_ident("i8")
|| inner_tp.path.is_ident("u8")
|| inner_tp.path.is_ident("i16")
|| inner_tp.path.is_ident("u16")
|| inner_tp.path.is_ident("i32")
|| inner_tp.path.is_ident("u32")
|| inner_tp.path.is_ident("f32")
|| inner_tp.path.is_ident("i64")
|| inner_tp.path.is_ident("u64")
|| inner_tp.path.is_ident("f64")
|| inner_tp.path.is_ident("i128")
|| inner_tp.path.is_ident("u128")
{
// get the size of the number in bytes
let field_size = match get_number_size(
&inner_type,
&field,
&mut errors,
) {
Some(value) => value,
None => continue,
};
field_parsing.push(quote! {
// Option type
byte_index = bit_sum / 8;
end_byte_index = byte_index + #field_size;
let #field_name = if bytes[byte_index..end_byte_index] == [0_u8; #field_size] {
None
} else {
// println!("{} byte_index: {} bit_sum: {}", stringify!(#field_name), byte_index, bit_sum);
bit_sum += 8 * #field_size;
Some(<#inner_tp>::from_be_bytes({
let slice = &bytes[byte_index..end_byte_index];
let mut arr = [0; #field_size];
arr.copy_from_slice(slice);
arr
}))
};
});
field_writing.push(quote! {
bytes.extend_from_slice(&#field_name.unwrap_or(0).to_be_bytes());
});
} else {
let error = syn::Error::new(
inner_type.span(),
"Unsupported type for Option<T>",
);
errors.push(error.to_compile_error());
continue;
}
}
}
}
syn::Type::Path(tp)
if !tp.path.segments.is_empty()
&& !is_primitive_type(&tp.path.segments[0].ident) =>
{
// Struct case
field_parsing.push(quote_spanned! { field.span() =>
byte_index = bit_sum / 8;
let predicted_size = core::mem::size_of::<#field_type>();
end_byte_index = byte_index + predicted_size;
// println!("{} byte_index: {} bit_sum: {}", stringify!(#field_name), byte_index, bit_sum);
bit_sum += (end_byte_index - byte_index) * 8;
let (#field_name, bytes_written) = #field_type::try_from_be_bytes(&bytes[byte_index..end_byte_index])?;
// println!("---------- {} bytes_written: {}", stringify!(#field_name), bytes_written);
bit_sum -= (predicted_size - bytes_written) * 8;
});
field_writing.push(quote_spanned! { field.span() =>
bytes.extend_from_slice(&message_macro::BeBytes::to_be_bytes(&#field_name));
});
}
_ => {
let error_message =
format!("Unsupported type for field {}", field_name);
let error = syn::Error::new(field.ty.span(), error_message);
errors.push(error.to_compile_error());
continue;
}
}
}
}
let struct_field_names = fields.named.iter().map(|f| &f.ident).collect::<Vec<_>>();
let constructor_arg_list = fields.named.iter().map(|f| {
let field_ident = &f.ident;
let field_type = &f.ty;
quote! { #field_ident: #field_type }
});
let expanded = quote! {
impl #my_trait_path for #name {
fn try_from_be_bytes(bytes: &[u8]) -> Result<(Self, usize), Box<dyn std::error::Error>> {
let mut bit_sum = 0;
let mut byte_index = 0;
let mut end_byte_index = 0;
#(#field_parsing)*
Ok((Self {
#( #struct_field_names, )*
}, bit_sum / 8))
}
fn to_be_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::new();
#( {
let #struct_field_names = self.#struct_field_names.to_owned();
#field_writing
} )*
bytes
}
fn field_size(&self) -> usize {
std::mem::size_of_val(self)
}
}
impl #name {
#[allow(clippy::too_many_arguments)]
pub fn new(#(#constructor_arg_list,)*) -> Result<Self, Box<dyn std::error::Error>> {
#(#field_limit_check)*
Ok(Self {
#( #struct_field_names, )*
})
}
}
};
let output = quote! {
#expanded
#(#errors)*
};
output.into()
}
field => {
let error = syn::Error::new(field.span(), "Only named fields are supported")
.to_compile_error();
let output = quote! {
#error
};
output.into()
}
},
Data::Enum(data_enum) => {
// eprintln!("data_enum {:#?}", data_enum);
let variants = data_enum.variants;
let values = variants
.iter()
.enumerate()
.map(|(index, variant)| {
let ident = &variant.ident;
let mut assigned_value = index as u8;
if let Some((_, syn::Expr::Lit(expr_lit))) = &variant.discriminant {
if let syn::Lit::Int(token) = &expr_lit.lit {
assigned_value = token.base10_parse().unwrap();
}
};
(ident, assigned_value)
})
.collect::<Vec<_>>();
let from_be_bytes_arms = values.iter().map(|(ident, assigned_value)| {
quote! {
#assigned_value => Ok((Self::#ident, 1)),
}
});
let to_be_bytes_arms = values.iter().map(|(ident, assigned_value)| {
quote! {
Self::#ident => #assigned_value as u8,
}
});
let expanded = quote! {
impl #my_trait_path for #name {
fn try_from_be_bytes(bytes: &[u8]) -> Result<(Self, usize), Box<dyn std::error::Error>> {
if bytes.is_empty() {
return Err(Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "No bytes provided.")));
}
let value = bytes[0];
match value {
#(#from_be_bytes_arms)*
_ => Err(Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "No matching variant found."))),
}
}
fn to_be_bytes(&self) -> Vec<u8> {
let mut bytes = Vec::new();
let val = match self {
#(#to_be_bytes_arms)*
};
bytes.push(val);
bytes
}
fn field_size(&self) -> usize {
std::mem::size_of_val(self)
}
}
};
expanded.into()
}
_ => {
let error =
syn::Error::new(Span::call_site(), "Type is not supported").to_compile_error();
let output = quote! {
#error
};
output.into()
}
}
}
fn parse_write_number(
field_size: usize,
field_parsing: &mut Vec<quote::__private::TokenStream>,
field_name: &syn::Ident,
field_type: &syn::Type,
field_writing: &mut Vec<quote::__private::TokenStream>,
) {
field_parsing.push(quote! {
byte_index = bit_sum / 8;
// println!("{} pwn byte_index: {} bit_sum: {}", stringify!(#field_name), byte_index, bit_sum);
end_byte_index = byte_index + #field_size;
bit_sum += 8 * #field_size;
let #field_name = <#field_type>::from_be_bytes({
let slice = &bytes[byte_index..end_byte_index];
let mut arr = [0; #field_size];
arr.copy_from_slice(slice);
arr
});
});
field_writing.push(quote! {
// bytes[#byte_index..#end_byte_index].copy_from_slice(&#field_name.to_be_bytes());
bytes.extend_from_slice(&#field_name.to_be_bytes());
});
}
fn get_number_size(
field_type: &syn::Type,
field: &syn::Field,
errors: &mut Vec<quote::__private::TokenStream>,
) -> Option<usize> {
if let syn::Type::Path(ref tp) = field_type {
if let Some(inner_type) = solve_for_inner_type(tp, "Vec") {
return match &inner_type {
syn::Type::Path(tp) if tp.path.is_ident("u8") => Some(1),
_ => {
let error = syn::Error::new(inner_type.span(), "Unsupported type for Vec<T>");
errors.push(error.to_compile_error());
None
}
};
}
}
let field_size = match &field_type {
syn::Type::Path(tp) if tp.path.is_ident("i8") || tp.path.is_ident("u8") => 1,
syn::Type::Path(tp) if tp.path.is_ident("i16") || tp.path.is_ident("u16") => 2,
syn::Type::Path(tp)
if tp.path.is_ident("i32") || tp.path.is_ident("u32") || tp.path.is_ident("f32") =>
{
4
}
syn::Type::Path(tp)
if tp.path.is_ident("i64") || tp.path.is_ident("u64") || tp.path.is_ident("f64") =>
{
8
}
syn::Type::Path(tp) if tp.path.is_ident("i128") || tp.path.is_ident("u128") => 16,
_ => {
let error = syn::Error::new(field.ty.span(), "Unsupported type");
errors.push(error.to_compile_error());
return None;
}
};
Some(field_size)
}
fn parse_u8_attribute(
attributes: Vec<syn::Attribute>,
u8_attribute_present: &mut bool,
errors: &mut Vec<quote::__private::TokenStream>,
non_bit_fields: &mut usize,
) -> (Option<usize>, Option<usize>) {
let mut pos = None;
let mut size = None;
for attr in attributes {
if attr.path().is_ident("U8") {
*u8_attribute_present = true;
let nested_result = attr.parse_nested_meta(|meta| {
if meta.path.is_ident("pos") || meta.path.is_ident("size") {
if meta.path.is_ident("pos") {
let content;
parenthesized!(content in meta.input);
let lit: LitInt = content.parse()?;
let n: usize = lit.base10_parse()?;
pos = Some(n);
return Ok(());
}
if meta.path.is_ident("size") {
let content;
parenthesized!(content in meta.input);
let lit: LitInt = content.parse()?;
let n: usize = lit.base10_parse()?;
size = Some(n);
return Ok(());
}
} else {
return Err(meta.error(
"Allowed attributes are `pos` and `size` - Example: #[U8(pos=1, size=3)]"
.to_string(),
));
}
Ok(())
});
if let Err(e) = nested_result {
errors.push(e.to_compile_error());
}
} else {
*non_bit_fields += 1;
}
}
(pos, size)
}
/// Given a type and an identifier, `solve_for_inner_type` attempts to retrieve the inner type of the input type
/// that is wrapped by the provided identifier. If the input type does not contain the specified identifier or
/// has more than one generic argument, the function returns `None`.
fn solve_for_inner_type(input: &syn::TypePath, identifier: &str) -> Option<syn::Type> {
// Retrieve type segments
let syn::TypePath {
path: syn::Path { segments, .. },
..
} = input;
let args = match &segments[0] {
syn::PathSegment {
ident,
arguments:
syn::PathArguments::AngleBracketed(AngleBracketedGenericArguments { args, .. }),
} if ident == identifier && args.len() == 1 => args,
_ => return None,
};
let inner_type = match &args[0] {
syn::GenericArgument::Type(t) => t,
_ => return None,
};
Some(inner_type.clone())
}
// Helper function to check if a given identifier is a primitive type
fn is_primitive_type(ident: &syn::Ident) -> bool {
let primitives = [
"u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize",
"f32", "f64", "char", "bool", "str",
];
primitives.iter().any(|&primitive| ident == primitive)
}
fn generate_chunks(n: usize, array_ident: proc_macro2::Ident) -> proc_macro2::TokenStream {
let indices: Vec<_> = (0..n).map(|i| quote! { #array_ident[#i] }).collect();
quote! { [ #( #indices ),* ] }
}