rustbinary 0.1.10

A bounded nextjson binary codec with adaptive frames, zero-allocation paths, schema evolution, and authenticated pipelines
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
//! Parser budgets and schema estimates for the self-describing profile.
//! Runtime limits cover bytes, cumulative reads, global tokens, collection size
//! and container depth. Depth alone does not bound branching.
//!
//! Allocation estimates exclude spare capacity, transient buffers and allocator
//! overhead. Custom traits are trusted code; their allocations and computation
//! are not constrained here. Hard memory ceilings require external enforcement.

use core::fmt;
use core::marker::PhantomData;

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;

use crate::config::{Config, DEFAULT_COLLECTION_LIMIT, DEFAULT_SIZE_LIMIT};
use crate::decoder;
use crate::tags::MAX_DEPTH;

/// Default structural admission weight per token. This is a policy heuristic,
/// not a bound on Rust collections, allocator overhead or custom trait code.
pub const ELEMENT_STRUCTURE_BYTES: u64 = 64;

/// Schema estimates used for admission policy. Implementations are trusted
/// application metadata, including when generated by a derive. No constant
/// constrains allocations or computation in a custom `NsonDeserialize`.
pub trait DecodeBounded {
    /// Estimated maximum encoded bytes, or `usize::MAX` if unknown.
    const MAX_INPUT: usize;
    /// Estimated owned storage; excludes allocator overhead and spare capacity.
    const MAX_ALLOC: usize;
    /// Maximum schema container depth, or `usize::MAX` if unknown.
    const MAX_DEPTH: usize;
    /// Estimated byte-read work, excluding speculative decoding and custom code.
    const MAX_WORK: usize;
    /// Estimated largest element storage, or `usize::MAX` if unknown.
    const MAX_STRUCTURAL_ELEMENT: usize = usize::MAX;

    /// Whether the schema supplies a finite allocation estimate.
    const STATICALLY_BOUNDED: bool = Self::MAX_ALLOC != usize::MAX;
}

/// Runtime budget for one bounded decode.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Budget {
    max_input: u64,
    max_alloc: u64,
    max_depth: usize,
    max_work: u64,
    element_structure_bytes: u64,
    max_values: u64,
    max_collection: u64,
}

impl Budget {
    /// Creates a budget with explicit limits.
    ///
    /// The per-element structural knob defaults to [`ELEMENT_STRUCTURE_BYTES`].
    pub const fn new(max_input: u64, max_alloc: u64, max_depth: usize, max_work: u64) -> Self {
        Self {
            max_input,
            max_alloc,
            max_depth,
            max_work,
            element_structure_bytes: ELEMENT_STRUCTURE_BYTES,
            max_values: DEFAULT_COLLECTION_LIMIT,
            max_collection: DEFAULT_COLLECTION_LIMIT,
        }
    }

    /// Derives a budget from `T`'s cost algebra.
    ///
    /// Finite constants become tight limits; `usize::MAX` constants fall back
    /// to the crate-wide defaults ([`DEFAULT_SIZE_LIMIT`] for input/allocation/
    /// work, `MAX_DEPTH` for depth). These defaults do not certify actual heap or CPU usage.
    pub const fn from_type<T: DecodeBounded>() -> Self {
        Self {
            max_input: const_or_default(T::MAX_INPUT, DEFAULT_SIZE_LIMIT),
            max_alloc: const_or_default(T::MAX_ALLOC, DEFAULT_SIZE_LIMIT),
            max_depth: if T::MAX_DEPTH == usize::MAX {
                MAX_DEPTH
            } else {
                T::MAX_DEPTH
            },
            max_work: const_or_default(T::MAX_WORK, DEFAULT_SIZE_LIMIT),
            element_structure_bytes: ELEMENT_STRUCTURE_BYTES,
            max_values: DEFAULT_COLLECTION_LIMIT,
            max_collection: DEFAULT_COLLECTION_LIMIT,
        }
    }

    /// Derives a budget from an existing [`Config`]'s resource policy.
    pub const fn from_config(config: Config) -> Self {
        let max_input = match config.limit() {
            Some(limit) => limit,
            None => DEFAULT_SIZE_LIMIT,
        };
        let max_alloc = match config.value_limit() {
            Some(limit) => limit.saturating_mul(ELEMENT_STRUCTURE_BYTES),
            None => DEFAULT_COLLECTION_LIMIT.saturating_mul(ELEMENT_STRUCTURE_BYTES),
        };
        Self {
            max_input,
            max_alloc,
            max_depth: config.depth_limit(),
            max_work: match config.decode_work_limit() {
                Some(n) => n,
                None => max_input,
            },
            element_structure_bytes: ELEMENT_STRUCTURE_BYTES,
            max_collection: match config.collection_limit() {
                Some(n) => n,
                None => DEFAULT_COLLECTION_LIMIT,
            },
            max_values: match config.value_limit() {
                Some(n) => n,
                None => DEFAULT_COLLECTION_LIMIT,
            },
        }
    }

    /// Sets the maximum input bytes a decode may consume.
    pub const fn with_max_input(mut self, limit: u64) -> Self {
        self.max_input = limit;
        self
    }

    /// Caps the reported allocation estimate used for admission, not actual heap use.
    pub const fn with_max_alloc(mut self, limit: u64) -> Self {
        self.max_alloc = limit;
        self
    }

    /// Sets the maximum parser nesting depth.
    ///
    /// Clamped to the crate-wide `MAX_DEPTH` at decode time.
    pub const fn with_max_depth(mut self, limit: usize) -> Self {
        self.max_depth = limit;
        self
    }

    /// Sets the cumulative parser byte-read limit, including retries.
    pub const fn with_max_work(mut self, limit: u64) -> Self {
        self.max_work = limit;
        self
    }

    /// Sets the per-token structural admission weight in bytes.
    ///
    /// Used only when the decoded type does not declare its own
    /// [`DecodeBounded::MAX_STRUCTURAL_ELEMENT`] (manual trait
    /// implementations). See the module documentation for the exact contract;
    /// the default is [`ELEMENT_STRUCTURE_BYTES`] (64).
    pub const fn with_element_structure_bytes(mut self, bytes: u64) -> Self {
        self.element_structure_bytes = bytes;
        self
    }

