ayaml 1.0.0

A safe, pure-Rust YAML parser, event stream, value model, Serde layer, and emitter
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
//! Resource limits and options for hostile YAML.
//!
//! The defaults use 32 MiB of input, depth 128, a byte-weighted alias budget,
//! and a 256-byte node cost estimate. A stream may hold up to 10,000 documents;
//! the single-document profile allows one. This is not the optional
//! `libyaml-compat` mode. Limits are inclusive
//! at the accepted boundary, and `max_depth` may not exceed
//! [`MAX_DEPTH_CAP`].

use std::fmt;

use crate::error::{Error, ErrorCode, ErrorKind};

/// Maximum structured-document input bytes.
pub const MAX_INPUT_BYTES: usize = 32 * 1024 * 1024;
/// Maximum collection nesting depth.
pub const MAX_DEPTH: usize = 128;
/// The largest `max_depth` an entry point accepts. A larger configured value
/// is an error.
///
/// Parsing, composing, the value writer, and the event writer keep their own
/// stacks, but Serde deserialization, [`from_value`](crate::from_value),
/// [`to_value`](crate::to_value), [`to_string`](crate::to_string) (via
/// `to_value`), [`Value::apply_merge_keys`](crate::Value::apply_merge_keys),
/// and dropping a [`Value`](crate::Value) recurse once per nesting level. At this depth
/// they fit a 2 MiB thread, the default for spawned and test threads, in
/// debug and release builds. The tightest paths measured, `from_value`,
/// `to_value`, and `to_string` over nested flow mappings with tags in a debug
/// build, need about 1.8 MiB at this depth, so 1.5 MiB overflows.
pub const MAX_DEPTH_CAP: usize = MAX_DEPTH;
/// Fixed alias-expansion allowance.
pub const MAX_ALIAS_EXPANSION_BYTES: usize = 256 * 1024 * 1024;
/// Additional alias allowance per input byte.
pub const ALIAS_BYTES_PER_INPUT_BYTE: usize = 16;
/// Estimated cost of one composed node.
pub const NODE_COST_BYTES: usize = 256;
/// Maximum bytes that tag handles expand to in one stream.
pub const MAX_TAG_EXPANSION_BYTES: usize = 64 * 1024 * 1024;
/// Default maximum documents in one stream. Single-document entry
/// points reject a second document regardless.
pub const DEFAULT_MAX_DOCUMENTS: usize = 10_000;
/// Maximum documents in the single-document profile.
pub const COMPAT_MAX_DOCUMENTS: usize = 1;

/// The resource that was exhausted.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LimitKind {
    /// Structured-document input bytes.
    InputBytes,
    /// Collection nesting depth.
    Depth,
    /// Alias-expansion bytes.
    AliasExpansion,
    /// Documents in a stream.
    Documents,
    /// Bytes in one scalar.
    ScalarBytes,
    /// Entries in one collection.
    CollectionEntries,
    /// Events in one stream, or the tokens a reader keeps for one stream.
    Events,
    /// Anchors in one stream.
    Anchors,
    /// Alias dereferences in one stream.
    AliasDereferences,
    /// Bytes written by an emitter call.
    OutputBytes,
    /// Bytes that tag handles expand to in a stream.
    TagExpansion,
}

impl fmt::Display for LimitKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let name = match self {
            Self::InputBytes => "input bytes",
            Self::Depth => "collection depth",
            Self::AliasExpansion => "alias expansion bytes",
            Self::Documents => "documents",
            Self::ScalarBytes => "scalar bytes",
            Self::CollectionEntries => "collection entries",
            Self::Events => "events",
            Self::Anchors => "anchors",
            Self::AliasDereferences => "alias dereferences",
            Self::OutputBytes => "output bytes",
            Self::TagExpansion => "tag expansion bytes",
        };
        formatter.write_str(name)
    }
}

/// A configured limit was exceeded.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LimitExceeded {
    kind: LimitKind,
    limit: u64,
    observed: u64,
}

