Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 8 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@ Ziglang-Set: a generic and general-purpose Set implementation for Zig. <br/>

#

A set offers a fast way to manipulate data and avoid excessive looping.

Zig currently [does not have](https://github.com/ziglang/zig/issues/6919) a built-in, general purpose Set data structure at this point in time. Until it does, try this!

Rationale: It may be common knowledge that a dictionary, map or hashset can be used as a set with a value of `void`. While this is true, there's a lot to think about in terms of supporting all the common set operations in a performant and correct way and there's no good reason why a common module for this shouldn't exist. After studying the Zig stdlib, I'm hoping this implementation can fill that gap and provide some value.
Rationale: It may be common knowledge that a dictionary, map or hashset can be used as a set with a value of `void`. While this is true, there's a lot to think about in terms of supporting all the common set operations in a performant and correct way and there's no good reason why a common module for this shouldn't exist. I'm hoping this implementation can fill that gap and provide some value after being modeled similar to other collections in Zig's stdlib.

#

This module offers a Set implementation built in the same vein and spirit of the other data structures within the Zig standard library. This is my attempt to model one that can get better over time and grow with community interest and support. See a problem, file a bug! Or better yet contribute and let's build the best implementation together.
This module offers a Set implementation built in the same vein and spirit of the other data structures within the Zig standard library. This is an attempt to model one that can get better over time and grow with community interest and support. See a problem, file a bug! Or better yet contribute and let's build the best implementation together.

I am the original author of the popular Go based set package: [golang-set](https://github.com/deckarep/golang-set) that is used by software components built by Docker, 1Password, Ethereum, SendGrid, CrowdStrike and HashiCorp. At just shy of `4.5k stars`, I figured I'd take a crack at building a comprehensive and generic Zig-based set that goes above and beyond the original Go implementation. After using Zig for over 3+ years on personal projects, I thought it was time that Zig had a robust Set implementation for itself.
I am the original author of a popular Go based set package: [golang-set](https://github.com/deckarep/golang-set) that is used by software components built by Docker, 1Password, Ethereum, SendGrid, CrowdStrike and HashiCorp. At just shy of `4.7k stars`, I figured I'd take a crack at building a comprehensive and generic Zig-based set that goes above and beyond the original Go implementation. After using Zig for over 3+ years on personal projects, I thought it was time that Zig had a robust Set implementation for itself.

This implementation gives credit and acknowledgement to the [Zig language](https://ziglang.org) and powerful [Std Library](https://ziglang.org/documentation/master/std/#std) [HashMap](https://ziglang.org/documentation/master/std/#std.hash_map.HashMap) data structure of which this set implementation is built on top of. Without that, this probably wouldn't exist. Efforts will be made to keep the Ziglang Set code fast and straightforward but this Set's raw speed will largely be bounded by the performance of the Zig HashMap of which it is built on top of.

Expand All @@ -38,11 +40,7 @@ This implementation gives credit and acknowledgement to the [Zig language](https
* A few flavors to choose from
* NOTE: Future versions of Zig [will be deprecating the `managed` variants](https://ziglang.org/download/0.14.0/release-notes.html#Embracing-Unmanaged-Style-Containers), and this repo will be following suit.
* Hash-based: everyday usecase, optimized for lookups primarily, insertion/removal secondarily - [further reading](https://devlog.hexops.com/2022/zig-hashmaps-explained/)
* HashSetManaged - initializes with an allocator and holds it internally (built on top of unmanaged)
* HashSetUnmanaged - does not hold an allocator, smaller footprint
* Array-based: more specialized, iteration much faster, insertion order preserved, indexing into underylying data - [further reading](https://devlog.hexops.com/2022/zig-hashmaps-explained/)
* ArrayHashSetManaged - initializes with an allocator and holds it internally (built on top of unmanaged)
* ArrayHashSetUnmanaged - does not hold an allocator, smaller footprint
* Common set operations
* add, append, appendSlice
* remove, removeAll
Expand All @@ -64,10 +62,9 @@ This implementation gives credit and acknowledgement to the [Zig language](https
* Custom hash function support
* "string" support
* Benchmarks

#
#### Why use a set?
* A set offers a fast way to manipulate data and avoid excessive looping. Look into it as there is already tons of literature on the advantages of having a set in your arsenal of tools.
#

#### Example
```zig
// import the namespace.
Expand Down Expand Up @@ -220,7 +217,7 @@ zig build test

```sh
# With Zig installed:
zigup build docs && cp -a zig-out/docs/. docs/
zig build docs && cp -a zig-out/docs/. docs/

# Alternatively, using Zigup:
zigup run <zig-version> build docs && cp -a zig-out/docs/. docs/
Expand Down
10 changes: 4 additions & 6 deletions build.zig.zon
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
.{
.name = .ziglangSet,
.version = "0.0.1",
.version = "0.1.0",
.fingerprint = 0x65aa5acd2ef4855,
.minimum_zig_version = "0.15.1",
.minimum_zig_version = "0.16.0",

.dependencies = .{},

.paths = .{
"LICENSE",
"build.zig",
"build.zig.zon",
"src/array_hash_set/managed.zig",
"src/array_hash_set/unmanaged.zig",
"src/hash_set/managed.zig",
"src/hash_set/unmanaged.zig",
"src/hash_set.zig",
"src/array_hash_set.zig",
"src/root.zig",
},
}
18 changes: 17 additions & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,15 @@
code a {
color: #000000;
}
.source-code {
display: grid;
grid-template-columns: auto 1fr;
align-items: start;
}
.source-line-numbers pre {
text-align: right;
color: #666;
}
#listFields > div, #listParams > div {
margin-bottom: 1em;
}
Expand Down Expand Up @@ -429,7 +438,14 @@ <h2>Example Usage</h2>
</div>
<div id="sectSource" class="hidden">
<h2>Source Code</h2>
<pre><code id="sourceText"></code></pre>
<div class="source-code">
<div class="source-line-numbers">
<pre><code id="sourceLineNumbers"></code></pre>
</div>
<div class="source-text">
<pre><code id="sourceText"></code></pre>
</div>
</div>
</div>
</section>
<div id="helpDialog" class="hidden">
Expand Down
25 changes: 22 additions & 3 deletions docs/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
const domSectTypes = document.getElementById("sectTypes");
const domSectValues = document.getElementById("sectValues");
const domSourceText = document.getElementById("sourceText");
const domSourceLineNumbers = document.getElementById("sourceLineNumbers");
const domStatus = document.getElementById("status");
const domTableFnErrors = document.getElementById("tableFnErrors");
const domTldDocs = document.getElementById("tldDocs");
Expand Down Expand Up @@ -129,6 +130,11 @@
domSearch.addEventListener('input', onSearchChange, false);
window.addEventListener('keydown', onWindowKeyDown, false);
onHashChange(null);
if (domSearch.value) {
// user started typing a search query while the page was loading
curSearchIndex = -1;
startAsyncSearch();
}
});
});

Expand Down Expand Up @@ -233,6 +239,7 @@
href: location.hash,
}]);

domSourceLineNumbers.innerHTML = declLineNumbersHtml(decl_index);
domSourceText.innerHTML = declSourceHtml(decl_index);

domSectSource.classList.remove("hidden");
Expand Down Expand Up @@ -384,6 +391,7 @@
if (members.length !== 0 || fields.length !== 0) {
renderNamespace(decl_index, members, fields);
} else {
domSourceLineNumbers.innerHTML = declLineNumbersHtml(decl_index);
domSourceText.innerHTML = declSourceHtml(decl_index);
domSectSource.classList.remove("hidden");
}
Expand Down Expand Up @@ -414,6 +422,7 @@
renderErrorSet(base_decl, errorSetNodeList(decl_index, errorSetNode));
}