    /// Sets the global token-visit limit, including keys and speculative retries.
    pub const fn with_max_values(mut self, limit: u64) -> Self {
        self.max_values = limit;
        self
    }

    /// Sets the per-container entry limit, independently of global visits.
    pub const fn with_max_collection(mut self, limit: u64) -> Self {
        self.max_collection = limit;
        self
    }

    /// Returns the per-container entry limit.
    pub const fn max_collection(self) -> u64 {
        self.max_collection
    }

    /// Returns the global token-visit limit.
    pub const fn max_values(self) -> u64 {
        self.max_values
    }

    /// Returns the maximum input bytes.
    pub const fn max_input(self) -> u64 {
        self.max_input
    }

    /// Returns the allocation-estimate admission budget (not a heap limit).
    pub const fn max_alloc(self) -> u64 {
        self.max_alloc
    }

    /// Returns the maximum nesting depth.
    pub const fn max_depth(self) -> usize {
        self.max_depth
    }

    /// Returns the cumulative parser byte-read limit.
    pub const fn max_work(self) -> u64 {
        self.max_work
    }

    /// Returns the per-element structural admission weight.
    pub const fn element_structure_bytes(self) -> u64 {
        self.element_structure_bytes
    }
}

impl Default for Budget {
    fn default() -> Self {
        Self {
            max_input: DEFAULT_SIZE_LIMIT,
            max_alloc: DEFAULT_COLLECTION_LIMIT.saturating_mul(ELEMENT_STRUCTURE_BYTES),
            max_depth: MAX_DEPTH,
            max_work: DEFAULT_SIZE_LIMIT,
            element_structure_bytes: ELEMENT_STRUCTURE_BYTES,
            max_values: DEFAULT_COLLECTION_LIMIT,
            max_collection: DEFAULT_COLLECTION_LIMIT,
        }
    }
}

/// Parser measurements and explicitly unverified schema estimates.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ResourceUse {
    /// Exact input bytes consumed by the decode.
    pub read: u64,
    /// Unverified allocation estimate. Does not cover capacity growth,
    /// transient allocations, allocator metadata or custom trait behavior.
    /// Successful bounded decoding keeps this estimate within `max_alloc`.
    pub alloc_estimate: u64,
    /// Runtime parser depth ceiling, including unknown fields.
    pub depth_bound: usize,
    /// Cumulative bytes read by the parser, including speculative rereads.
    /// This is not a CPU-time bound on deserialization or custom code.
    pub work_read: u64,
    /// Tokens read across all branches, keys, skipped fields and retries.
    pub values: u64,
}

/// A value decoded under a budget, together with its resource-use evidence.
#[derive(Debug)]
pub struct Decoded<T> {
    /// The decoded value.
    pub value: T,
    /// Resource-use evidence for this decode.
    pub use_: ResourceUse,
}

impl<T> Decoded<T> {
    /// Maps the value, retaining the original decode metrics. Allocations and
    /// work performed by `f` are not included in those metrics.
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Decoded<U> {
        Decoded {
            value: f(self.value),
            use_: self.use_,
        }
    }
}

/// Which budget dimension was exceeded.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[non_exhaustive]
pub enum BudgetExceeded {
    /// The input exceeded the byte budget before (or during) decoding.
    Input {
        /// The configured limit.
        limit: u64,
    },
    /// The allocation admission estimate exceeds the budget.
    Alloc {
        /// The configured allocation budget.
        limit: u64,
    },
    /// The type's nesting depth exceeds the configured depth budget.
    Depth {
        /// The configured limit.
        limit: usize,
    },
    /// The global token-visit budget was exceeded.
    Values {
        /// Configured token limit.
        limit: u64,
    },
    /// The cumulative byte-read budget was exceeded.
    Work {
        /// The configured limit.
        limit: u64,
    },
}

/// Errors from [`decode_bounded`].
#[derive(Debug)]
#[non_exhaustive]
pub enum DecodeError {
    /// The budget was exceeded; see [`BudgetExceeded`] for the dimension.
    Budget(BudgetExceeded),
    /// The underlying codec rejected the input (malformed, size/collection
    /// limit, trailing bytes, ...).
    Codec(crate::Error),
}

impl fmt::Display for BudgetExceeded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Input { limit } => write!(f, "bounded decode: input exceeds {limit} bytes"),
            Self::Alloc { limit } => {
                write!(
                    f,
                    "bounded decode: schema allocation estimate exceeds admission budget {limit}"
                )
            }
            Self::Depth { limit } => write!(f, "bounded decode: depth exceeds {limit}"),
            Self::Values { limit } => write!(f, "bounded decode: tokens exceed {limit}"),
            Self::Work { limit } => write!(f, "bounded decode: work exceeds {limit} units"),
        }
    }
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Budget(budget) => budget.fmt(f),
            Self::Codec(error) => write!(f, "bounded decode failed: {error}"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for DecodeError {}

impl From<crate::Error> for DecodeError {
    fn from(error: crate::Error) -> Self {
        Self::Codec(error)
    }
}

/// Selects `value` when finite, otherwise `default`.
#[doc(hidden)]
pub const fn const_or_default(value: usize, default: u64) -> u64 {
    if value == usize::MAX {
        default
    } else {
        value as u64
    }
}

/// Enforced limits derived from a [`Budget`] and a type's static-boundedness.
#[doc(hidden)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EnforcedLimits {
    /// Input byte limit (the tighter of `max_input` and `max_work`).
    pub byte_limit: u64,
    /// Per-collection element cap.
    pub collection_limit: u64,
    /// Global token-visit cap, including all branches and retries.
    pub value_limit: u64,
    /// Nesting-depth cap (clamped to `MAX_DEPTH`).
    pub depth_limit: usize,
}

/// Converts schema weights into parser admission limits. For dynamic types,
/// the caller first subtracts input storage from `max_alloc`. The remaining
/// budget bounds weighted token visits, not real allocations.
#[doc(hidden)]
pub const fn derive_enforced_limits(
    budget: Budget,
    statically_bounded: bool,
    per_element_ceiling: u64,
) -> EnforcedLimits {
    let byte_limit = if budget.max_input < budget.max_work {
        budget.max_input
    } else {
        budget.max_work
    };
    let collection_limit = if statically_bounded {
        byte_limit
    } else {
        // A zero weight disables this heuristic; explicit parser limits remain.
        match budget.max_alloc.checked_div(per_element_ceiling) {
            Some(raw) if raw < byte_limit => raw,
            _ => byte_limit,
        }
    };
    let value_limit = if collection_limit < budget.max_values {
        collection_limit
    } else {
        budget.max_values
    };
    let collection_limit = if collection_limit < budget.max_collection {
        collection_limit
    } else {
        budget.max_collection
    };
    let depth_limit = if budget.max_depth < MAX_DEPTH {
        budget.max_depth
    } else {
        MAX_DEPTH
    };
    EnforcedLimits {
        byte_limit,
        collection_limit,
        value_limit,
        depth_limit,
    }
}

