qubit-json 0.12.3

Resource-aware infrastructure for lenient and strict JSON processing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Transaction-aware Serde compound serializers.

use std::cell::Cell;
use std::cell::RefCell;
use std::collections::BTreeSet;

use qubit_budget::ResourceQuantity;
use qubit_budget::json::JsonContainerKind;
use qubit_budget::json::JsonMeasurement;
use serde::Serialize;
use serde::ser::SerializeMap;
use serde::ser::SerializeSeq;
use serde::ser::SerializeStruct;
use serde::ser::SerializeStructVariant;
use serde::ser::SerializeTuple;
use serde::ser::SerializeTupleStruct;
use serde::ser::SerializeTupleVariant;
use serde_json::Value;

use super::CompoundState;
use super::JsonValueEncodeContext;
use super::JsonValueMapKeySerializer;
use super::JsonValueSerializer;
use super::RawValueConsumer;
use super::private_text_serializer::PrivateTextSerializer;
use crate::encode::JsonSerializationError;
use crate::encode::JsonSerializationErrorKind;
use crate::encode::JsonSerializerStateError;
use crate::internal::JsonPrivateProtocolKind;
use crate::internal::JsonPrivateProtocolState;
use crate::value::SafeJsonValue;
use crate::value::internal::SafeValueBuilder;

/// Shared staged transaction and sticky first-failure state for one projection.
/// Compounds borrow this context and never commit it themselves.
///
/// # Type Parameters
///
/// * `'context` - Lifetime of the shared context borrow.
/// * `'transaction` - Lifetime of the staged resource transaction.
/// * `'budget` - Lifetime of the configured resource budget.
/// * `R` - Resource quantity tracked by the budget.
/// * `Q` - Quantity representation used for resource accounting.
type ContextCell<'context, 'transaction, 'budget, R, Q> =
    &'context RefCell<JsonValueEncodeContext<'transaction, 'budget, R, Q>>;

/// Accumulates one Serde compound with guarded children and sticky failures.
///
/// Children remain wrapped in `SafeJsonValue` until the compound ends
/// successfully; a failed child or measurement prevents the partial tree from
/// being returned. Private raw-value and number payloads use dedicated protocol
/// states. A generic map event sequence is treated as a map and cannot reveal
/// that it originated from serde_json's private `Number` representation.
///
/// # Type Parameters
///
/// * `'context` - Lifetime of the borrowed shared encoding context.
/// * `'transaction` - Lifetime of its staged resource transaction.
/// * `'budget` - Lifetime of its configured resource budget.
/// * `R` - Resource quantity tracked by the budget; it must be cloneable.
/// * `Q` - Quantity representation required by resource accounting.
pub(in crate::value::json_value_encoder) struct JsonValueCompound<
    'context,
    'transaction,
    'budget,
    R,
    Q,
> where
    Q: ResourceQuantity,
{
    /// Shared staged transaction and first-failure state; this compound does
    /// not own the right to commit the transaction.
    context: ContextCell<'context, 'transaction, 'budget, R, Q>,
    /// Active compound shape and its guarded, not-yet-committed children.
    state: CompoundState,
    /// First failure is retained even if the serializer ignores a child error.
    failure: Cell<Option<JsonSerializationError>>,
}

