-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.zig
197 lines (162 loc) · 6.12 KB
/
main.zig
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
const std = @import("std");
const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator;
const mustache = @import("mustache");
// Mustache template
const template_text =
\\{{! This is a spec-compliant mustache template }}
\\Hello {{name}} from Zig
\\This template was generated with
\\{{#env}}
\\Zig: {{zig_version}}
\\Mustache: {{mustache_version}}
\\{{/env}}
\\Supported features:
\\{{#features}}
\\ - {{name}} {{condition}}
\\{{/features}}
;
const Feature = struct {
name: []const u8,
condition: []const u8,
};
// Context, can be any Zig struct, supporting optionals, slices, tuples, recursive types, pointers, etc.
var ctx = .{
.name = "friends",
.env = .{
.zig_version = "master",
.mustache_version = "alpha",
},
.features = &[_]Feature{
.{ .name = "interpolation", .condition = "✅ done" },
.{ .name = "sections", .condition = "✅ done" },
.{ .name = "comments", .condition = "✅ done" },
.{ .name = "delimiters", .condition = "✅ done" },
.{ .name = "partials", .condition = "✅ done" },
.{ .name = "lambdas", .condition = "✅ done" },
.{ .name = "inheritance", .condition = "⏳ comming soon" },
},
};
pub fn main() anyerror!void {
try renderFromString();
try renderFromJson();
//try renderComptimeTemplate();
try renderFromCachedTemplate();
try renderFromFile();
//try renderComptimePartialTemplate();
}
/// Render a template from a string
pub fn renderFromString() anyerror!void {
var gpa = GeneralPurposeAllocator(.{}){};
defer {
if (gpa.detectLeaks()) @panic("renderFromString leaked");
_ = gpa.deinit();
}
const allocator = gpa.allocator();
var out = std.io.getStdOut();
// Direct render to save memory
try mustache.renderText(allocator, template_text, ctx, out.writer());
}
/// Render a template from a Json object
pub fn renderFromJson() anyerror!void {
var gpa = GeneralPurposeAllocator(.{}){};
defer {
if (gpa.detectLeaks()) @panic("renderFromJson leaked");
_ = gpa.deinit();
}
const allocator = gpa.allocator();
var out = std.io.getStdOut();
// Serializing the context as a json string
const json_text = try std.json.stringifyAlloc(allocator, ctx, .{});
defer allocator.free(json_text);
var tree = try std.json.parseFromSlice(std.json.Value, allocator, json_text, .{});
defer tree.deinit();
// Rendering from a Json object
try mustache.renderText(allocator, template_text, tree.value, out.writer());
}
/// Parses a template at comptime to render many times at runtime, no allocations needed
pub fn renderComptimeTemplate() anyerror!void {
var out = std.io.getStdOut();
// Comptime-parsed template
const comptime_template = comptime mustache.parseComptime(template_text, .{}, .{});
var repeat: u32 = 0;
while (repeat < 10) : (repeat += 1) {
try mustache.render(comptime_template, ctx, out.writer());
}
}
/// Caches a template to render many times
pub fn renderFromCachedTemplate() anyerror!void {
var gpa = GeneralPurposeAllocator(.{}){};
defer {
if (gpa.detectLeaks()) @panic("renderFromCachedTemplate leaked");
_ = gpa.deinit();
}
const allocator = gpa.allocator();
// Store this template and render many times from it
const cached_template = switch (try mustache.parseText(allocator, template_text, .{}, .{ .copy_strings = false })) {
.success => |ret| ret,
.parse_error => |detail| {
std.log.err("Parse error {s} at lin {}, col {}", .{ @errorName(detail.parse_error), detail.lin, detail.col });
return;
},
};
defer cached_template.deinit(allocator);
var repeat: u32 = 0;
while (repeat < 10) : (repeat += 1) {
const result = try mustache.allocRender(allocator, cached_template, ctx);
defer allocator.free(result);
var out = std.io.getStdOut();
try out.writeAll(result);
}
}
/// Render a template from a file path
pub fn renderFromFile() anyerror!void {
// 16KB should be enough memory for this job
var plenty_of_memory = std.heap.GeneralPurposeAllocator(.{ .enable_memory_limit = true }){
.requested_memory_limit = 16 * 1024,
};
defer _ = plenty_of_memory.deinit();
const allocator = plenty_of_memory.allocator();
const path = try std.fs.selfExeDirPathAlloc(allocator);
defer allocator.free(path);
// Creating a temp file
const path_to_template = try std.fs.path.join(allocator, &.{ path, "template.mustache" });
defer allocator.free(path_to_template);
defer std.fs.deleteFileAbsolute(path_to_template) catch {};
{
var file = try std.fs.createFileAbsolute(path_to_template, .{ .truncate = true });
defer file.close();
var repeat: u32 = 0;
// Writing the same template 10K times on a file
while (repeat < 10_000) : (repeat += 1) {
try file.writeAll(template_text);
}
}
var out = std.io.getStdOut();
// Rendering this large template with only 16KB of RAM
try mustache.renderFile(allocator, path_to_template, ctx, out.writer());
}
/// Parses a template at comptime to render many times at runtime, no allocations needed
pub fn renderComptimePartialTemplate() anyerror!void {
var out = std.io.getStdOut();
// Comptime-parsed template
const comptime_template = comptime mustache.parseComptime(
\\{{=[ ]=}}
\\📜 hello [>partial], your lucky number is [sub_value.value]
\\--------------------------------------
\\
, .{}, .{});
// Comptime tuple with a comptime partial template
const comptime_partials = .{ "partial", comptime mustache.parseComptime("from {{name}}", .{}, .{}) };
const Data = struct {
name: []const u8,
sub_value: struct {
value: u32,
},
};
// Runtime value
const data: Data = .{ .name = "mustache", .sub_value = .{ .value = 42 } };
var repeat: u32 = 0;
while (repeat < 10) : (repeat += 1) {
try mustache.renderPartials(comptime_template, comptime_partials, data, out.writer());
}
}