impl LimitExceeded {
    /// Create a limit violation.
    #[must_use]
    pub const fn new(kind: LimitKind, limit: u64, observed: u64) -> Self {
        Self {
            kind,
            limit,
            observed,
        }
    }

    /// The exhausted resource.
    #[must_use]
    pub const fn kind(self) -> LimitKind {
        self.kind
    }

    /// The configured ceiling.
    #[must_use]
    pub const fn limit(self) -> u64 {
        self.limit
    }

    /// The observed or attempted value.
    #[must_use]
    pub const fn observed(self) -> u64 {
        self.observed
    }
}

impl fmt::Display for LimitExceeded {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} limit exceeded: limit {}, observed {}",
            self.kind, self.limit, self.observed
        )
    }
}

impl std::error::Error for LimitExceeded {}

impl From<LimitExceeded> for Error {
    fn from(value: LimitExceeded) -> Self {
        Self::coded(
            ErrorKind::Limit,
            ErrorCode::from_limit_kind(value.kind()),
            value.to_string(),
        )
        .with_limit(value)
    }
}

/// Limits applied to one parse.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Limits {
    /// Maximum structured-document input bytes.
    pub max_input_bytes: usize,
    /// Maximum collection nesting depth, at most [`MAX_DEPTH_CAP`].
    pub max_depth: usize,
    /// Fixed alias-expansion byte allowance.
    pub max_alias_expansion_bytes: usize,
    /// Additional alias allowance per input byte.
    pub alias_bytes_per_input_byte: usize,
    /// Estimated cost of one composed node, at least 1. Each alias is charged this much for every
    /// node it copies, on top of the text it copies, so a small cost lets more nodes through the
    /// alias budget.
    pub node_cost_bytes: usize,
    /// Maximum documents in one stream.
    pub max_documents: usize,
    /// Maximum bytes in one scalar: the larger of its text in the input and the value it reads
    /// as. A block scalar's text runs from its `|` or `>` through its last line, so its header,
    /// indentation, and trailing blank lines count. A double-quoted `\L` or `\P` takes 2 bytes of
    /// text and 3 of value.
    pub max_scalar_bytes: usize,
    /// Maximum entries in one collection.
    pub max_collection_entries: usize,
    /// Maximum events in one stream, and maximum tokens a reader keeps for one stream. The events
    /// are those [`parse_events`](crate::parse_events) yields, the stream's start and end
    /// included, and every reader counts them alike. The tokens are the input's scalars, anchors,
    /// aliases, tags, indicators, document markers, and directives. Neither count includes a
    /// line break or a comment.
    pub max_events: usize,
    /// Maximum anchors in one stream. An event writer counts the names of one document's
    /// anchors against it, which it holds to check that document's aliases.
    pub max_anchors: usize,
    /// Maximum alias dereferences in one stream.
    pub max_alias_dereferences: usize,
    /// Maximum bytes written by one emitter call.
    pub max_output_bytes: usize,
    /// Maximum bytes that tag handles expand to in one stream. Each use of a handle counts the
    /// whole prefix it stands for, so a long `%TAG` prefix can't multiply the cost of short tags.
    pub max_tag_expansion_bytes: usize,
}

impl Default for Limits {
    /// The single-document profile with a stream-sized document limit.
    fn default() -> Self {
        Self::default_profile()
    }
}

impl Limits {
    /// The default profile, usable in `const` contexts.
    #[must_use]
    pub const fn new() -> Self {
        Self::default_profile()
    }

    /// The default profile, usable in `const` contexts.
    pub(crate) const fn default_profile() -> Self {
        Self {
            max_documents: DEFAULT_MAX_DOCUMENTS,
            ..Self::compat()
        }
    }

