shiguredo_http11 2026.4.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
//! 条件付きリクエストヘッダー (RFC 9110)
//!
//! ## 概要
//!
//! RFC 9110 Section 13 に基づいた条件付きリクエストヘッダーのパースを提供します。
//!
//! ## 使い方
//!
//! ```rust
//! use shiguredo_http11::conditional::{IfMatch, IfNoneMatch, IfModifiedSince, IfUnmodifiedSince};
//! use shiguredo_http11::etag::EntityTag;
//! use shiguredo_http11::date::HttpDate;
//!
//! // If-Match
//! let if_match = IfMatch::parse("\"abc\", \"def\"").unwrap();
//! let etag = EntityTag::strong("abc").unwrap();
//! assert!(if_match.matches(&etag));
//!
//! // If-None-Match
//! let if_none_match = IfNoneMatch::parse("*").unwrap();
//! assert!(if_none_match.is_any());
//!
//! // If-Modified-Since
//! let if_mod = IfModifiedSince::parse("Sun, 06 Nov 1994 08:49:37 GMT", 2026).unwrap();
//! let _ = if_mod.date();
//! ```

use crate::date::{DateError, HttpDate};
use crate::etag::{ETagList, EntityTag, parse_etag_list};
use core::fmt;

/// 条件付きリクエストエラー
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConditionalError {
    /// 空の入力
    Empty,
    /// 不正な形式
    InvalidFormat,
    /// ETag パースエラー
    ETagError,
    /// 日付パースエラー
    DateError,
}

impl fmt::Display for ConditionalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConditionalError::Empty => write!(f, "empty conditional header"),
            ConditionalError::InvalidFormat => write!(f, "invalid conditional header format"),
            ConditionalError::ETagError => write!(f, "invalid etag in conditional header"),
            ConditionalError::DateError => write!(f, "invalid date in conditional header"),
        }
    }
}

impl core::error::Error for ConditionalError {}

/// If-Match ヘッダー (RFC 9110 Section 13.1.1)
///
/// リソースの現在の表現が指定された ETag のいずれかと一致する場合のみ
/// リクエストを処理します。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfMatch(ETagList);

impl IfMatch {
    /// If-Match ヘッダーをパース
    pub fn parse(input: &str) -> Result<Self, ConditionalError> {
        parse_etag_list(input)
            .map(IfMatch)
            .map_err(|_| ConditionalError::ETagError)
    }

    /// ワイルドカード (*) かどうか
    pub fn is_any(&self) -> bool {
        self.0.is_any()
    }

    /// 指定した ETag が条件を満たすか (Strong 比較)
    ///
    /// If-Match は Strong 比較を使用します (RFC 9110 Section 13.1.1)
    pub fn matches(&self, etag: &EntityTag) -> bool {
        self.0.contains_strong(etag)
    }

    /// 内部の ETag リストを取得
    pub fn etags(&self) -> &ETagList {
        &self.0
    }
}

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

/// If-None-Match ヘッダー (RFC 9110 Section 13.1.2)
///
/// リソースの現在の表現が指定された ETag のいずれとも一致しない場合のみ
/// リクエストを処理します。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfNoneMatch(ETagList);

impl IfNoneMatch {
    /// If-None-Match ヘッダーをパース
    pub fn parse(input: &str) -> Result<Self, ConditionalError> {
        parse_etag_list(input)
            .map(IfNoneMatch)
            .map_err(|_| ConditionalError::ETagError)
    }

    /// ワイルドカード (*) かどうか
    pub fn is_any(&self) -> bool {
        self.0.is_any()
    }

    /// 指定した ETag が条件を満たすか (Weak 比較)
    ///
    /// If-None-Match は Weak 比較を使用します (RFC 9110 Section 13.1.2)
    /// 戻り値が true = リクエストを処理すべき (条件を満たす)
    /// 戻り値が false = 304/412 を返すべき (条件を満たさない)
    pub fn matches(&self, etag: &EntityTag) -> bool {
        !self.0.contains_weak(etag)
    }

    /// 内部の ETag リストを取得
    pub fn etags(&self) -> &ETagList {
        &self.0
    }
}

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

/// If-Modified-Since ヘッダー (RFC 9110 Section 13.1.3)
///
/// 指定した日時以降にリソースが変更された場合のみリクエストを処理します。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfModifiedSince(HttpDate);

