shiguredo_http11 2026.1.0

HTTP/1.1 Library
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
//! Content-Disposition ヘッダーパース (RFC 6266)
//!
//! ## 概要
//!
//! RFC 6266 に基づいた Content-Disposition ヘッダーのパースを提供します。
//!
//! ## 使い方
//!
//! ```rust
//! use shiguredo_http11::content_disposition::{ContentDisposition, DispositionType};
//!
//! // attachment with filename
//! let cd = ContentDisposition::parse("attachment; filename=\"example.txt\"").unwrap();
//! assert_eq!(cd.disposition_type(), DispositionType::Attachment);
//! assert_eq!(cd.filename(), Some("example.txt"));
//!
//! // inline
//! let cd = ContentDisposition::parse("inline").unwrap();
//! assert_eq!(cd.disposition_type(), DispositionType::Inline);
//! ```

use core::fmt;

/// Content-Disposition パースエラー
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ContentDispositionError {
    /// 空の入力
    Empty,
    /// 不正な形式
    InvalidFormat,
    /// 不正な disposition-type
    InvalidDispositionType,
    /// 不正なパラメータ
    InvalidParameter,
    /// 不正な RFC 8187 エンコーディング
    InvalidExtValue,
    /// 重複パラメータ (RFC 6266)
    DuplicateParameter(String),
}

impl fmt::Display for ContentDispositionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ContentDispositionError::Empty => write!(f, "empty content-disposition"),
            ContentDispositionError::InvalidFormat => {
                write!(f, "invalid content-disposition format")
            }
            ContentDispositionError::InvalidDispositionType => {
                write!(f, "invalid disposition-type")
            }
            ContentDispositionError::InvalidParameter => write!(f, "invalid parameter"),
            ContentDispositionError::InvalidExtValue => write!(f, "invalid ext-value encoding"),
            ContentDispositionError::DuplicateParameter(name) => {
                write!(f, "duplicate parameter: {}", name)
            }
        }
    }
}

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

/// Disposition タイプ
///
/// RFC 6266 Section 4.1: disposition-type は拡張可能 (拡張トークンを受け入れる)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DispositionType {
    /// inline: コンテンツをインラインで表示
    Inline,
    /// attachment: コンテンツをダウンロードとして扱う
    Attachment,
    /// form-data: multipart/form-data のパート用
    FormData,
    /// 拡張 disposition-type (RFC 6266 準拠)
    Unknown(String),
}

impl DispositionType {
    /// disposition-type をパース
    ///
    /// RFC 6266 Section 4.1: 標準タイプ (inline, attachment, form-data) に加えて、
    /// 有効なトークンであれば拡張タイプとして受け入れる
    fn from_str(s: &str) -> Result<Self, ContentDispositionError> {
        let lower = s.to_ascii_lowercase();
        match lower.as_str() {
            "inline" => Ok(DispositionType::Inline),
            "attachment" => Ok(DispositionType::Attachment),
            "form-data" => Ok(DispositionType::FormData),
            _ => {
                // 拡張 disposition-type: 有効なトークンであれば受け入れる
                if is_valid_token(s) {
                    Ok(DispositionType::Unknown(lower))
                } else {
                    Err(ContentDispositionError::InvalidDispositionType)
                }
            }
        }
    }
}

impl fmt::Display for DispositionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            DispositionType::Inline => write!(f, "inline"),
            DispositionType::Attachment => write!(f, "attachment"),
            DispositionType::FormData => write!(f, "form-data"),
            DispositionType::Unknown(s) => write!(f, "{}", s),
        }
    }
}

/// Content-Disposition ヘッダー
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentDisposition {
    /// disposition-type
    disposition_type: DispositionType,
    /// filename パラメータ (ASCII)
    filename: Option<String>,
    /// filename* パラメータ (RFC 8187 エンコード済み、デコード後の値)
    filename_ext: Option<String>,
    /// name パラメータ (form-data 用)
    name: Option<String>,
    /// その他のパラメータ
    parameters: Vec<(String, String)>,
}