    /// The single-document profile.
    ///
    /// This is not the optional `libyaml-compat` mode; it is the default profile with a
    /// one-document stream limit.
    #[must_use]
    pub const fn compat() -> Self {
        Self {
            max_input_bytes: MAX_INPUT_BYTES,
            max_depth: MAX_DEPTH,
            max_alias_expansion_bytes: MAX_ALIAS_EXPANSION_BYTES,
            alias_bytes_per_input_byte: ALIAS_BYTES_PER_INPUT_BYTE,
            node_cost_bytes: NODE_COST_BYTES,
            max_documents: COMPAT_MAX_DOCUMENTS,
            max_scalar_bytes: MAX_INPUT_BYTES,
            max_collection_entries: 1_000_000,
            max_events: 1_000_000,
            max_anchors: 100_000,
            max_alias_dereferences: 100_000,
            max_output_bytes: 64 * 1024 * 1024,
            max_tag_expansion_bytes: MAX_TAG_EXPANSION_BYTES,
        }
    }

    /// The default profile with the four count limits lifted, for a valid document within
    /// [`MAX_INPUT_BYTES`] that exceeds the memory-bounded defaults.
    ///
    /// The default count limits deliberately bound the tokens an eager read keeps: to 32 MB where
    /// they are plain scalars and indicators, and to about 150 MB at the most, where each is a tag
    /// with a long name. A dense document can so reach one of them before the input limit. This profile
    /// sets `max_events`, `max_collection_entries`, `max_anchors`, and
    /// `max_alias_dereferences` to `usize::MAX`; the input, depth, scalar, tag-expansion,
    /// document, and alias budgets still apply. A read at this profile can hold a
    /// gigabyte of tokens, so use it only for input whose size and trustworthiness you know.
    #[must_use]
    pub const fn for_max_input() -> Self {
        Self {
            max_documents: DEFAULT_MAX_DOCUMENTS,
            max_events: usize::MAX,
            max_collection_entries: usize::MAX,
            max_anchors: usize::MAX,
            max_alias_dereferences: usize::MAX,
            ..Self::compat()
        }
    }

    /// Set the maximum input size.
    #[must_use]
    pub const fn with_max_input_bytes(mut self, value: usize) -> Self {
        self.max_input_bytes = value;
        self
    }

    /// Set the maximum collection nesting depth.
    #[must_use]
    pub const fn with_max_depth(mut self, value: usize) -> Self {
        self.max_depth = value;
        self
    }

    /// Set the fixed alias-expansion allowance.
    #[must_use]
    pub const fn with_max_alias_expansion_bytes(mut self, value: usize) -> Self {
        self.max_alias_expansion_bytes = value;
        self
    }

    /// Set the per-input-byte alias allowance.
    #[must_use]
    pub const fn with_alias_bytes_per_input_byte(mut self, value: usize) -> Self {
        self.alias_bytes_per_input_byte = value;
        self
    }

    /// Set the estimated cost of one composed node. Every entry point rejects 0, which would make
    /// a copied collection of nulls free and so turn the alias budget off. A cost below the
    /// memory a node takes, about 100 bytes, lets aliases hold more memory than the budget: at 1,
    /// aliases of empty nodes held about 65 times it before the budget stopped them.
    #[must_use]
    pub const fn with_node_cost_bytes(mut self, value: usize) -> Self {
        self.node_cost_bytes = value;
        self
    }

    /// Set the maximum number of documents in one stream.
    #[must_use]
    pub const fn with_max_documents(mut self, value: usize) -> Self {
        self.max_documents = value;
        self
    }

    /// Set the maximum size of one scalar, its text or its value, whichever is larger; see
    /// [`max_scalar_bytes`](Self::max_scalar_bytes).
    #[must_use]
    pub const fn with_max_scalar_bytes(mut self, value: usize) -> Self {
        self.max_scalar_bytes = value;
        self
    }

    /// Set the maximum number of entries in one collection.
    #[must_use]
    pub const fn with_max_collection_entries(mut self, value: usize) -> Self {
        self.max_collection_entries = value;
        self
    }

    /// Set the maximum number of events, and of kept tokens, in one stream; see
    /// [`max_events`](Self::max_events).
    #[must_use]
    pub const fn with_max_events(mut self, value: usize) -> Self {
        self.max_events = value;
        self
    }

