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.
23 #include "got_compat.h"
27 tp_write(struct template *tp, const char *str, size_t len)
32 avail = tp->tp_cap - tp->tp_len;
34 if (template_flush(tp) == -1)
42 memcpy(tp->tp_buf + tp->tp_len, str, avail);
52 tp_writes(struct template *tp, const char *str)
54 return (tp_write(tp, str, strlen(str)));
58 tp_writef(struct template *tp, const char *fmt, ...)
65 r = vasprintf(&str, fmt, ap);
69 r = tp_write(tp, str, r);
75 tp_urlescape(struct template *tp, const char *str)
84 if (iscntrl((unsigned char)*str) ||
85 isspace((unsigned char)*str) ||
86 *str == '\'' || *str == '"' || *str == '\\') {
87 r = snprintf(tmp, sizeof(tmp), "%%%2X", *str);
88 if (r < 0 || (size_t)r >= sizeof(tmp))
90 if (tp_write(tp, tmp, r) == -1)
93 if (tp_write(tp, str, 1) == -1)
102 htmlescape(struct template *tp, char c)
106 return tp_write(tp, "<", 4);
108 return tp_write(tp, ">", 4);
110 return tp_write(tp, "&", 5);
112 return tp_write(tp, """, 6);
114 return tp_write(tp, "'", 6);
116 return tp_write(tp, &c, 1);
121 tp_htmlescape(struct template *tp, const char *str)
126 for (; *str; ++str) {
127 if (htmlescape(tp, *str) == -1)
135 tp_write_htmlescape(struct template *tp, const char *str, size_t len)
139 for (i = 0; i < len; ++i) {
140 if (htmlescape(tp, str[i]) == -1)
148 template(void *arg, tmpl_write writefn, char *buf, size_t siz)
152 if ((tp = calloc(1, sizeof(*tp))) == NULL)
156 tp->tp_write = writefn;
164 template_flush(struct template *tp)
169 if (tp->tp_write(tp->tp_arg, tp->tp_buf, tp->tp_len) == -1)
176 template_free(struct template *tp)