impl<'context, 'transaction, 'budget, R, Q> JsonValueCompound<'context, 'transaction, 'budget, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Creates an accumulator for an already-admitted sequence container.
    ///
    /// # Parameters
    ///
    /// * `context` - Shared staged accounting and sticky failure state.
    /// * `depth` - Depth of this container; child values use `depth + 1`.
    /// * `kind` - Container identity used for sequence-item admission.
    /// * `capacity` - Initial allocation hint, bounded by the caller before
    ///   entry.
    ///
    /// # Returns
    ///
    /// An empty guarded accumulator. Construction does not admit the container
    /// or commit the transaction. Current callers cap the allocation hint at
    /// 1024; the hint is not a limit on the accepted collection size or
    /// total memory.
    pub(in crate::value::json_value_encoder) fn sequence(
        context: ContextCell<'context, 'transaction, 'budget, R, Q>,
        depth: usize,
        kind: JsonContainerKind,
        capacity: usize,
    ) -> Self {
        Self {
            context,
            state: CompoundState::Sequence {
                values: SafeValueBuilder::array_with_capacity(capacity),
                depth,
                count: 0,
                kind,
            },
            failure: Cell::new(None),
        }
    }

    /// Creates an accumulator for an already-admitted map container.
    ///
    /// # Parameters
    ///
    /// * `context` - Shared staged accounting and sticky failure state.
    /// * `depth` - Depth of this container; values use `depth + 1`.
    /// * `capacity` - Initial allocation hint, bounded by the caller before
    ///   entry.
    ///
    /// # Returns
    ///
    /// An empty guarded accumulator. Construction does not admit the container
    /// or commit the transaction. Current callers cap the allocation hint at
    /// 1024; the hint is not a limit on the accepted collection size or
    /// total memory.
    pub(in crate::value::json_value_encoder) fn map(
        context: ContextCell<'context, 'transaction, 'budget, R, Q>,
        depth: usize,
        capacity: usize,
    ) -> Self {
        Self {
            context,
            state: CompoundState::Map {
                values: Vec::with_capacity(capacity),
                keys: BTreeSet::new(),
                next_key: None,
                depth,
                count: 0,
            },
            failure: Cell::new(None),
        }
    }

    /// Creates an accumulator for an already-admitted tuple enum variant.
    ///
    /// # Parameters
    ///
    /// * `context` - Shared staged accounting and sticky failure state.
    /// * `variant` - Name of the variant used as the outer object's key.
    /// * `depth` - Depth of the outer object; the inner sequence is at `depth +
    ///   1`.
    /// * `capacity` - Initial allocation hint, bounded by the caller before
    ///   entry.
    ///
    /// # Returns
    ///
    /// An empty guarded accumulator. The caller has already admitted the outer
    /// one-entry object, its variant key, and the inner sequence. Children use
    /// `depth + 2`. Capacity is only a caller-bounded initial allocation hint.
    /// Creating the accumulator does not commit the staged transaction.
    pub(in crate::value::json_value_encoder) fn tuple_variant(
        context: ContextCell<'context, 'transaction, 'budget, R, Q>,
        variant: &str,
        depth: usize,
        capacity: usize,
    ) -> Self {
        Self {
            context,
            state: CompoundState::TupleVariant {
                variant: variant.to_owned(),
                values: SafeValueBuilder::array_with_capacity(capacity),
                depth,
                count: 0,
            },
            failure: Cell::new(None),
        }
    }

    /// Creates an accumulator for an already-admitted struct enum variant.
    ///
    /// # Parameters
    ///
    /// * `context` - Shared staged accounting and sticky failure state.
    /// * `variant` - Name of the variant used as the outer object's key.
    /// * `depth` - Depth of the outer object; the inner map is at `depth + 1`.
    /// * `capacity` - Initial allocation hint, bounded by the caller before
    ///   entry.
    ///
    /// # Returns
    ///
    /// An empty guarded accumulator. The caller has already admitted the outer
    /// one-entry object, its variant key, and the inner map. Fields use `depth
    /// + 2`. Capacity is only a caller-bounded initial allocation hint.
    ///
    /// Creating the accumulator does not commit the staged transaction.
    pub(in crate::value::json_value_encoder) fn struct_variant(
        context: ContextCell<'context, 'transaction, 'budget, R, Q>,
        variant: &str,
        depth: usize,
        capacity: usize,
    ) -> Self {
        Self {
            context,
            state: CompoundState::StructVariant {
                variant: variant.to_owned(),
                values: Vec::with_capacity(capacity),
                keys: BTreeSet::new(),
                depth,
                count: 0,
            },
            failure: Cell::new(None),
        }
    }

    /// Creates an accumulator for a recognized private protocol.
    ///
    /// `kind` and `state` must describe the same protocol; the state must be
    /// Pending after the protocol field count has been validated. This only
    /// creates the payload accumulator. It does not parse the payload, admit
    /// the resulting tree, or commit the shared transaction.
    ///
    /// # Parameters
    ///
    /// * `context` - Shared staged transaction and sticky failure state.
    /// * `depth` - Depth at which the materialized private value is admitted.
    /// * `kind` - Recognized private protocol kind.
    /// * `state` - Pending protocol state for that kind.
    ///
    /// # Returns
    ///
    /// An empty accumulator awaiting the protocol payload.
    pub(in crate::value::json_value_encoder) fn private(
        context: ContextCell<'context, 'transaction, 'budget, R, Q>,
        depth: usize,
        kind: JsonPrivateProtocolKind,
        state: JsonPrivateProtocolState,
    ) -> Self {
        let state = match kind {
            JsonPrivateProtocolKind::RawValue => CompoundState::RawValue {
                text: None,
                state,
                depth,
            },
            JsonPrivateProtocolKind::Number => CompoundState::Number {
                text: None,
                state,
                depth,
            },
        };
        Self {
            context,
            state,
            failure: Cell::new(None),
        }
    }

    /// Retains this compound's first serialization failure and records it in
    /// the shared context.
    ///
    /// # Parameters
    ///
    /// * `error` - Serialization error to retain if no earlier failure exists.
    ///
    /// # Returns
    ///
    /// The first error retained by this compound.
    fn fail(&self, error: JsonSerializationError) -> JsonSerializationError {
        if self.failure.get().is_none() {
            self.failure.set(Some(error));
        }
        let _ = self.context.borrow_mut().record_serialization_error(error);
        self.failure.get().unwrap_or(error)
    }

    /// Records a compound-finalization error in the shared context before
    /// returning it. The retained failure remains observable even if an
    /// enclosing `Serialize` implementation ignores this result and later
    /// reports success. The shared context preserves first-failure precedence.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Successful finalization value carried through unchanged.
    ///
    /// # Parameters
    ///
    /// * `context` - Shared serialization context that retains failures.
    /// * `result` - Result of finalizing the compound.
    ///
    /// # Returns
    ///
    /// The finalization value on success, or the retained serialization error.
    ///
    /// # Errors
    ///
    /// Returns the first serialization error recorded in the shared context.
    fn keep_end_error<T>(
        context: ContextCell<'_, '_, '_, R, Q>,
        result: Result<T, JsonSerializationError>,
    ) -> Result<T, JsonSerializationError> {
        result.map_err(|error| context.borrow_mut().record_serialization_error(error))
    }

    /// Stops this compound when either its local or shared context has failed.
    ///
    /// # Returns
    ///
    /// `Ok(())` while both failure states are clear; otherwise, the first
    /// retained serialization error.
    ///
    /// # Errors
    ///
    /// Returns the first failure recorded by this compound or its shared
    /// encoding context.
    fn check_failure(&self) -> Result<(), JsonSerializationError> {
        if let Some(error) = self.failure.get() {
            return Err(error);
        }
        let failed = self.context.borrow().has_failure();
        if failed {
            let error = self.context.borrow().ser_error();
            return Err(error);
        }
        Ok(())
    }

    /// Admits one resource measurement and makes any rejection sticky.
    ///
    /// # Parameters
    ///
    /// * `measurement` - Resource usage to admit to the shared transaction.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the measurement is admitted.
    ///
    /// # Errors
    ///
    /// Returns and retains the resource-budget error when admission fails.
    fn admit(&mut self, measurement: JsonMeasurement) -> Result<(), JsonSerializationError> {
        let result = { self.context.borrow_mut().admit(measurement) };
        result.map_err(|error| self.fail(error))
    }

    /// Serializes one child and checks shared failure state even after an `Ok`
    /// result. A custom `Serialize` implementation may swallow a nested
    /// serializer error; checking the context prevents that error from being
    /// converted into success. Child errors are retained through this
    /// compound's failure path.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value being encoded as a child.
    ///
    /// # Parameters
    ///
    /// * `value` - Child value to serialize.
    /// * `depth` - Nesting depth at which to serialize the child.
    ///
    /// # Returns
    ///
    /// The protected child value when serialization succeeds.
    ///
    /// # Errors
    ///
    /// Returns the first retained serialization failure.
    fn serialize_child<T>(
        &mut self,
        value: &T,
        depth: usize,
    ) -> Result<SafeJsonValue, JsonSerializationError>
    where
        T: Serialize + ?Sized,
    {
        match value.serialize(JsonValueSerializer::new(self.context, depth)) {
            Ok(value) => {
                self.check_failure()?;
                Ok(value)
            }
            Err(error) => Err(self.fail(error)),
        }
    }

    /// Checks a prospective item count against the shared container limits.
    ///
    /// # Parameters
    ///
    /// * `kind` - Container category whose limit applies.
    /// * `count` - Prospective number of items after the next insertion.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the count is within the configured container limit.
    ///
    /// # Errors
    ///
    /// Returns and retains the serialization error when the count is rejected.
    fn check_count(
        &mut self,
        kind: JsonContainerKind,
        count: usize,
    ) -> Result<(), JsonSerializationError> {
        let result = { self.context.borrow_mut().check_container_count(kind, count) };
        result.map_err(|error| self.fail(error))
    }

    /// Collects one field of the recognized private protocol and retains
    /// failures in the shared context.
    ///
    /// The private text serializer checks the UTF-8 source-byte length against
    /// the configured temporary payload limit before appending text. Complete
    /// JSON syntax and number materialization are checked when the compound is
    /// finished; successful collection alone does not validate the payload.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value whose text representation is collected.
    ///
    /// # Parameters
    ///
    /// * `kind` - Private protocol whose payload is being collected.
    /// * `key` - Protocol field name presented by the serializer.
    /// * `value` - Value serialized by the restricted text serializer.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the private payload field is collected and the protocol
    /// advances to its complete state.
    ///
    /// # Errors
    ///
    /// Returns and retains an error for an invalid protocol state, rejected
    /// payload value, or temporary text-limit violation.
    fn set_private_field<T>(
        &mut self,
        kind: JsonPrivateProtocolKind,
        key: &'static str,
        value: &T,
    ) -> Result<(), JsonSerializationError>
    where
        T: Serialize + ?Sized,
    {
        let context = self.context;
        let mut check_text_bytes = |length| context.borrow_mut().check_private_text_bytes(length);
        let result = match &mut self.state {
            CompoundState::RawValue { text, state, .. }
            | CompoundState::Number { text, state, .. } => {
                set_private_payload(text, state, kind, key, value, &mut check_text_bytes)
            }
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        };
        result.map_err(|error| self.fail(error))
    }

    /// Releases a completed guarded array as a protected JSON value.
    ///
    /// # Parameters
    ///
    /// * `values` - Completed children retained by the guarded builder.
    ///
    /// # Returns
    ///
    /// The guarded JSON array built from the supplied children.
    #[must_use]
    #[inline]
    fn finish_sequence(values: SafeValueBuilder) -> SafeJsonValue {
        SafeJsonValue::new(values.finish())
    }

    /// Releases completed guarded entries as a protected JSON object.
    ///
    /// # Parameters
    ///
    /// * `values` - Completed keys and guarded values to insert into the
    ///   object.
    ///
    /// # Returns
    ///
    /// The guarded JSON object built from the supplied entries.
    #[must_use]
    fn finish_object(values: Vec<(String, SafeJsonValue)>) -> SafeJsonValue {
        let mut object = SafeValueBuilder::object();
        for (key, value) in values {
            object.insert(key, value);
        }
        SafeJsonValue::new(object.finish())
    }

    /// Materializes a completed private payload and records any failure.
    ///
    /// # Returns
    ///
    /// The guarded JSON value produced by the payload.
    ///
    /// # Errors
    ///
    /// Returns and records an invalid protocol, malformed payload, or resource
    /// admission error.
    fn finish_private(self) -> Result<SafeJsonValue, JsonSerializationError> {
        let context = self.context;
        self.finish_private_inner()
            .map_err(|error| context.borrow_mut().record_serialization_error(error))
    }

    /// Validates the complete private protocol before parsing/admitting its
    /// payload.
    ///
    /// # Returns
    ///
    /// The guarded JSON value after protocol validation and materialization.
    ///
    /// # Errors
    ///
    /// Returns an invalid-state error for an incomplete or mismatched protocol,
    /// or the payload parsing/admission error.
    fn finish_private_inner(self) -> Result<SafeJsonValue, JsonSerializationError> {
        match &self.state {
            CompoundState::RawValue {
                text: Some(text),
                state,
                depth,
            } => {
                if state.finish().is_err() {
                    return Err(private_invalid_state(JsonPrivateProtocolKind::RawValue));
                }
                decode_raw_value(text, self.context, *depth)
            }
            CompoundState::RawValue { state, .. } => {
                let _ = state.finish();
                Err(private_invalid_state(JsonPrivateProtocolKind::RawValue))
            }
            CompoundState::Number {
                text: Some(text),
                state,
                depth,
            } => {
                if state.finish().is_err() {
                    return Err(private_invalid_state(JsonPrivateProtocolKind::Number));
                }
                match crate::internal::StrictJsonNumber::parse(text) {
                    Ok(number) => {
                        let bytes = crate::value::internal::json_number_lexeme_length(&number);
                        self.context.borrow_mut().admit(JsonMeasurement::Number {
                            depth: *depth,
                            bytes,
                        })?;
                        Ok(SafeJsonValue::new(Value::Number(number)))
                    }
                    Err(error) => Err(self.context.borrow_mut().record_serialization_error(error)),
                }
            }
            CompoundState::Number { state, .. } => {
                let _ = state.finish();
                Err(private_invalid_state(JsonPrivateProtocolKind::Number))
            }
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        }
    }
}