    /// Set the maximum number of anchors in one stream.
    #[must_use]
    pub const fn with_max_anchors(mut self, value: usize) -> Self {
        self.max_anchors = value;
        self
    }

    /// Set the maximum number of alias dereferences in one stream.
    #[must_use]
    pub const fn with_max_alias_dereferences(mut self, value: usize) -> Self {
        self.max_alias_dereferences = value;
        self
    }

    /// Set the maximum output size for one emitter call.
    #[must_use]
    pub const fn with_max_output_bytes(mut self, value: usize) -> Self {
        self.max_output_bytes = value;
        self
    }

    /// Set the maximum bytes that tag handles expand to in one stream.
    #[must_use]
    pub const fn with_max_tag_expansion_bytes(mut self, value: usize) -> Self {
        self.max_tag_expansion_bytes = value;
        self
    }

    /// The alias-expansion budget for an input of `input_len` bytes.
    ///
    /// The input contribution is capped at `max_input_bytes`, so padding a
    /// document cannot raise the budget above roughly 768 MiB with the
    /// compatibility constants.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    #[must_use]
    pub fn expansion_budget(&self, input_len: usize) -> usize {
        let input = input_len.min(self.max_input_bytes);
        self.max_alias_expansion_bytes
            .saturating_add(self.alias_bytes_per_input_byte.saturating_mul(input))
    }

    /// Reject settings no entry point can honour, a `max_depth` above [`MAX_DEPTH_CAP`], and
    /// settings that would turn a budget off: a `node_cost_bytes` of 0 makes every node an alias
    /// copies free, so a nest of aliases to collections of nulls could grow without bound.
    pub(crate) const fn is_valid(&self) -> bool {
        self.max_depth <= MAX_DEPTH_CAP && self.node_cost_bytes > 0
    }

    /// Reject settings no entry point can honour, returning a descriptive [`Error`].
    pub(crate) fn validate(&self) -> Result<(), Error> {
        if self.is_valid() {
            return Ok(());
        }
        if self.max_depth > MAX_DEPTH_CAP {
            return Err(Error::coded(
                ErrorKind::Limit,
                ErrorCode::InvalidLimits,
                format!(
                    "max_depth {} is above the supported maximum of {MAX_DEPTH_CAP}",
                    self.max_depth
                ),
            ));
        }
        if self.node_cost_bytes == 0 {
            return Err(Error::coded(
                ErrorKind::Limit,
                ErrorCode::InvalidLimits,
                "node_cost_bytes 0 would make the nodes an alias copies free, which turns off the \
                 alias budget; the least accepted cost is 1",
            ));
        }
        Ok(())
    }

    /// Check the input size before scanning.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_input(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::InputBytes, self.max_input_bytes, observed)
    }

    /// Check collection depth before descending.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_depth(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::Depth, self.max_depth, observed)
    }

    /// Check the number of documents.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_documents(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::Documents, self.max_documents, observed)
    }

    /// Check the bytes that tag handles have expanded to so far.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_tag_expansion(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(
            LimitKind::TagExpansion,
            self.max_tag_expansion_bytes,
            observed,
        )
    }

    /// Check a scalar's byte length.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_scalar_bytes(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::ScalarBytes, self.max_scalar_bytes, observed)
    }

    /// Check one collection's entry count.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_collection_entries(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(
            LimitKind::CollectionEntries,
            self.max_collection_entries,
            observed,
        )
    }

    /// Check the event count.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_events(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::Events, self.max_events, observed)
    }

    /// Check the anchor count.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_anchors(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::Anchors, self.max_anchors, observed)
    }

    /// Check the alias-dereference count.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_alias_dereferences(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(
            LimitKind::AliasDereferences,
            self.max_alias_dereferences,
            observed,
        )
    }

    /// Check output bytes before a write.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_output_bytes(&self, observed: usize) -> Result<(), LimitExceeded> {
        check(LimitKind::OutputBytes, self.max_output_bytes, observed)
    }

    /// Check a charged node/alias expansion against an explicit budget.
    ///
    /// # Errors
    ///
    /// Returns an error when `observed` exceeds this limit or the limit setting is invalid.
    pub fn check_alias_expansion(
        &self,
        input_len: usize,
        observed: usize,
    ) -> Result<(), LimitExceeded> {
        check(
            LimitKind::AliasExpansion,
            self.expansion_budget(input_len),
            observed,
        )
    }
}

