bebytes_derive 2.10.1

A macro to generate/parse binary representation of messages with custom bit fields
Documentation
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
use proc_macro2::TokenStream;
use syn::{Error as SynError, Ident};

#[cfg(feature = "std")]
use std::vec::Vec;

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

/// Error aggregation type for handling multiple parse errors
pub type ParseResult<T> = Result<T, Vec<SynError>>;

/// Processing context to thread through computations
#[derive(Clone, Debug)]
pub struct ProcessingContext {
    pub endianness: crate::consts::Endianness,
    pub bit_position: usize,
    pub is_last_field: bool,
}

impl ProcessingContext {
    pub fn new(endianness: crate::consts::Endianness) -> Self {
        Self {
            endianness,
            bit_position: 0,
            is_last_field: false,
        }
    }

    pub fn with_bit_position(mut self, bit_position: usize) -> Self {
        self.bit_position = bit_position;
        self
    }

    pub fn with_last_field(mut self, is_last_field: bool) -> Self {
        self.is_last_field = is_last_field;
        self
    }
}

/// Result of processing a single field
#[derive(Debug, Clone)]
pub struct FieldProcessResult {
    pub limit_check: TokenStream,
    pub parsing: TokenStream,
    pub writing: TokenStream,
    pub direct_writing: TokenStream, // New: direct buffer writing
    pub accessor: TokenStream,
    pub bit_sum: TokenStream,
}

impl FieldProcessResult {
    pub fn new(
        limit_check: TokenStream,
        parsing: TokenStream,
        writing: TokenStream,
        direct_writing: TokenStream,
        accessor: TokenStream,
        bit_sum: TokenStream,
    ) -> Self {
        Self {
            limit_check,
            parsing,
            writing,
            direct_writing,
            accessor,
            bit_sum,
        }
    }
}

/// Builder pattern for complex `FieldData` structures
pub struct FieldDataBuilder {
    limit_checks: Vec<TokenStream>,
    parsings: Vec<TokenStream>,
    writings: Vec<TokenStream>,
    direct_writings: Vec<TokenStream>, // New: direct buffer writings
    accessors: Vec<TokenStream>,
    bit_sums: Vec<TokenStream>,
}

impl FieldDataBuilder {
    pub fn new() -> Self {
        Self {
            limit_checks: Vec::new(),
            parsings: Vec::new(),
            writings: Vec::new(),
            direct_writings: Vec::new(),
            accessors: Vec::new(),
            bit_sums: Vec::new(),
        }
    }

    pub fn add_result(mut self, result: FieldProcessResult) -> Self {
        self.limit_checks.push(result.limit_check);
        self.parsings.push(result.parsing);
        self.writings.push(result.writing);
        self.direct_writings.push(result.direct_writing);
        self.accessors.push(result.accessor);
        self.bit_sums.push(result.bit_sum);
        self
    }

    pub fn build(self) -> crate::structs::FieldData {
        crate::structs::FieldData {
            field_limit_check: self.limit_checks,
            errors: Vec::new(), // Errors handled separately now
            field_parsing: self.parsings,
            bit_sum: self.bit_sums,
            field_writing: self.writings,
            direct_writing: self.direct_writings,
            named_fields: self.accessors,
            total_size: 0,
        }
    }
}

impl Default for FieldDataBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Attribute data structure for functional parsing
#[derive(Debug, Default, Clone)]
pub struct AttributeData {
    pub size: Option<usize>,
    pub field: Option<Vec<Ident>>,
    pub size_expression: Option<crate::size_expr::SizeExpression>,
    pub is_bits_attribute: bool,
    pub until_marker: Option<u8>,
    pub after_marker: Option<u8>,
}

impl AttributeData {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_size(mut self, size: usize) -> Self {
        self.size = Some(size);
        self
    }

    pub fn with_field(mut self, field: Vec<Ident>) -> Self {
        self.field = Some(field);
        self
    }

    pub fn with_bits_attribute(mut self) -> Self {
        self.is_bits_attribute = true;
        self
    }

    pub fn with_size_expression(mut self, size_expr: crate::size_expr::SizeExpression) -> Self {
        self.size_expression = Some(size_expr);
        self
    }

    pub fn with_until_marker(mut self, marker: u8) -> Self {
        self.until_marker = Some(marker);
        self
    }

    pub fn with_after_marker(mut self, marker: u8) -> Self {
        self.after_marker = Some(marker);
        self
    }

    /// Merge multiple `AttributeData` instances, prioritizing non-`None` values
    pub fn merge(attrs: Vec<Self>) -> Self {
        attrs.into_iter().fold(Self::default(), |mut acc, attr| {
            acc.size = attr.size.or(acc.size);
            acc.field = attr.field.or(acc.field);
            acc.size_expression = attr.size_expression.or(acc.size_expression);
            acc.is_bits_attribute |= attr.is_bits_attribute;
            acc.until_marker = attr.until_marker.or(acc.until_marker);
            acc.after_marker = attr.after_marker.or(acc.after_marker);
            acc
        })
    }
}

/// Error aggregation utilities
pub mod error_utils {
    use super::{ParseResult, SynError, Vec};

    /// Collect results, separating successes from errors
    pub fn aggregate_results<T>(
        results: impl Iterator<Item = Result<T, SynError>>,
    ) -> ParseResult<Vec<T>> {
        let results: Vec<_> = results.collect();
        let mut successes = Vec::new();
        let mut errors = Vec::new();

        for result in results {
            match result {
                Ok(success) => successes.push(success),
                Err(error) => errors.push(error),
            }
        }

        if errors.is_empty() {
            Ok(successes)
        } else {
            Err(errors)
        }
    }
}