impl IfModifiedSince {
    /// If-Modified-Since ヘッダーをパース
    ///
    /// `reference_year` は RFC 850 形式の 2 桁年解決に使う現在年
    /// (RFC 9110 §5.6.7)。
    pub fn parse(input: &str, reference_year: u16) -> Result<Self, ConditionalError> {
        HttpDate::parse(input)
            .or_else(|e| match e {
                DateError::Rfc850Date => HttpDate::parse_rfc850(input, reference_year),
                other => Err(other),
            })
            .map(IfModifiedSince)
            .map_err(|_| ConditionalError::DateError)
    }

    /// 日時を取得
    pub fn date(&self) -> &HttpDate {
        &self.0
    }

    /// 指定した Last-Modified が条件を満たすか (RFC 9110 Section 13.1.3)
    ///
    /// 戻り値が true = リクエストを処理すべき (変更されている)
    /// 戻り値が false = 304 を返すべき (変更されていない)
    ///
    /// RFC 9110: last-modified が if-modified-since 以前または等しい場合 false
    pub fn is_modified(&self, last_modified: &HttpDate) -> bool {
        last_modified > &self.0
    }
}

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

/// If-Unmodified-Since ヘッダー (RFC 9110 Section 13.1.4)
///
/// 指定した日時以降にリソースが変更されていない場合のみリクエストを処理します。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IfUnmodifiedSince(HttpDate);

impl IfUnmodifiedSince {
    /// If-Unmodified-Since ヘッダーをパース
    ///
    /// `reference_year` は RFC 850 形式の 2 桁年解決に使う現在年
    /// (RFC 9110 §5.6.7)。
    pub fn parse(input: &str, reference_year: u16) -> Result<Self, ConditionalError> {
        HttpDate::parse(input)
            .or_else(|e| match e {
                DateError::Rfc850Date => HttpDate::parse_rfc850(input, reference_year),
                other => Err(other),
            })
            .map(IfUnmodifiedSince)
            .map_err(|_| ConditionalError::DateError)
    }

    /// 日時を取得
    pub fn date(&self) -> &HttpDate {
        &self.0
    }
}

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

/// If-Range ヘッダー (RFC 9110 Section 13.1.5)
///
/// Range リクエストで使用され、ETag または日時を指定できます。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IfRange {
    /// ETag による条件
    ETag(EntityTag),
    /// 日時による条件
    Date(HttpDate),
}

impl IfRange {
    /// If-Range ヘッダーをパース
    ///
    /// `reference_year` は RFC 850 形式の 2 桁年解決に使う現在年
    /// (RFC 9110 §5.6.7)。
    pub fn parse(input: &str, reference_year: u16) -> Result<Self, ConditionalError> {
        let input = input.trim();
        if input.is_empty() {
            return Err(ConditionalError::Empty);
        }

        // ETag は引用符で始まる、または W/ で始まる
        // RFC 9110 Section 8.8.3: weak prefix は %s"W/" (case-sensitive) で "w/" は不正。
        // ただし "w/" 始まりは ETag を意図した誤入力とみなし、日付パースに回さず
        // ETag エラーを返して weak prefix のケース誤りを示唆する。
        if input.starts_with('"') || input.starts_with("W/") || input.starts_with("w/") {
            EntityTag::parse(input)
                .map(IfRange::ETag)
                .map_err(|_| ConditionalError::ETagError)
        } else {
            HttpDate::parse(input)
                .or_else(|e| match e {
                    DateError::Rfc850Date => HttpDate::parse_rfc850(input, reference_year),
                    other => Err(other),
                })
                .map(IfRange::Date)
                .map_err(|_| ConditionalError::DateError)
        }
    }

    /// ETag かどうか
    pub fn is_etag(&self) -> bool {
        matches!(self, IfRange::ETag(_))
    }

    /// 日時かどうか
    pub fn is_date(&self) -> bool {
        matches!(self, IfRange::Date(_))
    }

    /// ETag を取得
    pub fn etag(&self) -> Option<&EntityTag> {
        match self {
            IfRange::ETag(e) => Some(e),
            IfRange::Date(_) => None,
        }
    }

    /// 日時を取得
    pub fn date(&self) -> Option<&HttpDate> {
        match self {
            IfRange::ETag(_) => None,
            IfRange::Date(d) => Some(d),
        }
    }
}

