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