form-net 0.3.0

Sans-IO form parsing for Rust: application/x-www-form-urlencoded and streaming multipart/form-data, with budgets checked before allocation, safe upload spilling, and typed extraction. No third-party dependencies.
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
//! Budgets ([`Limits`]) and behaviours ([`Policy`]).
//!
//! Both are small `Copy` values with `const` setters, so a route's
//! configuration is a `const` checked once at startup.

use crate::error::{FormError, Limit};

/// The bytes the multipart parser keeps for the `_charset_` field's value.
pub(crate) const CHARSET_CAPTURE: usize = 32;

/// Every budget form-net enforces.
///
/// Each budget is checked before the bytes it governs are buffered, stored,
/// or passed on. A limit of 0 means none allowed. A limit larger than the one
/// containing it is capped by it (the effective value is the smaller), so a
/// route sets only the limits it cares about.
///
/// | Field | Default |
/// |---|---|
/// | `max_body_bytes` | 10 MiB |
/// | `max_fields` | 1,000 |
/// | `max_name_bytes` | 256 |
/// | `max_value_bytes` | 1 MiB |
/// | `max_text_bytes` | 2 MiB |
/// | `max_parts` | 100 |
/// | `max_files` | 20 |
/// | `max_file_bytes` | 10 MiB |
/// | `max_part_header_bytes` | 8 KiB |
/// | `max_part_headers` | 8 |
/// | `max_filename_bytes` | 1,024 |
/// | `max_preamble_bytes` | 1 KiB |
/// | `max_epilogue_bytes` | 1 KiB |
/// | `max_padding_bytes` | 32 |
/// | `sniff_bytes` | 0 |
/// | `max_token_bytes` | 128 |
///
/// # Examples
///
/// ```
/// use form_net::Limits;
///
/// // A login route: a small body, a few fields, no files.
/// const LOGIN: Limits = Limits::DEFAULT
///     .with_max_body_bytes(4 * 1024)
///     .with_max_fields(8)
///     .with_max_files(0);
/// assert!(LOGIN.validate().is_ok());
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
    /// Every byte fed, both formats, preamble and epilogue included.
    pub max_body_bytes: u64,
    /// urlencoded pairs; multipart text fields.
    pub max_fields: u32,
    /// Raw (encoded) name length. Capped by `max_body_bytes`.
    pub max_name_bytes: u32,
    /// One urlencoded value or one multipart text field. Capped by
    /// `max_text_bytes`.
    pub max_value_bytes: u32,
    /// All text values of one body together. Capped by `max_body_bytes`.
    pub max_text_bytes: u64,
    /// Multipart parts of either kind.
    pub max_parts: u32,
    /// Multipart file parts.
    pub max_files: u32,
    /// One file part. Capped by `max_body_bytes`.
    pub max_file_bytes: u64,
    /// One part's header block, CRLF CRLF included (at least 64).
    pub max_part_header_bytes: u32,
    /// Header lines per part.
    pub max_part_headers: u16,
    /// A raw `filename`, or a decoded `filename*`. Capped by
    /// `max_part_header_bytes`.
    pub max_filename_bytes: u32,
    /// Bytes before the first delimiter. Capped by `max_body_bytes`.
    pub max_preamble_bytes: u32,
    /// Bytes after the close delimiter. Capped by `max_body_bytes`.
    pub max_epilogue_bytes: u32,
    /// Transport padding after a delimiter.
    pub max_padding_bytes: u8,
    /// The sniff window per file part (0: off). Capped by `max_file_bytes`.
    pub sniff_bytes: u32,
    /// The captured anti-forgery token. Capped by `max_value_bytes`.
    pub max_token_bytes: u16,
}

