File: file_mask.c

package info (click to toggle)
rhash 1.4.3-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,408 kB
  • sloc: ansic: 19,132; sh: 1,196; xml: 933; makefile: 662; python: 431; java: 364; cs: 288; perl: 196; ruby: 76; sed: 16
file content (89 lines) | stat: -rw-r--r-- 2,301 bytes parent folder | download | duplicates (4)
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
/* file_mask.c - matching file against a list of file masks */
#include "file_mask.h"
#include "file.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * Convert the given string to lower-case then put it into
 * the specified array of 'file masks'.
 *
 * @param arr array of file masks
 * @param mask a string to add
 */
static void file_mask_add(file_mask_array* vect, const char* mask)
{
	rsh_vector_add_ptr(vect, 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* vect = file_mask_new();
	file_mask_add_list(vect, comma_separated_list);
	return vect;
}

/**
 * Split the given string by comma and put the parts into array.
 *
 * @param vect the array to put the parsed elements to
 * @param comma_separated_list the string to split
 */
void file_mask_add_list(file_mask_array* vect, const char* comma_separated_list)
{
	char* buf;
	char* cur;
	char* 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(vect, cur);
	}
	free(buf);
}

/**
 * Match a file path against a list of string trailers.
 * Usually used to match a filename against list of file extensions.
 *
 * @param vect the array of string trailers
 * @param file the file path to match
 * @return 1 if matched, 0 otherwise
 */
int file_mask_match(file_mask_array* vect, struct file_t* file)
{
	unsigned i;
	int res = 0;
	size_t len, namelen;
	char* buf;
	const char* name = file_get_print_path(file, FPathUtf8);
	if (!name)
		return 0;
	/* all names should match against an empty array */
	if (!vect || !vect->size)
		return 1;
	/* get a lowercase name version to ignore case when matching */
	buf = str_tolower(name);
	namelen = strlen(buf);
	for (i = 0; i < vect->size; i++) {
		len = strlen((char*)vect->array[i]);
		if (namelen >= len && memcmp(buf + namelen - len, vect->array[i], len) == 0) {
			res = 1; /* matched */
			break;
		}
	}
	free(buf);
	return res;
}