* loop over strtok_r results directly * set default value upfront because it depends solely on the first value * don't strtrim values, parseindex already takes care of any whitespace not removed by strtok_r * add doxygen Signed-off-by: Andrew Gregory <andrew.gregory.8@gmail.com> --- src/pacman/util.c | 65 +++++++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/src/pacman/util.c b/src/pacman/util.c index 115f328..ee67994 100644 --- a/src/pacman/util.c +++ b/src/pacman/util.c @@ -1311,55 +1311,58 @@ static int parseindex(char *s, int *val, int min, int max) } } +/** + * @brief Parse selected values from an input string. + * + * Multiple values may be separated by spaces or commas. Ranges can be + * specified with '-'. Values can be negated by prefixing them with '^'. + * + * @param array array of integers to hold selected values + * @param count number of options + * @param response string to parse + * + * @return 0 on success, -1 on error + */ static int multiselect_parse(char *array, int count, char *response) { char *str, *saveptr; - for(str = response; ; str = NULL) { + str = strtok_r(response, " ,", &saveptr); + + /* if first token is including, we unselect all targets */ + if(str && str[0] != '^') { + memset(array, 0, count); + } + + for(; str; str = strtok_r(NULL, " ,", &saveptr)) { int include = 1; int start, end; - size_t len; - char *ends = NULL; - char *starts = strtok_r(str, " ,", &saveptr); - - if(starts == NULL) { - break; - } - len = strtrim(starts); - if(len == 0) - continue; + char *ends; - if(*starts == '^') { - starts++; - len--; + if(str[0] == '^') { + str++; include = 0; - } else if(str) { - /* if first token is including, we unselect all targets */ - memset(array, 0, count); } - if(len > 1) { - /* check for range */ - char *p; - if((p = strchr(starts + 1, '-'))) { - *p = 0; - ends = p + 1; - } + /* check for a range */ + if((ends = strchr(str + 1, '-'))) { + *ends = '\0'; + ends++; } - if(parseindex(starts, &start, 1, count) != 0) + if(parseindex(str, &start, 1, count) != 0) { return -1; + } - if(!ends) { - array[start - 1] = include; - } else { - int d; + if(ends) { if(parseindex(ends, &end, start, count) != 0) { return -1; } - for(d = start; d <= end; d++) { - array[d - 1] = include; + for(; start <= end; start++) { + array[start - 1] = include; } + } else { + array[start - 1] = include; } } -- 1.8.2