summaryrefslogtreecommitdiff
path: root/src/str.c
blob: e8e417dbd09d66ec657165b4913570c60471f472 (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
#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 ((base == 16 && al_str_at(s, i) == '0' && // 0xbecd
          (al_str_at(s, i + 1) == 'x' || al_str_at(s, i + 1) == 'X')) ||
        (base == 2 && al_str_at(s, i) == '0' && // 0b01011101
          (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 when expressing a number.
            error = true;
            break;
        }

        // Character invalid for given base or trying to add the next digit
        // would cause an overflow/underflow.
        if (c >= base || ret > cutoff || (ret == cutoff && c > add_limit)) {
            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;

    if (line->data == NULL) {
        *line = *buffer;
    } else if ((bytes = (u32)((line->data += line->len + 1) - buffer->data)) >= buffer->len) {
        // Move to the start of the assumed next line. If bytes >= buffer->len,
        // there is no next line.
        return false;
    }

    // Remaining bytes.
    bytes = buffer->len - bytes;

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

    // If !nl, move to the end of the buffer.
    line->len = !nl ? bytes : (u32)(nl - line->data);

    return true;
}