domSourceLineNumbers.innerHTML = declLineNumbersHtml(decl_index);
domSourceText.innerHTML = declSourceHtml(decl_index);
domSectSource.classList.remove("hidden");
}
Expand All @@ -428,6 +437,7 @@
domTldDocs.classList.remove("hidden");
}

domSourceLineNumbers.innerHTML = declLineNumbersHtml(decl_index);
domSourceText.innerHTML = declSourceHtml(decl_index);
domSectSource.classList.remove("hidden");
}
Expand Down Expand Up @@ -643,27 +653,32 @@
}

function onHashChange(state) {
// Use a non-null state value to prevent the window scrolling if the user goes back to this history entry.
history.replaceState({}, "");
navigate(location.hash);
if (state == null) window.scrollTo({top: 0});
}

function onPopState(ev) {
onHashChange(ev.state);
syncDomSearch();
}

function navigate(location_hash) {
updateCurNav(location_hash);
if (domSearch.value !== curNavSearch) {
domSearch.value = curNavSearch;
}
render();
if (imFeelingLucky) {
imFeelingLucky = false;
activateSelectedResult();
}
}

function syncDomSearch() {
if (domSearch.value !== curNavSearch) {
domSearch.value = curNavSearch;
}
}

function activateSelectedResult() {
if (domSectSearchResults.classList.contains("hidden")) {
return;
Expand Down Expand Up @@ -908,6 +923,10 @@
return unwrapString(wasm_exports.decl_source_html(decl_index));
}

function declLineNumbersHtml(decl_index) {
return unwrapString(wasm_exports.decl_line_numbers_html(decl_index));
}

function declDoctestHtml(decl_index) {
return unwrapString(wasm_exports.decl_doctest_html(decl_index));
}
Expand Down
Binary file modified docs/main.wasm
Binary file not shown.
Binary file modified docs/sources.tar
Binary file not shown.
10 changes: 5 additions & 5 deletions src/array_hash_set.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// Open Source Initiative OSI - The MIT License (MIT):Licensing
/// The MIT License (MIT)
/// Copyright (c) 2025 Ralph Caraveo (deckarep@gmail.com)
/// Copyright (c) 2026 Ralph Caraveo (deckarep@gmail.com)
/// Permission is hereby granted, free of charge, to any person obtaining a copy of
/// this software and associated documentation files (the "Software"), to deal in
/// the Software without restriction, including without limitation the rights to
Expand Down Expand Up @@ -69,11 +69,11 @@ pub fn ArraySet(comptime E: type) type {
};

const Self = @This();

pub const empty: Self = .{
.unmanaged = Map{},
};

// pub fn init() Self {
// return .{
// .unmanaged = Map{},
Expand All @@ -86,7 +86,7 @@ pub fn ArraySet(comptime E: type) type {
return self;
}

/// TODO: zig has still not changed neither of the two maps from selectMap 0.16,
/// TODO: zig has still not changed neither of the two maps from selectMap 0.16,
/// so we need to pass the allocator to deinit that.
pub fn deinit(self: *Self, allocator: Allocator) void {
self.unmanaged.deinit(allocator);
Expand Down Expand Up @@ -827,6 +827,6 @@ test "removals" {
test "sizeOf matches" {
// No bloat guarantee, after all we're just building on top of what's good.
const expectedByteSize = 40;
try expectEqual(expectedByteSize, @sizeOf(std.array_hash_map.AutoArrayHashMapUnmanaged(u32, void)));
try expectEqual(expectedByteSize, @sizeOf(std.AutoArrayHashMapUnmanaged(u32, void)));
try expectEqual(expectedByteSize, @sizeOf(ArraySet(u32)));
}
16 changes: 8 additions & 8 deletions src/hash_set.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// Open Source Initiative OSI - The MIT License (MIT):Licensing
/// The MIT License (MIT)
/// Copyright (c) 2025 Ralph Caraveo (deckarep@gmail.com)
/// Copyright (c) 2026 Ralph Caraveo (deckarep@gmail.com)
/// Permission is hereby granted, free of charge, to any person obtaining a copy of
/// this software and associated documentation files (the "Software"), to deal in
/// the Software without restriction, including without limitation the rights to
Expand Down Expand Up @@ -72,7 +72,7 @@ pub fn HashSetWithContext(comptime E: type, comptime Context: type, comptime max
pub const Iterator = Map.KeyIterator;

const Self = @This();

pub const empty: Self = if (@sizeOf(Context) == 0) .{
.unmanaged = Map{},
.context = if (Context == void) {} else undefined,
Expand Down Expand Up @@ -105,7 +105,7 @@ pub fn HashSetWithContext(comptime E: type, comptime Context: type, comptime max
}

/// Destroys the unmanaged Set.
/// TODO: zig has still not changed the HashMap in 0.16, so we need to pass
/// TODO: zig has still not changed the HashMap in 0.16, so we need to pass
/// the allocator here. It needs to be removed.
pub fn deinit(self: *Self, allocator: Allocator) void {
self.unmanaged.deinit(allocator);
Expand Down Expand Up @@ -251,10 +251,10 @@ pub fn HashSetWithContext(comptime E: type, comptime Context: type, comptime max
/// and other. This set will contain all elements of this set that are not
/// also elements of other.
pub fn differenceUpdate(self: *Self, other: Self) Allocator.Error!void {
var iter = other.iterator();
while (iter.next()) |key_ptr| {
_ = self.remove(key_ptr.*);
var iter = other.iterator();

while (iter.next()) |key_ptr| {
_ = self.remove(key_ptr.*);
}
}

Expand Down Expand Up @@ -344,7 +344,7 @@ pub fn HashSetWithContext(comptime E: type, comptime Context: type, comptime max

for (to_remove.items) |item| {
_ = self.remove(item);
}
}
}

/// isDisjoint returns true if the intersection between two sets is the null set.
Expand Down
23 changes: 21 additions & 2 deletions src/main.zig
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
/// Open Source Initiative OSI - The MIT License (MIT):Licensing
/// The MIT License (MIT)
/// Copyright (c) 2026 Ralph Caraveo (deckarep@gmail.com)
/// Permission is hereby granted, free of charge, to any person obtaining a copy of
/// this software and associated documentation files (the "Software"), to deal in
/// the Software without restriction, including without limitation the rights to
/// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
/// of the Software, and to permit persons to whom the Software is furnished to do
/// so, subject to the following conditions:
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///
///
const std = @import("std");
const set = @import("root.zig");

Expand All @@ -20,12 +40,11 @@ pub fn main(init: std.process.Init) void {
// now we can initialize a HashSet with empty if no context is provided
var A: HashSet(u32) = .empty;
defer A.deinit(gpa);

var B: ArraySet(u32) = .empty;
defer B.deinit(gpa);

const ctx = SimpleHasher{};
var C: set.HashSetContext(u32, SimpleHasher, 75) = .initContext(ctx);
defer C.deinit(gpa);

}
4 changes: 1 addition & 3 deletions src/root.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// Open Source Initiative OSI - The MIT License (MIT):Licensing
/// The MIT License (MIT)
/// Copyright (c) 2025 Ralph Caraveo (deckarep@gmail.com)
/// Copyright (c) 2026 Ralph Caraveo (deckarep@gmail.com)
/// Permission is hereby granted, free of charge, to any person obtaining a copy of
/// this software and associated documentation files (the "Software"), to deal in
/// the Software without restriction, including without limitation the rights to
Expand All @@ -18,7 +18,6 @@
/// SOFTWARE.
///
///

/// Set is just a short convenient "default" alias. If you don't know
/// which to pick, just use Set.
pub const Set = HashSet;
Expand All @@ -30,7 +29,6 @@ pub const HashSetContext = @import("hash_set.zig").HashSetWithContext;
/// This is a bit more specialized and optimized for heavy iteration.
pub const ArraySet = @import("array_hash_set.zig").ArraySet;


test "tests" {
_ = @import("hash_set.zig");
_ = @import("array_hash_set.zig");
Expand Down
Loading