tex: include stdlib.h for using size_t
[ctxt.git] / doc.c
blob19df6a72d70253fd973f65c93a93a0323986ba8b
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, size_t 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_write(struct doc *doc, char *s)
35 int n = strlen(s);
36 if (n > doc->size / 2) {
37 doc_flush(doc);
38 flush_buf(doc->fd, s, n);
39 return;
41 if (n + doc->len > doc->size)
42 doc_flush(doc);
43 memcpy(doc->buf + doc->len, s, n);
44 doc->len += n;
47 void doc_free(struct doc *doc)
49 doc_flush(doc);
50 free(doc->buf);
51 free(doc);