-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmime.rs
1574 lines (1412 loc) · 51 KB
/
mime.rs
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
//! Provides functionality for handling MIME types.
use crate::util::unwrap_some;
use std::cmp::Ordering;
use std::fmt::{Debug, Display, Formatter};
/// QValue is defined as a fixed point number with up to 3 digits
/// after comma. with a valid range from 0 to 1.
/// We represent this as an u16 from 0 to 1000.
#[derive(Ord, PartialOrd, Eq, PartialEq, Copy, Clone, Debug, Hash)]
#[repr(transparent)]
pub struct QValue(u16);
impl QValue {
/// q=1.0
pub const MAX: QValue = QValue(1000);
/// q=0.0
pub const MIN: QValue = QValue(0);
/// Parses the QValue in http header representation.
/// Note: this is without the "q=" prefix!
/// Returns none if the value is either out of bounds or otherwise invalid.
pub fn parse(qvalue: impl AsRef<str>) -> Option<QValue> {
let qvalue = qvalue.as_ref();
match qvalue.len() {
1 => {
if qvalue == "1" {
return Some(QValue(1000));
}
if qvalue == "0" {
return Some(QValue(0));
}
None
}
2 => None,
3 => {
if !qvalue.starts_with("0.") {
if qvalue == "1.0" {
return Some(QValue(1000));
}
return None;
}
if let Ok(value) = qvalue[2..].parse::<u16>() {
return Some(QValue(value * 100));
}
None
}
4 => {
if !qvalue.starts_with("0.") {
if qvalue == "1.00" {
return Some(QValue(1000));
}
return None;
}
if let Ok(value) = qvalue[2..].parse::<u16>() {
return Some(QValue(value * 10));
}
None
}
5 => {
if !qvalue.starts_with("0.") {
if qvalue == "1.000" {
return Some(QValue(1000));
}
return None;
}
if let Ok(value) = qvalue[2..].parse::<u16>() {
return Some(QValue(value));
}
None
}
_ => None,
}
}
/// Returns the QValue in http header representation.
/// Note: this is without the "q=" prefix!
pub const fn as_str(&self) -> &'static str {
constutils::qvalue_to_strs!()
}
/// returns this QValue as an u16. This value always ranges from 0 to 1000.
/// 1000 corresponds to 1.0 since q-values are fixed point numbers with up to 3 digits after comma.
pub const fn as_u16(&self) -> u16 {
self.0
}
/// Returns a QValue from the given u16. Parameters greater than 1000 are clamped to 1000.
pub const fn from_clamped(qvalue: u16) -> QValue {
if qvalue > 1000 {
return QValue(1000);
}
QValue(qvalue)
}
}
impl Display for QValue {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl Default for QValue {
fn default() -> Self {
QValue(1000)
}
}
/// Version of MimeType that can contain "*" symbols.
#[derive(Clone, PartialEq, Debug, Eq, Hash)]
pub enum AcceptMimeType {
/// video/* or text/* or ...
GroupWildcard(MimeGroup),
/// text/html or application/json or ...
Specific(MimeType),
/// */*
Wildcard,
}
impl AsRef<AcceptMimeType> for AcceptMimeType {
fn as_ref(&self) -> &AcceptMimeType {
self
}
}
impl AcceptMimeType {
/// Parses an accept mime type.
pub fn parse(value: impl AsRef<str>) -> Option<AcceptMimeType> {
let mime = value.as_ref();
let mime = mime.split_once(";").map(|(mime, _)| mime).unwrap_or(mime);
if mime == "*/*" {
return Some(AcceptMimeType::Wildcard);
}
match MimeType::parse(mime) {
None => match MimeGroup::parse(mime) {
Some(group) => {
if &mime[group.as_str().len()..] != "/*" {
return None;
}
Some(AcceptMimeType::GroupWildcard(group))
}
None => None,
},
Some(mime) => Some(AcceptMimeType::Specific(mime)),
}
}
/// Returns true if this AcceptMimeType permits the given mime type.
pub fn permits_specific(&self, mime_type: impl AsRef<MimeType>) -> bool {
match self {
AcceptMimeType::GroupWildcard(group) => group == mime_type.as_ref().mime_group(),
AcceptMimeType::Specific(mime) => mime == mime_type.as_ref(),
AcceptMimeType::Wildcard => true,
}
}
/// Returns true if this AcceptMimeType will accept ANY mime from the given group.
pub fn permits_group(&self, mime_group: impl AsRef<MimeGroup>) -> bool {
match self {
AcceptMimeType::GroupWildcard(group) => group == mime_group.as_ref(),
AcceptMimeType::Specific(_) => false,
AcceptMimeType::Wildcard => true,
}
}
/// Returns true if this AcceptMimeType will permit ANY mime type permitted by the other AcceptMimeType.
pub fn permits(&self, mime_type: impl AsRef<AcceptMimeType>) -> bool {
match mime_type.as_ref() {
AcceptMimeType::GroupWildcard(group) => self.permits_group(group),
AcceptMimeType::Specific(mime) => self.permits_specific(mime),
AcceptMimeType::Wildcard => matches!(self, AcceptMimeType::Wildcard),
}
}
}
impl Display for AcceptMimeType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
AcceptMimeType::GroupWildcard(group) => {
f.write_str(group.as_str())?;
f.write_str("/*")?;
}
AcceptMimeType::Specific(mime) => {
f.write_str(mime.as_str())?;
}
AcceptMimeType::Wildcard => f.write_str("*/*")?,
}
Ok(())
}
}
///
/// Represents one part of an accept mime
/// # See
/// <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept>
#[derive(Clone, PartialEq, Debug, Eq)]
pub struct AcceptQualityMimeType {
value: AcceptMimeType,
q: QValue,
}
impl PartialOrd<Self> for AcceptQualityMimeType {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for AcceptQualityMimeType {
fn cmp(&self, other: &Self) -> Ordering {
other.q.cmp(&self.q)
}
}
impl AcceptQualityMimeType {
/// This fn parses an Accept header value from a client http request.
/// The returned Vec is sorted in descending order of quality value q.
pub fn parse(value: impl AsRef<str>) -> Option<Vec<Self>> {
let value = value.as_ref();
let mut data = Vec::new();
for mut mime in value.split(",") {
mime = mime.trim();
if let Some((mime, rawq)) = mime.split_once(";") {
if !rawq.starts_with("q=") {
// TODO we dont support level notation...
return None;
}
let qvalue = QValue::parse(&rawq[2..])?;
if mime == "*/*" {
data.push(AcceptQualityMimeType { value: AcceptMimeType::Wildcard, q: qvalue });
continue;
}
match MimeType::parse(mime) {
None => match MimeGroup::parse(mime) {
Some(group) => {
if &mime[group.as_str().len()..] != "/*" {
return None;
}
data.push(AcceptQualityMimeType {
value: AcceptMimeType::GroupWildcard(group),
q: qvalue,
})
}
None => return None,
},
Some(mime) => {
data.push(AcceptQualityMimeType { value: AcceptMimeType::Specific(mime), q: qvalue })
}
};
continue;
}
if mime == "*/*" {
data.push(AcceptQualityMimeType { value: AcceptMimeType::Wildcard, q: QValue::default() });
continue;
}
match MimeType::parse(mime) {
None => match MimeGroup::parse(mime) {
Some(group) => {
if &mime[group.as_str().len()..] != "/*" {
return None;
}
data.push(AcceptQualityMimeType {
value: AcceptMimeType::GroupWildcard(group),
q: QValue::default(),
})
}
None => return None,
},
Some(mime) => data.push(AcceptQualityMimeType {
value: AcceptMimeType::Specific(mime),
q: QValue::default(),
}),
};
}
data.sort();
Some(data)
}
/// Serializes a Vec of AcceptMime's into a full http header string.
/// The returned string is guaranteed to work with the `parse` fn.
pub fn elements_to_header_value(elements: &Vec<Self>) -> String {
let mut buffer = String::new();
for element in elements {
if !buffer.is_empty() {
buffer += ",";
}
buffer += element.to_string().as_str();
}
buffer
}
/// Gets the accept mime type without Q Value.
pub fn get_type(&self) -> &AcceptMimeType {
&self.value
}
/// Get the QValue of this accept mime.
pub const fn qvalue(&self) -> QValue {
self.q
}
/// Is this a */* accept?
pub const fn is_wildcard(&self) -> bool {
matches!(self.value, AcceptMimeType::Wildcard)
}
/// Is this a group wildcard? i.e: `video/*` or `text/*`
pub const fn is_group_wildcard(&self) -> bool {
matches!(self.value, AcceptMimeType::GroupWildcard(_))
}
/// Is this a non wildcard mime? i.e: `video/mp4`
pub const fn is_specific(&self) -> bool {
matches!(self.value, AcceptMimeType::Specific(_))
}
/// Get the mime type. returns none if this is any type of wildcard mime
pub const fn mime(&self) -> Option<&MimeType> {
match &self.value {
AcceptMimeType::Specific(mime) => Some(mime),
_ => None,
}
}
/// Get the mime type. returns none if this is the `*/*` mime.
pub const fn group(&self) -> Option<&MimeGroup> {
match &self.value {
AcceptMimeType::Specific(mime) => Some(mime.mime_group()),
AcceptMimeType::GroupWildcard(group) => Some(group),
_ => None,
}
}
/// Returns a AcceptMime equivalent to calling parse with `*/*`
pub const fn wildcard(q: QValue) -> AcceptQualityMimeType {
AcceptQualityMimeType { value: AcceptMimeType::Wildcard, q }
}
/// Returns a AcceptMime equivalent to calling parse with `group/*` depending on MimeGroup.
pub const fn from_group(group: MimeGroup, q: QValue) -> AcceptQualityMimeType {
AcceptQualityMimeType { value: AcceptMimeType::GroupWildcard(group), q }
}
/// Returns a AcceptMime equivalent to calling parse with `group/type` depending on MimeType.
pub const fn from_mime(mime: MimeType, q: QValue) -> AcceptQualityMimeType {
AcceptQualityMimeType { value: AcceptMimeType::Specific(mime), q }
}
}
impl Default for AcceptQualityMimeType {
fn default() -> Self {
AcceptQualityMimeType::wildcard(QValue::default())
}
}
impl Display for AcceptQualityMimeType {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(&self.value, f)?;
if self.q.as_u16() != 1000 {
f.write_str(";q=")?;
f.write_str(self.q.as_str())?;
}
Ok(())
}
}
/// Mime types are split into groups denoted by whatever is before of the "/"
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
pub enum MimeGroup {
/// Fonts
Font,
/// Custom application specific things.
Application,
/// Images, anything that can be rendered onto a screen.
Image,
/// Video maybe with audio maybe without.
Video,
/// Audio
Audio,
/// Any human or pseudo human-readable text.
Text,
/// Anything else.
Other(String),
}
impl AsRef<MimeGroup> for MimeGroup {
fn as_ref(&self) -> &MimeGroup {
self
}
}
impl Display for MimeGroup {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
const WELL_KNOWN_GROUPS: &[MimeGroup] = &[
MimeGroup::Font,
MimeGroup::Application,
MimeGroup::Image,
MimeGroup::Video,
MimeGroup::Audio,
MimeGroup::Text,
];
impl MimeGroup {
/// Parses a mime group from a str.
/// This str can be either the mime group directly such as "video"
/// or the full mime type such as "video/mp4"
/// or the accept mime such as "video/*"
/// both will yield Some(MimeGroup::Video)
///
/// This fn returns none if the passed string contains "*" in the mime group.
/// in the group or other invalid values.
///
pub fn parse<T: AsRef<str>>(value: T) -> Option<Self> {
let mut value = value.as_ref();
if let Some((group, _)) = value.split_once("/") {
value = group;
}
for char in value.bytes() {
if !check_header_byte(char) {
return None;
}
}
Some(match value {
"font" => MimeGroup::Font,
"application" => MimeGroup::Application,
"image" => MimeGroup::Image,
"video" => MimeGroup::Video,
"audio" => MimeGroup::Audio,
"text" => MimeGroup::Text,
_ => MimeGroup::Other(value.to_string()),
})
}
/// returns a static array over all well known mime groups.
#[must_use]
pub const fn well_known() -> &'static [MimeGroup] {
WELL_KNOWN_GROUPS
}
/// returns true if this is a well known http mime group.
#[must_use]
pub const fn is_well_known(&self) -> bool {
!matches!(self, Self::Other(_))
}
/// returns true if this is a custom http mime group.
#[must_use]
pub const fn is_custom(&self) -> bool {
matches!(self, Self::Other(_))
}
/// Returns a static str of the mime group or None if the mime type is heap allocated.
pub const fn well_known_str(&self) -> Option<&'static str> {
Some(match self {
MimeGroup::Font => "font",
MimeGroup::Application => "application",
MimeGroup::Image => "image",
MimeGroup::Video => "video",
MimeGroup::Audio => "audio",
MimeGroup::Text => "text",
MimeGroup::Other(_) => return None,
})
}
/// returns the str name of the mime group.
/// This name can be fed back into parse to get the equivalent enum of self.
pub fn as_str(&self) -> &str {
match self {
MimeGroup::Font => "font",
MimeGroup::Application => "application",
MimeGroup::Image => "image",
MimeGroup::Video => "video",
MimeGroup::Audio => "audio",
MimeGroup::Text => "text",
MimeGroup::Other(o) => o.as_str(),
}
}
}
/// Represents a MIME type as used in the `Content-Type` header.
///
/// # This list is not complete.
/// If you are missing a type then create a PR.
///
/// All PR's for types found on IANA's mime list will always be accepted.
///
/// All PR's for other types will be accepted if the file type is reasonably common
/// and the suggested mime type can found on the internet.
#[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
#[non_exhaustive]
pub enum MimeType {
///////////////////////////////////////// FONT
/// font/ttf
FontTtf,
/// font/otf
FontOtf,
/// font/woff
FontWoff,
/// font/woff2
FontWoff2,
////////////////////////////////////// Application
/// application/x-abiword
ApplicationAbiWord,
/// application/x-freearc
ApplicationFreeArc,
/// application/vnd.amazon.ebook
ApplicationAmazonEbook,
/// application/x-bzip
ApplicationBzip,
/// application/x-bzip2
ApplicationBzip2,
/// application/x-cdf
ApplicationCDAudio,
/// application/x-csh
ApplicationCShell,
/// application/msword
ApplicationMicrosoftWord,
/// application/vnd.openxmlformats-officedocument.wordprocessingml.document
ApplicationMicrosoftWordXml,
/// application/vnd.ms-fontobject
ApplicationMicrosoftFont,
/// application/epub+zip
ApplicationEpub,
/// application/gzip IANA
/// application/x-gzip Microsoft
ApplicationGzip,
/// application/java-archive
ApplicationJar,
/// application/x-java-class
ApplicationJavaClass,
/// application/octet-stream
ApplicationOctetStream,
/// application/json
ApplicationJson,
/// application/ld+json
ApplicationJsonLd,
/// application/yaml
ApplicationYaml,
/// application/x-lua
TextLua,
/// application/x-lua-bytecode
ApplicationLuaBytecode,
/// application/pdf
ApplicationPdf,
/// application/zip
ApplicationZip,
/// application/vnd.apple.installer+xml
ApplicationAppleInstallerPackage,
/// application/vnd.oasis.opendocument.presentation
ApplicationOpenDocumentPresentation,
/// application/vnd.oasis.opendocument.spreadsheet
ApplicationOpenDocumentSpreadsheet,
/// application/vnd.oasis.opendocument.text
ApplicationOpenDocumentText,
/// application/ogg
ApplicationOgg,
/// application/x-httpd-php
ApplicationPhp,
/// application/vnd.ms-powerpoint
ApplicationMicrosoftPowerpoint,
/// application/vnd.openxmlformats-officedocument.presentationml.presentation
ApplicationMicrosoftPowerpointXml,
/// application/vnd.rar
ApplicationRar,
/// application/rtf
ApplicationRichText,
/// application/x-sh
ApplicationBourneShell,
/// application/x-tar
ApplicationTapeArchive,
/// application/vnd.visio
ApplicationMicrosoftVisio,
/// application/xhtml+xml
ApplicationXHtml,
/// application/vnd.ms-excel
ApplicationMicrosoftExcel,
/// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
ApplicationMicrosoftExcelXml,
/// application/xml
/// text/xml
ApplicationXml,
/// application/vnd.mozilla.xul+xml
ApplicationXul,
/// application/dicom
ApplicationDicom,
/// application/x-7z-compressed
Application7Zip,
/// application/x-xz
ApplicationXz,
/// application/wasm
ApplicationWasm,
////////////////////////////////////// VIDEO
/// video/mp4
VideoMp4,
/// video/ogg
VideoOgg,
/// video/webm
VideoWebm,
/// video/x-msvideo
VideoAvi,
/// video/mpeg
VideoMpeg,
/// video/mp2t
VideoMpegTransportStream,
/// audio/3gpp
Video3gpp,
/// audio/3gpp2
Video3gpp2,
///////////////////////////////////// Image animated and not
/// image/bmp
ImageBmp,
/// image/gif
ImageGif,
/// image/jpeg
ImageJpeg,
/// image/avif
ImageAvif,
/// image/png
ImagePng,
/// image/apng
ImageApng,
/// image/webp
ImageWebp,
/// image/svg+xml
ImageSvg,
/// image/vnd.microsoft.icon
ImageIcon,
/// image/tiff
ImageTiff,
///////////////////////////////////// AUDIO
/// audio/aac
AudioAac,
/// audio/midi
/// audio/x-midi
AudioMidi,
/// audio/mpeg
AudioMpeg,
/// audio/ogg
AudioOgg,
/// audio/wav
AudioWaveform,
/// audio/webm
AudioWebm,
/// audio/3gpp
Audio3gpp,
/// audio/3gpp2
Audio3gpp2,
//////////////////////////////////// Text documents
/// text/css
TextCss,
/// text/html
TextHtml,
/// text/javascript
TextJavaScript,
/// text/plain
TextPlain,
/// text/csv
TextCsv,
/// text/calendar
TextCalendar,
///Anything else
Other(MimeGroup, String),
}
impl AsRef<MimeType> for MimeType {
fn as_ref(&self) -> &MimeType {
self
}
}
const WELL_KNOWN_TYPES: &[MimeType] = &[
MimeType::FontTtf,
MimeType::FontOtf,
MimeType::FontWoff,
MimeType::FontWoff2,
MimeType::ApplicationAbiWord,
MimeType::ApplicationFreeArc,
MimeType::ApplicationAmazonEbook,
MimeType::ApplicationBzip,
MimeType::ApplicationBzip2,
MimeType::ApplicationCDAudio,
MimeType::ApplicationCShell,
MimeType::ApplicationMicrosoftWord,
MimeType::ApplicationMicrosoftWordXml,
MimeType::ApplicationMicrosoftFont,
MimeType::ApplicationEpub,
MimeType::ApplicationGzip,
MimeType::ApplicationJar,
MimeType::ApplicationJavaClass,
MimeType::ApplicationOctetStream,
MimeType::ApplicationJson,
MimeType::ApplicationJsonLd,
MimeType::ApplicationPdf,
MimeType::ApplicationZip,
MimeType::ApplicationAppleInstallerPackage,
MimeType::ApplicationOpenDocumentPresentation,
MimeType::ApplicationOpenDocumentSpreadsheet,
MimeType::ApplicationOpenDocumentText,
MimeType::ApplicationOgg,
MimeType::ApplicationPhp,
MimeType::ApplicationMicrosoftPowerpoint,
MimeType::ApplicationMicrosoftPowerpointXml,
MimeType::ApplicationRar,
MimeType::ApplicationRichText,
MimeType::ApplicationBourneShell,
MimeType::ApplicationTapeArchive,
MimeType::ApplicationMicrosoftVisio,
MimeType::ApplicationXHtml,
MimeType::ApplicationMicrosoftExcel,
MimeType::ApplicationMicrosoftExcelXml,
MimeType::ApplicationXml,
MimeType::ApplicationXul,
MimeType::ApplicationDicom,
MimeType::Application7Zip,
MimeType::ApplicationWasm,
MimeType::VideoMp4,
MimeType::VideoOgg,
MimeType::VideoWebm,
MimeType::VideoAvi,
MimeType::VideoMpeg,
MimeType::VideoMpegTransportStream,
MimeType::Video3gpp,
MimeType::Video3gpp2,
MimeType::ImageBmp,
MimeType::ImageGif,
MimeType::ImageJpeg,
MimeType::ImageAvif,
MimeType::ImagePng,
MimeType::ImageApng,
MimeType::ImageWebp,
MimeType::ImageSvg,
MimeType::ImageIcon,
MimeType::ImageTiff,
MimeType::AudioAac,
MimeType::AudioMidi,
MimeType::AudioMpeg,
MimeType::AudioOgg,
MimeType::AudioWaveform,
MimeType::AudioWebm,
MimeType::Audio3gpp,
MimeType::Audio3gpp2,
MimeType::TextCss,
MimeType::TextHtml,
MimeType::TextJavaScript,
MimeType::TextPlain,
MimeType::TextCsv,
MimeType::TextCalendar,
MimeType::ApplicationYaml,
MimeType::TextLua,
MimeType::ApplicationLuaBytecode,
MimeType::ApplicationXz,
];
impl MimeType {
/// Converts from a file extension without the `.` to the enum variant.
/// If the MIME type cannot be inferred from the extension, returns `MimeType::ApplicationOctetStream`.
pub fn from_extension(extension: impl AsRef<str>) -> Self {
//TODO Heap allocation to_ascii_lowercase
match extension.as_ref().to_ascii_lowercase().as_str() {
"css" => MimeType::TextCss,
"html" => MimeType::TextHtml,
"htm" => MimeType::TextHtml,
"js" => MimeType::TextJavaScript,
"mjs" => MimeType::TextJavaScript,
"txt" => MimeType::TextPlain,
"bmp" => MimeType::ImageBmp,
"gif" => MimeType::ImageGif,
"jpeg" => MimeType::ImageJpeg,
"jpg" => MimeType::ImageJpeg,
"png" => MimeType::ImagePng,
"webp" => MimeType::ImageWebp,
"svg" => MimeType::ImageSvg,
"ico" => MimeType::ImageIcon,
"json" => MimeType::ApplicationJson,
"pdf" => MimeType::ApplicationPdf,
"zip" => MimeType::ApplicationZip,
"mp4" => MimeType::VideoMp4,
"ogv" => MimeType::VideoOgg,
"webm" => MimeType::VideoWebm,
"ttf" => MimeType::FontTtf,
"otf" => MimeType::FontOtf,
"woff" => MimeType::FontWoff,
"woff2" => MimeType::FontWoff2,
"abw" => MimeType::ApplicationAbiWord,
"arc" => MimeType::ApplicationFreeArc,
"azw" => MimeType::ApplicationAmazonEbook,
"bz" => MimeType::ApplicationBzip,
"bz2" => MimeType::ApplicationBzip2,
"cda" => MimeType::ApplicationCDAudio,
"csh" => MimeType::ApplicationCShell,
"doc" => MimeType::ApplicationMicrosoftWord,
"docx" => MimeType::ApplicationMicrosoftWordXml,
"eot" => MimeType::ApplicationMicrosoftFont,
"epub" => MimeType::ApplicationEpub,
"gz" => MimeType::ApplicationGzip,
"jar" => MimeType::ApplicationJar,
"class" => MimeType::ApplicationJavaClass,
"bin" => MimeType::ApplicationOctetStream,
"jsonld" => MimeType::ApplicationJsonLd,
"mpkg" => MimeType::ApplicationAppleInstallerPackage,
"odp" => MimeType::ApplicationOpenDocumentPresentation,
"ods" => MimeType::ApplicationOpenDocumentSpreadsheet,
"odt" => MimeType::ApplicationOpenDocumentText,
"ogx" => MimeType::ApplicationOgg,
"php" => MimeType::ApplicationPhp,
"ppt" => MimeType::ApplicationMicrosoftPowerpoint,
"pptx" => MimeType::ApplicationMicrosoftPowerpointXml,
"rar" => MimeType::ApplicationRar,
"rtf" => MimeType::ApplicationRichText,
"sh" => MimeType::ApplicationBourneShell,
"tar" => MimeType::ApplicationTapeArchive,
"vsd" => MimeType::ApplicationMicrosoftVisio,
"xhtml" => MimeType::ApplicationXHtml,
"xls" => MimeType::ApplicationMicrosoftExcel,
"xlsx" => MimeType::ApplicationMicrosoftExcelXml,
"xml" => MimeType::ApplicationXml,
"xul" => MimeType::ApplicationXul,
"dcm" => MimeType::ApplicationDicom,
"7z" => MimeType::Application7Zip,
"wasm" => MimeType::ApplicationWasm,
"avi" => MimeType::VideoAvi,
"mpeg" => MimeType::VideoMpeg,
"ts" => MimeType::VideoMpegTransportStream,
"3gp" => MimeType::Video3gpp,
"3g2" => MimeType::Video3gpp2,
"avif" => MimeType::ImageAvif,
"apng" => MimeType::ImageApng,
"tif" => MimeType::ImageTiff,
"aac" => MimeType::AudioAac,
"mid" => MimeType::AudioMidi,
"mp3" => MimeType::AudioMpeg,
"oga" => MimeType::AudioOgg,
"wav" => MimeType::AudioWaveform,
"weba" => MimeType::AudioWebm,
"csv" => MimeType::TextCsv,
"cal" => MimeType::TextCalendar,
"yaml" | "yml" => MimeType::ApplicationYaml,
"lua" => MimeType::TextLua,
"luac" => MimeType::ApplicationLuaBytecode,
"xz" => MimeType::ApplicationXz,
_ => MimeType::ApplicationOctetStream,
}
}
/// returns the file extension that is most likely correct for the given file type.
/// For mime types where this is not clear "bin" is returned.
#[must_use]
pub const fn extension(&self) -> &'static str {
match self {
MimeType::FontTtf => "ttf",
MimeType::FontOtf => "otf",
MimeType::FontWoff => "woff",
MimeType::FontWoff2 => "woff2",
MimeType::ApplicationAbiWord => "abw",
MimeType::ApplicationFreeArc => "arc",
MimeType::ApplicationAmazonEbook => "azw",
MimeType::ApplicationBzip => "bz",
MimeType::ApplicationBzip2 => "bz2",
MimeType::ApplicationCDAudio => "cda",
MimeType::ApplicationCShell => "csh",
MimeType::ApplicationMicrosoftWord => "doc",
MimeType::ApplicationMicrosoftWordXml => "docx",
MimeType::ApplicationMicrosoftFont => "eot",
MimeType::ApplicationEpub => "epub",
MimeType::ApplicationGzip => "gz",
MimeType::ApplicationJar => "jar",
MimeType::ApplicationJavaClass => "class",
MimeType::ApplicationOctetStream => "bin",
MimeType::ApplicationJson => "json",
MimeType::ApplicationJsonLd => "jsonld",
MimeType::ApplicationPdf => "pdf",
MimeType::ApplicationZip => "zip",
MimeType::ApplicationAppleInstallerPackage => "mpkg",
MimeType::ApplicationOpenDocumentPresentation => "odp",
MimeType::ApplicationOpenDocumentSpreadsheet => "ods",
MimeType::ApplicationOpenDocumentText => "odt",
MimeType::ApplicationOgg => "ogx",
MimeType::ApplicationPhp => "php",
MimeType::ApplicationMicrosoftPowerpoint => "ppt",
MimeType::ApplicationMicrosoftPowerpointXml => "pptx",
MimeType::ApplicationRar => "rar",
MimeType::ApplicationRichText => "rtf",
MimeType::ApplicationBourneShell => "sh",
MimeType::ApplicationTapeArchive => "tar",
MimeType::ApplicationMicrosoftVisio => "vsd",
MimeType::ApplicationXHtml => "xhtml",
MimeType::ApplicationMicrosoftExcel => "xls",
MimeType::ApplicationMicrosoftExcelXml => "xlsx",
MimeType::ApplicationXml => "xml",
MimeType::ApplicationXul => "xul",
MimeType::ApplicationDicom => "dcm",
MimeType::Application7Zip => "7z",
MimeType::ApplicationWasm => "wasm",
MimeType::VideoMp4 => "mp4",
MimeType::VideoOgg => "ogv",
MimeType::VideoWebm => "webm",
MimeType::VideoAvi => "avi",
MimeType::VideoMpeg => "mpeg",
MimeType::VideoMpegTransportStream => "ts",
MimeType::Video3gpp => "3gp",
MimeType::Video3gpp2 => "3g2",
MimeType::ImageBmp => "bmp",
MimeType::ImageGif => "gif",
MimeType::ImageJpeg => "jpg",
MimeType::ImageAvif => "avif",
MimeType::ImagePng => "png",
MimeType::ImageApng => "apng",
MimeType::ImageWebp => "webp",
MimeType::ImageSvg => "svg",
MimeType::ImageIcon => "ico",