/// Decodes a value with strict trailing-byte rejection and parser budgets.
///
/// Byte reads, global token visits and depth are checked at runtime. Heap
/// usage and custom trait computation are not bounded by this function.
pub fn decode_bounded<'de, T>(input: &'de [u8], budget: Budget) -> Result<Decoded<T>, DecodeError>
where
    T: DecodeBounded + nextjson::NsonDeserialize<'de>,
{
    let input_len = u64::try_from(input.len()).map_err(|_| {
        DecodeError::Budget(BudgetExceeded::Input {
            limit: budget.max_input,
        })
    })?;
    if input_len > budget.max_input {
        return Err(DecodeError::Budget(BudgetExceeded::Input {
            limit: budget.max_input,
        }));
    }
    // Reject budgets that cannot accommodate the schema admission estimates.
    // These constants are not measured allocation or work.
    if T::MAX_DEPTH != usize::MAX && T::MAX_DEPTH > budget.max_depth {
        return Err(DecodeError::Budget(BudgetExceeded::Depth {
            limit: budget.max_depth,
        }));
    }
    if T::MAX_WORK != usize::MAX && T::MAX_WORK as u64 > budget.max_work {
        return Err(DecodeError::Budget(BudgetExceeded::Work {
            limit: budget.max_work,
        }));
    }
    if T::MAX_ALLOC != usize::MAX && T::MAX_ALLOC as u64 > budget.max_alloc {
        return Err(DecodeError::Budget(BudgetExceeded::Alloc {
            limit: budget.max_alloc,
        }));
    }
    // A schema weight is an admission heuristic, never an allocation proof.
    let structural = if T::MAX_STRUCTURAL_ELEMENT == usize::MAX {
        budget.element_structure_bytes()
    } else {
        T::MAX_STRUCTURAL_ELEMENT as u64
    };
    let has_static_estimate = T::MAX_ALLOC != usize::MAX;
    let structural_budget = if has_static_estimate {
        budget
    } else {
        let remaining = budget
            .max_alloc
            .checked_sub(input_len)
            .ok_or(DecodeError::Budget(BudgetExceeded::Alloc {
                limit: budget.max_alloc,
            }))?;
        budget.with_max_alloc(remaining)
    };
    let limits = derive_enforced_limits(
        structural_budget,
        T::STATICALLY_BOUNDED && has_static_estimate,
        structural,
    );
    let config = Config::standard()
        .with_limit(limits.byte_limit)
        .with_collection_limit(limits.collection_limit)
        .with_depth_limit(limits.depth_limit)
        .with_value_limit(limits.value_limit)
        .with_decode_work_limit(budget.max_work);
    let (value, consumed, work_read, values) = decoder::from_slice_with_resources(input, config)
        .map_err(|error| match error {
            crate::Error::WorkLimit { limit } => {
                DecodeError::Budget(BudgetExceeded::Work { limit })
            }
            crate::Error::ValueLimit { limit } => {
                DecodeError::Budget(BudgetExceeded::Values { limit })
            }
            crate::Error::DepthLimit { limit } => {
                DecodeError::Budget(BudgetExceeded::Depth { limit })
            }
            other => DecodeError::Codec(other),
        })?;
    if consumed != input.len() {
        return Err(DecodeError::Codec(crate::Error::TrailingBytes {
            remaining: input.len() - consumed,
        }));
    }
    let read = consumed as u64;
    let depth_bound = limits.depth_limit;
    let alloc_estimate = if T::MAX_ALLOC != usize::MAX {
        T::MAX_ALLOC as u64
    } else {
        read.saturating_add(values.saturating_mul(structural))
    };
    Ok(Decoded {
        value,
        use_: ResourceUse {
            read,
            alloc_estimate,
            depth_bound,
            work_read,
            values,
        },
    })
}

macro_rules! primitive {
    ($($ty:ty => $input:expr),+ $(,)?) => {$(
        impl DecodeBounded for $ty {
            const MAX_INPUT: usize = $input;
            const MAX_ALLOC: usize = 0;
            const MAX_DEPTH: usize = 0;
            const MAX_WORK: usize = $input + 1;
            const MAX_STRUCTURAL_ELEMENT: usize = 0;
        }
    )+};
}

// Encoded widths mirror `StaticSize`: tag + full-width payload under the
// variable profile, or tag + marker-varint for 64/128-bit integers.
primitive! {
    () => 1, bool => 1, char => 13,
    i8 => 9, u8 => 9,
    i16 => 9, u16 => 9,
    i32 => 9, u32 => 9,
    i64 => 10, u64 => 10,
    i128 => 18, u128 => 18,
    f32 => 5, f64 => 9
}

impl<T: DecodeBounded> DecodeBounded for Option<T> {
    const MAX_INPUT: usize = max(1, T::MAX_INPUT);
    const MAX_ALLOC: usize = T::MAX_ALLOC;
    const MAX_DEPTH: usize = T::MAX_DEPTH;
    const MAX_WORK: usize = saturating_add(1, T::MAX_WORK);
    const MAX_STRUCTURAL_ELEMENT: usize = T::MAX_STRUCTURAL_ELEMENT;
}

impl<T: DecodeBounded, const N: usize> DecodeBounded for [T; N] {
    // Array tag + elements + terminator.
    const MAX_INPUT: usize = saturating_add(saturating_mul(T::MAX_INPUT, N), 2);
    const MAX_ALLOC: usize = saturating_mul(T::MAX_ALLOC, N);
    const MAX_DEPTH: usize = depth_plus_one(T::MAX_DEPTH);
    const MAX_WORK: usize = saturating_add(saturating_mul(T::MAX_WORK, N), 2);
    const MAX_STRUCTURAL_ELEMENT: usize = T::MAX_STRUCTURAL_ELEMENT;
}

