vespera 0.1.47

A fully automated OpenAPI engine for Axum with zero-config route and schema discovery
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
//! Native multipart form data extraction for Vespera.
//!
//! Replaces the `axum_typed_multipart` crate with a zero-dependency (beyond axum)
//! implementation of typed multipart extraction. All types here are referenced by
//! the `#[derive(Multipart)]` macro's generated code.
//!
//! # Key types
//!
//! - [`TypedMultipart<T>`] — Axum extractor that parses `multipart/form-data` into `T`
//! - [`TypedMultipartError`] — Error type for multipart parsing failures
//! - [`FieldData<T>`] — Wrapper providing file metadata alongside field contents
//! - [`FieldMetadata`] — Metadata extracted from a multipart field
//! - [`TryFromMultipartWithState<S>`] — Trait for parsing a full multipart request
//! - [`TryFromFieldWithState<S>`] — Trait for parsing a single multipart field

use std::fmt;

use axum::extract::multipart::{Field, MultipartError, MultipartRejection};
use axum::extract::{FromRequest, Request};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};

// ═══════════════════════════════════════════════════════════════════════════════
// Error type
// ═══════════════════════════════════════════════════════════════════════════════

/// Errors that can occur when parsing multipart form data.
#[derive(Debug)]
pub enum TypedMultipartError {
    /// The request could not be parsed as multipart (e.g., missing Content-Type).
    InvalidRequest {
        /// The underlying rejection from axum's Multipart extractor.
        source: MultipartRejection,
    },
    /// An error occurred while reading the multipart body stream.
    InvalidRequestBody {
        /// The underlying multipart stream error.
        source: MultipartError,
    },
    /// A required field was not present in the multipart form.
    MissingField {
        /// Name of the missing field.
        field_name: String,
    },
    /// A field's value could not be parsed as the expected type.
    WrongFieldType {
        /// Name of the field.
        field_name: String,
        /// The expected type name.
        wanted: String,
        /// Description of the parse error.
        source: String,
    },
    /// A non-repeatable field appeared more than once (strict mode).
    DuplicateField {
        /// Name of the duplicate field.
        field_name: String,
    },
    /// An unrecognized field was found (strict mode only).
    UnknownField {
        /// Name of the unknown field.
        field_name: String,
    },
    /// A field's value is not a valid variant of the expected enum.
    InvalidEnumValue {
        /// Name of the field.
        field_name: String,
        /// The invalid value that was received.
        value: String,
    },
    /// A field without a name was encountered (strict mode only).
    NamelessField,
    /// A field exceeded its configured size limit.
    FieldTooLarge {
        /// Name of the field.
        field_name: String,
        /// The configured limit in bytes.
        limit_bytes: usize,
    },
    /// A catch-all for other errors during multipart processing.
    Other {
        /// Description of the error.
        source: String,
    },
}

impl fmt::Display for TypedMultipartError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidRequest { source } => {
                write!(f, "Invalid multipart request: {source}")
            }
            Self::InvalidRequestBody { source } => {
                write!(f, "Invalid multipart body: {source}")
            }
            Self::MissingField { field_name } => {
                write!(f, "Missing field: `{field_name}`")
            }
            Self::WrongFieldType {
                field_name,
                wanted,
                source,
            } => {
                write!(
                    f,
                    "Wrong type for field `{field_name}` (expected {wanted}): {source}"
                )
            }
            Self::DuplicateField { field_name } => {
                write!(f, "Duplicate field: `{field_name}`")
            }
            Self::UnknownField { field_name } => {
                write!(f, "Unknown field: `{field_name}`")
            }
            Self::InvalidEnumValue { field_name, value } => {
                write!(f, "Invalid enum value `{value}` for field `{field_name}`")
            }
            Self::NamelessField => write!(f, "Encountered a field without a name"),
            Self::FieldTooLarge {
                field_name,
                limit_bytes,
            } => {
                write!(
                    f,
                    "Field `{field_name}` exceeds size limit of {limit_bytes} bytes"
                )
            }
            Self::Other { source } => write!(f, "{source}"),
        }
    }
}

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

