xref: /memcached-1.4.29/util.c (revision fba0a891)
1 #include <stdlib.h>
2 #include <assert.h>
3 #include <ctype.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <stdlib.h>
7 
8 #include "memcached.h"
9 
10 bool safe_strtoull(const char *str, uint64_t *out) {
11     assert(out != NULL);
12     errno = 0;
13     *out = 0;
14     char *endptr;
15     unsigned long long ull = strtoull(str, &endptr, 10);
16     if (errno == ERANGE)
17         return false;
18     if (isspace(*endptr) || (*endptr == '\0' && endptr != str)) {
19         if ((long long) ull < 0) {
20             /* only check for negative signs in the uncommon case when
21              * the unsigned number is so big that it's negative as a
22              * signed number. */
23             if (strchr(str, '-') != NULL) {
24                 return false;
25             }
26         }
27         *out = ull;
28         return true;
29     }
30     return false;
31 }
32 
33 bool safe_strtoll(const char *str, int64_t *out) {
34     assert(out != NULL);
35     errno = 0;
36     *out = 0;
37     char *endptr;
38     long long ll = strtoll(str, &endptr, 10);
39     if (errno == ERANGE)
40         return false;
41     if (isspace(*endptr) || (*endptr == '\0' && endptr != str)) {
42         *out = ll;
43         return true;
44     }
45     return false;
46 }
47 
48 bool safe_strtoul(const char *str, uint32_t *out) {
49     char *endptr = NULL;
50     unsigned long l = 0;
51     assert(out);
52     assert(str);
53     *out = 0;
54     errno = 0;
55 
56     l = strtoul(str, &endptr, 10);
57     if (errno == ERANGE) {
58         return false;
59     }
60 
61     if (isspace(*endptr) || (*endptr == '\0' && endptr != str)) {
62         if ((long) l < 0) {
63             /* only check for negative signs in the uncommon case when
64              * the unsigned number is so big that it's negative as a
65              * signed number. */
66             if (strchr(str, '-') != NULL) {
67                 return false;
68             }
69         }
70         *out = l;
71         return true;
72     }
73 
74     return false;
75 }
76 
77 bool safe_strtol(const char *str, int32_t *out) {
78     assert(out != NULL);
79     errno = 0;
80     *out = 0;
81     char *endptr;
82     long l = strtol(str, &endptr, 10);
83     if (errno == ERANGE)
84         return false;
85     if (isspace(*endptr) || (*endptr == '\0' && endptr != str)) {
86         *out = l;
87         return true;
88     }
89     return false;
90 }
91