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