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;
135 static void test_err(void *x UNUSED, uns flags, char *msg UNUSED)
137 if (flags & FBSOCK_READ)
139 else if (flags & FBSOCK_WRITE)
141 if (flags & FBSOCK_TIMEOUT)
142 printf(" TIMEOUT\n");
154 struct fbsock_params p = {
160 struct fastbuf *f = fbsock_create(&p);
162 bputsn(f, "Oook!"); // This fits in PIPE_BUF
166 if (!bgets(f, buf, sizeof(buf)))
168 if (strcmp(buf, "Oook!"))
169 die("Misread input");
171 bgets(f, buf, sizeof(buf));