0ee509d9e8b93d2e537d8010b034468707e65a32
[lms] / lightmediascanner / src / lib / lightmediascanner_utils.c
1 #include <lightmediascanner_utils.h>
2 #include <ctype.h>
3 #include <alloca.h>
4
5 /**
6  * Strips string, in place.
7  *
8  * @param str string to be stripped.
9  * @param p_len string length to analyse, also the place where the final size
10  *        is stored.
11  */
12 void
13 lms_strstrip(char *str, unsigned int *p_len)
14 {
15     int i, len;
16     char *p;
17
18     len = *p_len;
19
20     if (len < 2) /* just '\0'? */
21         return;
22
23     p = str + len - 1;
24     for (i = len - 1; i >= 0; i--) {
25         if (isspace(*p)) {
26             *p = '\0';
27             len--;
28             p--;
29         } else
30             break;
31     }
32     if (len == 0) {
33         *p_len = 0;
34         return;
35     }
36
37     p = str;
38     for (i = 0; i < len; i++) {
39         if (isspace(*p))
40             p++;
41         else
42             break;
43     }
44     len -= i;
45     if (len == 0) {
46         *str = '\0';
47         *p_len = 0;
48         return;
49     }
50
51     *p_len = len;
52
53     if (str < p)
54         for (; len > 0; len--, str++, p++)
55             *str = *p;
56 }
57
58 /**
59  * Find out which of the given extensions matches the given name.
60  *
61  * @param name string to analyse.
62  * @param name_len string length.
63  * @param exts array of extensions to be checked.
64  * @param exts_len number of items in array @p exts
65  *
66  * @return index in @p exts or -1 if it doesn't match none.
67  */
68 int
69 lms_which_extension(const char *name, unsigned int name_len, const struct lms_string_size *exts, unsigned int exts_len) {
70     int i;
71     unsigned int *exts_pos;
72     const char *s;
73
74     exts_pos = alloca(exts_len * sizeof(*exts_pos));
75     for (i = 0; i < exts_len; i++)
76         exts_pos[i] = exts[i].len;
77
78     for (s = name + name_len - 1; s >= name; s--) {
79         int i, match;
80         char c1, c2;
81
82         c1 = *s;
83         if (c1 >= 'a')
84             c2 = c1;
85         else
86             c2 = 'a' + c1 - 'A';
87
88         match = 0;
89         for (i = 0; i < exts_len; i++) {
90             if (exts_pos[i] > 0) {
91                 char ce;
92
93                 ce = exts[i].str[exts_pos[i] - 1];
94                 if (ce == c1 || ce == c2) {
95                     if (exts_pos[i] == 1)
96                         return i;
97                     exts_pos[i]--;
98                     match = 1;
99                 } else
100                     exts_pos[i] = 0;
101             }
102         }
103         if (!match)
104             return -1;
105     }
106
107     return -1;
108 }