salvo_core 0.92.2

Salvo is a powerful web framework that can make your work easier.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
use std::borrow::Cow;
use std::cmp;
use std::fs::Metadata;
use std::io::Read as StdRead;
use std::ops::{Deref, DerefMut};
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use bytes::Bytes;
use enumflags2::{BitFlags, bitflags};
use headers::*;
use mime::Mime;
use tokio::fs::File;
#[allow(unused_imports)]
use tokio::io::{AsyncReadExt, AsyncSeekExt};

use super::{ChunkedFile, ChunkedState};
use crate::http::body::ResBody;
use crate::http::header::{
    CONTENT_DISPOSITION, CONTENT_ENCODING, CONTENT_TYPE, IF_NONE_MATCH, RANGE,
};
use crate::http::mime::{detect_text_mime, fill_mime_charset_if_need, is_charset_required_mime};
use crate::http::{HttpRange, Request, Response, StatusCode, StatusError};
use crate::{Depot, Error, Result, Writer, async_trait};

const CHUNK_SIZE: u64 = 1024 * 1024;

#[bitflags(default = Etag | LastModified | ContentDisposition)]
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum Flag {
    Etag = 0b0001,
    LastModified = 0b0010,
    ContentDisposition = 0b0100,
}

/// A file with an associated name and metadata for HTTP serving.
///
/// `NamedFile` wraps a file handle with HTTP-specific functionality including:
///
/// - Automatic MIME type detection based on file extension
/// - ETag generation for caching
/// - Last-Modified header support
/// - Content-Disposition header for downloads
/// - HTTP Range request support for partial content
/// - Chunked transfer for large files
///
/// # Opening Files
///
/// Files can be opened directly or through a builder:
///
/// ```
/// use salvo_core::fs::NamedFile;
///
/// async fn examples() {
///     // Simple open
///     let file = NamedFile::open("document.pdf").await;
///
///     // Builder pattern for more control
///     let file = NamedFile::builder("document.pdf")
///         .attached_name("report.pdf")
///         .buffer_size(65536)
///         .build()
///         .await;
/// }
/// ```
///
/// # Using as a Response
///
/// `NamedFile` implements [`Writer`], so it can be returned directly from handlers:
///
/// ```ignore
/// #[handler]
/// async fn download(res: &mut Response) -> Result<NamedFile> {
///     NamedFile::open("./files/document.pdf").await
/// }
/// ```
///
/// # Content-Disposition
///
/// By default, text, images, video, and audio files are served with
/// `Content-Disposition: inline`, while other files use `attachment`.
/// Use [`NamedFileBuilder::attached_name`] to force a download with a specific filename.
///
/// # Caching Headers
///
/// By default, `NamedFile` generates `ETag` and `Last-Modified` headers
/// and respects conditional request headers (`If-None-Match`, `If-Modified-Since`, etc.).
/// These can be disabled via [`use_etag()`](NamedFile::use_etag) and
/// [`use_last_modified()`](NamedFile::use_last_modified).
#[derive(Debug)]
pub struct NamedFile {
    path: PathBuf,
    file: File,
    modified: Option<SystemTime>,
    buffer_size: u64,
    metadata: Metadata,
    flags: BitFlags<Flag>,
    content_type: mime::Mime,
    content_disposition: Option<HeaderValue>,
    content_encoding: Option<HeaderValue>,
    /// Pre-read content for small files, avoiding ChunkedFile + spawn_blocking overhead.
    preread: Option<Bytes>,
}

/// Builder for constructing [`NamedFile`] instances with custom configuration.
///
/// The builder pattern allows customizing various aspects of file serving:
///
/// - MIME content type
/// - Content-Disposition (inline vs attachment)
/// - Download filename
/// - Buffer size for chunked reading
/// - ETag and Last-Modified header generation
///
/// # Example
///
/// ```ignore
/// use salvo_core::fs::NamedFile;
///
/// let file = NamedFile::builder("./data/export.csv")
///     .attached_name("data-export-2024.csv")  // Force download with this name
///     .content_type("text/csv".parse().unwrap())
///     .buffer_size(131072)  // 128KB chunks
///     .use_etag(true)
///     .build()
///     .await?;
/// ```
#[derive(Clone, Debug)]
pub struct NamedFileBuilder {
    path: PathBuf,
    attached_name: Option<String>,
    disposition_type: Option<String>,
    content_type: Option<mime::Mime>,
    content_encoding: Option<String>,
    buffer_size: Option<u64>,
    flags: BitFlags<Flag>,
}
impl NamedFileBuilder {
    /// Sets attached filename and returns `Self`.
    #[inline]
    #[must_use]
    pub fn attached_name<T: Into<String>>(mut self, attached_name: T) -> Self {
        self.attached_name = Some(attached_name.into());
        self.flags.insert(Flag::ContentDisposition);
        self
    }

