Root/
Source at commit 2350 created 10 years 5 months ago. By ifabio, remove duplicated define. | |
---|---|
1 | /*␊ |
2 | * strntoumax.c␊ |
3 | *␊ |
4 | * The strntoumax() function and associated␊ |
5 | */␊ |
6 | #include "libsaio.h"␊ |
7 | ␊ |
8 | static inline int digitval(int ch)␊ |
9 | {␊ |
10 | ␉if (ch >= '0' && ch <= '9') {␊ |
11 | ␉␉return ch - '0';␊ |
12 | ␉} else if (ch >= 'A' && ch <= 'Z') {␊ |
13 | ␉␉return ch - 'A' + 10;␊ |
14 | ␉} else if (ch >= 'a' && ch <= 'z') {␊ |
15 | ␉␉return ch - 'a' + 10;␊ |
16 | ␉} else {␊ |
17 | ␉␉return -1;␊ |
18 | ␉}␊ |
19 | }␊ |
20 | ␊ |
21 | uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n)␊ |
22 | {␊ |
23 | ␉int minus = 0;␊ |
24 | ␉uintmax_t v = 0;␊ |
25 | ␉int d;␊ |
26 | ␊ |
27 | ␉while (n && isspace((unsigned char)*nptr)) {␊ |
28 | ␉␉nptr++;␊ |
29 | ␉␉n--;␊ |
30 | ␉}␊ |
31 | ␊ |
32 | ␉/* Single optional + or - */␊ |
33 | ␉if (n) {␊ |
34 | ␉␉char c = *nptr;␊ |
35 | ␉␉if (c == '-' || c == '+') {␊ |
36 | ␉␉␉minus = (c == '-');␊ |
37 | ␉␉␉nptr++;␊ |
38 | ␉␉␉n--;␊ |
39 | ␉␉}␊ |
40 | ␉}␊ |
41 | ␊ |
42 | ␉if (base == 0) {␊ |
43 | ␉␉if (n >= 2 && nptr[0] == '0' &&␊ |
44 | ␉␉ (nptr[1] == 'x' || nptr[1] == 'X')) {␊ |
45 | ␉␉␉n -= 2;␊ |
46 | ␉␉␉nptr += 2;␊ |
47 | ␉␉␉base = 16;␊ |
48 | ␉␉} else if (n >= 1 && nptr[0] == '0') {␊ |
49 | ␉␉␉n--;␊ |
50 | ␉␉␉nptr++;␊ |
51 | ␉␉␉base = 8;␊ |
52 | ␉␉} else {␊ |
53 | ␉␉␉base = 10;␊ |
54 | ␉␉}␊ |
55 | ␉} else if (base == 16) {␊ |
56 | ␉␉if (n >= 2 && nptr[0] == '0' &&␊ |
57 | ␉␉ (nptr[1] == 'x' || nptr[1] == 'X')) {␊ |
58 | ␉␉␉n -= 2;␊ |
59 | ␉␉␉nptr += 2;␊ |
60 | ␉␉}␊ |
61 | ␉}␊ |
62 | ␊ |
63 | ␉while (n && (d = digitval(*nptr)) >= 0 && d < base) {␊ |
64 | ␉␉v = v * base + d;␊ |
65 | ␉␉n--;␊ |
66 | ␉␉nptr++;␊ |
67 | ␉}␊ |
68 | ␊ |
69 | ␉if (endptr)␊ |
70 | ␉␉*endptr = (char *)nptr;␊ |
71 | ␊ |
72 | ␉return minus ? -v : v;␊ |
73 | }␊ |
74 |