libcdsb/src/set/modify.c

75 lines
1.8 KiB
C

/* This software is licensed by the MIT License, see LICENSE file */
/* Copyright © 2022 Gregory Lirent */
#include "../../include/set.h"
#include "../__internal/rbtree.h"
#include "../__internal/assert.h"
bool libcdsb_vset_insert(set_t* x, vtype_variable value) {
int cmp;
rbnode_t* n;
rbnode_t* p;
if (!rbnode_is_empty(n = x->root)) {
do {
p = n;
cmp = variable_compare(value, vnode_peek(&n->value, x->type));
if (cmp == 0) return false;
n = (cmp < 0) ? n->left : n->right;
} while (!rbnode_is_empty(n));
n = rbnode_create(nullptr, p, 1);
if (cmp < 0) p->left = n;
else p->right = n;
if (!rbnode_is_root(p))
rbnode_fixup(&x->root, n);
} else n = x->root = rbnode_create(nullptr, rbnode_empty, 0);
n->value = vnode_create_ex(x->type, value);
return true;
}
bool libcdsb_vset_attach(set_t* x, vtype_variable value) {
int cmp;
rbnode_t* n;
rbnode_t* p;
vnode_t vn;
vnode_attach_ex(&vn, x->type, value);
n = x->root;
value.type = x->type;
value.pointer = vnode_peek(&vn, value.type).pointer;
if (!rbnode_is_empty(n)) {
do {
p = n;
cmp = variable_compare(value, vnode_peek(&n->value, x->type));
if (cmp == 0) {
vnode_free(&vn, value.type);
return false;
}
n = (cmp < 0) ? n->left : n->right;
} while (!rbnode_is_empty(n));
n = rbnode_create(vn, p, 1);
if (cmp < 0) p->left = n;
else p->right = n;
if (!rbnode_is_root(p))
rbnode_fixup(&x->root, n);
} else n = x->root = rbnode_create(vn, rbnode_empty, 0);
return true;
}