feedparser-rs 0.8.0

High-performance RSS/Atom/JSON Feed parser
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
//! Parser limits to prevent `DoS` attacks and excessive memory usage

/// Single source of truth for the parser limit fields: name, builder name, default.
///
/// Invokes `$callback!` with one `docs... field, setter = default;` entry per limit.
/// Used by the core and by both language bindings so no field can be forgotten.
#[doc(hidden)]
#[macro_export]
macro_rules! __parser_limit_fields {
    ($callback:ident) => {
        $callback! {
            #[doc = " Maximum number of entries/items in a feed"]
            #[doc = ""]
            #[doc = " Prevents memory exhaustion from feeds with millions of items."]
            #[doc = " Typical feeds have 10-100 entries, large feeds may have up to 1000."]
            #[doc = ""]
            #[doc = " Default: 10,000 entries"]
            max_entries, with_max_entries = 10_000;
            #[doc = " Maximum number of links per feed (channel-level)"]
            #[doc = ""]
            #[doc = " Prevents link bombing attacks."]
            #[doc = ""]
            #[doc = " Default: 100 links"]
            max_links_per_feed, with_max_links_per_feed = 100;
            #[doc = " Maximum number of links per entry"]
            #[doc = ""]
            #[doc = " Prevents link bombing in individual entries."]
            #[doc = ""]
            #[doc = " Default: 50 links"]
            max_links_per_entry, with_max_links_per_entry = 50;
            #[doc = " Maximum number of authors per feed or entry"]
            #[doc = ""]
            #[doc = " Default: 20 authors"]
            max_authors, with_max_authors = 20;
            #[doc = " Maximum number of contributors per feed or entry"]
            #[doc = ""]
            #[doc = " Default: 20 contributors"]
            max_contributors, with_max_contributors = 20;
            #[doc = " Maximum number of tags/categories per feed or entry"]
            #[doc = ""]
            #[doc = " Default: 100 tags"]
            max_tags, with_max_tags = 100;
            #[doc = " Maximum number of content blocks per entry"]
            #[doc = ""]
            #[doc = " Atom feeds can have multiple content elements."]
            #[doc = ""]
            #[doc = " Default: 10 content blocks"]
            max_content_blocks, with_max_content_blocks = 10;
            #[doc = " Maximum number of enclosures per entry"]
            #[doc = ""]
            #[doc = " Podcast feeds typically have 1 enclosure per episode."]
            #[doc = ""]
            #[doc = " Default: 20 enclosures"]
            max_enclosures, with_max_enclosures = 20;
            #[doc = " Maximum number of XML namespaces"]
            #[doc = ""]
            #[doc = " Prevents namespace pollution attacks."]
            #[doc = ""]
            #[doc = " Default: 100 namespaces"]
            max_namespaces, with_max_namespaces = 100;
            #[doc = " Maximum XML nesting depth"]
            #[doc = ""]
            #[doc = " Prevents stack overflow from deeply nested XML."]
            #[doc = ""]
            #[doc = " Default: 100 levels"]
            max_nesting_depth, with_max_nesting_depth = 100;
            #[doc = " Maximum HTML tag nesting depth accepted by HTML sanitization"]
            #[doc = ""]
            #[doc = " The HTML sanitizer's underlying HTML5 tree builder exhibits quadratic-time"]
            #[doc = " behavior on pathologically deep tag nesting within a single text field"]
            #[doc = " (verified: multi-second slowdown from a single deeply nested `<div>`"]
            #[doc = " chain). Content nested deeper than this is escaped as plain text"]
            #[doc = " (`&lt;`/`&gt;`) instead of being run through the sanitizer, bounding"]
            #[doc = " worst-case CPU cost to linear regardless of input shape."]
            #[doc = ""]
            #[doc = " This is a safety bound, not a compatibility ceiling to be tuned up to"]
            #[doc = " match \"typical\" content: exceeding it degrades gracefully (the field's"]
            #[doc = " HTML formatting is lost, but its text content is fully preserved and"]
            #[doc = " still safely escaped) rather than dropping data or erroring, so it is"]
            #[doc = " safe to keep conservative. Legitimate feed content — even unusually"]
            #[doc = " deep block-quoted reply chains or nested tables — rarely exceeds a few"]
            #[doc = " dozen levels; 100 (50 under the strict preset) leaves headroom"]
            #[doc = " above that without leaving much headroom for abuse."]
            #[doc = ""]
            #[doc = " Default: 100 levels"]
            max_html_nesting_depth, with_max_html_nesting_depth = 100;
            #[doc = " Maximum text field length in bytes"]
            #[doc = ""]
            #[doc = " Prevents excessive memory from huge title/description fields."]
            #[doc = ""]
            #[doc = " For JSON Feed it applies to every copied string except `version`: titles,"]
            #[doc = " descriptions, summaries, content, tags and author names are truncated,"]
            #[doc = " while identifiers, URLs, dates, types, language tags and extensions with"]
            #[doc = " an over-long key are dropped, without setting `bozo`."]
            #[doc = ""]
            #[doc = " It also bounds the per-value serialized size of a captured JSON Feed"]
            #[doc = " extension object (see the JSON Feed extension count limit) and its node count, to the larger of"]
            #[doc = " 1024 and this text length divided by the size of a `serde_json::Value`."]
            #[doc = " Every scalar, array and object is one node, and each object"]
            #[doc = " member adds weight for its key and slot (more for the first one, which"]
            #[doc = " allocates). A value over either bound is dropped entirely rather than truncated."]
            #[doc = ""]
            #[doc = " Default: 10 MB"]
            max_text_length, with_max_text_length = 10 * 1024 * 1024;
            #[doc = " Maximum total feed size in bytes"]
            #[doc = ""]
            #[doc = " The entire feed must fit within this limit."]
            #[doc = ""]
            #[doc = " Default: 100 MB"]
            max_feed_size_bytes, with_max_feed_size_bytes = 100 * 1024 * 1024;
            #[doc = " Maximum attribute value length in bytes"]
            #[doc = ""]
            #[doc = " XML attributes should be reasonably sized."]
            #[doc = ""]
            #[doc = " Default: 64 KB"]
            max_attribute_length, with_max_attribute_length = 64 * 1024;
            #[doc = " Maximum number of podcast soundbites per entry"]
            #[doc = ""]
            #[doc = " Podcast 2.0 soundbite elements for shareable clips."]
            #[doc = ""]
            #[doc = " Default: 10 soundbites"]
            max_podcast_soundbites, with_max_podcast_soundbites = 10;
            #[doc = " Maximum number of podcast transcripts per entry"]
            #[doc = ""]
            #[doc = " Podcast 2.0 transcript elements."]
            #[doc = ""]
            #[doc = " Default: 20 transcripts"]
            max_podcast_transcripts, with_max_podcast_transcripts = 20;
            #[doc = " Maximum number of podcast funding elements per feed"]
            #[doc = ""]
            #[doc = " Podcast 2.0 funding elements for donation links."]
            #[doc = ""]
            #[doc = " Default: 20 funding elements"]
            max_podcast_funding, with_max_podcast_funding = 20;
            #[doc = " Maximum number of podcast person elements per entry"]
            #[doc = ""]
            #[doc = " Podcast 2.0 person elements for hosts, guests, etc."]
            #[doc = ""]
            #[doc = " Default: 50 persons"]
            max_podcast_persons, with_max_podcast_persons = 50;
            #[doc = " Maximum number of podcast value recipients per feed"]
            #[doc = ""]
            #[doc = " Podcast 2.0 value recipients for payment splitting."]
            #[doc = " Prevents `DoS` from feeds with excessive recipient lists."]
            #[doc = ""]
            #[doc = " Default: 20 recipients"]
            max_value_recipients, with_max_value_recipients = 20;
            #[doc = " Maximum number of alternate enclosures per entry"]
            #[doc = ""]
            #[doc = " Default: 20"]
            max_podcast_alternate_enclosures, with_max_podcast_alternate_enclosures = 20;
            #[doc = " Maximum number of sources per alternate enclosure"]
            #[doc = ""]
            #[doc = " Default: 10"]
            max_podcast_alternate_enclosure_sources, with_max_podcast_alternate_enclosure_sources = 10;
            #[doc = " Maximum number of podroll entries per feed"]
            #[doc = ""]
            #[doc = " Default: 50"]
            max_podcast_podroll, with_max_podcast_podroll = 50;
            #[doc = " Maximum number of socialInteract elements per entry"]
            #[doc = ""]
            #[doc = " Default: 20"]
            max_podcast_social_interact, with_max_podcast_social_interact = 20;
            #[doc = " Maximum number of txt records per feed or entry"]
            #[doc = ""]
            #[doc = " Default: 20"]
            max_podcast_txt, with_max_podcast_txt = 20;
            #[doc = " Maximum number of follow links per feed or entry"]
            #[doc = ""]
            #[doc = " Default: 20"]
            max_podcast_follow, with_max_podcast_follow = 20;
            #[doc = " Maximum number of chat references per feed or entry"]
            #[doc = ""]
            #[doc = " Podcast 2.0 chat elements pointing to chat rooms/servers."]
            #[doc = ""]
            #[doc = " Default: 20"]
            max_podcast_chat, with_max_podcast_chat = 20;
            #[doc = " Maximum number of value time splits per `podcast:value` element"]
            #[doc = ""]
            #[doc = " Podcast 2.0 valueTimeSplit elements for routing payments over time"]
            #[doc = " ranges. Prevents `DoS` from feeds with excessive split lists."]
            #[doc = ""]
            #[doc = " Default: 20"]
            max_podcast_value_time_splits, with_max_podcast_value_time_splits = 20;
            #[doc = " Maximum number of JSON Feed extension objects captured per scope"]
            #[doc = ""]
            #[doc = " JSON Feed permits custom object keys (starting with `_` followed by a"]
            #[doc = " letter) anywhere in a feed; this bounds how many distinct keys are"]
            #[doc = " captured per feed-root or item-root scope, counted independently. When a"]
            #[doc = " scope has more extension keys than this limit, the surviving keys are the"]
            #[doc = " alphabetically-first ones, not the document-order-first ones: `serde_json`"]
            #[doc = " backs a JSON object with a `BTreeMap` by default (the `preserve_order`"]
            #[doc = " feature, which would switch it to an `IndexMap` and make truncation"]
            #[doc = " document-order-first, is not enabled)."]
            #[doc = ""]
            #[doc = " Default: 100"]
            max_json_extensions, with_max_json_extensions = 100;
            #[doc = " Maximum estimated memory, in bytes, retained by all captured JSON Feed"]
            #[doc = " extensions of one document"]
            #[doc = ""]
            #[doc = " The extension count limit and the text length limit bound each scope and value, but"]
            #[doc = " not their number across items. The estimate counts keys, strings and weighted"]
            #[doc = " nodes. Values are admitted in document order: a value that does not fit in"]
            #[doc = " what is left is dropped, without setting `bozo`. A single value can need about"]
            #[doc = " twice the text length limit, so raise both together."]
            #[doc = ""]
            #[doc = " Default: 32 MB"]
            max_json_extension_memory_bytes, with_max_json_extension_memory_bytes = 32 * 1024 * 1024;
            #[doc = " Maximum number of points kept per `GeoRSS` or GML geometry"]
            #[doc = ""]
            #[doc = " Caps the coordinate list of a line, polygon, point or box read from `GeoRSS`"]
            #[doc = " Simple or GML elements. The coordinate text itself stays bounded by the text"]
            #[doc = " length limit. Excess points are dropped without setting `bozo`, so a polygon may"]
            #[doc = " be left unclosed. A geometry left with fewer points than its kind needs (1 for"]
            #[doc = " a point, 2 for a line or box, 3 for a polygon) is dropped. W3C Basic Geo"]
            #[doc = " latitude/longitude pairs always have one point and are not capped."]
            #[doc = ""]
            #[doc = " Default: 10,000 points"]
            max_geo_points, with_max_geo_points = 10_000;
        }
    };
}