impl ContentDisposition {
    /// Content-Disposition ヘッダー文字列をパース
    ///
    /// # 例
    ///
    /// ```rust
    /// use shiguredo_http11::content_disposition::{ContentDisposition, DispositionType};
    ///
    /// let cd = ContentDisposition::parse("attachment; filename=\"report.pdf\"").unwrap();
    /// assert_eq!(cd.disposition_type(), DispositionType::Attachment);
    /// assert_eq!(cd.filename(), Some("report.pdf"));
    /// ```
    pub fn parse(input: &str) -> Result<Self, ContentDispositionError> {
        let input = input.trim();
        if input.is_empty() {
            return Err(ContentDispositionError::Empty);
        }

        // 引用符を考慮してパラメータを分割
        let parts = split_params(input);

        // disposition-type
        let type_str = parts
            .first()
            .ok_or(ContentDispositionError::InvalidFormat)?;
        let disposition_type = DispositionType::from_str(type_str.trim())?;

        let mut cd = ContentDisposition {
            disposition_type,
            filename: None,
            filename_ext: None,
            name: None,
            parameters: Vec::new(),
        };

        // パラメータをパース
        // RFC 6266: 同名パラメータの複数出現は無効
        let mut seen_params = Vec::new();

        for part in parts.iter().skip(1) {
            let part = part.trim();
            if part.is_empty() {
                continue;
            }

            if let Some(eq_pos) = part.find('=') {
                let param_name = part[..eq_pos].trim().to_ascii_lowercase();
                let param_value = part[eq_pos + 1..].trim();

                // 重複パラメータチェック
                if seen_params.iter().any(|n: &String| n == &param_name) {
                    return Err(ContentDispositionError::DuplicateParameter(param_name));
                }
                seen_params.push(param_name.clone());

                match param_name.as_str() {
                    "filename" => {
                        cd.filename = Some(parse_param_value(param_value)?);
                    }
                    "filename*" => {
                        cd.filename_ext = Some(parse_ext_value(param_value)?);
                    }
                    "name" => {
                        cd.name = Some(parse_param_value(param_value)?);
                    }
                    _ => {
                        cd.parameters
                            .push((param_name, parse_param_value(param_value)?));
                    }
                }
            }
        }

        Ok(cd)
    }

    /// 新しい ContentDisposition を作成
    pub fn new(disposition_type: DispositionType) -> Self {
        ContentDisposition {
            disposition_type,
            filename: None,
            filename_ext: None,
            name: None,
            parameters: Vec::new(),
        }
    }

    /// disposition-type を取得
    pub fn disposition_type(&self) -> DispositionType {
        self.disposition_type.clone()
    }

    /// filename を取得 (filename* があればそちらを優先)
    ///
    /// RFC 6266 Section 4.3 に従い、filename* が存在する場合はそちらを優先します。
    pub fn filename(&self) -> Option<&str> {
        self.filename_ext.as_deref().or(self.filename.as_deref())
    }

    /// filename パラメータを取得 (ASCII のみ)
    pub fn filename_ascii(&self) -> Option<&str> {
        self.filename.as_deref()
    }

    /// filename* パラメータを取得 (デコード済み)
    pub fn filename_ext(&self) -> Option<&str> {
        self.filename_ext.as_deref()
    }

    /// name パラメータを取得 (form-data 用)
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// パラメータを取得
    pub fn parameter(&self, name: &str) -> Option<&str> {
        let name_lower = name.to_ascii_lowercase();
        for (k, v) in &self.parameters {
            if k == &name_lower {
                return Some(v);
            }
        }
        None
    }

    /// inline かどうか
    pub fn is_inline(&self) -> bool {
        self.disposition_type == DispositionType::Inline
    }

    /// attachment かどうか
    pub fn is_attachment(&self) -> bool {
        self.disposition_type == DispositionType::Attachment
    }

    /// form-data かどうか
    pub fn is_form_data(&self) -> bool {
        self.disposition_type == DispositionType::FormData
    }

    /// filename を設定
    pub fn with_filename(mut self, filename: &str) -> Self {
        self.filename = Some(filename.to_string());
        self
    }

    /// filename* を設定 (UTF-8 でエンコード)
    pub fn with_filename_ext(mut self, filename: &str) -> Self {
        self.filename_ext = Some(filename.to_string());
        self
    }

    /// name を設定 (form-data 用)
    pub fn with_name(mut self, name: &str) -> Self {
        self.name = Some(name.to_string());
        self
    }
}

impl fmt::Display for ContentDisposition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.disposition_type)?;

        if let Some(name) = &self.name {
            write!(f, "; name=\"{}\"", escape_quoted_string(name))?;
        }

        if let Some(filename) = &self.filename {
            write!(f, "; filename=\"{}\"", escape_quoted_string(filename))?;
        }

        if let Some(filename_ext) = &self.filename_ext {
            write!(f, "; filename*=UTF-8''{}", encode_ext_value(filename_ext))?;
        }

        for (name, value) in &self.parameters {
            write!(f, "; {}=\"{}\"", name, escape_quoted_string(value))?;
        }

        Ok(())
    }
}

