libcdsb/src/array/extra.c

69 lines
1.6 KiB
C
Raw Normal View History

2022-06-02 15:52:43 +03:00
/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2022 Gregory Lirent */
#include "include.h"
#include "../__internal/assert.h"
#include "../__internal/vnode.h"
ssize_t array_find(const arr_t* x, const void* v, vtype vt) {
int c;
ssize_t index;
if (is_integer(x->type)) {
tvalue_assert(vt);
} else if (is_float(x->type)) {
tvalue_assert(vt);
} else type_assert(x->type, vt);
index = -1;
if (x->size) {
void* p = x->mem;
void* e = array_end(x);
assert(!is_null(x->mem));
if (x->type != vt) {
do {
++index;
c = vtype_compare(p, x->type, v, vt);
if (c == 0)
return index;
p += vtype_size(x->type);
} while (p < e);
} else {
do {
++index;
c = vtype_compare_eq(p, v, vt);
if (c == 0)
return index;
p += vtype_size(x->type);
} while (p < e);
}
}
return -1;
}
ssize_t array_push(arr_t* x, const void* v, vtype vt) {
void* p;
ssize_t i = x->size;
vnode_t n = vnode_tcreate(x->type, v, vt);
if ((ssize_t)array_allocated_nmemb(x) - vtype_size(x->type) < 0) {
++x->size;
x->mem = realloc(x->mem, array_allocated_nmemb(x));
} else ++x->size;
memcpy(array_at(x, i), vnode_peek(&n, x->type), vtype_size(x->type));
if (x->type < VTYPE_STRING) vnode_free(&n, x->type);
return i;
}