bseek.c (929B)
1 #include "lib9.h" 2 #include <bio.h> 3 4 long long 5 Bseek(Biobuf *bp, long long offset, int base) 6 { 7 vlong n, d; 8 int bufsz; 9 10 switch(bp->state) { 11 default: 12 fprint(2, "Bseek: unknown state %d\n", bp->state); 13 return Beof; 14 15 case Bracteof: 16 bp->state = Bractive; 17 bp->icount = 0; 18 bp->gbuf = bp->ebuf; 19 20 case Bractive: 21 n = offset; 22 if(base == 1) { 23 n += Boffset(bp); 24 base = 0; 25 } 26 27 /* 28 * try to seek within buffer 29 */ 30 if(base == 0) { 31 d = n - Boffset(bp); 32 bufsz = bp->ebuf - bp->gbuf; 33 if(-bufsz <= d && d <= bufsz){ 34 bp->icount += d; 35 if(d >= 0) { 36 if(bp->icount <= 0) 37 return n; 38 } else { 39 if(bp->ebuf - bp->gbuf >= -bp->icount) 40 return n; 41 } 42 } 43 } 44 45 /* 46 * reset the buffer 47 */ 48 n = lseek(bp->fid, n, base); 49 bp->icount = 0; 50 bp->gbuf = bp->ebuf; 51 break; 52 53 case Bwactive: 54 Bflush(bp); 55 n = seek(bp->fid, offset, base); 56 break; 57 } 58 bp->offset = n; 59 return n; 60 }