aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/lexer/Lexer.zig7
-rw-r--r--src/parser.zig16
-rw-r--r--src/root.zig9
3 files changed, 29 insertions, 3 deletions
diff --git a/src/lexer/Lexer.zig b/src/lexer/Lexer.zig
index 318e422..8b3893d 100644
--- a/src/lexer/Lexer.zig
+++ b/src/lexer/Lexer.zig
@@ -18,6 +18,13 @@ pub fn init(content: []const u8) error{InvalidUtf8}!Self {
return .{ .iter = view.iterator() };
}
+// Must free bytes in iter.
+pub fn initReader(alloc: Allocator, r: *std.io.Reader) !Self {
+ var acc = try std.ArrayList(u8).initCapacity(alloc, 2);
+ try r.appendRemainingUnlimited(alloc, &acc);
+ return init(try acc.toOwnedSlice(alloc));
+}
+
pub fn nextKind(self: *Self) ?Lexed.Kind {
const next_rune = self.iter.peek(1);
if (next_rune.len == 0) return null;
diff --git a/src/parser.zig b/src/parser.zig
index 775dc4a..85a757d 100644
--- a/src/parser.zig
+++ b/src/parser.zig
@@ -11,20 +11,30 @@ pub const Error = error{
FeatureNotSupported,
} || Lexer.Error || paragraph.Error || title.Error || link.Error;
+pub fn parseReader(parent: Allocator, r: *std.io.Reader) ![]const u8 {
+ var l = try Lexer.initReader(parent, r);
+ defer parent.free(l.iter.bytes);
+ return gen(parent, &l);
+}
+
pub fn parse(parent: Allocator, content: []const u8) Error![]const u8 {
+ var l = try Lexer.init(content);
+ return gen(parent, &l);
+}
+
+fn gen(parent: Allocator, l: *Lexer) Error![]const u8 {
var arena = std.heap.ArenaAllocator.init(parent);
defer arena.deinit();
const alloc = arena.allocator();
var elements = try std.ArrayList(Element).initCapacity(alloc, 2);
- var l = try Lexer.init(content);
base: while (l.nextKind()) |it| {
try elements.append(alloc, switch (it) {
// block paragraph
- .literal, .bold, .italic, .code, .link => try paragraph.parse(alloc, &l),
+ .literal, .bold, .italic, .code, .link => try paragraph.parse(alloc, l),
// other blocks
- .title => try title.parse(alloc, &l),
+ .title => try title.parse(alloc, l),
.weak_delimiter, .strong_delimiter => {
var v = (try l.next(alloc)).?;
v.deinit();
diff --git a/src/root.zig b/src/root.zig
index 4750814..956f584 100644
--- a/src/root.zig
+++ b/src/root.zig
@@ -56,6 +56,15 @@ pub fn zigParse(alloc: std.mem.Allocator, content: []const u8) Error![]const u8
return parser.parse(alloc, content);
}
+pub fn zigParseReader(alloc: std.mem.Allocator, r: *std.io.Reader) ![]const u8 {
+ return parser.parseReader(alloc, r);
+}
+
+pub fn zigParseFile(alloc: std.mem.Allocator, path: []const u8) ![]const u8 {
+ const file = try std.fs.cwd().readFileAlloc(alloc, path, std.math.maxInt(usize));
+ return zigParse(alloc, file);
+}
+
test {
std.testing.refAllDeclsRecursive(@This());
}