/// 引用符を考慮してセミコロンで分割
fn split_params(input: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut in_quotes = false;
    let mut escape_next = false;

    for c in input.chars() {
        if escape_next {
            current.push(c);
            escape_next = false;
            continue;
        }

        match c {
            '\\' if in_quotes => {
                current.push(c);
                escape_next = true;
            }
            '"' => {
                current.push(c);
                in_quotes = !in_quotes;
            }
            ';' if !in_quotes => {
                parts.push(current);
                current = String::new();
            }
            _ => {
                current.push(c);
            }
        }
    }

    if !current.is_empty() {
        parts.push(current);
    }

    parts
}

/// パラメータ値をパース (引用符付きまたはトークン)
///
/// RFC 9110 Section 5.6.6: パラメータ値がトークンの場合、
/// トークン文字 (tchar) のみで構成されている必要がある
fn parse_param_value(value: &str) -> Result<String, ContentDispositionError> {
    let value = value.trim();

    if value.starts_with('"') {
        // 引用符で始まる場合
        if value.ends_with('"') && value.len() >= 2 {
            // 正常な引用符付き文字列
            parse_quoted_string(&value[1..value.len() - 1])
        } else {
            // 閉じ引用符がない
            Err(ContentDispositionError::InvalidParameter)
        }
    } else {
        // トークン: RFC 9110 Section 5.6.2 準拠の検証
        if !is_valid_token(value) {
            return Err(ContentDispositionError::InvalidParameter);
        }
        Ok(value.to_string())
    }
}

/// 有効なトークンかどうか
fn is_valid_token(s: &str) -> bool {
    !s.is_empty() && s.bytes().all(is_token_char)
}

/// RFC 9110 Section 5.6.2 のトークン文字 (tchar)
///
/// tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." /
///         "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
fn is_token_char(b: u8) -> bool {
    matches!(b,
        b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' |
        b'0'..=b'9' | b'A'..=b'Z' | b'^' | b'_' | b'`' | b'a'..=b'z' | b'|' | b'~'
    )
}

/// 引用符付き文字列をパース (エスケープ処理)
fn parse_quoted_string(s: &str) -> Result<String, ContentDispositionError> {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars();

    while let Some(c) = chars.next() {
        if c == '\\' {
            // エスケープシーケンス
            if let Some(escaped) = chars.next() {
                result.push(escaped);
            } else {
                return Err(ContentDispositionError::InvalidParameter);
            }
        } else {
            result.push(c);
        }
    }

    Ok(result)
}

/// RFC 8187 ext-value をパース
///
/// 形式: charset'language'value
/// 例: UTF-8''%E6%97%A5%E6%9C%AC%E8%AA%9E.txt
fn parse_ext_value(value: &str) -> Result<String, ContentDispositionError> {
    let value = value.trim();

    // charset'language'value の形式
    let first_quote = value
        .find('\'')
        .ok_or(ContentDispositionError::InvalidExtValue)?;
    let charset = &value[..first_quote];

    let rest = &value[first_quote + 1..];
    let second_quote = rest
        .find('\'')
        .ok_or(ContentDispositionError::InvalidExtValue)?;
    // language は無視 (オプション)
    let encoded_value = &rest[second_quote + 1..];

    // charset は UTF-8 のみサポート (RFC 6266 推奨)
    if !charset.eq_ignore_ascii_case("UTF-8") {
        return Err(ContentDispositionError::InvalidExtValue);
    }

    // パーセントデコード
    percent_decode(encoded_value)
}

/// パーセントデコード
fn percent_decode(s: &str) -> Result<String, ContentDispositionError> {
    let mut bytes = Vec::with_capacity(s.len());
    let mut chars = s.chars();

    while let Some(c) = chars.next() {
        if c == '%' {
            let hex: String = chars.by_ref().take(2).collect();
            if hex.len() != 2 {
                return Err(ContentDispositionError::InvalidExtValue);
            }
            let byte = u8::from_str_radix(&hex, 16)
                .map_err(|_| ContentDispositionError::InvalidExtValue)?;
            bytes.push(byte);
        } else {
            // RFC 8187 Section 3.2: パーセントエンコード以外は attr-char のみ許可
            if !c.is_ascii() || !is_attr_char(c as u8) {
                return Err(ContentDispositionError::InvalidExtValue);
            }
            bytes.push(c as u8);
        }
    }

    String::from_utf8(bytes).map_err(|_| ContentDispositionError::InvalidExtValue)
}

