bufblock.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "mk.h"
  2. static Bufblock *freelist;
  3. #define QUANTA 4096
  4. Bufblock *
  5. newbuf(void)
  6. {
  7. Bufblock *p;
  8. if (freelist) {
  9. p = freelist;
  10. freelist = freelist->next;
  11. } else {
  12. p = (Bufblock *) Malloc(sizeof(Bufblock));
  13. p->start = Malloc(QUANTA*sizeof(*p->start));
  14. p->end = p->start+QUANTA;
  15. }
  16. p->current = p->start;
  17. *p->start = 0;
  18. p->next = 0;
  19. return p;
  20. }
  21. void
  22. freebuf(Bufblock *p)
  23. {
  24. p->next = freelist;
  25. freelist = p;
  26. }
  27. void
  28. growbuf(Bufblock *p)
  29. {
  30. int n;
  31. Bufblock *f;
  32. char *cp;
  33. n = p->end-p->start+QUANTA;
  34. /* search the free list for a big buffer */
  35. for (f = freelist; f; f = f->next) {
  36. if (f->end-f->start >= n) {
  37. memcpy(f->start, p->start, p->end-p->start);
  38. cp = f->start;
  39. f->start = p->start;
  40. p->start = cp;
  41. cp = f->end;
  42. f->end = p->end;
  43. p->end = cp;
  44. f->current = f->start;
  45. break;
  46. }
  47. }
  48. if (!f) { /* not found - grow it */
  49. p->start = Realloc(p->start, n);
  50. p->end = p->start+n;
  51. }
  52. p->current = p->start+n-QUANTA;
  53. }
  54. void
  55. bufcpy(Bufblock *buf, char *cp, int n)
  56. {
  57. while (n--)
  58. insert(buf, *cp++);
  59. }
  60. void
  61. insert(Bufblock *buf, int c)
  62. {
  63. if (buf->current >= buf->end)
  64. growbuf(buf);
  65. *buf->current++ = c;
  66. }
  67. void
  68. rinsert(Bufblock *buf, Rune r)
  69. {
  70. int n;
  71. n = runelen(r);
  72. if (buf->current+n > buf->end)
  73. growbuf(buf);
  74. runetochar(buf->current, &r);
  75. buf->current += n;
  76. }