From a883c6349c21a0cab209e100d936340c50e087d2 Mon Sep 17 00:00:00 2001 From: Davidlohr Bueso Date: Tue, 11 Oct 2011 23:18:12 -0400 Subject: lib,strutils: share parse_range() This function is currently only being used by partx(8), but it's handy and generic enough that we can use it elsewhere as well. Signed-off-by: Davidlohr Bueso --- lib/strutils.c | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) (limited to 'lib/strutils.c') diff --git a/lib/strutils.c b/lib/strutils.c index aad9f7738..fb1822976 100644 --- a/lib/strutils.c +++ b/lib/strutils.c @@ -424,7 +424,7 @@ int string_to_idarray(const char *list, int ary[], size_t arysz, * as a possition in the 'ary' bit array. It means that the 'id' has to be in * range <0..N> where N < sizeof(ary) * NBBY. * - * Returns: 0 on sucess, <0 on error. + * Returns: 0 on success, <0 on error. */ int string_to_bitarray(const char *list, char *ary, @@ -461,6 +461,49 @@ int string_to_bitarray(const char *list, return 0; } +/* + * Parse the lower and higher values in a string containing + * "lower:higher" or "lower-higher" format. Note that either + * the lower or the higher values may be missing. + * + * Returns: 0 on success, <0 on error. + */ +int parse_range(const char *str, int *lower, int *upper) +{ + char *end = NULL; + + if (!str) + return 0; + + *upper = *lower = 0; + errno = 0; + + if (*str == ':') { /* <:N> */ + str++; + *upper = strtol(str, &end, 10); + if (errno || !end || *end || end == str) + return -1; + } else { + *upper = *lower = strtol(str, &end, 10); + if (errno || !end || end == str) + return -1; + + if (*end == ':' && !*(end + 1)) /* */ + *upper = 0; + else if (*end == '-' || *end == ':') { /* */ + str = end + 1; + end = NULL; + errno = 0; + *upper = strtol(str, &end, 10); + + if (errno || !end || *end || end == str) + return -1; + } + } + return 0; +} + + #ifdef TEST_PROGRAM int main(int argc, char *argv[]) -- cgit v1.2.3-55-g7522