    /// Sets disposition encoding and returns `Self`.
    #[inline]
    #[must_use]
    pub fn disposition_type<T: Into<String>>(mut self, disposition_type: T) -> Self {
        self.disposition_type = Some(disposition_type.into());
        self.flags.insert(Flag::ContentDisposition);
        self
    }

    /// Disable `Content-Disposition` header.
    ///
    /// By default Content-Disposition` header is enabled.
    #[inline]
    pub fn disable_content_disposition(&mut self) {
        self.flags.remove(Flag::ContentDisposition);
    }

    /// Sets content type and returns `Self`.
    #[inline]
    #[must_use]
    pub fn content_type(mut self, content_type: mime::Mime) -> Self {
        self.content_type = Some(content_type);
        self
    }

    /// Sets content encoding and returns `Self`.
    #[inline]
    #[must_use]
    pub fn content_encoding<T: Into<String>>(mut self, content_encoding: T) -> Self {
        self.content_encoding = Some(content_encoding.into());
        self
    }

    /// Sets buffer size and returns `Self`.
    #[inline]
    #[must_use]
    pub fn buffer_size(mut self, buffer_size: u64) -> Self {
        self.buffer_size = Some(buffer_size);
        self
    }

    /// Specifies whether to use ETag or not.
    ///
    /// Default is true.
    #[inline]
    #[must_use]
    pub fn use_etag(mut self, value: bool) -> Self {
        if value {
            self.flags.insert(Flag::Etag);
        } else {
            self.flags.remove(Flag::Etag);
        }
        self
    }

    /// Specifies whether to use Last-Modified or not.
    ///
    /// Default is true.
    #[inline]
    #[must_use]
    pub fn use_last_modified(mut self, value: bool) -> Self {
        if value {
            self.flags.insert(Flag::LastModified);
        } else {
            self.flags.remove(Flag::LastModified);
        }
        self
    }

    /// Build a new `NamedFile` and send it.
    pub async fn send(self, req_headers: &HeaderMap, res: &mut Response) {
        if !self.path.exists() {
            res.render(StatusError::not_found());
        } else {
            match self.build().await {
                Ok(file) => file.send(req_headers, res).await,
                Err(_) => res.render(StatusError::internal_server_error()),
            }
        }
    }

