code / tomo

Lines41.3K C23.7K Markdown9.7K YAML5.0K Tomo2.3K
7 others 763
Python231 Shell230 make212 INI47 Text21 SVG16 Lua6
(62 lines)
1 // Boolean methods/type info
2 #include <err.h>
3 #include <gc.h>
4 #include <stdbool.h>
5 #include <stdint.h>
6 #include <sys/param.h>
8 #include "bools.h"
9 #include "integers.h"
10 #include "optionals.h"
11 #include "text.h"
12 #include "util.h"
14 PUREFUNC public Text_t Bool$as_text(const void *b, bool colorize, const TypeInfo_t *info) {
15 (void)info;
16 if (!b) return Text("Bool");
17 if (colorize) return *(Bool_t *)b ? Text("\x1b[35myes\x1b[m") : Text("\x1b[35mno\x1b[m");
18 else return *(Bool_t *)b ? Text("yes") : Text("no");
21 static bool try_parse(Text_t text, Text_t target, bool target_value, Text_t *remainder, bool *result) {
22 static const Text_t lang = Text("C");
23 if (text.length < target.length) return false;
24 Text_t prefix = Text$to(text, Int$from_int64(target.length));
25 if (Text$equal_ignoring_case(prefix, target, lang)) {
26 if (remainder) *remainder = Text$from(text, Int$from_int64(target.length + 1));
27 else if (text.length > target.length) return false;
28 *result = target_value;
29 return true;
30 } else {
31 return false;
35 PUREFUNC public OptionalBool_t Bool$parse(Text_t text, Text_t *remainder) {
36 bool result;
37 if (try_parse(text, Text("yes"), true, remainder, &result)
38 || try_parse(text, Text("true"), true, remainder, &result)
39 || try_parse(text, Text("on"), true, remainder, &result) || try_parse(text, Text("1"), true, remainder, &result)
40 || try_parse(text, Text("no"), false, remainder, &result)
41 || try_parse(text, Text("false"), false, remainder, &result)
42 || try_parse(text, Text("off"), false, remainder, &result)
43 || try_parse(text, Text("0"), false, remainder, &result))
44 return result;
45 else return NONE_BOOL;
48 static bool Bool$is_none(const void *b, const TypeInfo_t *info) {
49 (void)info;
50 return *(OptionalBool_t *)b == NONE_BOOL;
53 public
54 const TypeInfo_t Bool$info = {
55 .size = sizeof(bool),
56 .align = __alignof__(bool),
57 .metamethods =
59 .as_text = Bool$as_text,
60 .is_none = Bool$is_none,
61 },
62 };