| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
#include <ctype.h> |
| 27 |
#include <errno.h> |
| 28 |
#include <limits.h> |
| 29 |
#include <inttypes.h> |
| 30 |
#include <stdio.h> |
| 31 |
|
| 32 |
#include "asterisk/conversions.h" |
| 33 |
|
| 34 |
static int str_is_negative(const char **str) |
| 35 |
{ |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
while (isspace(**str)) ++*str; |
| 41 |
return **str == '-'; |
| 42 |
} |
| 43 |
|
| 44 |
int ast_str_to_int(const char *str, int *res) |
| 45 |
{ |
| 46 |
intmax_t val; |
| 47 |
|
| 48 |
if (ast_str_to_imax(str, &val) || val < INT_MIN || val > INT_MAX) { |
| 49 |
return -1; |
| 50 |
} |
| 51 |
|
| 52 |
*res = val; |
| 53 |
return 0; |
| 54 |
} |
| 55 |
|
| 56 |
int ast_str_to_uint(const char *str, unsigned int *res) |
| 57 |
{ |
| 58 |
uintmax_t val; |
| 59 |
|
| 60 |
if (ast_str_to_umax(str, &val) || val > UINT_MAX) { |
| 61 |
return -1; |
| 62 |
} |
| 63 |
|
| 64 |
*res = val; |
| 65 |
return 0; |
| 66 |
} |
| 67 |
|
| 68 |
int ast_str_to_long(const char *str, long *res) |
| 69 |
{ |
| 70 |
intmax_t val; |
| 71 |
|
| 72 |
if (ast_str_to_imax(str, &val) || val < LONG_MIN || val > LONG_MAX) { |
| 73 |
return -1; |
| 74 |
} |
| 75 |
|
| 76 |
*res = val; |
| 77 |
return 0; |
| 78 |
} |
| 79 |
|
| 80 |
int ast_str_to_ulong(const char *str, unsigned long *res) |
| 81 |
{ |
| 82 |
uintmax_t val; |
| 83 |
|
| 84 |
if (ast_str_to_umax(str, &val) || val > ULONG_MAX) { |
| 85 |
return -1; |
| 86 |
} |
| 87 |
|
| 88 |
*res = val; |
| 89 |
return 0; |
| 90 |
} |
| 91 |
|
| 92 |
int ast_str_to_imax(const char *str, intmax_t *res) |
| 93 |
{ |
| 94 |
char *end; |
| 95 |
intmax_t val; |
| 96 |
|
| 97 |
if (!str) { |
| 98 |
return -1; |
| 99 |
} |
| 100 |
|
| 101 |
errno = 0; |
| 102 |
val = strtoimax(str, &end, 10); |
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
if (str == end || *end != '\0' || (errno == ERANGE && |
| 111 |
(val == INTMAX_MIN || val == INTMAX_MAX))) { |
| 112 |
return -1; |
| 113 |
} |
| 114 |
|
| 115 |
*res = val; |
| 116 |
return 0; |
| 117 |
} |
| 118 |
|
| 119 |
int ast_str_to_umax(const char *str, uintmax_t *res) |
| 120 |
{ |
| 121 |
char *end; |
| 122 |
uintmax_t val; |
| 123 |
|
| 124 |
if (!str || str_is_negative(&str)) { |
| 125 |
return -1; |
| 126 |
} |
| 127 |
|
| 128 |
errno = 0; |
| 129 |
val = strtoumax(str, &end, 10); |
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
if ((str == end || *end != '\0' || (errno == ERANGE && val == UINTMAX_MAX))) { |
| 138 |
return -1; |
| 139 |
} |
| 140 |
|
| 141 |
*res = val; |
| 142 |
return 0; |
| 143 |
} |