/// A zero-sized cryptographic SipHash-1-3 hasher that reuses one process-wide random seed,
/// preserving PRF-grade `HashDoS` resistance without repeated `RandomState::new()` calls.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct GlobalHasher;

impl std::hash::BuildHasher for GlobalHasher {
    type Hasher = std::collections::hash_map::DefaultHasher;

    #[inline]
    fn build_hasher(&self) -> Self::Hasher {
        static STATE: std::sync::OnceLock<std::hash::RandomState> = std::sync::OnceLock::new();
        STATE
            .get_or_init(std::hash::RandomState::new)
            .build_hasher()
    }
}

/// The alias use charged so far: dereferences and the estimated bytes they
/// materialize. One budget covers a whole stream, so a multi-document
/// stream cannot multiply it.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct AliasBudget {
    dereferences: usize,
    bytes: usize,
}

impl AliasBudget {
    /// Charge one alias against `limits`, returning the structured [`LimitExceeded`] on overflow.
    pub(crate) fn charge_limits(
        &mut self,
        limits: &Limits,
        input_len: usize,
        size: usize,
    ) -> Result<(), LimitExceeded> {
        self.dereferences = self.dereferences.saturating_add(1);
        limits.check_alias_dereferences(self.dereferences)?;
        self.bytes = self.bytes.saturating_add(size);
        limits.check_alias_expansion(input_len, self.bytes)
    }

    /// Charge one alias to a node estimated at `size` bytes, before
    /// anything is materialized for it.
    pub(crate) fn charge(
        &mut self,
        limits: &Limits,
        input_len: usize,
        size: usize,
    ) -> Result<(), Error> {
        self.charge_limits(limits, input_len, size)
            .map_err(Error::from)
    }

    /// Charge estimated expanded bytes without incrementing the dereference count (used while
    /// materializing nodes already inside an alias expansion).
    pub(crate) fn charge_bytes(
        &mut self,
        limits: &Limits,
        input_len: usize,
        size: usize,
    ) -> Result<(), Error> {
        self.bytes = self.bytes.saturating_add(size);
        limits
            .check_alias_expansion(input_len, self.bytes)
            .map_err(Error::from)
    }
}

