salvo_core 0.96.0

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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
use std::borrow::Cow;
use std::cmp;
use std::ffi::OsStr;
use std::fs::Metadata;
use std::io::{Read as StdRead, Seek as StdSeek, SeekFrom};
use std::ops::{Deref, DerefMut};
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use bytes::Bytes;
use enumflags2::{BitFlags, bitflags};
use headers::*;
use mime::Mime;
use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode};
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,
    X_CONTENT_TYPE_OPTIONS,
};
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;
const PRELOAD_THRESHOLD: u64 = 1024 * 1024;
const RFC5987_ATTR_CHAR_ENCODE_SET: &AsciiSet = &CONTROLS
    .add(b' ')
    .add(b'"')
    .add(b'%')
    .add(b'\'')
    .add(b'(')
    .add(b')')
    .add(b'*')
    .add(b',')
    .add(b'/')
    .add(b':')
    .add(b';')
    .add(b'<')
    .add(b'=')
    .add(b'>')
    .add(b'?')
    .add(b'@')
    .add(b'[')
    .add(b'\\')
    .add(b']')
    .add(b'{')
    .add(b'}');

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

/// 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)
///         .preload_threshold(262144)
///         .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.
///
/// XML-based documents are the exception: `image/svg+xml`, `text/xml`, `text/xsl`
/// and anything else carrying an `xml` subtype or a `+xml` suffix default to
/// `attachment` even though their top-level type is `image` or `text`, because a
/// browser rendering one as a document will run any script it contains in the
/// serving origin. Pass [`NamedFileBuilder::disposition_type`] to override this
/// for content you trust.
///
/// # Security Headers
///
/// Responses carry `X-Content-Type-Options: nosniff` by default so a browser
/// cannot reinterpret a file as a more dangerous type than its `Content-Type`
/// claims. See [`NamedFileBuilder::use_content_type_options`].
///
/// # 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,
    /// Overrides the name `Content-Disposition` reports, when the bytes come from
    /// a different path than the requested resource.
    disposition_name: Option<String>,
    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