/// Advances the private protocol through begin, payload collection, and
/// complete. Only text payloads are accepted. The supplied callback checks
/// UTF-8 source bytes against the temporary text limit before appending them.
/// This helper does not parse the complete JSON payload or record a sticky
/// shared error; its caller owns first-error recording.
///
/// # Type Parameters
///
/// * `T` - Serde value expected to produce one text payload.
///
/// # Parameters
///
/// * `text` - Destination for the collected payload text.
/// * `state` - Protocol lifecycle state advanced by this payload.
/// * `kind` - Protocol whose payload is being collected.
/// * `key` - Field name supplied by the serializer.
/// * `value` - Serde value expected to serialize as text.
/// * `check_text_bytes` - Callback enforcing the temporary text byte limit.
///
/// # Returns
///
/// `Ok(())` after exactly one valid text payload completes the protocol.
///
/// # Errors
///
/// Returns an invalid-state error for an unexpected field or non-text value,
/// or the serializer/text-limit error produced while collecting the payload.
fn set_private_payload<T>(
    text: &mut Option<String>,
    state: &mut JsonPrivateProtocolState,
    kind: JsonPrivateProtocolKind,
    key: &'static str,
    value: &T,
    check_text_bytes: &mut dyn FnMut(usize) -> Result<(), JsonSerializationError>,
) -> Result<(), JsonSerializationError>
where
    T: Serialize + ?Sized,
{
    if state.begin(key).is_err() {
        return Err(private_invalid_state(kind));
    }
    let value = match value.serialize(PrivateTextSerializer {
        kind,
        check_text_bytes,
    }) {
        Ok(Value::String(value)) => value,
        Ok(_) => {
            state.fail();
            return Err(private_invalid_state(kind));
        }
        Err(error) => {
            state.fail();
            return Err(error);
        }
    };
    *text = Some(value);
    if state.complete().is_err() {
        return Err(private_invalid_state(kind));
    }
    Ok(())
}

