]> git.ipfire.org Git - thirdparty/bird.git/blame - lib/strtoul.c
Merge remote-tracking branch 'origin/master' into mq-filter-stack
[thirdparty/bird.git] / lib / strtoul.c
CommitLineData
2915e711
MM
1/*
2 * BIRD Library -- Parse numbers
3 *
4 * (c) 2019 Maria Matejka <mq@jmq.cz>
5 *
6 * Can be freely distributed and used under the terms of the GNU GPL.
7 */
8
9#include "nest/bird.h"
10#include "lib/string.h"
11
12#include <errno.h>
13
14#define ULI_MAX_DIV10 (UINT64_MAX / 10)
15#define ULI_MAX_MOD10 (UINT64_MAX % 10)
16
17u64
18bstrtoul10(const char *str, char **end)
19{
20 u64 out = 0;
21 for (*end = (char *) str; (**end >= '0') && (**end <= '9'); (*end)++) {
22 u64 digit = **end - '0';
23 if ((out > ULI_MAX_DIV10) ||
24 (out == ULI_MAX_DIV10) && (digit > ULI_MAX_MOD10)) {
25 errno = ERANGE;
26 return UINT64_MAX;
27 }
28
29 out *= 10;
30 out += (**end) - '0';
31 }
32 return out;
33}
34
35u64
36bstrtoul16(const char *str, char **end)
37{
38 u64 out = 0;
39 for (int i=0; i<=(64/4); i++) {
40 switch (str[i]) {
41 case '0' ... '9':
42 out *= 16;
43 out += str[i] - '0';
44 break;
45 case 'a' ... 'f':
46 out *= 16;
47 out += str[i] + 10 - 'a';
48 break;
49 case 'A' ... 'F':
50 out *= 16;
51 out += str[i] + 10 - 'A';
52 break;
53 default:
54 *end = (char *) &(str[i]);
55 return out;
56 }
57 }
58
59 errno = ERANGE;
60 return UINT64_MAX;
61}