1#![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#[derive(Debug, Clone, Eq, Hash, PartialEq)]
152pub struct EntityTag<'t> {
153 pub weak: bool,
155 tag: Cow<'t, str>,
157}
158
159impl<'t> EntityTag<'t> {
160 pub const HEADER_NAME: &'static str = "ETag";
162}
163
164impl<'t> EntityTag<'t> {
165 #[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 #[inline]
179 pub const fn get_tag_cow(&self) -> &Cow<'t, str> {
180 &self.tag
181 }
182}
183
184impl<'t> EntityTag<'t> {
185 #[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 #[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 Self::check_unquoted_tag(s)?;
237
238 Ok(quoted)
239 }
240
241 #[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 #[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 Self::check_unquoted_tag(s)
288 } else {
289 Err(EntityTagError::MissingClosingDoubleQuote)
290 }
291 } else {
292 Err(EntityTagError::MissingStartingDoubleQuote)
293 }
294 }
295
296 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 #[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 #[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 #[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 #[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 #[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 #[inline]
413 pub fn get_tag(&self) -> &str {
414 self.tag.as_ref()
415 }
416
417 #[inline]
419 pub fn into_tag(self) -> Cow<'t, str> {
420 self.tag
421 }
422
423 #[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 #[inline]
437 pub fn strong_eq(&self, other: &EntityTag) -> bool {
438 !self.weak && !other.weak && self.tag == other.tag
439 }
440
441 #[inline]
443 pub fn weak_eq(&self, other: &EntityTag) -> bool {
444 self.tag == other.tag
445 }
446
447 #[inline]
449 pub fn strong_ne(&self, other: &EntityTag) -> bool {
450 !self.strong_eq(other)
451 }
452
453 #[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 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}