impl<R, Q> SerializeSeq for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON value produced when this sequence is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid elements or compound state.
    type Error = JsonSerializationError;

    /// Serializes one child after count, depth, and resource checks succeed.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value being encoded as an element.
    ///
    /// # Parameters
    ///
    /// * `value` - Element value to serialize.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the element is admitted and appended.
    ///
    /// # Errors
    ///
    /// Returns the retained failure if the compound already failed, its count
    /// or depth is invalid, or child serialization fails.
    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        self.check_failure()?;
        let (depth, count, kind) = match &self.state {
            CompoundState::Sequence {
                depth, count, kind, ..
            } => (*depth, *count, *kind),
            _ => return Err(self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))),
        };
        let next_count = count.checked_add(1).ok_or_else(|| {
            self.fail(JsonSerializationError::new(
                JsonSerializationErrorKind::CollectionLengthOverflow {
                    kind: crate::encode::JsonCollectionKind::Array,
                },
            ))
        })?;
        self.check_count(kind, next_count)?;
        let child_depth = depth.checked_add(1).ok_or_else(|| {
            self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))
        })?;
        let child = self.serialize_child(value, child_depth)?;
        let CompoundState::Sequence { values, count, .. } = &mut self.state else {
            unreachable!()
        };
        values.push(child);
        *count = next_count;
        Ok(())
    }

    /// Completes the compound only when no earlier failure or incomplete
    /// protocol remains.
    ///
    /// # Returns
    ///
    /// The guarded JSON array after all elements have been accepted.
    ///
    /// # Errors
    ///
    /// Returns the retained serialization error or an error for an unexpected
    /// compound state.
    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.check_failure()?;
        let context = self.context;
        let result = match self.state {
            CompoundState::Sequence { values, .. } => Ok(Self::finish_sequence(values)),
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        };
        Self::keep_end_error(context, result)
    }
}