/// - Preload threshold for small-file responses
/// - 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
///     .preload_threshold(262144)  // Preload files up to 256KB
///     .use_etag(true)
///     .build()
///     .await?;
/// ```
#[derive(Clone, Debug)]
pub struct NamedFileBuilder {
    path: PathBuf,
    attached_name: Option<String>,
    disposition_name: Option<String>,
    disposition_type: Option<String>,
    content_type: Option<mime::Mime>,
    content_encoding: Option<String>,
    buffer_size: Option<u64>,
    preload_threshold: 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 the file name used in `Content-Disposition` without forcing the
    /// disposition to `attachment`, and returns `Self`.
    ///
    /// Use this when the bytes are read from a different path than the resource
    /// the client asked for, so a download is saved under the requested name
    /// rather than the name of the file on disk. [`Self::attached_name`] sets the
    /// same name but also forces `attachment`.
    #[inline]
    #[must_use]
    pub fn disposition_name<T: Into<String>>(mut self, disposition_name: T) -> Self {
        self.disposition_name = Some(disposition_name.into());
        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, the `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 chunk buffer size and returns `Self`.
    ///
    /// This controls the maximum chunk size used when a file is streamed. It does not change the
    /// small-file preload threshold. Use [`Self::preload_threshold`] to configure that separately.
    #[inline]
    #[must_use]
    pub fn buffer_size(mut self, buffer_size: u64) -> Self {
        self.buffer_size = Some(buffer_size);
        self
    }

    /// Sets small-file preload threshold and returns `Self`.
    ///
    /// Files whose size is less than or equal to this threshold are read during build and sent from
    /// memory. Larger files are streamed in chunks using [`Self::buffer_size`]. Set this to `0` to
    /// disable preloading for non-empty files.
    #[inline]
    #[must_use]
    pub fn preload_threshold(mut self, threshold: u64) -> Self {
        self.preload_threshold = Some(threshold);
        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
    }

    /// Specifies whether to send `X-Content-Type-Options: nosniff` or not.
    ///
    /// Default is true. Turn this off only when a client depends on MIME
    /// sniffing to interpret a file whose extension does not describe it.
    #[inline]
    #[must_use]
    pub fn use_content_type_options(mut self, value: bool) -> Self {
        if value {
            self.flags.insert(Flag::ContentTypeOptions);
        } else {
            self.flags.remove(Flag::ContentTypeOptions);
        }
        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,
            preload_threshold,
            disposition_type,
            attached_name,
            disposition_name,
            flags,
        } = self;

        let buf_size = buffer_size.unwrap_or(CHUNK_SIZE).max(1);
        let preload_threshold = preload_threshold.unwrap_or(PRELOAD_THRESHOLD);

        // An extension such as `.svgz` names a media type *and* the coding applied
        // to it. Recover the coding here, because the type alone describes the
        // decoded document and would leave the response claiming a gzip stream is
        // an SVG. An explicitly configured encoding always wins.
        let content_encoding = content_encoding.or_else(|| {
            path.extension()
                .and_then(OsStr::to_str)
                .and_then(extension_content_encoding)
                .map(ToOwned::to_owned)
        });

        // Determine what charset detection is needed before the blocking call.
        let inferred_mime = content_type
            .clone()
            .or_else(|| mime_infer::from_path(&path).first());
        // When a content encoding is set, the on-disk bytes are the *encoded*
        // (e.g. gzip) payload of a precompressed sidecar file. Sniffing a charset
        // or text mime from those compressed bytes yields a bogus result (the
        // compressed blob is not valid UTF-8), so the wrong `charset=` would be
        // attached to the `Content-Type` and the client mojibakes the decoded
        // text. Skip content-based detection in that case.
        let is_encoded = content_encoding.is_some();
        let needs_charset = !is_encoded
            && inferred_mime
                .as_ref()
                .map(|m| is_charset_required_mime(m) && m.get_param("charset").is_none())
                .unwrap_or(false);
        let needs_detect = !is_encoded && content_type.is_none() && path.extension().is_none();

        let needs_detection_sample = needs_charset || needs_detect;

        // Single spawn_blocking: open + metadata + optional preread/detection sample.
        // This replaces 3-7 separate spawn_blocking calls with just 1.
        struct FileInfo {
            file: std::fs::File,
            metadata: Metadata,
            preread: Option<Vec<u8>>,
            detection_sample: 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 <= preload_threshold), read the entire content now.
            // This avoids ChunkedFile's spawn_blocking + into_std overhead later.
            let preread = if file_size <= preload_threshold {
                let mut buf = vec![0u8; file_size as usize];
                file.read_exact(&mut buf)?;
                Some(buf)
            } else {
                None
            };

            let detection_sample = if needs_detection_sample {
                if let Some(preread) = &preread {
                    Some(preread[..cmp::min(1024, preread.len())].to_vec())
                } else {
                    let mut sample = vec![0u8; cmp::min(1024, file_size) as usize];
                    file.read_exact(&mut sample)?;
                    file.seek(SeekFrom::Start(0))?;
                    Some(sample)
                }
            } else {
                None
            };

            Ok(FileInfo {
                file,
                metadata,
                preread,
                detection_sample,
            })
        })
        .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 = info.detection_sample.as_deref().unwrap_or(&[]);
                fill_mime_charset_if_need(&mut mime, sample);
            }
            mime
        } else if needs_detect {
            let sample = info.detection_sample.as_deref().unwrap_or(&[]);
            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(
                disposition_name_source(disposition_name.as_deref(), &path),
                &content_type,
                disposition_type.as_deref(),
                attached_name.as_deref(),
            )?);
        }
        Ok(NamedFile {
            path,
            disposition_name,
            file,
            content_type,
            content_disposition,
            modified: info.metadata.modified().ok(),
            metadata: info.metadata,
            content_encoding,
            buffer_size: buf_size,
            flags,
            preread,
        })
    }
}
/// Whether a browser rendering `content_type` as a document could run script in
/// the serving origin.
///
/// An SVG carries `<script>` elements and event handler attributes, and any XML
/// document can name an XSLT stylesheet through `<?xml-stylesheet ?>` and render
/// scripted HTML from it. Both execute against the origin that served the file, so
/// serving one inline turns an uploaded "image" into stored XSS.
///
/// `application/*` XML types already fell on the `attachment` side because their
/// top-level type is not in the inline list. What slipped past were the `image`
/// and `text` spellings, which is every case below.
fn is_scriptable_xml(content_type: &Mime) -> bool {
    let subtype = content_type.subtype().as_str();
    // The `+xml` structured syntax suffix: `image/svg+xml`, `application/xslt+xml`.
    content_type.suffix() == Some(mime::XML)
        // `text/xml`, plus RFC 7303's `xml-dtd` and `xml-external-parsed-entity`,
        // which are XML but carry no suffix. Compare only the segment before the
        // first hyphen, so a subtype merely starting with those letters — say
        // `xmlish` — is not swept along.
        || subtype
            .split_once('-')
            .map_or(subtype, |(head, _)| head)
            .eq_ignore_ascii_case("xml")
        // `text/xsl` is the legacy type that `<?xml-stylesheet ?>` itself names,
        // and browsers parse it as XML.
        || subtype.eq_ignore_ascii_case("xsl")
}

/// The path whose file name names the file in `Content-Disposition`.
///
/// Normally that is the path on disk, but the two diverge when the bytes come
/// from somewhere other than the resource that was requested: `StaticDir` serving
/// the precompressed sidecar `logo.svg.br` for a request for `logo.svg` must
/// still offer the download as `logo.svg`.
fn disposition_name_source<'a>(disposition_name: Option<&'a str>, path: &'a Path) -> &'a Path {
    disposition_name.map_or(path, Path::new)
}

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() || is_scriptable_xml(content_type) {
            "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(),
        };
        let quoted_filename = escape_quoted_filename(&attached_name);
        if quoted_filename == attached_name {
            format!(r#"attachment; filename="{quoted_filename}""#)
        } else {
            let encoded_filename =
                utf8_percent_encode(&attached_name, RFC5987_ATTR_CHAR_ENCODE_SET);
            format!(
                r#"attachment; filename="{quoted_filename}"; filename*=UTF-8''{encoded_filename}"#
            )
        }
        .parse::<HeaderValue>()
        .map_err(Error::other)?
    } else {
        disposition_type
            .parse::<HeaderValue>()
            .map_err(Error::other)?
    };
    Ok(content_disposition)
}

fn escape_quoted_filename(filename: &str) -> String {
    let mut escaped = String::with_capacity(filename.len());
    for ch in filename.chars() {
        match ch {
            '"' | '\\' => {
                escaped.push('\\');
                escaped.push(ch);
            }
            '\t' => escaped.push(' '),
            ch if ch.is_ascii_control() || !ch.is_ascii() => escaped.push('_'),
            ch => escaped.push(ch),
        }
    }
    escaped
}

/// Extensions that name a content-coded form of another media type, paired with
/// the coding they imply.
///
/// `.gz` and `.tgz` are deliberately absent: there the gzip stream is the
/// representation being served, not a coding applied to something else.
const CONTENT_CODED_EXTS: &[(&str, &str)] = &[
    ("svgz", "gzip"),
    // X3D's compressed interchange forms, gzip per ISO/IEC 19776.
    ("x3dz", "gzip"),
    ("x3dvz", "gzip"),
    ("x3dbz", "gzip"),
];

/// The content coding implied by a file extension.
///
/// An extension maps to a single media type, so `mime_infer` reports `.svgz` as
/// `image/svg+xml` — the type of the document *inside* the gzip stream. Serving
/// that without also advertising the coding hands the client compressed bytes
/// labelled as an SVG document, which it cannot render.
///
/// [`NamedFile`] applies this itself. It is public so a handler that picks a file
/// to serve can tell that the file already carries a coding — a precompressed
/// variant of a `.svgz` would stack a second coding on top of the gzip.
///
/// The extension is matched case-insensitively, as `mime_infer` matches it.
#[must_use]
pub fn extension_content_encoding(ext: &str) -> Option<&'static str> {
    CONTENT_CODED_EXTS
        .iter()
        .find(|(candidate, _)| ext.eq_ignore_ascii_case(candidate))
        .map(|(_, encoding)| *encoding)
}

impl NamedFile {
    /// Creates a new [`NamedFileBuilder`].
    #[inline]
    pub fn builder(path: impl Into<PathBuf>) -> NamedFileBuilder {
        NamedFileBuilder {
            path: path.into(),
            attached_name: None,
            disposition_name: None,
            disposition_type: None,
            content_type: None,
            content_encoding: None,
            buffer_size: None,
            preload_threshold: 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, video and audio
    /// content types other than XML-based ones, and `attachment` for everything
    /// else. 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, the `Content-Disposition` header is enabled.
    #[inline]
    pub fn disable_content_disposition(&mut self) {
        self.flags.remove(Flag::ContentDisposition);
    }

    /// Specifies whether to send `X-Content-Type-Options: nosniff` or not.
    ///
    /// Default is true. Turn this off only when a client depends on MIME
    /// sniffing to interpret a file whose extension does not describe it.
    #[inline]
    pub fn use_content_type_options(&mut self, value: bool) {
        if value {
            self.flags.insert(Flag::ContentTypeOptions);
        } else {
            self.flags.remove(Flag::ContentTypeOptions);
        }
    }

    /// 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 = match mtime.duration_since(UNIX_EPOCH) {
                Ok(dur) => dur,
                Err(err) => {
                    tracing::warn!(
                        error = ?err,
                        path = %self.path.display(),
                        "skip file etag for modification time before unix epoch"
                    );
                    return None;
                }
            };
            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
    }

    fn encodable_last_modified(&self, mtime: SystemTime) -> Option<SystemTime> {
        if let Err(err) = mtime.duration_since(UNIX_EPOCH) {
            tracing::warn!(
                error = ?err,
                path = %self.path.display(),
                "skip file last-modified header for modification time before unix epoch"
            );
            None
        } else {
            Some(mtime)
        }
    }
    /// 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(self, req_headers: &HeaderMap, res: &mut Response) {
        self.send_inner(req_headers, res, true).await;
    }

    /// Consume self and send only the headers to [`Response`].
    ///
    /// This follows the same conditional and range handling as [`Self::send`], but does not attach
    /// a response body.
    pub async fn send_head(self, req_headers: &HeaderMap, res: &mut Response) {
        self.send_inner(req_headers, res, false).await;
    }

    async fn send_inner(mut self, req_headers: &HeaderMap, res: &mut Response, send_body: bool) {
        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>())
        {
            let since: SystemTime = since.into();
            since < http_date_precision(*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>())
        {
            let since: SystemTime = since.into();
            since >= http_date_precision(*last_modified)
        } else {
            false
        };

        // A caller may have already chosen the response's Content-Type. Default
        // the disposition from the type the client will actually receive, not
        // necessarily the type detected for the file on disk. Treat an invalid
        // pre-existing value conservatively as opaque binary data.
        let effective_content_type = if res.headers().contains_key(CONTENT_TYPE) {
            res.content_type().unwrap_or(mime::APPLICATION_OCTET_STREAM)
        } else {
            self.content_type.clone()
        };

        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(
                    disposition_name_source(self.disposition_name.as_deref(), &self.path),
                    &effective_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 self.flags.contains(Flag::ContentTypeOptions)
            && !res.headers().contains_key(X_CONTENT_TYPE_OPTIONS)
        {
            res.headers_mut()
                .insert(X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
        }
        if let Some(lm) = last_modified.and_then(|lm| self.encodable_last_modified(lm)) {
            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());
        }
        // Conditional request handling must precede Range processing: per RFC 7232
        // a `304 Not Modified` / `412 Precondition Failed` takes priority over the
        // `206`/`416` produced by a Range request.
        if precondition_failed {
            res.status_code(StatusCode::PRECONDITION_FAILED);
            return;
        } else if not_modified {
            res.status_code(StatusCode::NOT_MODIFIED);
            return;
        }

        let file_size = self.metadata.len();
        let mut offset = 0;
        let mut is_partial = false;

        // check for range header
        if let Some(range) = req_headers.get(RANGE) {
            let Ok(range) = range.to_str() else {
                res.status_code(StatusCode::BAD_REQUEST);
                return;
            };
            match HttpRange::parse(range, length) {
                // A single range is served as `206 Partial Content`.
                Ok(ranges) if ranges.len() == 1 => {
                    offset = ranges[0].start;
                    length = ranges[0].length;
                    is_partial = true;
                }
                // Multiple ranges would require a `multipart/byteranges` body, which
                // is not supported here. Per RFC 7233 the server may ignore the Range
                // header and return the full `200 OK` representation instead.
                Ok(ranges) if ranges.len() > 1 => {}
                // Empty / unsatisfiable range.
                _ => {
                    res.headers_mut()
                        .typed_insert(ContentRange::unsatisfied_bytes(length));
                    res.status_code(StatusCode::RANGE_NOT_SATISFIABLE);
                    return;
                }
            }
        }

        if is_partial {
            // Range request
            res.status_code(StatusCode::PARTIAL_CONTENT);
            // Single source of truth for the byte count, clamped to the file so the
            // `Content-Range`, `Content-Length` and the body always agree.
            let total_size = length.min(file_size.saturating_sub(offset));
            match ContentRange::bytes(offset..offset.saturating_add(total_size), file_size) {
                Ok(content_range) => {
                    res.headers_mut().typed_insert(content_range);
                }
                Err(e) => {
                    tracing::error!(error = ?e, "set file's content range failed");
                }
            }
            res.headers_mut().typed_insert(ContentLength(total_size));

            if !send_body {
                return;
            }

            // Fast path: slice from preread bytes if available
            if let Some(preread) = self.preread.take() {
                let end = cmp::min(offset.saturating_add(total_size) 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));

            if !send_body {
                return;
            }

            // Fast path: send preread bytes directly — zero spawn_blocking calls
            if let Some(preread) = self.preread.take() {
                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
    }
}

fn http_date_precision(time: SystemTime) -> SystemTime {
    match time.duration_since(UNIX_EPOCH) {
        Ok(dur) => UNIX_EPOCH + Duration::from_secs(dur.as_secs()),
        Err(err) => {
            let dur = err.duration();
            let secs = dur.as_secs() + u64::from(dur.subsec_nanos() > 0);
            UNIX_EPOCH
                .checked_sub(Duration::from_secs(secs))
                .unwrap_or(time)
        }
    }
}

/// 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
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn content_disposition_escapes_quoted_filename() {
        let value = build_content_disposition(
            "ignored.txt",
            &mime::APPLICATION_OCTET_STREAM,
            None,
            Some("report\"\\\r\n.txt"),
        )
        .unwrap();

        assert_eq!(
            value.to_str().unwrap(),
            r#"attachment; filename="report\"\\__.txt"; filename*=UTF-8''report%22%5C%0D%0A.txt"#
        );
    }

    fn default_disposition_for(content_type: &Mime) -> String {
        build_content_disposition("upload.bin", content_type, None, None)
            .expect("build content disposition")
            .to_str()
            .expect("header is ascii")
            .to_owned()
    }

    #[test]
    fn scriptable_xml_defaults_to_attachment() {
        // An SVG can carry <script>/onload, and any XML document can pull in an
        // XSLT stylesheet that renders scripted HTML. Serving either inline from
        // the app's own origin turns an uploaded "image" into stored XSS.
        for content_type in [
            mime::IMAGE_SVG,
            mime::TEXT_XML,
            "application/xml".parse().expect("parse mime"),
            "application/xhtml+xml".parse().expect("parse mime"),
            "application/rss+xml".parse().expect("parse mime"),
        ] {
            assert!(
                default_disposition_for(&content_type).starts_with("attachment"),
                "{content_type} must not default to inline"
            );
        }
    }

    #[test]
    fn non_xml_media_still_defaults_to_inline() {
        // The XML carve-out must not pull ordinary media off the inline path.
        for content_type in [
            mime::IMAGE_PNG,
            mime::TEXT_PLAIN,
            // A static file server exists to serve HTML documents inline.
            mime::TEXT_HTML,
            "video/mp4".parse().expect("parse mime"),
            "audio/mpeg".parse().expect("parse mime"),
            "text/javascript".parse().expect("parse mime"),
        ] {
            assert_eq!(
                default_disposition_for(&content_type),
                "inline",
                "{content_type} must stay inline"
            );
        }
    }

    #[test]
    fn xml_types_without_the_suffix_default_to_attachment() {
        // These name XML without carrying an `xml` subtype or a `+xml` suffix, so
        // the structural checks alone would let them through on `text`.
        for content_type in [
            // The type `<?xml-stylesheet type="text/xsl" ?>` itself names.
            "text/xsl",
            "text/xml-external-parsed-entity",
            "text/xml-dtd",
            // Matching is case-insensitive, as MIME comparisons are.
            "TEXT/XSL",
            "Text/XML",
        ] {
            let content_type = content_type.parse().expect("parse mime");
            assert!(
                default_disposition_for(&content_type).starts_with("attachment"),
                "{content_type} must not default to inline"
            );
        }
    }

    #[test]
    fn xml_lookalike_subtypes_stay_inline() {
        // The XML carve-out keys on the type actually being XML; a subtype that
        // merely starts with the same letters must not be dragged along.
        for content_type in ["text/xmlish", "image/xslfoo", "text/xsl-but-not"] {
            let content_type = content_type.parse().expect("parse mime");
            assert_eq!(
                default_disposition_for(&content_type),
                "inline",
                "{content_type} must stay inline"
            );
        }
    }

    #[test]
    fn disposition_name_replaces_the_on_disk_file_name() {
        // `StaticDir` reads `logo.svg.br` but the client asked for `logo.svg`.
        let value = build_content_disposition(
            disposition_name_source(Some("logo.svg"), Path::new("/srv/assets/logo.svg.br")),
            &mime::IMAGE_SVG,
            None,
            None,
        )
        .expect("build content disposition");
        assert_eq!(
            value.to_str().expect("header is ascii"),
            r#"attachment; filename="logo.svg""#
        );
    }

    #[test]
    fn attached_name_outranks_disposition_name() {
        let value = build_content_disposition(
            disposition_name_source(Some("logo.svg"), Path::new("logo.svg.br")),
            &mime::IMAGE_SVG,
            None,
            Some("chosen.svg"),
        )
        .expect("build content disposition");
        assert_eq!(
            value.to_str().expect("header is ascii"),
            r#"attachment; filename="chosen.svg""#
        );
    }

    #[test]
    fn disposition_name_falls_back_to_the_path() {
        let value = build_content_disposition(
            disposition_name_source(None, Path::new("/srv/assets/logo.svg")),
            &mime::IMAGE_SVG,
            None,
            None,
        )
        .expect("build content disposition");
        assert_eq!(
            value.to_str().expect("header is ascii"),
            r#"attachment; filename="logo.svg""#
        );
    }

    #[test]
    fn explicit_disposition_type_overrides_xml_default() {
        // Serving trusted SVG assets inline stays possible.
        let value = build_content_disposition("logo.svg", &mime::IMAGE_SVG, Some("inline"), None)
            .expect("build content disposition");
        assert_eq!(value.to_str().expect("header is ascii"), "inline");
    }

    #[tokio::test]
    async fn svg_is_served_as_attachment_with_nosniff() {
        use std::io::Write as _;

        let mut file = tempfile::Builder::new()
            .suffix(".svg")
            .tempfile()
            .expect("create temp file");
        file.write_all(
            br#"<svg xmlns="http://www.w3.org/2000/svg" onload="alert(document.domain)"/>"#,
        )
        .expect("write svg");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");
        // The file must be recognised *as* an SVG, otherwise this test would also
        // pass on an unidentified file falling back to `application/octet-stream`.
        assert_eq!(named.content_type(), &mime::IMAGE_SVG);

        let mut res = Response::new();
        named.send(&HeaderMap::new(), &mut res).await;

        let disposition = res
            .headers()
            .get(CONTENT_DISPOSITION)
            .expect("content-disposition is set")
            .to_str()
            .expect("header is ascii");
        assert!(
            disposition.starts_with("attachment"),
            "svg served with `{disposition}`"
        );
        assert_eq!(
            res.headers()
                .get(X_CONTENT_TYPE_OPTIONS)
                .map(|v| v.to_str().expect("header is ascii")),
            Some("nosniff")
        );
    }

    #[tokio::test]
    async fn response_content_type_controls_default_disposition() {
        use std::io::Write as _;

        let mut file = tempfile::Builder::new()
            .suffix(".txt")
            .tempfile()
            .expect("create temp file");
        file.write_all(b"plain text").expect("write text");
        file.flush().expect("flush");

        for content_type in ["image/svg+xml", "invalid"] {
            let named = NamedFile::builder(file.path())
                .build()
                .await
                .expect("build named file");
            assert_eq!(named.content_type().type_(), mime::TEXT);
            assert_eq!(named.content_type().subtype(), mime::PLAIN);

            let mut res = Response::new();
            res.headers_mut()
                .insert(CONTENT_TYPE, content_type.parse().expect("header value"));
            named.send(&HeaderMap::new(), &mut res).await;

            let disposition = res
                .headers()
                .get(CONTENT_DISPOSITION)
                .expect("content-disposition is set")
                .to_str()
                .expect("header is ascii");
            assert!(
                disposition.starts_with("attachment"),
                "response type `{content_type}` produced `{disposition}`"
            );
        }
    }

    #[tokio::test]
    async fn safe_response_content_type_can_keep_default_disposition_inline() {
        use std::io::Write as _;

        let mut file = tempfile::Builder::new()
            .suffix(".svg")
            .tempfile()
            .expect("create temp file");
        file.write_all(br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#)
            .expect("write svg");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");
        assert_eq!(named.content_type(), &mime::IMAGE_SVG);

        let mut res = Response::new();
        res.headers_mut()
            .insert(CONTENT_TYPE, HeaderValue::from_static("image/png"));
        named.send(&HeaderMap::new(), &mut res).await;

        assert_eq!(
            res.headers()
                .get(CONTENT_DISPOSITION)
                .expect("content-disposition is set"),
            "inline"
        );
    }

    #[tokio::test]
    async fn precompressed_file_does_not_sniff_charset_from_encoded_bytes() {
        use std::io::Write as _;

        // Simulate a `.js.gz` sidecar: the on-disk bytes are a gzip payload, which
        // is not valid UTF-8. Without the fix, charset detection runs on these
        // compressed bytes and attaches a bogus `charset=` to the text/javascript
        // content type, causing the client to mojibake the decoded source.
        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        file.write_all(&[
            0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xab, 0xe2, 0x80, 0x9c,
            0xc3, 0xa9, 0xb4, 0xd6, 0xfe, 0x00,
        ])
        .expect("write gzip-like bytes");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .content_type("text/javascript".parse().expect("parse mime"))
            .content_encoding("gzip")
            .build()
            .await
            .expect("build named file");

        // No charset must be sniffed from the encoded payload.
        assert_eq!(named.content_type().get_param("charset"), None);
        assert_eq!(
            named.content_encoding().map(|v| v.to_str().unwrap()),
            Some("gzip")
        );
    }

    #[tokio::test]
    async fn buffer_size_does_not_raise_preload_threshold() {
        use std::io::Write as _;

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        let bytes = vec![b'a'; (PRELOAD_THRESHOLD + 1) as usize];
        file.write_all(&bytes).expect("write file");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .buffer_size(PRELOAD_THRESHOLD * 2)
            .build()
            .await
            .expect("build named file");

        assert_eq!(named.buffer_size, PRELOAD_THRESHOLD * 2);
        assert!(named.preread.is_none());
    }

    #[tokio::test]
    async fn preload_threshold_can_be_configured() {
        use std::io::Write as _;

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        let bytes = vec![b'a'; (PRELOAD_THRESHOLD + 1) as usize];
        file.write_all(&bytes).expect("write file");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .preload_threshold(PRELOAD_THRESHOLD + 1)
            .build()
            .await
            .expect("build named file");

        assert_eq!(
            named.preread.as_ref().map(Bytes::len),
            Some((PRELOAD_THRESHOLD + 1) as usize)
        );
    }

    #[tokio::test]
    async fn preload_threshold_zero_still_detects_extensionless_text_mime() {
        let temp_dir = tempfile::tempdir().expect("create temp dir");
        let path = temp_dir.path().join("README");
        std::fs::write(&path, b"plain text content").expect("write extensionless file");

        let named = NamedFile::builder(&path)
            .preload_threshold(0)
            .build()
            .await
            .expect("build named file");

        assert_eq!(named.content_type().type_(), mime::TEXT);
        assert_eq!(named.content_type().subtype(), mime::PLAIN);
        assert!(named.preread.is_none());
    }

    #[tokio::test]
    async fn preload_threshold_zero_still_sniffs_charset() {
        let temp_dir = tempfile::tempdir().expect("create temp dir");
        let path = temp_dir.path().join("data.json");
        std::fs::write(&path, br#"{"message":"hello"}"#).expect("write json file");

        let named = NamedFile::builder(&path)
            .preload_threshold(0)
            .build()
            .await
            .expect("build named file");

        assert_eq!(named.content_type().type_(), mime::APPLICATION);
        assert_eq!(named.content_type().subtype(), mime::JSON);
        assert_eq!(
            named
                .content_type()
                .get_param("charset")
                .map(|v| v.as_str()),
            Some("utf-8")
        );
        assert!(named.preread.is_none());
    }

    #[tokio::test]
    async fn send_head_sets_headers_without_body() {
        use crate::http::header::{ACCEPT_RANGES, CONTENT_LENGTH, CONTENT_TYPE};
        use crate::http::{HeaderMap, Response};

        let temp_dir = tempfile::tempdir().expect("create temp dir");
        let path = temp_dir.path().join("hello.txt");
        std::fs::write(&path, b"hello").expect("write file");

        let named = NamedFile::builder(&path)
            .content_type(mime::TEXT_PLAIN)
            .preload_threshold(0)
            .build()
            .await
            .expect("build named file");
        let mut res = Response::new();
        named.send_head(&HeaderMap::new(), &mut res).await;

        assert_eq!(res.status_code, Some(StatusCode::OK));
        assert_eq!(res.headers().get(CONTENT_LENGTH).unwrap(), "5");
        assert_eq!(res.headers().get(ACCEPT_RANGES).unwrap(), "bytes");
        assert!(
            res.headers()
                .get(CONTENT_TYPE)
                .unwrap()
                .to_str()
                .unwrap()
                .starts_with("text/plain")
        );
        assert!(res.body.is_none());
    }

    #[tokio::test]
    async fn zero_buffer_size_is_clamped() {
        use std::io::Write as _;

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        file.write_all(b"hello").expect("write file");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .buffer_size(0)
            .build()
            .await
            .expect("build named file");

        assert_eq!(named.buffer_size, 1);
    }

    #[tokio::test]
    async fn etag_returns_none_for_pre_epoch_modified_time() {
        use std::io::Write as _;
        use std::time::Duration;

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        file.write_all(b"hello").expect("write file");
        file.flush().expect("flush");

        let mut named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");
        named.modified = Some(UNIX_EPOCH - Duration::from_secs(1));

        assert_eq!(named.etag(), None);
    }

    #[tokio::test]
    async fn send_skips_last_modified_for_pre_epoch_modified_time() {
        use std::io::Write as _;
        use std::time::Duration;

        use crate::http::header::{IF_MODIFIED_SINCE, LAST_MODIFIED};
        use crate::http::{HeaderMap, Response};

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        file.write_all(b"hello").expect("write file");
        file.flush().expect("flush");

        let mut named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");
        let pre_epoch = UNIX_EPOCH - Duration::from_secs(1);
        named.modified = Some(pre_epoch);
        named.use_etag(false);
        assert_eq!(named.last_modified(), Some(pre_epoch));

        let mut headers = HeaderMap::new();
        headers.insert(
            IF_MODIFIED_SINCE,
            HeaderValue::from_static("Thu, 01 Jan 1970 00:00:00 GMT"),
        );
        let mut res = Response::new();
        named.send(&headers, &mut res).await;

        assert_eq!(res.status_code, Some(StatusCode::NOT_MODIFIED));
        assert!(!res.headers().contains_key(LAST_MODIFIED));
    }

    #[tokio::test]
    async fn send_if_modified_since_uses_http_date_precision() {
        use std::io::Write as _;
        use std::time::Duration;

        use crate::http::header::IF_MODIFIED_SINCE;
        use crate::http::{HeaderMap, Response};

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        file.write_all(b"hello").expect("write file");
        file.flush().expect("flush");

        let mut named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");
        named.modified =
            Some(UNIX_EPOCH + Duration::from_secs(100) + Duration::from_nanos(500_000_000));
        named.use_etag(false);

        let mut headers = HeaderMap::new();
        headers.insert(
            IF_MODIFIED_SINCE,
            HeaderValue::from_static("Thu, 01 Jan 1970 00:01:40 GMT"),
        );
        let mut res = Response::new();
        named.send(&headers, &mut res).await;

        assert_eq!(res.status_code, Some(StatusCode::NOT_MODIFIED));
    }

    #[tokio::test]
    async fn send_if_unmodified_since_uses_http_date_precision() {
        use std::io::Write as _;
        use std::time::Duration;

        use crate::http::header::IF_UNMODIFIED_SINCE;
        use crate::http::{HeaderMap, Response};

        let mut file = tempfile::NamedTempFile::new().expect("create temp file");
        file.write_all(b"hello").expect("write file");
        file.flush().expect("flush");

        let mut named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");
        named.modified =
            Some(UNIX_EPOCH + Duration::from_secs(100) + Duration::from_nanos(500_000_000));
        named.use_etag(false);

        let mut headers = HeaderMap::new();
        headers.insert(
            IF_UNMODIFIED_SINCE,
            HeaderValue::from_static("Thu, 01 Jan 1970 00:01:40 GMT"),
        );
        let mut res = Response::new();
        named.send(&headers, &mut res).await;

        assert_eq!(res.status_code, Some(StatusCode::OK));
    }

    #[test]
    fn content_disposition_preserves_non_ascii_with_filename_star() {
        let value = build_content_disposition(
            "ignored.txt",
            &mime::APPLICATION_OCTET_STREAM,
            None,
            Some("报告.csv"),
        )
        .unwrap();

        assert_eq!(
            value.to_str().unwrap(),
            "attachment; filename=\"__.csv\"; filename*=UTF-8''%E6%8A%A5%E5%91%8A.csv"
        );
    }

    #[test]
    fn only_self_coded_extensions_imply_an_encoding() {
        assert_eq!(extension_content_encoding("svgz"), Some("gzip"));
        // Matching follows `mime_infer`, which is case-insensitive.
        assert_eq!(extension_content_encoding("SVGZ"), Some("gzip"));
        assert_eq!(extension_content_encoding("x3dz"), Some("gzip"));
        // A `.gz` or `.tgz` *is* the representation being served, not a coding
        // applied to some other type, so it must keep its own content type and
        // arrive undecoded.
        assert_eq!(extension_content_encoding("gz"), None);
        assert_eq!(extension_content_encoding("tgz"), None);
        assert_eq!(extension_content_encoding("svg"), None);
    }

    #[tokio::test]
    async fn svgz_is_typed_as_svg_and_encoded_as_gzip() {
        use std::io::Write as _;

        let mut file = tempfile::Builder::new()
            .suffix(".svgz")
            .tempfile()
            .expect("create temp file");
        file.write_all(&[0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03])
            .expect("write gzip header");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .build()
            .await
            .expect("build named file");

        assert_eq!(named.content_type(), &mime::IMAGE_SVG);
        assert_eq!(
            named.content_encoding().map(|v| v.to_str().unwrap()),
            Some("gzip")
        );
    }

    #[tokio::test]
    async fn explicit_content_encoding_wins_over_the_extension() {
        use std::io::Write as _;

        // A `.svgz` recompressed as a brotli sidecar must report what the caller
        // configured, not the coding its extension would otherwise imply.
        let mut file = tempfile::Builder::new()
            .suffix(".svgz")
            .tempfile()
            .expect("create temp file");
        file.write_all(b"not really brotli").expect("write");
        file.flush().expect("flush");

        let named = NamedFile::builder(file.path())
            .content_encoding("br")
            .build()
            .await
            .expect("build named file");

        assert_eq!(
            named.content_encoding().map(|v| v.to_str().unwrap()),
            Some("br")
        );
    }
}