add assert header to jh.h
[libjh.git] / bufchain.c
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <fcntl.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6
7 int bufio_chain_append(bufio_chain *bc, void *buf, size_t len) {
8   bufio_chain_entry *e = calloc(1, sizeof(*e));
9   if (e != NULL) return -1;
10   e->next = NULL;
11   e->buf = buf;
12   e->len = len;
13   if (bc->head != NULL) {
14     bc->tail->next = e;
15   } else {
16     bc->head = e;
17   }
18   bc->tail = e;
19   return 0;
20 }
21
22 int bufio_chain_flush(bufio_chain *bc, int fd) {
23   while (bc->head != NULL) {
24     bufio_chain_entry *e = bc->head;
25     int res = write(fd, e->buf+e->used, e->len-e->used);
26     if (res < 0) return res;
27     assert(e->used == e->len || res != 0);
28     e->used += res;
29     if (e->used == e->len) {
30       bc->head = e->next;
31       free(e->buf);
32       free(e);
33     }
34   }
35   bc->tail = NULL;
36   return 0;
37 }
38
39 void bufio_chain_clear(bufio_chain *bc) {
40   while (bc->head != NULL) {
41     bufio_chain_entry *e = bc->head;
42     free(e->buf);
43     bc->head = e->next;
44     free(e);
45   }
46   bc->tail = NULL;
47 }