impl<R, Q> SerializeTuple for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON value produced when this tuple is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid elements or compound state.
    type Error = JsonSerializationError;
    /// Serializes one positional child using the sequence implementation.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value being encoded as a tuple element.
    ///
    /// # Parameters
    ///
    /// * `value` - Tuple element to serialize.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the tuple element is appended.
    ///
    /// # Errors
    ///
    /// Returns the sequence serializer's count, depth, or child-serialization
    /// error.
    #[inline]
    fn serialize_element<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        SerializeSeq::serialize_element(self, value)
    }
    /// Completes the tuple and returns its guarded value.
    ///
    /// # Returns
    ///
    /// The guarded JSON array representing the tuple.
    ///
    /// # Errors
    ///
    /// Returns the sequence serializer's retained failure or invalid-state
    /// error.
    #[inline]
    fn end(self) -> Result<Self::Ok, Self::Error> {
        SerializeSeq::end(self)
    }
}

impl<R, Q> SerializeTupleStruct for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON value produced when this tuple struct is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid fields or compound state.
    type Error = JsonSerializationError;
    /// Serializes one tuple-struct field using the sequence implementation.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value being encoded as a tuple-struct field.
    ///
    /// # Parameters
    ///
    /// * `value` - Tuple-struct field value to serialize.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the field is appended.
    ///
    /// # Errors
    ///
    /// Returns the sequence serializer's count, depth, or child-serialization
    /// error.
    #[inline]
    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        SerializeSeq::serialize_element(self, value)
    }
    /// Completes the tuple struct and returns its guarded value.
    ///
    /// # Returns
    ///
    /// The guarded JSON array representing the tuple struct.
    ///
    /// # Errors
    ///
    /// Returns the sequence serializer's retained failure or invalid-state
    /// error.
    #[inline]
    fn end(self) -> Result<Self::Ok, Self::Error> {
        SerializeSeq::end(self)
    }
}

impl<R, Q> SerializeTupleVariant for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON value produced when this tuple variant is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid elements or compound state.
    type Error = JsonSerializationError;
    /// Serializes one enum-variant element after count and depth checks.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value being encoded as a variant element.
    ///
    /// # Parameters
    ///
    /// * `value` - Enum-variant element to serialize.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the element is admitted and appended.
    ///
    /// # Errors
    ///
    /// Returns the retained failure if the compound failed, count or depth
    /// validation fails, or child serialization fails.
    fn serialize_field<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        self.check_failure()?;
        let (depth, count) = match &self.state {
            CompoundState::TupleVariant { depth, count, .. } => (*depth, *count),
            _ => return Err(self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))),
        };
        let next = count.checked_add(1).ok_or_else(|| {
            self.fail(JsonSerializationError::new(
                JsonSerializationErrorKind::CollectionLengthOverflow {
                    kind: crate::encode::JsonCollectionKind::Array,
                },
            ))
        })?;
        self.check_count(JsonContainerKind::Sequence, next)?;
        let child_depth = depth.checked_add(2).ok_or_else(|| {
            self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))
        })?;
        let child = self.serialize_child(value, child_depth)?;
        let CompoundState::TupleVariant { values, count, .. } = &mut self.state else {
            unreachable!()
        };
        values.push(child);
        *count = next;
        Ok(())
    }
    /// Completes the variant object and returns its guarded value.
    ///
    /// # Returns
    ///
    /// The guarded one-entry JSON object containing the tuple variant.
    ///
    /// # Errors
    ///
    /// Returns a retained serialization error or an invalid compound-state
    /// error.
    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.check_failure()?;
        let context = self.context;
        let result = match self.state {
            CompoundState::TupleVariant {
                variant, values, ..
            } => {
                let inner = Self::finish_sequence(values);
                let mut object = SafeValueBuilder::object();
                object.insert(variant, inner);
                Ok(SafeJsonValue::new(object.finish()))
            }
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        };
        Self::keep_end_error(context, result)
    }
}

