Skip to main content

entity_tag/
lib.rs

1/*!
2# Entity Tag
3
4This crate provides a `EntityTag` structure and functions to deal with the ETag header field of HTTP.
5
6## Examples
7
8```rust
9use entity_tag::EntityTag;
10
11let etag1 = EntityTag::with_str(true, "foo").unwrap();
12let etag2 = EntityTag::from_str("\"foo\"").unwrap();
13
14assert_eq!(true, etag1.weak);
15assert_eq!(false, etag2.weak);
16
17assert!(etag1.weak_eq(&etag2));
18assert!(etag1.strong_ne(&etag2));
19```
20
21## No Std
22
23Disable the default features to compile this crate without std.
24
25```toml
26[dependencies.entity-tag]
27version = "*"
28default-features = false
29```
30
31## Hashers
32
33Generated ETag constructors are optional.
34Enable `weak-hasher` to use XXH3-128 weak ETag generation and `strong-hasher` to use BLAKE3-256 strong ETag generation.
35
36```toml
37[dependencies.entity-tag]
38version = "*"
39features = ["weak-hasher", "strong-hasher"]
40```
41
42File metadata tags use only the file length and modification time, not the file content.
43If the modification time is not available, they use only the file length.
44
45For strong validation, prefer `from_data_strong` with the bytes sent in the response.
46Only use `from_file_meta_strong` if the metadata values reliably distinguish every version and representation of the resource.
47
48```rust
49use entity_tag::EntityTag;
50
51# #[cfg(feature = "weak-hasher")]
52# {
53let etag3 = EntityTag::from_data(&[102, 111, 111]);
54assert_eq!(r#"W/"ea75LoNFQSGrbl9kB359ig""#, etag3.to_string());
55# }
56
57# #[cfg(feature = "strong-hasher")]
58# {
59let etag4 = EntityTag::from_data_strong(&[102, 111, 111]);
60assert_eq!(r#""BOC7OfMLGj/rifU2yTvhUFVILfdIZ0sA0m5adXd3Auk""#, etag4.to_string());
61# }
62
63# #[cfg(all(feature = "std", feature = "weak-hasher"))]
64# {
65let metadata = std::fs::metadata(std::env::current_exe().unwrap()).unwrap();
66let etag5 = EntityTag::from_file_meta(&metadata);
67println!("{}", etag5);
68# }
69
70# #[cfg(all(feature = "std", feature = "strong-hasher"))]
71# {
72let metadata = std::fs::metadata(std::env::current_exe().unwrap()).unwrap();
73let etag6 = EntityTag::from_file_meta_strong(&metadata);
74println!("{}", etag6);
75# }
76```
77*/
78
79#![cfg_attr(not(feature = "std"), no_std)]
80
81extern crate alloc;
82
83mod entity_tag_error;
84
85use alloc::{borrow::Cow, string::String};
86use core::{
87    fmt::{self, Display, Formatter, Write},
88    str::FromStr,
89};
90#[cfg(all(feature = "std", any(feature = "weak-hasher", feature = "strong-hasher")))]
91use std::fs::Metadata;
92#[cfg(all(feature = "std", any(feature = "weak-hasher", feature = "strong-hasher")))]
93use std::time::UNIX_EPOCH;
94
95#[cfg(any(feature = "weak-hasher", feature = "strong-hasher"))]
96use base64::{Engine, engine::general_purpose::STANDARD_NO_PAD};
97pub use entity_tag_error::EntityTagError;
98#[cfg(feature = "weak-hasher")]
99use xxhash_rust::xxh3::xxh3_128;
100
101#[cfg(feature = "strong-hasher")]
102#[inline]
103fn encode_blake3_256(data: &[u8]) -> String {
104    STANDARD_NO_PAD.encode(blake3::hash(data).as_bytes())
105}
106
107#[cfg(feature = "weak-hasher")]
108#[inline]
109fn encode_xxh3_128_data(data: &[u8]) -> String {
110    encode_xxh3_128(xxh3_128(data))
111}
112
113#[cfg(feature = "weak-hasher")]
114#[inline]
115fn encode_xxh3_128(hash: u128) -> String {
116    STANDARD_NO_PAD.encode(hash.to_be_bytes())
117}
118
119#[cfg(all(feature = "std", any(feature = "weak-hasher", feature = "strong-hasher")))]
120fn encode_file_meta<F>(metadata: &Metadata, encode: F) -> String
121where
122    F: Fn(&[u8]) -> String, {
123    let len_bytes = metadata.len().to_le_bytes();
124
125    if let Ok(modified_time) = metadata.modified() {
126        match modified_time.duration_since(UNIX_EPOCH) {
127            Ok(time) => {
128                let mut bytes = [0; 24];
129
130                bytes[..8].copy_from_slice(&len_bytes);
131                bytes[8..].copy_from_slice(&time.as_nanos().to_le_bytes());
132
133                encode(&bytes)
134            },
135            Err(err) => {
136                let mut bytes = [0; 25];
137
138                bytes[..8].copy_from_slice(&len_bytes);
139                bytes[8] = b'-';
140                bytes[9..].copy_from_slice(&err.duration().as_nanos().to_le_bytes());
141
142                encode(&bytes)
143            },
144        }
145    } else {
146        encode(&len_bytes)
147    }
148}
149
150/// An entity tag, defined in [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#section-8.8.3).
151#[derive(Debug, Clone, Eq, Hash, PartialEq)]
152pub struct EntityTag<'t> {
153    /// Whether to have a weakness indicator.
154    pub weak: bool,
155    /// The opaque tag content without the surrounding double quotes.
156    tag:      Cow<'t, str>,
157}
158
159impl<'t> EntityTag<'t> {
160    /// `ETag`
161    pub const HEADER_NAME: &'static str = "ETag";
162}
163
164impl<'t> EntityTag<'t> {
165    /// Construct a new EntityTag without checking.
166    ///
167    /// # Safety
168    /// The caller must ensure `tag` is a valid unquoted entity-tag value, because this function skips all validation.
169    #[inline]
170    pub const unsafe fn new_unchecked(weak: bool, tag: Cow<'t, str>) -> Self {
171        EntityTag {
172            weak,
173            tag,
174        }
175    }
176
177    /// Get the tag. The double quotes are not included.
178    #[inline]
179    pub const fn get_tag_cow(&self) -> &Cow<'t, str> {
180        &self.tag
181    }
182}
183
184impl<'t> EntityTag<'t> {
185    /// Construct a new EntityTag without checking.
186    ///
187    /// # Safety
188    /// The caller must ensure `tag` is a valid unquoted entity-tag value, because this function skips all validation.
189    #[inline]
190    pub unsafe fn with_string_unchecked<S: Into<String>>(weak: bool, tag: S) -> EntityTag<'static> {
191        EntityTag {
192            weak,
193            tag: Cow::from(tag.into()),
194        }
195    }
196
197    /// Construct a new EntityTag without checking.
198    ///
199    /// # Safety
200    /// The caller must ensure `tag` is a valid unquoted entity-tag value, because this function skips all validation.
201    #[inline]
202    pub unsafe fn with_str_unchecked<S: ?Sized + AsRef<str>>(weak: bool, tag: &'t S) -> Self {
203        EntityTag {
204            weak,
205            tag: Cow::from(tag.as_ref()),
206        }
207    }
208}
209
210impl<'t> EntityTag<'t> {
211    #[inline]
212    fn check_unquoted_tag(s: &str) -> Result<(), EntityTagError> {
213        if s.bytes().all(|c| c == b'\x21' || (b'\x23'..=b'\x7e').contains(&c) || c >= b'\x80') {
214            Ok(())
215        } else {
216            Err(EntityTagError::InvalidTag)
217        }
218    }
219
220    fn check_tag(s: &str) -> Result<bool, EntityTagError> {
221        let (s, quoted) =
222            if let Some(stripped) = s.strip_prefix('"') { (stripped, true) } else { (s, false) };
223
224        let s = if quoted {
225            if let Some(stripped) = s.strip_suffix('"') {
226                stripped
227            } else {
228                return Err(EntityTagError::MissingClosingDoubleQuote);
229            }
230        } else {
231            s
232        };
233
234        // now check the ETag characters
235
236        Self::check_unquoted_tag(s)?;
237
238        Ok(quoted)
239    }
240
241    /// Construct a new EntityTag from an opaque tag, with or without surrounding double quotes.
242    #[inline]
243    pub fn with_string<S: AsRef<str> + Into<String>>(
244        weak: bool,
245        tag: S,
246    ) -> Result<EntityTag<'static>, EntityTagError> {
247        let mut tag: String = tag.into();
248
249        let quoted = Self::check_tag(&tag)?;
250
251        if quoted {
252            tag.remove(tag.len() - 1);
253            tag.remove(0);
254        }
255
256        Ok(EntityTag {
257            weak,
258            tag: Cow::from(tag),
259        })
260    }
261
262    /// Construct a new EntityTag from an opaque tag, with or without surrounding double quotes.
263    #[inline]
264    pub fn with_str<S: ?Sized + AsRef<str>>(
265        weak: bool,
266        tag: &'t S,
267    ) -> Result<Self, EntityTagError> {
268        let tag = tag.as_ref();
269
270        let quoted = Self::check_tag(tag)?;
271
272        let tag = if quoted { &tag[1..(tag.len() - 1)] } else { tag };
273
274        Ok(EntityTag {
275            weak,
276            tag: Cow::from(tag),
277        })
278    }
279}
280
281impl<'t> EntityTag<'t> {
282    #[inline]
283    fn check_opaque_tag(s: &str) -> Result<(), EntityTagError> {
284        if let Some(s) = s.strip_prefix('"') {
285            if let Some(s) = s.strip_suffix('"') {
286                // now check the ETag characters
287                Self::check_unquoted_tag(s)
288            } else {
289                Err(EntityTagError::MissingClosingDoubleQuote)
290            }
291        } else {
292            Err(EntityTagError::MissingStartingDoubleQuote)
293        }
294    }
295
296    /// Parse and construct a new EntityTag from a full ETag header value.
297    pub fn from_string<S: AsRef<str> + Into<String>>(
298        etag: S,
299    ) -> Result<EntityTag<'static>, EntityTagError> {
300        let mut tag: String = etag.into();
301
302        let weak = {
303            let s = tag.as_str();
304
305            let (weak, opaque_tag) = if let Some(opaque_tag) = s.strip_prefix("W/") {
306                (true, opaque_tag)
307            } else {
308                (false, s)
309            };
310
311            Self::check_opaque_tag(opaque_tag)?;
312
313            weak
314        };
315
316        tag.remove(tag.len() - 1);
317
318        if weak {
319            tag.replace_range(..3, "");
320        } else {
321            tag.remove(0);
322        }
323
324        Ok(EntityTag {
325            weak,
326            tag: Cow::from(tag),
327        })
328    }
329
330    /// Parse and construct a new EntityTag from a full ETag header value.
331    #[allow(clippy::should_implement_trait)]
332    pub fn from_str<S: ?Sized + AsRef<str>>(etag: &'t S) -> Result<Self, EntityTagError> {
333        let s = etag.as_ref();
334
335        let (weak, opaque_tag) = if let Some(opaque_tag) = s.strip_prefix("W/") {
336            (true, opaque_tag)
337        } else {
338            (false, s)
339        };
340
341        Self::check_opaque_tag(opaque_tag)?;
342
343        Ok(EntityTag {
344            weak,
345            tag: Cow::from(&opaque_tag[1..(opaque_tag.len() - 1)]),
346        })
347    }
348
349    #[cfg(feature = "weak-hasher")]
350    /// Construct a weak EntityTag from data with an XXH3-128 fingerprint.
351    ///
352    /// Requires the `weak-hasher` feature.
353    #[inline]
354    pub fn from_data<S: ?Sized + AsRef<[u8]>>(data: &S) -> EntityTag<'static> {
355        let tag = encode_xxh3_128_data(data.as_ref());
356
357        EntityTag {
358            weak: true, tag: Cow::from(tag)
359        }
360    }
361
362    #[cfg(feature = "strong-hasher")]
363    /// Construct a strong EntityTag from data with a BLAKE3-256 digest.
364    ///
365    /// Requires the `strong-hasher` feature.
366    #[inline]
367    pub fn from_data_strong<S: ?Sized + AsRef<[u8]>>(data: &S) -> EntityTag<'static> {
368        let tag = encode_blake3_256(data.as_ref());
369
370        EntityTag {
371            weak: false, tag: Cow::from(tag)
372        }
373    }
374
375    #[cfg(all(feature = "std", feature = "weak-hasher"))]
376    /// Construct a weak EntityTag from file metadata with an XXH3-128 fingerprint.
377    ///
378    /// Requires the `std` and `weak-hasher` features.
379    /// This method hashes the file length and modification time, not the file content.
380    /// If the modification time is not available, it hashes only the file length.
381    #[inline]
382    pub fn from_file_meta(metadata: &Metadata) -> EntityTag<'static> {
383        let tag = encode_file_meta(metadata, encode_xxh3_128_data);
384
385        EntityTag {
386            weak: true, tag: Cow::from(tag)
387        }
388    }
389
390    #[cfg(all(feature = "std", feature = "strong-hasher"))]
391    /// Construct a strong EntityTag from file metadata with a BLAKE3-256 digest.
392    ///
393    /// Requires the `std` and `strong-hasher` features.
394    ///
395    /// # Strong Validation
396    /// This method hashes the file length and modification time, not the file content.
397    /// If the modification time is not available, it hashes only the file length.
398    /// Only use this method if these metadata values change for every content change and distinguish all representations of the same resource.
399    /// Otherwise, use [`Self::from_data_strong`] with the bytes sent in the response.
400    #[inline]
401    pub fn from_file_meta_strong(metadata: &Metadata) -> EntityTag<'static> {
402        let tag = encode_file_meta(metadata, encode_blake3_256);
403
404        EntityTag {
405            weak: false, tag: Cow::from(tag)
406        }
407    }
408}
409
410impl<'t> EntityTag<'t> {
411    /// Get the tag. The double quotes are not included.
412    #[inline]
413    pub fn get_tag(&self) -> &str {
414        self.tag.as_ref()
415    }
416
417    /// Into the tag. The double quotes are not included.
418    #[inline]
419    pub fn into_tag(self) -> Cow<'t, str> {
420        self.tag
421    }
422
423    /// Extracts the owned data.
424    #[inline]
425    pub fn into_owned(self) -> EntityTag<'static> {
426        let tag = self.tag.into_owned();
427
428        EntityTag {
429            weak: self.weak, tag: Cow::from(tag)
430        }
431    }
432}
433
434impl<'t> EntityTag<'t> {
435    /// For strong comparison two entity-tags are equivalent if both are not weak and their opaque-tags match character-by-character.
436    #[inline]
437    pub fn strong_eq(&self, other: &EntityTag) -> bool {
438        !self.weak && !other.weak && self.tag == other.tag
439    }
440
441    /// For weak comparison two entity-tags are equivalent if their opaque-tags match character-by-character, regardless of either or both being tagged as "weak".
442    #[inline]
443    pub fn weak_eq(&self, other: &EntityTag) -> bool {
444        self.tag == other.tag
445    }
446
447    /// The inverse of `strong_eq`.
448    #[inline]
449    pub fn strong_ne(&self, other: &EntityTag) -> bool {
450        !self.strong_eq(other)
451    }
452
453    /// The inverse of `weak_eq`.
454    #[inline]
455    pub fn weak_ne(&self, other: &EntityTag) -> bool {
456        !self.weak_eq(other)
457    }
458}
459
460impl FromStr for EntityTag<'static> {
461    type Err = EntityTagError;
462
463    #[inline]
464    fn from_str(s: &str) -> Result<Self, Self::Err> {
465        // Calls the inherent borrowed parser (inherent methods take priority over trait methods), then copies the tag.
466        EntityTag::from_str(s).map(EntityTag::into_owned)
467    }
468}
469
470impl<'t> Display for EntityTag<'t> {
471    #[inline]
472    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
473        if self.weak {
474            f.write_str("W/")?;
475        }
476
477        f.write_char('"')?;
478        f.write_str(self.tag.as_ref())?;
479        f.write_char('"')
480    }
481}