2.69
xs_mime.h
1/* copyright (c) 2022 - 2025 grunfink et al. / MIT license */
2
3#ifndef _XS_MIME_H
4
5#define _XS_MIME_H
6
7const char *xs_mime_by_ext(const char *file);
8
9extern const char *xs_mime_types[];
10
11#ifdef XS_IMPLEMENTATION
12
13/* intentionally brain-dead simple */
14/* CAUTION: sorted by extension */
15
16const char *xs_mime_types[] = {
17 "3gp", "video/3gpp",
18 "aac", "audio/aac",
19 "avif", "image/avif",
20 "css", "text/css",
21 "flac", "audio/flac",
22 "flv", "video/flv",
23 "gif", "image/gif",
24 "gmi", "text/gemini",
25 "html", "text/html",
26 "jpeg", "image/jpeg",
27 "jpg", "image/jpeg",
28 "json", "application/json",
29 "m4a", "audio/aac",
30 "m4v", "video/mp4",
31 "md", "text/markdown",
32 "mov", "video/quicktime",
33 "mp3", "audio/mp3",
34 "mp4", "video/mp4",
35 "mpg4", "video/mp4",
36 "oga", "audio/ogg",
37 "ogg", "audio/ogg",
38 "ogv", "video/ogg",
39 "opus", "audio/ogg",
40 "png", "image/png",
41 "svg", "image/svg+xml",
42 "svgz", "image/svg+xml",
43 "txt", "text/plain",
44 "wav", "audio/wav",
45 "webm", "video/webm",
46 "webp", "image/webp",
47 "wma", "audio/wma",
48 "xml", "text/xml",
49 NULL, NULL,
50};
51
52
53const char *xs_mime_by_ext(const char *file)
54/* returns the MIME type by file extension */
55{
56 const char *ext = strrchr(file, '.');
57
58 if (ext) {
59 xs *uext = xs_tolower_i(xs_dup(ext + 1));
60 int b = 0;
61 int t = xs_countof(xs_mime_types) / 2 - 2;
62
63 while (t >= b) {
64 int n = (b + t) / 2;
65 const char *p = xs_mime_types[n * 2];
66
67 int c = strcmp(uext, p);
68
69 if (c < 0)
70 t = n - 1;
71 else
72 if (c > 0)
73 b = n + 1;
74 else
75 return xs_mime_types[(n * 2) + 1];
76 }
77 }
78
79 return "application/octet-stream";
80}
81
82
83#endif /* XS_IMPLEMENTATION */
84
85#endif /* XS_MIME_H */