actix_web/http/header/
if_range.rs

1use std::fmt::{self, Display, Write};
2
3use super::{
4    from_one_raw_str, EntityTag, Header, HeaderName, HeaderValue, HttpDate, InvalidHeaderValue,
5    TryIntoHeaderValue, Writer,
6};
7use crate::{error::ParseError, http::header, HttpMessage};
8
9/// `If-Range` header, defined
10/// in [RFC 7233 ยง3.2](https://datatracker.ietf.org/doc/html/rfc7233#section-3.2)
11///
12/// If a client has a partial copy of a representation and wishes to have
13/// an up-to-date copy of the entire representation, it could use the
14/// Range header field with a conditional GET (using either or both of
15/// If-Unmodified-Since and If-Match.)  However, if the precondition
16/// fails because the representation has been modified, the client would
17/// then have to make a second request to obtain the entire current
18/// representation.
19///
20/// The `If-Range` header field allows a client to \"short-circuit\" the
21/// second request.  Informally, its meaning is as follows: if the
22/// representation is unchanged, send me the part(s) that I am requesting
23/// in Range; otherwise, send me the entire representation.
24///
25/// # ABNF
26/// ```plain
27/// If-Range = entity-tag / HTTP-date
28/// ```
29///
30/// # Example Values
31///
32/// * `Sat, 29 Oct 1994 19:43:31 GMT`
33/// * `\"xyzzy\"`
34///
35/// # Examples
36/// ```
37/// use actix_web::HttpResponse;
38/// use actix_web::http::header::{EntityTag, IfRange};
39///
40/// let mut builder = HttpResponse::Ok();
41/// builder.insert_header(
42///     IfRange::EntityTag(
43///         EntityTag::new(false, "abc".to_owned())
44///     )
45/// );
46/// ```
47///
48/// ```
49/// use std::time::{Duration, SystemTime};
50/// use actix_web::{http::header::IfRange, HttpResponse};
51///
52/// let mut builder = HttpResponse::Ok();
53/// let fetched = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
54/// builder.insert_header(
55///     IfRange::Date(fetched.into())
56/// );
57/// ```
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub enum IfRange {
60    /// The entity-tag the client has of the resource.
61    EntityTag(EntityTag),
62
63    /// The date when the client retrieved the resource.
64    Date(HttpDate),
65}
66
67impl Header for IfRange {
68    fn name() -> HeaderName {
69        header::IF_RANGE
70    }
71    #[inline]
72    fn parse<T>(msg: &T) -> Result<Self, ParseError>
73    where
74        T: HttpMessage,
75    {
76        let etag: Result<EntityTag, _> = from_one_raw_str(msg.headers().get(&header::IF_RANGE));
77        if let Ok(etag) = etag {
78            return Ok(IfRange::EntityTag(etag));
79        }
80        let date: Result<HttpDate, _> = from_one_raw_str(msg.headers().get(&header::IF_RANGE));
81        if let Ok(date) = date {
82            return Ok(IfRange::Date(date));
83        }
84        Err(ParseError::Header)
85    }
86}
87
88impl Display for IfRange {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match *self {
91            IfRange::EntityTag(ref x) => Display::fmt(x, f),
92            IfRange::Date(ref x) => Display::fmt(x, f),
93        }
94    }
95}
96
97impl TryIntoHeaderValue for IfRange {
98    type Error = InvalidHeaderValue;
99
100    fn try_into_value(self) -> Result<HeaderValue, Self::Error> {
101        let mut writer = Writer::new();
102        let _ = write!(&mut writer, "{}", self);
103        HeaderValue::from_maybe_shared(writer.take())
104    }
105}
106
107#[cfg(test)]
108mod test_parse_and_format {
109    use std::str;
110
111    use super::IfRange as HeaderField;
112    use crate::http::header::*;
113
114    crate::http::header::common_header_test!(test1, [b"Sat, 29 Oct 1994 19:43:31 GMT"]);
115    crate::http::header::common_header_test!(test2, [b"\"abc\""]);
116    crate::http::header::common_header_test!(test3, [b"this-is-invalid"], None::<IfRange>);
117}