impl<R, Q> SerializeMap for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON object produced when this map is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid entries or compound state.
    type Error = JsonSerializationError;
    /// Serializes and checks the prospective key before the corresponding value
    /// is admitted.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value serialized as a map key.
    ///
    /// # Parameters
    ///
    /// * `key` - Key to serialize and retain for the next value.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the key passes validation and is retained for its value.
    ///
    /// # Errors
    ///
    /// Returns an error for a pending prior key, invalid key representation,
    /// count or budget rejection, or prior compound failure.
    fn serialize_key<T>(&mut self, key: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        self.check_failure()?;
        let (count, pending) = match &self.state {
            CompoundState::Map {
                count, next_key, ..
            } => (*count, next_key.is_some()),
            _ => return Err(self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))),
        };
        if pending {
            return Err(self.fail(invalid_state(
                JsonSerializerStateError::MapKeyAlreadyPending,
            )));
        }
        let next = count.checked_add(1).ok_or_else(|| {
            self.fail(JsonSerializationError::new(
                JsonSerializationErrorKind::CollectionLengthOverflow {
                    kind: crate::encode::JsonCollectionKind::Object,
                },
            ))
        })?;
        self.check_count(JsonContainerKind::Map, next)?;
        let key = match key.serialize(JsonValueMapKeySerializer::new(self.context)) {
            Ok(key) => key,
            Err(error) => return Err(self.fail(error)),
        };
        self.admit(JsonMeasurement::Key { bytes: key.len() })?;
        let CompoundState::Map {
            next_key, count, ..
        } = &mut self.state
        else {
            unreachable!()
        };
        *next_key = Some(key);
        *count = next;
        Ok(())
    }
    /// Adds a value only after its pending key and guarded child succeed.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value serialized as the pending map value.
    ///
    /// # Parameters
    ///
    /// * `value` - Value corresponding to the pending key.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the value is serialized and paired with its key.
    ///
    /// # Errors
    ///
    /// Returns an error when no key is pending, the key is duplicated, child
    /// serialization fails, or the compound has already failed.
    fn serialize_value<T>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        self.check_failure()?;
        let depth = match &self.state {
            CompoundState::Map {
                keys,
                next_key,
                depth,
                ..
            } => {
                let Some(key) = next_key.as_ref() else {
                    return Err(
                        self.fail(invalid_state(JsonSerializerStateError::MapValueWithoutKey))
                    );
                };
                if keys.contains(key.as_str()) {
                    return Err(self.fail(JsonSerializationError::new(
                        JsonSerializationErrorKind::DuplicateObjectKey,
                    )));
                }
                *depth
            }
            _ => return Err(self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))),
        };
        if let CompoundState::Map { keys, next_key, .. } = &mut self.state {
            keys.insert(
                next_key
                    .as_ref()
                    .expect("pending map key was checked")
                    .clone(),
            );
        }
        let child_depth = depth.checked_add(1).ok_or_else(|| {
            self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))
        })?;
        let key = match &mut self.state {
            CompoundState::Map { next_key, .. } => {
                next_key.take().expect("pending map key was checked")
            }
            _ => unreachable!(),
        };
        let child = self.serialize_child(value, child_depth)?;
        let CompoundState::Map { values, .. } = &mut self.state else {
            unreachable!()
        };
        values.push((key, child));
        Ok(())
    }
    /// Completes the map, rejecting a key that has no corresponding value.
    ///
    /// # Returns
    ///
    /// The guarded JSON object after all key-value pairs are complete.
    ///
    /// # Errors
    ///
    /// Returns an error for a pending key, unexpected state, or earlier
    /// retained serialization failure.
    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.check_failure()?;
        let context = self.context;
        let result = match self.state {
            CompoundState::Map {
                values,
                next_key: None,
                ..
            } => Ok(Self::finish_object(values)),
            CompoundState::Map {
                next_key: Some(_), ..
            } => Err(invalid_state(
                JsonSerializerStateError::MapEndedWithPendingKey,
            )),
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        };
        Self::keep_end_error(context, result)
    }
}

impl<R, Q> SerializeStruct for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON object produced when this struct is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid fields or compound state.
    type Error = JsonSerializationError;
    /// Accepts omitted fields for ordinary structs, but not private protocols.
    ///
    /// # Parameters
    ///
    /// * `key` - Name of the struct field omitted by the serializer.
    ///
    /// # Returns
    ///
    /// `Ok(())` for ordinary structs, where omission requires no state change.
    ///
    /// # Errors
    ///
    /// Returns and retains an error when omission violates a private payload
    /// protocol.
    fn skip_field(&mut self, _: &'static str) -> Result<(), Self::Error> {
        match &self.state {
            CompoundState::RawValue { .. } => {
                Err(self.fail(private_invalid_state(JsonPrivateProtocolKind::RawValue)))
            }
            CompoundState::Number { .. } => {
                Err(self.fail(private_invalid_state(JsonPrivateProtocolKind::Number)))
            }
            _ => Ok(()),
        }
    }
    /// Serializes a unique struct field or advances a private payload protocol.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value encoded for the field or private payload.
    ///
    /// # Parameters
    ///
    /// * `key` - Static field name supplied by Serde.
    /// * `value` - Field or protocol payload value to serialize.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the field is appended or a private payload completes.
    ///
    /// # Errors
    ///
    /// Returns an error for duplicate fields, invalid protocol state, count or
    /// budget rejection, or child/payload serialization failure.
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        self.check_failure()?;
        match &self.state {
            CompoundState::Map {
                keys, depth, count, ..
            } => {
                let (depth, count, duplicate) = (*depth, *count, keys.contains(key));
                if duplicate {
                    return Err(self.fail(JsonSerializationError::new(
                        JsonSerializationErrorKind::DuplicateObjectKey,
                    )));
                }
                let next = count.checked_add(1).ok_or_else(|| {
                    self.fail(JsonSerializationError::new(
                        JsonSerializationErrorKind::CollectionLengthOverflow {
                            kind: crate::encode::JsonCollectionKind::Object,
                        },
                    ))
                })?;
                self.check_count(JsonContainerKind::Map, next)?;
                self.admit(JsonMeasurement::Key { bytes: key.len() })?;
                if let CompoundState::Map { keys, .. } = &mut self.state {
                    keys.insert(key.to_owned());
                }
                let child_depth = depth.checked_add(1).ok_or_else(|| {
                    self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))
                })?;
                let child = self.serialize_child(value, child_depth)?;
                let CompoundState::Map { values, count, .. } = &mut self.state else {
                    unreachable!()
                };
                values.push((key.to_owned(), child));
                *count = next;
                Ok(())
            }
            CompoundState::RawValue { .. } => {
                self.set_private_field(JsonPrivateProtocolKind::RawValue, key, value)
            }
            CompoundState::Number { .. } => {
                self.set_private_field(JsonPrivateProtocolKind::Number, key, value)
            }
            _ => Err(self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))),
        }
    }
    /// Completes the struct or validates and materializes its private payload.
    ///
    /// # Returns
    ///
    /// The guarded JSON object or materialized private payload.
    ///
    /// # Errors
    ///
    /// Returns an error for incomplete or invalid state, malformed private
    /// payload, resource rejection, or an earlier retained failure.
    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.check_failure()?;
        if matches!(
            &self.state,
            CompoundState::RawValue { .. } | CompoundState::Number { .. }
        ) {
            return self.finish_private();
        }
        let context = self.context;
        let result = match self.state {
            CompoundState::Map {
                values,
                next_key: None,
                ..
            } => Ok(Self::finish_object(values)),
            CompoundState::Map {
                next_key: Some(_), ..
            } => Err(invalid_state(
                JsonSerializerStateError::MapEndedWithPendingKey,
            )),
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        };
        Self::keep_end_error(context, result)
    }
}