impl<T> DecodeBounded for PhantomData<T> {
    const MAX_INPUT: usize = 1;
    const MAX_ALLOC: usize = 0;
    const MAX_DEPTH: usize = 0;
    const MAX_WORK: usize = 2;
    const MAX_STRUCTURAL_ELEMENT: usize = 0;
}

/// Compile-time helper: maximum over a list of `usize` constants.
macro_rules! max_depth {
    ($a:expr) => {
        $a
    };
    ($a:expr, $($rest:expr),+) => {
        crate::bounded::max($a, max_depth!($($rest),+))
    };
}

macro_rules! tuple_bounded {
    ($($name:ident),+) => {
        impl<$($name: DecodeBounded),+> DecodeBounded for ($($name,)+) {
            const MAX_INPUT: usize = 2usize $(.saturating_add($name::MAX_INPUT))+;
            const MAX_ALLOC: usize = 0usize $(.saturating_add($name::MAX_ALLOC))+;
            const MAX_DEPTH: usize = depth_plus_one(max_depth!($($name::MAX_DEPTH),+));
            const MAX_WORK: usize = 2usize $(.saturating_add($name::MAX_WORK))+;
            const MAX_STRUCTURAL_ELEMENT: usize = max_depth!($($name::MAX_STRUCTURAL_ELEMENT),+);
        }
    };
}

tuple_bounded!(A);
tuple_bounded!(A, B);
tuple_bounded!(A, B, C);
tuple_bounded!(A, B, C, D);
tuple_bounded!(A, B, C, D, E);
tuple_bounded!(A, B, C, D, E, F);
tuple_bounded!(A, B, C, D, E, F, G);
tuple_bounded!(A, B, C, D, E, F, G, H);

impl DecodeBounded for String {
    const MAX_INPUT: usize = usize::MAX;
    const MAX_ALLOC: usize = usize::MAX;
    const MAX_DEPTH: usize = 0;
    const MAX_WORK: usize = usize::MAX;
    // The String heap is data-bound (every byte is read from the wire).
    const MAX_STRUCTURAL_ELEMENT: usize = 0;
}

impl<T: DecodeBounded> DecodeBounded for Vec<T> {
    const MAX_INPUT: usize = usize::MAX;
    const MAX_ALLOC: usize = usize::MAX;
    const MAX_DEPTH: usize = depth_plus_one(T::MAX_DEPTH);
    const MAX_WORK: usize = usize::MAX;
    const MAX_STRUCTURAL_ELEMENT: usize = max(core::mem::size_of::<T>(), T::MAX_STRUCTURAL_ELEMENT);
}

impl<T: DecodeBounded> DecodeBounded for Box<T> {
    const MAX_INPUT: usize = T::MAX_INPUT;
    const MAX_ALLOC: usize = saturating_add(T::MAX_ALLOC, core::mem::size_of::<T>());
    const MAX_DEPTH: usize = T::MAX_DEPTH;
    const MAX_WORK: usize = T::MAX_WORK;
    // Requested storage only; allocator overhead is excluded.
    const MAX_STRUCTURAL_ELEMENT: usize = max(core::mem::size_of::<T>(), T::MAX_STRUCTURAL_ELEMENT);
}

/// Borrowed UTF-8 text decodes into the input frame and allocates nothing.
impl DecodeBounded for &str {
    const MAX_INPUT: usize = usize::MAX;
    const MAX_ALLOC: usize = 0;
    const MAX_DEPTH: usize = 0;
    const MAX_WORK: usize = usize::MAX;
    const MAX_STRUCTURAL_ELEMENT: usize = 0;
}

/// Borrowed byte slices decode into the input frame and allocate nothing.
impl<T> DecodeBounded for &[T] {
    const MAX_INPUT: usize = usize::MAX;
    const MAX_ALLOC: usize = 0;
    const MAX_DEPTH: usize = 1;
    const MAX_WORK: usize = usize::MAX;
    const MAX_STRUCTURAL_ELEMENT: usize = 0;
}

/// Compile-time helper: saturating addition.
#[doc(hidden)]
pub const fn saturating_add(left: usize, right: usize) -> usize {
    left.saturating_add(right)
}

/// Compile-time helper: saturating multiplication.
#[doc(hidden)]
pub const fn saturating_mul(left: usize, right: usize) -> usize {
    left.saturating_mul(right)
}

/// Compile-time helper: maximum of two `usize` values.
#[doc(hidden)]
pub const fn max(left: usize, right: usize) -> usize {
    if left > right {
        left
    } else {
        right
    }
}

