bgetrune.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. int32_t
  13. Bgetrune(Biobufhdr *bp)
  14. {
  15. int c, i;
  16. Rune rune;
  17. char str[UTFmax];
  18. c = Bgetc(bp);
  19. if(c < Runeself) { /* one char */
  20. bp->runesize = 1;
  21. return c;
  22. }
  23. str[0] = c;
  24. bp->runesize = 0;
  25. for(i=1;;) {
  26. c = Bgetc(bp);
  27. if(c < 0)
  28. return c;
  29. if (i >= sizeof str)
  30. return Runeerror;
  31. str[i++] = c;
  32. if(fullrune(str, i)) {
  33. /* utf is long enough to be a rune, but could be bad. */
  34. bp->runesize = chartorune(&rune, str);
  35. if (rune == Runeerror)
  36. bp->runesize = 0; /* push back nothing */
  37. else
  38. /* push back bytes unconsumed by chartorune */
  39. for(; i > bp->runesize; i--)
  40. Bungetc(bp);
  41. return rune;
  42. }
  43. }
  44. }
  45. int
  46. Bungetrune(Biobufhdr *bp)
  47. {
  48. if(bp->state == Bracteof)
  49. bp->state = Bractive;
  50. if(bp->state != Bractive)
  51. return Beof;
  52. bp->icount -= bp->runesize;
  53. bp->runesize = 0;
  54. return 1;
  55. }