2 * Copyright (c) 2022 Omar Polo <op@openbsd.org>
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
26 tp_write(struct template *tp, const char *str, size_t len)
31 avail = tp->tp_cap - tp->tp_len;
33 if (template_flush(tp) == -1)
41 memcpy(tp->tp_buf + tp->tp_len, str, avail);
51 tp_writes(struct template *tp, const char *str)
53 return (tp_write(tp, str, strlen(str)));
57 tp_writef(struct template *tp, const char *fmt, ...)
64 r = vasprintf(&str, fmt, ap);
68 r = tp_write(tp, str, r);
74 tp_urlescape(struct template *tp, const char *str)
83 if (iscntrl((unsigned char)*str) ||
84 isspace((unsigned char)*str) ||
85 *str == '\'' || *str == '"' || *str == '\\') {
86 r = snprintf(tmp, sizeof(tmp), "%%%2X", *str);
87 if (r < 0 || (size_t)r >= sizeof(tmp))
89 if (tp_write(tp, tmp, r) == -1)
92 if (tp_write(tp, str, 1) == -1)
101 htmlescape(struct template *tp, char c)
105 return tp_write(tp, "<", 4);
107 return tp_write(tp, ">", 4);
109 return tp_write(tp, "&", 5);
111 return tp_write(tp, """, 6);
113 return tp_write(tp, "'", 6);
115 return tp_write(tp, &c, 1);
120 tp_htmlescape(struct template *tp, const char *str)
125 for (; *str; ++str) {
126 if (htmlescape(tp, *str) == -1)
134 tp_write_htmlescape(struct template *tp, const char *str, size_t len)
138 for (i = 0; i < len; ++i) {
139 if (htmlescape(tp, str[i]) == -1)
147 template(void *arg, tmpl_write writefn, char *buf, size_t siz)
151 if ((tp = calloc(1, sizeof(*tp))) == NULL)
155 tp->tp_write = writefn;
163 template_flush(struct template *tp)
168 if (tp->tp_write(tp->tp_arg, tp->tp_buf, tp->tp_len) == -1)
175 template_free(struct template *tp)