shiguredo_http11 2026.6.1

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
//! Range リクエストヘッダー (RFC 9110)
//!
//! ## 概要
//!
//! RFC 9110 Section 14 に基づいた Range リクエストヘッダーのパースを提供します。
//!
//! ## 使い方
//!
//! ```rust
//! use shiguredo_http11::range::{Range, ContentRange, AcceptRanges};
//!
//! // Range ヘッダーパース
//! let range = Range::parse("bytes=0-499").unwrap();
//! assert_eq!(range.unit(), "bytes");
//! let specs = range.ranges();
//! assert_eq!(specs.len(), 1);
//!
//! // Content-Range ヘッダー生成
//! let cr = ContentRange::new_bytes(0, 499, Some(1000));
//! assert_eq!(cr.to_string(), "bytes 0-499/1000");
//!
//! // Accept-Ranges ヘッダーパース
//! let ar = AcceptRanges::parse("bytes").unwrap();
//! assert!(ar.accepts_bytes());
//! ```

use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;

use crate::validate::{is_valid_token, trim_ows};

/// Range パースエラー
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RangeError {
    /// 空の入力
    Empty,
    /// 不正な形式
    InvalidFormat,
    /// 不正な単位
    InvalidUnit,
    /// 不正な範囲
    InvalidRange,
    /// 範囲が不正 (開始 > 終了)
    InvalidBounds,
}

impl fmt::Display for RangeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RangeError::Empty => write!(f, "empty range header"),
            RangeError::InvalidFormat => write!(f, "invalid range header format"),
            RangeError::InvalidUnit => write!(f, "invalid range unit"),
            RangeError::InvalidRange => write!(f, "invalid range specification"),
            RangeError::InvalidBounds => write!(f, "invalid range bounds"),
        }
    }
}

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

/// 範囲指定
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RangeSpec {
    /// 開始位置から終了位置まで (両端含む)
    /// bytes=0-499 → Range { start: 0, end: 499 }
    Range { start: u64, end: u64 },
    /// 開始位置から末尾まで
    /// bytes=500- → FromStart { start: 500 }
    FromStart { start: u64 },
    /// 末尾から n バイト
    /// bytes=-500 → Suffix { length: 500 }
    Suffix { length: u64 },
}

impl RangeSpec {
    /// 実際のバイト範囲を計算
    ///
    /// total_length はリソースの総バイト数
    /// 戻り値は (start, end) で両端含む
    pub fn to_bounds(&self, total_length: u64) -> Option<(u64, u64)> {
        if total_length == 0 {
            return None;
        }
        match *self {
            RangeSpec::Range { start, end } => {
                if start > end || start >= total_length {
                    return None;
                }
                let end = end.min(total_length - 1);
                Some((start, end))
            }
            RangeSpec::FromStart { start } => {
                if start >= total_length {
                    return None;
                }
                Some((start, total_length - 1))
            }
            RangeSpec::Suffix { length } => {
                if length == 0 {
                    return None;
                }
                let start = total_length.saturating_sub(length);
                Some((start, total_length - 1))
            }
        }
    }
}

impl fmt::Display for RangeSpec {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            RangeSpec::Range { start, end } => write!(f, "{}-{}", start, end),
            RangeSpec::FromStart { start } => write!(f, "{}-", start),
            RangeSpec::Suffix { length } => write!(f, "-{}", length),
        }
    }
}

/// Range ヘッダー (RFC 9110 Section 14.2)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Range {
    /// 範囲単位 (通常は "bytes")
    unit: String,
    /// 範囲指定のリスト
    ranges: Vec<RangeSpec>,
}

impl Range {
    /// Range ヘッダーをパース
    ///
    /// # 例
    ///
    /// ```rust
    /// use shiguredo_http11::range::Range;
    ///
    /// // 単一範囲
    /// let range = Range::parse("bytes=0-499").unwrap();
    /// assert_eq!(range.unit(), "bytes");
    ///
    /// // 複数範囲
    /// let range = Range::parse("bytes=0-499, 1000-1499").unwrap();
    /// assert_eq!(range.ranges().len(), 2);
    ///
    /// // 末尾から
    /// let range = Range::parse("bytes=-500").unwrap();
    /// ```
    pub fn parse(input: &str) -> Result<Self, RangeError> {
        let input = trim_ows(input);
        if input.is_empty() {
            return Err(RangeError::Empty);
        }

        // unit=ranges の形式
        let eq_pos = input.find('=').ok_or(RangeError::InvalidFormat)?;
        let unit = trim_ows(&input[..eq_pos]);
        let ranges_str = trim_ows(&input[eq_pos + 1..]);

        // RFC 9110 Section 14.1: range-unit = token
        if !is_valid_token(unit) {
            return Err(RangeError::InvalidUnit);
        }

        let mut ranges = Vec::new();
        for part in ranges_str.split(',') {
            let part = trim_ows(part);
            if part.is_empty() {
                continue;
            }
            ranges.push(parse_range_spec(part)?);
        }

        if ranges.is_empty() {
            return Err(RangeError::Empty);
        }

        Ok(Range {
            unit: unit.to_string(),
            ranges,
        })
    }

