commit f2cb64797e490c46413cef32d7154531b974d230
parent ec3fa2663a65c6a4e331ae1704824ffb9f2168f6
Author: rpa <rpa@grass>
Date: Thu, 15 Jun 2023 11:23:44 +0000
src/util: commit slice.c
Diffstat:
1 file changed, 16 insertions(+), 4 deletions(-)
diff --git a/src/util/slice.c b/src/util/slice.c
@@ -14,6 +14,12 @@ allocarray(Type *type, int count)
return a;
}
+void
+freearray(Array *a)
+{
+ free(a);
+}
+
Slice *
allocslice(Type *type, int len, int cap)
{
@@ -49,12 +55,18 @@ slicecopy(Slice *a)
Slice *
sliceappendp(Slice *s, int count, void *p)
{
+ assert(s != nil);
+ assert(p != nil);
if (s->len + count < s->cap) {
s->len += count;
} else {
- Slice *new = allocslice(s->arr->type, s->len + count, s->cap + count);
- memcpy(new->p, s->p, s->len * s->arr->type->nbytes);
- s = new;
+ Array *arr = allocarray(s->arr->type, s->len + count);
+ memcpy(arr->p, s->p, s->len * s->arr->type->nbytes);
+ freearray(s->arr);
+ s->arr = arr;
+ s->len += count;
+ s->cap = arr->count;
+ s->p = arr->p;
}
void *np = slicegetp(s, s->len - count);
memcpy(np, p, count * s->arr->type->nbytes);
@@ -87,6 +99,6 @@ slicegetp(Slice *s, int n)
void
freeslice(Slice *s)
{
- free(s->arr);
+ freearray(s->arr);
free(s);
}