Skip to main content

range_requests/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3use std::{
4    num::{NonZero, NonZeroU64},
5    ops::RangeInclusive,
6};
7
8use bytes::Bytes;
9
10pub mod headers;
11
12use crate::headers::{
13    content_range::{Bound, HttpContentRange, Unsatisfiable},
14    range::HttpRange,
15};
16
17/// Returns a [`BodyRange`] of [`Bytes`] if the provided [`HttpRange`] is satisfiable, otherwise it returns [`UnsatisfiableRange`].
18///
19/// [`HttpRange`]: crate::headers::range::HttpRange
20pub fn serve_file_with_http_range(
21    body: Bytes,
22    http_range: Option<HttpRange>,
23) -> Result<BodyRange<Bytes>, UnsatisfiableRange> {
24    let size = u64::try_from(body.len()).expect("we do not support 128bit usize");
25    let size = NonZeroU64::try_from(size).map_err(|_| {
26        UnsatisfiableRange(HttpContentRange::Unsatisfiable(Unsatisfiable::new(size)))
27    })?;
28
29    let content_range = file_range(size, http_range)?;
30
31    let start = usize::try_from(*content_range.range.start()).expect("u64 doesn't fit usize");
32    let end = usize::try_from(*content_range.range.end()).expect("u64 doesn't fit usize");
33
34    Ok(BodyRange {
35        body: body.slice(start..=end),
36        header: content_range.header,
37    })
38}
39
40/// Returns a [`ContentRange`] if the provided [`HttpRange`] is satisfiable, otherwise it returns [`UnsatisfiableRange`].
41///
42/// [`HttpRange`]: crate::headers::range::HttpRange
43pub fn file_range(
44    size: NonZero<u64>,
45    http_range: Option<HttpRange>,
46) -> Result<ContentRange, UnsatisfiableRange> {
47    let size = size.get();
48
49    let Some(http_range) = http_range else {
50        return Ok(ContentRange {
51            header: None,
52            range: 0..=size - 1,
53        });
54    };
55
56    let range = match http_range {
57        HttpRange::StartingPoint(start) if start < size => start..=size - 1,
58        HttpRange::Range(range) if range.end() < size => range.start()..=range.end(),
59        HttpRange::Suffix(suffix) if suffix > 0 && suffix <= size => size - suffix..=size - 1,
60        _ => {
61            let content_range = HttpContentRange::Unsatisfiable(Unsatisfiable::new(size));
62            return Err(UnsatisfiableRange(content_range));
63        }
64    };
65
66    let content_range = HttpContentRange::Bound(Bound::new(range.clone(), Some(size)).unwrap());
67
68    Ok(ContentRange {
69        header: Some(content_range),
70        range,
71    })
72}
73
74/// A container for the payload slice and the optional `Content-Range` header.
75///
76/// The header is `None` only if the body was not sliced.
77///
78/// If the `axum` feature is enabled this struct also implements `IntoResponse`.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct BodyRange<T> {
81    body: T,
82    header: Option<HttpContentRange>,
83}
84
85impl<T> BodyRange<T> {
86    /// Returns the sliced body.
87    pub fn body(&self) -> &T {
88        &self.body
89    }
90
91    pub fn into_body(self) -> T {
92        self.body
93    }
94
95    /// Returns an option of [`HttpContentRange`].
96    /// If it's None the provided [`HttpRange`] was None too.
97    pub fn header(&self) -> Option<HttpContentRange> {
98        self.header
99    }
100}
101
102/// A container for the payload range and the optional `Content-Range` header.
103///
104/// The header is `None` only if the body was not sliced.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub struct ContentRange {
107    header: Option<HttpContentRange>,
108    range: RangeInclusive<u64>,
109}
110
111impl ContentRange {
112    /// Returns an option of [`HttpContentRange`].
113    /// If it's None the provided [`HttpRange`] was None too.
114    pub fn header(&self) -> Option<HttpContentRange> {
115        self.header
116    }
117
118    /// Returns a [`RangeInclusive`] of `u64` useful to manually slice the response body.
119    pub fn range(&self) -> &RangeInclusive<u64> {
120        &self.range
121    }
122}
123
124/// An unsatisfiable range request.
125///
126/// If the `axum` feature is enabled this struct also implements `IntoResponse`.
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct UnsatisfiableRange(HttpContentRange);
129
130impl UnsatisfiableRange {
131    /// Returns the [`HttpContentRange`] header.
132    pub fn header(&self) -> HttpContentRange {
133        self.0
134    }
135}
136
137#[cfg(feature = "axum")]
138mod axum {
139    use crate::{BodyRange, UnsatisfiableRange};
140
141    use axum_core::response::{IntoResponse, Response};
142    use bytes::Bytes;
143    use http::{HeaderValue, StatusCode, header::CONTENT_RANGE};
144
145    impl IntoResponse for BodyRange<Bytes> {
146        fn into_response(self) -> Response {
147            match self.header {
148                Some(range) => (
149                    StatusCode::PARTIAL_CONTENT,
150                    [(CONTENT_RANGE, HeaderValue::from(&range))],
151                    self.body,
152                )
153                    .into_response(),
154                None => (StatusCode::OK, self.body).into_response(),
155            }
156        }
157    }
158
159    impl IntoResponse for UnsatisfiableRange {
160        fn into_response(self) -> Response {
161            (
162                StatusCode::RANGE_NOT_SATISFIABLE,
163                [(CONTENT_RANGE, HeaderValue::from(&self.0))],
164            )
165                .into_response()
166        }
167    }
168}