]> git.lizzy.rs Git - plan9front.git/blob - sys/src/cmd/webfs/buf.c
cwfs: back to previous version
[plan9front.git] / sys / src / cmd / webfs / buf.c
1 #include <u.h>
2 #include <libc.h>
3 #include <bio.h>
4 #include <ip.h>
5 #include <plumb.h>
6 #include <thread.h>
7 #include <fcall.h>
8 #include <9p.h>
9 #include "dat.h"
10 #include "fns.h"
11
12 void
13 initibuf(Ibuf *b, Ioproc *io, int fd)
14 {
15         b->fd = fd;
16         b->io = io;
17         b->rp = b->wp = b->buf;
18 }
19
20 int
21 readibuf(Ibuf *b, char *buf, int len)
22 {
23         int n;
24
25         n = b->wp - b->rp;
26         if(n > 0){
27                 if(n > len)
28                         n = len;
29                 memmove(buf, b->rp, n);
30                 b->rp += n;
31                 return n;
32         }
33         return ioreadn(b->io, b->fd, buf, len);
34 }
35
36 void
37 unreadline(Ibuf *b, char *line)
38 {
39         int i, n;
40
41         i = strlen(line);
42         n = b->wp - b->rp;
43         memmove(&b->buf[i+1], b->rp, n);
44         memmove(b->buf, line, i);
45         b->buf[i] = '\n';
46         b->rp = b->buf;
47         b->wp = b->rp+i+1+n;
48 }
49
50 int
51 readline(Ibuf *b, char *buf, int len)
52 {
53         int n;
54         char *p;
55
56         len--;
57
58         for(p = buf;;){
59                 if(b->rp >= b->wp){
60                         n = ioread(b->io, b->fd, b->wp, sizeof(b->buf)/2);
61                         if(n < 0)
62                                 return -1;
63                         if(n == 0)
64                                 break;
65                         b->wp += n;
66                 }
67                 n = *b->rp++;
68                 if(len > 0){
69                         *p++ = n;
70                         len--;
71                 }
72                 if(n == '\n')
73                         break;
74         }
75
76         /* drop trailing white */
77         for(;;){
78                 if(p <= buf)
79                         break;
80                 n = *(p-1);
81                 if(n != ' ' && n != '\t' && n != '\r' && n != '\n')
82                         break;
83                 p--;
84         }
85
86         *p = 0;
87         return p-buf;
88 }
89