fn check(kind: LimitKind, limit: usize, observed: usize) -> Result<(), LimitExceeded> {
    if observed > limit {
        Err(LimitExceeded::new(
            kind,
            u64::try_from(limit).unwrap_or(u64::MAX),
            u64::try_from(observed).unwrap_or(u64::MAX),
        ))
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{LimitKind, Limits, MAX_ALIAS_EXPANSION_BYTES, MAX_DEPTH, MAX_INPUT_BYTES};

    #[test]
    fn compatibility_defaults_match_the_profile() {
        let limits = Limits::compat();
        assert_eq!(limits.max_input_bytes, 32 * 1024 * 1024);
        assert_eq!(limits.max_depth, MAX_DEPTH);
        assert_eq!(limits.max_alias_expansion_bytes, 256 * 1024 * 1024);
        assert_eq!(limits.alias_bytes_per_input_byte, 16);
        assert_eq!(limits.node_cost_bytes, 256);
        assert_eq!(limits.max_documents, 1);
    }

    #[test]
    fn defaults_use_a_stream_document_limit() {
        assert_eq!(
            Limits::default(),
            Limits {
                max_documents: 10_000,
                ..Limits::compat()
            }
        );
    }

    #[test]
    fn max_input_profile_lifts_only_the_count_limits() {
        let limits = Limits::for_max_input();
        assert_eq!(limits.max_input_bytes, MAX_INPUT_BYTES);
        assert_eq!(limits.max_depth, MAX_DEPTH);
        assert_eq!(limits.max_documents, 10_000);
        assert_eq!(limits.max_events, usize::MAX);
        assert_eq!(limits.max_collection_entries, usize::MAX);
        assert_eq!(limits.max_anchors, usize::MAX);
        assert_eq!(limits.max_alias_dereferences, usize::MAX);
        assert!(limits.with_max_events(1).check_events(2).is_err());
    }

    #[test]
    fn input_boundary_is_inclusive() {
        let limits = Limits::default();
        assert!(limits.check_input(MAX_INPUT_BYTES - 1).is_ok());
        assert!(limits.check_input(MAX_INPUT_BYTES).is_ok());
        let error = limits.check_input(MAX_INPUT_BYTES + 1).unwrap_err();
        assert_eq!(error.kind(), LimitKind::InputBytes);
        assert_eq!(error.limit(), MAX_INPUT_BYTES as u64);
    }

    #[test]
    fn depth_boundary_is_inclusive() {
        let limits = Limits::default();
        assert!(limits.check_depth(MAX_DEPTH).is_ok());
        assert_eq!(
            limits.check_depth(MAX_DEPTH + 1).unwrap_err().kind(),
            LimitKind::Depth
        );
    }

    #[test]
    fn alias_budget_formula_and_cap() {
        let limits = Limits::default();
        assert_eq!(limits.expansion_budget(0), MAX_ALIAS_EXPANSION_BYTES);
        assert_eq!(
            limits.expansion_budget(1024),
            MAX_ALIAS_EXPANSION_BYTES + 1024 * 16
        );
        assert_eq!(
            limits.expansion_budget(MAX_INPUT_BYTES),
            MAX_ALIAS_EXPANSION_BYTES + MAX_INPUT_BYTES * 16
        );
        assert_eq!(
            limits.expansion_budget(MAX_INPUT_BYTES + 1),
            MAX_ALIAS_EXPANSION_BYTES + MAX_INPUT_BYTES * 16
        );
    }

    #[test]
    fn alias_expansion_boundary_is_inclusive() {
        let limits = Limits::default();
        let budget = limits.expansion_budget(0);
        assert!(limits.check_alias_expansion(0, budget - 1).is_ok());
        assert!(limits.check_alias_expansion(0, budget).is_ok());
        assert_eq!(
            limits
                .check_alias_expansion(0, budget + 1)
                .unwrap_err()
                .kind(),
            LimitKind::AliasExpansion
        );
    }

    #[test]
    fn limits_and_alias_budget_saturate_without_overflow() {
        let huge = Limits::default()
            .with_max_input_bytes(usize::MAX)
            .with_max_alias_expansion_bytes(usize::MAX - 10)
            .with_alias_bytes_per_input_byte(usize::MAX);
        assert_eq!(huge.expansion_budget(usize::MAX), usize::MAX);
        assert_eq!(huge.expansion_budget(1), usize::MAX);
        assert_eq!(huge.expansion_budget(0), usize::MAX - 10);

        let capped = Limits::default().with_max_input_bytes(16);
        assert_eq!(
            capped.expansion_budget(16),
            capped.expansion_budget(usize::MAX)
        );

        assert!(
            Limits::default()
                .with_max_depth(super::MAX_DEPTH_CAP)
                .validate()
                .is_ok()
        );
        assert!(
            Limits::default()
                .with_max_depth(super::MAX_DEPTH_CAP + 1)
                .validate()
                .is_err()
        );
        assert!(
            Limits::default()
                .with_node_cost_bytes(0)
                .validate()
                .is_err()
        );
        assert!(Limits::default().with_node_cost_bytes(1).validate().is_ok());

        let mut budget = super::AliasBudget {
            dereferences: usize::MAX - 1,
            bytes: usize::MAX - 4,
        };
        let limits = Limits::default()
            .with_max_alias_dereferences(usize::MAX)
            .with_max_alias_expansion_bytes(usize::MAX);
        assert!(budget.charge(&limits, 0, 16).is_ok());
        assert_eq!(budget.dereferences, usize::MAX);
        assert_eq!(budget.bytes, usize::MAX);

        let tight = Limits::default()
            .with_max_alias_dereferences(2)
            .with_max_alias_expansion_bytes(10)
            .with_alias_bytes_per_input_byte(0);
        let mut fresh = super::AliasBudget::default();
        assert!(fresh.charge(&tight, 100, 6).is_ok());
        assert!(fresh.charge(&tight, 100, 4).is_ok());
        assert!(fresh.charge(&tight, 100, 1).is_err());
    }
}

#[cfg(kani)]
mod kani_proofs {
    use super::{AliasBudget, LimitKind, Limits, MAX_DEPTH_CAP, check};

    #[kani::proof]
    fn verify_expansion_budget_overflow_free_and_capped() {
        let max_input: usize = kani::any();
        let fixed_cap: usize = kani::any();
        let len_a: usize = kani::any();
        let len_b: usize = kani::any();
        kani::assume(len_a <= len_b);

        // Default multiplier (16), zero multiplier, unit multiplier, and saturating MAX.
        for per_byte in [0_usize, 1, 16, usize::MAX] {
            let limits = Limits::default()
                .with_max_input_bytes(max_input)
                .with_max_alias_expansion_bytes(fixed_cap)
                .with_alias_bytes_per_input_byte(per_byte);

            let b_a = limits.expansion_budget(len_a);
            let b_b = limits.expansion_budget(len_b);
            let b_cap = limits.expansion_budget(max_input);
            assert!(b_a >= fixed_cap);
            assert!(b_a <= b_b);
            assert!(b_b <= b_cap);
            if len_b >= max_input {
                assert_eq!(b_b, b_cap);
            }
        }
    }

    #[kani::proof]
    fn verify_check_and_validate_boundaries() {
        let limit: usize = kani::any();
        let observed: usize = kani::any();
        match check(LimitKind::Events, limit, observed) {
            Ok(()) => assert!(observed <= limit),
            Err(err) => {
                assert!(observed > limit);
                assert_eq!(err.kind(), LimitKind::Events);
                assert_eq!(err.limit(), limit as u64);
                assert_eq!(err.observed(), observed as u64);
            }
        }

        let max_depth: usize = kani::any();
        let node_cost: usize = kani::any();
        let limits = Limits::default()
            .with_max_depth(max_depth)
            .with_node_cost_bytes(node_cost);
        assert_eq!(
            limits.is_valid(),
            max_depth <= MAX_DEPTH_CAP && node_cost > 0
        );
    }

    #[kani::proof]
    fn verify_alias_budget_charge_saturating_and_monotonic() {
        let start_derefs: usize = kani::any();
        let start_bytes: usize = kani::any();
        let max_derefs: usize = kani::any();
        let fixed_bytes: usize = kani::any();
        let max_input: usize = kani::any();
        let input_len: usize = kani::any();
        let charge_size: usize = kani::any();

        let limits = Limits::default()
            .with_max_input_bytes(max_input)
            .with_max_alias_dereferences(max_derefs)
            .with_max_alias_expansion_bytes(fixed_bytes)
            .with_alias_bytes_per_input_byte(16);

        let mut budget = AliasBudget {
            dereferences: start_derefs,
            bytes: start_bytes,
        };
        let result = budget.charge_limits(&limits, input_len, charge_size);
        assert!(budget.dereferences >= start_derefs);
        if result.is_ok() {
            assert!(budget.dereferences <= max_derefs);
            assert!(budget.bytes >= start_bytes);
            assert!(budget.bytes <= limits.expansion_budget(input_len));
        }
    }
}