    /// 単位を取得
    pub fn unit(&self) -> &str {
        &self.unit
    }

    /// バイト範囲かどうか
    pub fn is_bytes(&self) -> bool {
        self.unit.eq_ignore_ascii_case("bytes")
    }

    /// 範囲指定のリストを取得
    pub fn ranges(&self) -> &[RangeSpec] {
        &self.ranges
    }

    /// 最初の範囲を取得
    pub fn first(&self) -> Option<&RangeSpec> {
        self.ranges.first()
    }
}

impl fmt::Display for Range {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}=", self.unit)?;
        let specs: Vec<String> = self.ranges.iter().map(|r| r.to_string()).collect();
        write!(f, "{}", specs.join(", "))
    }
}

/// 範囲指定をパース
fn parse_range_spec(s: &str) -> Result<RangeSpec, RangeError> {
    let dash_pos = s.find('-').ok_or(RangeError::InvalidRange)?;

    let start_str = trim_ows(&s[..dash_pos]);
    let end_str = trim_ows(&s[dash_pos + 1..]);

    if start_str.is_empty() && end_str.is_empty() {
        return Err(RangeError::InvalidRange);
    }

    if start_str.is_empty() {
        // Suffix: -500
        let length = end_str
            .parse::<u64>()
            .map_err(|_| RangeError::InvalidRange)?;
        return Ok(RangeSpec::Suffix { length });
    }

    let start = start_str
        .parse::<u64>()
        .map_err(|_| RangeError::InvalidRange)?;

    if end_str.is_empty() {
        // FromStart: 500-
        return Ok(RangeSpec::FromStart { start });
    }

    // Range: 0-499
    let end = end_str
        .parse::<u64>()
        .map_err(|_| RangeError::InvalidRange)?;

    if start > end {
        return Err(RangeError::InvalidBounds);
    }

    Ok(RangeSpec::Range { start, end })
}

/// Content-Range の start / end / complete_length の整合性を検証する
///
/// RFC 9110 Section 14.4 (行 6634-6638) の validity rule:
/// - last-pos < first-pos は invalid
/// - complete-length <= last-pos は invalid
fn validate_content_range_parts(
    start: u64,
    end: u64,
    complete_length: Option<u64>,
) -> Result<(), RangeError> {
    if start > end {
        return Err(RangeError::InvalidBounds);
    }
    if let Some(len) = complete_length
        && len <= end
    {
        return Err(RangeError::InvalidBounds);
    }
    Ok(())
}

/// Content-Range ヘッダー (RFC 9110 Section 14.4)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentRange {
    /// 範囲単位
    unit: String,
    /// 開始位置
    start: Option<u64>,
    /// 終了位置
    end: Option<u64>,
    /// 完全な長さ (不明な場合は None)
    complete_length: Option<u64>,
}

impl ContentRange {
    /// Content-Range ヘッダーをパース
    pub fn parse(input: &str) -> Result<Self, RangeError> {
        let input = trim_ows(input);
        if input.is_empty() {
            return Err(RangeError::Empty);
        }

        // unit range/length の形式
        let space_pos = input.find(' ').ok_or(RangeError::InvalidFormat)?;
        let unit = trim_ows(&input[..space_pos]);
        let rest = trim_ows(&input[space_pos + 1..]);

        // RFC 9110 Section 14.1: range-unit = token
        if !is_valid_token(unit) {
            return Err(RangeError::InvalidUnit);
        }

        // range/length
        let slash_pos = rest.find('/').ok_or(RangeError::InvalidFormat)?;
        let range_str = trim_ows(&rest[..slash_pos]);
        let length_str = trim_ows(&rest[slash_pos + 1..]);

        let complete_length = if length_str == "*" {
            None
        } else {
            Some(
                length_str
                    .parse::<u64>()
                    .map_err(|_| RangeError::InvalidFormat)?,
            )
        };

        if range_str == "*" {
            // RFC 9110 Section 14.4: unsatisfied-range = "*/" complete-length
            // complete-length = 1*DIGIT (必須)
            if complete_length.is_none() {
                return Err(RangeError::InvalidFormat);
            }
            return Ok(ContentRange {
                unit: unit.to_string(),
                start: None,
                end: None,
                complete_length,
            });
        }

        // start-end
        let dash_pos = range_str.find('-').ok_or(RangeError::InvalidFormat)?;
        let start = range_str[..dash_pos]
            .parse::<u64>()
            .map_err(|_| RangeError::InvalidFormat)?;
        let end = range_str[dash_pos + 1..]
            .parse::<u64>()
            .map_err(|_| RangeError::InvalidFormat)?;

        validate_content_range_parts(start, end, complete_length)?;

        Ok(ContentRange {
            unit: unit.to_string(),
            start: Some(start),
            end: Some(end),
            complete_length,
        })
    }