/// Compile-time helper: one container level, preserving `usize::MAX`.
#[doc(hidden)]
pub const fn depth_plus_one(depth: usize) -> usize {
    if depth == usize::MAX {
        usize::MAX
    } else {
        depth + 1
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Error;
    use alloc::borrow::ToOwned;
    use alloc::format;
    use alloc::vec;

    #[derive(
        Debug, PartialEq, nextjson::NsonSerialize, nextjson::NsonDeserialize, crate::DecodeBounded,
    )]
    struct StaticRecord {
        id: u64,
        enabled: bool,
        coordinates: [i32; 2],
    }

    #[derive(
        Debug, PartialEq, nextjson::NsonSerialize, nextjson::NsonDeserialize, crate::DecodeBounded,
    )]
    struct DynamicRecord {
        id: u64,
        name: String,
        tags: Vec<u8>,
    }

    fn static_value() -> StaticRecord {
        StaticRecord {
            id: 7,
            enabled: true,
            coordinates: [1, -2],
        }
    }

    #[test]
    fn static_type_decode_reports_exact_bounds() {
        let value = static_value();
        let bytes = crate::options().serialize(&value).unwrap();
        let budget = Budget::from_type::<StaticRecord>();
        // The derived algebra is an exact upper bound on the wire size.
        assert_eq!(budget.max_input(), StaticRecord::MAX_INPUT as u64);
        assert!(budget.max_input() >= bytes.len() as u64);
        assert_eq!(budget.max_alloc(), 0);
        // Object level + the array field level.
        assert_eq!(budget.max_depth(), 2);
        let decoded = decode_bounded::<StaticRecord>(&bytes, budget).unwrap();
        assert_eq!(decoded.value, value);
        assert_eq!(decoded.use_.read as usize, bytes.len());
        assert_eq!(decoded.use_.alloc_estimate, 0);
        assert_eq!(decoded.use_.depth_bound, 2);
        assert_eq!(decoded.use_.work_read, bytes.len() as u64);
        // The type reports itself as statically bounded.
        const _: () = assert!(StaticRecord::STATICALLY_BOUNDED);
        const _: () = assert!(!DynamicRecord::STATICALLY_BOUNDED);
    }

    #[test]
    fn static_type_input_budget_is_enforced() {
        let value = static_value();
        let bytes = crate::options().serialize(&value).unwrap();
        // A budget too small for the type is rejected before decoding.
        let budget = Budget::from_type::<StaticRecord>().with_max_input(3);
        assert!(matches!(
            decode_bounded::<StaticRecord>(&bytes, budget),
            Err(DecodeError::Budget(BudgetExceeded::Input { limit: 3 }))
        ));
        // A budget whose depth cannot accommodate the type is rejected.
        let budget = Budget::from_type::<StaticRecord>().with_max_depth(0);
        assert!(matches!(
            decode_bounded::<StaticRecord>(&bytes, budget),
            Err(DecodeError::Budget(BudgetExceeded::Depth { limit: 0 }))
        ));
    }

    #[test]
    fn dynamic_type_decode_is_budget_checked() {
        let value = DynamicRecord {
            id: 1,
            name: "hello".to_owned(),
            tags: vec![1, 2, 3],
        };
        let bytes = crate::options().serialize(&value).unwrap();
        let budget = Budget::default();
        let decoded = decode_bounded::<DynamicRecord>(&bytes, budget).unwrap();
        assert_eq!(decoded.value, value);
        assert_eq!(decoded.use_.read as usize, bytes.len());
        // Dynamic ceiling: read + structural cap.
        assert!(decoded.use_.alloc_estimate >= bytes.len() as u64);
        assert!(decoded.use_.work_read >= bytes.len() as u64);
        // A tight input budget rejects the input up front.
        let tight = budget.with_max_input((bytes.len() - 2) as u64);
        assert!(matches!(
            decode_bounded::<DynamicRecord>(&bytes, tight),
            Err(DecodeError::Budget(BudgetExceeded::Input { .. }))
        ));
    }

    #[test]
    fn dynamic_collections_respect_alloc_budget() {
        let value = DynamicRecord {
            id: 1,
            name: String::new(),
            tags: vec![0u8; 100],
        };
        let bytes = crate::options().serialize(&value).unwrap();
        let budget = Budget::default().with_max_alloc(0);
        assert!(matches!(
            decode_bounded::<DynamicRecord>(&bytes, budget),
            Err(DecodeError::Budget(BudgetExceeded::Alloc { limit: 0 }))
        ));
    }

    #[test]
    fn depth_budget_caps_nesting_for_dynamic_types() {
        // A nested Vec<Vec<u8>> has derived depth D = 2; a budget with that
        // ceiling must accept it, and one level shallower must reject it.
        let value: Vec<Vec<u8>> = vec![vec![1, 2], vec![3]];
        let bytes = crate::options().serialize(&value).unwrap();
        assert_eq!(<Vec<Vec<u8>> as DecodeBounded>::MAX_DEPTH, 2);
        let ok = Budget::default().with_max_depth(2);
        let decoded = decode_bounded::<Vec<Vec<u8>>>(&bytes, ok).unwrap();
        assert_eq!(decoded.use_.depth_bound, 2);
        let too_shallow = Budget::default().with_max_depth(1);
        assert!(matches!(
            decode_bounded::<Vec<Vec<u8>>>(&bytes, too_shallow),
            Err(DecodeError::Budget(BudgetExceeded::Depth { limit: 1 }))
        ));
    }

    #[test]
    fn trailing_bytes_are_rejected() {
        let value = 42u8;
        let mut bytes = crate::options().serialize(&value).unwrap();
        bytes.push(0);
        assert!(matches!(
            decode_bounded::<u8>(&bytes, Budget::default()),
            Err(DecodeError::Codec(Error::TrailingBytes { remaining: 1 }))
        ));
    }

    #[test]
    fn budget_from_config_matches_config_limits() {
        let config = crate::options()
            .with_limit(4096)
            .with_collection_limit(128)
            .with_depth_limit(8);
        let budget = Budget::from_config(config);
        assert_eq!(budget.max_input(), 4096);
        assert_eq!(
            budget.max_alloc(),
            DEFAULT_COLLECTION_LIMIT * ELEMENT_STRUCTURE_BYTES
        );
        assert_eq!(budget.max_depth(), 8);
        assert_eq!(budget.max_work(), DEFAULT_SIZE_LIMIT);
    }

    #[test]
    fn algebra_matches_wire_shapes() {
        // A unit value is a single null tag.
        assert_eq!(<() as DecodeBounded>::MAX_INPUT, 1);
        assert_eq!(<() as DecodeBounded>::MAX_DEPTH, 0);
        // Option<u8> is the null tag or the tagged value.
        assert_eq!(<Option<u8> as DecodeBounded>::MAX_INPUT, 9);
        assert_eq!(<Option<u8> as DecodeBounded>::MAX_DEPTH, 0);
        // [u16; 4] is tag + 4 values + terminator.
        assert_eq!(<[u16; 4] as DecodeBounded>::MAX_INPUT, 2 + 4 * 9);
        assert_eq!(<[u16; 4] as DecodeBounded>::MAX_DEPTH, 1);
        // Tuples are arrays with a depth level.
        assert_eq!(<(u8, bool) as DecodeBounded>::MAX_INPUT, 2 + 9 + 1);
        assert_eq!(<(u8, bool) as DecodeBounded>::MAX_DEPTH, 1);
        // Dynamic collections add exactly one depth level and report MAX.
        assert_eq!(<Vec<u8> as DecodeBounded>::MAX_DEPTH, 1);
        assert_eq!(<Vec<Vec<u8>> as DecodeBounded>::MAX_DEPTH, 2);
        assert_eq!(<String as DecodeBounded>::MAX_INPUT, usize::MAX);
        assert_eq!(<String as DecodeBounded>::MAX_ALLOC, usize::MAX);
        // Borrowed strings allocate nothing but are content-dependent.
        assert_eq!(<&str as DecodeBounded>::MAX_ALLOC, 0);
        assert_eq!(<&str as DecodeBounded>::MAX_INPUT, usize::MAX);
        // Box adds the type's heap footprint and no container level.
        assert_eq!(
            <Box<u64> as DecodeBounded>::MAX_ALLOC,
            core::mem::size_of::<u64>()
        );
        assert_eq!(<Box<u64> as DecodeBounded>::MAX_DEPTH, 0);
        assert_eq!(<Option<Box<u64>> as DecodeBounded>::MAX_DEPTH, 0);
    }

    #[test]
    fn structural_element_bounds_match_collection_shapes() {
        // String's heap is data-bound: zero structural allocation.
        assert_eq!(<String as DecodeBounded>::MAX_STRUCTURAL_ELEMENT, 0);
        // Vec<u8> backing buffer is 1 byte per element.
        assert_eq!(
            <Vec<u8> as DecodeBounded>::MAX_STRUCTURAL_ELEMENT,
            core::mem::size_of::<u8>()
        );
        // Vec<String> backing buffer is the String header (24 bytes) per
        // element; its heap data is bounded by the read budget.
        assert_eq!(
            <Vec<String> as DecodeBounded>::MAX_STRUCTURAL_ELEMENT,
            core::mem::size_of::<String>()
        );
        // A plain struct field contributes its own collections' ceilings:
        // DynamicRecord { id: u64, name: String, tags: Vec<u8> } -> Vec<u8>.
        assert_eq!(
            <DynamicRecord as DecodeBounded>::MAX_STRUCTURAL_ELEMENT,
            core::mem::size_of::<u8>()
        );
        // Box<T> reports the boxed type's size as structural ceiling.
        assert_eq!(
            <Box<u64> as DecodeBounded>::MAX_STRUCTURAL_ELEMENT,
            core::mem::size_of::<u64>()
        );
        // Static types report zero structural allocation.
        assert_eq!(<StaticRecord as DecodeBounded>::MAX_STRUCTURAL_ELEMENT, 0);
    }

    #[test]
    fn primitive_algebra_is_exact() {
        fn assert_primitive<T: DecodeBounded>(b: usize) {
            assert_eq!(T::MAX_INPUT, b);
            assert_eq!(T::MAX_ALLOC, 0);
            assert_eq!(T::MAX_DEPTH, 0);
            assert_eq!(T::MAX_WORK, b + 1);
        }
        assert_primitive::<()>(1);
        assert_primitive::<bool>(1);
        assert_primitive::<char>(13);
        assert_primitive::<i8>(9);
        assert_primitive::<u8>(9);
        assert_primitive::<i16>(9);
        assert_primitive::<u16>(9);
        assert_primitive::<i32>(9);
        assert_primitive::<u32>(9);
        assert_primitive::<i64>(10);
        assert_primitive::<u64>(10);
        assert_primitive::<i128>(18);
        assert_primitive::<u128>(18);
        assert_primitive::<f32>(5);
        assert_primitive::<f64>(9);
    }

    #[test]
    fn option_array_tuple_algebra_is_exact() {
        // Option adds the null-tag branch (max with 1) and no depth level.
        assert_eq!(<Option<u8> as DecodeBounded>::MAX_INPUT, 9);
        assert_eq!(<Option<u8> as DecodeBounded>::MAX_DEPTH, 0);
        assert_eq!(<Option<Vec<u8>> as DecodeBounded>::MAX_DEPTH, 1);
        assert_eq!(
            <Option<Vec<u8>> as DecodeBounded>::MAX_STRUCTURAL_ELEMENT,
            1
        );
        assert_eq!(<Option<String> as DecodeBounded>::MAX_ALLOC, usize::MAX);
        assert_eq!(<Option<String> as DecodeBounded>::MAX_STRUCTURAL_ELEMENT, 0);
        // Arrays: tag + N elements + terminator, exactly one container level.
        assert_eq!(<[u8; 0] as DecodeBounded>::MAX_INPUT, 2);
        assert_eq!(<[u8; 0] as DecodeBounded>::MAX_DEPTH, 1);
        assert_eq!(<[u8; 3] as DecodeBounded>::MAX_INPUT, 2 + 3 * 9);
        assert_eq!(<[u8; 3] as DecodeBounded>::MAX_WORK, 2 + 3 * 10);
        assert_eq!(<[[u8; 2]; 3] as DecodeBounded>::MAX_DEPTH, 2);
        // Tuples use array semantics with per-field sums.
        assert_eq!(<(u8, bool) as DecodeBounded>::MAX_INPUT, 2 + 9 + 1);
        assert_eq!(<(u8, bool) as DecodeBounded>::MAX_DEPTH, 1);
        assert_eq!(
            <(u8, u16, u32, u64, u128, i8, i16, i32) as DecodeBounded>::MAX_INPUT,
            2 + 9 + 9 + 9 + 10 + 18 + 9 + 9 + 9
        );
        // PhantomData emits/consumes a null tag without owned storage.
        assert_eq!(<PhantomData<u64> as DecodeBounded>::MAX_INPUT, 1);
        assert_eq!(<PhantomData<u64> as DecodeBounded>::MAX_DEPTH, 0);
        assert_eq!(<PhantomData<u64> as DecodeBounded>::MAX_ALLOC, 0);
        assert_eq!(<PhantomData<u64> as DecodeBounded>::MAX_WORK, 2);
    }

    #[derive(
        Debug, PartialEq, nextjson::NsonSerialize, nextjson::NsonDeserialize, crate::DecodeBounded,
    )]
    struct NestedRecord {
        header: StaticRecord,
        items: [u8; 3],
        maybe: Option<i64>,
    }

    #[derive(
        Debug, PartialEq, nextjson::NsonSerialize, nextjson::NsonDeserialize, crate::DecodeBounded,
    )]
    enum StaticEnum {
        A,
        B(u8),
        C { x: i32, y: i32 },
    }

    #[derive(
        Debug, PartialEq, nextjson::NsonSerialize, nextjson::NsonDeserialize, crate::DecodeBounded,
    )]
    enum ShapeEnum {
        Unit,
        Newtype(u64),
        Tuple(u8, bool),
        Named { code: u16, label: String },
    }

    #[test]
    fn derive_algebra_nested_struct_matches_hand_computation() {
        // header: B=80 W=84 D=2; items [u8;3]: B=29 W=32 D=1; maybe: B=10
        // W=12 D=0. Keys add 9 + name length. The object wrapper adds 2.
        assert_eq!(
            NestedRecord::MAX_INPUT,
            2 + (80 + 15) + (29 + 14) + (10 + 14)
        );
        assert_eq!(
            NestedRecord::MAX_WORK,
            2 + (84 + 15) + (32 + 14) + (12 + 14)
        );
        assert_eq!(NestedRecord::MAX_DEPTH, 3);
        assert_eq!(NestedRecord::MAX_ALLOC, 0);
        assert_eq!(NestedRecord::MAX_STRUCTURAL_ELEMENT, 0);
        const _: () = assert!(NestedRecord::STATICALLY_BOUNDED);
    }

    #[test]
    fn derive_algebra_enums_match_hand_computation() {
        // StaticEnum: variants A(unit), B(u8), C{x,y}. B = 1 + max(10+1,
        // 10+9, 10+(2+19+19)) + 1 = 52; W = 1 + max(10+1, 10+10, 10+42) + 1
        // = 54; D = 1 + max(0,0,1) = 2.
        assert_eq!(StaticEnum::MAX_INPUT, 52);
        assert_eq!(StaticEnum::MAX_WORK, 54);
        assert_eq!(StaticEnum::MAX_DEPTH, 2);
        assert_eq!(StaticEnum::MAX_ALLOC, 0);
        assert_eq!(StaticEnum::MAX_STRUCTURAL_ELEMENT, 0);
        const _: () = assert!(StaticEnum::STATICALLY_BOUNDED);
        // ShapeEnum: the Named variant carries a String, so B/A/W are dynamic
        // (usize::MAX). Depth stays finite: the Named variant adds the String
        // level (D=1) inside its own object level, and the enum adds another
        // -> 3. Structural stays zero (String is data-bound).
        assert_eq!(ShapeEnum::MAX_INPUT, usize::MAX);
        assert_eq!(ShapeEnum::MAX_ALLOC, usize::MAX);
        assert_eq!(ShapeEnum::MAX_WORK, usize::MAX);
        assert_eq!(ShapeEnum::MAX_DEPTH, 2);
        assert_eq!(ShapeEnum::MAX_STRUCTURAL_ELEMENT, 0);
        const _: () = assert!(!ShapeEnum::STATICALLY_BOUNDED);
    }

    #[test]
    fn decode_bounded_respects_derived_static_algebra() {
        let value = NestedRecord {
            header: static_value(),
            items: [1, 2, 3],
            maybe: Some(-5),
        };
        let bytes = crate::options().serialize(&value).unwrap();
        let budget = Budget::from_type::<NestedRecord>();
        assert_eq!(budget.max_input(), NestedRecord::MAX_INPUT as u64);
        assert_eq!(budget.max_alloc(), 0);
        assert_eq!(budget.max_depth(), 3);
        let decoded = decode_bounded::<NestedRecord>(&bytes, budget).unwrap();
        assert_eq!(decoded.value, value);
        assert_eq!(decoded.use_.read as usize, bytes.len());
        assert!(decoded.use_.read <= NestedRecord::MAX_INPUT as u64);
        assert_eq!(decoded.use_.alloc_estimate, 0);
        assert_eq!(decoded.use_.depth_bound, NestedRecord::MAX_DEPTH);
        assert!(decoded.use_.work_read <= NestedRecord::MAX_WORK as u64);
    }

    #[test]
    fn decode_bounded_respects_derived_enum_algebra() {
        for value in [
            StaticEnum::A,
            StaticEnum::B(7),
            StaticEnum::C { x: -1, y: 2 },
        ] {
            let bytes = crate::options().serialize(&value).unwrap();
            let decoded =
                decode_bounded::<StaticEnum>(&bytes, Budget::from_type::<StaticEnum>()).unwrap();
            assert_eq!(decoded.value, value);
            assert_eq!(decoded.use_.alloc_estimate, 0);
            assert_eq!(decoded.use_.depth_bound, 2);
            assert!(decoded.use_.read <= StaticEnum::MAX_INPUT as u64);
        }
        // The dynamic enum decodes under a default budget.
        for value in [
            ShapeEnum::Unit,
            ShapeEnum::Newtype(u64::MAX),
            ShapeEnum::Tuple(0, true),
            ShapeEnum::Named {
                code: 9,
                label: "x".into(),
            },
        ] {
            let bytes = crate::options().serialize(&value).unwrap();
            let decoded = decode_bounded::<ShapeEnum>(&bytes, Budget::default()).unwrap();
            assert_eq!(decoded.value, value);
            assert_eq!(decoded.use_.depth_bound, Budget::default().max_depth());
        }
    }

    #[test]
    fn input_budget_boundary_is_exact() {
        let value: Vec<u8> = vec![1, 2, 3];
        let bytes = crate::options().serialize(&value).unwrap();
        // A budget of exactly the frame size decodes; one byte less rejects
        // before any allocation.
        let exact = Budget::default().with_max_input(bytes.len() as u64);
        assert!(decode_bounded::<Vec<u8>>(&bytes, exact).is_ok());
        let tight = Budget::default().with_max_input(bytes.len() as u64 - 1);
        assert!(matches!(
            decode_bounded::<Vec<u8>>(&bytes, tight),
            Err(DecodeError::Budget(BudgetExceeded::Input { .. }))
        ));
    }

    #[test]
    fn work_budget_boundary_is_exact() {
        // Static types reject a work budget below W(T) up front.
        let value = static_value();
        let bytes = crate::options().serialize(&value).unwrap();
        let exact =
            Budget::from_type::<StaticRecord>().with_max_work(StaticRecord::MAX_WORK as u64);
        assert!(decode_bounded::<StaticRecord>(&bytes, exact).is_ok());
        let tight =
            Budget::from_type::<StaticRecord>().with_max_work(StaticRecord::MAX_WORK as u64 - 1);
        assert!(matches!(
            decode_bounded::<StaticRecord>(&bytes, tight),
            Err(DecodeError::Budget(BudgetExceeded::Work { .. }))
        ));
        // Dynamic types enforce work through the byte limit (read <= work):
        // a budget of exactly the frame size decodes, one byte short cannot
        // read the whole frame and must fail (which error variant depends on
        // where the limit binds).
        let dyn_value: Vec<u64> = (0..16).collect();
        let dyn_bytes = crate::options().serialize(&dyn_value).unwrap();
        let len = dyn_bytes.len() as u64;
        let exact = Budget::default().with_max_work(len);
        let decoded = decode_bounded::<Vec<u64>>(&dyn_bytes, exact).unwrap();
        assert_eq!(decoded.use_.read, len);
        assert!(decoded.use_.work_read >= len);
        let tight = Budget::default().with_max_work(len - 1);
        let result = decode_bounded::<Vec<u64>>(&dyn_bytes, tight);
        assert!(
            result.is_err(),
            "a work budget below the frame size ({len}) must fail; got {:?}",
            result.map(|d| d.use_)
        );
    }

    #[test]
    fn weighted_token_admission_boundary_is_exact() {
        // Root array plus 100 elements requires 101 global tokens at weight 1.
        let value: Vec<u8> = vec![0u8; 100];
        let bytes = crate::options().serialize(&value).unwrap();
        let tight = Budget::default()
            .with_max_alloc(bytes.len() as u64 + 99)
            .with_max_input(bytes.len() as u64);
        assert!(matches!(
            decode_bounded::<Vec<u8>>(&bytes, tight),
            Err(DecodeError::Budget(BudgetExceeded::Values { limit: 99 }))
        ));
        let exact = Budget::default()
            .with_max_alloc(bytes.len() as u64 + 101)
            .with_max_input(bytes.len() as u64);
        assert!(decode_bounded::<Vec<u8>>(&bytes, exact).is_ok());
    }

    #[test]
    fn element_structure_knob_falls_back_when_structural_unknown() {
        // A manual DecodeBounded implementation leaves MAX_STRUCTURAL_ELEMENT
        // at its usize::MAX default; decode_bounded then uses the budget knob
        // as the per-element structural ceiling.
        let budget = Budget::default()
            .with_max_alloc(256)
            .with_element_structure_bytes(1);
        let limits = derive_enforced_limits(budget, false, budget.element_structure_bytes());
        assert_eq!(limits.collection_limit, 256);
        let budget = budget.with_element_structure_bytes(64);
        let limits = derive_enforced_limits(budget, false, budget.element_structure_bytes());
        assert_eq!(limits.collection_limit, 4);
        // A zero knob means no structural allocation: no per-element cap.
        let budget = budget.with_element_structure_bytes(0);
        let limits = derive_enforced_limits(budget, false, budget.element_structure_bytes());
        assert_eq!(
            limits.collection_limit,
            limits.byte_limit.min(budget.max_collection())
        );
    }

    #[test]
    fn decode_bounded_matches_plain_deserialize() {
        let values: Vec<DynamicRecord> = (0..20)
            .map(|i| DynamicRecord {
                id: i,
                name: format!("name{i}"),
                tags: (0..i % 5).map(|j| j as u8).collect(),
            })
            .collect();
        let bytes = crate::options().serialize(&values).unwrap();
        let budget = Budget::default()
            .with_max_input(bytes.len() as u64)
            .with_max_alloc(1 << 20);
        let decoded = decode_bounded::<Vec<DynamicRecord>>(&bytes, budget).unwrap();
        assert_eq!(decoded.value, values);
        assert_eq!(decoded.use_.read as usize, bytes.len());
        // The plain codec agrees on the same bytes.
        let plain: Vec<DynamicRecord> = crate::options().deserialize(&bytes).unwrap();
        assert_eq!(plain, values);
    }

    #[test]
    fn budget_builder_setters_and_accessors_roundtrip() {
        let budget = Budget::new(1, 2, 3, 4)
            .with_max_input(10)
            .with_max_alloc(20)
            .with_max_depth(30)
            .with_max_work(40)
            .with_element_structure_bytes(7);
        assert_eq!(budget.max_input(), 10);
        assert_eq!(budget.max_alloc(), 20);
        assert_eq!(budget.max_depth(), 30);
        assert_eq!(budget.max_work(), 40);
        assert_eq!(budget.element_structure_bytes(), 7);
        // Defaults.
        let default = Budget::default();
        assert_eq!(default.max_input(), DEFAULT_SIZE_LIMIT);
        assert_eq!(default.max_work(), DEFAULT_SIZE_LIMIT);
        assert_eq!(default.max_depth(), MAX_DEPTH);
        assert_eq!(default.element_structure_bytes(), ELEMENT_STRUCTURE_BYTES);
        assert_eq!(
            default.max_alloc(),
            DEFAULT_COLLECTION_LIMIT * ELEMENT_STRUCTURE_BYTES
        );
    }

    #[test]
    fn deeply_nested_depth_algebra_is_exact() {
        // Depth is always finite and grows by one container per Vec level.
        assert_eq!(<Vec<u8> as DecodeBounded>::MAX_DEPTH, 1);
        assert_eq!(<Vec<Vec<u8>> as DecodeBounded>::MAX_DEPTH, 2);
        assert_eq!(<Vec<Vec<Vec<u8>>> as DecodeBounded>::MAX_DEPTH, 3);
        assert_eq!(
            <Vec<Vec<Vec<Vec<Vec<Vec<u8>>>>>> as DecodeBounded>::MAX_DEPTH,
            6
        );
        // Depth in a struct is the max over fields plus the object level.
        assert_eq!(NestedRecord::MAX_DEPTH, 3);
        assert_eq!(<Option<StaticRecord> as DecodeBounded>::MAX_DEPTH, 2);
    }

    #[test]
    fn static_boundedness_flags_are_correct() {
        const _: () = assert!(StaticRecord::STATICALLY_BOUNDED);
        const _: () = assert!(NestedRecord::STATICALLY_BOUNDED);
        const _: () = assert!(StaticEnum::STATICALLY_BOUNDED);
        const _: () = assert!(!DynamicRecord::STATICALLY_BOUNDED);
        const _: () = assert!(!ShapeEnum::STATICALLY_BOUNDED);
        const _: () = assert!(!<Vec<u8>>::STATICALLY_BOUNDED);
        const _: () = assert!(<Option<u8>>::STATICALLY_BOUNDED);
        const _: () = assert!(<[u8; 4]>::STATICALLY_BOUNDED);
    }
}