shithub: scc

Download patch

ref: 0922923b6268490b89a24c1b4cc7316a34daea16
parent: 272bc8e3488ce5c7220ebf7cc731a04211b6dba4
author: Quentin Rameau <quinq@fifth.space>
date: Sun Dec 23 12:41:39 EST 2018

[libc] Add strtoul

--- a/src/libc/stdlib/Makefile
+++ b/src/libc/stdlib/Makefile
@@ -19,6 +19,7 @@
        qsort.o\
        rand.o\
        realloc.o\
+       strtoul.o\
        strtoull.o\
 
 all: $(OBJS)
--- /dev/null
+++ b/src/libc/stdlib/strtoul.c
@@ -1,0 +1,64 @@
+#include <ctype.h>
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+
+#undef strtoul
+
+unsigned long
+strtoul(const char *s, char **end, int base)
+{
+	int d, sign = 1;
+	unsigned long n;
+	static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+	const char *t, *p;
+
+	while (isspace(*s))
+		++s;
+
+	switch (*s) {
+	case '-':
+		sign = -1;
+	case '+':
+		++s;
+	}
+
+	if (base == 0) {
+		if (*s == '0' && toupper(s[1]) == 'X')
+			base = 16;
+		else if (*s == '0')
+			base = 8;
+		else
+			base = 10;
+	}
+
+	if (base == 16 && *s == '0' && toupper(s[1]) == 'X')
+		s += 2;
+
+	n = 0;
+	for (t = s; p = strchr(digits, toupper(*t)); ++t) {
+		if ((d = p - digits) >= base)
+			break;
+		if (n > ULONG_MAX/base)
+			goto overflow;
+		n *= base;
+		if (d > ULONG_MAX - n)
+			goto overflow;
+		n += d;
+	}
+
+
+	if (end)
+		*end = t;
+	if (n == 0 && s == t)
+		errno = EINVAL;
+	return n*sign;
+
+overflow:
+	if (end)
+		*end = t;
+	errno = ERANGE;
+
+	return ULONG_MAX;
+}