major cleanup and improved block handling
[ctxt.git] / doc.c
blob8c0312df2e38ffa6d1d8d6583293517253633d1d
1 #include <stdlib.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include "ctxt.h"
6 #define BUFFSIZE 2 * 1024
8 struct doc *doc_alloc(int fd)
10 struct doc *doc = xmalloc(sizeof(struct doc));
11 doc->fd = fd;
12 doc->size = BUFFSIZE;
13 doc->len = 0;
14 doc->buf = xmalloc(BUFFSIZE);
15 return doc;
18 static void flush_buf(int fd, char *buf, int len)
20 int c = 0;
21 int n = 0;
22 while (len > n && (c = write(fd, buf + n, len - n)) >= 0)
23 n += c;
26 static void doc_flush(struct doc *doc)
28 flush_buf(doc->fd, doc->buf, doc->len);
29 doc->len = 0;
32 void doc_memcat(struct doc *doc, char *s, int n)
34 if (n > doc->size / 2) {
35 doc_flush(doc);
36 flush_buf(doc->fd, s, n);
37 return;
39 if (n + doc->len > doc->size)
40 doc_flush(doc);
41 memcpy(doc->buf + doc->len, s, n);
42 doc->len += n;
45 void doc_write(struct doc *doc, char *s)
47 doc_memcat(doc, s, strlen(s));
50 void doc_free(struct doc *doc)
52 doc_flush(doc);
53 free(doc->buf);
54 free(doc);