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
//! Postcard parser implementing FormatParser and FormatJitParser.
//!
//! Postcard is NOT a self-describing format, but Tier-0 deserialization is supported
//! via the `hint_struct_fields` mechanism. The driver tells the parser how many fields
//! to expect, and the parser emits `OrderedField` events accordingly.
use alloc::borrow::Cow;
use alloc::vec::Vec;
use crate::DEFAULT_MAX_COLLECTION_ELEMENTS;
use crate::error::codes;
use facet_format::{
ContainerKind, DeserializeErrorKind, EnumVariantHint, FieldKey, FieldLocationHint,
FormatParser, ParseError, ParseEvent, ParseEventKind, SavePoint, ScalarTypeHint, ScalarValue,
};
use facet_reflect::Span;
/// Create a ParseError from an error code and position.
fn error_from_code(code: i32, pos: usize) -> ParseError {
let message = match code {
codes::UNEXPECTED_EOF | codes::UNEXPECTED_END_OF_INPUT => "unexpected end of input",
codes::VARINT_OVERFLOW => "varint overflow",
codes::SEQ_UNDERFLOW => "sequence underflow",
codes::INVALID_BOOL => "invalid boolean value",
codes::INVALID_UTF8 => "invalid UTF-8",
codes::INVALID_OPTION_DISCRIMINANT => "invalid option discriminant",
codes::INVALID_ENUM_DISCRIMINANT => "invalid enum discriminant",
codes::UNSUPPORTED_OPAQUE_TYPE => "unsupported opaque type",
codes::COLLECTION_TOO_LARGE => "collection length exceeds maximum",
codes::UNSUPPORTED => "unsupported operation",
_ => "unknown error",
};
ParseError::new(
Span::new(pos, 1),
DeserializeErrorKind::InvalidValue {
message: message.into(),
},
)
}
/// Stored variant metadata for enum parsing.
#[derive(Debug, Clone)]
struct VariantMeta {
name: String,
kind: facet_core::StructKind,
field_count: usize,
}
/// Parser state for tracking nested structures.
#[derive(Debug, Clone)]
enum ParserState {
/// At the top level or after completing a value.
Ready,
/// Inside a struct, tracking remaining fields.
InStruct { remaining_fields: usize },
/// Inside a sequence, tracking remaining elements.
InSequence { remaining_elements: u64 },
/// Inside an enum variant, tracking parsing progress.
InEnum {
variant_name: String,
variant_kind: facet_core::StructKind,
variant_field_count: usize,
field_key_emitted: bool,
/// For multi-field variants, whether we've emitted the inner wrapper start
wrapper_start_emitted: bool,
/// For multi-field variants, whether we've emitted the inner wrapper end
wrapper_end_emitted: bool,
},
/// Inside a map, tracking remaining entries.
/// Maps are serialized as sequences of key-value pairs.
InMap { remaining_entries: u64 },
/// Inside a dynamically tagged array (facet_value::Value array).
InDynamicArray { remaining_elements: u64 },
/// Inside a dynamically tagged object (facet_value::Value object).
InDynamicObject {
remaining_entries: u64,
expecting_key: bool,
},
}
/// Postcard parser for Tier-0 and Tier-2 deserialization.
///
/// For Tier-0, the parser relies on `hint_struct_fields` to know how many fields
/// to expect in structs. Sequences are length-prefixed in the wire format.
pub struct PostcardParser<'de> {
input: &'de [u8],
pos: usize,
max_collection_elements: u64,
/// Stack of parser states for nested structures.
state_stack: Vec<ParserState>,
/// Peeked event (for `peek_event`).
peeked: Option<ParseEvent<'de>>,
/// Pending struct field count from `hint_struct_fields`.
pending_struct_fields: Option<usize>,
/// Pending scalar type hint from `hint_scalar_type`.
pending_scalar_type: Option<ScalarTypeHint>,
/// Pending sequence flag from `hint_sequence`.
pending_sequence: bool,
/// Pending byte sequence flag from `hint_byte_sequence`.
pending_byte_sequence: bool,
/// Pending remaining-bytes flag from `hint_remaining_byte_sequence`.
pending_remaining_bytes: bool,
/// Pending fixed-size array length from `hint_array`.
pending_array: Option<usize>,
/// Pending option flag from `hint_option`.
pending_option: bool,
/// Pending enum variant metadata from `hint_enum`.
pending_enum: Option<Vec<VariantMeta>>,
/// Pending opaque scalar type from `hint_opaque_scalar`.
pending_opaque: Option<OpaqueScalarHint>,
/// Pending map flag from `hint_map`.
pending_map: bool,
/// Pending dynamic value tag from `hint_dynamic_value`.
pending_dynamic: bool,
}
/// Information about an opaque scalar type for format-specific handling.
#[derive(Debug, Clone)]
struct OpaqueScalarHint {
type_identifier: &'static str,
/// True if the inner type is f32 (for OrderedFloat/NotNan)
inner_is_f32: bool,
}
impl<'de> PostcardParser<'de> {
/// Create a new postcard parser from input bytes.
pub const fn new(input: &'de [u8]) -> Self {
Self::with_limits(input, DEFAULT_MAX_COLLECTION_ELEMENTS)
}
/// Create a new postcard parser with custom safety limits.
pub const fn with_limits(input: &'de [u8], max_collection_elements: u64) -> Self {
Self {
input,
pos: 0,
max_collection_elements,
state_stack: Vec::new(),
peeked: None,
pending_struct_fields: None,
pending_scalar_type: None,
pending_sequence: false,
pending_byte_sequence: false,
pending_remaining_bytes: false,
pending_array: None,
pending_option: false,
pending_enum: None,
pending_opaque: None,
pending_map: false,
pending_dynamic: false,
}
}
/// Read a single byte, advancing position.
fn read_byte(&mut self) -> Result<u8, ParseError> {
if self.pos >= self.input.len() {
return Err(error_from_code(codes::UNEXPECTED_EOF, self.pos));
}
let byte = self.input[self.pos];
self.pos += 1;
Ok(byte)
}
/// Read a varint (LEB128 encoded unsigned integer).
fn read_varint(&mut self) -> Result<u64, ParseError> {
let mut result: u64 = 0;
let mut shift: u32 = 0;
loop {
let byte = self.read_byte()?;
let data = (byte & 0x7F) as u64;
if shift >= 64 {
return Err(error_from_code(codes::VARINT_OVERFLOW, self.pos));
}
result |= data << shift;
shift += 7;
if (byte & 0x80) == 0 {
return Ok(result);
}
}
}
fn validate_collection_count(&self, count: u64) -> Result<(), ParseError> {
if count <= self.max_collection_elements {
return Ok(());
}
Err(ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: format!(
"collection length {} exceeds maximum {}",
count, self.max_collection_elements
)
.into(),
},
))
}
/// Read a signed varint (ZigZag + LEB128).
fn read_signed_varint(&mut self) -> Result<i64, ParseError> {
let unsigned = self.read_varint()?;
// ZigZag decode: (n >> 1) ^ -(n & 1)
let decoded = ((unsigned >> 1) as i64) ^ -((unsigned & 1) as i64);
Ok(decoded)
}
/// Read a varint for u128 (LEB128 encoded, up to 19 bytes).
fn read_varint_u128(&mut self) -> Result<u128, ParseError> {
let mut result: u128 = 0;
let mut shift: u32 = 0;
loop {
let byte = self.read_byte()?;
let data = (byte & 0x7F) as u128;
if shift >= 128 {
return Err(error_from_code(codes::VARINT_OVERFLOW, self.pos));
}
result |= data << shift;
shift += 7;
if (byte & 0x80) == 0 {
return Ok(result);
}
}
}
/// Read a signed varint for i128 (ZigZag + LEB128).
fn read_signed_varint_i128(&mut self) -> Result<i128, ParseError> {
let unsigned = self.read_varint_u128()?;
// ZigZag decode: (n >> 1) ^ -(n & 1)
let decoded = ((unsigned >> 1) as i128) ^ -((unsigned & 1) as i128);
Ok(decoded)
}
/// Read N bytes as a slice.
fn read_bytes(&mut self, len: usize) -> Result<&'de [u8], ParseError> {
let end = self
.pos
.checked_add(len)
.ok_or_else(|| error_from_code(codes::UNEXPECTED_EOF, self.pos))?;
if end > self.input.len() {
return Err(error_from_code(codes::UNEXPECTED_EOF, self.pos));
}
let bytes = &self.input[self.pos..end];
self.pos = end;
Ok(bytes)
}
/// Get the current parser state (top of stack or Ready).
fn current_state(&self) -> &ParserState {
self.state_stack.last().unwrap_or(&ParserState::Ready)
}
/// Generate the next event based on current state.
fn generate_next_event(&mut self) -> Result<ParseEvent<'de>, ParseError> {
// Check if we have a pending option hint
if self.pending_option {
self.pending_option = false;
let discriminant = self.read_byte()?;
match discriminant {
0x00 => {
return Ok(self.event(ParseEventKind::Scalar(ScalarValue::Null)));
}
0x01 => {
// Some(value) - consumed the discriminant. The deserializer will peek to check
// if it's None, see this is not Null, and then call deserialize_into for the value.
// Return a placeholder event (like OrderedField) to signal "not None".
// The deserializer will then call hint + expect for the inner value.
return Ok(self.event(ParseEventKind::OrderedField));
}
_ => {
return Err(ParseError::new(
Span::new(self.pos - 1, 1),
DeserializeErrorKind::InvalidValue {
message: format!("invalid Option discriminant: {}", discriminant)
.into(),
},
));
}
}
}
// Check if we have a pending dynamic value hint (tagged dynamic values)
if self.pending_dynamic {
self.pending_dynamic = false;
return self.parse_dynamic_tag_event();
}
// Check if we have a pending enum hint
if let Some(variants) = self.pending_enum.take() {
let variant_index = self.read_varint()? as usize;
if variant_index >= variants.len() {
return Err(ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: format!(
"enum variant index {} out of range (max {})",
variant_index,
variants.len() - 1
)
.into(),
},
));
}
let variant = &variants[variant_index];
// Push InEnum state to emit StructStart, FieldKey, content, StructEnd sequence
self.state_stack.push(ParserState::InEnum {
variant_name: variant.name.clone(),
variant_kind: variant.kind,
variant_field_count: variant.field_count,
field_key_emitted: false,
wrapper_start_emitted: false,
wrapper_end_emitted: false,
});
return Ok(self.event(ParseEventKind::StructStart(ContainerKind::Object)));
}
// Check if we have a pending opaque scalar hint (format-specific binary encoding)
if let Some(opaque) = self.pending_opaque.take() {
return self.parse_opaque_scalar(opaque);
}
// Check if we have a pending trailing bytes hint (consume rest of input as bytes)
if self.pending_remaining_bytes {
self.pending_remaining_bytes = false;
let bytes = &self.input[self.pos..];
self.pos = self.input.len();
return Ok(
self.event(ParseEventKind::Scalar(ScalarValue::Bytes(Cow::Borrowed(
bytes,
)))),
);
}
// Check if we have a pending scalar type hint
if let Some(hint) = self.pending_scalar_type.take() {
return self.parse_scalar_with_hint(hint);
}
// Check if we have a pending sequence hint (variable-length, reads count from wire)
if self.pending_sequence {
self.pending_sequence = false;
let count = self.read_varint()?;
self.validate_collection_count(count)?;
self.state_stack.push(ParserState::InSequence {
remaining_elements: count,
});
return Ok(self.event(ParseEventKind::SequenceStart(ContainerKind::Array)));
}
// Check if we have a pending byte sequence hint (bulk read for Vec<u8>)
if self.pending_byte_sequence {
self.pending_byte_sequence = false;
let bytes = self.parse_bytes()?;
return Ok(
self.event(ParseEventKind::Scalar(ScalarValue::Bytes(Cow::Borrowed(
bytes,
)))),
);
}
// Check if we have a pending fixed-size array hint (length known from type, no wire prefix)
if let Some(len) = self.pending_array.take() {
self.state_stack.push(ParserState::InSequence {
remaining_elements: len as u64,
});
return Ok(self.event(ParseEventKind::SequenceStart(ContainerKind::Array)));
}
// Check if we have a pending struct hint
if let Some(num_fields) = self.pending_struct_fields.take() {
self.state_stack.push(ParserState::InStruct {
remaining_fields: num_fields,
});
return Ok(self.event(ParseEventKind::StructStart(ContainerKind::Object)));
}
// Check if we have a pending map hint (maps are length-prefixed sequences of key-value pairs)
if self.pending_map {
self.pending_map = false;
let count = self.read_varint()?;
self.validate_collection_count(count)?;
self.state_stack.push(ParserState::InMap {
remaining_entries: count,
});
return Ok(self.event(ParseEventKind::SequenceStart(ContainerKind::Array)));
}
// Check current state
match self.current_state().clone() {
ParserState::Ready => {
// At top level without a hint - error
Err(ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: "postcard parser needs type hints (use hint_scalar_type, hint_struct_fields, or hint_sequence)".into(),
},
))
}
ParserState::InStruct { remaining_fields } => {
if remaining_fields == 0 {
// Struct complete
self.state_stack.pop();
Ok(self.event(ParseEventKind::StructEnd))
} else {
// More fields to go - emit OrderedField and decrement
if let Some(ParserState::InStruct { remaining_fields }) =
self.state_stack.last_mut()
{
*remaining_fields -= 1;
}
Ok(self.event(ParseEventKind::OrderedField))
}
}
ParserState::InSequence { remaining_elements } => {
if remaining_elements == 0 {
// Sequence complete
self.state_stack.pop();
Ok(self.event(ParseEventKind::SequenceEnd))
} else {
// More elements remaining. Return OrderedField as a placeholder to indicate
// "not end yet". The deserializer will then call hint + expect for the next element.
// Decrement the counter after returning the placeholder.
if let Some(ParserState::InSequence { remaining_elements }) =
self.state_stack.last_mut()
{
*remaining_elements -= 1;
}
Ok(self.event(ParseEventKind::OrderedField))
}
}
ParserState::InEnum {
variant_name,
variant_kind,
variant_field_count,
field_key_emitted,
wrapper_start_emitted,
wrapper_end_emitted,
} => {
use facet_core::StructKind;
if !field_key_emitted {
// Step 1: Emit the FieldKey with the variant name
if let Some(ParserState::InEnum {
field_key_emitted, ..
}) = self.state_stack.last_mut()
{
*field_key_emitted = true;
}
Ok(self.event(ParseEventKind::FieldKey(FieldKey::new(
Cow::Owned(variant_name.clone()),
FieldLocationHint::KeyValue,
))))
} else if !wrapper_start_emitted {
// Step 2: After FieldKey, emit wrapper start (if needed)
match variant_kind {
StructKind::Unit => {
// Unit variant - no wrapper, skip directly to StructEnd
self.state_stack.pop();
Ok(self.event(ParseEventKind::StructEnd))
}
StructKind::Tuple | StructKind::TupleStruct => {
// Check if it's a newtype (single-field) or multi-field tuple
if variant_field_count == 1 {
// Newtype variant - no wrapper, content consumed directly
// Mark wrapper as emitted so we skip directly to final StructEnd
if let Some(ParserState::InEnum {
wrapper_start_emitted,
wrapper_end_emitted,
..
}) = self.state_stack.last_mut()
{
*wrapper_start_emitted = true;
*wrapper_end_emitted = true; // Skip wrapper end emission
}
// Recursively call to get the next event (likely a scalar hint response)
self.generate_next_event()
} else {
// Multi-field tuple variant - emit SequenceStart and push InSequence state
// But unlike regular sequences, tuple enum variants don't use OrderedField placeholders
// The deserializer calls deserialize_into directly for each field
// So we DON'T push InSequence - we track manually via wrapper_end_emitted
if let Some(ParserState::InEnum {
wrapper_start_emitted,
..
}) = self.state_stack.last_mut()
{
*wrapper_start_emitted = true;
}
Ok(self.event(ParseEventKind::SequenceStart(ContainerKind::Array)))
}
}
StructKind::Struct => {
// Struct variant - mark wrapper start emitted and push InStruct state
// The InStruct state will emit OrderedField events for each field
// (postcard encodes struct fields in order without names)
if let Some(ParserState::InEnum {
wrapper_start_emitted,
..
}) = self.state_stack.last_mut()
{
*wrapper_start_emitted = true;
}
// Get the field count from the variant
let field_count = if let ParserState::InEnum {
variant_field_count,
..
} = self.current_state()
{
*variant_field_count
} else {
0
};
self.state_stack.push(ParserState::InStruct {
remaining_fields: field_count,
});
Ok(self.event(ParseEventKind::StructStart(ContainerKind::Object)))
}
}
} else if !wrapper_end_emitted {
// Step 3: Emit wrapper end for multi-field variants
match variant_kind {
StructKind::Unit => {
// Already handled above
unreachable!()
}
StructKind::Tuple | StructKind::TupleStruct => {
// For multi-field tuples, emit SequenceEnd
if variant_field_count > 1 {
if let Some(ParserState::InEnum {
wrapper_end_emitted,
..
}) = self.state_stack.last_mut()
{
*wrapper_end_emitted = true;
}
Ok(self.event(ParseEventKind::SequenceEnd))
} else {
// Newtype - already marked wrapper_end_emitted=true, skip to final StructEnd
self.state_stack.pop();
Ok(self.event(ParseEventKind::StructEnd))
}
}
StructKind::Struct => {
// Struct variants use InStruct which already popped, so we're ready for final StructEnd
self.state_stack.pop();
Ok(self.event(ParseEventKind::StructEnd))
}
}
} else {
// Step 4: Emit final outer StructEnd
// This is reached after wrapper end has been emitted
self.state_stack.pop();
Ok(self.event(ParseEventKind::StructEnd))
}
}
ParserState::InMap { remaining_entries } => {
if remaining_entries == 0 {
// Map complete
self.state_stack.pop();
Ok(self.event(ParseEventKind::SequenceEnd))
} else {
// More entries remaining. Return OrderedField as a placeholder to indicate
// "not end yet". The deserializer will call hint + expect for key and value.
// Decrement the counter after returning the placeholder.
if let Some(ParserState::InMap { remaining_entries }) =
self.state_stack.last_mut()
{
*remaining_entries -= 1;
}
Ok(self.event(ParseEventKind::OrderedField))
}
}
ParserState::InDynamicArray { remaining_elements } => {
if remaining_elements == 0 {
self.state_stack.pop();
Ok(self.event(ParseEventKind::SequenceEnd))
} else {
self.parse_dynamic_tag_event()
}
}
ParserState::InDynamicObject {
remaining_entries,
expecting_key,
} => {
if remaining_entries == 0 {
self.state_stack.pop();
Ok(self.event(ParseEventKind::StructEnd))
} else if expecting_key {
let key = self.parse_string()?;
if let Some(ParserState::InDynamicObject { expecting_key, .. }) =
self.state_stack.last_mut()
{
*expecting_key = false;
}
Ok(self.event(ParseEventKind::FieldKey(FieldKey::new(
Cow::Borrowed(key),
FieldLocationHint::KeyValue,
))))
} else {
self.parse_dynamic_tag_event()
}
}
}
}
/// Parse a scalar value with the given type hint.
fn parse_scalar_with_hint(
&mut self,
hint: ScalarTypeHint,
) -> Result<ParseEvent<'de>, ParseError> {
let scalar = match hint {
ScalarTypeHint::Bool => {
let val = self.parse_bool()?;
ScalarValue::Bool(val)
}
ScalarTypeHint::U8 => {
let val = self.parse_u8()?;
ScalarValue::U64(val as u64)
}
ScalarTypeHint::U16 => {
let val = self.parse_u16()?;
ScalarValue::U64(val as u64)
}
ScalarTypeHint::U32 => {
let val = self.parse_u32()?;
ScalarValue::U64(val as u64)
}
ScalarTypeHint::U64 => {
let val = self.parse_u64()?;
ScalarValue::U64(val)
}
ScalarTypeHint::U128 => {
let val = self.parse_u128()?;
ScalarValue::U128(val)
}
ScalarTypeHint::Usize => {
// usize is encoded as varint, decode as u64
let val = self.parse_u64()?;
ScalarValue::U64(val)
}
ScalarTypeHint::I8 => {
let val = self.parse_i8()?;
ScalarValue::I64(val as i64)
}
ScalarTypeHint::I16 => {
let val = self.parse_i16()?;
ScalarValue::I64(val as i64)
}
ScalarTypeHint::I32 => {
let val = self.parse_i32()?;
ScalarValue::I64(val as i64)
}
ScalarTypeHint::I64 => {
let val = self.parse_i64()?;
ScalarValue::I64(val)
}
ScalarTypeHint::I128 => {
let val = self.parse_i128()?;
ScalarValue::I128(val)
}
ScalarTypeHint::Isize => {
// isize is encoded as zigzag varint, decode as i64
let val = self.parse_i64()?;
ScalarValue::I64(val)
}
ScalarTypeHint::F32 => {
let val = self.parse_f32()?;
ScalarValue::F64(val as f64)
}
ScalarTypeHint::F64 => {
let val = self.parse_f64()?;
ScalarValue::F64(val)
}
ScalarTypeHint::String => {
let val = self.parse_string()?;
ScalarValue::Str(Cow::Borrowed(val))
}
ScalarTypeHint::Bytes => {
let val = self.parse_bytes()?;
ScalarValue::Bytes(Cow::Borrowed(val))
}
ScalarTypeHint::Char => {
// Per postcard spec: char is encoded as UTF-8 string (length-prefixed UTF-8 bytes)
let s = self.parse_string()?;
// Validate it's exactly one char
let mut chars = s.chars();
let c = chars.next().ok_or_else(|| {
ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: "empty string for char".into(),
},
)
})?;
if chars.next().is_some() {
return Err(ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: "string contains more than one char".into(),
},
));
}
// Represent as string since ScalarValue doesn't have Char
ScalarValue::Str(Cow::Owned(c.to_string()))
}
};
Ok(self.event(ParseEventKind::Scalar(scalar)))
}
/// Parse an opaque scalar value with format-specific binary encoding.
///
/// This handles types like UUID (16 raw bytes), ULID (16 raw bytes),
/// OrderedFloat (raw float bytes), etc. that have efficient binary
/// representations in postcard.
fn parse_opaque_scalar(
&mut self,
opaque: OpaqueScalarHint,
) -> Result<ParseEvent<'de>, ParseError> {
let scalar = match opaque.type_identifier {
// UUID/ULID: 16 raw bytes (no length prefix)
"Uuid" | "Ulid" => {
let bytes = self.read_fixed_bytes(16)?;
ScalarValue::Bytes(Cow::Borrowed(bytes))
}
// OrderedFloat/NotNan: raw float bytes (size depends on inner type)
// We handle both f32 and f64 variants by checking the shape's inner field
"OrderedFloat" | "NotNan" => {
// Check inner shape to determine f32 vs f64
if opaque.inner_is_f32 {
let val = self.parse_f32()?;
ScalarValue::F64(val as f64)
} else {
// Default to f64
let val = self.parse_f64()?;
ScalarValue::F64(val)
}
}
// Camino Utf8PathBuf/Utf8Path: regular string
"Utf8PathBuf" | "Utf8Path" => {
let val = self.parse_string()?;
ScalarValue::Str(Cow::Borrowed(val))
}
// Chrono types: RFC3339 strings
"DateTime<Utc>"
| "DateTime<Local>"
| "DateTime<FixedOffset>"
| "NaiveDateTime"
| "NaiveDate"
| "NaiveTime" => {
let val = self.parse_string()?;
ScalarValue::Str(Cow::Borrowed(val))
}
// Jiff types: RFC3339/ISO8601 strings
"Timestamp" | "Zoned" | "civil::DateTime" | "civil::Date" | "civil::Time" | "Span"
| "SignedDuration" => {
let val = self.parse_string()?;
ScalarValue::Str(Cow::Borrowed(val))
}
// Time crate types: RFC3339 strings
"UtcDateTime" | "OffsetDateTime" | "PrimitiveDateTime" | "Date" | "Time" => {
let val = self.parse_string()?;
ScalarValue::Str(Cow::Borrowed(val))
}
// Unknown opaque type - shouldn't happen (hint_opaque_scalar returned true)
_ => {
return Err(ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: format!("unsupported opaque type: {}", opaque.type_identifier)
.into(),
},
));
}
};
Ok(self.event(ParseEventKind::Scalar(scalar)))
}
/// Read exactly N bytes from input without length prefix.
fn read_fixed_bytes(&mut self, len: usize) -> Result<&'de [u8], ParseError> {
let end = self
.pos
.checked_add(len)
.ok_or_else(|| error_from_code(codes::UNEXPECTED_EOF, self.pos))?;
if end > self.input.len() {
return Err(error_from_code(codes::UNEXPECTED_EOF, self.pos));
}
let bytes = &self.input[self.pos..end];
self.pos = end;
Ok(bytes)
}
/// Parse a boolean value.
pub fn parse_bool(&mut self) -> Result<bool, ParseError> {
let byte = self.read_byte()?;
match byte {
0 => Ok(false),
1 => Ok(true),
_ => Err(error_from_code(codes::INVALID_BOOL, self.pos - 1)),
}
}
/// Parse an unsigned 8-bit integer.
pub fn parse_u8(&mut self) -> Result<u8, ParseError> {
self.read_byte()
}
/// Parse an unsigned 16-bit integer (varint).
pub fn parse_u16(&mut self) -> Result<u16, ParseError> {
let val = self.read_varint()?;
Ok(val as u16)
}
/// Parse an unsigned 32-bit integer (varint).
pub fn parse_u32(&mut self) -> Result<u32, ParseError> {
let val = self.read_varint()?;
Ok(val as u32)
}
/// Parse an unsigned 64-bit integer (varint).
pub fn parse_u64(&mut self) -> Result<u64, ParseError> {
self.read_varint()
}
/// Parse an unsigned 128-bit integer (varint).
pub fn parse_u128(&mut self) -> Result<u128, ParseError> {
self.read_varint_u128()
}
/// Parse a signed 8-bit integer (single byte, two's complement).
pub fn parse_i8(&mut self) -> Result<i8, ParseError> {
// i8 is encoded as a single byte in two's complement form (not varint)
let byte = self.read_byte()?;
Ok(byte as i8)
}
/// Parse a signed 16-bit integer (zigzag varint).
pub fn parse_i16(&mut self) -> Result<i16, ParseError> {
let val = self.read_signed_varint()?;
Ok(val as i16)
}
/// Parse a signed 32-bit integer (zigzag varint).
pub fn parse_i32(&mut self) -> Result<i32, ParseError> {
let val = self.read_signed_varint()?;
Ok(val as i32)
}
/// Parse a signed 64-bit integer (zigzag varint).
pub fn parse_i64(&mut self) -> Result<i64, ParseError> {
self.read_signed_varint()
}
/// Parse a signed 128-bit integer (zigzag varint).
pub fn parse_i128(&mut self) -> Result<i128, ParseError> {
self.read_signed_varint_i128()
}
/// Parse a 32-bit float (little-endian).
pub fn parse_f32(&mut self) -> Result<f32, ParseError> {
let bytes = self.read_bytes(4)?;
Ok(f32::from_le_bytes(bytes.try_into().unwrap()))
}
/// Parse a 64-bit float (little-endian).
pub fn parse_f64(&mut self) -> Result<f64, ParseError> {
let bytes = self.read_bytes(8)?;
Ok(f64::from_le_bytes(bytes.try_into().unwrap()))
}
/// Parse a string (varint length + UTF-8 bytes).
pub fn parse_string(&mut self) -> Result<&'de str, ParseError> {
let len = self.read_varint()? as usize;
let bytes = self.read_bytes(len)?;
core::str::from_utf8(bytes).map_err(|_| {
let mut context = [0u8; 16];
let context_len = len.min(16);
context[..context_len].copy_from_slice(&bytes[..context_len]);
ParseError::new(
Span::new(self.pos - len, len),
DeserializeErrorKind::InvalidUtf8 {
context,
context_len: context_len as u8,
},
)
})
}
/// Parse bytes (varint length + raw bytes).
pub fn parse_bytes(&mut self) -> Result<&'de [u8], ParseError> {
let len = self.read_varint()? as usize;
self.read_bytes(len)
}
/// Begin parsing a sequence, returning the element count.
pub fn begin_sequence(&mut self) -> Result<u64, ParseError> {
let count = self.read_varint()?;
self.validate_collection_count(count)?;
self.state_stack.push(ParserState::InSequence {
remaining_elements: count,
});
Ok(count)
}
fn parse_dynamic_tag_event(&mut self) -> Result<ParseEvent<'de>, ParseError> {
// If we're inside a dynamic object and expecting a value, advance entry tracking now.
if let Some(ParserState::InDynamicObject {
remaining_entries,
expecting_key,
}) = self.state_stack.last_mut()
&& !*expecting_key
{
*remaining_entries = remaining_entries.saturating_sub(1);
*expecting_key = true;
}
if let Some(ParserState::InDynamicArray { remaining_elements }) =
self.state_stack.last_mut()
{
*remaining_elements = remaining_elements.saturating_sub(1);
}
let tag = self.read_byte()?;
match tag {
0 => Ok(self.event(ParseEventKind::Scalar(ScalarValue::Null))),
1 => self.parse_scalar_with_hint(ScalarTypeHint::Bool),
2 => self.parse_scalar_with_hint(ScalarTypeHint::I64),
3 => self.parse_scalar_with_hint(ScalarTypeHint::U64),
4 => self.parse_scalar_with_hint(ScalarTypeHint::F64),
5 => self.parse_scalar_with_hint(ScalarTypeHint::String),
6 => self.parse_scalar_with_hint(ScalarTypeHint::Bytes),
7 => {
let count = self.read_varint()?;
self.validate_collection_count(count)?;
self.state_stack.push(ParserState::InDynamicArray {
remaining_elements: count,
});
Ok(self.event(ParseEventKind::SequenceStart(ContainerKind::Array)))
}
8 => {
let count = self.read_varint()?;
self.validate_collection_count(count)?;
self.state_stack.push(ParserState::InDynamicObject {
remaining_entries: count,
expecting_key: true,
});
Ok(self.event(ParseEventKind::StructStart(ContainerKind::Object)))
}
9 => self.parse_scalar_with_hint(ScalarTypeHint::String),
_ => Err(ParseError::new(
Span::new(self.pos.saturating_sub(1), 1),
DeserializeErrorKind::InvalidValue {
message: format!("invalid dynamic value tag: {}", tag).into(),
},
)),
}
}
}
impl<'de> PostcardParser<'de> {
/// Create an event with the current span.
#[inline]
fn event(&self, kind: ParseEventKind<'de>) -> ParseEvent<'de> {
ParseEvent::new(kind, Span::new(self.pos, 1))
}
}
impl<'de> FormatParser<'de> for PostcardParser<'de> {
fn next_event(&mut self) -> Result<Option<ParseEvent<'de>>, ParseError> {
// Return peeked event if available
if let Some(event) = self.peeked.take() {
return Ok(Some(event));
}
Ok(Some(self.generate_next_event()?))
}
fn peek_event(&mut self) -> Result<Option<ParseEvent<'de>>, ParseError> {
if self.peeked.is_none() {
self.peeked = Some(self.generate_next_event()?);
}
Ok(self.peeked.clone())
}
fn skip_value(&mut self) -> Result<(), ParseError> {
// For non-self-describing formats, skipping is complex because
// we don't know the type/size of the value.
Err(ParseError::new(
Span::new(self.pos, 1),
DeserializeErrorKind::InvalidValue {
message: "skip_value not supported for postcard (non-self-describing)".into(),
},
))
}
fn current_span(&self) -> Option<Span> {
Some(Span::new(self.pos, 1))
}
fn format_namespace(&self) -> Option<&'static str> {
Some("postcard")
}
fn save(&mut self) -> SavePoint {
// Postcard doesn't support save/restore (non-self-describing format)
// The solver can't work with positional formats anyway
unimplemented!("save/restore not supported for postcard (non-self-describing)")
}
fn restore(&mut self, _save_point: SavePoint) {
// Postcard doesn't support save/restore (non-self-describing format)
unimplemented!("save/restore not supported for postcard (non-self-describing)")
}
fn is_self_describing(&self) -> bool {
false
}
fn hint_struct_fields(&mut self, num_fields: usize) {
self.pending_struct_fields = Some(num_fields);
// Clear any peeked OrderedField placeholder for sequences
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_scalar_type(&mut self, hint: ScalarTypeHint) {
self.pending_scalar_type = Some(hint);
// Clear any peeked OrderedField placeholder for sequences
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_sequence(&mut self) {
self.pending_sequence = true;
// Clear any peeked OrderedField placeholder
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_byte_sequence(&mut self) -> bool {
self.pending_byte_sequence = true;
// Clear any peeked OrderedField placeholder
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
true // Postcard supports bulk byte reading
}
fn hint_remaining_byte_sequence(&mut self) -> bool {
self.pending_remaining_bytes = true;
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
true
}
fn hint_array(&mut self, len: usize) {
self.pending_array = Some(len);
// Clear any peeked OrderedField placeholder
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_option(&mut self) {
self.pending_option = true;
// Clear any peeked OrderedField placeholder
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_enum(&mut self, variants: &[EnumVariantHint]) {
// Store variant metadata, converting to owned strings to avoid lifetime issues.
let metas: Vec<VariantMeta> = variants
.iter()
.map(|v| VariantMeta {
name: v.name.to_string(),
kind: v.kind,
field_count: v.field_count,
})
.collect();
self.pending_enum = Some(metas);
// Clear any peeked OrderedField placeholder for sequences
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_map(&mut self) {
self.pending_map = true;
// Clear any peeked OrderedField placeholder
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
fn hint_dynamic_value(&mut self) {
// Clear any peeked OrderedField placeholder (it's just a "not done yet" signal)
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
// If something else is peeked, don't override it
if self.peeked.is_some() {
return;
}
self.pending_dynamic = true;
}
fn hint_opaque_scalar(
&mut self,
type_identifier: &'static str,
shape: &'static facet_core::Shape,
) -> bool {
// Check if we handle this type specially in postcard
let handled = matches!(
type_identifier,
// UUID/ULID: 16 raw bytes
"Uuid" | "Ulid"
// OrderedFloat/NotNan: raw float bytes (size determined by inner type)
| "OrderedFloat" | "NotNan"
// Camino paths: strings
| "Utf8PathBuf" | "Utf8Path"
// Chrono types: RFC3339 strings
| "DateTime<Utc>" | "DateTime<Local>" | "DateTime<FixedOffset>"
| "NaiveDateTime" | "NaiveDate" | "NaiveTime"
// Jiff types: RFC3339/ISO8601 strings
| "Timestamp" | "Zoned" | "civil::DateTime" | "civil::Date" | "civil::Time"
| "Span" | "SignedDuration"
// Time crate types: RFC3339 strings
| "UtcDateTime" | "OffsetDateTime" | "PrimitiveDateTime" | "Date" | "Time"
);
if handled {
// Check inner shape for OrderedFloat/NotNan to determine f32 vs f64
let inner_is_f32 = shape
.inner
.map(|inner| inner.is_type::<f32>())
.unwrap_or(false);
self.pending_opaque = Some(OpaqueScalarHint {
type_identifier,
inner_is_f32,
});
// Clear any peeked OrderedField placeholder
if self
.peeked
.as_ref()
.is_some_and(|e| matches!(e.kind, ParseEventKind::OrderedField))
{
self.peeked = None;
}
}
handled
}
}