impl IntoResponse for TypedMultipartError {
    fn into_response(self) -> Response {
        let status = match &self {
            Self::InvalidRequest { .. }
            | Self::InvalidRequestBody { .. }
            | Self::MissingField { .. }
            | Self::DuplicateField { .. }
            | Self::UnknownField { .. }
            | Self::InvalidEnumValue { .. }
            | Self::NamelessField => StatusCode::BAD_REQUEST,
            Self::WrongFieldType { .. } => StatusCode::UNSUPPORTED_MEDIA_TYPE,
            Self::FieldTooLarge { .. } => StatusCode::PAYLOAD_TOO_LARGE,
            Self::Other { .. } => StatusCode::INTERNAL_SERVER_ERROR,
        };
        (status, self.to_string()).into_response()
    }
}

impl From<MultipartError> for TypedMultipartError {
    fn from(source: MultipartError) -> Self {
        Self::InvalidRequestBody { source }
    }
}

impl From<MultipartRejection> for TypedMultipartError {
    fn from(source: MultipartRejection) -> Self {
        Self::InvalidRequest { source }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Traits
// ═══════════════════════════════════════════════════════════════════════════════

/// Parse a full multipart request body into a struct.
///
/// Typically generated by `#[derive(Multipart)]`. Each field in the struct
/// is matched against multipart field names and parsed via
/// [`TryFromFieldWithState`].
pub trait TryFromMultipartWithState<S: Send + Sync>: Sized {
    /// Parse the multipart stream into `Self`.
    fn try_from_multipart_with_state(
        multipart: &mut axum::extract::Multipart,
        state: &S,
    ) -> impl std::future::Future<Output = Result<Self, TypedMultipartError>> + Send;
}

/// Parse a single multipart field into a value.
///
/// Built-in implementations exist for `String`, `bool`, all integer and float
/// types, `char`, `tempfile::NamedTempFile`, and `FieldData<T>`.
pub trait TryFromFieldWithState<S: Send + Sync>: Sized {
    /// Parse a single field into `Self`, optionally enforcing a byte-size limit.
    fn try_from_field_with_state(
        field: Field<'_>,
        limit_bytes: Option<usize>,
        state: &S,
    ) -> impl std::future::Future<Output = Result<Self, TypedMultipartError>> + Send;
}

// ═══════════════════════════════════════════════════════════════════════════════
// Field metadata
// ═══════════════════════════════════════════════════════════════════════════════

/// Metadata extracted from a multipart field part.
#[derive(Debug, Clone)]
pub struct FieldMetadata {
    /// The field name (`name` attribute in the form).
    pub name: Option<String>,
    /// The original filename (present for file uploads).
    pub file_name: Option<String>,
    /// The MIME content type of the field.
    pub content_type: Option<String>,
    /// All HTTP headers associated with this multipart part.
    pub headers: axum::http::HeaderMap,
}

impl From<&Field<'_>> for FieldMetadata {
    fn from(field: &Field<'_>) -> Self {
        Self {
            name: field.name().map(String::from),
            file_name: field.file_name().map(String::from),
            content_type: field.content_type().map(String::from),
            headers: field.headers().clone(),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FieldData<T>
// ═══════════════════════════════════════════════════════════════════════════════

/// A multipart field's parsed contents along with its metadata.
///
/// Use this wrapper when you need access to the file name, content type,
/// or other headers alongside the parsed value.
///
/// ```rust,ignore
/// use vespera::multipart::FieldData;
/// use tempfile::NamedTempFile;
///
/// #[derive(Multipart, Schema)]
/// pub struct Upload {
///     pub file: FieldData<NamedTempFile>,
/// }
/// ```
#[derive(Debug)]
pub struct FieldData<T> {
    /// Metadata about the field (name, filename, content-type, headers).
    pub metadata: FieldMetadata,
    /// The parsed contents of the field.
    pub contents: T,
}

impl<T, S> TryFromFieldWithState<S> for FieldData<T>
where
    T: TryFromFieldWithState<S> + Send,
    S: Send + Sync,
{
    async fn try_from_field_with_state(
        field: Field<'_>,
        limit_bytes: Option<usize>,
        state: &S,
    ) -> Result<Self, TypedMultipartError> {
        let metadata = FieldMetadata::from(&field);
        let contents = T::try_from_field_with_state(field, limit_bytes, state).await?;
        Ok(Self { metadata, contents })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TypedMultipart<T> extractor
// ═══════════════════════════════════════════════════════════════════════════════

/// Axum extractor for typed multipart form data.
///
/// Wraps a struct `T` that implements [`TryFromMultipartWithState`] (typically
/// via `#[derive(Multipart)]`).
///
/// ```rust,ignore
/// use vespera::multipart::{TypedMultipart, FieldData};
/// use tempfile::NamedTempFile;
///
/// #[derive(Multipart, Schema)]
/// pub struct UploadRequest {
///     pub name: String,
///     pub file: FieldData<NamedTempFile>,
/// }
///
/// #[vespera::route(post)]
/// pub async fn upload(
///     TypedMultipart(req): TypedMultipart<UploadRequest>,
/// ) -> Json<String> {
///     Json(req.name)
/// }
/// ```
pub struct TypedMultipart<T>(pub T);

impl<T> std::ops::Deref for TypedMultipart<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> std::ops::DerefMut for TypedMultipart<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T, S> FromRequest<S> for TypedMultipart<T>
where
    T: TryFromMultipartWithState<S>,
    S: Send + Sync + 'static,
{
    type Rejection = TypedMultipartError;

    async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
        let mut multipart = axum::extract::Multipart::from_request(req, state)
            .await
            .map_err(TypedMultipartError::from)?;
        let value = T::try_from_multipart_with_state(&mut multipart, state).await?;
        Ok(Self(value))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// Built-in TryFromFieldWithState implementations
// ═══════════════════════════════════════════════════════════════════════════════

// ─── Helpers ────────────────────────────────────────────────────────────────

/// Read all bytes from a multipart field, enforcing an optional size limit.
///
/// When a limit is set, bytes are read incrementally via `chunk()` and the
/// cumulative size is checked after each chunk. Without a limit, `bytes()` is
/// called for a single-allocation read.
async fn read_field_data(
    mut field: Field<'_>,
    limit: Option<usize>,
) -> Result<(String, Vec<u8>), TypedMultipartError> {
    let field_name = field.name().unwrap_or_default().to_string();

    let data = if let Some(limit) = limit {
        let mut buf = Vec::new();
        while let Some(chunk) = field.chunk().await? {
            buf.extend_from_slice(&chunk);
            if buf.len() > limit {
                return Err(TypedMultipartError::FieldTooLarge {
                    field_name,
                    limit_bytes: limit,
                });
            }
        }
        buf
    } else {
        field.bytes().await?.to_vec()
    };

    Ok((field_name, data))
}

/// Parse a string as a boolean using clap-style conventions.
///
/// Accepted truthy values: `true`, `yes`, `y`, `1`, `on`
/// Accepted falsy  values: `false`, `no`, `n`, `0`, `off`
fn str_to_bool(s: &str) -> Option<bool> {
    match s.to_ascii_lowercase().as_str() {
        "true" | "yes" | "y" | "1" | "on" => Some(true),
        "false" | "no" | "n" | "0" | "off" => Some(false),
        _ => None,
    }
}

// ─── String ─────────────────────────────────────────────────────────────────

impl<S: Send + Sync> TryFromFieldWithState<S> for String {
    async fn try_from_field_with_state(
        field: Field<'_>,
        limit_bytes: Option<usize>,
        _state: &S,
    ) -> Result<Self, TypedMultipartError> {
        let (field_name, data) = read_field_data(field, limit_bytes).await?;
        Self::from_utf8(data).map_err(|e| TypedMultipartError::WrongFieldType {
            field_name,
            wanted: "String".to_string(),
            source: e.to_string(),
        })
    }
}

// ─── bool ───────────────────────────────────────────────────────────────────

impl<S: Send + Sync> TryFromFieldWithState<S> for bool {
    async fn try_from_field_with_state(
        field: Field<'_>,
        limit_bytes: Option<usize>,
        _state: &S,
    ) -> Result<Self, TypedMultipartError> {
        let (field_name, data) = read_field_data(field, limit_bytes).await?;
        let text = std::str::from_utf8(&data).map_err(|e| TypedMultipartError::WrongFieldType {
            field_name: field_name.clone(),
            wanted: "bool".to_string(),
            source: e.to_string(),
        })?;
        str_to_bool(text).ok_or_else(|| TypedMultipartError::WrongFieldType {
            field_name,
            wanted: "bool".to_string(),
            source: format!("invalid boolean value: `{text}`"),
        })
    }
}

// ─── Numeric types ──────────────────────────────────────────────────────────

macro_rules! impl_try_from_field_for_number {
    ($($ty:ty),* $(,)?) => {
        $(
                impl<S: Send + Sync> TryFromFieldWithState<S> for $ty {
                async fn try_from_field_with_state(
                    field: Field<'_>,
                    limit_bytes: Option<usize>,
                    _state: &S,
                ) -> Result<Self, TypedMultipartError> {
                    let (field_name, data) = read_field_data(field, limit_bytes).await?;
                    let text = std::str::from_utf8(&data).map_err(|e| {
                        TypedMultipartError::WrongFieldType {
                            field_name: field_name.clone(),
                            wanted: stringify!($ty).to_string(),
                            source: e.to_string(),
                        }
                    })?;
                    text.trim().parse::<$ty>().map_err(|e| {
                        TypedMultipartError::WrongFieldType {
                            field_name,
                            wanted: stringify!($ty).to_string(),
                            source: e.to_string(),
                        }
                    })
                }
            }
        )*
    };
}

impl_try_from_field_for_number!(
    i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, isize, usize, f32, f64,
);

// ─── char ───────────────────────────────────────────────────────────────────

impl<S: Send + Sync> TryFromFieldWithState<S> for char {
    async fn try_from_field_with_state(
        field: Field<'_>,
        limit_bytes: Option<usize>,
        _state: &S,
    ) -> Result<Self, TypedMultipartError> {
        let (field_name, data) = read_field_data(field, limit_bytes).await?;
        let text = std::str::from_utf8(&data).map_err(|e| TypedMultipartError::WrongFieldType {
            field_name: field_name.clone(),
            wanted: "char".to_string(),
            source: e.to_string(),
        })?;
        let mut chars = text.chars();
        match (chars.next(), chars.next()) {
            (Some(c), None) => Ok(c),
            _ => Err(TypedMultipartError::WrongFieldType {
                field_name,
                wanted: "char".to_string(),
                source: "expected exactly one character".to_string(),
            }),
        }
    }
}

// ─── NamedTempFile ──────────────────────────────────────────────────────────

impl<S: Send + Sync> TryFromFieldWithState<S> for tempfile::NamedTempFile {
    async fn try_from_field_with_state(
        mut field: Field<'_>,
        limit_bytes: Option<usize>,
        _state: &S,
    ) -> Result<Self, TypedMultipartError> {
        let field_name = field.name().unwrap_or_default().to_string();
        let mut temp = Self::new().map_err(|e| TypedMultipartError::Other {
            source: e.to_string(),
        })?;

        let mut total = 0usize;
        while let Some(chunk) = field.chunk().await? {
            total += chunk.len();
            if let Some(limit) = limit_bytes
                && total > limit
            {
                return Err(TypedMultipartError::FieldTooLarge {
                    field_name,
                    limit_bytes: limit,
                });
            }
            std::io::Write::write_all(&mut temp, &chunk).map_err(|e| {
                TypedMultipartError::Other {
                    source: e.to_string(),
                }
            })?;
        }

        Ok(temp)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::StatusCode;
    use axum::response::IntoResponse;

    #[test]
    fn test_str_to_bool_truthy() {
        for val in &[
            "true", "True", "TRUE", "yes", "Yes", "y", "Y", "1", "on", "ON",
        ] {
            assert_eq!(str_to_bool(val), Some(true), "expected true for `{val}`");
        }
    }

    #[test]
    fn test_str_to_bool_falsy() {
        for val in &[
            "false", "False", "FALSE", "no", "No", "n", "N", "0", "off", "OFF",
        ] {
            assert_eq!(str_to_bool(val), Some(false), "expected false for `{val}`");
        }
    }

    #[test]
    fn test_str_to_bool_invalid() {
        for val in &["maybe", "2", "", "yep", "nah"] {
            assert_eq!(str_to_bool(val), None, "expected None for `{val}`");
        }
    }

    // ─── Display tests for all error variants ───────────────────────────

    #[test]
    fn test_error_display() {
        let err = TypedMultipartError::MissingField {
            field_name: "name".to_string(),
        };
        assert_eq!(err.to_string(), "Missing field: `name`");

        let err = TypedMultipartError::FieldTooLarge {
            field_name: "file".to_string(),
            limit_bytes: 1024,
        };
        assert_eq!(
            err.to_string(),
            "Field `file` exceeds size limit of 1024 bytes"
        );

        let err = TypedMultipartError::WrongFieldType {
            field_name: "age".to_string(),
            wanted: "i32".to_string(),
            source: "invalid digit".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Wrong type for field `age` (expected i32): invalid digit"
        );
    }

    #[test]
    fn test_error_display_duplicate_field() {
        let err = TypedMultipartError::DuplicateField {
            field_name: "email".to_string(),
        };
        assert_eq!(err.to_string(), "Duplicate field: `email`");
    }

    #[test]
    fn test_error_display_unknown_field() {
        let err = TypedMultipartError::UnknownField {
            field_name: "foo".to_string(),
        };
        assert_eq!(err.to_string(), "Unknown field: `foo`");
    }

    #[test]
    fn test_error_display_invalid_enum_value() {
        let err = TypedMultipartError::InvalidEnumValue {
            field_name: "status".to_string(),
            value: "maybe".to_string(),
        };
        assert_eq!(
            err.to_string(),
            "Invalid enum value `maybe` for field `status`"
        );
    }

    #[test]
    fn test_error_display_nameless_field() {
        let err = TypedMultipartError::NamelessField;
        assert_eq!(err.to_string(), "Encountered a field without a name");
    }

    #[test]
    fn test_error_display_other() {
        let err = TypedMultipartError::Other {
            source: "something went wrong".to_string(),
        };
        assert_eq!(err.to_string(), "something went wrong");
    }

    // ─── IntoResponse status code tests ─────────────────────────────────

    #[test]
    fn test_into_response_duplicate_field() {
        let err = TypedMultipartError::DuplicateField {
            field_name: "x".to_string(),
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_into_response_unknown_field() {
        let err = TypedMultipartError::UnknownField {
            field_name: "x".to_string(),
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_into_response_invalid_enum_value() {
        let err = TypedMultipartError::InvalidEnumValue {
            field_name: "x".to_string(),
            value: "bad".to_string(),
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_into_response_nameless_field() {
        let err = TypedMultipartError::NamelessField;
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_into_response_wrong_field_type() {
        let err = TypedMultipartError::WrongFieldType {
            field_name: "age".to_string(),
            wanted: "i32".to_string(),
            source: "err".to_string(),
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[test]
    fn test_into_response_field_too_large() {
        let err = TypedMultipartError::FieldTooLarge {
            field_name: "file".to_string(),
            limit_bytes: 100,
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
    }

    #[test]
    fn test_into_response_other() {
        let err = TypedMultipartError::Other {
            source: "err".to_string(),
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_into_response_missing_field() {
        let err = TypedMultipartError::MissingField {
            field_name: "x".to_string(),
        };
        let resp = err.into_response();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    // ─── Error trait ────────────────────────────────────────────────────

    #[test]
    fn test_error_trait_is_implemented() {
        let err: Box<dyn std::error::Error> = Box::new(TypedMultipartError::Other {
            source: "test".to_string(),
        });
        assert_eq!(err.to_string(), "test");
    }

    // ─── TypedMultipart Deref / DerefMut ────────────────────────────────

    #[test]
    fn test_typed_multipart_deref() {
        let tm = TypedMultipart("hello".to_string());
        // Deref: &TypedMultipart<String> → &String
        assert_eq!(&*tm, "hello");
        assert_eq!(tm.len(), 5); // auto-deref to String method
    }

    #[test]
    fn test_typed_multipart_deref_mut() {
        let mut tm = TypedMultipart(vec![1, 2, 3]);
        // DerefMut: &mut TypedMultipart<Vec<i32>> → &mut Vec<i32>
        tm.push(4);
        assert_eq!(&*tm, &[1, 2, 3, 4]);
    }
}