9base

revived minimalist port of Plan 9 userland to Unix
git clone git://git.suckless.org/9base
Log | Files | Refs | README | LICENSE

bread.c (681B)


      1 #include	"lib9.h"
      2 #include	<bio.h>
      3 
      4 long
      5 Bread(Biobuf *bp, void *ap, long count)
      6 {
      7 	long c;
      8 	unsigned char *p;
      9 	int i, n, ic;
     10 
     11 	p = ap;
     12 	c = count;
     13 	ic = bp->icount;
     14 
     15 	while(c > 0) {
     16 		n = -ic;
     17 		if(n > c)
     18 			n = c;
     19 		if(n == 0) {
     20 			if(bp->state != Bractive)
     21 				break;
     22 			i = read(bp->fid, bp->bbuf, bp->bsize);
     23 			if(i <= 0) {
     24 				bp->state = Bracteof;
     25 				if(i < 0)
     26 					bp->state = Binactive;
     27 				break;
     28 			}
     29 			bp->gbuf = bp->bbuf;
     30 			bp->offset += i;
     31 			if(i < bp->bsize) {
     32 				memmove(bp->ebuf-i, bp->bbuf, i);
     33 				bp->gbuf = bp->ebuf-i;
     34 			}
     35 			ic = -i;
     36 			continue;
     37 		}
     38 		memmove(p, bp->ebuf+ic, n);
     39 		c -= n;
     40 		ic += n;
     41 		p += n;
     42 	}
     43 	bp->icount = ic;
     44 	return count-c;
     45 }