impl<R, Q> SerializeStructVariant for JsonValueCompound<'_, '_, '_, R, Q>
where
    R: Clone,
    Q: ResourceQuantity,
{
    /// Guarded JSON object produced when this struct variant is completed.
    type Ok = SafeJsonValue;
    /// Serialization error retained for invalid fields or compound state.
    type Error = JsonSerializationError;
    /// Serializes a unique field in the enum variant's inner object.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Serde value encoded for the variant field.
    ///
    /// # Parameters
    ///
    /// * `key` - Static field name supplied by Serde.
    /// * `value` - Variant field value to serialize.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the unique variant field is admitted and appended.
    ///
    /// # Errors
    ///
    /// Returns an error for duplicate fields, invalid state, count or budget
    /// rejection, or child serialization failure.
    fn serialize_field<T>(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize + ?Sized,
    {
        self.check_failure()?;
        let (depth, count, duplicate) = match &self.state {
            CompoundState::StructVariant {
                keys, depth, count, ..
            } => (*depth, *count, keys.contains(key)),
            _ => return Err(self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))),
        };
        if duplicate {
            return Err(self.fail(JsonSerializationError::new(
                JsonSerializationErrorKind::DuplicateObjectKey,
            )));
        }
        let next = count.checked_add(1).ok_or_else(|| {
            self.fail(JsonSerializationError::new(
                JsonSerializationErrorKind::CollectionLengthOverflow {
                    kind: crate::encode::JsonCollectionKind::Object,
                },
            ))
        })?;
        self.check_count(JsonContainerKind::Map, next)?;
        self.admit(JsonMeasurement::Key { bytes: key.len() })?;
        if let CompoundState::StructVariant { keys, .. } = &mut self.state {
            keys.insert(key.to_owned());
        }
        let child_depth = depth.checked_add(2).ok_or_else(|| {
            self.fail(invalid_state(JsonSerializerStateError::UnexpectedCompound))
        })?;
        let child = self.serialize_child(value, child_depth)?;
        let CompoundState::StructVariant { values, count, .. } = &mut self.state else {
            unreachable!()
        };
        values.push((key.to_owned(), child));
        *count = next;
        Ok(())
    }
    /// Completes the enum variant object and returns its guarded value.
    ///
    /// # Returns
    ///
    /// The guarded one-entry JSON object containing the struct variant.
    ///
    /// # Errors
    ///
    /// Returns a retained serialization error or an invalid compound-state
    /// error.
    fn end(self) -> Result<Self::Ok, Self::Error> {
        self.check_failure()?;
        let context = self.context;
        let result = match self.state {
            CompoundState::StructVariant {
                variant, values, ..
            } => {
                let inner = Self::finish_object(values);
                let mut outer = SafeValueBuilder::object();
                outer.insert(variant, inner);
                Ok(SafeJsonValue::new(outer.finish()))
            }
            _ => Err(invalid_state(JsonSerializerStateError::UnexpectedCompound)),
        };
        Self::keep_end_error(context, result)
    }
}

/// Wraps a serializer lifecycle violation in the serialization error type.
///
/// # Parameters
///
/// * `reason` - State-machine violation to preserve in the error.
///
/// # Returns
///
/// A serialization error identifying the invalid serializer state.
fn invalid_state(reason: JsonSerializerStateError) -> JsonSerializationError {
    JsonSerializationError::new(JsonSerializationErrorKind::InvalidSerializerState { reason })
}

/// Creates the private-protocol lifecycle error for the supplied protocol.
///
/// # Parameters
///
/// * `kind` - Private protocol whose lifecycle was violated.
///
/// # Returns
///
/// A serialization error identifying the violated private protocol state.
pub(super) fn private_invalid_state(kind: JsonPrivateProtocolKind) -> JsonSerializationError {
    invalid_state(kind.invalid_state())
}

