ref: a61a1f51567f27ec605986354a28f8360abb1bda
parent: 5d669c823851eb8c74acba4b0e8673f8da02ae0a
author: Ori Bernstein <ori@eigenstate.org>
date: Thu Sep 8 18:04:43 EDT 2016
Add html escaping.
--- a/lib/escfmt/bld.sub
+++ b/lib/escfmt/bld.sub
@@ -1,6 +1,7 @@
lib escfmt =
escsh.myr
+ eschtml.myr
- lib ../std:std
- lib ../sys:sys
+ lib ../std:std
+ lib ../sys:sys
;;
--- /dev/null
+++ b/lib/escfmt/eschtml.myr
@@ -1,0 +1,31 @@
+use std
+
+pkg escfmt =
+ type eschtml = byte[:]
+
+ const html : (s : byte[:] -> eschtml)
+;;
+
+const __init__ = {
+ var s = ("" : eschtml)
+ std.fmtinstall(std.typeof(s), htmlfmt, [][:])
+}
+
+const html = {s
+ -> (s : eschtml)
+}
+
+const htmlfmt = {sb, ap, args
+ var s : byte[:]
+
+ s = std.vanext(ap)
+ for c in std.bychar(s)
+ match c
+ | '&': std.sbputs(sb, "&")
+ | '<': std.sbputs(sb, "<")
+ | '>': std.sbputs(sb, ">")
+ | '/': std.sbputs(sb, "/")
+ | _: std.sbputc(sb, c)
+ ;;
+ ;;
+}
--- /dev/null
+++ b/lib/escfmt/test/eschtml.myr
@@ -1,0 +1,29 @@
+use std
+use escfmt
+use testr
+
+const main = {
+ testr.run([\
+ [.name="nop", .fn={ctx
+ var s = std.fmt("{}", escfmt.html("word"))
+ testr.check(ctx, std.sleq("word", s), "mismatched escape")
+ std.slfree(s)
+ }],
+ [.name="twowords", .fn={ctx
+ var s = std.fmt("{}", escfmt.html("spaced word"))
+ testr.check(ctx, std.sleq("spaced word", s), "mismatched escape")
+ std.slfree(s)
+ }],
+ [.name="quoted", .fn={ctx
+ var s = std.fmt("{}", escfmt.html("<stuff> </stuff>"))
+ testr.check(ctx, std.sleq("<stuff>&nbsp;</stuff>", s), std.fmt("mismatched escape {}", s))
+ std.slfree(s)
+ }],
+ [.name="doublequoted", .fn={ctx
+ var s = std.fmt("{}", escfmt.html("<stuff>&nbsp;</stuff>"))
+ testr.check(ctx, std.sleq("&lt;stuff&gt;&amp;nbsp;&lt;&#x2f;stuff&gt;", s), std.fmt("mismatched escape {}", s))
+ std.slfree(s)
+ }],
+ ][:])
+}
+