aboutsummaryrefslogtreecommitdiff
path: root/src/eval/html/Literal.zig
blob: a75b16c8566e37898960565189e6a89572a99214 (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
const std = @import("std");
const Allocator = std.mem.Allocator;
const html = @import("html.zig");
const Element = @import("Element.zig");
const Node = Element.Node;
const Error = Element.Error;

literal: []const u8,
node: Node = .{
    .ptr = undefined,
    .vtable = .{ .element = fromNode },
},

const Self = @This();

pub fn init(alloc: Allocator, literal: []const u8) Error!*Element.Literal {
    const v = try alloc.create(Self);
    v.* = .{ .literal = try html.escape(alloc, literal) };
    v.node.ptr = v;
    return v;
}

pub fn initNoEscape(alloc: Allocator, literal: []const u8) Error!*Element.Literal {
    const v = try alloc.create(Self);
    v.* = .{ .literal = try alloc.dupe(u8, literal) };
    v.node.ptr = v;
    return v;
}

pub fn element(self: *Self) Element {
    return .{ .vtable = .{ .render = render, .node = getNode }, .ptr = self };
}

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));
    return try alloc.dupe(u8, self.literal);
}