use m4_normalize on the output strings to remove trailing spaces/tabs and consolidate...
[AROS.git] / workbench / c / Shell / buffer.c
blobd1b2c544a9436f56f82579728763b81db3d269c1
1 /*
2 Copyright (C) 1995-2011, The AROS Development Team. All rights reserved.
3 $Id$
4 */
6 #include <aros/debug.h>
7 #include <exec/memory.h>
8 #include <proto/dos.h>
9 #include <proto/exec.h>
11 #include "buffer.h"
13 #define BUF_SIZE 512
15 static BOOL bufferExpand(Buffer *out, LONG size, APTR SysBase)
17 ULONG newLength = out->len + size;
19 if (newLength > out->mem)
21 ULONG newSize = BUF_SIZE;
22 STRPTR tmp;
24 while (newSize < newLength)
25 newSize += BUF_SIZE;
27 if ((tmp = AllocMem(newSize + 1, MEMF_ANY)) == NULL)
28 return FALSE;
30 if (out->len > 0)
31 CopyMem(out->buf, tmp, out->len);
33 if (out->mem > 0)
34 FreeMem(out->buf, out->mem);
36 out->buf = tmp;
37 out->mem = newSize;
39 return TRUE;
42 LONG bufferInsert(STRPTR str, ULONG size, Buffer *out, APTR SysBase)
44 ULONG newLength;
45 if (!bufferExpand(out, size, SysBase))
46 return ERROR_NO_FREE_STORE;
48 memmove(out->buf + size, out->buf, out->len);
49 CopyMem(str, out->buf, size);
50 newLength = out->len + size;
51 out->len = newLength;
52 out->buf[newLength] = '\0';
54 return 0;
57 LONG bufferAppend(STRPTR str, ULONG size, Buffer *out, APTR SysBase)
59 ULONG newLength;
60 if (!bufferExpand(out, size, SysBase))
61 return ERROR_NO_FREE_STORE;
63 CopyMem(str, out->buf + out->len, size);
64 newLength = out->len + size;
65 out->len = newLength;
66 out->buf[newLength] = '\0';
68 return 0;
71 LONG bufferCopy(Buffer *in, Buffer *out, ULONG size, APTR SysBase)
73 STRPTR s = in->buf + in->cur;
74 LONG ret = bufferAppend(s, size, out, SysBase);
75 in->cur += size;
76 return ret;
79 void bufferFree(Buffer *b, APTR SysBase)
81 if (b->mem <= 0)
82 return;
84 FreeMem(b->buf, b->mem + 1);
86 b->buf = NULL;
87 b->len = 0;
88 b->cur = 0;
89 b->mem = 0;
92 LONG bufferReadItem(STRPTR buf, ULONG size, Buffer *in, APTR DOSBase)
94 struct CSource tin = { in->buf, in->len, in->cur };
95 LONG ret = ReadItem(buf, size, &tin);
97 in->cur = tin.CS_CurChr;
100 * Workaround for intentional ReadItem() bug:
101 * If it hits end of buffer, it will push back one character.
102 * This bug replicates OS3.1 behavior, on which many existing
103 * programs rely. They all have own workarounds. We too.
105 if (in->cur == in->len - 1)
107 D(bug("[bufferReadItem] Getting last character\n"));
108 in->cur++;
111 return ret;
114 void bufferReset(Buffer *b)
116 if (b->mem > 0)
117 b->buf[0] = '\0';
119 b->len = 0;
120 b->cur = 0;