Debian Codegraph @

format/ini/scan.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use bufio;
5 use io;
6 use strings;
7
8 export type scanner = struct {
9 scan: bufio::scanner,
10 lineno: size,
11 section: str,
12 };
13
14 // Creates an INI file scanner. The supplied handle need not be buffered, since
15 // the returned [[scanner]] manages its own internal [[bufio::scanner]]. Use
16 // [[next]] to read entries. The caller must call [[finish]] once they're done
17 // with the INI scanner.
18 export fn scan(in: io::handle) scanner = {
19 return scanner {
20 scan = bufio::newscanner(in),
21 lineno = 1,
22 ...
23 };
24 };
25
26 // Frees resources associated with a [[scanner]].
27 export fn finish(sc: *scanner) void = {
28 bufio::finish(&sc.scan);
29 free(sc.section);
30 };
31
32 // An entry in an INI file: (section, key, value).
33 export type entry = (const str, const str, const str);
34
35 // Duplicates an [[entry]]. Use [[entry_finish]] to free it.
36 export fn entry_dup(ent: entry) (entry | nomem) = {
37 let dup: entry = ("", "", "");
38 let ok = false;
39 defer if (!ok) entry_finish(dup);
40 dup.0 = strings::dup(ent.0)?;
41 dup.1 = strings::dup(ent.1)?;
42 dup.2 = strings::dup(ent.2)?;
43 ok = true;
44 return dup;
45 };
46
47 // Frees an [[entry]] previously duplicated with [[entry_dup]].
48 export fn entry_finish(ent: entry) void = {
49 free(ent.0);
50 free(ent.1);
51 free(ent.2);
52 };
53
54 // Returns the next entry from an INI file. The return value is borrowed from
55 // the [[scanner]]. Use [[entry_dup]] to retain a copy.
56 export fn next(sc: *scanner) (entry | io::EOF | error | nomem) = {
57 for (const line => bufio::scan_line(&sc.scan)?) {
58 defer sc.lineno += 1;
59
60 const line = strings::trim(line);
61 if (len(line) == 0 || strings::hasprefix(line, "#")) {
62 continue;
63 };
64
65 if (strings::hasprefix(line, "[")) {
66 const end = match (strings::index(line, ']')) {
67 case let idx: size =>
68 yield idx;
69 case void =>
70 return sc.lineno: syntaxerr;
71 };
72 match (strings::dup(strings::sub(line, 1, end))) {
73 case let s: str =>
74 free(sc.section);
75 sc.section = s;
76 case nomem =>
77 // XXX maybe add a bufio::unread_line?
78 bufio::unread(&sc.scan, ['\n': u8]);
79 bufio::unread(&sc.scan, strings::toutf8(line));
80 sc.lineno -= 1;
81 return nomem;
82 };
83 continue;
84 };
85
86 const eq = match (strings::index(line, '=')) {
87 case let idx: size =>
88 yield idx;
89 case void =>
90 return sc.lineno: syntaxerr;
91 };
92 return (
93 sc.section,
94 strings::sub(line, 0, eq),
95 strings::sub(line, eq + 1, strings::end),
96 );
97 };
98
99 return io::EOF;
100 };