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
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
//! Message encoder codegen.
//!
//! `generate_message_encoder` emits the encoder flyweight for a message: the
//! schema marker struct, fixed-field setters (primitives, arrays, composites,
//! enums, sets), `wrap`/`wrap_and_apply_header`/`*_unchecked` entry points,
//! encoded-length support, group/var-data tail setters, consuming tail
//! stages, unchecked companions, and optional `apply_nulls`. Depends on
//! [`super::group_encoder`], [`super::message_header_template`],
//! [`super::nullification`], [`super::conversion_helpers`],
//! [`super::field_type`], [`super::encoded_length`], and `structured_ir`.
use crate::ir::{ByteOrder, Presence};
use crate::structured_ir::*;
use super::conversion_helpers::{ENCODER_RESERVED, field_has_conversion_free, resolve_field_ident};
use super::encoded_length;
use super::field_type::field_type_ident;
use super::group_encoder::generate_group_encoder;
use super::message_header_template::message_header_template;
use super::nullification::{generate_nullification, null_image_stmts_for_field};
use super::runtime::{doc_attr_tokens, emit_field_consts, to_pascal_case, to_snake_case};
pub(crate) fn generate_message_encoder(
msg: &MessageStructure,
elements: &SchemaElements,
byte_order: ByteOrder,
schema_id: u16,
schema_version: u16,
header_type: &str,
multi_message: bool,
conversions: &[crate::ConversionSelector],
domain_types: &[(crate::ConversionSelector, String)],
enable_meta_attributes: bool,
enable_display_debug: bool,
) -> proc_macro2::TokenStream {
let raw_name = &msg.name;
let name = to_pascal_case(raw_name);
let order_suffix = match byte_order {
ByteOrder::LittleEndian => "le",
ByteOrder::BigEndian => "be",
};
// Prefer the resolved message block length (includes schema-declared
// padding via `blockLength="…"`). Fall back to a tight field-span only if
// resolve left it zero (should not happen for real messages).
// Constant fields have zero wire footprint.
let computed_block_length = msg
.fields
.iter()
.filter(|f| f.presence != Presence::Constant)
.fold(0, |acc, f| {
let size = f.field_type.size();
acc.max(f.offset + size)
});
let block_length = msg.block_length.max(computed_block_length);
#[expect(unused_variables)]
let header_pascal = to_pascal_case(header_type);
let header_size = elements
.composites
.iter()
.find(|c| c[0].name == header_type)
.and_then(|c| c[0].encoding.offset)
.unwrap_or(8);
let total_tail = msg.groups.len() + msg.var_data.len();
let is_fixed = total_tail == 0;
// Classify and generate encoded-length support.
let encoded_len_gen = encoded_length::generate(msg, block_length, header_size, elements);
let encoded_length = header_size + block_length;
let mut max_tail = 0usize;
for g in &msg.groups {
let (_, dim_size, _, _) = get_dimension_info(elements, &g.dimension_type);
max_tail = max_tail.saturating_add(dim_size.saturating_add(g.effective_block_length()));
}
for vd in &msg.var_data {
let (_, prefix_size, _, _) = get_vardata_info(elements, &vd.type_name);
max_tail = max_tail.saturating_add(prefix_size.saturating_add(vd.max_length.unwrap_or(0)));
}
let max_encoded_length = header_size
.saturating_add(block_length)
.saturating_add(max_tail);
const STACK_LIMIT: usize = 65536;
let max_encoded_capped = max_encoded_length.min(STACK_LIMIT);
let is_capped = max_encoded_length > STACK_LIMIT;
let span = proc_macro2::Span::call_site();
let snake_name = to_snake_case(&msg.name);
let name_encoder_ident = syn::Ident::new(&format!("{}Encoder", name), span);
let unfixed_encoder_ident = syn::Ident::new(&format!("{}UnfixedEncoder", name), span);
let name_decoder_ident = syn::Ident::new(&format!("{}Decoder", name), span);
// Pre-compute the exact schema-declared header wire image. Composite
// offsets may introduce padding and blockLength may use another unsigned
// primitive width; every multi-octet member follows schema byteOrder.
let header_tpl = message_header_template(
elements,
header_type,
header_size,
byte_order,
block_length,
msg.id,
schema_id,
schema_version,
);
let hdr_lits: Vec<syn::LitInt> = header_tpl
.iter()
.map(|b| syn::LitInt::new(&b.to_string(), span))
.collect();
let header_size_lit = syn::LitInt::new(&header_size.to_string(), span);
let block_length_lit = syn::LitInt::new(&block_length.to_string(), span);
let schema_id_lit = syn::LitInt::new(&schema_id.to_string(), span);
let schema_version_lit = syn::LitInt::new(&schema_version.to_string(), span);
let msg_id_lit = syn::LitInt::new(&msg.id.to_string(), span);
let encoded_length_lit = syn::LitInt::new(&encoded_length.to_string(), span);
let max_encoded_capped_lit = syn::LitInt::new(&max_encoded_capped.to_string(), span);
let to_endian = syn::Ident::new(&format!("to_{}_bytes", order_suffix), span);
let mut ts = proc_macro2::TokenStream::new();
let sealed_path = super::runtime::sealed_path_tokens();
let tail_pascal: Vec<String> = msg
.groups
.iter()
.map(|g| to_pascal_case(&g.name))
.chain(msg.var_data.iter().map(|vd| to_pascal_case(&vd.name)))
.collect();
let stage_idents: Vec<syn::Ident> = if total_tail > 0 {
let mut stages = vec![name_encoder_ident.clone()];
for (i, field) in tail_pascal.iter().enumerate() {
if i < total_tail - 1 {
stages.push(syn::Ident::new(&format!("{}After{}", name, field), span));
} else {
stages.push(syn::Ident::new(&format!("{}Complete", name), span));
}
}
stages
} else {
vec![name_encoder_ident.clone()]
};
if let Some(ref desc) = msg.description {
ts.extend(doc_attr_tokens(desc));
}
for (si, stage) in stage_idents.iter().enumerate() {
let stage_name = stage.to_string();
let stage_name_lit = syn::LitStr::new(&stage_name, span);
// Root encoder always carries FieldsState so `as_bytes*` / tails are
// unavailable until `fixed(&FixedFields)`. Later stages are already
// past fixed and only need HeaderState.
let is_root = si == 0;
if is_root {
let root_doc = if total_tail > 0 {
quote::quote! {
#[doc = concat!("Encoder stage `", #stage_name_lit, "` — call `fixed(&FixedFields)` before tails.")]
}
} else {
quote::quote! {
#[doc = concat!("Encoder stage `", #stage_name_lit, "` — call `fixed(&FixedFields)` before `as_bytes_with_header` / `as_body_bytes`.")]
}
};
ts.extend(quote::quote! {
#root_doc
#[must_use = "encoder must be consumed to write the message"]
pub struct #stage<'a, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent, F: sbe_rt::FieldsState = sbe_rt::FieldsUnfixed> {
buf: &'a mut [u8],
msg_offset: usize,
offset: usize,
_header: core::marker::PhantomData<H>,
_fields: core::marker::PhantomData<F>,
}
});
} else {
ts.extend(quote::quote! {
#[doc = concat!("Encoder stage `", #stage_name_lit, "` — write tail elements in wire order.")]
#[must_use = "encoder must be consumed to write the message"]
pub struct #stage<'a, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent> {
buf: &'a mut [u8],
msg_offset: usize,
offset: usize,
_header: core::marker::PhantomData<H>,
}
});
}
// Encoder Display + Debug: only when the decoder has Display/Debug.
if enable_display_debug {
if is_root {
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> core::fmt::Display for #stage<'a, H, F> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match #name_decoder_ident::decode(self.buf, self.msg_offset) {
Ok(dec) => core::fmt::Display::fmt(&dec, f),
Err(_) => write!(f, "<partial {}>", #stage_name_lit),
}
}
}
impl<'a, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> core::fmt::Debug for #stage<'a, H, F> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match #name_decoder_ident::decode(self.buf, self.msg_offset) {
Ok(dec) => core::fmt::Debug::fmt(&dec, f),
Err(_) => f.debug_struct(#stage_name_lit)
.field("msg_offset", &self.msg_offset)
.field("offset", &self.offset)
.field("buf_len", &self.buf.len())
.finish(),
}
}
}
});
} else {
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState> core::fmt::Display for #stage<'a, H> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match #name_decoder_ident::decode(self.buf, self.msg_offset) {
Ok(dec) => core::fmt::Display::fmt(&dec, f),
Err(_) => write!(f, "<partial {}>", #stage_name_lit),
}
}
}
impl<'a, H: sbe_rt::HeaderState> core::fmt::Debug for #stage<'a, H> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match #name_decoder_ident::decode(self.buf, self.msg_offset) {
Ok(dec) => core::fmt::Debug::fmt(&dec, f),
Err(_) => f.debug_struct(#stage_name_lit)
.field("msg_offset", &self.msg_offset)
.field("offset", &self.offset)
.field("buf_len", &self.buf.len())
.finish(),
}
}
}
});
}
}
}
// Associated constants live on the *defaulted* concrete impl so
// `CarEncoder::TEMPLATE_ID` needs no turbofish. Instance methods go on
// the generic `H` impl so HeaderAbsent and HeaderPresent share setters.
let mut impl_consts = proc_macro2::TokenStream::new();
let mut impl_contents = proc_macro2::TokenStream::new();
// Phase transitions (`fixed()` / `raw_fixed()`) — these must stay on the
// unfixed phase, unlike the individual setters, which are safe in either
// phase. Splitting them is what lets a conversion setter (`*_from`) reach
// a terminal method: it can run after `fixed()` has proven every required
// field written, instead of being stranded on an encoder that can never
// complete.
let mut phase_contents = proc_macro2::TokenStream::new();
// Individual setters for `raw_fixed()` writer (body-relative offsets).
let mut raw_impl_contents = proc_macro2::TokenStream::new();
// Root encoder always carries FieldsState so completion byte views (and
// tails) stay locked until `fixed(&FixedFields)` writes required fields.
let fields_phantom = quote::quote! { _fields: core::marker::PhantomData, };
if is_fixed {
impl_consts.extend(quote::quote! {
pub const SCHEMA_ID: u16 = #schema_id_lit;
pub const SCHEMA_VERSION: u16 = #schema_version_lit;
pub const TEMPLATE_ID: u16 = #msg_id_lit;
pub const BLOCK_LENGTH: usize = #block_length_lit;
const _BLOCK_LEN: () = assert!(Self::BLOCK_LENGTH == #block_length_lit);
/// Schema-declared message header size in bytes.
pub const HEADER_LENGTH: usize = #header_size_lit;
/// Stack-allocate with `let mut buf = [0u8; Msg::ENCODED_LENGTH];`
/// Header-inclusive fixed length. Claim/app framing: payload starts
/// at `frame[Self::ENCODED_LENGTH..]`.
pub const ENCODED_LENGTH: usize = #encoded_length_lit;
const _ENCODED_LEN: () = assert!(Self::ENCODED_LENGTH >= Self::BLOCK_LENGTH);
/// Header-inclusive encoded length. Same as [`Self::ENCODED_LENGTH`];
/// provided for API consistency with flat and complex message
/// shapes so every encoder has a `compute_length_with_header` method.
#[inline]
pub const fn compute_length_with_header() -> usize {
Self::ENCODED_LENGTH
}
pub const HEADER_TEMPLATE: [u8; #header_size_lit] = [#(#hdr_lits),*];
const _HEADER_TEMPLATE_LEN: () =
assert!(Self::HEADER_TEMPLATE.len() == #header_size_lit);
});
// Placement utils live only on EncoderMetadata via get_metadata().
} else {
let impl_consts_suffix = if is_capped {
// When theoretical max exceeds 64KB, do NOT emit MAX_ENCODED_LENGTH —
// the constant would be a dangerous lie. Use EncodedLength instead.
quote::quote! {}
} else {
quote::quote! {
#[doc = " Upper bound of any encoded form of this message (header + body). \
Prefer exact sizing via `Self::compute_length()` / the staged \
`*EncodedLength` builder when the message has groups or var-data; \
a stack `[0u8; Self::MAX_ENCODED_LENGTH]` is fine only when this \
constant is a true fixed upper bound you intend to use."]
pub const MAX_ENCODED_LENGTH: usize = #max_encoded_capped_lit;
const _MAX_ENCODED_LEN: () = assert!(Self::MAX_ENCODED_LENGTH >= Self::BLOCK_LENGTH);
}
};
impl_consts.extend(quote::quote! {
pub const SCHEMA_ID: u16 = #schema_id_lit;
pub const SCHEMA_VERSION: u16 = #schema_version_lit;
pub const TEMPLATE_ID: u16 = #msg_id_lit;
pub const BLOCK_LENGTH: usize = #block_length_lit;
const _BLOCK_LEN: () = assert!(Self::BLOCK_LENGTH == #block_length_lit);
/// Schema-declared message header size in bytes.
pub const HEADER_LENGTH: usize = #header_size_lit;
#impl_consts_suffix
pub const HEADER_TEMPLATE: [u8; #header_size_lit] = [#(#hdr_lits),*];
const _HEADER_TEMPLATE_LEN: () =
assert!(Self::HEADER_TEMPLATE.len() == #header_size_lit);
});
// compute_length() — convenience factory for the staged length builder
if !encoded_len_gen.standalone.is_empty() {
let el_ident = syn::Ident::new(&format!("{name}EncodedLength"), span);
impl_consts.extend(quote::quote! {
#[inline]
pub const fn compute_length() -> #el_ident {
#el_ident::new()
}
});
}
// Placement utils live only on EncoderMetadata via get_metadata().
}
// ── Hot-path bounds check: one cmp, cold error construction ──
// The error path is `#[cold] #[inline(never)]` so the hot path is a single
// `cmp + ja` followed by the same body as the unchecked companion. The
// compiler keeps the cold `Err` constructor out of the hot icache, and
// the branch predictor always predicts not-taken for correctly-sized buffers.
let needed_lit = syn::LitInt::new(&(header_size + block_length).to_string(), span);
let cold_check = quote::quote! {
/// Cold error constructor — never inlined into the hot path.
#[cold]
#[inline(never)]
fn buffer_too_short(buf: &[u8], offset: usize, needed: usize) -> sbe_rt::EncodeError {
sbe_rt::EncodeError::BufferTooShort {
field: "message header+body",
needed,
available: buf.len().saturating_sub(offset),
}
}
};
// Constructors + cold helper on the concrete (default-H) impl so
// `CarEncoder::wrap_and_apply_header` needs no turbofish.
impl_consts.extend(cold_check);
// Three-tier constructors:
// try_* — safe, returns Result on short buffers
// bare name — safe, panics on short buffers (extent proved before
// unchecked field setters)
// *_unchecked — unsafe, caller proves HEADER + fixed body extent
let wrap_fn = quote::quote! {
/// Wrap a mutable buffer for encoding with one bounds/overflow check.
/// Does **not** write the message header (`HeaderAbsent`).
///
/// `msg_offset` is the **message start** (first byte of the SBE frame),
/// not the body. sbe-tool Rust `wrap` takes the body offset instead.
///
/// Prefer [`Self::wrap_and_apply_header`] when encoding a full frame.
#[inline]
pub fn try_wrap(
buf: &'a mut [u8],
msg_offset: usize,
) -> Result<#name_encoder_ident<'a, sbe_rt::HeaderAbsent>, sbe_rt::EncodeError> {
if #needed_lit > buf.len().saturating_sub(msg_offset) {
return Err(Self::buffer_too_short(buf, msg_offset, #needed_lit));
}
// SAFETY: extent check above proved header + fixed body fit.
Ok(unsafe { Self::wrap_unchecked(buf, msg_offset) })
}
/// Trusted body-only wrap. Proves header + fixed-body extent then
/// constructs; **panics** if the buffer is too short. Field setters
/// use unchecked writes justified by that proof.
///
/// Prefer [`Self::try_wrap`] at untrusted boundaries.
#[inline]
pub fn wrap(
buf: &'a mut [u8],
msg_offset: usize,
) -> #name_encoder_ident<'a, sbe_rt::HeaderAbsent> {
if #needed_lit > buf.len().saturating_sub(msg_offset) {
panic!("{}", Self::buffer_too_short(buf, msg_offset, #needed_lit));
}
// SAFETY: extent check above proved header + fixed body fit.
unsafe { Self::wrap_unchecked(buf, msg_offset) }
}
/// Zero-check body-only wrap — raw pointer ops, **UB** on OOB.
/// Only for proven-tight hot loops where the panic machinery is
/// measurable in the critical path.
///
/// # Safety
/// `msg_offset + HEADER_LENGTH + BLOCK_LENGTH` must not overflow
/// and must be ≤ `buf.len()` for the lifetime of the encoder.
#[inline]
pub unsafe fn wrap_unchecked(
buf: &'a mut [u8],
msg_offset: usize,
) -> #name_encoder_ident<'a, sbe_rt::HeaderAbsent> {
let body_offset = msg_offset + #header_size_lit;
#name_encoder_ident {
buf,
msg_offset,
offset: body_offset + #block_length_lit,
_header: core::marker::PhantomData,
#fields_phantom
}
}
};
impl_consts.extend(wrap_fn);
let wrap_apply_fn = quote::quote! {
/// Wrap a mutable buffer, write the header, with one bounds/overflow check.
/// `offset` is the **message start** (see [`Self::wrap`]).
///
/// Optional-field nullification is **not** applied by default — call
/// `apply_nulls()` if you want null sentinels.
#[inline]
pub fn try_wrap_and_apply_header(
buf: &'a mut [u8],
offset: usize,
) -> Result<#name_encoder_ident<'a, sbe_rt::HeaderPresent>, sbe_rt::EncodeError> {
if #needed_lit > buf.len().saturating_sub(offset) {
return Err(Self::buffer_too_short(buf, offset, #needed_lit));
}
// SAFETY: extent check above proved header + fixed body fit.
Ok(unsafe { Self::wrap_and_apply_header_unchecked(buf, offset) })
}
/// Trusted full-frame wrap + header. Proves header + fixed-body extent
/// then writes the header; **panics** if the buffer is too short.
/// Field setters use unchecked writes justified by that proof.
///
/// Prefer [`Self::try_wrap_and_apply_header`] at untrusted boundaries.
/// Call [`Self::wrap_and_apply_header_unchecked`] only with a proven
/// extent when even panic machinery must be avoided.
#[inline]
pub fn wrap_and_apply_header(
buf: &'a mut [u8],
offset: usize,
) -> #name_encoder_ident<'a, sbe_rt::HeaderPresent> {
if #needed_lit > buf.len().saturating_sub(offset) {
panic!("{}", Self::buffer_too_short(buf, offset, #needed_lit));
}
// SAFETY: extent check above proved header + fixed body fit.
unsafe { Self::wrap_and_apply_header_unchecked(buf, offset) }
}
/// Zero-check full-frame wrap + header — `copy_nonoverlapping`, **UB**
/// on OOB. Only for proven-tight hot loops.
///
/// # Safety
/// `offset + HEADER_LENGTH + BLOCK_LENGTH` must not overflow and must be
/// ≤ `buf.len()` for the lifetime of the encoder.
#[inline]
pub unsafe fn wrap_and_apply_header_unchecked(
buf: &'a mut [u8],
offset: usize,
) -> #name_encoder_ident<'a, sbe_rt::HeaderPresent> {
// SAFETY: caller guarantees offset + HEADER_LENGTH ≤ buf.len().
unsafe {
core::ptr::copy_nonoverlapping(
Self::HEADER_TEMPLATE.as_ptr(),
buf.as_mut_ptr().add(offset),
#header_size_lit,
);
}
let body_offset = offset + #header_size_lit;
#name_encoder_ident {
buf,
msg_offset: offset,
offset: body_offset + #block_length_lit,
_header: core::marker::PhantomData,
#fields_phantom
}
}
};
impl_consts.extend(wrap_apply_fn);
// Claim-compatible wrap: validates buffer is exactly ENCODED_LENGTH bytes.
// For use with try_claim / pre-sized claim buffers where the buffer is pre-sized to the message.
if is_fixed {
impl_consts.extend(quote::quote! {
/// Wrap a mutable buffer sized exactly to `ENCODED_LENGTH` bytes.
/// For use with claim buffers (`try_claim`) where the caller has
/// already allocated exactly the right size.
#[inline]
pub fn wrap_into_claim(
buf: &'a mut [u8],
) -> Result<#name_encoder_ident<'a, sbe_rt::HeaderPresent>, sbe_rt::EncodeError> {
if buf.len() != Self::ENCODED_LENGTH {
return Err(sbe_rt::EncodeError::ClaimLengthMismatch {
expected: Self::ENCODED_LENGTH,
actual: buf.len(),
});
}
Ok(Self::wrap_and_apply_header(buf, 0))
}
});
}
// Opt-in: write null sentinels for all optional fields. Call this after
// wrap_and_apply_header if you want unset optional fields to carry their
// schema-defined null value instead of whatever was in the buffer.
// Not called by default (sbe-tool does not nullify on wrap).
{
let mut null_buf = String::new();
let offset_base = format!("self.msg_offset + {header_size}");
generate_nullification(
&mut null_buf,
&msg.fields,
&offset_base,
"self.buf",
byte_order,
elements,
);
if !null_buf.is_empty() {
let null_ts: proc_macro2::TokenStream = null_buf
.parse()
.expect("generate_nullification produced invalid token stream");
let apply_nulls_fn = quote::quote! {
/// Write the schema-defined null sentinel into every optional field.
///
/// Optional only — `wrap_and_apply_header` does not nullify by default
/// (matching sbe-tool). Call this if you want unset optional fields to
/// carry their null value rather than stale buffer contents.
#[inline]
pub fn apply_nulls(&mut self) -> &mut Self {
#null_ts
self
}
};
impl_contents.extend(apply_nulls_fn);
}
}
// Placement utils live only on EncoderMetadata via get_metadata() —
// see ENCODER_RESERVED in conversion_helpers (inherent methods only).
for f in &msg.fields {
let f_name = to_snake_case(&f.name);
// Offset of this field from the message header start (header + body offset).
let body_offset = header_size + f.offset;
let body_offset_lit = syn::LitInt::new(&body_offset.to_string(), span);
// Absolute buffer index under the truthful coordinate system.
let abs_offset = quote::quote! { self.msg_offset + #body_offset_lit };
// RawFixedWriter holds a body-only slice with msg_offset = 0, so field
// offsets are body-relative (schema field offset), not header-inclusive.
let field_off_lit = syn::LitInt::new(&f.offset.to_string(), span);
let raw_abs = quote::quote! { self.msg_offset + #field_off_lit };
// In converter mode, raw setters are suffixed _wire when a domain
// Raw setters become *_wire when a conversion is configured so the
// converted setter takes the original name.
let wire_name = field_has_conversion_free(f, conversions).then(|| format!("{f_name}_wire"));
let method_name = wire_name.as_deref().unwrap_or(&f_name);
let f_ident = resolve_field_ident(&f_name, &wire_name, ENCODER_RESERVED);
// Field descriptions must attach to the setter method (impl_contents),
// not the outer token stream — otherwise they float free of the API.
let field_doc = f.description.as_ref().map(|d| doc_attr_tokens(d));
match &f.field_type {
FieldType::Primitive(prim, length) => {
if f.presence == Presence::Constant {
continue;
}
let prim_size = prim.size();
let prim_size_lit = syn::LitInt::new(&prim_size.to_string(), span);
let r_type: syn::Type = syn::parse_str(rust_type(*prim)).unwrap();
if let Some(len) = length {
let len_lit = syn::LitInt::new(&len.to_string(), span);
if prim_size == 1 {
// [u8; N] / [i8; N] / char: no multi-byte endian swap; bulk
// copy via u8 view (i8 arrays cannot `copy_from_slice` into [u8]).
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: [#r_type; #len_lit]) -> &mut Self {
let offset = #abs_offset;
unsafe {
let dst = self.buf.get_unchecked_mut(offset..offset + #len_lit);
let src = core::slice::from_raw_parts(
val.as_ptr() as *const u8,
#len_lit,
);
dst.copy_from_slice(src);
}
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: [#r_type; #len_lit]) -> &mut Self {
let offset = #raw_abs;
unsafe {
let dst = self.buf.get_unchecked_mut(offset..offset + #len_lit);
let src = core::slice::from_raw_parts(
val.as_ptr() as *const u8,
#len_lit,
);
dst.copy_from_slice(src);
}
self
}
});
// Zero-padded string write (Java vehicleCode(String) parity).
let str_ident = syn::Ident::new(&format!("{method_name}_str"), span);
let field_lit = syn::LitStr::new(&f.name, span);
impl_contents.extend(quote::quote! {
#[inline]
pub fn #str_ident(&mut self, src: &str) -> Result<&mut Self, sbe_rt::EncodeError> {
if src.len() > #len_lit {
return Err(sbe_rt::EncodeError::FixedArrayTooLong {
field: #field_lit,
max_length: #len_lit,
actual: src.len(),
});
}
let mut tmp = [0 as #r_type; #len_lit];
let bytes = src.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
tmp[i] = bytes[i] as #r_type;
i += 1;
}
Ok(self.#f_ident(tmp))
}
});
raw_impl_contents.extend(quote::quote! {
#[inline]
pub fn #str_ident(&mut self, src: &str) -> Result<&mut Self, sbe_rt::EncodeError> {
if src.len() > #len_lit {
return Err(sbe_rt::EncodeError::FixedArrayTooLong {
field: #field_lit,
max_length: #len_lit,
actual: src.len(),
});
}
let mut tmp = [0 as #r_type; #len_lit];
let bytes = src.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
tmp[i] = bytes[i] as #r_type;
i += 1;
}
Ok(self.#f_ident(tmp))
}
});
} else {
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: [#r_type; #len_lit]) -> &mut Self {
let offset = #abs_offset;
let mut idx = 0usize;
while idx < #len_lit {
unsafe {
self.buf.get_unchecked_mut(offset + idx * #prim_size_lit..offset + (idx + 1) * #prim_size_lit)
.copy_from_slice(&val[idx].#to_endian());
}
idx += 1;
}
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: [#r_type; #len_lit]) -> &mut Self {
let offset = #raw_abs;
let mut idx = 0usize;
while idx < #len_lit {
unsafe {
self.buf.get_unchecked_mut(offset + idx * #prim_size_lit..offset + (idx + 1) * #prim_size_lit)
.copy_from_slice(&val[idx].#to_endian());
}
idx += 1;
}
self
}
});
}
// Unrolled put_field(v0, v1, …) for small fixed arrays (Java putSomeNumbers).
if (2..=8).contains(len) {
let put_ident = syn::Ident::new(&format!("put_{method_name}"), span);
let params: Vec<syn::Ident> = (0..*len)
.map(|i| syn::Ident::new(&format!("v{i}"), span))
.collect();
impl_contents.extend(quote::quote! {
#[inline]
pub fn #put_ident(&mut self, #(#params: #r_type),*) -> &mut Self {
self.#f_ident([#(#params),*])
}
});
raw_impl_contents.extend(quote::quote! {
#[inline]
pub fn #put_ident(&mut self, #(#params: #r_type),*) -> &mut Self {
self.#f_ident([#(#params),*])
}
});
}
} else if prim_size == 1 {
// Direct byte write for u8/i8/char — 1 instruction vs 3.
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #r_type) -> &mut Self {
*unsafe { self.buf.get_unchecked_mut(#abs_offset) } = val as u8;
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #r_type) -> &mut Self {
*unsafe { self.buf.get_unchecked_mut(#raw_abs) } = val as u8;
self
}
});
} else {
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #r_type) -> &mut Self {
let offset = #abs_offset;
// SAFETY: wrap/wrap_and_apply_header validates buf.len() >= msg_offset + HEADER + BLOCK,
// and field extent is within BLOCK_LENGTH by construction.
unsafe {
self.buf.get_unchecked_mut(offset..offset + #prim_size_lit)
.copy_from_slice(&val.#to_endian());
}
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #r_type) -> &mut Self {
let offset = #raw_abs;
unsafe {
self.buf.get_unchecked_mut(offset..offset + #prim_size_lit)
.copy_from_slice(&val.#to_endian());
}
self
}
});
}
}
FieldType::Composite {
name: comp_name,
size: comp_size,
} => {
let target_type: syn::Type = syn::parse_str(&to_pascal_case(comp_name)).unwrap();
let comp_size_lit = syn::LitInt::new(&comp_size.to_string(), span);
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #target_type) -> &mut Self {
let offset = #abs_offset;
self.buf[offset..offset + #comp_size_lit]
.copy_from_slice(&val.0);
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #target_type) -> &mut Self {
let offset = #raw_abs;
self.buf[offset..offset + #comp_size_lit]
.copy_from_slice(&val.0);
self
}
});
}
FieldType::Enum {
name: enum_name,
encoding_type,
} => {
if f.presence == Presence::Constant {
continue;
}
let target_type: syn::Type = syn::parse_str(&to_pascal_case(enum_name)).unwrap();
let r_type: syn::Type = syn::parse_str(rust_type(*encoding_type)).unwrap();
let prim_size = encoding_type.size();
let prim_size_lit = syn::LitInt::new(&prim_size.to_string(), span);
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #target_type) -> &mut Self {
let offset = #abs_offset;
self.buf[offset..offset + #prim_size_lit].copy_from_slice(&(val as #r_type).#to_endian());
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #target_type) -> &mut Self {
let offset = #raw_abs;
self.buf[offset..offset + #prim_size_lit].copy_from_slice(&(val as #r_type).#to_endian());
self
}
});
// Boolean fields get an additional setter that accepts bool directly
if crate::structured_ir::is_bool_enum(elements, enum_name) {
let f_name_bool = syn::Ident::new(&format!("{}_bool", f_name), span);
impl_contents.extend(quote::quote! {
#[inline]
pub fn #f_name_bool(&mut self, val: bool) -> &mut Self {
self.buf[#abs_offset] = val as u8;
self
}
});
raw_impl_contents.extend(quote::quote! {
#[inline]
pub fn #f_name_bool(&mut self, val: bool) -> &mut Self {
self.buf[#raw_abs] = val as u8;
self
}
});
}
}
FieldType::Set {
name: set_name,
encoding_type,
} => {
let target_type: syn::Type = syn::parse_str(&to_pascal_case(set_name)).unwrap();
let prim_size = encoding_type.size();
let prim_size_lit = syn::LitInt::new(&prim_size.to_string(), span);
impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #target_type) -> &mut Self {
let offset = #abs_offset;
self.buf[offset..offset + #prim_size_lit].copy_from_slice(&val.0.#to_endian());
self
}
});
raw_impl_contents.extend(quote::quote! {
#field_doc
#[inline]
pub fn #f_ident(&mut self, val: #target_type) -> &mut Self {
let offset = #raw_abs;
self.buf[offset..offset + #prim_size_lit].copy_from_slice(&val.0.#to_endian());
self
}
});
}
}
// Field id / offset / length / MetaAttribute (also on encoder, Java parity).
// Field NULL/MIN/MAX consts on concrete impl — turbofish-free access.
if enable_meta_attributes {
impl_consts.extend(emit_field_consts(f));
}
}
// No partial as_bytes on incomplete stages — complete-message byte/length
// views exist only on the terminal complete stage.
// Encoded-length support: strategy-classified (computed above).
// Length helpers are associated functions — keep on concrete impl for
// turbofish-free `CarEncoder::compute_encoded_length_with_message_header(...)`.
impl_consts.extend(encoded_len_gen.encoder_impl.clone());
// A complete, owned, latest-version snapshot of every required fixed
// field. Optional fields are `Option<T>`; constants are excluded.
// No `Default` — every required field must be explicitly initialised.
{
let fixed_name = syn::Ident::new(&format!("{name}FixedFields"), span);
let mut fixed_fields_ts = proc_macro2::TokenStream::new();
for f in &msg.fields {
if f.presence == crate::Presence::Constant {
continue;
}
let fname_snake = to_snake_case(&f.name);
let f_ident = syn::Ident::new(&fname_snake, span);
if let Some(ref desc) = f.description {
fixed_fields_ts.extend(doc_attr_tokens(desc));
}
let is_optional = f.presence == crate::Presence::Optional;
if is_optional {
let ty = field_type_ident(&f.field_type, span);
fixed_fields_ts.extend(quote::quote! {
pub #f_ident: Option<#ty>,
});
} else {
let ty = field_type_ident(&f.field_type, span);
fixed_fields_ts.extend(quote::quote! {
pub #f_ident: #ty,
});
}
}
ts.extend(quote::quote! {
/// Complete set of latest-version fixed fields for this message.
/// Required fields (including `sinceVersion` fields) are concrete
/// values; only presence-optional fields are `Option<T>`. Constants
/// are excluded.
///
/// This struct is **intentionally exhaustive** (not
/// `#[non_exhaustive]`): when the schema adds a fixed field, every
/// `fixed(&…)` call site must be updated. That is a feature — schema
/// changes surface as compile errors rather than silent defaults.
#[derive(Debug, Clone)]
pub struct #fixed_name {
#fixed_fields_ts
}
});
}
{
let fixed_name = syn::Ident::new(&format!("{name}FixedFields"), span);
// Build the write block: for each non-constant field, write from the struct.
// Use _wire suffixed setters for converter-enabled composite fields.
let mut write_stmts = proc_macro2::TokenStream::new();
let buf_expr: syn::Expr = syn::parse_quote!(self.buf);
for f in &msg.fields {
if f.presence == crate::Presence::Constant {
continue;
}
let fname_snake = to_snake_case(&f.name);
let is_converted = field_has_conversion_free(f, conversions);
let setter_ident = {
let base = resolve_field_ident(&fname_snake, &None, ENCODER_RESERVED);
if is_converted {
syn::Ident::new(&format!("{}_wire", base), span)
} else {
base
}
};
let field_ident = syn::Ident::new(&fname_snake, span);
if f.presence == crate::Presence::Optional {
// Some → write value; None → write exact schema null image so
// dirty buffers cannot leak prior optional values.
let body_off = header_size + f.offset;
let body_off_lit = syn::LitInt::new(&body_off.to_string(), span);
let abs_off = quote::quote! { self.msg_offset + #body_off_lit };
let null_write = match null_image_stmts_for_field(
f, abs_off, &buf_expr, byte_order, elements,
) {
Ok(Some(ts)) => ts,
Ok(None) => {
// Optional field without a wire image — treat as zero fill
// of the declared field size (defensive; should not happen
// for resolved optionals).
let sz = f.field_type.size();
let sz_lit = syn::LitInt::new(&sz.to_string(), span);
quote::quote! {
{
let offset = self.msg_offset + #body_off_lit;
self.buf[offset..offset + #sz_lit].fill(0);
}
}
}
Err(reason) => {
// Surface as a compile_error! so the consumer build fails
// with a typed diagnostic rather than panicking the generator.
let msg_lit = syn::LitStr::new(
&format!(
"cannot derive null image for optional field '{}' on message '{}': {reason}",
f.name, msg.name
),
span,
);
quote::quote! { compile_error!(#msg_lit); }
}
};
write_stmts.extend(quote::quote! {
if let Some(ref v) = fixed.#field_ident {
self.#setter_ident(*v);
} else {
#null_write
}
});
} else {
write_stmts.extend(quote::quote! {
self.#setter_ident(fixed.#field_ident);
});
}
}
// `format!`, not `///`: a doc comment inside `quote!` is already a
// string literal when interpolation runs, so `#fixed_name` in one would
// reach the generated docs verbatim.
let fixed_doc = format!(
"Set all fixed fields at once from a [`{fixed_name}`] value.\n\n\
Required fields are always written; optional fields write the \
schema null wire image when `None` (including nested optional \
composite members). Returns the encoder ready for ordered tail methods."
);
let fixed_doc_tokens = crate::codegen::runtime::doc_lines_tokens(&fixed_doc);
phase_contents.extend(quote::quote! {
#fixed_doc_tokens
// `inline(always)`, not `inline`: T-13 added a null-image `else`
// arm per optional field, which pushed this body past LLVM's
// inline threshold and got the hint declined. Measured on
// `ergo_historic/null_option/encode_fixed`: 2.33ns baseline →
// 4.28ns (hint declined) → 1.92ns (forced). Re-verify with
// `just bench-historic` before weakening this.
#[inline(always)]
#[must_use]
pub fn fixed(mut self, fixed: &#fixed_name) -> #name_encoder_ident<'a, H, sbe_rt::FieldsFixed> {
#write_stmts
#name_encoder_ident {
buf: self.buf,
msg_offset: self.msg_offset,
offset: self.offset,
_header: core::marker::PhantomData,
_fields: core::marker::PhantomData,
}
}
});
}
{
let raw_name = syn::Ident::new(&format!("{name}RawFixedWriter"), span);
let fixed_name = syn::Ident::new(&format!("{name}FixedFields"), span);
let raw_struct_doc = format!(
"Raw fixed-field writer. Individual field setters are available \
only on this writer. When done, embed the fields in a \
[`{fixed_name}`] and call the encoder's `fixed()`."
);
let raw_struct_doc_tokens = crate::codegen::runtime::doc_lines_tokens(&raw_struct_doc);
let raw_fixed_doc = format!(
"Return a dedicated raw fixed-field writer. All individual field \
setters are available on the writer. To advance to tail stages, \
collect the values into a [`{fixed_name}`] and call `fixed()`."
);
let raw_fixed_doc_tokens = crate::codegen::runtime::doc_lines_tokens(&raw_fixed_doc);
ts.extend(quote::quote! {
#raw_struct_doc_tokens
#[must_use = "raw fixed writer must be embedded in FixedFields"]
pub struct #raw_name<'a> {
buf: &'a mut [u8],
msg_offset: usize,
offset: usize,
}
impl<'a> #raw_name<'a> {
#raw_impl_contents
}
});
phase_contents.extend(quote::quote! {
#raw_fixed_doc_tokens
#[inline]
#[must_use]
pub fn raw_fixed(self) -> #raw_name<'a> {
let body_start = self.msg_offset + #header_size_lit;
#raw_name {
buf: &mut self.buf[body_start..],
msg_offset: 0,
offset: self.offset - body_start,
}
}
});
}
// Concrete (default H, default F=Unfixed) for associated constants + constructors.
ts.extend(quote::quote! {
impl<'a> #name_encoder_ident<'a> {
#impl_consts
}
});
// Unfixed phase: setters plus the phase transitions. Emitted as one
// concrete impl, exactly as before — these are the benchmarked hot paths
// (`encode_scalar_body_only`, `optional_enum_nullify`), and relocating
// them into a generic `impl<H, F>` measurably regressed both against
// sbe-tool. Keep this block concrete and unsplit.
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #name_encoder_ident<'a, H, sbe_rt::FieldsUnfixed> {
#impl_contents
#phase_contents
}
});
// Fixed phase: the same individual setters again, so a conversion setter
// (`*_from`) can run after `fixed()` and still reach a terminal method —
// `fixed()` takes wire values, so a domain-typed field has no other route
// to completion. Phase transitions are deliberately absent: `fixed()`
// stays one-way, so terminal methods remain locked until every required
// field is written.
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #name_encoder_ident<'a, H, sbe_rt::FieldsFixed> {
#impl_contents
}
});
// ── Metadata facet ──────────────────────────────────────────────────
let enc_metadata_ident = syn::Ident::new(&format!("{}EncoderMetadata", name), span);
// Complete-sounding `as_bytes_with_header` only when there are no tails;
// otherwise this stage is fixed-block only and must not look like a frame.
let meta_bytes = if msg.is_fixed() {
// Complete-sounding byte views live on the FieldsFixed encoder, not
// on unfixed metadata — wrap + get_metadata().as_bytes_with_header()
// must not publish an unwritten body.
quote::quote! {}
} else {
quote::quote! {
/// Fixed-block body bytes only (groups/var-data not yet written).
/// For a complete frame use the terminal stage's
/// `as_bytes_with_header`.
#[inline]
pub fn as_fixed_body_bytes(&self) -> &[u8] {
&self.encoder_buf[self.encoder_msg_offset + #header_size_lit..self.encoder_offset]
}
/// Header + fixed block only — **not** a complete SBE message when
/// groups or var-data remain. Prefer the complete stage's
/// `as_bytes_with_header`.
#[inline]
pub fn as_fixed_region_with_header(&self) -> &[u8] {
&self.encoder_buf[self.encoder_msg_offset..self.encoder_offset]
}
}
};
if msg.is_fixed() {
ts.extend(quote::quote! {
/// Buffer-placement metadata. Holds a reference to the parent encoder
/// — zero-copy. Utility methods live here so no schema field can
/// collide with them.
#[derive(Clone, Copy)]
pub struct #enc_metadata_ident<'m, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent, F: sbe_rt::FieldsState = sbe_rt::FieldsUnfixed> {
encoder_msg_offset: usize,
encoder_offset: usize,
encoder_buf: &'m [u8],
_h: core::marker::PhantomData<H>,
_f: core::marker::PhantomData<F>,
}
impl<'m, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> #enc_metadata_ident<'m, H, F> {
/// Absolute offset of this message within the original buffer
/// (the `msg_offset` argument passed to `wrap`).
#[inline]
pub const fn message_offset(&self) -> usize {
self.encoder_msg_offset
}
/// Absolute current write cursor within the original buffer.
#[inline]
pub const fn limit(&self) -> usize {
self.encoder_offset
}
/// The complete original buffer this encoder wraps.
#[inline]
pub const fn buffer(&self) -> &[u8] {
self.encoder_buf
}
}
impl<'m, H: sbe_rt::HeaderState> #enc_metadata_ident<'m, H, sbe_rt::FieldsFixed> {
/// Message body bytes (header exclusive). Only after `fixed()`.
#[inline]
pub fn as_body_bytes(&self) -> &[u8] {
&self.encoder_buf[self.encoder_msg_offset + #header_size_lit..self.encoder_offset]
}
/// Header-inclusive frame bytes. Only after `fixed()`.
#[inline]
pub fn as_bytes_with_header(&self) -> &[u8] {
&self.encoder_buf[self.encoder_msg_offset..self.encoder_offset]
}
}
});
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> #name_encoder_ident<'a, H, F> {
#[inline]
pub fn get_metadata(&self) -> #enc_metadata_ident<'_, H, F> {
#enc_metadata_ident {
encoder_msg_offset: self.msg_offset,
encoder_offset: self.offset,
encoder_buf: self.buf,
_h: core::marker::PhantomData,
_f: core::marker::PhantomData,
}
}
}
});
} else {
ts.extend(quote::quote! {
/// Buffer-placement metadata. Holds a reference to the parent encoder
/// — zero-copy. Utility methods live here so no schema field can
/// collide with them.
#[derive(Clone, Copy)]
pub struct #enc_metadata_ident<'m, H: sbe_rt::HeaderState = sbe_rt::HeaderPresent> {
encoder_msg_offset: usize,
encoder_offset: usize,
encoder_buf: &'m [u8],
_h: core::marker::PhantomData<H>,
}
impl<'m, H: sbe_rt::HeaderState> #enc_metadata_ident<'m, H> {
#meta_bytes
/// Absolute offset of this message within the original buffer
/// (the `msg_offset` argument passed to `wrap`).
#[inline]
pub const fn message_offset(&self) -> usize {
self.encoder_msg_offset
}
/// Absolute current write cursor within the original buffer.
#[inline]
pub const fn limit(&self) -> usize {
self.encoder_offset
}
/// The complete original buffer this encoder wraps.
#[inline]
pub const fn buffer(&self) -> &[u8] {
self.encoder_buf
}
}
});
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> #name_encoder_ident<'a, H, F> {
#[inline]
pub fn get_metadata(&self) -> #enc_metadata_ident<'_, H> {
#enc_metadata_ident {
encoder_msg_offset: self.msg_offset,
encoder_offset: self.offset,
encoder_buf: self.buf,
_h: core::marker::PhantomData,
}
}
}
});
}
if total_tail > 0 {
let mut tail_idx = 0;
for g in &msg.groups {
let current_stage = &stage_idents[tail_idx];
let next_stage = &stage_idents[tail_idx + 1];
let g_snake = syn::Ident::new(&to_snake_case(&g.name), span);
let raw_enc_name = to_pascal_case(&g.name);
let scoped_enc = if multi_message {
format!("{}{}", &name, raw_enc_name)
} else {
raw_enc_name
};
let g_pascal_enc = syn::Ident::new(&format!("{scoped_enc}Encoder"), span);
let (_dim_name, dim_size, _, _) = get_dimension_info(elements, &g.dimension_type);
let (num_offset, num_size, num_prim) = get_dim_num_layout(elements, &g.dimension_type);
let dim_size_lit = syn::LitInt::new(&dim_size.to_string(), span);
let num_offset_lit = syn::LitInt::new(&num_offset.to_string(), span);
let num_size_lit = syn::LitInt::new(&num_size.to_string(), span);
let count_ty: syn::Type = syn::parse_str(rust_type(num_prim)).unwrap();
let g_snake_unknown =
syn::Ident::new(&format!("{}_unknown_size", to_snake_case(&g.name)), span);
// `format!`, not `///`: `#g_snake` inside a `quote!` doc comment
// would be emitted verbatim instead of the sibling method's name.
let unknown_count_doc = format!(
"Encode this group without knowing the count up front.\n\n\
The dimension header is written with a zero placeholder; after \
the closure returns, the actual entry count is back-patched \
into the header. No `GroupFull` check — overflow is the \
caller's responsibility.\n\n\
Prefer [`Self::{g_snake}`] when the count is known at compile \
time or from a small input."
);
let unknown_count_doc_tokens =
crate::codegen::runtime::doc_lines_tokens(&unknown_count_doc);
// Root stage (first group) only available after fixed(&FixedFields).
let root_impl_header = if tail_idx == 0 {
quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #current_stage<'a, H, sbe_rt::FieldsFixed>
}
} else {
quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #current_stage<'a, H>
}
};
ts.extend(quote::quote! {
#root_impl_header {
/// Encode this group with a known count up front.
/// Closures return [`sbe_rt::GroupResult`]
/// (`Result<(), EncodeError>`); `?` works — there is no
/// separate `try_*` method name.
#[inline]
#[must_use]
pub fn #g_snake<F>(
mut self,
count: #count_ty,
f: F,
) -> Result<#next_stage<'a, H>, sbe_rt::EncodeError>
where
F: FnOnce(&mut #g_pascal_enc<'a>) -> sbe_rt::GroupResult,
{
if self.offset + #dim_size_lit > self.buf.len() {
return Err(sbe_rt::EncodeError::BufferTooShort {
field: stringify!(#g_snake),
needed: #dim_size_lit,
available: self.buf.len().saturating_sub(self.offset),
}
.into());
}
self.buf[self.offset..self.offset + #dim_size_lit]
.copy_from_slice(&#g_pascal_enc::GROUP_DIM_TEMPLATE);
self.buf
[self.offset + #num_offset_lit..self.offset + #num_offset_lit + #num_size_lit]
.copy_from_slice(&count.#to_endian());
let mut group =
#g_pascal_enc::wrap(self.buf, self.offset + #dim_size_lit, count);
f(&mut group)?;
let written = group.written();
if written != count {
return Err(sbe_rt::EncodeError::GroupCountMismatch {
declared: count as u32,
actual: written as u32,
});
}
Ok(#next_stage {
buf: group.buf,
msg_offset: self.msg_offset,
offset: group.offset,
_header: core::marker::PhantomData,
})
}
#unknown_count_doc_tokens
#[inline]
#[must_use]
pub fn #g_snake_unknown<F>(
mut self,
f: F,
) -> Result<#next_stage<'a, H>, sbe_rt::EncodeError>
where
F: FnOnce(&mut #g_pascal_enc<'a>) -> sbe_rt::GroupResult,
{
if self.offset + #dim_size_lit > self.buf.len() {
return Err(sbe_rt::EncodeError::BufferTooShort {
field: stringify!(#g_snake),
needed: #dim_size_lit,
available: self.buf.len().saturating_sub(self.offset),
}
.into());
}
self.buf[self.offset..self.offset + #dim_size_lit]
.copy_from_slice(&#g_pascal_enc::GROUP_DIM_TEMPLATE);
let count_offset = self.offset + #num_offset_lit;
self.buf[count_offset..count_offset + #num_size_lit].fill(0);
// Use MAX count to skip GroupFull checks during add().
// Run in a block so group's reborrow of self.buf ends
// before we back-patch the count.
let (buf, offset, actual) = {
let mut group = #g_pascal_enc::wrap(
self.buf, self.offset + #dim_size_lit, #count_ty::MAX,
);
f(&mut group)?;
let n = group.written();
(group.buf, group.offset, n)
};
// Back-patch the actual count.
buf[count_offset..count_offset + #num_size_lit]
.copy_from_slice(&actual.#to_endian());
Ok(#next_stage {
buf,
msg_offset: self.msg_offset,
offset,
_header: core::marker::PhantomData,
})
}
}
});
tail_idx += 1;
}
// VarData methods
for vd in &msg.var_data {
let current_stage = &stage_idents[tail_idx];
let next_stage = &stage_idents[tail_idx + 1];
let vd_snake = syn::Ident::new(&to_snake_case(&vd.name), span);
let vd_snake_unchecked =
syn::Ident::new(&format!("{}_unchecked", to_snake_case(&vd.name)), span);
let vd_snake_with = syn::Ident::new(&format!("{}_with", to_snake_case(&vd.name)), span);
let (_, prefix_size, _, len_type) = get_vardata_info(elements, &vd.type_name);
let prefix_size_lit = syn::LitInt::new(&prefix_size.to_string(), span);
let len_rust_type: syn::Type = syn::parse_str(rust_type(len_type)).unwrap();
// Checked body: conditionally includes max_length guard.
let mut checked_body = proc_macro2::TokenStream::new();
let mut with_checked_body = proc_macro2::TokenStream::new();
if let Some(max) = vd.max_length {
let max_lit = syn::LitInt::new(&max.to_string(), span);
let vd_name_str = &vd.name;
checked_body.extend(quote::quote! {
if data.len() > #max_lit {
return Err(sbe_rt::EncodeError::VarDataTooLong {
field: #vd_name_str,
max_length: #max_lit,
actual: data.len(),
});
}
});
with_checked_body.extend(quote::quote! {
if exact_len > #max_lit {
return Err(sbe_rt::EncodeError::VarDataTooLong {
field: #vd_name_str,
max_length: #max_lit,
actual: exact_len,
}.into());
}
});
}
let shared_body = quote::quote! {
let needed = #prefix_size_lit + data.len();
if self.offset + needed > self.buf.len() {
return Err(sbe_rt::EncodeError::BufferTooShort {
field: stringify!(#vd_snake),
needed,
available: self.buf.len().saturating_sub(self.offset),
});
}
let wire_length = <#len_rust_type>::try_from(data.len()).map_err(|_| {
sbe_rt::EncodeError::VarDataTooLong {
field: stringify!(#vd_snake),
max_length: <#len_rust_type>::MAX as usize,
actual: data.len(),
}
})?;
let len_bytes = wire_length.#to_endian();
self.buf[self.offset..self.offset + #prefix_size_lit]
.copy_from_slice(&len_bytes);
let start = self.offset + #prefix_size_lit;
self.buf[start..start + data.len()].copy_from_slice(data);
Ok(#next_stage {
buf: self.buf,
msg_offset: self.msg_offset,
offset: start + data.len(),
_header: core::marker::PhantomData,
})
};
let vd_impl_header = if tail_idx == 0 {
quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #current_stage<'a, H, sbe_rt::FieldsFixed>
}
} else {
quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #current_stage<'a, H>
}
};
ts.extend(quote::quote! {
#vd_impl_header {
#[inline]
#[must_use]
pub fn #vd_snake(
mut self,
data: &[u8],
) -> Result<#next_stage<'a, H>, sbe_rt::EncodeError> {
#checked_body
#shared_body
}
#[inline]
#[must_use]
pub fn #vd_snake_unchecked(
mut self,
data: &[u8],
) -> Result<#next_stage<'a, H>, sbe_rt::EncodeError> {
#shared_body
}
/// Lend exactly `exact_len` bytes of the var-data region
/// to a closure for nested-message encoding. Zero-copy:
/// the closure writes directly into the outer buffer.
///
/// Canonical nested-SBE pattern (AppMessage → L2Book):
/// ```text
/// let inner_len = InnerEncoder::compute_length_with_header(...);
/// after.payload_with(inner_len, |payload| {
/// let len = InnerEncoder::wrap_and_apply_header(payload, 0)?
/// .field(value)
/// // continue the single encoder chain through all tail stages
/// .encoded_length_with_header();
/// debug_assert_eq!(len, inner_len);
/// Ok(())
/// })?;
/// ```
/// Returns the next stage on success; on failure the
/// caller error propagates unchanged and no partial
/// data is published.
#[inline]
#[must_use]
pub fn #vd_snake_with<E, F>(
mut self,
exact_len: usize,
f: F,
) -> Result<#next_stage<'a, H>, E>
where
E: From<sbe_rt::EncodeError>,
F: FnOnce(&mut [u8]) -> Result<(), E>,
{
#with_checked_body
let needed = #prefix_size_lit + exact_len;
if self.offset + needed > self.buf.len() {
return Err(sbe_rt::EncodeError::BufferTooShort {
field: stringify!(#vd_snake),
needed,
available: self.buf.len().saturating_sub(self.offset),
}.into());
}
let wire_length = <#len_rust_type>::try_from(exact_len).map_err(|_| {
sbe_rt::EncodeError::VarDataTooLong {
field: stringify!(#vd_snake),
max_length: <#len_rust_type>::MAX as usize,
actual: exact_len,
}
})?;
let len_bytes = wire_length.#to_endian();
self.buf[self.offset..self.offset + #prefix_size_lit]
.copy_from_slice(&len_bytes);
let start = self.offset + #prefix_size_lit;
f(&mut self.buf[start..start + exact_len])?;
Ok(#next_stage {
buf: self.buf,
msg_offset: self.msg_offset,
offset: start + exact_len,
_header: core::marker::PhantomData,
})
}
}
});
tail_idx += 1;
}
// Complete state: body methods on any H; header bytes only on HeaderPresent.
let complete_ident = &stage_idents[total_tail];
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #complete_ident<'a, H> {
/// SBE message body bytes (excluding the message header).
#[inline]
pub fn as_body_bytes(&self) -> &[u8] {
let body_start = self.msg_offset + #header_size_lit;
&self.buf[body_start..self.offset]
}
/// SBE message body length (excluding the message header).
#[inline]
pub fn encoded_length(&self) -> usize {
self.offset - self.msg_offset - #header_size_lit
}
/// Total SBE message length including the header region.
/// Pure arithmetic — available for body-only wraps too.
#[inline]
pub fn encoded_length_with_header(&self) -> usize {
self.offset - self.msg_offset
}
/// Unwritten region after this message's write cursor to the end of
/// the original buffer. Use for multi-message packing, e.g.
/// `NextEncoder::wrap_and_apply_header(remaining, 0)`. This is **not**
/// the payload of the current message — for the absolute write
/// cursor while keeping the encoder alive, use
/// `get_metadata().limit()`.
#[inline]
pub fn into_remaining_mut(self) -> &'a mut [u8] {
&mut self.buf[self.offset..]
}
}
impl<'a> #complete_ident<'a, sbe_rt::HeaderPresent> {
/// Header-inclusive bytes. Only available when the encoder was
/// constructed via `wrap_and_apply_header` (not raw `wrap`).
#[inline]
pub fn as_bytes_with_header(&self) -> &[u8] {
&self.buf[self.msg_offset..self.offset]
}
}
});
} else {
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState> #name_encoder_ident<'a, H, sbe_rt::FieldsFixed> {
/// SBE message body bytes (excluding the message header).
/// Only available after `fixed(&FixedFields)`.
#[inline]
pub fn as_body_bytes(&self) -> &[u8] {
let body_start = self.msg_offset + #header_size_lit;
&self.buf[body_start..self.offset]
}
/// SBE message body length (excluding the message header).
/// Only available after `fixed(&FixedFields)`.
#[inline]
pub fn encoded_length(&self) -> usize {
self.offset - self.msg_offset - #header_size_lit
}
/// Total SBE message length including the header region.
/// Only available after `fixed(&FixedFields)`.
#[inline]
pub fn encoded_length_with_header(&self) -> usize {
self.offset - self.msg_offset
}
/// Unwritten region after this message's write cursor to the end of
/// the original buffer. Use for multi-message packing, e.g.
/// `NextEncoder::wrap_and_apply_header(remaining, 0)`. Only available
/// after `fixed(&FixedFields)` so a reused buffer cannot pack the
/// next message while this body is still stale.
#[inline]
pub fn into_remaining_mut(self) -> &'a mut [u8] {
&mut self.buf[self.offset..]
}
}
impl<'a> #name_encoder_ident<'a, sbe_rt::HeaderPresent, sbe_rt::FieldsFixed> {
/// Header-inclusive bytes. Only available after
/// `wrap_and_apply_header` **and** `fixed(&FixedFields)`.
#[inline]
pub fn as_bytes_with_header(&self) -> &[u8] {
&self.buf[self.msg_offset..self.offset]
}
}
});
}
// Every FieldsState / HeaderState combination is a generated message type.
// `fixed()` returns `Encoder<_, FieldsFixed>` — that must stay `SbeMessage`.
ts.extend(quote::quote! {
impl<'a, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> #sealed_path::Sealed
for #name_encoder_ident<'a, H, F>
{
}
impl<'a, H: sbe_rt::HeaderState, F: sbe_rt::FieldsState> sbe_rt::SbeMessage
for #name_encoder_ident<'a, H, F>
{
const TEMPLATE_ID: u16 = #msg_id_lit;
const BLOCK_LENGTH: usize = #block_length_lit;
const SCHEMA_ID: u16 = #schema_id_lit;
const SCHEMA_VERSION: u16 = #schema_version_lit;
}
});
// ── T-14: UnfixedEncoder names the pre-`fixed()` stage ──────────
let unfixed_doc = if total_tail > 0 {
quote::quote! {
/// Pre-`fixed()` root encoder stage. Individual fixed-field setters
/// and [`fixed`](Self::fixed) live here; group/var-data tails are
/// only available on the [`sbe_rt::FieldsFixed`] phase after
/// `fixed(&FixedFields)`.
}
} else {
quote::quote! {
/// Pre-`fixed()` root encoder stage. Individual fixed-field setters
/// and [`fixed`](Self::fixed) live here; byte views are only
/// available on the [`sbe_rt::FieldsFixed`] phase after
/// `fixed(&FixedFields)`.
}
};
ts.extend(quote::quote! {
#unfixed_doc
pub type #unfixed_encoder_ident<'a, H = sbe_rt::HeaderPresent> =
#name_encoder_ident<'a, H, sbe_rt::FieldsUnfixed>;
});
let mut group_buf = String::new();
let enc_group_names: Vec<String> = msg
.groups
.iter()
.map(|g| {
let raw = to_pascal_case(&g.name);
if multi_message {
format!("{}{}", &name, raw)
} else {
raw
}
})
.collect();
for (gi, g) in msg.groups.iter().enumerate() {
generate_group_encoder(
&mut group_buf,
g,
elements,
byte_order,
&enc_group_names[gi],
&conversions,
domain_types,
);
}
if !group_buf.is_empty() {
let group_ts: proc_macro2::TokenStream = group_buf
.parse()
.expect("generate_group_encoder produced invalid token stream");
ts.extend(group_ts);
}
// Checked + unsafe unchecked constructors are emitted once on the
// concrete impl above. Do not re-emit a second safe zero-check
// pair here — that reintroduced UB from safe Rust.
ts.extend(encoded_len_gen.standalone);
ts
}