brdline.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. void*
  13. Brdline(Biobufhdr *bp, int delim)
  14. {
  15. char *ip, *ep;
  16. int i, j;
  17. i = -bp->icount;
  18. if(i == 0) {
  19. /*
  20. * eof or other error
  21. */
  22. if(bp->state != Bractive) {
  23. if(bp->state == Bracteof)
  24. bp->state = Bractive;
  25. bp->rdline = 0;
  26. bp->gbuf = bp->ebuf;
  27. return 0;
  28. }
  29. }
  30. /*
  31. * first try in remainder of buffer (gbuf doesn't change)
  32. */
  33. ip = (char*)bp->ebuf - i;
  34. ep = memchr(ip, delim, i);
  35. if(ep) {
  36. j = (ep - ip) + 1;
  37. bp->rdline = j;
  38. bp->icount += j;
  39. return ip;
  40. }
  41. /*
  42. * copy data to beginning of buffer
  43. */
  44. if(i < bp->bsize)
  45. memmove(bp->bbuf, ip, i);
  46. bp->gbuf = bp->bbuf;
  47. /*
  48. * append to buffer looking for the delim
  49. */
  50. ip = (char*)bp->bbuf + i;
  51. while(i < bp->bsize) {
  52. j = read(bp->fid, ip, bp->bsize-i);
  53. if(j <= 0) {
  54. /*
  55. * end of file with no delim
  56. */
  57. memmove(bp->ebuf-i, bp->bbuf, i);
  58. bp->rdline = i;
  59. bp->icount = -i;
  60. bp->gbuf = bp->ebuf-i;
  61. return 0;
  62. }
  63. bp->offset += j;
  64. i += j;
  65. ep = memchr(ip, delim, j);
  66. if(ep) {
  67. /*
  68. * found in new piece
  69. * copy back up and reset everything
  70. */
  71. ip = (char*)bp->ebuf - i;
  72. if(i < bp->bsize){
  73. memmove(ip, bp->bbuf, i);
  74. bp->gbuf = (uint8_t*)ip;
  75. }
  76. j = (ep - (char*)bp->bbuf) + 1;
  77. bp->rdline = j;
  78. bp->icount = j - i;
  79. return ip;
  80. }
  81. ip += j;
  82. }
  83. /*
  84. * full buffer without finding
  85. */
  86. bp->rdline = bp->bsize;
  87. bp->icount = -bp->bsize;
  88. bp->gbuf = bp->bbuf;
  89. return 0;
  90. }
  91. int
  92. Blinelen(Biobufhdr *bp)
  93. {
  94. return bp->rdline;
  95. }