/// RFC 8187 ext-value 用にエンコード
fn encode_ext_value(s: &str) -> String {
    let mut result = String::new();
    for byte in s.bytes() {
        if is_attr_char(byte) {
            result.push(byte as char);
        } else {
            result.push('%');
            result.push_str(&format!("{:02X}", byte));
        }
    }
    result
}

/// RFC 8187 attr-char
fn is_attr_char(b: u8) -> bool {
    matches!(b,
        b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' |
        b'!' | b'#' | b'$' | b'&' | b'+' | b'-' | b'.' |
        b'^' | b'_' | b'`' | b'|' | b'~'
    )
}

/// 引用符付き文字列用にエスケープ
fn escape_quoted_string(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    for c in s.chars() {
        if c == '"' || c == '\\' {
            result.push('\\');
        }
        result.push(c);
    }
    result
}

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

    #[test]
    fn test_parse_inline() {
        let cd = ContentDisposition::parse("inline").unwrap();
        assert_eq!(cd.disposition_type(), DispositionType::Inline);
        assert!(cd.is_inline());
        assert!(!cd.is_attachment());
    }

    #[test]
    fn test_parse_attachment() {
        let cd = ContentDisposition::parse("attachment").unwrap();
        assert_eq!(cd.disposition_type(), DispositionType::Attachment);
        assert!(cd.is_attachment());
    }

    #[test]
    fn test_parse_attachment_with_filename() {
        let cd = ContentDisposition::parse("attachment; filename=\"example.txt\"").unwrap();
        assert!(cd.is_attachment());
        assert_eq!(cd.filename(), Some("example.txt"));
    }

    #[test]
    fn test_parse_filename_without_quotes() {
        let cd = ContentDisposition::parse("attachment; filename=example.txt").unwrap();
        assert_eq!(cd.filename(), Some("example.txt"));
    }

    #[test]
    fn test_parse_filename_with_escape() {
        let cd = ContentDisposition::parse(r#"attachment; filename="file\"name.txt""#).unwrap();
        assert_eq!(cd.filename(), Some("file\"name.txt"));
    }

    #[test]
    fn test_parse_filename_ext() {
        let cd = ContentDisposition::parse(
            "attachment; filename*=UTF-8''%E6%97%A5%E6%9C%AC%E8%AA%9E.txt",
        )
        .unwrap();
        assert_eq!(cd.filename(), Some("日本語.txt"));
        assert_eq!(cd.filename_ext(), Some("日本語.txt"));
    }

    #[test]
    fn test_filename_ext_priority() {
        // filename* が filename より優先される
        let cd = ContentDisposition::parse(
            "attachment; filename=\"fallback.txt\"; filename*=UTF-8''preferred.txt",
        )
        .unwrap();
        assert_eq!(cd.filename(), Some("preferred.txt"));
        assert_eq!(cd.filename_ascii(), Some("fallback.txt"));
    }

    #[test]
    fn test_parse_form_data() {
        let cd = ContentDisposition::parse("form-data; name=\"field1\"").unwrap();
        assert!(cd.is_form_data());
        assert_eq!(cd.name(), Some("field1"));
    }

    #[test]
    fn test_parse_form_data_with_filename() {
        let cd =
            ContentDisposition::parse("form-data; name=\"file\"; filename=\"image.png\"").unwrap();
        assert!(cd.is_form_data());
        assert_eq!(cd.name(), Some("file"));
        assert_eq!(cd.filename(), Some("image.png"));
    }

    #[test]
    fn test_parse_case_insensitive() {
        let cd = ContentDisposition::parse("ATTACHMENT; FILENAME=\"test.txt\"").unwrap();
        assert!(cd.is_attachment());
        assert_eq!(cd.filename(), Some("test.txt"));
    }

    #[test]
    fn test_parse_empty() {
        assert!(ContentDisposition::parse("").is_err());
    }

    #[test]
    fn test_parse_invalid_type() {
        // 不正なトークン (スペースを含む) はエラー
        assert!(ContentDisposition::parse("hello world").is_err());
        // 不正なトークン (@ を含む) はエラー
        assert!(ContentDisposition::parse("type@invalid").is_err());
    }

    #[test]
    fn test_display() {
        let cd = ContentDisposition::new(DispositionType::Attachment).with_filename("test.txt");
        assert_eq!(cd.to_string(), "attachment; filename=\"test.txt\"");
    }

    #[test]
    fn test_display_with_filename_ext() {
        let cd = ContentDisposition::new(DispositionType::Attachment)
            .with_filename("fallback.txt")
            .with_filename_ext("日本語.txt");
        let s = cd.to_string();
        assert!(s.contains("attachment"));
        assert!(s.contains("filename=\"fallback.txt\""));
        assert!(s.contains("filename*=UTF-8''"));
    }

    #[test]
    fn test_display_form_data() {
        let cd = ContentDisposition::new(DispositionType::FormData)
            .with_name("field")
            .with_filename("file.txt");
        let s = cd.to_string();
        assert!(s.contains("form-data"));
        assert!(s.contains("name=\"field\""));
        assert!(s.contains("filename=\"file.txt\""));
    }

    #[test]
    fn test_builder() {
        let cd = ContentDisposition::new(DispositionType::Attachment)
            .with_filename("example.txt")
            .with_filename_ext("例.txt");

        assert!(cd.is_attachment());
        assert_eq!(cd.filename_ascii(), Some("example.txt"));
        assert_eq!(cd.filename_ext(), Some("例.txt"));
        assert_eq!(cd.filename(), Some("例.txt")); // filename* 優先
    }

    #[test]
    fn test_ext_value_invalid_char() {
        // RFC 8187 Section 3.2: attr-char 以外の生文字は不正
        // スペースは attr-char ではない
        assert!(ContentDisposition::parse("attachment; filename*=UTF-8''hello world.txt").is_err());
        // @ は attr-char ではない
        assert!(ContentDisposition::parse("attachment; filename*=UTF-8''test@file.txt").is_err());
    }

    #[test]
    fn test_ext_value_valid_chars() {
        // RFC 8187: 許可された attr-char はそのまま使える
        let cd =
            ContentDisposition::parse("attachment; filename*=UTF-8''test-file_v1.0.txt").unwrap();
        assert_eq!(cd.filename(), Some("test-file_v1.0.txt"));
    }

    // 修正 2: 拡張 disposition-type サポート (RFC 6266 Section 4.1)

    #[test]
    fn test_unknown_disposition_type() {
        // 拡張 disposition-type がパースできること
        let cd = ContentDisposition::parse("signal").unwrap();
        assert_eq!(
            cd.disposition_type(),
            DispositionType::Unknown("signal".to_string())
        );
    }

    #[test]
    fn test_unknown_disposition_type_with_params() {
        // 拡張 disposition-type + パラメータ
        let cd = ContentDisposition::parse("notification; id=123").unwrap();
        assert_eq!(
            cd.disposition_type(),
            DispositionType::Unknown("notification".to_string())
        );
        assert_eq!(cd.parameter("id"), Some("123"));
    }

    #[test]
    fn test_unknown_disposition_type_case_insensitive() {
        // 大文字小文字は区別しない (小文字に正規化)
        let cd = ContentDisposition::parse("CUSTOM-TYPE").unwrap();
        assert_eq!(
            cd.disposition_type(),
            DispositionType::Unknown("custom-type".to_string())
        );
    }

    #[test]
    fn test_invalid_disposition_type() {
        // 不正なトークン (スペースを含む) はエラー
        assert!(ContentDisposition::parse("hello world").is_err());
    }

    #[test]
    fn test_invalid_disposition_type_special_char() {
        // 不正なトークン (@ を含む) はエラー
        assert!(ContentDisposition::parse("type@invalid").is_err());
    }

    #[test]
    fn test_unknown_disposition_display() {
        let cd = ContentDisposition::parse("custom-type; name=\"test\"").unwrap();
        let s = cd.to_string();
        assert!(s.starts_with("custom-type"));
    }

    // 修正 3: パラメータ値のトークン検証 (RFC 9110 Section 5.6.2)

    #[test]
    fn test_invalid_token_parameter_value() {
        // 不正なトークン値 (@ を含む) はエラー
        assert!(ContentDisposition::parse("attachment; filename=hello@world.txt").is_err());
    }

    #[test]
    fn test_invalid_token_parameter_value_space() {
        // スペースを含むトークン値はエラー (引用符で囲む必要がある)
        assert!(ContentDisposition::parse("attachment; filename=hello world.txt").is_err());
    }

    #[test]
    fn test_valid_token_parameter_value() {
        // 有効なトークン値は通る
        let cd = ContentDisposition::parse("attachment; filename=valid-token_v1.0").unwrap();
        assert_eq!(cd.filename(), Some("valid-token_v1.0"));
    }

    #[test]
    fn test_quoted_special_chars() {
        // 引用符で囲めば特殊文字も OK
        let cd = ContentDisposition::parse("attachment; filename=\"hello@world.txt\"").unwrap();
        assert_eq!(cd.filename(), Some("hello@world.txt"));
    }
}