1 #include "less.h" 2 #include "xbuf.h" 3 4 /* 5 * Initialize an expandable text buffer. 6 */ 7 public void 8 xbuf_init(xbuf) 9 struct xbuffer *xbuf; 10 { 11 xbuf->data = NULL; 12 xbuf->size = xbuf->end = 0; 13 } 14 15 public void 16 xbuf_deinit(xbuf) 17 struct xbuffer *xbuf; 18 { 19 if (xbuf->data != NULL) 20 free(xbuf->data); 21 xbuf_init(xbuf); 22 } 23 24 public void 25 xbuf_reset(xbuf) 26 struct xbuffer *xbuf; 27 { 28 xbuf->end = 0; 29 } 30 31 /* 32 * Add a char to an expandable text buffer. 33 */ 34 public void 35 xbuf_add(xbuf, ch) 36 struct xbuffer *xbuf; 37 int ch; 38 { 39 if (xbuf->end >= xbuf->size) 40 { 41 char *data; 42 xbuf->size = (xbuf->size == 0) ? 16 : xbuf->size * 2; 43 data = (char *) ecalloc(xbuf->size, sizeof(char)); 44 if (xbuf->data != NULL) 45 { 46 memcpy(data, xbuf->data, xbuf->end); 47 free(xbuf->data); 48 } 49 xbuf->data = data; 50 } 51 xbuf->data[xbuf->end++] = ch; 52 } 53 54 public int 55 xbuf_pop(buf) 56 struct xbuffer *buf; 57 { 58 if (buf->end == 0) 59 return -1; 60 return buf->data[--(buf->end)]; 61 } 62 63 public void 64 xbuf_set(dst, src) 65 struct xbuffer *dst; 66 struct xbuffer *src; 67 { 68 int i; 69 70 xbuf_reset(dst); 71 for (i = 0; i < src->end; i++) 72 xbuf_add(dst, src->data[i]); 73 } 74