~ntgg/zosh

07f7aa4bd065a8c281d1c6ff4f07d62e25f006bf — Noah Graff 4 years ago 0ce3c9f
added initEmpty, changed peekChar to use peek.

initEmpty cannot fail. peekChar uses peek interally, as that is just
better design.
1 files changed, 16 insertions(+), 4 deletions(-)

M src/text_buffer.zig
M src/text_buffer.zig => src/text_buffer.zig +16 -4
@@ 20,6 20,18 @@ pub const TextBuffer = struct {
        column: usize,
    };

    pub fn initEmpty(allocator: *Allocator) TextBuffer {
        return TextBuffer{
            .bytes = [_]u8{},
            .pos = Pos{
                .offset = 0,
                .line = 1,
                .column = 1,
            },
            .allocator = allocator,
        };
    }

    pub fn init(allocator: *Allocator, text: []const u8) !TextBuffer {
        return TextBuffer{
            .bytes = try std.mem.dupe(allocator, u8, text),


@@ 59,10 71,9 @@ pub const TextBuffer = struct {

    /// Observe the next character.
    pub fn peekChar(buf: TextBuffer) ?u8 {
        if (buf.pos.offset < buf.bytes.len) {
            return buf.bytes[buf.pos.offset];
        }
        return null;
        const c = buf.peek(1);
        if (c.len < 1) return null;
        return c[0];
    }

    /// Returns a slice into the bytes of the TextBuffer with


@@ 111,6 122,7 @@ test "TextBuffer tests" {
    defer buffer.deinit();
    t.expectEqual(TextBuffer.Pos{ .offset = 0, .line = 1, .column = 1 }, buffer.pos);
    t.expectEqual(u8('e'), buffer.at(0));
    t.expectEqual(u8('i'), buffer.at(6));
    t.expectEqual(u8('e'), buffer.peekChar().?);
    t.expectEqual(u8('e'), buffer.peekChar().?);
    t.expectEqual(TextBuffer.Pos{ .offset = 0, .line = 1, .column = 1 }, buffer.pos);