rama_http_headers/common/
range.rs

1use std::ops::{Bound, RangeBounds};
2
3use rama_http_types::{HeaderName, HeaderValue};
4
5use crate::{Error, Header};
6
7/// `Range` header, defined in [RFC7233](https://tools.ietf.org/html/rfc7233#section-3.1)
8///
9/// The "Range" header field on a GET request modifies the method
10/// semantics to request transfer of only one or more subranges of the
11/// selected representation data, rather than the entire selected
12/// representation data.
13///
14/// # ABNF
15///
16/// ```text
17/// Range = byte-ranges-specifier / other-ranges-specifier
18/// other-ranges-specifier = other-range-unit "=" other-range-set
19/// other-range-set = 1*VCHAR
20///
21/// bytes-unit = "bytes"
22///
23/// byte-ranges-specifier = bytes-unit "=" byte-range-set
24/// byte-range-set = 1#(byte-range-spec / suffix-byte-range-spec)
25/// byte-range-spec = first-byte-pos "-" [last-byte-pos]
26/// first-byte-pos = 1*DIGIT
27/// last-byte-pos = 1*DIGIT
28/// ```
29///
30/// # Example values
31///
32/// * `bytes=1000-`
33/// * `bytes=-2000`
34/// * `bytes=0-1,30-40`
35/// * `bytes=0-10,20-90,-100`
36///
37/// # Examples
38///
39/// ```
40/// use rama_http_headers::Range;
41///
42///
43/// let range = Range::bytes(0..1234).unwrap();
44/// ```
45#[derive(Clone, Debug, PartialEq)]
46pub struct Range(HeaderValue);
47
48rama_utils::macros::error::static_str_error! {
49    #[doc = "range is not valid"]
50    pub struct InvalidRange;
51}
52
53impl Range {
54    /// Creates a `Range` header from bounds.
55    pub fn bytes(bounds: impl RangeBounds<u64>) -> Result<Self, InvalidRange> {
56        let v = match (bounds.start_bound(), bounds.end_bound()) {
57            (Bound::Included(start), Bound::Included(end)) => format!("bytes={}-{}", start, end),
58            (Bound::Included(start), Bound::Excluded(&end)) => {
59                format!("bytes={}-{}", start, end - 1)
60            }
61            (Bound::Included(start), Bound::Unbounded) => format!("bytes={}-", start),
62            // These do not directly translate.
63            //(Bound::Unbounded, Bound::Included(end)) => format!("bytes=-{}", end),
64            //(Bound::Unbounded, Bound::Excluded(&end)) => format!("bytes=-{}", end - 1),
65            _ => return Err(InvalidRange),
66        };
67
68        Ok(Range(HeaderValue::from_str(&v).unwrap()))
69    }
70
71    /// Iterate the range sets as a tuple of bounds, if valid with length.
72    ///
73    /// The length of the content is passed as an argument, and all ranges
74    /// that can be satisfied will be iterated.
75    pub fn satisfiable_ranges(
76        &self,
77        len: u64,
78    ) -> impl Iterator<Item = (Bound<u64>, Bound<u64>)> + '_ {
79        let s = self
80            .0
81            .to_str()
82            .expect("valid string checked in Header::decode()");
83
84        s["bytes=".len()..].split(',').filter_map(move |spec| {
85            let mut iter = spec.trim().splitn(2, '-');
86            let start = parse_bound(iter.next()?)?;
87            let end = parse_bound(iter.next()?)?;
88
89            // Unbounded ranges in HTTP are actually a suffix
90            // For example, `-100` means the last 100 bytes.
91            if let Bound::Unbounded = start {
92                if let Bound::Included(end) = end {
93                    if len < end {
94                        // Last N bytes is larger than available!
95                        return None;
96                    }
97                    return Some((Bound::Included(len - end), Bound::Unbounded));
98                }
99                // else fall through
100            }
101
102            Some((start, end))
103        })
104    }
105}
106
107fn parse_bound(s: &str) -> Option<Bound<u64>> {
108    if s.is_empty() {
109        return Some(Bound::Unbounded);
110    }
111
112    s.parse().ok().map(Bound::Included)
113}
114
115impl Header for Range {
116    fn name() -> &'static HeaderName {
117        &::rama_http_types::header::RANGE
118    }
119
120    fn decode<'i, I: Iterator<Item = &'i HeaderValue>>(values: &mut I) -> Result<Self, Error> {
121        values
122            .next()
123            .and_then(|val| {
124                if val.to_str().ok()?.starts_with("bytes=") {
125                    Some(Range(val.clone()))
126                } else {
127                    None
128                }
129            })
130            .ok_or_else(Error::invalid)
131    }
132
133    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
134        values.extend(::std::iter::once(self.0.clone()));
135    }
136}
137
138/*
139
140impl ByteRangeSpec {
141    /// Given the full length of the entity, attempt to normalize the byte range
142    /// into an satisfiable end-inclusive (from, to) range.
143    ///
144    /// The resulting range is guaranteed to be a satisfiable range within the bounds
145    /// of `0 <= from <= to < full_length`.
146    ///
147    /// If the byte range is deemed unsatisfiable, `None` is returned.
148    /// An unsatisfiable range is generally cause for a server to either reject
149    /// the client request with a `416 Range Not Satisfiable` status code, or to
150    /// simply ignore the range header and serve the full entity using a `200 OK`
151    /// status code.
152    ///
153    /// This function closely follows [RFC 7233][1] section 2.1.
154    /// As such, it considers ranges to be satisfiable if they meet the following
155    /// conditions:
156    ///
157    /// > If a valid byte-range-set includes at least one byte-range-spec with
158    /// a first-byte-pos that is less than the current length of the
159    /// representation, or at least one suffix-byte-range-spec with a
160    /// non-zero suffix-length, then the byte-range-set is satisfiable.
161    /// Otherwise, the byte-range-set is unsatisfiable.
162    ///
163    /// The function also computes remainder ranges based on the RFC:
164    ///
165    /// > If the last-byte-pos value is
166    /// absent, or if the value is greater than or equal to the current
167    /// length of the representation data, the byte range is interpreted as
168    /// the remainder of the representation (i.e., the server replaces the
169    /// value of last-byte-pos with a value that is one less than the current
170    /// length of the selected representation).
171    ///
172    /// [1]: https://tools.ietf.org/html/rfc7233
173    pub fn to_satisfiable_range(&self, full_length: u64) -> Option<(u64, u64)> {
174        // If the full length is zero, there is no satisfiable end-inclusive range.
175        if full_length == 0 {
176            return None;
177        }
178        match self {
179            &ByteRangeSpec::FromTo(from, to) => {
180                if from < full_length && from <= to {
181                    Some((from, ::std::cmp::min(to, full_length - 1)))
182                } else {
183                    None
184                }
185            },
186            &ByteRangeSpec::AllFrom(from) => {
187                if from < full_length {
188                    Some((from, full_length - 1))
189                } else {
190                    None
191                }
192            },
193            &ByteRangeSpec::Last(last) => {
194                if last > 0 {
195                    // From the RFC: If the selected representation is shorter
196                    // than the specified suffix-length,
197                    // the entire representation is used.
198                    if last > full_length {
199                        Some((0, full_length - 1))
200                    } else {
201                        Some((full_length - last, full_length - 1))
202                    }
203                } else {
204                    None
205                }
206            }
207        }
208    }
209}
210
211impl Range {
212    /// Get the most common byte range header ("bytes=from-to")
213    pub fn bytes(from: u64, to: u64) -> Range {
214        Range::Bytes(vec![ByteRangeSpec::FromTo(from, to)])
215    }
216
217    /// Get byte range header with multiple subranges
218    /// ("bytes=from1-to1,from2-to2,fromX-toX")
219    pub fn bytes_multi(ranges: Vec<(u64, u64)>) -> Range {
220        Range::Bytes(ranges.iter().map(|r| ByteRangeSpec::FromTo(r.0, r.1)).collect())
221    }
222}
223
224
225impl fmt::Display for ByteRangeSpec {
226    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227        match *self {
228            ByteRangeSpec::FromTo(from, to) => write!(f, "{}-{}", from, to),
229            ByteRangeSpec::Last(pos) => write!(f, "-{}", pos),
230            ByteRangeSpec::AllFrom(pos) => write!(f, "{}-", pos),
231        }
232    }
233}
234
235
236impl fmt::Display for Range {
237    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
238        match *self {
239            Range::Bytes(ref ranges) => {
240                try!(write!(f, "bytes="));
241
242                for (i, range) in ranges.iter().enumerate() {
243                    if i != 0 {
244                        try!(f.write_str(","));
245                    }
246                    try!(Display::fmt(range, f));
247                }
248                Ok(())
249            },
250            Range::Unregistered(ref unit, ref range_str) => {
251                write!(f, "{}={}", unit, range_str)
252            },
253        }
254    }
255}
256
257impl FromStr for Range {
258    type Err = ::Error;
259
260    fn from_str(s: &str) -> ::Result<Range> {
261        let mut iter = s.splitn(2, '=');
262
263        match (iter.next(), iter.next()) {
264            (Some("bytes"), Some(ranges)) => {
265                let ranges = from_comma_delimited(ranges);
266                if ranges.is_empty() {
267                    return Err(::Error::Header);
268                }
269                Ok(Range::Bytes(ranges))
270            }
271            (Some(unit), Some(range_str)) if unit != "" && range_str != "" => {
272                Ok(Range::Unregistered(unit.to_owned(), range_str.to_owned()))
273
274            },
275            _ => Err(::Error::Header)
276        }
277    }
278}
279
280impl FromStr for ByteRangeSpec {
281    type Err = ::Error;
282
283    fn from_str(s: &str) -> ::Result<ByteRangeSpec> {
284        let mut parts = s.splitn(2, '-');
285
286        match (parts.next(), parts.next()) {
287            (Some(""), Some(end)) => {
288                end.parse().or(Err(::Error::Header)).map(ByteRangeSpec::Last)
289            },
290            (Some(start), Some("")) => {
291                start.parse().or(Err(::Error::Header)).map(ByteRangeSpec::AllFrom)
292            },
293            (Some(start), Some(end)) => {
294                match (start.parse(), end.parse()) {
295                    (Ok(start), Ok(end)) if start <= end => Ok(ByteRangeSpec::FromTo(start, end)),
296                    _ => Err(::Error::Header)
297                }
298            },
299            _ => Err(::Error::Header)
300        }
301    }
302}
303
304fn from_comma_delimited<T: FromStr>(s: &str) -> Vec<T> {
305    s.split(',')
306        .filter_map(|x| match x.trim() {
307            "" => None,
308            y => Some(y)
309        })
310        .filter_map(|x| x.parse().ok())
311        .collect()
312}
313
314impl Header for Range {
315
316    fn header_name() -> &'static str {
317        static NAME: &'static str = "Range";
318        NAME
319    }
320
321    fn parse_header(raw: &Raw) -> ::Result<Range> {
322        from_one_raw_str(raw)
323    }
324
325    fn fmt_header(&self, f: &mut ::Formatter) -> fmt::Result {
326        f.fmt_line(self)
327    }
328
329}
330
331#[test]
332fn test_parse_bytes_range_valid() {
333    let r: Range = Header::parse_header(&"bytes=1-100".into()).unwrap();
334    let r2: Range = Header::parse_header(&"bytes=1-100,-".into()).unwrap();
335    let r3 =  Range::bytes(1, 100);
336    assert_eq!(r, r2);
337    assert_eq!(r2, r3);
338
339    let r: Range = Header::parse_header(&"bytes=1-100,200-".into()).unwrap();
340    let r2: Range = Header::parse_header(&"bytes= 1-100 , 101-xxx,  200- ".into()).unwrap();
341    let r3 =  Range::Bytes(
342        vec![ByteRangeSpec::FromTo(1, 100), ByteRangeSpec::AllFrom(200)]
343    );
344    assert_eq!(r, r2);
345    assert_eq!(r2, r3);
346
347    let r: Range = Header::parse_header(&"bytes=1-100,-100".into()).unwrap();
348    let r2: Range = Header::parse_header(&"bytes=1-100, ,,-100".into()).unwrap();
349    let r3 =  Range::Bytes(
350        vec![ByteRangeSpec::FromTo(1, 100), ByteRangeSpec::Last(100)]
351    );
352    assert_eq!(r, r2);
353    assert_eq!(r2, r3);
354
355    let r: Range = Header::parse_header(&"custom=1-100,-100".into()).unwrap();
356    let r2 =  Range::Unregistered("custom".to_owned(), "1-100,-100".to_owned());
357    assert_eq!(r, r2);
358
359}
360
361#[test]
362fn test_parse_unregistered_range_valid() {
363    let r: Range = Header::parse_header(&"custom=1-100,-100".into()).unwrap();
364    let r2 =  Range::Unregistered("custom".to_owned(), "1-100,-100".to_owned());
365    assert_eq!(r, r2);
366
367    let r: Range = Header::parse_header(&"custom=abcd".into()).unwrap();
368    let r2 =  Range::Unregistered("custom".to_owned(), "abcd".to_owned());
369    assert_eq!(r, r2);
370
371    let r: Range = Header::parse_header(&"custom=xxx-yyy".into()).unwrap();
372    let r2 =  Range::Unregistered("custom".to_owned(), "xxx-yyy".to_owned());
373    assert_eq!(r, r2);
374}
375
376#[test]
377fn test_parse_invalid() {
378    let r: ::Result<Range> = Header::parse_header(&"bytes=1-a,-".into());
379    assert_eq!(r.ok(), None);
380
381    let r: ::Result<Range> = Header::parse_header(&"bytes=1-2-3".into());
382    assert_eq!(r.ok(), None);
383
384    let r: ::Result<Range> = Header::parse_header(&"abc".into());
385    assert_eq!(r.ok(), None);
386
387    let r: ::Result<Range> = Header::parse_header(&"bytes=1-100=".into());
388    assert_eq!(r.ok(), None);
389
390    let r: ::Result<Range> = Header::parse_header(&"bytes=".into());
391    assert_eq!(r.ok(), None);
392
393    let r: ::Result<Range> = Header::parse_header(&"custom=".into());
394    assert_eq!(r.ok(), None);
395
396    let r: ::Result<Range> = Header::parse_header(&"=1-100".into());
397    assert_eq!(r.ok(), None);
398}
399
400#[test]
401fn test_fmt() {
402    use Headers;
403
404    let mut headers = Headers::new();
405
406    headers.set(
407        Range::Bytes(
408            vec![ByteRangeSpec::FromTo(0, 1000), ByteRangeSpec::AllFrom(2000)]
409    ));
410    assert_eq!(&headers.to_string(), "Range: bytes=0-1000,2000-\r\n");
411
412    headers.clear();
413    headers.set(Range::Bytes(vec![]));
414
415    assert_eq!(&headers.to_string(), "Range: bytes=\r\n");
416
417    headers.clear();
418    headers.set(Range::Unregistered("custom".to_owned(), "1-xxx".to_owned()));
419
420    assert_eq!(&headers.to_string(), "Range: custom=1-xxx\r\n");
421}
422
423#[test]
424fn test_byte_range_spec_to_satisfiable_range() {
425    assert_eq!(Some((0, 0)), ByteRangeSpec::FromTo(0, 0).to_satisfiable_range(3));
426    assert_eq!(Some((1, 2)), ByteRangeSpec::FromTo(1, 2).to_satisfiable_range(3));
427    assert_eq!(Some((1, 2)), ByteRangeSpec::FromTo(1, 5).to_satisfiable_range(3));
428    assert_eq!(None, ByteRangeSpec::FromTo(3, 3).to_satisfiable_range(3));
429    assert_eq!(None, ByteRangeSpec::FromTo(2, 1).to_satisfiable_range(3));
430    assert_eq!(None, ByteRangeSpec::FromTo(0, 0).to_satisfiable_range(0));
431
432    assert_eq!(Some((0, 2)), ByteRangeSpec::AllFrom(0).to_satisfiable_range(3));
433    assert_eq!(Some((2, 2)), ByteRangeSpec::AllFrom(2).to_satisfiable_range(3));
434    assert_eq!(None, ByteRangeSpec::AllFrom(3).to_satisfiable_range(3));
435    assert_eq!(None, ByteRangeSpec::AllFrom(5).to_satisfiable_range(3));
436    assert_eq!(None, ByteRangeSpec::AllFrom(0).to_satisfiable_range(0));
437
438    assert_eq!(Some((1, 2)), ByteRangeSpec::Last(2).to_satisfiable_range(3));
439    assert_eq!(Some((2, 2)), ByteRangeSpec::Last(1).to_satisfiable_range(3));
440    assert_eq!(Some((0, 2)), ByteRangeSpec::Last(5).to_satisfiable_range(3));
441    assert_eq!(None, ByteRangeSpec::Last(0).to_satisfiable_range(3));
442    assert_eq!(None, ByteRangeSpec::Last(2).to_satisfiable_range(0));
443}
444
445bench_header!(bytes_multi, Range, { vec![b"bytes=1-1001,2001-3001,10001-".to_vec()]});
446bench_header!(custom_unit, Range, { vec![b"other=0-100000".to_vec()]});
447*/
448
449#[test]
450fn test_to_satisfiable_range_suffix() {
451    let range = super::test_decode::<Range>(&["bytes=-100"]).unwrap();
452    let bounds = range.satisfiable_ranges(350).next().unwrap();
453    assert_eq!(bounds, (Bound::Included(250), Bound::Unbounded));
454}
455
456#[test]
457fn test_to_unsatisfiable_range_suffix() {
458    let range = super::test_decode::<Range>(&["bytes=-350"]).unwrap();
459    let bounds = range.satisfiable_ranges(100).next();
460    assert_eq!(bounds, None);
461}