summaryrefslogtreecommitdiff
path: root/userland/libc/stdlib/strtol.c
blob: 7aa776044e3f16d1f6fd09c730df742bd37efcb9 (plain)
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <assert.h>

extern int errno;
extern int get_value(char c, long base);

// https://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
long strtol(const char *str, char **restrict endptr, int base) {
  long ret_value = 0;
  if (endptr)
    *endptr = str;
  // Ignore inital white-space sequence
  for (; *str && isspace(*str); str++)
    ;
  if (!*str)
    return ret_value;

  int sign = 0;
  if ('-' == *str) {
    // FIXME
    sign = 1;
    str++;
    assert(0);
  } else if ('+' == *str) {
    str++;
  }

  if (0 == base) {
    // FIXME
    assert(0);
  }

  if (2 <= base && 36 >= base) {
    for (; *str; str++) {
      ret_value *= base;
      int val = get_value(*str, base);
      if (ret_value > LONG_MAX - val) {
        errno = ERANGE;
        return 0;
      }
      ret_value += val;
    }
  } else {
    errno = EINVAL;
    return 0;
  }
  if (endptr)
    *endptr = str;
  return ret_value;
}