xref: /dpdk/examples/vm_power_manager/parse.c (revision 25d11a86c56d50947af33d0b79ede622809bd8b9)
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2010-2014 Intel Corporation.
3  * Copyright(c) 2014 6WIND S.A.
4  */
5 
6 #include <string.h>
7 #include <rte_log.h>
8 #include "parse.h"
9 
10 /*
11  * Parse elem, the elem could be single number/range or group
12  * 1) A single number elem, it's just a simple digit. e.g. 9
13  * 2) A single range elem, two digits with a '-' between. e.g. 2-6
14  * 3) A group elem, combines multiple 1) or 2) e.g 0,2-4,6
15  *    Within group, '-' used for a range separator;
16  *                       ',' used for a single number.
17  */
18 int
19 parse_set(const char *input, uint16_t set[], unsigned int num)
20 {
21 	unsigned int idx;
22 	const char *str = input;
23 	char *end = NULL;
24 	unsigned int min, max;
25 
26 	memset(set, 0, num * sizeof(uint16_t));
27 
28 	while (isblank(*str))
29 		str++;
30 
31 	/* only digit or left bracket is qualify for start point */
32 	if (!isdigit(*str) || *str == '\0')
33 		return -1;
34 
35 	while (isblank(*str))
36 		str++;
37 	if (*str == '\0')
38 		return -1;
39 
40 	min = num;
41 	do {
42 
43 		/* go ahead to the first digit */
44 		while (isblank(*str))
45 			str++;
46 		if (!isdigit(*str))
47 			return -1;
48 
49 		/* get the digit value */
50 		errno = 0;
51 		idx = strtoul(str, &end, 10);
52 		if (errno || end == NULL || idx >= num)
53 			return -1;
54 
55 		/* go ahead to separator '-' and ',' */
56 		while (isblank(*end))
57 			end++;
58 		if (*end == '-') {
59 			if (min == num)
60 				min = idx;
61 			else /* avoid continuous '-' */
62 				return -1;
63 		} else if ((*end == ',') || (*end == '\0')) {
64 			max = idx;
65 
66 			if (min == num)
67 				min = idx;
68 
69 			for (idx = RTE_MIN(min, max);
70 					idx <= RTE_MAX(min, max); idx++) {
71 				set[idx] = 1;
72 			}
73 			min = num;
74 		} else
75 			return -1;
76 
77 		str = end + 1;
78 	} while (*end != '\0');
79 
80 	return str - input;
81 }
82