impl fmt::Display for IfRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IfRange::ETag(e) => write!(f, "{}", e),
            IfRange::Date(d) => write!(f, "{}", d),
        }
    }
}

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

    #[test]
    fn test_if_match_single() {
        let im = IfMatch::parse("\"abc\"").unwrap();
        let etag = EntityTag::strong("abc").unwrap();
        assert!(im.matches(&etag));

        let other = EntityTag::strong("xyz").unwrap();
        assert!(!im.matches(&other));
    }

    #[test]
    fn test_if_match_multiple() {
        let im = IfMatch::parse("\"a\", \"b\", \"c\"").unwrap();
        assert!(im.matches(&EntityTag::strong("b").unwrap()));
        assert!(!im.matches(&EntityTag::strong("d").unwrap()));
    }

    #[test]
    fn test_if_match_any() {
        let im = IfMatch::parse("*").unwrap();
        assert!(im.is_any());
        assert!(im.matches(&EntityTag::strong("anything").unwrap()));
    }

    #[test]
    fn test_if_match_weak_not_match() {
        // If-Match は Strong 比較を使用するため、Weak ETag は一致しない
        let im = IfMatch::parse("W/\"abc\"").unwrap();
        let etag = EntityTag::strong("abc").unwrap();
        assert!(!im.matches(&etag));
    }

    #[test]
    fn test_if_none_match_single() {
        let inm = IfNoneMatch::parse("\"abc\"").unwrap();
        let etag = EntityTag::strong("abc").unwrap();
        assert!(!inm.matches(&etag)); // 一致するので処理しない

        let other = EntityTag::strong("xyz").unwrap();
        assert!(inm.matches(&other)); // 一致しないので処理する
    }

    #[test]
    fn test_if_none_match_any() {
        let inm = IfNoneMatch::parse("*").unwrap();
        assert!(inm.is_any());
        // * は全てに一致するので、どの ETag でも処理しない
        assert!(!inm.matches(&EntityTag::strong("anything").unwrap()));
    }

    #[test]
    fn test_if_none_match_weak() {
        // If-None-Match は Weak 比較を使用
        let inm = IfNoneMatch::parse("W/\"abc\"").unwrap();
        let etag = EntityTag::strong("abc").unwrap();
        assert!(!inm.matches(&etag)); // Weak 比較で一致するので処理しない
    }

    #[test]
    fn test_if_modified_since() {
        let ims = IfModifiedSince::parse("Sun, 06 Nov 1994 08:49:37 GMT", 2026).unwrap();
        assert_eq!(ims.date().day(), 6);
        assert_eq!(ims.date().month(), 11);
        assert_eq!(ims.date().year(), 1994);
    }

    #[test]
    fn test_if_modified_since_is_modified() {
        // If-Modified-Since: 1994-11-06
        let ims = IfModifiedSince::parse("Sun, 06 Nov 1994 08:49:37 GMT", 2026).unwrap();

        // last-modified が同じ → false (304)
        let same = HttpDate::parse("Sun, 06 Nov 1994 08:49:37 GMT").unwrap();
        assert!(!ims.is_modified(&same));

        // last-modified が古い → false (304)
        let older = HttpDate::parse("Sat, 05 Nov 1994 08:49:37 GMT").unwrap();
        assert!(!ims.is_modified(&older));

        // last-modified が新しい → true (処理する)
        let newer = HttpDate::parse("Mon, 07 Nov 1994 08:49:37 GMT").unwrap();
        assert!(ims.is_modified(&newer));
    }

    #[test]
    fn test_if_unmodified_since() {
        let ius = IfUnmodifiedSince::parse("Sun, 06 Nov 1994 08:49:37 GMT", 2026).unwrap();
        assert_eq!(ius.date().day(), 6);
    }

    #[test]
    fn test_if_range_etag() {
        let ir = IfRange::parse("\"abc123\"", 2026).unwrap();
        assert!(ir.is_etag());
        assert_eq!(ir.etag().unwrap().tag(), "abc123");
    }

    #[test]
    fn test_if_range_weak_etag() {
        let ir = IfRange::parse("W/\"abc123\"", 2026).unwrap();
        assert!(ir.is_etag());
        assert!(ir.etag().unwrap().is_weak());
    }

    #[test]
    fn test_if_range_date() {
        let ir = IfRange::parse("Sun, 06 Nov 1994 08:49:37 GMT", 2026).unwrap();
        assert!(ir.is_date());
        assert_eq!(ir.date().unwrap().day(), 6);
    }

    #[test]
    fn test_if_match_display() {
        let im = IfMatch::parse("\"a\", \"b\"").unwrap();
        assert_eq!(im.to_string(), "\"a\", \"b\"");
    }

    #[test]
    fn test_if_range_display() {
        let ir = IfRange::parse("\"abc\"", 2026).unwrap();
        assert_eq!(ir.to_string(), "\"abc\"");
    }
}