1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include "writer.h"
34
35 void writer_init(Writer *w,
SYS_NETFD fd,
char *buf,
size_t len) {
36 w->fd = fd;
37 w->write = (wr_writefunc)net_write;
38 w->buffer = buf;
39 w->size = len;
40 w->pos =
0;
41 w->error =
0;
42 }
43
44 void writer_init_with_stream(Writer *w,
void *stream, wr_writefunc writefunc,
char *buf,
size_t len) {
45 w->fd = stream;
46 w->write = writefunc;
47 w->buffer = buf;
48 w->size = len;
49 w->pos =
0;
50 w->error =
0;
51 }
52
53 int writer_flush(Writer *w) {
54 if(w->error) {
55 return w->error;
56 }
57
58 size_t pos =
0;
59 size_t len = w->pos;
60
61 while(len >
0) {
62
63
64 ssize_t r = w->write(w->fd, w->buffer + pos, len);
65 if(r <=
0) {
66 break;
67 }
68 len -= r;
69 pos += r;
70 }
71
72 if(pos != w->pos) {
73 w->error =
1;
74 return 1;
75 }
76
77 w->pos =
0;
78 return 0;
79 }
80
81 int writer_put(Writer *w,
const char *s,
size_t len) {
82 if(w->error) {
83 return w->error;
84 }
85
86
87 size_t a = w->size - w->pos;
88 if(a ==
0) {
89 if(writer_flush(w)) {
90 return 1;
91 }
92 }
93
94 size_t cplen = len > a ? a : len;
95 memcpy(w->buffer+w->pos, s, cplen);
96 w->pos += cplen;
97
98 if(cplen < len) {
99
100
101 return writer_put(w, s + cplen, len - cplen);
102 }
else {
103 return 0;
104 }
105 }
106
107 int writer_puts(Writer *w, cxstring s) {
108 return writer_put(w, s.ptr, s.length);
109 }
110
111 int writer_putc(Writer *w,
char c) {
112 if(w->pos == w->size) {
113 if(writer_flush(w)) {
114 return 1;
115 }
116 }
117 w->buffer[w->pos++] = c;
118 return 0;
119 }
120
121 int writer_fwrite(
const void *s,
size_t size,
size_t nelem, Writer *out) {
122 int w = writer_put(out, s, size*nelem);
123 return w/size;
124 }
125