forked from vysheng/tgl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tg-mime-types.c
108 lines (101 loc) · 2.33 KB
/
tg-mime-types.c
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
#include <string.h>
#include <assert.h>
#define MAX_MIME_TYPES_NUM 10000
#include "mime-types.c"
static int mime_initialized;
static int mime_type_number;
static char *mime_type_names[MAX_MIME_TYPES_NUM];
static char *mime_type_extensions[MAX_MIME_TYPES_NUM];
static void mime_init (void) {
char *start = (char *)mime_types;
char *end = start + mime_types_len;
mime_initialized = 1;
char *c = start;
while (c < end) {
if (*c == '#') {
while (c < end && *c != '\n') {
c ++;
}
if (c < end) {
c ++;
}
} else {
while (*c <= ' ' && *c != '\n' && c < end) {
c ++;
}
assert (*c > ' ' && *c != '\n' && c < end);
char *name = c;
while (*c > ' ' && *c != '\n' && c < end) {
c ++;
}
assert (*c <= ' ' && *c != '\n' && c < end);
*c = 0;
c ++;
while (1) {
while (*c <= ' ' && *c != '\n' && c < end) {
c ++;
}
if (*c == '\n' || c == end) {
if (*c == '\n') { c ++; }
break;
}
char *ext = c;
while (*c > ' ' && *c != '\n' && c < end) {
c ++;
}
assert (c != end);
int br = (*c == '\n');
*c = 0;
c ++;
assert (mime_type_number < MAX_MIME_TYPES_NUM);
mime_type_names[mime_type_number] = name;
mime_type_extensions[mime_type_number] = ext;
mime_type_number ++;
if (br) { break; }
}
}
}
}
char *tg_extension_by_mime (const char *mime_type) {
if (!mime_initialized) {
mime_init ();
}
int i;
for (i = 0; i < mime_type_number; i++) {
if (!strcmp (mime_type_names[i], mime_type)) {
return mime_type_extensions[i];
}
}
return NULL;
}
char *tg_mime_by_filename (const char *filename) {
int l = strlen (filename);
const char *p = filename - 1 + l;
while (p >= filename && *p != '.') {
p --;
}
p ++;
if (!mime_initialized) {
mime_init ();
}
static char *def = "application/octet-stream";
if (strlen (p) > 10) {
return def;
}
static char s[11];
strcpy (s, p);
char *q = s;
while (*q) {
if (*q >= 'A' && *p <= 'Z') {
*q = *q + 'z' - 'Z';
}
q ++;
}
int i;
for (i = 0; i < mime_type_number; i++) {
if (!strcmp (mime_type_extensions[i], s)) {
return mime_type_names[i];
}
}
return def;
}