hyperx/header/shared/
entity.rs

1use std::str::FromStr;
2use std::fmt::{self, Display};
3
4/// check that each char in the slice is either:
5/// 1. `%x21`, or
6/// 2. in the range `%x23` to `%x7E`, or
7/// 3. above `%x80`
8fn check_slice_validity(slice: &str) -> bool {
9    slice.bytes().all(|c|
10        c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >= b'\x80'))
11}
12
13/// An entity tag, defined in [RFC7232](https://tools.ietf.org/html/rfc7232#section-2.3)
14///
15/// An entity tag consists of a string enclosed by two literal double quotes.
16/// Preceding the first double quote is an optional weakness indicator,
17/// which always looks like `W/`. Examples for valid tags are `"xyzzy"` and `W/"xyzzy"`.
18///
19/// # ABNF
20///
21/// ```text
22/// entity-tag = [ weak ] opaque-tag
23/// weak       = %x57.2F ; "W/", case-sensitive
24/// opaque-tag = DQUOTE *etagc DQUOTE
25/// etagc      = %x21 / %x23-7E / obs-text
26///            ; VCHAR except double quotes, plus obs-text
27/// ```
28///
29/// # Comparison
30/// To check if two entity tags are equivalent in an application always use the `strong_eq` or
31/// `weak_eq` methods based on the context of the Tag. Only use `==` to check if two tags are
32/// identical.
33///
34/// The example below shows the results for a set of entity-tag pairs and
35/// both the weak and strong comparison function results:
36///
37/// | ETag 1  | ETag 2  | Strong Comparison | Weak Comparison |
38/// |---------|---------|-------------------|-----------------|
39/// | `W/"1"` | `W/"1"` | no match          | match           |
40/// | `W/"1"` | `W/"2"` | no match          | no match        |
41/// | `W/"1"` | `"1"`   | no match          | match           |
42/// | `"1"`   | `"1"`   | match             | match           |
43#[derive(Clone, Debug, Eq, PartialEq)]
44pub struct EntityTag {
45    /// Weakness indicator for the tag
46    pub weak: bool,
47    /// The opaque string in between the DQUOTEs
48    tag: String
49}
50
51impl EntityTag {
52    /// Constructs a new EntityTag.
53    /// # Panics
54    /// If the tag contains invalid characters.
55    pub fn new(weak: bool, tag: String) -> EntityTag {
56        assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
57        EntityTag { weak: weak, tag: tag }
58    }
59
60    /// Constructs a new weak EntityTag.
61    /// # Panics
62    /// If the tag contains invalid characters.
63    pub fn weak(tag: String) -> EntityTag {
64        EntityTag::new(true, tag)
65    }
66
67    /// Constructs a new strong EntityTag.
68    /// # Panics
69    /// If the tag contains invalid characters.
70    pub fn strong(tag: String) -> EntityTag {
71        EntityTag::new(false, tag)
72    }
73
74    /// Get the tag.
75    pub fn tag(&self) -> &str {
76        self.tag.as_ref()
77    }
78
79    /// Set the tag.
80    /// # Panics
81    /// If the tag contains invalid characters.
82    pub fn set_tag(&mut self, tag: String) {
83        assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
84        self.tag = tag
85    }
86
87    /// For strong comparison two entity-tags are equivalent if both are not weak and their
88    /// opaque-tags match character-by-character.
89    pub fn strong_eq(&self, other: &EntityTag) -> bool {
90        !self.weak && !other.weak && self.tag == other.tag
91    }
92
93    /// For weak comparison two entity-tags are equivalent if their
94    /// opaque-tags match character-by-character, regardless of either or
95    /// both being tagged as "weak".
96    pub fn weak_eq(&self, other: &EntityTag) -> bool {
97        self.tag == other.tag
98    }
99
100    /// The inverse of `EntityTag.strong_eq()`.
101    pub fn strong_ne(&self, other: &EntityTag) -> bool {
102        !self.strong_eq(other)
103    }
104
105    /// The inverse of `EntityTag.weak_eq()`.
106    pub fn weak_ne(&self, other: &EntityTag) -> bool {
107        !self.weak_eq(other)
108    }
109}
110
111impl Display for EntityTag {
112    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
113        if self.weak {
114            write!(f, "W/\"{}\"", self.tag)
115        } else {
116            write!(f, "\"{}\"", self.tag)
117        }
118    }
119}
120
121impl FromStr for EntityTag {
122    type Err = ::Error;
123    fn from_str(s: &str) -> ::Result<EntityTag> {
124        let length: usize = s.len();
125        let slice = &s[..];
126        // Early exits if it doesn't terminate in a DQUOTE.
127        if !slice.ends_with('"') || slice.len() < 2 {
128            return Err(::Error::Header);
129        }
130        // The etag is weak if its first char is not a DQUOTE.
131        if slice.len() >= 2 && slice.starts_with('"')
132                && check_slice_validity(&slice[1..length-1]) {
133            // No need to check if the last char is a DQUOTE,
134            // we already did that above.
135            return Ok(EntityTag { weak: false, tag: slice[1..length-1].to_owned() });
136        } else if slice.len() >= 4 && slice.starts_with("W/\"")
137                && check_slice_validity(&slice[3..length-1]) {
138            return Ok(EntityTag { weak: true, tag: slice[3..length-1].to_owned() });
139        }
140        Err(::Error::Header)
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::EntityTag;
147
148    #[test]
149    fn test_etag_parse_success() {
150        // Expected success
151        assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(),
152            EntityTag::strong("foobar".to_owned()));
153        assert_eq!("\"\"".parse::<EntityTag>().unwrap(),
154            EntityTag::strong("".to_owned()));
155        assert_eq!("W/\"weaktag\"".parse::<EntityTag>().unwrap(),
156            EntityTag::weak("weaktag".to_owned()));
157        assert_eq!("W/\"\x65\x62\"".parse::<EntityTag>().unwrap(),
158            EntityTag::weak("\x65\x62".to_owned()));
159        assert_eq!("W/\"\"".parse::<EntityTag>().unwrap(), EntityTag::weak("".to_owned()));
160    }
161
162    #[test]
163    fn test_etag_parse_failures() {
164        // Expected failures
165        assert!("no-dquotes".parse::<EntityTag>().is_err());
166        assert!("w/\"the-first-w-is-case-sensitive\"".parse::<EntityTag>().is_err());
167        assert!("".parse::<EntityTag>().is_err());
168        assert!("\"unmatched-dquotes1".parse::<EntityTag>().is_err());
169        assert!("unmatched-dquotes2\"".parse::<EntityTag>().is_err());
170        assert!("matched-\"dquotes\"".parse::<EntityTag>().is_err());
171    }
172
173    #[test]
174    fn test_etag_fmt() {
175        assert_eq!(format!("{}", EntityTag::strong("foobar".to_owned())), "\"foobar\"");
176        assert_eq!(format!("{}", EntityTag::strong("".to_owned())), "\"\"");
177        assert_eq!(format!("{}", EntityTag::weak("weak-etag".to_owned())), "W/\"weak-etag\"");
178        assert_eq!(format!("{}", EntityTag::weak("\u{0065}".to_owned())), "W/\"\x65\"");
179        assert_eq!(format!("{}", EntityTag::weak("".to_owned())), "W/\"\"");
180    }
181
182    #[test]
183    fn test_cmp() {
184        // | ETag 1  | ETag 2  | Strong Comparison | Weak Comparison |
185        // |---------|---------|-------------------|-----------------|
186        // | `W/"1"` | `W/"1"` | no match          | match           |
187        // | `W/"1"` | `W/"2"` | no match          | no match        |
188        // | `W/"1"` | `"1"`   | no match          | match           |
189        // | `"1"`   | `"1"`   | match             | match           |
190        let mut etag1 = EntityTag::weak("1".to_owned());
191        let mut etag2 = EntityTag::weak("1".to_owned());
192        assert!(!etag1.strong_eq(&etag2));
193        assert!(etag1.weak_eq(&etag2));
194        assert!(etag1.strong_ne(&etag2));
195        assert!(!etag1.weak_ne(&etag2));
196
197        etag1 = EntityTag::weak("1".to_owned());
198        etag2 = EntityTag::weak("2".to_owned());
199        assert!(!etag1.strong_eq(&etag2));
200        assert!(!etag1.weak_eq(&etag2));
201        assert!(etag1.strong_ne(&etag2));
202        assert!(etag1.weak_ne(&etag2));
203
204        etag1 = EntityTag::weak("1".to_owned());
205        etag2 = EntityTag::strong("1".to_owned());
206        assert!(!etag1.strong_eq(&etag2));
207        assert!(etag1.weak_eq(&etag2));
208        assert!(etag1.strong_ne(&etag2));
209        assert!(!etag1.weak_ne(&etag2));
210
211        etag1 = EntityTag::strong("1".to_owned());
212        etag2 = EntityTag::strong("1".to_owned());
213        assert!(etag1.strong_eq(&etag2));
214        assert!(etag1.weak_eq(&etag2));
215        assert!(!etag1.strong_ne(&etag2));
216        assert!(!etag1.weak_ne(&etag2));
217    }
218}