2 * UCW Library -- Fast Buffered I/O on Sockets with Timeouts
4 * (c) 2008 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 #include "ucw/fastbuf.h"
12 #include "ucw/fb-socket.h"
21 struct fbsock_params par;
25 #define FB_SOCK(f) ((struct fb_sock *)(f)->is_fastbuf)
28 fbs_refill(struct fastbuf *f)
30 struct fbsock_params *p = &FB_SOCK(f)->par;
38 int e = poll(&pf, 1, p->timeout_ms);
41 p->err(p->data, FBSOCK_READ, "read error");
46 p->err(p->data, FBSOCK_READ | FBSOCK_TIMEOUT, "read timeout");
51 int l = read(p->fd, f->buffer, f->bufend-f->buffer);
54 if (errno == EINTR || errno == EAGAIN)
56 p->err(p->data, FBSOCK_READ, "read error");
59 f->bstop = f->buffer + l;
66 fbs_spout(struct fastbuf *f)
68 struct fbsock_params *p = &FB_SOCK(f)->par;
74 int l = f->bptr - f->buffer;
76 char *buf = f->buffer;
80 int e = poll(&pf, 1, p->timeout_ms);
83 p->err(p->data, FBSOCK_WRITE, "write error");
88 p->err(p->data, FBSOCK_WRITE | FBSOCK_TIMEOUT, "write timeout");
92 e = write(p->fd, buf, l);
95 if (errno == EINTR || errno == EAGAIN)
97 p->err(p->data, FBSOCK_WRITE, "write error");
106 fbs_close(struct fastbuf *f)
108 close(FB_SOCK(f)->par.fd);
113 fbsock_create(struct fbsock_params *p)
115 struct fb_sock *F = xmalloc(sizeof(*F) + p->bufsize);
116 struct fastbuf *f = &F->fb;
118 bzero(F, sizeof(*F));
121 f->bptr = f->bstop = f->buffer;
122 f->bufend = f->buffer + p->bufsize;
123 f->name = "<socket>";
124 f->refill = fbs_refill;
125 f->spout = fbs_spout;
126 f->close = fbs_close;
127 f->can_overwrite_buffer = 1;
136 static void test_err(void *x UNUSED, uns flags, char *msg UNUSED)
138 if (flags & FBSOCK_READ)
140 else if (flags & FBSOCK_WRITE)
142 if (flags & FBSOCK_TIMEOUT)
143 printf(" TIMEOUT\n");
155 struct fbsock_params p = {
161 struct fastbuf *f = fbsock_create(&p);
163 bputsn(f, "Oook!"); // This fits in PIPE_BUF
167 if (!bgets(f, buf, sizeof(buf)))
169 if (strcmp(buf, "Oook!"))
170 die("Misread input");
172 bgets(f, buf, sizeof(buf));