missing commit in generator.h
[galan.git] / src / buffer.c
blob5e2078917f360a80b3900fd2d17787c78e4dc107
1 /* gAlan - Graphical Audio Language
2 * Copyright (C) 1999 Tony Garnock-Jones
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
23 #include "buffer.h"
25 BUFFER newbuf(int initial_length) {
26 BUFFER buf = malloc(sizeof(Buffer));
28 buf->buflength = initial_length;
29 buf->pos = 0;
30 buf->buf = malloc(initial_length);
31 memset(buf->buf, 0, initial_length);
33 return buf;
36 BUFFER dupbuf(BUFFER buf) {
37 BUFFER n = malloc(sizeof(Buffer));
39 n->buflength = buf->buflength;
40 n->pos = buf->pos;
41 n->buf = malloc(buf->buflength);
42 memcpy(n->buf, buf->buf, buf->buflength);
44 return n;
47 void killbuf(BUFFER buf) {
48 free(buf->buf);
49 free(buf);
52 void buf_append(BUFFER buf, char ch) {
53 if (buf->pos >= buf->buflength) {
54 char *newbuf = malloc(buf->buflength + 128);
56 if (newbuf == NULL) {
57 fprintf(stderr, "buf_append: could not grow buffer\n");
58 exit(1);
61 memset(newbuf, 0, buf->buflength + 128);
62 memcpy(newbuf, buf->buf, buf->buflength);
63 free(buf->buf);
64 buf->buf = newbuf;
65 buf->buflength += 128;
68 buf->buf[buf->pos++] = ch;
71 void buf_insert(BUFFER buf, char ch, int pos) {
72 int i;
74 if (pos < 0)
75 pos = 0;
76 if (pos > buf->pos)
77 pos = buf->pos;
79 buf_append(buf, 0);
80 for (i = buf->pos; i > pos; i--)
81 buf->buf[i] = buf->buf[i-1];
82 buf->buf[pos] = ch;
85 void buf_delete(BUFFER buf, int pos) {
86 int i;
88 if (pos < 0)
89 pos = 0;
90 if (pos >= buf->pos)
91 pos = buf->pos - 1;
93 for (i = pos; i < buf->pos; i++)
94 buf->buf[i] = buf->buf[i+1];
95 buf->buf[buf->pos - 1] = '\0';
96 buf->pos--;