55a1fededea60b28cda785a77c73eee3b390ee47
[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 #include "bufio.h"
10
11 int bufio_chain_append(bufio_chain *bc, void *buf, size_t len) {
12   bufio_chain_entry *e = calloc(1, sizeof(*e));
13   if (e != NULL) return -1;
14   e->next = NULL;
15   e->buf = buf;
16   e->len = len;
17   if (bc->head != NULL) {
18     bc->tail->next = e;
19   } else {
20     bc->head = e;
21   }
22   bc->tail = e;
23   return 0;
24 }
25
26 int bufio_chain_flush(bufio_chain *bc, int fd) {
27   while (bc->head != NULL) {
28     bufio_chain_entry *e = bc->head;
29     int res = write(fd, e->buf+e->used, e->len-e->used);
30     if (res < 0) return res;
31     assert(e->used == e->len || res != 0);
32     e->used += res;
33     if (e->used == e->len) {
34       bc->head = e->next;
35       free(e->buf);
36       free(e);
37     }
38   }
39   bc->tail = NULL;
40   return 0;
41 }
42
43 void bufio_chain_clear(bufio_chain *bc) {
44   while (bc->head != NULL) {
45     bufio_chain_entry *e = bc->head;
46     free(e->buf);
47     bc->head = e->next;
48     free(e);
49   }
50   bc->tail = NULL;
51 }