2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
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.
18 * A streaming text/plain "parser."
21 #include "telescope.h"
26 static int textplain_parse(struct parser*, const char*, size_t);
27 static int textplain_free(struct parser*);
30 emit_line(struct parser *p, enum line_type type, const char *line, size_t len)
34 if ((l = calloc(1, sizeof(*l))) == NULL)
40 if ((l->line = calloc(1, len+1)) == NULL) {
45 memcpy(l->line, line, len);
48 if (TAILQ_EMPTY(&p->head))
49 TAILQ_INSERT_HEAD(&p->head, l, lines);
51 TAILQ_INSERT_TAIL(&p->head, l, lines);
57 textplain_initparser(struct parser *p)
59 memset(p, 0, sizeof(*p));
61 p->parse = &textplain_parse;
62 p->free = &textplain_free;
64 emit_line(p, LINE_PRE_START, NULL, 0);
68 append(struct parser *p, const char *buf, size_t len)
73 newlen = len + p->len;
74 if ((t = calloc(1, newlen)) == NULL)
76 memcpy(t, p->buf, p->len);
77 memcpy(t + p->len, buf, len);
85 set_buf(struct parser *p, const char *buf, size_t len)
95 if ((p->buf = calloc(1, len)) == NULL)
97 memcpy(p->buf, buf, len);
103 textplain_parse(struct parser *p, const char *buf, size_t size)
113 if (!append(p, buf, size))
120 if ((e = telescope_strnchr((char*)b, '\n', len)) == NULL)
124 r = emit_line(p, LINE_PRE_CONTENT, b, l);
138 return set_buf(p, b, len);
142 textplain_free(struct parser *p)
144 /* flush the buffer */
146 if (!emit_line(p, LINE_PRE_CONTENT, p->buf, p->len))
150 return emit_line(p, LINE_PRE_END, NULL, 0);