Make string_to_uint_ex more universal

And add support for reading of various types.

* string_to_uint.c (string_to_uint_ex): Change to work with long long.
(string_to_uint): Move it...
* string_to_uint.h (string_to_uint): ...here.
(string_to_uint_upto): Accept long long as max_val, return long long.
(string_to_ulong, string_to_kulong, string_to_ulonglong): New functions,
for completeness.

Co-Authored-by: Dmitry V. Levin <ldv@altlinux.org>
This commit is contained in:
Eugene Syromyatnikov 2018-02-01 12:31:21 +01:00 committed by Dmitry V. Levin
parent eb45473d7f
commit 83454d741f
2 changed files with 39 additions and 20 deletions

View File

@ -30,27 +30,27 @@
#endif
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include "string_to_uint.h"
int
long long
string_to_uint_ex(const char *const str, char **const endptr,
const unsigned int max_val, const char *const accepted_ending)
const unsigned long long max_val,
const char *const accepted_ending)
{
char *end;
long val;
long long val;
if (!*str)
return -1;
errno = 0;
val = strtol(str, &end, 10);
val = strtoll(str, &end, 10);
if (str == end || val < 0 || (unsigned long) val > max_val
|| (val == LONG_MAX && errno == ERANGE))
if (str == end || val < 0 || (unsigned long long) val > max_val
|| (val == LLONG_MAX && errno == ERANGE))
return -1;
if (*end && (!accepted_ending || !strchr(accepted_ending, *end)))
@ -59,11 +59,5 @@ string_to_uint_ex(const char *const str, char **const endptr,
if (endptr)
*endptr = end;
return (int) val;
}
int
string_to_uint(const char *const str)
{
return string_to_uint_upto(str, INT_MAX);
return val;
}

View File

@ -28,17 +28,42 @@
#ifndef STRACE_STRING_TO_UINT_H
#define STRACE_STRING_TO_UINT_H
extern int
string_to_uint(const char *str);
#include <limits.h>
extern int
#include "kernel_types.h"
extern long long
string_to_uint_ex(const char *str, char **endptr,
unsigned int max_val, const char *accepted_ending);
unsigned long long max_val, const char *accepted_ending);
static inline int
string_to_uint_upto(const char *const str, const unsigned int max_val)
static inline long long
string_to_uint_upto(const char *const str, const unsigned long long max_val)
{
return string_to_uint_ex(str, NULL, max_val, NULL);
}
static inline int
string_to_uint(const char *str)
{
return string_to_uint_upto(str, INT_MAX);
}
static inline long
string_to_ulong(const char *str)
{
return string_to_uint_upto(str, LONG_MAX);
}
static inline kernel_long_t
string_to_kulong(const char *str)
{
return string_to_uint_upto(str, ((kernel_ulong_t) -1ULL) >> 1);
}
static inline long long
string_to_ulonglong(const char *str)
{
return string_to_uint_upto(str, LLONG_MAX);
}
#endif /* !STRACE_STRING_TO_UINT_H */