/// Pure helper functions to replace mutation-based ones
pub mod pure_helpers {
    use super::TokenStream;
    use quote::quote;
    use syn::Ident;

    /// Create a field accessor without side effects
    pub fn create_field_accessor(field_name: &Ident, needs_owned: bool) -> TokenStream {
        if needs_owned {
            quote! { let #field_name = self.#field_name.clone(); }
        } else {
            quote! { let #field_name = self.#field_name; }
        }
    }

    /// Create a bit sum token without side effects
    pub fn create_bit_sum(size: usize) -> TokenStream {
        quote! { bit_sum += #size; }
    }

    /// Create a bit sum for byte-aligned fields
    pub fn create_byte_bit_sum(size: usize) -> TokenStream {
        quote! { bit_sum += #size * 8; }
    }

    /// Create byte indices tokens
    pub fn create_byte_indices(field_size: usize) -> TokenStream {
        quote! {
            // Ensure byte alignment when transitioning from bitfields
            if _bit_sum % 8 != 0 {
                _bit_sum = usize::div_ceil(_bit_sum, 8) * 8;
            }
            byte_index = _bit_sum / 8;
            end_byte_index = byte_index + #field_size;
            if end_byte_index > bytes.len() {
                return Err(::bebytes::BeBytesError::InsufficientData {
                    expected: #field_size,
                    actual: bytes.len().saturating_sub(byte_index),
                });
            }
            _bit_sum += 8 * #field_size;
        }
    }

    /// Create primitive type parsing code
    pub fn create_primitive_parsing(
        field_name: &Ident,
        field_type: &syn::Type,
        endianness: crate::consts::Endianness,
    ) -> Result<TokenStream, syn::Error> {
        let type_size = crate::utils::get_primitive_type_size(field_type)?;

        // Special handling for char type
        if let syn::Type::Path(tp) = field_type {
            if tp.path.is_ident("char") {
                return Ok(create_char_parsing(field_name, endianness));
            }
        }

        create_numeric_parsing(field_name, field_type, type_size, endianness)
    }

    /// Create char type parsing code
    fn create_char_parsing(
        field_name: &Ident,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        match endianness {
            crate::consts::Endianness::Big => quote! {
                let char_value = u32::from_be_bytes([
                    bytes[byte_index], bytes[byte_index + 1],
                    bytes[byte_index + 2], bytes[byte_index + 3]
                ]);
                let #field_name = char::from_u32(char_value)
                    .ok_or_else(|| ::bebytes::BeBytesError::InvalidDiscriminant {
                        value: (char_value & 0xFF) as u8,
                        type_name: "char",
                    })?;
            },
            crate::consts::Endianness::Little => quote! {
                let char_value = u32::from_le_bytes([
                    bytes[byte_index], bytes[byte_index + 1],
                    bytes[byte_index + 2], bytes[byte_index + 3]
                ]);
                let #field_name = char::from_u32(char_value)
                    .ok_or_else(|| ::bebytes::BeBytesError::InvalidDiscriminant {
                        value: (char_value & 0xFF) as u8,
                        type_name: "char",
                    })?;
            },
        }
    }

    /// Create numeric type parsing code
    fn create_numeric_parsing(
        field_name: &Ident,
        field_type: &syn::Type,
        type_size: usize,
        endianness: crate::consts::Endianness,
    ) -> Result<TokenStream, syn::Error> {
        let from_bytes_method = match endianness {
            crate::consts::Endianness::Big => quote!(from_be_bytes),
            crate::consts::Endianness::Little => quote!(from_le_bytes),
        };

        match type_size {
            1 => Ok(quote! {
                let #field_name = bytes[byte_index] as #field_type;
            }),
            2 => Ok(quote! {
                let #field_name = #field_type::#from_bytes_method([
                    bytes[byte_index], bytes[byte_index + 1]
                ]);
            }),
            4 => Ok(quote! {
                let #field_name = #field_type::#from_bytes_method([
                    bytes[byte_index], bytes[byte_index + 1],
                    bytes[byte_index + 2], bytes[byte_index + 3]
                ]);
            }),
            8 => Ok(quote! {
                let #field_name = #field_type::#from_bytes_method([
                    bytes[byte_index], bytes[byte_index + 1],
                    bytes[byte_index + 2], bytes[byte_index + 3],
                    bytes[byte_index + 4], bytes[byte_index + 5],
                    bytes[byte_index + 6], bytes[byte_index + 7]
                ]);
            }),
            16 => Ok(quote! {
                let #field_name = #field_type::#from_bytes_method([
                    bytes[byte_index], bytes[byte_index + 1],
                    bytes[byte_index + 2], bytes[byte_index + 3],
                    bytes[byte_index + 4], bytes[byte_index + 5],
                    bytes[byte_index + 6], bytes[byte_index + 7],
                    bytes[byte_index + 8], bytes[byte_index + 9],
                    bytes[byte_index + 10], bytes[byte_index + 11],
                    bytes[byte_index + 12], bytes[byte_index + 13],
                    bytes[byte_index + 14], bytes[byte_index + 15]
                ]);
            }),
            _ => Err(syn::Error::new_spanned(
                field_type,
                "Unsupported primitive type size",
            )),
        }
    }

    /// Create primitive type writing code
    pub fn create_primitive_writing(
        field_name: &Ident,
        field_type: &syn::Type,
        endianness: crate::consts::Endianness,
    ) -> Result<TokenStream, syn::Error> {
        let type_size = crate::utils::get_primitive_type_size(field_type)?;

        // Special handling for char type
        if let syn::Type::Path(tp) = field_type {
            if tp.path.is_ident("char") {
                return match endianness {
                    crate::consts::Endianness::Big => Ok(quote! {
                        let char_bytes = (#field_name as u32).to_be_bytes();
                        bytes.extend_from_slice(&char_bytes);
                        _bit_sum += 32;
                    }),
                    crate::consts::Endianness::Little => Ok(quote! {
                        let char_bytes = (#field_name as u32).to_le_bytes();
                        bytes.extend_from_slice(&char_bytes);
                        _bit_sum += 32;
                    }),
                };
            }
        }

        match endianness {
            crate::consts::Endianness::Big => match type_size {
                1 => Ok(quote! {
                    ::bebytes::BufMut::put_u8(bytes, #field_name as u8);
                    _bit_sum += 8;
                }),
                2 => Ok(quote! {
                    ::bebytes::BufMut::put_u16(bytes, #field_name as u16);
                    _bit_sum += 16;
                }),
                4 => Ok(quote! {
                    ::bebytes::BufMut::put_u32(bytes, #field_name as u32);
                    _bit_sum += 32;
                }),
                8 => Ok(quote! {
                    ::bebytes::BufMut::put_u64(bytes, #field_name as u64);
                    _bit_sum += 64;
                }),
                16 => Ok(quote! {
                    ::bebytes::BufMut::put_u128(bytes, #field_name as u128);
                    _bit_sum += 128;
                }),
                _ => Ok(quote! {
                    let field_slice = &#field_name.to_be_bytes();
                    bytes.extend_from_slice(field_slice);
                    _bit_sum += field_slice.len() * 8;
                }),
            },
            crate::consts::Endianness::Little => match type_size {
                1 => Ok(quote! {
                    ::bebytes::BufMut::put_u8(bytes, #field_name as u8);
                    _bit_sum += 8;
                }),
                2 => Ok(quote! {
                    ::bebytes::BufMut::put_u16_le(bytes, #field_name as u16);
                    _bit_sum += 16;
                }),
                4 => Ok(quote! {
                    ::bebytes::BufMut::put_u32_le(bytes, #field_name as u32);
                    _bit_sum += 32;
                }),
                8 => Ok(quote! {
                    ::bebytes::BufMut::put_u64_le(bytes, #field_name as u64);
                    _bit_sum += 64;
                }),
                16 => Ok(quote! {
                    ::bebytes::BufMut::put_u128_le(bytes, #field_name as u128);
                    _bit_sum += 128;
                }),
                _ => Ok(quote! {
                    let field_slice = &#field_name.to_le_bytes();
                    bytes.extend_from_slice(field_slice);
                    _bit_sum += field_slice.len() * 8;
                }),
            },
        }
    }

    /// Create limit check for bit fields
    pub fn create_bit_field_limit_check(
        field_name: &Ident,
        field_type: &syn::Type,
        size: usize,
    ) -> TokenStream {
        let mask: u128 = (1 << size) - 1;

        // Special handling for char type
        if let syn::Type::Path(tp) = field_type {
            if tp.path.is_ident("char") {
                return quote! {
                    if (#field_name as u32) > #mask as u32 {
                        panic!("Value of field {} is out of range (max value: {})",
                            stringify!(#field_name), #mask);
                    }
                };
            }
        }

        quote! {
            if #field_name > #mask as #field_type {
                panic!("Value of field {} is out of range (max value: {})",
                    stringify!(#field_name), #mask);
            }
        }
    }

    /// Generate field access path from a vector of idents
    pub fn generate_field_access_path(ident_path: &[Ident]) -> TokenStream {
        if ident_path.len() == 1 {
            let ident = &ident_path[0];
            quote!(#ident)
        } else {
            let first = &ident_path[0];
            let rest = &ident_path[1..];
            rest.iter()
                .fold(quote!(#first), |acc, segment| quote!(#acc.#segment))
        }
    }

    /// Calculate bits in byte helper - returns min(8 - `bit_offset`, `total_bits` - `bits_processed`)
    pub fn create_bits_in_byte_calc(
        bit_offset_expr: &TokenStream,
        total_bits: &TokenStream,
        bits_processed: &TokenStream,
    ) -> TokenStream {
        quote! {
            core::cmp::min(8 - #bit_offset_expr, #total_bits - #bits_processed)
        }
    }

    /// Generate aligned multi-byte bit field parsing code
    pub fn create_aligned_multibyte_parsing(
        field_type: &syn::Type,
        from_bytes_method: &TokenStream,
        number_length: usize,
    ) -> TokenStream {
        quote! {
            let slice = &bytes[byte_start..byte_start + #number_length];
            let mut arr = [0u8; #number_length];
            arr.copy_from_slice(slice);
            #field_type::#from_bytes_method(arr)
        }
    }

    /// Generate aligned char bit field parsing code with validation
    pub fn create_aligned_char_parsing(
        from_bytes_method: &TokenStream,
        number_length: usize,
    ) -> TokenStream {
        quote! {
            {
                let slice = &bytes[byte_start..byte_start + #number_length];
                let mut arr = [0u8; #number_length];
                arr.copy_from_slice(slice);
                let char_value = u32::#from_bytes_method(arr);
                char::from_u32(char_value)
                    .ok_or_else(|| ::bebytes::BeBytesError::InvalidDiscriminant {
                        value: (char_value & 0xFF) as u8,
                        type_name: "char",
                    })?
            }
        }
    }

    /// Generate unaligned multi-byte bit field parsing code
    pub fn create_unaligned_multibyte_parsing(
        field_type: &syn::Type,
        size: usize,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        let bits_in_byte = create_bits_in_byte_calc(
            &quote!(current_bit_offset),
            &quote!(#size),
            &quote!(bits_read),
        );

        match endianness {
            crate::consts::Endianness::Big => quote! {
                let mut result = 0 as #field_type;
                let mut bits_read = 0;
                let mut byte_idx = byte_start;
                let mut current_bit_offset = bit_offset;

                while bits_read < #size {
                    let bits_in_byte = #bits_in_byte;
                    let byte_val = bytes[byte_idx] as #field_type;
                    let shifted = (byte_val >> (8 - current_bit_offset - bits_in_byte)) & ((1 << bits_in_byte) - 1);
                    result = (result << bits_in_byte) | shifted;

                    bits_read += bits_in_byte;
                    byte_idx += 1;
                    current_bit_offset = 0;
                }
                result
            },
            crate::consts::Endianness::Little => quote! {
                let mut result = 0 as #field_type;
                let mut bits_read = 0;
                let mut byte_idx = byte_start;
                let mut current_bit_offset = bit_offset;

                while bits_read < #size {
                    let bits_in_byte = #bits_in_byte;
                    let byte_val = bytes[byte_idx] as #field_type;
                    let shifted = (byte_val >> current_bit_offset) & ((1 << bits_in_byte) - 1);
                    result |= shifted << bits_read;

                    bits_read += bits_in_byte;
                    byte_idx += 1;
                    current_bit_offset = 0;
                }
                result
            },
        }
    }

    /// Generate unaligned char bit field parsing code with validation
    pub fn create_unaligned_char_parsing(
        size: usize,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        let bits_in_byte = create_bits_in_byte_calc(
            &quote!(current_bit_offset),
            &quote!(#size),
            &quote!(bits_read),
        );

        match endianness {
            crate::consts::Endianness::Big => quote! {
                {
                    let mut result = 0u32;
                    let mut bits_read = 0;
                    let mut byte_idx = byte_start;
                    let mut current_bit_offset = bit_offset;

                    while bits_read < #size {
                        let bits_in_byte = #bits_in_byte;
                        let byte_val = bytes[byte_idx] as u32;
                        let shifted = (byte_val >> (8 - current_bit_offset - bits_in_byte)) & ((1 << bits_in_byte) - 1);
                        result = (result << bits_in_byte) | shifted;

                        bits_read += bits_in_byte;
                        byte_idx += 1;
                        current_bit_offset = 0;
                    }
                    char::from_u32(result)
                        .ok_or_else(|| ::bebytes::BeBytesError::InvalidDiscriminant {
                            value: (result & 0xFF) as u8,
                            type_name: "char",
                        })?
                }
            },
            crate::consts::Endianness::Little => quote! {
                {
                    let mut result = 0u32;
                    let mut bits_read = 0;
                    let mut byte_idx = byte_start;
                    let mut current_bit_offset = bit_offset;

                    while bits_read < #size {
                        let bits_in_byte = #bits_in_byte;
                        let byte_val = bytes[byte_idx] as u32;
                        let shifted = (byte_val >> current_bit_offset) & ((1 << bits_in_byte) - 1);
                        result |= shifted << bits_read;

                        bits_read += bits_in_byte;
                        byte_idx += 1;
                        current_bit_offset = 0;
                    }
                    char::from_u32(result)
                        .ok_or_else(|| ::bebytes::BeBytesError::InvalidDiscriminant {
                            value: (result & 0xFF) as u8,
                            type_name: "char",
                        })?
                }
            },
        }
    }

    /// Generate aligned multi-byte bit field writing code
    pub fn create_aligned_multibyte_writing(
        field_type: &syn::Type,
        to_bytes_method: &TokenStream,
        number_length: usize,
    ) -> TokenStream {
        quote! {
            let value_bytes = #field_type::#to_bytes_method(value);
            if bytes.len() < byte_start + #number_length {
                bytes.resize(byte_start + #number_length, 0);
            }
            bytes[byte_start..byte_start + #number_length].copy_from_slice(&value_bytes);
        }
    }

    /// Generate unaligned multi-byte bit field writing code
    pub fn create_unaligned_multibyte_writing(
        field_type: &syn::Type,
        size: usize,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        let bits_in_byte = create_bits_in_byte_calc(
            &quote!(current_bit_offset),
            &quote!(#size),
            &quote!(bits_written),
        );

        match endianness {
            crate::consts::Endianness::Big => quote! {
                let mut remaining_value = value;
                let mut bits_written = 0;
                let mut byte_idx = byte_start;
                let mut current_bit_offset = bit_offset;

                while bits_written < #size {
                    let bits_in_byte = #bits_in_byte;
                    let mask = ((1 << bits_in_byte) - 1) as u8;
                    let shift = #size - bits_written - bits_in_byte;
                    let byte_bits = ((remaining_value >> shift) & mask as #field_type) as u8;

                    if bytes.len() <= byte_idx {
                        bytes.resize(byte_idx + 1, 0);
                    }
                    bytes[byte_idx] |= byte_bits << (8 - current_bit_offset - bits_in_byte);

                    bits_written += bits_in_byte;
                    byte_idx += 1;
                    current_bit_offset = 0;
                }
            },
            crate::consts::Endianness::Little => quote! {
                let mut remaining_value = value;
                let mut bits_written = 0;
                let mut byte_idx = byte_start;
                let mut current_bit_offset = bit_offset;

                while bits_written < #size {
                    let bits_in_byte = #bits_in_byte;
                    let mask = ((1 << bits_in_byte) - 1) as #field_type;
                    let byte_bits = (remaining_value & mask) as u8;

                    if bytes.len() <= byte_idx {
                        bytes.resize(byte_idx + 1, 0);
                    }
                    bytes[byte_idx] |= byte_bits << current_bit_offset;

                    remaining_value >>= bits_in_byte;
                    bits_written += bits_in_byte;
                    byte_idx += 1;
                    current_bit_offset = 0;
                }
            },
        }
    }

    /// Generate aligned char bit field writing code
    pub fn create_aligned_char_writing(
        to_bytes_method: &TokenStream,
        number_length: usize,
    ) -> TokenStream {
        quote! {
            let value_bytes = u32::#to_bytes_method(value as u32);
            if bytes.len() < byte_start + #number_length {
                bytes.resize(byte_start + #number_length, 0);
            }
            bytes[byte_start..byte_start + #number_length].copy_from_slice(&value_bytes);
        }
    }

    /// Generate unaligned char bit field writing code
    pub fn create_unaligned_char_writing(
        size: usize,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        let bits_in_byte = create_bits_in_byte_calc(
            &quote!(current_bit_offset),
            &quote!(#size),
            &quote!(bits_written),
        );

        match endianness {
            crate::consts::Endianness::Big => quote! {
                let mut remaining_value = value as u32;
                let mut bits_written = 0;
                let mut byte_idx = byte_start;
                let mut current_bit_offset = bit_offset;

                while bits_written < #size {
                    let bits_in_byte = #bits_in_byte;
                    let mask = ((1 << bits_in_byte) - 1) as u8;
                    let shift = #size - bits_written - bits_in_byte;
                    let byte_bits = ((remaining_value >> shift) & mask as u32) as u8;

                    if bytes.len() <= byte_idx {
                        bytes.resize(byte_idx + 1, 0);
                    }
                    bytes[byte_idx] |= byte_bits << (8 - current_bit_offset - bits_in_byte);

                    bits_written += bits_in_byte;
                    byte_idx += 1;
                    current_bit_offset = 0;
                }
            },
            crate::consts::Endianness::Little => quote! {
                let mut remaining_value = value as u32;
                let mut bits_written = 0;
                let mut byte_idx = byte_start;
                let mut current_bit_offset = bit_offset;

                while bits_written < #size {
                    let bits_in_byte = #bits_in_byte;
                    let mask = ((1 << bits_in_byte) - 1) as u32;
                    let byte_bits = (remaining_value & mask) as u8;

                    if bytes.len() <= byte_idx {
                        bytes.resize(byte_idx + 1, 0);
                    }
                    bytes[byte_idx] |= byte_bits << current_bit_offset;

                    remaining_value >>= bits_in_byte;
                    bits_written += bits_in_byte;
                    byte_idx += 1;
                    current_bit_offset = 0;
                }
            },
        }
    }

    /// Generate single-byte bit field parsing code based on endianness
    pub fn create_single_byte_bit_parsing(
        field_name: &Ident,
        field_type: &syn::Type,
        size: usize,
        mask: u128,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        match endianness {
            crate::consts::Endianness::Big => quote! {
                let #field_name = {
                    let byte_idx = _bit_sum / 8;
                    let bit_offset = _bit_sum % 8;

                    // Check if field spans two bytes
                    if bit_offset + #size > 8 {
                        // Field spans two bytes
                        let mut result = 0 as #field_type;
                        let mut bits_read = 0;
                        let mut current_byte_idx = byte_idx;
                        let mut current_bit_offset = bit_offset;

                        while bits_read < #size {
                            if current_byte_idx >= bytes.len() {
                                return Err(::bebytes::BeBytesError::InsufficientData {
                                    expected: current_byte_idx + 1,
                                    actual: bytes.len(),
                                });
                            }

                            let bits_in_byte = core::cmp::min(8 - current_bit_offset, #size - bits_read);
                            let byte_val = bytes[current_byte_idx] as #field_type;
                            let shifted = (byte_val >> (8 - current_bit_offset - bits_in_byte)) & ((1 << bits_in_byte) - 1);
                            result = (result << bits_in_byte) | shifted;

                            bits_read += bits_in_byte;
                            current_byte_idx += 1;
                            current_bit_offset = 0;
                        }
                        result
                    } else {
                        // Field fits in single byte
                        let mask = #mask as #field_type;
                        let byte_val = bytes[byte_idx] as #field_type;
                        (byte_val >> (8 - bit_offset - #size)) & mask
                    }
                };
                _bit_sum += #size;
            },
            crate::consts::Endianness::Little => quote! {
                let #field_name = {
                    let byte_idx = _bit_sum / 8;
                    let bit_offset = _bit_sum % 8;
                    let mask = #mask as #field_type;
                    let byte_val = bytes[byte_idx] as #field_type;
                    (byte_val >> bit_offset) & mask
                };
                _bit_sum += #size;
            },
        }
    }

    /// Generate single-byte bit field writing code based on endianness
    pub fn create_single_byte_bit_writing(
        field_name: &Ident,
        size: usize,
        mask: u128,
        endianness: crate::consts::Endianness,
    ) -> TokenStream {
        match endianness {
            crate::consts::Endianness::Big => quote! {
                {
                    let byte_idx = _bit_sum / 8;
                    let bit_offset = _bit_sum % 8;

                    // Check if field spans two bytes
                    if bit_offset + #size > 8 {
                        // Field spans two bytes - use multi-byte approach
                        let mut remaining_value = #field_name as u8;
                        let mut bits_written = 0;
                        let mut current_byte_idx = byte_idx;
                        let mut current_bit_offset = bit_offset;

                        while bits_written < #size {
                            let bits_in_byte = core::cmp::min(8 - current_bit_offset, #size - bits_written);
                            let bit_mask = ((1 << bits_in_byte) - 1) as u8;
                            let shift = #size - bits_written - bits_in_byte;
                            let byte_bits = ((remaining_value >> shift) & bit_mask) as u8;

                            if bytes.len() <= current_byte_idx {
                                bytes.resize(current_byte_idx + 1, 0);
                            }
                            bytes[current_byte_idx] |= byte_bits << (8 - current_bit_offset - bits_in_byte);

                            bits_written += bits_in_byte;
                            current_byte_idx += 1;
                            current_bit_offset = 0;
                        }
                    } else {
                        // Field fits in single byte
                        let mask = #mask as u8;
                        if bytes.len() <= byte_idx {
                            bytes.resize(byte_idx + 1, 0);
                        }
                        bytes[byte_idx] |= ((#field_name as u8) & mask) << (8 - bit_offset - #size);
                    }
                }
                _bit_sum += #size;
            },
            crate::consts::Endianness::Little => quote! {
                {
                    let byte_idx = _bit_sum / 8;
                    let bit_offset = _bit_sum % 8;

                    // Check if field spans multiple bytes
                    if bit_offset + #size > 8 {
                        // Field spans multiple bytes - use multi-byte approach for LE
                        let mut remaining_value = #field_name as u16; // Use larger type for multi-byte
                        let mut bits_written = 0;
                        let mut current_byte_idx = byte_idx;
                        let mut current_bit_offset = bit_offset;

                        while bits_written < #size {
                            let bits_in_byte = core::cmp::min(8 - current_bit_offset, #size - bits_written);
                            let bit_mask = ((1 << bits_in_byte) - 1) as u16;
                            let byte_bits = (remaining_value & bit_mask) as u8;

                            if bytes.len() <= current_byte_idx {
                                bytes.resize(current_byte_idx + 1, 0);
                            }
                            bytes[current_byte_idx] |= byte_bits << current_bit_offset;

                            remaining_value >>= bits_in_byte;
                            bits_written += bits_in_byte;
                            current_byte_idx += 1;
                            current_bit_offset = 0;
                        }
                    } else {
                        // Field fits in single byte
                        let mask = #mask as u8;
                        if bytes.len() <= byte_idx {
                            bytes.resize(byte_idx + 1, 0);
                        }
                        bytes[byte_idx] |= ((#field_name as u8) & mask) << bit_offset;
                    }
                }
                _bit_sum += #size;
            },
        }
    }
}

/// Functional attribute parsing
pub mod functional_attrs {
    use super::{error_utils, AttributeData, ParseResult, Vec};
    use syn::{parse::Parser, LitInt};

    /// Parse attributes functionally without side effects
    pub fn parse_attributes_functional(
        attributes: &[syn::Attribute],
    ) -> ParseResult<AttributeData> {
        // Check for multiple bits attributes first
        let bits_count = attributes
            .iter()
            .filter(|attr| attr.path().is_ident("bits"))
            .count();
        if bits_count > 1 {
            return Err(vec![syn::Error::new_spanned(
                attributes.first().unwrap(),
                "Multiple #[bits] attributes on the same field are not allowed",
            )]);
        }

        let results: Vec<Result<Option<AttributeData>, syn::Error>> = attributes
            .iter()
            .map(|attr| {
                if attr.path().is_ident("bits") {
                    parse_bits_attribute_functional(attr).map(|size_opt| {
                        let mut data = AttributeData::new().with_bits_attribute();
                        if let Some(size) = size_opt {
                            data = data.with_size(size);
                        }
                        Some(data)
                    })
                } else if attr.path().is_ident("With") {
                    parse_with_attribute_with_expressions(attr)
                } else if attr.path().is_ident("FromField") {
                    parse_from_field_attribute_functional(attr)
                        .map(|field| Some(AttributeData::new().with_field(field)))
                } else if attr.path().is_ident("size") {
                    parse_size_attribute_with_expressions(attr)
                } else if attr.path().is_ident("bebytes") {
                    parse_bebytes_attribute_functional(attr)
                } else if attr.path().is_ident("UntilMarker") {
                    parse_until_marker_attribute_functional(attr)
                        .map(|marker| Some(AttributeData::new().with_until_marker(marker)))
                } else if attr.path().is_ident("AfterMarker") {
                    parse_after_marker_attribute_functional(attr)
                        .map(|marker| Some(AttributeData::new().with_after_marker(marker)))
                } else {
                    Ok(None)
                }
            })
            .collect();

        let flattened: Vec<Result<AttributeData, syn::Error>> =
            results.into_iter().filter_map(Result::transpose).collect();

        // Check for attribute conflicts before merging
        let mut conflict_errors = Vec::new();

        // Check for FromField vs With(size) conflict
        let has_from_field = attributes
            .iter()
            .any(|attr| attr.path().is_ident("FromField"));
        let has_with_size = attributes.iter().any(|attr| {
            attr.path().is_ident("With") && {
                // Check if the With attribute contains size()
                let mut has_size = false;
                if let Ok(()) = attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("size") {
                        has_size = true;
                    }
                    Ok(())
                }) {}
                has_size
            }
        });

        if has_from_field && has_with_size {
            conflict_errors.push(syn::Error::new_spanned(
                attributes
                    .iter()
                    .find(|attr| attr.path().is_ident("FromField"))
                    .unwrap(),
                "Cannot use both #[FromField] and #[With(size())] on the same field",
            ));
        }

        // Check for multiple endian attributes
        let endian_attrs: Vec<_> = attributes
            .iter()
            .filter(|attr| {
                attr.path().is_ident("bebytes") && {
                    let mut is_endian = false;
                    if let Ok(()) = attr.parse_nested_meta(|meta| {
                        if meta.path.is_ident("big_endian") || meta.path.is_ident("little_endian") {
                            is_endian = true;
                        }
                        Ok(())
                    }) {}
                    is_endian
                }
            })
            .collect();

        if endian_attrs.len() > 1 {
            conflict_errors.push(syn::Error::new_spanned(
                endian_attrs.first().unwrap(),
                "Cannot specify both big_endian and little_endian attributes on the same field",
            ));
        }

        // If there are conflict errors, return them
        if !conflict_errors.is_empty() {
            return Err(conflict_errors);
        }

        error_utils::aggregate_results(flattened.into_iter()).map(AttributeData::merge)
    }

    /// Parse bits attribute functionally
    pub fn parse_bits_attribute_functional(
        attr: &syn::Attribute,
    ) -> Result<Option<usize>, syn::Error> {
        // Check the meta type first
        match &attr.meta {
            syn::Meta::Path(_) => {
                // #[bits] without parentheses - not allowed by Rust for derive macro attributes
                // This case won't actually be reached due to Rust's validation
                Ok(None)
            }
            syn::Meta::List(list) => {
                // Check if tokens are empty first
                if list.tokens.is_empty() {
                    // #[bits()] with empty parentheses - auto-size
                    return Ok(None);
                }

                // Try to parse as integer literal
                let parser =
                    syn::punctuated::Punctuated::<LitInt, syn::Token![,]>::parse_terminated;
                let parsed = parser.parse2(list.tokens.clone())?;

                if let Some(first) = parsed.first() {
                    // #[bits(N)] with explicit size
                    Ok(Some(first.base10_parse()?))
                } else {
                    Err(syn::Error::new_spanned(
                        attr,
                        "Expected integer literal in #[bits(N)]",
                    ))
                }
            }
            syn::Meta::NameValue(_) => Err(syn::Error::new_spanned(
                attr,
                "Expected #[bits(N)] or #[bits()], not name-value style",
            )),
        }
    }

    /// Parse with attribute with support for size expressions
    pub fn parse_with_attribute_with_expressions(
        attr: &syn::Attribute,
    ) -> Result<Option<AttributeData>, syn::Error> {
        let mut size = None;
        let mut size_expression = None;

        // Parse the content inside With(...)
        match &attr.meta {
            syn::Meta::List(list) => {
                // Parse the tokens inside With(...)
                let tokens = &list.tokens;

                // Try to parse as "size(...)" pattern
                let tokens_str = tokens.to_string();
                if tokens_str.starts_with("size") {
                    // Find the content inside size(...)
                    if let Some(start) = tokens_str.find('(') {
                        if let Some(end) = tokens_str.rfind(')') {
                            let expr_content = &tokens_str[start + 1..end];

                            // Try to parse as integer literal first
                            if let Ok(n) = expr_content.trim().parse::<usize>() {
                                size = Some(n);
                            } else {
                                // Parse as expression
                                let parsed_expr =
                                    crate::size_expr::SizeExpression::parse(expr_content.trim())?;
                                size_expression = Some(parsed_expr);
                            }
                        } else {
                            return Err(syn::Error::new_spanned(
                                attr,
                                "Missing closing parenthesis in size attribute",
                            ));
                        }
                    } else {
                        return Err(syn::Error::new_spanned(attr, "Expected size(...) format"));
                    }
                } else {
                    return Err(syn::Error::new_spanned(
                        attr,
                        "Only size attribute is supported in With",
                    ));
                }
            }
            _ => {
                return Err(syn::Error::new_spanned(
                    attr,
                    "With attribute must have parentheses: #[With(size(...))]",
                ));
            }
        }

        if size.is_some() || size_expression.is_some() {
            let mut attr_data = AttributeData::new();
            if let Some(s) = size {
                attr_data = attr_data.with_size(s);
            }
            if let Some(expr) = size_expression {
                attr_data = attr_data.with_size_expression(expr);
            }
            Ok(Some(attr_data))
        } else {
            Ok(None)
        }
    }

    /// Parse standalone size attribute with expression support
    pub fn parse_size_attribute_with_expressions(
        attr: &syn::Attribute,
    ) -> Result<Option<AttributeData>, syn::Error> {
        // Parse the content inside #[size(...)]
        match &attr.meta {
            syn::Meta::List(list) => {
                let tokens = &list.tokens;
                let expr_str = tokens.to_string();
                let parsed_expr = crate::size_expr::SizeExpression::parse(&expr_str)?;
                let attr_data = AttributeData::new().with_size_expression(parsed_expr);
                Ok(Some(attr_data))
            }
            _ => Err(syn::Error::new_spanned(
                attr,
                "size attribute must have parentheses: #[size(expression)]",
            )),
        }
    }

    /// Parse from field attribute functionally
    pub fn parse_from_field_attribute_functional(
        attr: &syn::Attribute,
    ) -> Result<Vec<syn::Ident>, syn::Error> {
        let field_path: Vec<syn::Ident>;

        // Parse the attribute content as a token stream
        match &attr.meta {
            syn::Meta::List(list) => {
                // Parse tokens inside FromField(...)
                let tokens = list.tokens.clone();
                let parser = syn::punctuated::Punctuated::<syn::Ident, syn::Token![.]>::parse_separated_nonempty;
                match parser.parse2(tokens) {
                    Ok(punctuated) => {
                        // Convert punctuated list to Vec<Ident>
                        field_path = punctuated.into_iter().collect();
                    }
                    Err(e) => return Err(e),
                }
            }
            _ => {
                return Err(syn::Error::new_spanned(
                    attr,
                    "Expected #[FromField(field_name)] or #[FromField(header.qdcount)]",
                ))
            }
        }

        if field_path.is_empty() {
            Err(syn::Error::new_spanned(attr, "Missing field name or path"))
        } else {
            Ok(field_path)
        }
    }

    /// Parse `UntilMarker` attribute functionally
    /// Handles `#[UntilMarker(0xFF)]`, `#[UntilMarker(255)]`, or `#[UntilMarker('\n')]`
    pub fn parse_until_marker_attribute_functional(
        attr: &syn::Attribute,
    ) -> Result<u8, syn::Error> {
        match &attr.meta {
            syn::Meta::List(list) => {
                // Try parsing as integer first
                if let Ok(literal) = syn::parse2::<syn::LitInt>(list.tokens.clone()) {
                    return literal.base10_parse::<u8>();
                }

                // Try parsing as character
                if let Ok(literal) = syn::parse2::<syn::LitChar>(list.tokens.clone()) {
                    let ch = literal.value();
                    if ch.is_ascii() {
                        return Ok(ch as u8);
                    }
                    return Err(syn::Error::new_spanned(
                        attr,
                        "Character markers must be ASCII (value <= 127)",
                    ));
                }

                Err(syn::Error::new_spanned(
                    attr,
                    "Expected #[UntilMarker(byte_value)] or #[UntilMarker('ascii_char')]",
                ))
            }
            _ => Err(syn::Error::new_spanned(
                attr,
                "Expected #[UntilMarker(byte_value)] or #[UntilMarker('ascii_char')]",
            )),
        }
    }

    /// Parse `AfterMarker` attribute functionally
    /// Handles `#[AfterMarker(0xFF)]`, `#[AfterMarker(255)]`, or `#[AfterMarker('\n')]`
    pub fn parse_after_marker_attribute_functional(
        attr: &syn::Attribute,
    ) -> Result<u8, syn::Error> {
        match &attr.meta {
            syn::Meta::List(list) => {
                // Try parsing as integer first
                if let Ok(literal) = syn::parse2::<syn::LitInt>(list.tokens.clone()) {
                    return literal.base10_parse::<u8>();
                }

                // Try parsing as character
                if let Ok(literal) = syn::parse2::<syn::LitChar>(list.tokens.clone()) {
                    let ch = literal.value();
                    if ch.is_ascii() {
                        return Ok(ch as u8);
                    }
                    return Err(syn::Error::new_spanned(
                        attr,
                        "Character markers must be ASCII (value <= 127)",
                    ));
                }

                Err(syn::Error::new_spanned(
                    attr,
                    "Expected #[AfterMarker(byte_value)] or #[AfterMarker('ascii_char')]",
                ))
            }
            _ => Err(syn::Error::new_spanned(
                attr,
                "Expected #[AfterMarker(byte_value)] or #[AfterMarker('ascii_char')]",
            )),
        }
    }

    /// Parse bebytes attribute functionally
    /// Handles #[bebytes(size = "expression")] and similar bebytes-specific attributes
    pub fn parse_bebytes_attribute_functional(
        attr: &syn::Attribute,
    ) -> Result<Option<AttributeData>, syn::Error> {
        let mut result = AttributeData::new();
        let mut found_something = false;

        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("size") {
                let value = meta
                    .value()
                    .map_err(|_| syn::Error::new_spanned(&meta.path, "Expected size expression"))?;

                // Parse the string literal containing the size expression
                let lit_str: syn::LitStr = value.parse()?;
                let size_expr = lit_str.value();

                // Parse and validate the size expression
                let parsed_expr =
                    crate::size_expr::SizeExpression::parse(&size_expr).map_err(|e| {
                        syn::Error::new_spanned(attr, format!("Invalid size expression: {e}"))
                    })?;

                result.size_expression = Some(parsed_expr);
                found_something = true;
                Ok(())
            } else {
                // For other bebytes attributes like big_endian, little_endian, etc., we don't need to handle them here
                // They are handled elsewhere in the codebase
                Ok(())
            }
        })?;

        if found_something {
            Ok(Some(result))
        } else {
            Ok(None)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proc_macro2::Span;
    use quote::quote;

    #[test]
    fn test_processing_context_builder() {
        let ctx = ProcessingContext::new(crate::consts::Endianness::Big)
            .with_bit_position(16)
            .with_last_field(true);

        assert_eq!(ctx.bit_position, 16);
        assert!(ctx.is_last_field);
    }

    #[test]
    fn test_field_data_builder() {
        let result = FieldProcessResult::new(
            quote! { check },
            quote! { parse },
            quote! { write },
            quote! { direct_write },
            quote! { access },
            quote! { bit_sum },
        );

        let builder = FieldDataBuilder::new();
        let field_data = builder.add_result(result).build();

        assert_eq!(field_data.field_limit_check.len(), 1);
        assert_eq!(field_data.field_parsing.len(), 1);
        assert_eq!(field_data.field_writing.len(), 1);
        assert_eq!(field_data.named_fields.len(), 1);
        assert_eq!(field_data.bit_sum.len(), 1);
    }

    #[test]
    fn test_attribute_data_merge() {
        let attr1 = AttributeData::new().with_size(8);
        let attr2 = AttributeData::new().with_bits_attribute();
        let attr3 = AttributeData::new().with_field(vec![Ident::new("test", Span::call_site())]);

        let merged = AttributeData::merge(vec![attr1, attr2, attr3]);

        assert_eq!(merged.size, Some(8));
        assert!(merged.is_bits_attribute);
        assert!(merged.field.is_some());
    }

    #[test]
    fn test_error_aggregation() {
        let results = vec![
            Ok(1),
            Err(SynError::new(Span::call_site(), "error1")),
            Ok(2),
            Err(SynError::new(Span::call_site(), "error2")),
        ];

        let result = error_utils::aggregate_results(results.into_iter());
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().len(), 2);
    }

    #[test]
    fn test_successful_aggregation() {
        let results = vec![Ok(1), Ok(2), Ok(3)];
        let result = error_utils::aggregate_results(results.into_iter());
        assert_eq!(result.unwrap(), vec![1, 2, 3]);
    }
}