macro_rules! setter {
    ($(#[$doc:meta])* $name:ident, $field:ident, $ty:ty) => {
        $(#[$doc])*
        #[must_use]
        pub const fn $name(mut self, value: $ty) -> Self {
            self.$field = value;
            self
        }
    };
}

const fn min_u64(a: u64, b: u64) -> u64 {
    if a < b { a } else { b }
}

/// `value` as `usize`, or `usize::MAX` when it does not fit.
const fn to_usize(value: u64) -> usize {
    if value > usize::MAX as u64 {
        usize::MAX
    } else {
        value as usize
    }
}

const fn add_usize(a: usize, b: usize) -> usize {
    match a.checked_add(b) {
        Some(v) => v,
        None => usize::MAX,
    }
}

impl Limits {
    /// The defaults in the table above.
    pub const DEFAULT: Limits = Limits {
        max_body_bytes: 10 * 1024 * 1024,
        max_fields: 1_000,
        max_name_bytes: 256,
        max_value_bytes: 1024 * 1024,
        max_text_bytes: 2 * 1024 * 1024,
        max_parts: 100,
        max_files: 20,
        max_file_bytes: 10 * 1024 * 1024,
        max_part_header_bytes: 8 * 1024,
        max_part_headers: 8,
        max_filename_bytes: 1_024,
        max_preamble_bytes: 1_024,
        max_epilogue_bytes: 1_024,
        max_padding_bytes: 32,
        sniff_bytes: 0,
        max_token_bytes: 128,
    };

    setter!(
        /// Sets `max_body_bytes`.
        with_max_body_bytes, max_body_bytes, u64);
    setter!(
        /// Sets `max_fields`.
        with_max_fields, max_fields, u32);
    setter!(
        /// Sets `max_name_bytes`.
        with_max_name_bytes, max_name_bytes, u32);
    setter!(
        /// Sets `max_value_bytes`.
        with_max_value_bytes, max_value_bytes, u32);
    setter!(
        /// Sets `max_text_bytes`.
        with_max_text_bytes, max_text_bytes, u64);
    setter!(
        /// Sets `max_parts`.
        with_max_parts, max_parts, u32);
    setter!(
        /// Sets `max_files`.
        with_max_files, max_files, u32);
    setter!(
        /// Sets `max_file_bytes`.
        with_max_file_bytes, max_file_bytes, u64);
    setter!(
        /// Sets `max_part_header_bytes`.
        with_max_part_header_bytes, max_part_header_bytes, u32);
    setter!(
        /// Sets `max_part_headers`.
        with_max_part_headers, max_part_headers, u16);
    setter!(
        /// Sets `max_filename_bytes`.
        with_max_filename_bytes, max_filename_bytes, u32);
    setter!(
        /// Sets `max_preamble_bytes`.
        with_max_preamble_bytes, max_preamble_bytes, u32);
    setter!(
        /// Sets `max_epilogue_bytes`.
        with_max_epilogue_bytes, max_epilogue_bytes, u32);
    setter!(
        /// Sets `max_padding_bytes`.
        with_max_padding_bytes, max_padding_bytes, u8);
    setter!(
        /// Sets `sniff_bytes`.
        with_sniff_bytes, sniff_bytes, u32);
    setter!(
        /// Sets `max_token_bytes`.
        with_max_token_bytes, max_token_bytes, u16);

    /// Refuses the values no body could satisfy, so a misconfiguration is
    /// found at startup: a `max_part_header_bytes` below 64 (the shortest
    /// useful `Content-Disposition` line must fit), or buffer sizes that do
    /// not fit in `usize`. Every parser constructor and every `*_with`
    /// function calls it.
    ///
    /// # Errors
    ///
    /// [`FormError::InvalidLimits`] naming the refused field.
    ///
    /// # Examples
    ///
    /// ```
    /// use form_net::Limits;
    ///
    /// assert!(Limits::DEFAULT.validate().is_ok());
    /// let broken = Limits::DEFAULT.with_max_part_header_bytes(16);
    /// assert_eq!(broken.validate().unwrap_err().code(), "invalid_limits");
    /// ```
    pub fn validate(&self) -> Result<(), FormError> {
        if self.max_part_header_bytes < 64 {
            return Err(FormError::InvalidLimits {
                limit: Limit::PartHeaderBytes,
            });
        }
        let parts = [
            u64::from(self.max_part_header_bytes),
            u64::from(self.name()),
            u64::from(self.filename()),
            u64::from(self.token()),
            CHARSET_CAPTURE as u64,
        ];
        let total = parts.iter().fold(0u64, |a, &b| a.saturating_add(b));
        if total > usize::MAX as u64 {
            return Err(FormError::InvalidLimits {
                limit: Limit::PartHeaderBytes,
            });
        }
        let url = u64::from(self.name())
            .saturating_add(u64::from(self.value()))
            .saturating_add(1);
        if url > usize::MAX as u64 {
            return Err(FormError::InvalidLimits {
                limit: Limit::ValueLength,
            });
        }
        Ok(())
    }

    /// Validates these limits together with a policy: a token field with an
    /// effective `max_token_bytes` of 0 can never be captured.
    pub(crate) fn validate_with(&self, policy: &crate::Policy) -> Result<(), FormError> {
        self.validate()?;
        if policy.token_field.is_some() && self.token() == 0 {
            return Err(FormError::InvalidLimits {
                limit: Limit::TokenLength,
            });
        }
        Ok(())
    }

    /// The buffer length the multipart parser needs with these limits and
    /// this policy: the header block, the decoded field name, the decoded
    /// `filename*` (only under `ExtendedFilenamePolicy::AcceptAlone`), the
    /// token (only with a token field), and 32 bytes for `_charset_`.
    ///
    /// A `const fn`, so a stack buffer can be sized at compile time.
    ///
    /// # Examples
    ///
    /// ```
    /// use form_net::{Limits, Policy};
    ///
    /// const LIMITS: Limits = Limits::DEFAULT.with_max_part_header_bytes(1024);
    /// const LEN: usize = LIMITS.multipart_buffer_len(&Policy::DEFAULT);
    /// assert_eq!(LEN, 1024 + 256 + 32);
    /// let buffer = [0u8; LEN];
    /// ```
    #[must_use]
    pub const fn multipart_buffer_len(&self, policy: &crate::Policy) -> usize {
        let mut len = add_usize(self.max_part_header_bytes as usize, self.name() as usize);
        if matches!(
            policy.extended_filename,
            crate::ExtendedFilenamePolicy::AcceptAlone
        ) {
            len = add_usize(len, self.filename() as usize);
        }
        if policy.token_field.is_some() {
            len = add_usize(len, self.token() as usize);
        }
        add_usize(len, CHARSET_CAPTURE)
    }

    /// The scratch length the streaming urlencoded parser needs:
    /// `max_name_bytes + max_value_bytes + 1` (effective values).
    ///
    /// # Examples
    ///
    /// ```
    /// use form_net::Limits;
    ///
    /// const LIMITS: Limits = Limits::DEFAULT.with_max_text_bytes(1000);
    /// assert_eq!(LIMITS.urlencoded_buffer_len(), 256 + 1000 + 1);
    /// ```
    #[must_use]
    pub const fn urlencoded_buffer_len(&self) -> usize {
        add_usize(add_usize(self.name() as usize, self.value() as usize), 1)
    }

    // Effective values: each capped by the limit that contains it.

    pub(crate) const fn body(&self) -> u64 {
        self.max_body_bytes
    }

    pub(crate) const fn text(&self) -> u64 {
        min_u64(self.max_text_bytes, self.body())
    }

    pub(crate) const fn value(&self) -> u32 {
        min_u64(self.max_value_bytes as u64, self.text()) as u32
    }

    pub(crate) const fn name(&self) -> u32 {
        min_u64(self.max_name_bytes as u64, self.body()) as u32
    }

    pub(crate) const fn file(&self) -> u64 {
        min_u64(self.max_file_bytes, self.body())
    }

    pub(crate) const fn filename(&self) -> u32 {
        min_u64(
            self.max_filename_bytes as u64,
            self.max_part_header_bytes as u64,
        ) as u32
    }

    pub(crate) const fn token(&self) -> u16 {
        min_u64(self.max_token_bytes as u64, self.value() as u64) as u16
    }

    pub(crate) const fn preamble(&self) -> u64 {
        min_u64(self.max_preamble_bytes as u64, self.body())
    }

    pub(crate) const fn epilogue(&self) -> u64 {
        min_u64(self.max_epilogue_bytes as u64, self.body())
    }

    pub(crate) const fn body_usize(&self) -> usize {
        to_usize(self.body())
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// The behaviours a route may choose. The defaults are the strict ones;
/// every alternative is named after what it allows.
///
/// # Examples
///
/// ```
/// use form_net::{EmptyFilePolicy, HeaderPolicy, Policy, TokenField};
///
/// const UPLOADS: Policy = Policy::DEFAULT
///     .with_token_field(TokenField::new("csrf_token"))
///     .with_empty_files(EmptyFilePolicy::Skip)
///     .with_unknown_headers(HeaderPolicy::Refuse);
/// assert_eq!(UPLOADS.token_field.map(|t| t.name()), Some("csrf_token"));
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Policy {
    /// A malformed `%` in urlencoded input. Default `Refuse`.
    pub percent: PercentPolicy,
    /// `filename*` in a part. Default `Refuse`.
    pub extended_filename: ExtendedFilenamePolicy,
    /// Part headers other than the three known ones. Default `Ignore`.
    pub unknown_headers: HeaderPolicy,
    /// A file input left empty. Default `Report`.
    pub empty_files: EmptyFilePolicy,
    /// The anti-forgery token field to capture. Default none.
    pub token_field: Option<TokenField>,
}

impl Policy {
    /// The strict defaults.
    pub const DEFAULT: Policy = Policy {
        percent: PercentPolicy::Refuse,
        extended_filename: ExtendedFilenamePolicy::Refuse,
        unknown_headers: HeaderPolicy::Ignore,
        empty_files: EmptyFilePolicy::Report,
        token_field: None,
    };

    /// Sets `percent`.
    #[must_use]
    pub const fn with_percent(mut self, policy: PercentPolicy) -> Self {
        self.percent = policy;
        self
    }

    /// Sets `extended_filename`.
    #[must_use]
    pub const fn with_extended_filename(mut self, policy: ExtendedFilenamePolicy) -> Self {
        self.extended_filename = policy;
        self
    }

    /// Sets `unknown_headers`.
    #[must_use]
    pub const fn with_unknown_headers(mut self, policy: HeaderPolicy) -> Self {
        self.unknown_headers = policy;
        self
    }

    /// Sets `empty_files`.
    #[must_use]
    pub const fn with_empty_files(mut self, policy: EmptyFilePolicy) -> Self {
        self.empty_files = policy;
        self
    }

    /// Sets the token field to capture.
    #[must_use]
    pub const fn with_token_field(mut self, field: TokenField) -> Self {
        self.token_field = Some(field);
        self
    }
}

impl Default for Policy {
    fn default() -> Self {
        Self::DEFAULT
    }
}

/// What a `%` not followed by two hex digits means in urlencoded input.
///
/// # Examples
///
/// ```
/// use form_net::{decode_into, PercentPolicy};
///
/// let mut out = [0u8; 8];
/// assert!(decode_into(b"100%", &mut out, PercentPolicy::Refuse).is_err());
/// assert_eq!(decode_into(b"100%", &mut out, PercentPolicy::Literal)?, "100%");
/// # Ok::<(), form_net::FormError>(())
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PercentPolicy {
    /// Refuse it (default).
    Refuse,
    /// Keep it as a literal byte, as WHATWG percent-decode does.
    Literal,
}

/// What a `filename*` parameter (RFC 8187) in a part means. Browsers never
/// send it; RFC 7578 forbids senders from using it.
///
/// Both `filename` and `filename*` in one part are refused under every
/// policy.
///
/// # Examples
///
/// ```
/// use form_net::{ExtendedFilenamePolicy, Policy};
///
/// let accept = Policy::DEFAULT.with_extended_filename(ExtendedFilenamePolicy::AcceptAlone);
/// assert_eq!(Policy::DEFAULT.extended_filename, ExtendedFilenamePolicy::Refuse);
/// assert_ne!(accept, Policy::DEFAULT);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExtendedFilenamePolicy {
    /// Refuse any `filename*` (default).
    Refuse,
    /// Accept and decode it (UTF-8 only) when it is the only file name.
    AcceptAlone,
    /// Drop it; a part with only `filename*` is then a text field.
    Ignore,
}

/// Part headers other than `Content-Disposition`, `Content-Type`, and
/// `Content-Transfer-Encoding`.
///
/// # Examples
///
/// ```
/// use form_net::{HeaderPolicy, Policy};
///
/// assert_eq!(Policy::DEFAULT.unknown_headers, HeaderPolicy::Ignore);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HeaderPolicy {
    /// Skip them, as RFC 7578 section 4.8 requires (default). They still
    /// count toward the header budgets.
    Ignore,
    /// Refuse them.
    Refuse,
}

/// A file input left empty (`filename=""` and no data).
///
/// # Examples
///
/// ```
/// use form_net::{EmptyFilePolicy, Policy};
///
/// assert_eq!(Policy::DEFAULT.empty_files, EmptyFilePolicy::Report);
/// ```
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EmptyFilePolicy {
    /// Report it as a file part with an empty file name (default).
    Report,
    /// Produce nothing for it; it does not count against `max_files`.
    Skip,
}

/// The anti-forgery token field to capture from a multipart body.
///
/// # Examples
///
/// ```
/// use form_net::{TokenField, TokenPlacement};
///
/// let strict = TokenField::new("csrf_token");
/// assert_eq!(strict.placement(), TokenPlacement::BeforeFirstFile);
/// assert_eq!(strict.anywhere().placement(), TokenPlacement::Anywhere);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TokenField {
    name: &'static str,
    placement: TokenPlacement,
}

impl TokenField {
    /// A token field named `name` that must come before the first file.
    #[must_use]
    pub const fn new(name: &'static str) -> TokenField {
        TokenField {
            name,
            placement: TokenPlacement::BeforeFirstFile,
        }
    }

    /// The same field, allowed anywhere in the body.
    #[must_use]
    pub const fn anywhere(self) -> TokenField {
        TokenField {
            name: self.name,
            placement: TokenPlacement::Anywhere,
        }
    }

    /// The field name, matched byte for byte.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Where the field must be.
    #[must_use]
    pub const fn placement(&self) -> TokenPlacement {
        self.placement
    }
}

/// Where the token field must be.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TokenPlacement {
    /// Before the first file part (default of [`TokenField::new`]).
    BeforeFirstFile,
    /// Anywhere.
    Anywhere,
}

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

    #[test]
    fn test_limits_default_validates() {
        assert!(Limits::DEFAULT.validate().is_ok());
        assert_eq!(Limits::default(), Limits::DEFAULT);
    }

    #[test]
    fn test_limits_header_budget_below_64_refused() {
        for bytes in [0, 1, 63] {
            let l = Limits::DEFAULT.with_max_part_header_bytes(bytes);
            assert_eq!(
                l.validate(),
                Err(FormError::InvalidLimits {
                    limit: Limit::PartHeaderBytes
                })
            );
        }
        assert!(
            Limits::DEFAULT
                .with_max_part_header_bytes(64)
                .validate()
                .is_ok()
        );
    }

    #[test]
    fn test_limits_containing_limit_caps_contained() {
        let l = Limits::DEFAULT.with_max_body_bytes(4096);
        assert_eq!(l.text(), 4096);
        assert_eq!(l.value(), 4096);
        assert_eq!(l.file(), 4096);
        assert_eq!(l.name(), 256);
        assert_eq!(l.token(), 128);
        let l = l.with_max_value_bytes(10);
        assert_eq!((l.value(), l.token()), (10, 10));
        let l = Limits::DEFAULT.with_max_part_header_bytes(100);
        assert_eq!(l.filename(), 100);
        let l = Limits::DEFAULT.with_sniff_bytes(64).with_max_file_bytes(16);
        assert!(l.validate().is_ok());
    }

    #[test]
    fn test_limits_zero_token_with_token_field_refused() {
        let policy = Policy::DEFAULT.with_token_field(TokenField::new("t"));
        let l = Limits::DEFAULT.with_max_token_bytes(0);
        assert_eq!(
            l.validate_with(&policy),
            Err(FormError::InvalidLimits {
                limit: Limit::TokenLength
            })
        );
        assert!(l.validate_with(&Policy::DEFAULT).is_ok());
    }

    #[test]
    fn test_buffer_lengths_follow_policy() {
        let l = Limits::DEFAULT;
        assert_eq!(l.multipart_buffer_len(&Policy::DEFAULT), 8192 + 256 + 32);
        let p = Policy::DEFAULT
            .with_extended_filename(ExtendedFilenamePolicy::AcceptAlone)
            .with_token_field(TokenField::new("t"));
        assert_eq!(l.multipart_buffer_len(&p), 8192 + 256 + 1024 + 128 + 32);
        assert_eq!(l.urlencoded_buffer_len(), 256 + 1024 * 1024 + 1);
    }

    #[test]
    fn test_setters_set_one_field_each() {
        let l = Limits::DEFAULT
            .with_max_body_bytes(1)
            .with_max_fields(2)
            .with_max_name_bytes(3)
            .with_max_value_bytes(4)
            .with_max_text_bytes(5)
            .with_max_parts(6)
            .with_max_files(7)
            .with_max_file_bytes(8)
            .with_max_part_header_bytes(9)
            .with_max_part_headers(10)
            .with_max_filename_bytes(11)
            .with_max_preamble_bytes(12)
            .with_max_epilogue_bytes(13)
            .with_max_padding_bytes(14)
            .with_sniff_bytes(15)
            .with_max_token_bytes(16);
        assert_eq!(
            (
                l.max_body_bytes,
                l.max_fields,
                l.max_name_bytes,
                l.max_value_bytes
            ),
            (1, 2, 3, 4)
        );
        assert_eq!(
            (l.max_text_bytes, l.max_parts, l.max_files, l.max_file_bytes),
            (5, 6, 7, 8)
        );
        assert_eq!(
            (
                l.max_part_header_bytes,
                l.max_part_headers,
                l.max_filename_bytes,
                l.max_preamble_bytes
            ),
            (9, 10, 11, 12)
        );
        assert_eq!(
            (
                l.max_epilogue_bytes,
                l.max_padding_bytes,
                l.sniff_bytes,
                l.max_token_bytes
            ),
            (13, 14, 15, 16)
        );
    }

    #[test]
    fn test_policy_setters() {
        let p = Policy::DEFAULT
            .with_percent(PercentPolicy::Literal)
            .with_extended_filename(ExtendedFilenamePolicy::Ignore)
            .with_unknown_headers(HeaderPolicy::Refuse)
            .with_empty_files(EmptyFilePolicy::Skip)
            .with_token_field(TokenField::new("t").anywhere());
        assert_eq!(p.percent, PercentPolicy::Literal);
        assert_eq!(p.extended_filename, ExtendedFilenamePolicy::Ignore);
        assert_eq!(p.unknown_headers, HeaderPolicy::Refuse);
        assert_eq!(p.empty_files, EmptyFilePolicy::Skip);
        assert_eq!(
            p.token_field.map(|t| (t.name(), t.placement())),
            Some(("t", TokenPlacement::Anywhere))
        );
        assert_eq!(Policy::default(), Policy::DEFAULT);
    }
}