aboutsummaryrefslogtreecommitdiff
path: root/src/stdlib/bools.c
blob: fd66957924e21475cd76887240ee074e95ca63d1 (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
// Boolean methods/type info
#include <ctype.h>
#include <err.h>
#include <gc.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/param.h>

#include "bools.h"
#include "optionals.h"
#include "text.h"
#include "util.h"

PUREFUNC public Text_t Boolヽas_text(const void *b, bool colorize, const TypeInfo_t *info)
{
    (void)info;
    if (!b) return Text("Bool");
    if (colorize)
        return *(Bool_t*)b ? Text("\x1b[35myes\x1b[m") : Text("\x1b[35mno\x1b[m");
    else
        return *(Bool_t*)b ? Text("yes") : Text("no");
}

static bool try_parse(Text_t text, Text_t target, bool target_value, Text_t *remainder, bool *result)
{
    static const Text_t lang = Text("C");
    if (text.length < target.length) return false;
    Text_t prefix = Textヽto(text, Intヽfrom_int64(target.length));
    if (Textヽequal_ignoring_case(prefix, target, lang)) {
        if (remainder) *remainder = Textヽfrom(text, Intヽfrom_int64(target.length + 1));
        else if (text.length > target.length) return false;
        *result = target_value;
        return true;
    } else {
        return false;
    }
}

PUREFUNC public OptionalBool_t Boolヽparse(Text_t text, Text_t *remainder)
{
    bool result;
    if (try_parse(text, Text("yes"), true, remainder, &result)
        || try_parse(text, Text("true"), true, remainder, &result)
        || try_parse(text, Text("on"), true, remainder, &result)
        || try_parse(text, Text("1"), true, remainder, &result)
        || try_parse(text, Text("no"), false, remainder, &result)
        || try_parse(text, Text("false"), false, remainder, &result)
        || try_parse(text, Text("off"), false, remainder, &result)
        || try_parse(text, Text("0"), false, remainder, &result))
        return result;
    else
        return NONE_BOOL;
}

static bool Boolヽis_none(const void *b, const TypeInfo_t *info)
{
    (void)info;
    return *(OptionalBool_t*)b == NONE_BOOL;
}

public const TypeInfo_t Boolヽinfo = {
    .size=sizeof(bool),
    .align=__alignof__(bool),
    .metamethods={
        .as_text=Boolヽas_text,
        .is_none=Boolヽis_none,
    },
};

// vim: ts=4 sw=0 et cino=L2,l1,(0,W4,m1,\:0