troff: let all writes go through troff_put()
[ctxt.git] / doc.c
blob0ca8d7fb7f165d8c77edad14de7b50348ed2357b
1 #include <stdlib.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include "ctxt.h"
5 #include "util.h"
7 #define BUFFSIZE 2 * 1024
9 struct doc *doc_alloc(int fd)
11 struct doc *doc = xmalloc(sizeof(struct doc));
12 doc->fd = fd;
13 doc->size = BUFFSIZE;
14 doc->len = 0;
15 doc->buf = xmalloc(BUFFSIZE);
16 return doc;
19 static void flush_buf(int fd, char *buf, int len)
21 int c = 0;
22 int n = 0;
23 while (len > n && (c = write(fd, buf + n, len - n)) >= 0)
24 n += c;
27 static void doc_flush(struct doc *doc)
29 flush_buf(doc->fd, doc->buf, doc->len);
30 doc->len = 0;
33 void doc_memcat(struct doc *doc, char *s, int n)
35 if (n > doc->size / 2) {
36 doc_flush(doc);
37 flush_buf(doc->fd, s, n);
38 return;
40 if (n + doc->len > doc->size)
41 doc_flush(doc);
42 memcpy(doc->buf + doc->len, s, n);
43 doc->len += n;
46 void doc_write(struct doc *doc, char *s)
48 doc_memcat(doc, s, strlen(s));
51 void doc_free(struct doc *doc)
53 doc_flush(doc);
54 free(doc->buf);
55 free(doc);