Sets - osvaldoandrade/ova-lib GitHub Wiki
Sets
Read this page when uniqueness is the point and the payload itself is the element.
Constructor and Variants
The constructor is:
set *create_set(set_type type, comparator cmp, hash_func_t hash);
The 2 variants are:
| Variant | Meaning |
|---|---|
SET_HASH |
hash-based set |
SET_TREE |
tree-based ordered set |
For SET_HASH, both cmp and hash must be provided, unless both are NULL. If both are NULL, the implementation falls back to pointer-identity comparison and pointer-bit hashing.
For SET_TREE, hash is ignored. If cmp is NULL, the implementation falls back to pointer-identity comparison.
Core API
| Field | Meaning |
|---|---|
add |
inserts one element and returns true only when insertion happened |
contains |
returns whether an element is present |
remove |
removes one element and returns whether removal happened |
size |
returns the current count |
to_list |
returns an allocated list container of stored element pointers |
add_bulk |
inserts all pointers from an array |
free |
frees set storage |
add_bulk skips duplicates according to the set comparator. If the set is NULL, the pointer array is NULL, or count <= 0, it does nothing.
Choose the Variant
Use SET_HASH when membership speed is the point and order does not matter.
Use SET_TREE when you need a materialized ordered result later through to_list.
For SET_TREE, to_list returns elements in comparator order.
For SET_HASH, to_list returns all elements but promises no order.
Null-Element Rule
add, contains, and remove reject NULL element pointers and return false.
That is stricter than the map API, which can store a NULL value and, with the right callbacks, even a NULL key.
Set Algebra
The algebra helpers are:
| Field | Meaning |
|---|---|
union_with |
returns a new set with elements from both operands |
intersection_with |
returns a new set with shared elements |
difference_with |
returns a new set with elements in a but not in b |
is_subset_of |
returns whether a is a subset of b |
These helpers require strict compatibility:
The sets must use the same implementation family.
The comparator pointers must be the same pointer.
If hashing is involved, the hash-function pointers must also be the same pointer.
If those rules are not met, the algebra helpers return NULL or false.
Ownership and Cleanup
Sets own internal storage only. They do not own stored payload pointers.
The list returned by to_list is caller-owned, but the payload pointers inside that list are the stored set elements, not copies.
Destroy the set with s->free(s) and destroy result lists with list->free.
Read Next
If you need key-value pairs, move to Maps. If you need ordered key-value lookup, range queries, predecessor, or successor, move to Trees.