libcdsb/src/array/get.c
2022-06-02 15:52:43 +03:00

78 lines
2.1 KiB
C

/* 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_get(arr_t* x, val_t* d, ssize_t i, _Bool cut) {
if (i < 0 && (i += x->size) < 0) i = 0;
if (i < x->size) {
assert(!is_null(x->mem));
if (cut) {
if (!is_null(d)) {
vnode_t n = vnode_create(array_at(x, i), x->type);
value_set(d, n, x->type, VF_WRITEABLE|VF_REMOVABLE);
}
array_cut(x, i, 1);
} else value_set(d, array_at(x, i), x->type, VF_WRITEABLE);
} else {
i = -1;
memset(d, 0, sizeof(*d));
}
return i;
}
_Bool array_slice(arr_t* x, arr_t* s, ssize_t i, size_t n, _Bool cut) {
if (n && s->size) {
assert(!is_null(s->mem));
if (i < 0 && (i += s->size) < 0) i = 0;
if (i + n > s->size) {
memset(x, 0, sizeof(*x));
return false;
}
x->type = s->type;
x->size = n;
x->mem = malloc(array_allocated_nmemb(x));
if (!cut && s->type >= VTYPE_STRING) {
void *p, *v, *e;
void (*init)(void*, const void*);
p = x->mem;
v = array_at(s, i);
e = array_at(x, n);
switch (s->type) { default: abort();
case VTYPE_STRING: init = (void*)string_copy_init; break;
case VTYPE_ARRAY: init = (void*) array_copy_init; break;
case VTYPE_LIST: init = (void*) list_copy_init; break;
case VTYPE_MAP: init = (void*) map_copy_init; break;
case VTYPE_SET: init = (void*) vset_copy_init; break;
}
do {
init(p, v);
p += vtype_size(x->type);
v += vtype_size(x->type);
} while (p < e);
} else memcpy(x->mem, array_at(s, i), n*vtype_size(x->type));
if (cut) array_cut(s, i, n);
} else {
memset(x, 0, sizeof(*x));
if (n && !s->size) return false;
}
return true;
}