blob: 440667aa3ddee94dca01e79c677876b812ccc0f9 (
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const Arena = std.heap.ArenaAllocator;
const Element = @import("Element.zig");
const Node = Element.Node;
const Error = Element.Error;
content: std.DoublyLinkedList = .{},
arena: Arena,
node: Node = .{
.ptr = undefined,
.vtable = .{ .element = fromNode },
},
const Self = @This();
pub fn init(parent: Allocator) Error!*Self {
var s = Self{ .arena = .init(parent) };
var alloc = s.arena.allocator();
const v = try alloc.create(Self);
v.* = s;
v.node.ptr = v;
return v;
}
pub fn deinit(self: *Self) void {
self.arena.deinit();
}
pub fn element(self: *Self) Element {
return .{ .vtable = .{
.render = render,
.node = getNode,
}, .ptr = self };
}
pub fn allocator(self: *Self) Allocator {
return self.arena.allocator();
}
pub fn append(self: *Self, el: Element) void {
self.content.append(&el.node().node);
}
fn getNode(context: *anyopaque) *Node {
const self: *Self = @ptrCast(@alignCast(context));
return &self.node;
}
fn fromNode(context: *anyopaque) Element {
const self: *Self = @ptrCast(@alignCast(context));
return self.element();
}
fn render(context: *anyopaque, alloc: Allocator) Error![]const u8 {
const self: *Self = @ptrCast(@alignCast(context));
if (self.content.first == null) return "";
var acc = try std.ArrayList(u8).initCapacity(alloc, 8);
errdefer acc.deinit(alloc);
var arena = Arena.init(alloc);
defer arena.deinit();
var v = self.content.first;
while (v) |it| : (v = it.next) try acc.appendSlice(alloc, try Node.from(it).element().render(arena.allocator()));
return acc.toOwnedSlice(alloc);
}
|