xref: /dpdk/examples/vm_power_manager/parse.c (revision 99a2dd955fba6e4cc23b77d590a033650ced9c45)
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 == ':') || (*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') && (*end != ':'));
79 
80 	return str - input;
81 }
82 
83 int
84 parse_branch_ratio(const char *input, float *branch_ratio)
85 {
86 	const char *str = input;
87 	char *end = NULL;
88 
89 	while (isblank(*str))
90 		str++;
91 
92 	if (*str == '\0')
93 		return -1;
94 
95 	/* Go straight to the ':' separator if present */
96 	while ((*str != '\0') && (*str != ':'))
97 		str++;
98 
99 	/* Branch ratio not specified in args so leave it at default setting */
100 	if (*str == '\0')
101 		return 0;
102 
103 	/* Confirm ':' separator present */
104 	if (*str != ':')
105 		return -1;
106 
107 	str++;
108 	errno = 0;
109 	*branch_ratio = strtof(str, &end);
110 	if (errno || end == NULL)
111 		return -1;
112 
113 	if (*end != '\0')
114 		return -1;
115 
116 	str = end + 1;
117 
118 	return str - input;
119 }
120