    /// 新しい Content-Range を作成 (bytes)
    ///
    /// # Panics
    ///
    /// - `start > end` の場合 panic する
    /// - `complete_length` が `Some(cl)` かつ `cl <= end` の場合 panic する
    ///
    /// `end = u64::MAX` のときは `complete_length` に `Some(_)` を指定できない
    /// (`u64` の最大値を超える値を表現できないため)。
    /// `complete_length = None` (不明) で構築すること。
    pub fn new_bytes(start: u64, end: u64, complete_length: Option<u64>) -> Self {
        assert!(start <= end, "ContentRange: start must be <= end");
        if let Some(len) = complete_length {
            assert!(
                len > end,
                "ContentRange: complete_length must be > last-pos"
            );
        }
        ContentRange {
            unit: "bytes".to_string(),
            start: Some(start),
            end: Some(end),
            complete_length,
        }
    }

    /// 範囲が満たせない場合の Content-Range (bytes */total)
    pub fn unsatisfied(unit: &str, complete_length: u64) -> Self {
        ContentRange {
            unit: unit.to_string(),
            start: None,
            end: None,
            complete_length: Some(complete_length),
        }
    }

    /// 単位を取得
    pub fn unit(&self) -> &str {
        &self.unit
    }

    /// 開始位置を取得
    pub fn start(&self) -> Option<u64> {
        self.start
    }

    /// 終了位置を取得
    pub fn end(&self) -> Option<u64> {
        self.end
    }

    /// 完全な長さを取得
    pub fn complete_length(&self) -> Option<u64> {
        self.complete_length
    }

    /// 範囲の長さを取得
    ///
    /// `(start=0, end=u64::MAX)` のように結果が `u64` に収まらない場合は `None` を返す。
    pub fn length(&self) -> Option<u64> {
        match (self.start, self.end) {
            (Some(s), Some(e)) => e.checked_sub(s).and_then(|d| d.checked_add(1)),
            _ => None,
        }
    }

    /// 範囲が満たせないかどうか
    pub fn is_unsatisfied(&self) -> bool {
        self.start.is_none() && self.end.is_none()
    }
}

impl fmt::Display for ContentRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.start, self.end) {
            (Some(s), Some(e)) => {
                write!(f, "{} {}-{}/", self.unit, s, e)?;
            }
            _ => {
                write!(f, "{} */", self.unit)?;
            }
        }
        match self.complete_length {
            Some(len) => write!(f, "{}", len),
            None => write!(f, "*"),
        }
    }
}

/// Accept-Ranges ヘッダー (RFC 9110 Section 14.3)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AcceptRanges {
    /// 受け入れる範囲単位のリスト
    units: Vec<String>,
}

impl AcceptRanges {
    /// Accept-Ranges ヘッダーをパース
    pub fn parse(input: &str) -> Result<Self, RangeError> {
        let input = trim_ows(input);
        if input.is_empty() {
            return Err(RangeError::Empty);
        }

        let units: Vec<String> = input
            .split(',')
            .map(|s| trim_ows(s).to_string())
            .filter(|s| !s.is_empty())
            .collect();

        if units.is_empty() {
            return Err(RangeError::Empty);
        }

        // RFC 9110 Section 14.3: acceptable-ranges = 1#range-unit
        // range-unit = token
        for unit in &units {
            if !is_valid_token(unit) {
                return Err(RangeError::InvalidUnit);
            }
        }

        // RFC 9110 Section 14.3: "none" は範囲リクエスト非対応を示す予約語であり、
        // 他の単位と混在させることはできない
        if units.len() > 1 && units.iter().any(|u| u.eq_ignore_ascii_case("none")) {
            return Err(RangeError::InvalidUnit);
        }

        Ok(AcceptRanges { units })
    }

    /// bytes を作成
    pub fn bytes() -> Self {
        AcceptRanges {
            units: alloc::vec!["bytes".to_string()],
        }
    }

    /// none を作成
    pub fn none() -> Self {
        AcceptRanges {
            units: alloc::vec!["none".to_string()],
        }
    }

    /// 単位のリストを取得
    pub fn units(&self) -> &[String] {
        &self.units
    }

    /// bytes を受け入れるかどうか
    pub fn accepts_bytes(&self) -> bool {
        self.units.iter().any(|u| u.eq_ignore_ascii_case("bytes"))
    }

    /// 何も受け入れないかどうか
    pub fn is_none(&self) -> bool {
        self.units.len() == 1 && self.units[0].eq_ignore_ascii_case("none")
    }
}

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