macro_rules! define_parser_limits {
    ($($(#[doc = $doc:literal])* $field:ident, $setter:ident = $default:expr;)+) => {
        /// Parser limits for protecting against denial-of-service attacks
        ///
        /// These limits prevent malicious or malformed feeds from causing excessive
        /// memory allocation, deep recursion, or other resource exhaustion issues.
        /// Every field has a `with_*` builder that replaces only that limit.
        ///
        /// # Examples
        ///
        /// ```
        /// use feedparser_rs::ParserLimits;
        ///
        /// let limits = ParserLimits::default();
        /// assert_eq!(limits.max_entries, 10_000);
        ///
        /// // Custom limits for restricted environments
        /// let strict = ParserLimits::default()
        ///     .with_max_entries(1_000)
        ///     .with_max_feed_size_bytes(10 * 1024 * 1024); // 10MB
        /// assert_eq!(strict.max_entries, 1_000);
        ///
        /// // A value over `max_json_extension_memory_bytes` is dropped without `bozo`
        /// let limits = ParserLimits::default().with_max_json_extension_memory_bytes(0);
        /// let data = br#"{"version":"https://jsonfeed.org/version/1.1","_x":1}"#;
        /// let feed = feedparser_rs::parse_with_limits(data, limits)?;
        /// assert!(feed.feed.json_extensions.is_empty());
        /// assert!(!feed.bozo);
        /// # Ok::<(), feedparser_rs::FeedError>(())
        /// ```
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        #[non_exhaustive]
        pub struct ParserLimits {
            $(
                $(#[doc = $doc])*
                pub $field: usize,
            )+
        }

        impl Default for ParserLimits {
            /// Creates default parser limits suitable for general use
            ///
            /// These defaults are conservative and should work for most feeds,
            /// including large podcast feeds and news aggregators.
            fn default() -> Self {
                Self { $($field: $default,)+ }
            }
        }

        impl ParserLimits {
            $(
                #[doc = concat!("Returns a copy with `", stringify!($field), "` replaced.")]
                #[must_use]
                pub const fn $setter(mut self, value: usize) -> Self {
                    self.$field = value;
                    self
                }
            )+
        }
    };
}

__parser_limit_fields!(define_parser_limits);

impl ParserLimits {
    /// Creates strict limits for resource-constrained environments
    ///
    /// Use this for embedded systems or when parsing untrusted feeds
    /// with minimal resources.
    ///
    /// # Examples
    ///
    /// ```
    /// use feedparser_rs::ParserLimits;
    ///
    /// let limits = ParserLimits::strict();
    /// assert_eq!(limits.max_entries, 1_000);
    /// ```
    #[must_use]
    pub const fn strict() -> Self {
        Self {
            max_entries: 1_000,
            max_links_per_feed: 20,
            max_links_per_entry: 10,
            max_authors: 5,
            max_contributors: 5,
            max_tags: 20,
            max_content_blocks: 3,
            max_enclosures: 5,
            max_namespaces: 20,
            max_nesting_depth: 50,
            max_html_nesting_depth: 50,
            max_text_length: 1024 * 1024,          // 1 MB
            max_feed_size_bytes: 10 * 1024 * 1024, // 10 MB
            max_attribute_length: 8 * 1024,        // 8 KB
            max_podcast_soundbites: 5,
            max_podcast_transcripts: 5,
            max_podcast_funding: 5,
            max_podcast_persons: 10,
            max_value_recipients: 5,
            max_podcast_alternate_enclosures: 5,
            max_podcast_alternate_enclosure_sources: 3,
            max_podcast_podroll: 10,
            max_podcast_social_interact: 5,
            max_podcast_txt: 5,
            max_podcast_follow: 5,
            max_podcast_chat: 5,
            max_podcast_value_time_splits: 5,
            max_json_extensions: 20,
            max_json_extension_memory_bytes: 4 * 1024 * 1024, // 4 MB
            max_geo_points: 1_000,
        }
    }

    /// Creates permissive limits for trusted feeds
    ///
    /// Use this only for feeds from trusted sources where you expect
    /// large data volumes (e.g., feed archives).
    ///
    /// # Examples
    ///
    /// ```
    /// use feedparser_rs::ParserLimits;
    ///
    /// let limits = ParserLimits::permissive();
    /// assert_eq!(limits.max_entries, 100_000);
    /// ```
    #[must_use]
    pub const fn permissive() -> Self {
        Self {
            max_entries: 100_000,
            max_links_per_feed: 500,
            max_links_per_entry: 200,
            max_authors: 100,
            max_contributors: 100,
            max_tags: 500,
            max_content_blocks: 50,
            max_enclosures: 100,
            max_namespaces: 500,
            max_nesting_depth: 200,
            max_html_nesting_depth: 200,
            max_text_length: 50 * 1024 * 1024,      // 50 MB
            max_feed_size_bytes: 500 * 1024 * 1024, // 500 MB
            max_attribute_length: 256 * 1024,       // 256 KB
            max_podcast_soundbites: 50,
            max_podcast_transcripts: 100,
            max_podcast_funding: 50,
            max_podcast_persons: 200,
            max_value_recipients: 50,
            max_podcast_alternate_enclosures: 100,
            max_podcast_alternate_enclosure_sources: 50,
            max_podcast_podroll: 200,
            max_podcast_social_interact: 100,
            max_podcast_txt: 100,
            max_podcast_follow: 100,
            max_podcast_chat: 100,
            max_podcast_value_time_splits: 50,
            max_json_extensions: 500,
            max_json_extension_memory_bytes: 256 * 1024 * 1024, // 256 MB
            max_geo_points: 100_000,
        }
    }

    /// Validates that a feed size is within limits
    ///
    /// Call this before starting to parse a feed.
    ///
    /// # Errors
    ///
    /// Returns an error if the feed exceeds `max_feed_size_bytes`.
    pub const fn check_feed_size(&self, size: usize) -> Result<(), LimitError> {
        if size > self.max_feed_size_bytes {
            Err(LimitError::FeedTooLarge {
                size,
                max: self.max_feed_size_bytes,
            })
        } else {
            Ok(())
        }
    }

    /// Validates that a collection size is within limits
    ///
    /// Use this during parsing to check collection sizes.
    ///
    /// # Errors
    ///
    /// Returns an error if the collection size exceeds the specified limit.
    pub const fn check_collection_size(
        &self,
        current: usize,
        limit: usize,
        name: &'static str,
    ) -> Result<(), LimitError> {
        if current >= limit {
            Err(LimitError::CollectionTooLarge {
                name,
                size: current,
                max: limit,
            })
        } else {
            Ok(())
        }
    }

    /// Validates XML nesting depth
    ///
    /// # Errors
    ///
    /// Returns an error if nesting depth exceeds `max_nesting_depth`.
    pub const fn check_nesting_depth(&self, depth: usize) -> Result<(), LimitError> {
        if depth > self.max_nesting_depth {
            Err(LimitError::NestingTooDeep {
                depth,
                max: self.max_nesting_depth,
            })
        } else {
            Ok(())
        }
    }

    /// Validates text field length
    ///
    /// # Errors
    ///
    /// Returns an error if text length exceeds `max_text_length`.
    pub const fn check_text_length(&self, length: usize) -> Result<(), LimitError> {
        if length > self.max_text_length {
            Err(LimitError::TextTooLong {
                length,
                max: self.max_text_length,
            })
        } else {
            Ok(())
        }
    }
}

/// Errors that occur when parser limits are exceeded
#[expect(
    missing_docs,
    reason = "variant fields are described by the `#[error]` messages"
)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum LimitError {
    /// Feed size exceeds maximum allowed
    #[error("Feed size ({size} bytes) exceeds maximum ({max} bytes)")]
    FeedTooLarge { size: usize, max: usize },

    /// Collection (entries, links, etc.) has too many items
    #[error("Collection '{name}' has {size} items, exceeds maximum ({max})")]
    CollectionTooLarge {
        name: &'static str,
        size: usize,
        max: usize,
    },

    /// XML nesting is too deep
    #[error("XML nesting depth ({depth}) exceeds maximum ({max})")]
    NestingTooDeep { depth: usize, max: usize },

    /// Text field is too long
    #[error("Text field length ({length} bytes) exceeds maximum ({max} bytes)")]
    TextTooLong { length: usize, max: usize },
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::assert_matches;

    #[test]
    fn test_default_limits() {
        let limits = ParserLimits::default();
        assert_eq!(limits.max_entries, 10_000);
        assert_eq!(limits.max_feed_size_bytes, 100 * 1024 * 1024);
    }

    #[test]
    fn test_strict_limits() {
        let limits = ParserLimits::strict();
        assert_eq!(limits.max_entries, 1_000);
        assert!(limits.max_entries < ParserLimits::default().max_entries);
    }

    #[test]
    fn test_permissive_limits() {
        let limits = ParserLimits::permissive();
        assert_eq!(limits.max_entries, 100_000);
        assert!(limits.max_entries > ParserLimits::default().max_entries);
    }

    #[test]
    fn test_check_feed_size_ok() {
        let limits = ParserLimits::default();
        assert!(limits.check_feed_size(1024).is_ok());
    }

    #[test]
    fn test_check_feed_size_too_large() {
        let limits = ParserLimits::default();
        let result = limits.check_feed_size(200 * 1024 * 1024);
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::FeedTooLarge { .. }));
    }

    #[test]
    fn test_check_collection_size_ok() {
        let limits = ParserLimits::default();
        assert!(
            limits
                .check_collection_size(50, limits.max_entries, "entries")
                .is_ok()
        );
    }

    #[test]
    fn test_check_collection_size_too_large() {
        let limits = ParserLimits::default();
        let result = limits.check_collection_size(10_001, limits.max_entries, "entries");
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
    }

    #[test]
    fn test_check_nesting_depth_ok() {
        let limits = ParserLimits::default();
        assert!(limits.check_nesting_depth(50).is_ok());
    }

    #[test]
    fn test_check_nesting_depth_too_deep() {
        let limits = ParserLimits::default();
        let result = limits.check_nesting_depth(101);
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::NestingTooDeep { .. }));
    }

    #[test]
    fn test_check_text_length_ok() {
        let limits = ParserLimits::default();
        assert!(limits.check_text_length(1024).is_ok());
    }

    #[test]
    fn test_check_text_length_too_long() {
        let limits = ParserLimits::default();
        let result = limits.check_text_length(20 * 1024 * 1024);
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::TextTooLong { .. }));
    }

    #[test]
    fn test_limit_error_display() {
        let err = LimitError::FeedTooLarge {
            size: 200_000_000,
            max: 100_000_000,
        };
        let msg = err.to_string();
        assert!(msg.contains("200000000"));
        assert!(msg.contains("100000000"));
    }

    #[test]
    fn test_max_value_recipients_default() {
        let limits = ParserLimits::default();
        assert_eq!(limits.max_value_recipients, 20);
    }

    #[test]
    fn test_max_value_recipients_strict() {
        let limits = ParserLimits::strict();
        assert_eq!(limits.max_value_recipients, 5);
        assert!(limits.max_value_recipients < ParserLimits::default().max_value_recipients);
    }

    #[test]
    fn test_max_value_recipients_permissive() {
        let limits = ParserLimits::permissive();
        assert_eq!(limits.max_value_recipients, 50);
        assert!(limits.max_value_recipients > ParserLimits::default().max_value_recipients);
    }

    #[test]
    fn test_value_recipients_limit_enforcement() {
        let limits = ParserLimits::default();

        // Within limit
        assert!(
            limits
                .check_collection_size(19, limits.max_value_recipients, "value_recipients")
                .is_ok()
        );

        // At limit
        assert!(
            limits
                .check_collection_size(20, limits.max_value_recipients, "value_recipients")
                .is_err()
        );

        // Exceeds limit
        let result =
            limits.check_collection_size(21, limits.max_value_recipients, "value_recipients");
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
    }

    #[test]
    fn test_max_podcast_chat_tiers() {
        assert_eq!(ParserLimits::default().max_podcast_chat, 20);
        assert_eq!(ParserLimits::strict().max_podcast_chat, 5);
        assert_eq!(ParserLimits::permissive().max_podcast_chat, 100);
        assert!(ParserLimits::strict().max_podcast_chat < ParserLimits::default().max_podcast_chat);
        assert!(
            ParserLimits::permissive().max_podcast_chat > ParserLimits::default().max_podcast_chat
        );
    }

    #[test]
    fn test_podcast_chat_limit_enforcement() {
        let limits = ParserLimits::default();
        assert!(
            limits
                .check_collection_size(19, limits.max_podcast_chat, "chat")
                .is_ok()
        );
        let result = limits.check_collection_size(20, limits.max_podcast_chat, "chat");
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
    }

    #[test]
    fn test_max_podcast_value_time_splits_tiers() {
        assert_eq!(ParserLimits::default().max_podcast_value_time_splits, 20);
        assert_eq!(ParserLimits::strict().max_podcast_value_time_splits, 5);
        assert_eq!(ParserLimits::permissive().max_podcast_value_time_splits, 50);
        assert!(
            ParserLimits::strict().max_podcast_value_time_splits
                < ParserLimits::default().max_podcast_value_time_splits
        );
        assert!(
            ParserLimits::permissive().max_podcast_value_time_splits
                > ParserLimits::default().max_podcast_value_time_splits
        );
    }

    #[test]
    fn test_podcast_value_time_splits_limit_enforcement() {
        let limits = ParserLimits::default();
        assert!(
            limits
                .check_collection_size(19, limits.max_podcast_value_time_splits, "time_splits")
                .is_ok()
        );
        let result =
            limits.check_collection_size(20, limits.max_podcast_value_time_splits, "time_splits");
        assert!(result.is_err());
        assert_matches!(result, Err(LimitError::CollectionTooLarge { .. }));
    }

    #[test]
    fn test_max_json_extension_memory_tiers() {
        let tiers = [
            ParserLimits::strict(),
            ParserLimits::default(),
            ParserLimits::permissive(),
        ];
        assert!(tiers.is_sorted_by_key(|limits| limits.max_json_extension_memory_bytes));
        // One value of the largest allowed size must fit.
        for limits in tiers {
            assert!(limits.max_json_extension_memory_bytes >= 2 * limits.max_text_length);
        }
    }

    #[test]
    fn test_max_json_extensions_tiers() {
        assert_eq!(ParserLimits::default().max_json_extensions, 100);
        assert_eq!(ParserLimits::strict().max_json_extensions, 20);
        assert_eq!(ParserLimits::permissive().max_json_extensions, 500);
        assert!(
            ParserLimits::strict().max_json_extensions
                < ParserLimits::default().max_json_extensions
        );
        assert!(
            ParserLimits::permissive().max_json_extensions
                > ParserLimits::default().max_json_extensions
        );
    }
}