#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include <assert.h>
/* Convert string to integer
*
* Parses a base-10 number from the given string. Checks that the
* string is not blank, contains only numerical characters, and is
* within the range of INT32_MIN to INT32_MAX. If the validation is
* successful the result is stored in *value; otherwise *value is
* unchanged and errno is set appropriately.
*
* \return true if the number parsed successfully, false on error
*/
static inline bool
safe_strtoint(const char *str, int32_t *value)
{
long ret;
char *end;
assert(str != NULL);
errno = 0;
ret = strtol(str, &end, 10);
if (errno != 0) {
return false;
} else if (end == str || *end != '\0') {
errno = EINVAL;
return false;
}
if ((long)((int32_t)ret) != ret) {
errno = ERANGE;
return false;
}
*value = (int32_t)ret;
return true;
}
safe convert string to integer function
最新推荐文章于 2022-03-03 18:14:19 发布