/* 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 libcdsb_array_push(arr_t* x, const void* v, vtype t) { ssize_t i = x->size; vnode_t n = vnode_tcreate(x->type, v, t); x->mem = realloc(x->mem, ++x->size * vtype_size(x->type)); memcpy(array_internal_at(x, i), vnode_peek(&n, x->type), vtype_size(x->type)); if (vtype_size(x->type) > sizeof(void*) && x->type < VTYPE_STRING) vnode_free(&n, x->type); return i; } size_t libcdsb_array_count(const arr_t* s, const void* v, vtype t) { void *p; void *e; int cmp; size_t n; p = s->mem; e = array_end(s); n = 0; do { cmp = vtype_compare(p, s->type, v, t); if (cmp == 0) ++n; p += vtype_size(s->type); } while (p < e); return n; } int libcdsb_array_get(vtype_array* x, ssize_t i, void* _, array_access_callback callback, vtype_bool cut) { int r = 0; if (i < 0 && (i += x->size) < 0) i = 0; if (i < x->size) { if (callback) r = callback(array_internal_at(x, i), i, x->type, _); if (cut) array_cut(x, i, 1); } else return -1; return r; } int libcdsb_array_find(arr_t* x, const void* v, vtype t, void* _, array_access_callback callback, bool r, bool cut) { void *p; ssize_t i; int cmp; if (!x->size) return -1; if (!r) { p = x->mem; i = 0; do { cmp = vtype_compare(p, x->type, v, t); if (cmp == 0) break; p += vtype_size(x->type); ++i; } while (i < x->size); if (i >= x->size) return -1; } else { p = array_end(x); i = x->size; while (i--) { p -= vtype_size(x->type); cmp = vtype_compare(p, x->type, v, t); if (cmp == 0) break; } if (i < 0) return i; } if (callback) cmp = callback(p, i, x->type, _); if (cut) array_cut(x, i, 1); return cmp; } int libcdsb_array_foreach(vtype_array* x, void* data, array_access_callback callback, bool flush) { void* p; void* e; size_t n; int r; p = x->mem; e = x->mem + x->size*vtype_size(x->type); n = 0; r = 0; while (p < e) { if ((r = callback(p, n, x->type, data))) break; p += vtype_size(x->type); ++n; } if (flush) { free(x->mem); memset(x, 0, sizeof(*x)); } return r; }