buf.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. #include <ip.h>
  13. #include <plumb.h>
  14. #include <thread.h>
  15. #include <fcall.h>
  16. #include <9p.h>
  17. #include "dat.h"
  18. #include "fns.h"
  19. void
  20. initibuf(Ibuf *b, Ioproc *io, int fd)
  21. {
  22. b->fd = fd;
  23. b->io = io;
  24. b->rp = b->wp = b->buf;
  25. }
  26. int
  27. readibuf(Ibuf *b, char *buf, int len)
  28. {
  29. int n;
  30. n = b->wp - b->rp;
  31. if(n > 0){
  32. if(n > len)
  33. n = len;
  34. memmove(buf, b->rp, n);
  35. b->rp += n;
  36. return n;
  37. }
  38. return ioreadn(b->io, b->fd, buf, len);
  39. }
  40. void
  41. unreadline(Ibuf *b, char *line)
  42. {
  43. int i, n;
  44. i = strlen(line);
  45. n = b->wp - b->rp;
  46. memmove(&b->buf[i+1], b->rp, n);
  47. memmove(b->buf, line, i);
  48. b->buf[i] = '\n';
  49. b->rp = b->buf;
  50. b->wp = b->rp+i+1+n;
  51. }
  52. int
  53. readline(Ibuf *b, char *buf, int len)
  54. {
  55. int n;
  56. char *p;
  57. len--;
  58. for(p = buf;;){
  59. if(b->rp >= b->wp){
  60. n = ioread(b->io, b->fd, b->wp, sizeof(b->buf)/2);
  61. if(n < 0)
  62. return -1;
  63. if(n == 0)
  64. break;
  65. b->wp += n;
  66. }
  67. n = *b->rp++;
  68. if(len > 0){
  69. *p++ = n;
  70. len--;
  71. }
  72. if(n == '\n')
  73. break;
  74. }
  75. /* drop trailing white */
  76. for(;;){
  77. if(p <= buf)
  78. break;
  79. n = *(p-1);
  80. if(n != ' ' && n != '\t' && n != '\r' && n != '\n')
  81. break;
  82. p--;
  83. }
  84. *p = 0;
  85. return p-buf;
  86. }