summaryrefslogtreecommitdiff
path: root/src/lib/parser.zig
blob: f0cc8d9ccb9ab85b7a71d4517ae2fe24268af040 (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
const std = @import("std");

pub const ParserError = error{ Unexpected, EndOfString };

str: []const u8,
pos: u32 = 0,

const Self = @This();

pub fn peek(self: Self) ?u8 {
    if (self.pos >= self.str.len) return null;
    return self.str[self.pos];
}

pub fn consume(self: *Self, c: u8) ParserError!void {
    if (self.peek()) |pk| {
        if (pk == c) {
            self.pos += 1;
            return;
        }
        return ParserError.Unexpected;
    }
    return ParserError.EndOfString;
}

pub fn skip(self: *Self) void {
    self.pos += 1;
}

pub fn skipMany(self: *Self, n: usize) void {
    for (0..n) |_|
        self.skip();
}

pub fn takeUntil(self: *Self, c: u8) ParserError![]const u8 {
    const i = self.pos;
    while (self.peek() != null and self.peek().? != c) self.skip();
    self.skip();
    return self.str[i .. self.pos - 1];
}