/// Materializes one RawValue payload through the guarded lexical builder.
///
/// Syntax, numeric range, duplicate-key, and budget failures retain their
/// existing mapping: budget failures preserve their budget error, while other
/// invalid payloads become `InvalidRawValue`.
///
/// # Type Parameters
///
/// * `R` - Cloneable resource quantity tracked by the staged transaction.
/// * `Q` - Quantity representation used by the resource budget.
///
/// # Parameters
///
/// * `text` - Complete raw JSON text collected from the private protocol.
/// * `context` - Shared staged transaction and sticky error state.
/// * `depth` - Nesting depth at which the resulting value is admitted.
///
/// # Returns
///
/// The guarded JSON value parsed from the complete raw JSON text.
///
/// # Errors
///
/// Returns a budget error when scanning exceeds configured limits; syntax,
/// number, duplicate-key, and guarded-builder failures are reported as an
/// invalid raw value.
fn decode_raw_value<R, Q>(
    text: &str,
    context: ContextCell<'_, '_, '_, R, Q>,
    depth: usize,
) -> Result<SafeJsonValue, JsonSerializationError>
where
    R: Clone,
    Q: ResourceQuantity,
{
    let mut builder = crate::value::internal::LexicalJsonValueBuilder::new(
        crate::lexical::JsonNumberModel::Integer64,
    );
    let has_limits = context.borrow().has_limits();
    let scan = {
        let mut ctx = context.borrow_mut();
        let transaction = ctx.transaction();
        crate::lexical::JsonLexicalScanner::at_depth(transaction, depth, has_limits)
            .with_number_model(crate::lexical::JsonNumberModel::Integer64)
            .scan_with_consumer(
                text.as_bytes(),
                &mut RawValueConsumer {
                    builder: &mut builder,
                },
            )
    };
    match scan {
        Ok(()) => {
            match builder.finish_guarded() {
                Ok(value) => Ok(value),
                Err(_) => Err(context.borrow_mut().record_serialization_error(
                    JsonSerializationError::new(JsonSerializationErrorKind::InvalidRawValue),
                )),
            }
        }
        Err(crate::lexical::JsonLexicalScanError::Lexical(
            crate::lexical::JsonLexicalError::Budget(error),
        )) => Err(context.borrow_mut().record_budget_failure(error)),
        Err(_) => {
            Err(context
                .borrow_mut()
                .record_serialization_error(JsonSerializationError::new(
                    JsonSerializationErrorKind::InvalidRawValue,
                )))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use qubit_budget::json::JsonContainerKind;
    use qubit_budget::json::JsonResource;
    use qubit_budget::json::JsonValueBudget;
    use qubit_budget::json::JsonValueLimits;
    use serde::ser::SerializeMap;
    use serde::ser::SerializeSeq;
    use serde::ser::SerializeStruct;
    use serde::ser::SerializeStructVariant;
    use serde::ser::SerializeTupleVariant;

    use super::CompoundState;
    use super::JsonValueCompound;
    use super::JsonValueEncodeContext;
    use crate::encode::JsonCollectionKind;
    use crate::encode::JsonSerializationErrorKind;
    use crate::encode::JsonSerializerStateError;

    #[test]
    fn test_compound_count_and_depth_overflow_are_sticky() {
        // Seed only the counters: reaching these guards must not require an
        // allocation or traversal proportional to usize::MAX.
        for path in [
            "sequence",
            "tuple-variant",
            "map",
            "struct",
            "struct-variant",
        ] {
            for overflow_count in [true, false] {
                let mut budget =
                    JsonValueBudget::new(JsonValueLimits::<JsonResource, usize>::new());
                let mut transaction = budget.transaction();
                let context = RefCell::new(JsonValueEncodeContext::new(&mut transaction, None));
                let mut compound = match path {
                    "sequence" => {
                        JsonValueCompound::sequence(&context, 1, JsonContainerKind::Sequence, 0)
                    }
                    "tuple-variant" => JsonValueCompound::tuple_variant(&context, "Tuple", 1, 0),
                    "struct-variant" => JsonValueCompound::struct_variant(&context, "Struct", 1, 0),
                    _ => JsonValueCompound::map(&context, 1, 0),
                };
                match &mut compound.state {
                    CompoundState::Sequence { count, depth, .. }
                    | CompoundState::TupleVariant { count, depth, .. }
                    | CompoundState::Map { count, depth, .. }
                    | CompoundState::StructVariant { count, depth, .. } => {
                        if overflow_count {
                            *count = usize::MAX;
                        } else {
                            *depth = usize::MAX;
                        }
                    }
                    _ => unreachable!("fixture is an ordinary compound"),
                }
                let result = match path {
                    "sequence" => SerializeSeq::serialize_element(&mut compound, &true),
                    "tuple-variant" => SerializeTupleVariant::serialize_field(&mut compound, &true),
                    "struct" => SerializeStruct::serialize_field(&mut compound, "key", &true),
                    "struct-variant" => {
                        SerializeStructVariant::serialize_field(&mut compound, "key", &true)
                    }
                    _ if overflow_count => SerializeMap::serialize_key(&mut compound, "key"),
                    _ => {
                        SerializeMap::serialize_key(&mut compound, "key")
                            .expect("key does not increase depth");
                        SerializeMap::serialize_value(&mut compound, &true)
                    }
                };
                let error = result.expect_err("overflow must be rejected before adding a child");
                let expected = if overflow_count {
                    JsonSerializationErrorKind::CollectionLengthOverflow {
                        kind: if matches!(path, "sequence" | "tuple-variant") {
                            JsonCollectionKind::Array
                        } else {
                            JsonCollectionKind::Object
                        },
                    }
                } else {
                    JsonSerializationErrorKind::InvalidSerializerState {
                        reason: JsonSerializerStateError::UnexpectedCompound,
                    }
                };
                assert_eq!(
                    error.kind(),
                    expected,
                    "{path}, count overflow: {overflow_count}"
                );
                assert_eq!(
                    compound.check_failure().expect_err("failure is sticky"),
                    error
                );
                assert_eq!(context.borrow().ser_error(), error);
            }
        }
    }
}