btrfs-progs: move arg_strtou64 to a separate file for library
[platform/upstream/btrfs-progs.git] / utils-lib.c
1 #define _GNU_SOURCE
2
3 #include "kerncompat.h"
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <limits.h>
7
8 #if BTRFS_FLAT_INCLUDES
9 #else
10 #endif /* BTRFS_FLAT_INCLUDES */
11
12 /*
13  * This function should be only used when parsing command arg, it won't return
14  * error to its caller and rather exit directly just like usage().
15  */
16 u64 arg_strtou64(const char *str)
17 {
18         u64 value;
19         char *ptr_parse_end = NULL;
20
21         value = strtoull(str, &ptr_parse_end, 0);
22         if (ptr_parse_end && *ptr_parse_end != '\0') {
23                 fprintf(stderr, "ERROR: %s is not a valid numeric value.\n",
24                         str);
25                 exit(1);
26         }
27
28         /*
29          * if we pass a negative number to strtoull, it will return an
30          * unexpected number to us, so let's do the check ourselves.
31          */
32         if (str[0] == '-') {
33                 fprintf(stderr, "ERROR: %s: negative value is invalid.\n",
34                         str);
35                 exit(1);
36         }
37         if (value == ULLONG_MAX) {
38                 fprintf(stderr, "ERROR: %s is too large.\n", str);
39                 exit(1);
40         }
41         return value;
42 }