forked from rhash/RHash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_mask.c
84 lines (78 loc) · 2.06 KB
/
file_mask.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
/* file_mask.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "common_func.h"
#include "file_mask.h"
/**
* Convert a string to a lower-case and put it into array of file-masks.
*
* @param arr array of file masks
* @param mask a string to add
*/
static void file_mask_add(file_mask_array* arr, const char* mask)
{
rsh_vector_add_ptr(arr, str_tolower(mask));
}
/**
* Construct array from a comma-separated list of strings.
*
* @param comma_separated_list the comma-separated list of strings
* @return constructed array
*/
file_mask_array* file_mask_new_from_list(const char* comma_separated_list)
{
file_mask_array* array = file_mask_new();
file_mask_add_list(array, comma_separated_list);
return array;
}
/**
* Parse string consisting of comma-delimited list of elements an
* add them to array.
*
* @param array the array to put parsed elements to
* @param comma_separated_list tre string to parse
*/
void file_mask_add_list(file_mask_array* array, const char* comma_separated_list)
{
char *buf, *cur, *next;
if(!comma_separated_list || !*comma_separated_list) {
return;
}
buf = rsh_strdup(comma_separated_list);
for(cur = buf; cur && *cur; cur = next) {
next = strchr(cur, ',');
if(next) *(next++) = '\0';
if(*cur != '\0') file_mask_add(array, cur);
}
free(buf);
}
/**
* Match a given name against a list of string trailers.
* Usually used to match a filename against list of file extensions.
*
* @param arr the array of string trailers
* @param name the name to match
*/
int file_mask_match(file_mask_array* arr, const char* name)
{
unsigned i;
int res = 0;
size_t len, namelen;
char* buf;
/* all names should match against an empty array */
if(!arr || !arr->size) return 1;
/* get a lowercase name version to ignore case when matching */
buf = str_tolower(name);
namelen = strlen(buf);
for(i = 0; i<arr->size; i++) {
len = strlen((char*)arr->array[i]);
if(namelen >= len && memcmp(buf + namelen - len, arr->array[i], len) == 0) {
res = 1; /* matched */
break;
}
}
free(buf);
return res;
}