summaryrefslogtreecommitdiff
path: root/src/str.c
blob: c955d513753b269886e0dbf5913ba737d2a4f6e7 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "../include/al/str.h"

// https://sourceware.org/git/?p=newlib-cygwin.git;a=blob;f=newlib/libc/stdlib/strtol.c;h=09d4333ed05f497ec00b7192204644349441e58d;hb=HEAD#l130
s64 al_str_to_long(str *s, s32 base)
{
    u64 ret = 0;
    u32 i = 0;
    s32 neg = 0;

    while (al_isspace(al_str_at(s, i)) && i < s->len) {
        i++;
    }

    if (al_str_at(s, i) == '-') {
        neg = 1;
        i++;
    } else if (al_str_at(s, i) == '+') {
        i++;
    }

    if (al_str_at(s, i) == '0' &&
        ((base == 16 && (al_str_at(s, i + 1) == 'x' || al_str_at(s, i + 1) == 'X')) ||
         (base == 2  && (al_str_at(s, i + 1) == 'b' || al_str_at(s, i + 1) == 'B')))) {
        i += 2;
    }

    u64 cutoff = neg ? -(u64)INT64_MIN : INT64_MAX;
    s32 add_limit = cutoff % (u64)base;
    cutoff /= (u64)base;

    bool error = false;

    for (; i < s->len; i++) {
        char c = al_str_at(s, i);

        if (c >= '0' && c <= '9') c -= '0';
        else if (c >= 'A' && c <= 'Z') c -= 'A' - 10;
        else if (c >= 'a' && c <= 'z') c -= 'a' - 10;
        else {
            // Character not valid for expressing a number.
            error = true;
            break;
        }

        if (c >= base || ret > cutoff || (ret == cutoff && c > add_limit)) {
            // Either the character is invalid for the requested base or
            // attempting to add it would cause an overflow.
            error = true;
            break;
        }

        ret = ret * base + c;
    }

    if (error) {
        ret = neg ? INT64_MIN : INT64_MAX;
    } else if (neg) {
        ret = -ret;
    }

    return ret;
}

bool al_str_get_line(str *buffer, char sep, str *line)
{
    u32 bytes = 0;

    // line must be zero'd before calling get_line() for the first time.
    if (line->data == NULL) {
        *line = *buffer;
    } else {
        // Move to the start of the next line, if it exists.
        line->data += line->len + 1;
        if ((bytes = line->data - buffer->data) >= buffer->len)
            return false; // No more lines.
    }

    bytes = buffer->len - bytes;

    char *nl = (char *)al_memchr(line->data, sep, bytes);

    // If we couldn't find a separator, move to the end of the buffer.
    line->len = !nl ? bytes : (u32)(nl - line->data);

    return true;
}