    /// Build a new [`NamedFile`].
    pub async fn build(self) -> Result<NamedFile> {
        let Self {
            path,
            content_type,
            content_encoding,
            buffer_size,
            disposition_type,
            attached_name,
            flags,
        } = self;

        let buf_size = buffer_size.unwrap_or(CHUNK_SIZE);

        // Determine what charset detection is needed before the blocking call.
        let inferred_mime = content_type
            .clone()
            .or_else(|| mime_infer::from_path(&path).first());
        let needs_charset = inferred_mime
            .as_ref()
            .map(|m| is_charset_required_mime(m) && m.get_param("charset").is_none())
            .unwrap_or(false);
        let needs_detect = content_type.is_none() && path.extension().is_none();

        // Single spawn_blocking: open + metadata + optional preread.
        // This replaces 3-7 separate spawn_blocking calls with just 1.
        struct FileInfo {
            file: std::fs::File,
            metadata: Metadata,
            preread: Option<Vec<u8>>,
        }
        let blocking_path = path.clone();
        let info = tokio::task::spawn_blocking(move || -> std::io::Result<FileInfo> {
            let mut file = std::fs::File::open(&blocking_path)?;
            let metadata = file.metadata()?;
            let file_size = metadata.len();

            // For small files (size <= buffer_size), read the entire content now.
            // This avoids ChunkedFile's spawn_blocking + into_std overhead later.
            let preread = if file_size <= buf_size {
                let mut buf = vec![0u8; file_size as usize];
                file.read_exact(&mut buf)?;
                Some(buf)
            } else {
                None
            };

            Ok(FileInfo {
                file,
                metadata,
                preread,
            })
        })
        .await
        .map_err(|e| Error::other(format!("spawn_blocking: {e}")))?
        .map_err(Error::Io)?;

        let file = File::from_std(info.file);

        // Resolve content type, using preread bytes for charset detection if needed.
        let content_type = if let Some(mut mime) = inferred_mime {
            if needs_charset {
                let sample = match &info.preread {
                    Some(buf) => &buf[..cmp::min(1024, buf.len())],
                    None => &[],
                };
                fill_mime_charset_if_need(&mut mime, sample);
            }
            mime
        } else if needs_detect {
            let sample = match &info.preread {
                Some(buf) => &buf[..cmp::min(1024, buf.len())],
                None => &[],
            };
            detect_text_mime(sample).unwrap_or(mime::APPLICATION_OCTET_STREAM)
        } else {
            mime::APPLICATION_OCTET_STREAM
        };

        let preread = info.preread.map(Bytes::from);

        let content_encoding = match content_encoding {
            Some(content_encoding) => Some(
                content_encoding
                    .parse::<HeaderValue>()
                    .map_err(Error::other)?,
            ),
            None => None,
        };

        let mut content_disposition = None;
        if attached_name.is_some() || disposition_type.is_some() {
            content_disposition = Some(build_content_disposition(
                &path,
                &content_type,
                disposition_type.as_deref(),
                attached_name.as_deref(),
            )?);
        }
        Ok(NamedFile {
            path,
            file,
            content_type,
            content_disposition,
            modified: info.metadata.modified().ok(),
            metadata: info.metadata,
            content_encoding,
            buffer_size: buf_size,
            flags,
            preread,
        })
    }
}
fn build_content_disposition(
    file_path: impl AsRef<Path>,
    content_type: &Mime,
    disposition_type: Option<&str>,
    attached_name: Option<&str>,
) -> Result<HeaderValue> {
    let disposition_type = disposition_type.unwrap_or_else(|| {
        if attached_name.is_some() {
            "attachment"
        } else {
            match (content_type.type_(), content_type.subtype()) {
                (mime::IMAGE | mime::TEXT | mime::VIDEO | mime::AUDIO, _)
                | (_, mime::JAVASCRIPT | mime::JSON) => "inline",
                _ => "attachment",
            }
        }
    });
    let content_disposition = if disposition_type == "attachment" {
        let attached_name = match attached_name {
            Some(attached_name) => Cow::Borrowed(attached_name),
            None => file_path
                .as_ref()
                .file_name()
                .map(|file_name| file_name.to_string_lossy().into_owned())
                .unwrap_or_else(|| "file".into())
                .into(),
        };
        format!(r#"attachment; filename="{attached_name}""#)
            .parse::<HeaderValue>()
            .map_err(Error::other)?
    } else {
        disposition_type
            .parse::<HeaderValue>()
            .map_err(Error::other)?
    };
    Ok(content_disposition)
}
impl NamedFile {
    /// Create new [`NamedFileBuilder`].
    #[inline]
    pub fn builder(path: impl Into<PathBuf>) -> NamedFileBuilder {
        NamedFileBuilder {
            path: path.into(),
            attached_name: None,
            disposition_type: None,
            content_type: None,
            content_encoding: None,
            buffer_size: None,
            flags: BitFlags::default(),
        }
    }

    /// Attempts to open a file in read-only mode.
    ///
    /// # Examples
    ///
    /// ```
    /// # use salvo_core::fs::NamedFile;
    /// # async fn open() {
    /// let file = NamedFile::open("foo.txt").await;
    /// # }
    /// ```
    #[inline]
    pub async fn open<P>(path: P) -> Result<Self>
    where
        P: Into<PathBuf> + Send,
    {
        Self::builder(path).build().await
    }

    /// Returns reference to the underlying `File` object.
    #[inline]
    pub fn file(&self) -> &File {
        &self.file
    }

    /// Retrieve the path of this file.
    #[inline]
    pub fn path(&self) -> &Path {
        self.path.as_path()
    }

    /// Get content type value.
    #[inline]
    pub fn content_type(&self) -> &mime::Mime {
        &self.content_type
    }
    /// Sets the MIME Content-Type for serving this file. By default
    /// the Content-Type is inferred from the filename extension.
    #[inline]
    pub fn set_content_type(&mut self, content_type: mime::Mime) {
        self.content_type = content_type;
    }

    /// Get Content-Disposition value.
    #[inline]
    pub fn content_disposition(&self) -> Option<&HeaderValue> {
        self.content_disposition.as_ref()
    }
    /// Sets the `Content-Disposition` for serving this file. This allows
    /// changing the inline/attachment disposition as well as the filename
    /// sent to the peer.
    ///
    /// By default the disposition is `inline` for text,
    /// image, and video content types, and `attachment` otherwise, and
    /// the filename is taken from the path provided in the `open` method
    /// after converting it to UTF-8 using
    /// [to_string_lossy](https://doc.rust-lang.org/std/ffi/struct.OsStr.html#method.to_string_lossy).
    #[inline]
    pub fn set_content_disposition(&mut self, content_disposition: HeaderValue) {
        self.content_disposition = Some(content_disposition);
        self.flags.insert(Flag::ContentDisposition);
    }

    /// Disable `Content-Disposition` header.
    ///
    /// By default Content-Disposition` header is enabled.
    #[inline]
    pub fn disable_content_disposition(&mut self) {
        self.flags.remove(Flag::ContentDisposition);
    }

    /// Get content encoding value reference.
    #[inline]
    pub fn content_encoding(&self) -> Option<&HeaderValue> {
        self.content_encoding.as_ref()
    }
    /// Sets content encoding for serving this file
    #[inline]
    pub fn set_content_encoding(&mut self, content_encoding: HeaderValue) {
        self.content_encoding = Some(content_encoding);
    }

    /// Get ETag value.
    pub fn etag(&self) -> Option<ETag> {
        // This etag format is similar to Apache's.
        self.modified.as_ref().and_then(|mtime| {
            let ino = {
                #[cfg(unix)]
                {
                    self.metadata.ino()
                }
                #[cfg(not(unix))]
                {
                    0
                }
            };

            let dur = mtime
                .duration_since(UNIX_EPOCH)
                .expect("modification time must be after epoch");
            let etag_str = format!(
                "\"{:x}-{:x}-{:x}-{:x}\"",
                ino,
                self.metadata.len(),
                dur.as_secs(),
                dur.subsec_nanos()
            );
            match etag_str.parse::<ETag>() {
                Ok(etag) => Some(etag),
                Err(e) => {
                    tracing::error!(error = ?e, etag = %etag_str, "set file's etag failed");
                    None
                }
            }
        })
    }
    /// Specifies whether to use ETag or not.
    ///
    /// Default is true.
    #[inline]
    pub fn use_etag(&mut self, value: bool) {
        if value {
            self.flags.insert(Flag::Etag);
        } else {
            self.flags.remove(Flag::Etag);
        }
    }

    /// GEt last_modified value.
    #[inline]
    pub fn last_modified(&self) -> Option<SystemTime> {
        self.modified
    }
    /// Specifies whether to use Last-Modified or not.
    ///
    /// Default is true.
    #[inline]
    pub fn use_last_modified(&mut self, value: bool) {
        if value {
            self.flags.insert(Flag::LastModified);
        } else {
            self.flags.remove(Flag::LastModified);
        }
    }
    /// Consume self and send content to [`Response`].
    pub async fn send(mut self, req_headers: &HeaderMap, res: &mut Response) {
        let etag = if self.flags.contains(Flag::Etag) {
            self.etag()
        } else {
            None
        };
        let last_modified = if self.flags.contains(Flag::LastModified) {
            self.last_modified()
        } else {
            None
        };

        // check preconditions
        let precondition_failed = if !any_match(etag.as_ref(), req_headers) {
            true
        } else if let (Some(last_modified), Some(since)) =
            (&last_modified, req_headers.typed_get::<IfUnmodifiedSince>())
        {
            !since.precondition_passes(*last_modified)
        } else {
            false
        };

        // check last modified
        let not_modified = if !none_match(etag.as_ref(), req_headers) {
            true
        } else if req_headers.contains_key(IF_NONE_MATCH) {
            false
        } else if let (Some(last_modified), Some(since)) =
            (&last_modified, req_headers.typed_get::<IfModifiedSince>())
        {
            !since.is_modified(*last_modified)
        } else {
            false
        };

        if self.flags.contains(Flag::ContentDisposition) {
            if let Some(content_disposition) = self.content_disposition.take() {
                res.headers_mut()
                    .insert(CONTENT_DISPOSITION, content_disposition);
            } else if !res.headers().contains_key(CONTENT_DISPOSITION) {
                // skip to set CONTENT_DISPOSITION header if it is already set.
                match build_content_disposition(&self.path, &self.content_type, None, None) {
                    Ok(content_disposition) => {
                        res.headers_mut()
                            .insert(CONTENT_DISPOSITION, content_disposition);
                    }
                    Err(e) => {
                        tracing::error!(error = ?e, "build file's content disposition failed");
                    }
                }
            }
        }
        if !res.headers().contains_key(CONTENT_TYPE) {
            res.headers_mut()
                .typed_insert(ContentType::from(self.content_type.clone()));
        }
        if let Some(lm) = last_modified {
            res.headers_mut().typed_insert(LastModified::from(lm));
        }
        if let Some(etag) = etag {
            res.headers_mut().typed_insert(etag);
        }
        res.headers_mut().typed_insert(AcceptRanges::bytes());

        let mut length = self.metadata.len();
        if let Some(content_encoding) = &self.content_encoding {
            res.headers_mut()
                .insert(CONTENT_ENCODING, content_encoding.clone());
        }
        let mut offset = 0;

        // check for range header
        let range = req_headers.get(RANGE);
        if let Some(range) = range {
            if let Ok(range) = range.to_str() {
                if let Ok(range) = HttpRange::parse(range, length)
                    && !range.is_empty()
                {
                    length = range[0].length;
                    offset = range[0].start;
                } else {
                    res.headers_mut()
                        .typed_insert(ContentRange::unsatisfied_bytes(length));
                    res.status_code(StatusCode::RANGE_NOT_SATISFIABLE);
                    return;
                };
            } else {
                res.status_code(StatusCode::BAD_REQUEST);
                return;
            };
        }

        if precondition_failed {
            res.status_code(StatusCode::PRECONDITION_FAILED);
            return;
        } else if not_modified {
            res.status_code(StatusCode::NOT_MODIFIED);
            return;
        }

        if offset != 0 || length != self.metadata.len() || range.is_some() {
            // Range request
            res.status_code(StatusCode::PARTIAL_CONTENT);
            match ContentRange::bytes(offset..offset + length, self.metadata.len()) {
                Ok(content_range) => {
                    res.headers_mut().typed_insert(content_range);
                }
                Err(e) => {
                    tracing::error!(error = ?e, "set file's content range failed");
                }
            }
            let total_size = cmp::min(length, self.metadata.len());
            res.headers_mut().typed_insert(ContentLength(total_size));

            // Fast path: slice from preread bytes if available
            if let Some(preread) = self.preread {
                let end = cmp::min((offset + length) as usize, preread.len());
                let start = cmp::min(offset as usize, end);
                res.replace_body(ResBody::Once(preread.slice(start..end)));
            } else {
                let reader = ChunkedFile {
                    offset,
                    total_size,
                    read_size: 0,
                    state: ChunkedState::File(Some(self.file.into_std().await)),
                    buffer_size: self.buffer_size,
                };
                res.stream(reader);
            }
        } else {
            // Full file response
            res.status_code(StatusCode::OK);
            res.headers_mut().typed_insert(ContentLength(length));

            // Fast path: send preread bytes directly — zero spawn_blocking calls
            if let Some(preread) = self.preread {
                res.replace_body(ResBody::Once(preread));
            } else {
                let reader = ChunkedFile {
                    offset,
                    state: ChunkedState::File(Some(self.file.into_std().await)),
                    total_size: length,
                    read_size: 0,
                    buffer_size: self.buffer_size,
                };
                res.stream(reader);
            }
        }
    }
}

#[async_trait]
impl Writer for NamedFile {
    async fn write(self, req: &mut Request, _depot: &mut Depot, res: &mut Response) {
        self.send(req.headers(), res).await;
    }
}

impl Deref for NamedFile {
    type Target = File;

    fn deref(&self) -> &File {
        &self.file
    }
}

impl DerefMut for NamedFile {
    fn deref_mut(&mut self) -> &mut File {
        &mut self.file
    }
}

/// Returns true if `req_headers` has no `If-Match` header or one which matches `etag`.
fn any_match(etag: Option<&ETag>, req_headers: &HeaderMap) -> bool {
    match req_headers.typed_get::<IfMatch>() {
        None => true,
        Some(if_match) => {
            if if_match == IfMatch::any() {
                true
            } else if let Some(etag) = etag {
                if_match.precondition_passes(etag)
            } else {
                false
            }
        }
    }
}

/// Returns true if `req_headers` doesn't have an `If-None-Match` header matching `req`.
fn none_match(etag: Option<&ETag>, req_headers: &HeaderMap) -> bool {
    match req_headers.typed_get::<IfNoneMatch>() {
        None => true,
        Some(if_none_match) => {
            if if_none_match == IfNoneMatch::any() {
                false
            } else if let Some(etag) = etag {
                if_none_match.precondition_passes(etag)
            } else {
                true
            }
        }
    }
}