bgetc.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include <u.h>
  10. #include <libc.h>
  11. #include <bio.h>
  12. int
  13. Bgetc(Biobufhdr *bp)
  14. {
  15. int i;
  16. loop:
  17. i = bp->icount;
  18. if(i != 0) {
  19. bp->icount = i+1;
  20. return bp->ebuf[i];
  21. }
  22. if(bp->state != Bractive) {
  23. if(bp->state == Bracteof)
  24. bp->state = Bractive;
  25. return Beof;
  26. }
  27. /*
  28. * get next buffer, try to keep Bungetsize
  29. * characters pre-catenated from the previous
  30. * buffer to allow that many ungets.
  31. */
  32. memmove(bp->bbuf-Bungetsize, bp->ebuf-Bungetsize, Bungetsize);
  33. i = read(bp->fid, bp->bbuf, bp->bsize);
  34. bp->gbuf = bp->bbuf;
  35. if(i <= 0) {
  36. bp->state = Bracteof;
  37. if(i < 0)
  38. bp->state = Binactive;
  39. return Beof;
  40. }
  41. if(i < bp->bsize) {
  42. memmove(bp->ebuf-i-Bungetsize, bp->bbuf-Bungetsize, i+Bungetsize);
  43. bp->gbuf = bp->ebuf-i;
  44. }
  45. bp->icount = -i;
  46. bp->offset += i;
  47. goto loop;
  48. }
  49. int
  50. Bungetc(Biobufhdr *bp)
  51. {
  52. if(bp->state == Bracteof)
  53. bp->state = Bractive;
  54. if(bp->state != Bractive)
  55. return Beof;
  56. bp->icount--;
  57. return 1;
  58. }