2 75a8a1ec 2022-02-08 op * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
4 75a8a1ec 2022-02-08 op * Permission to use, copy, modify, and distribute this software for any
5 75a8a1ec 2022-02-08 op * purpose with or without fee is hereby granted, provided that the above
6 75a8a1ec 2022-02-08 op * copyright notice and this permission notice appear in all copies.
8 75a8a1ec 2022-02-08 op * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 75a8a1ec 2022-02-08 op * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 75a8a1ec 2022-02-08 op * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 75a8a1ec 2022-02-08 op * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 75a8a1ec 2022-02-08 op * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 75a8a1ec 2022-02-08 op * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 75a8a1ec 2022-02-08 op * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 75a8a1ec 2022-02-08 op * A streaming text/plain "parser."
21 75a8a1ec 2022-02-08 op #include <stdlib.h>
22 75a8a1ec 2022-02-08 op #include <string.h>
24 75a8a1ec 2022-02-08 op #include "telescope.h"
25 75a8a1ec 2022-02-08 op #include "parser.h"
27 75a8a1ec 2022-02-08 op static int textplain_parse(struct parser*, const char*, size_t);
28 75a8a1ec 2022-02-08 op static int textplain_foreach_line(struct parser*, const char*, size_t);
29 75a8a1ec 2022-02-08 op static int textplain_free(struct parser*);
31 75a8a1ec 2022-02-08 op static inline int
32 75a8a1ec 2022-02-08 op emit_line(struct parser *p, const char *line, size_t len)
34 75a8a1ec 2022-02-08 op struct line *l;
36 75a8a1ec 2022-02-08 op if ((l = calloc(1, sizeof(*l))) == NULL)
39 75a8a1ec 2022-02-08 op l->type = LINE_TEXT;
41 75a8a1ec 2022-02-08 op if (len != 0) {
42 75a8a1ec 2022-02-08 op if ((l->line = calloc(1, len+1)) == NULL) {
47 75a8a1ec 2022-02-08 op memcpy(l->line, line, len);
50 75a8a1ec 2022-02-08 op TAILQ_INSERT_TAIL(&p->head, l, lines);
56 75a8a1ec 2022-02-08 op textplain_initparser(struct parser *p)
58 75a8a1ec 2022-02-08 op memset(p, 0, sizeof(*p));
60 75a8a1ec 2022-02-08 op p->name = "text/plain";
61 75a8a1ec 2022-02-08 op p->parse = &textplain_parse;
62 75a8a1ec 2022-02-08 op p->free = &textplain_free;
64 75a8a1ec 2022-02-08 op TAILQ_INIT(&p->head);
68 75a8a1ec 2022-02-08 op textplain_parse(struct parser *p, const char *buf, size_t size)
70 75a8a1ec 2022-02-08 op return parser_foreach_line(p, buf, size, textplain_foreach_line);
74 75a8a1ec 2022-02-08 op textplain_foreach_line(struct parser *p, const char *line, size_t linelen)
76 75a8a1ec 2022-02-08 op return emit_line(p, line, linelen);
80 75a8a1ec 2022-02-08 op textplain_free(struct parser *p)
82 75a8a1ec 2022-02-08 op if (p->len != 0)
83 75a8a1ec 2022-02-08 op return emit_line(p, p->buf, p->len);