std/set

March 14, 2026 ยท View on GitHub

Set<T> is a generic hash set implementation for storing unique values of type T. It uses an open-addressing hash table with linear probing.

Overview

  • Generic: Stores any type T.
  • Unique: Automatically handles duplicates; adding an existing element returns false.
  • Fast: O(1) average time complexity for additions, removals, and lookups.
  • RAII: Implements the Drop trait for automatic memory management.

Usage

import "std/set.zc"

fn main() {
    let s = Set<int>::new();
    
    s.add(10);
    s.add(20);
    s.add(10); // Duplicate, returns false
    
    if (s.contains(10)) {
        println "Set contains 10";
    }
    
    s.remove(20);
    println "Length: {s.length()}";
} // s is freed automatically here

Struct Definition

struct Set<T> {
    data: T*;
    len: usize;
    cap: usize;
    // ... internal fields
}

Methods

Construction

MethodSignatureDescription
newSet<T>::new() -> Set<T>Creates a new, empty set.

Modification

MethodSignatureDescription
addadd(self, val: T) -> boolAdds a value to the set. Returns true if added, false if already present.
removeremove(self, val: T) -> boolRemoves a value from the set. Returns true if present and removed.
clearclear(self)Removes all elements from the set without freeing allocated memory.

Access & Query

MethodSignatureDescription
containscontains(self, val: T) -> boolReturns true if the value exists in the set.
lengthlength(self) -> usizeReturns the number of unique elements.
is_emptyis_empty(self) -> boolReturns true if the set has no elements.
capacitycapacity(self) -> usizeReturns the current internal capacity.

Utility

MethodSignatureDescription
is_slot_occupiedis_slot_occupied(self, idx: usize) -> boolChecks if a specific internal hash slot is occupied.
val_atval_at(self, idx: usize) -> Option<T>Returns the value at a specific internal slot, if any.

Memory Management

MethodSignatureDescription
freefree(self)Manually frees the set's internal buffers.
Traitimpl Drop for SetAutomatically calls free() when the set goes out of scope.