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