avatar_url stringlengths 47 116 ⌀ | name stringlengths 1 46 | full_name stringlengths 7 60 | created_at stringdate 2016-04-01 08:17:56 2025-05-20 11:38:17 | description stringlengths 0 387 ⌀ | default_branch stringclasses 44
values | open_issues int64 0 4.93k | stargazers_count int64 0 78.2k | forks_count int64 0 3.09k | watchers_count int64 0 78.2k | tags_url stringlengths 0 94 | license stringclasses 27
values | topics listlengths 1 20 | size int64 0 4.82M | fork bool 2
classes | updated_at stringdate 2018-11-13 14:41:18 2025-05-22 08:23:54 | has_build_zig bool 2
classes | has_build_zig_zon bool 2
classes | zig_minimum_version stringclasses 50
values | repo_from stringclasses 3
values | dependencies listlengths 0 38 | readme_content stringlengths 0 437k | dependents listlengths 0 21 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://avatars.githubusercontent.com/u/200686?v=4 | zigualizer | deckarep/zigualizer | 2024-11-17T05:34:00Z | Zigualizer: A music visualizer built with Zig, powered by the FFT algorithm. | main | 0 | 29 | 1 | 29 | https://api.github.com/repos/deckarep/zigualizer/tags | MIT | [
"fft",
"music",
"raylib",
"spectrum-analyzer",
"visualizer",
"zig",
"zig-package",
"ziglang"
] | 9,397 | false | 2025-04-03T15:55:29Z | true | true | 0.13.0 | github | [] | zigualizer
Zigualizer: A music visualizer built with Zig, powered by the FFT algorithm.
<a>Click here</a> for a demo on YouTube!
Details
This implementation was originally based on the <a>Musializer project by @Tsoding</a>.
This version as it stands has been tested to work with Raylib 5.0.
I have modified this version to be backed by a generic circular buffer over a
fixed size array. Additionally, I am leveraging comptime in a few spots to
generate some static windowing functions.
Raylib integration
For a more thorough example see raylib.zig in the examples/ folder.
Integration is a 4-step process (aside from music stream code).
```zig
// 1. Import
const fft = @import("zigualizer");
// 2. Init
fft.FFT_Analyzer.reset();
// After loading up a Raylib Music stream.
track = c.LoadMusicStream(pathToTrack);
defer c.UnloadMusicStream(track);
// 3. Attach
c.AttachAudioStreamProcessor(track.stream, fft.FFT_Analyzer.fft_process_callback);
c.PlayMusicStream(track);
// In your update loop
fn update() void {
c.UpdateMusicStream(track);
// 4. Analyze
frames = fft.FFT_Analyzer.analyze(c.GetFrameTime());
}
// In your draw loop render the FFT however you like!
fn draw() void {
c.BeginDrawing();
defer c.EndDrawing();
c.ClearBackground(c.BLACK);
<code>// 5. Draw
renderFFT(400, 200);
</code>
}
```
Building the examples
```sh
Run the Raylib demo.
zig build -Dexample-name=raylib.zig && zig-out/example/raylib
``` | [] |
https://avatars.githubusercontent.com/u/7109515?v=4 | zig-c-tutorial | ramonmeza/zig-c-tutorial | 2024-11-07T04:32:55Z | Learn to create Zig bindings for C libraries! | main | 0 | 29 | 2 | 29 | https://api.github.com/repos/ramonmeza/zig-c-tutorial/tags | - | [
"binding",
"c",
"compiling",
"linking",
"shared",
"static",
"wrapper",
"zig",
"zig-program"
] | 33 | false | 2025-05-13T08:40:02Z | true | true | unknown | github | [] | Understanding How Zig and C Interact
A journey to understanding how Zig interacts with C and how someone not
well-versed in C can leverage the power of third-party C libraries.
What This Doesn't Cover
<ul>
<li>Using Zig in C</li>
<li>Using C</li>
<li>C at all</li>
</ul>
TOC
<ul>
<li><a>Utilizing This Project</a><ul>
<li><a>Zig Build Commands</a></li>
</ul>
</li>
<li><a>The Journey</a><ul>
<li><a>Create a Simple C application</a></li>
<li><a>Compiling the application using <code>zig cc</code></a></li>
<li><a>Leverage Zig's build system to build the C application</a></li>
<li><a>Create a Zig application that links to the C library</a></li>
<li><a>Using Zig to build a C Library</a></li>
<li><a>Create a Zig wrapper around a C Function</a></li>
<li><a>Linking to the Static/Shared Library</a></li>
</ul>
</li>
<li><a>Side Quests</a><ul>
<li><a>Testing C code in Zig</a></li>
</ul>
</li>
<li><a>Resources</a></li>
<li><a>Thanks</a></li>
</ul>
Utilizing this Project
Zig Build Commands
```sh
zig build [steps] [options]
Steps:
install (default) Copy build artifacts to prefix path
uninstall Remove build artifacts from prefix path
c_app Run a C application built with Zig's build system.
zig_app Run a Zig application linked to C source code.
zmath_static Create a static library from C source code.
zmath_shared Create a shared library from C source code.
zig_app_shared Run a Zig application that is linked to a shared library.
zig_app_static Run a Zig application that is linked to a static library.
tests Run a Zig tests of C source code.
```
The Journey
Create a Simple C Application
Let's create a simple math library in C, with functions declared in a header
file and implemented in the source file.
<a><code>zmath.h</code></a>
<code>c
extern int add(int a, int b);
extern int sub(int a, int b);</code>
<em>Note: <code>extern</code> is used here to export our functions.</em>
<a><code>zmath.c</code></a>
```c
include "zmath.h"
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
```
Next we create a simple application to utilize this library.
<a><code>c_app.c</code></a>
```c
include
include "zmath.h"
int main(void) {
int a = 10;
int b = 5;
<code>int resultAdd = add(a, b);
printf("%d + %d = %d\n", a, b, resultAdd);
int resultSub = sub(a, b);
printf("%d - %d = %d\n", a, b, resultSub);
return 0;
</code>
}
```
Compiling the application using <code>zig cc</code>
If you're familiar with <code>gcc</code>, this is no problem. Here's the command to compile
this application:
<code>sh
zig cc -Iinclude src/c_app.c src/zmath.c -o zig-out/bin/c_app.exe</code>
<em>The nice part about Zig is that it's a cross-compiler, so feel free to ignore that I'm on Windows.</em>
Now run the resulting executable:
```sh
<blockquote>
./zig-out/bin/c_app.exe
10 + 5 = 15
10 - 5 = 5
```
</blockquote>
Leverage Zig's build system to build the C application
Now we can create a file called <code>build.zig</code>, which Zig will use to build our application.
<a><code>build.zig</code></a>
```c
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const exe = b.addExecutable(.{
.name = "c_app",
.target = target,
.optimize = optimize,
});
exe.addIncludePath(b.path("include"));
exe.addCSourceFiles(.{
.files = &[_][]const u8{
"src/main.c",
"src/zmath.c"
}
});
exe.linkLibC();
b.installArtifact(exe);
</code>
}
```
Things to note:
- <code>b.addExecutable()</code> allows us to create an executable with given options, in
this case default target options and optimizations. It also allows us to name
our executable.
- <code>exe.addIncludePath()</code> takes a <code>LazyPath</code>, and it just so happens that
<code>std.Build</code> (the type of <code>b</code>) contains a function to return a <code>LazyPath</code> object
given a string.
- <code>exe.addCSourceFiles()</code> takes a <code>struct</code> that includes a <code>files</code> property.
This property is a pointer to an array of strings. I'll break down
<code>&[_][]const u8 {}</code> real quick in plain English:
```c
&[_][]const u8 {
"..",
"...",
// etc
}
// const u8 is a character
// []const u8 is an array of characters, or a string
// [<em>] is zig for "create an array with size automatically determined at compile time"
// [</em>][]const u8 is an array of strings
// & gives us a pointer to an object's memory address
// &[_][]const u8 is a pointer to an array of strings
// a reference to an automatically sized array of array of constants u8 objects.
// a pointer to the address in memory where an array of arrays of u8 exists
```
<em>Probably overkill of an explanation, but maybe someone will benefit from this.</em>
<ul>
<li>Next is <code>exe.linkLibC()</code>. This is the extremely convenient way that Zig links
to libc. There's also <code>linkLibCpp()</code>, which could be useful to keep in mind. If
you use a standard library, such as <code>stdio.h</code>, make sure to include <code>linkLibC()</code>,
otherwise you'll get a compilation error when trying to build.</li>
</ul>
Now we kick off the Zig build process:
<code>sh
zig build</code>
And run the resulting executable:
<code>sh
./zig-out/bin/c_compiled_with_zig_build.exe
10 + 5 = 15
10 - 5 = 5</code>
Same results as compiling with <code>zig cc</code>! Very cool. Let's move on to using a bit more Zig.
Create a Zig application that links to the C library
Basically, we want to recreate <code>c_app.c</code> in Zig. In this case, this is trivial.
<a><code>zig_app.zig</code></a>
```c
const std = @import("std");
const zmath = @cImport(@cInclude("zmath.h"));
pub fn main() !void {
const stdio = std.io.getStdOut().writer();
<code>const a = 10;
const b = 5;
const resultAdd = zmath.add(a, b);
try stdio.print("{} + {} = {}\n", .{ a, b, resultAdd });
const resultSub = zmath.sub(a, b);
try stdio.print("{} - {} = {}\n", .{ a, b, resultSub });
</code>
}
```
This is fairly simple to understand. What's important is that we are including
our C headers using Zig's <code>@cImport()</code> and <code>@cInclude()</code>.
Next we have to modify <code>build.zig</code> and point it to our <code>zig_app.zig</code> file
instead of <code>c_app.c</code>.
<a><code>build.zig</code></a>
```c
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const exe = b.addExecutable(.{
.name = "build_zig_linked_to_c",
.root_source_file = b.path("src/zig_app.zig"),
.target = target,
.optimize = optimize,
});
exe.addIncludePath(b.path("include"));
exe.addCSourceFile(.{
.file = b.path("src/zmath.c"),
});
exe.linkLibC();
return exe;
</code>
}
```
The only thing to pay attention to here is the <code>root_source_file</code> parameter in
<code>addExecutable()</code>. Here we point to a Zig file with <code>pub fn main() void</code>
implemented. This is a drop in replacement of <code>c_app.c</code>, or rather a Zig file
using a C library (when source code is available).
Using Zig to build a C Library
Up until now, we've been utilizing the C source code, since it's available to us,
but this is not always the case. Sometimes we may have a static or shared library
that we need to link against, rather than compiling the source code ourselves.
<em>If you want a deeper understanding of static and shared libraries, check out
the links in the <a>Resources</a> section.</em>
<a><code>build.zig</code></a>
```c
const std = @import("std");
pub fn build(b: <em>std.Build) </em>std.Build.Step.Compile {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const lib = b.addStaticLibrary(.{
.name = "zmath_static",
.target = target,
.optimize = optimize,
});
lib.addIncludePath(b.path("include"));
lib.addCSourceFiles(.{ .files = &[_][]const u8{"src/zmath.c"} });
lib.linkLibC();
b.installArtifact(lib);
</code>
}
```
We add our source files, include directory, link it to libc and install it.
When we run <code>zig build</code>, our library will be compiled to a static library file,
<code>zig-out/lib/zmath-static.lib</code>.
If you want to compile shared libraries instead, there's not much difference.
Instead of <code>b.addStaticLibrary()</code>, use <code>b.addSharedLibrary()</code>.
<em><a>See the difference in build.zig</a></em>
Create a Zig wrapper around a C Function
This is a simple example, so wrapping the C function in Zig may be overkill.
Either way, the idea is to wrap the call to our C functions in Zig, such that we
have a Zig interface between our application code and our C code. This allows us
to handle errors in a Zig fashion and pass proper types to the C code while
exposing them to the application code.
For this we'll create a new Zig file, <code>zmath_ext.zig</code>
<a><code>zmath_ext.zig</code></a>
```c
const zmath_h = @cImport(@cInclude("zmath.h"));
pub extern fn add(a: c_int, b: c_int) callconv(.C) c_int;
pub extern fn sub(a: c_int, b: c_int) callconv(.C) c_int;
```
This file is a declaration of external functions we wish to use in Zig. We'll
next create a <code>zmath.zig</code>, in which we will create Zig functions that will
expose Zig data types through our API and cast the parameters to their
corresponding C data types before calling the C functions.
<a><code>zmath.zig</code></a>
```c
const zmath_ext = @import("zmath_ext.zig");
pub fn add(a: i32, b: i32) !i32 {
const x = @as(c_int, @intCast(a));
const y = @as(c_int, @intCast(b));
return zmath_ext.add(x, y);
}
pub fn sub(a: i32, b: i32) !i32 {
const x = @as(c_int, @intCast(a));
const y = @as(c_int, @intCast(b));
return zmath_ext.sub(x, y);
}
```
As you can see, we translate the C types to Zig specific types for use in Zig
applications. We cast our input parameters to their C equivalent (<code>c_int</code>) for
the C function's parameters. You'll also notice the return type contains <code>!</code>,
meaning these functions will now return errors. This means within our
application, we'll need to call the function with <code>try</code>.
We'll create a new zig file for trying out the wrapper functions, called
<code>zig_c_wrapper.zig</code>. This is mostly to distinguish between our previous examples,
but this is just showing we no longer use <code>@cImport()</code> directly, and instead
utilize <code>zmath.zig</code> (our wrapper functions), to interact with the C code.
<a><code>zig_c_wrapper.zig</code></a>
```c
const std = @import("std");
const zmath = @import("zmath.zig");
pub fn main() !void {
const stdio = std.io.getStdOut().writer();
<code>const a = 10;
const b = 5;
const resultAdd = try zmath.add(a, b);
try stdio.print("{d} + {d} = {d}\n", .{ a, b, resultAdd });
const resultSub = try zmath.sub(a, b);
try stdio.print("{d} - {d} = {d}\n", .{ a, b, resultSub });
</code>
}
```
Linking to the Static/Shared Library
With this in place, and our static/shared library created, we can use <code>build.zig</code>
to link our application to our library.
<a><code>build.zig</code> for static libray</a>
```c
const std = @import("std");
pub fn build(b: <em>std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) </em>std.Build.Step.Compile {
const exe = b.addExecutable(.{
.name = "zig_app_shared",
.root_source_file = b.path("src/zig_c_wrapper.zig"),
.target = target,
.optimize = optimize,
});
<code>exe.addObjectFile(b.path("zig-out/lib/zmath-shared.lib"));
return exe;
</code>
}
```
It would be wise to note that here we built our library and then import it from
a path (using <code>addObjectFile()</code>). If you build from source, use <code>addObject(*Compile)</code>
instead and pass in the proper object. This is because Zig will compile faster
than your OS can save the library file, causing the build to fail because the
library file could not be found during the build time of this object (at least
when using <code>dependsOn()</code>, like we do in the main <a><code>build.zig</code></a> file
for this repo).
Side Quests
Some extra thoughts about working with Zig and intergrating/interacting with C.
Testing C code in Zig
I was curious if I could use Zig's testing features to test C code. There's
literally no reason why you couldn't, so here's how you do it.
<a><code>test_zmath.zig</code></a>
```c
const std = @import("std");
const testing = std.testing;
const zmath = @cImport(@cInclude("zmath.h"));
test "zmath.add() works" {
try testing.expect(zmath.add(1, 2) == 3);
try testing.expect(zmath.add(12, 12) == 24);
}
test "zmath.sub() works" {
try testing.expect(zmath.sub(2, 1) == 1);
try testing.expect(zmath.sub(12, 12) == 0);
}
```
<em>Strive to write good tests, this is just a proof of concept.</em>
<a><code>build.zig</code></a>
```c
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const tests_exe = b.addTest(.{
.name = "test_zmath",
.root_source_file = b.path("tests/test_zmath.zig"),
.target = target,
.optimize = optimize,
});
tests_exe.addIncludePath(b.path("include"));
tests_exe.addCSourceFile(.{
.file = b.path("src/zmath.c"),
});
tests_exe.linkLibC();
b.installArtifact(tests_exe);
</code>
}
```
Resources
<ul>
<li>https://mtlynch.io/notes/zig-call-c-simple/
What initially made me want to tackle this subject, this article is a great
starting point for understanding C and Zig.</li>
<li><a>Wikipedia article for "Shared Library"</a></li>
<li><a>Wikipedia article for "Static Library"</a></li>
<li><a>Discussion about this repository on Ziggit</a></li>
</ul>
Thanks
That's it. It was a long journey, but one that came with lots of learning and
experimenting. Zig is wonderful and being able to use C code without having to
use C is a game changer for me.
Thanks for sticking around and reading. If you have feedback or suggestions,
please don't hesitate to create an issue and we can work through it together.
<ul>
<li>Ramon</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/32778608?v=4 | zig-ebpf | anoushk1234/zig-ebpf | 2024-08-21T06:43:36Z | Zig virtual machine for eBPF programs. | main | 2 | 27 | 3 | 27 | https://api.github.com/repos/anoushk1234/zig-ebpf/tags | Apache-2.0 | [
"assembler",
"bpf",
"ebpf",
"interpreter",
"packet-filtering",
"zig"
] | 5,882 | false | 2025-04-13T06:26:56Z | true | true | unknown | github | [] | eBPF in Zig ⚡️
This is a wip implementation of eBPF in native Zig inspired by Quentin Monnet's <a>rbpf</a>. This is different from existing zig eBPF libraries as it implements the ISA natively in zig without depending on libbpf or any C modules.
What works
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> 64-bit ALU operations
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Memory operations
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Byteswap operations
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Branch instructions (needs more testing)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Syscalls
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> JIT Compiler
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Assembler (needs more testing)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Disassembler
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Unit Tests & Fuzzing
Why
Short answer: I was bored
Long answer: I wanted to work on something low level and complex, and also I really like Zig and wanted an excuse to write a large-ish project in it. I was inspired by Quentin Monnet and Solana Labs's work in rbpf and thought there should be a native Zig eBPF implementation. So I wanted to learn, experiment and have some fun in open source.
Contribution and Feedback
The author of this repo is new to Zig so if you feel there can be some improvements in making the code more idiomatic then PRs are welcome!
Following in the footsteps of rbpf, this project expects new commits to be coveryed by the <a>Developer's Ceritificate of Origin</a>.
License
zig-ebpf is distributed under both MIT License and Apache License(Version 2.0). | [] |
https://avatars.githubusercontent.com/u/46653655?v=4 | zdotenv | BitlyTwiser/zdotenv | 2024-09-20T15:12:28Z | Zdotenv - A port of Godotenv for Zig | main | 0 | 27 | 1 | 27 | https://api.github.com/repos/BitlyTwiser/zdotenv/tags | - | [
"dotenv",
"dotenv-parser",
"zig",
"ziglang"
] | 145 | false | 2025-03-03T01:47:31Z | true | true | unknown | github | [] |
Zdotenv is a simple .env parser and a port of godotenv and ruby dotenv, but with a smidge more simplicity.
Usage:
Add zdotenv to your zig project:
<code>zig fetch --save https://github.com/BitlyTwiser/zdotenv/archive/refs/tags/v0.1.1.tar.gz</code>
Add to build file:
<code>const zdotenv = b.dependency("zdotenv", .{});
exe.root_module.addImport("zdotenv", zdotenv.module("zdotenv"));</code>
Zdotenv has 2 pathways:
<ol>
<li>Absolute path to .env</li>
<li>
Expects an absolute path to the .env (unix systems expect a preceding / in the path)
<code>const z = try Zdotenv.init(std.heap.page_allocator);
// Must be an absolute path!
try z.loadFromFile("/home/<username>/Documents/gitclones/zdotenv/test-env.env");</code>
</li>
<li>
relaltive path:
</li>
<li>Expects the .env to be placed alongside the calling binary
<code>const z = try Zdotenv.init(std.heap.page_allocator);
try z.load();</code></li>
</ol>
Example from Main:
```
const std = @import("std");
const zdotenv = @import("lib.zig");
const assert = std.debug.assert;
/// The binary main is used for testing the package to showcase the API
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
<code>var dotenv = try zdotenv.Zdotenv.init(allocator);
try dotenv.load();
const env_map = try std.process.getEnvMap(allocator);
const pass = env_map.get("PASSWORD") orelse "foobar";
assert(std.mem.eql(u8, pass, "I AM ALIVE!!"));
</code>
}
```
Importing this into your own library, you will use <code>@import("zdotenv")</code>. Otherwise, this would be the same :)
C usage:
Zig (at the time of this writing) does not have a solid way of directly adjusting the env variables. Doing things like:
<code>var env_map = std.process.getEnvMap(std.heap.page_allocator);
env_map.put("t", "val");</code>
will only adjust the env map for the scope of this execution (i.e. scope of the current calling function). After function exit, the map goes back to its previous state.
Therefore, we do make a C call to store the env variables that are parsed. So linking libC and running tests with <code>--library c</code> is needed
Using the package is as simple as the above code examples. import below using zig zon, load the .env, and access the variables as needed using std.process.EnvMap :) | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zglfw | zig-gamedev/zglfw | 2024-11-03T21:42:48Z | Zig build package and bindings for GLFW | main | 5 | 26 | 23 | 26 | https://api.github.com/repos/zig-gamedev/zglfw/tags | MIT | [
"bindings",
"gamedev",
"glfw",
"zig"
] | 447 | false | 2025-05-15T17:23:57Z | true | true | 0.14.0 | github | [
{
"commit": "c0dbf11cdc17da5904ea8a17eadc54dee26567ec.tar.gz",
"name": "system_sdk",
"tar_url": "https://github.com/zig-gamedev/system_sdk/archive/c0dbf11cdc17da5904ea8a17eadc54dee26567ec.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/system_sdk"
}
] | <a>zglfw</a>
Zig build package and bindings for <a>GLFW 3.4</a>
Getting started
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ ... });
<code>const zglfw = b.dependency("zglfw", .{});
exe.root_module.addImport("zglfw", zglfw.module("root"));
if (target.result.os.tag != .emscripten) {
exe.linkLibrary(zglfw.artifact("glfw"));
}
</code>
}
```
Now in your code you may import and use <code>zglfw</code>:
```zig
const glfw = @import("zglfw");
pub fn main() !void {
try glfw.init();
defer glfw.terminate();
<code>const window = try glfw.createWindow(600, 600, "zig-gamedev: minimal_glfw_gl", null);
defer glfw.destroyWindow(window);
// or, using the equivilent, encapsulated, "objecty" API:
const window = try glfw.Window.create(600, 600, "zig-gamedev: minimal_glfw_gl", null);
defer window.destroy();
// setup your graphics context here
while (!window.shouldClose()) {
glfw.pollEvents();
// render your things here
window.swapBuffers();
}
</code>
}
```
See <a>zig-gamedev samples</a> for more complete usage examples. | [] |
https://avatars.githubusercontent.com/u/101147447?v=4 | zig_csv | matthewtolman/zig_csv | 2024-10-18T21:11:44Z | CSV tools (writing, parsing) for Zig | main | 0 | 24 | 3 | 24 | https://api.github.com/repos/matthewtolman/zig_csv/tags | MIT | [
"csv",
"zig",
"zig-library"
] | 200 | false | 2025-05-13T04:28:08Z | true | true | unknown | github | [] | ZCSV (Zig CSV)
<ul>
<li><a>Summary</a></li>
<li><a>Installation</a></li>
<li><a>Examples</a></li>
<li><a>Writing CSV</a></li>
<li><a>Reading a CSV</a></li>
<li><a>Map Parser</a></li>
<li><a>Column Parser</a></li>
<li><a>Slice Parser (zero-allocation)</a></li>
<li><a>Stream Parser (zero-allocation)</a></li>
<li><a>Parser Loop Limit Options</a></li>
<li><a>Changing delimiters, quotes, and newlines</a></li>
<li><a>Parser Builder</a></li>
<li><a>Memory Lifetimes</a></li>
<li><a>Utility Methods</a></li>
<li><a>Field Methods</a></li>
<li><a>Slice Methods</a></li>
<li><a>License</a></li>
</ul>
Summary
<blockquote>
Supported Zig versions: 0.13.0,0.14.0-dev.3280+bbd13ab96
</blockquote>
ZCSV is a CSV parser and writer library.
The CSV writer can encode many (but not all) built-in Zig datatypes. Alternatively, the writer can work with simple slices as well.
There are several parsers available with different tradeoffs between speed, memory usage, and developer experience.
The parsers are split into two main categories: allocating parsers and zero-allocation parsers. Generally, allocating parsers are easier to work with, but are slower while zero-allocation parsers are harder to work with. both writers and parsers which are allocation free while also having a parser which does use memory allocations for a more developer-friendly interface.
This library does allow customization of field and row delimiters, as well as the quoted character. It generally follows the CSV RFC with one key difference. The CSV RFC requires all newlines to be CRLF. However, this library provides parsers which allow for either CRLF newlines or LF newlines. This allows the parsers to parse both RFC-compliant CSV files and a few non-compliant CSV files.
Additionally, several utilities are provided to make working with CSVs slightly easier. Several decoding utilities exist to transform string field data into Zig primitives (such as field to integer). These utilities are opinionated to my use case, and are provided under their own namespace under <code>zcsv</code>. They are optional to use and can be safely ignored.
Note: All parsers do operate either line-by-line or field-by-field for all operations, including validation. This means that partial reads may happen when the first several rows of a file are valid but there is an error in the middle.
```zig
// Basic usage writing
const zcsv = @import("zcsv");
const std = @import("std");
// ....
// Get a destination writer
const stdout = std.io.getStdOut().writer();
// Get a CSV writer
const csv_out = zcsv.writer.init(stdout, .{});
// Write headers
try csv_out.writeRow(.{"field1", "field2", "field3", "field4"});
// Write a row
for (rowData) |elem| {
try csv_out.writeRow(.{elem.f1, elem.f2, elem.f3, elem.f4});
}
// Basic usage reading
// Get an allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Get a reader
const stdin = std.io.getStdIn().reader();
// Make a parser
var parser = zcsv.allocs.map.init(allocator, stdin, .{});
// Some allocating parsers need to be cleaned up
defer parser.deinit();
// Helper utility to convert CSV fields to ints
const fieldToInt = zcsv.decode.fieldToInt;
// Iterate over rows
while (parser.next()) |row| {
// Free row memory
defer row.deinit();
<code>const id_field = row.data().get("id") orelse return error.MissingIdColumn;
const id = fieldToInt(i64, id_field, 10) catch {
return error.InvalidIdValue;
} orelse return error.MissingIdValue;
std.debug.print("ID: {}\n", id);
</code>
}
// Zero-allocation parsing of an in-memory data structure
const csv =
\productid,productname,productsales
\1238943,"""Juice"" Box",9238
\3892392,"I can't believe it's not chicken!",480
\5934810,"Win The Fish",-
;
var parser = zcsv.zero_allocs.slice.init(csv, .{});
// Helper utility to write field strings to a writer
// Note: For this use case we could use field.decode(...)
// However, field.decode(...) only works with zero-allocation parsers,
// whereas writeFieldStrTo works with allocating and zero-allocation
// parsers
const writeFieldStrTo = zcsv.decode.writeFieldStrTo;
while (parser.next()) |row| {
// iterate over fields
var iter = row.iter();
<code>while (iter.next()) |field| {
// we need to manually decode fields to remove quotes
// we can opt out of decoding work for ignored fields
var decode_bytes: [256]u8 = undefined;
var decode_buff = std.io.fixedBufferStream(&decode_bytes);
try writeFieldStrTo(field, decode_buff.writer());
const decoded = decode_buff.getWritten();
// use decoded here
}
</code>
}
// check for errors
if (parser.err) |err| {
return err;
}
```
Installation
<ol>
<li>
Add zcsv as a dependency in your <code>build.zig.zon</code>:
<code>bash
zig fetch --save git+https://github.com/matthewtolman/zig_csv#main</code>
</li>
<li>
In your <code>build.zig</code>, add the <code>zcsv</code> module as a dependency to your program:
```zig
const zcsv = b.dependency("zcsv", .{
.target = target,
.optimize = optimize,
});
</li>
</ol>
exe.root_module.addImport("zcsv", zcsv.module("zcsv"));
```
Examples
The <code>examples/</code> folder holds a list of various examples. All of those examples are ran as part of the <code>zig build test</code> command. Each example also has it's own command to run just that example (e.g. <code>zig build example_1</code>).
Examples will use the <code>test.csv</code> file by default (assuming they read a file from disk). This file is provided to demonstrate different parsing scenarios.
Writing CSV
Writing CSV files is done line-by-line to a writer. The writing is done without dynamic memory allocation. Writing can be done by creating a CSV writer with <code>zcsv.writer.init</code> and then calling the <code>writeRow</code> and <code>writeRowStr</code> methods, or by calling <code>zcsv.writer.row</code> and <code>zcsv.writer.rowStr</code>. The advantage of creating a writer is that the writer will track the underlying <code>std.io.Writer</code> and parser options, whereas those options must be passed to the function variants manually.
The <code>writeRow</code> and <code>row</code> methods take a tuple of values and will encode most (but not all) builtin Zig values. However, this does require that a developer knows how many columns are needed at compile time. Alternatively, the <code>writeRowStr</code> and <code>rowStr</code> methods take a slice of byte slices (i.e. a slice of strings). This allows developers to pass in arbitrarily sized rows at runtime for encoding.
```zig
// Basic usage
const zcsv = @import("zcsv");
const std = @import("std");
// ....
// Get an output writer
const stdout = std.io.getStdOut().writer();
/// OPTION 1: CSV Writer
// Get a CSV writer
const csv_writer = zcsv.writer.init(stdout, .{});
// Write headers
try csv_writer.writeRow(.{"field1", "field2", "field3e", "field4"});
// Write rows
for (rowData) |elem| {
try csv_writer.writeRow(.{elem.f1, elem.f2, elem.f3, elem.f4});
}
// Option 2: Writer methods
// Write headers
try zcsv.writer.row(stdout, .{"field1", "field2", "field3", "field4"}, .{});
// Write row;
for (rowData) |elem| {
try zcsv.writer.row(stdout, .{elem.f1, elem.f2, elem.f3, elem.f4}, .{});
}
```
Reading a CSV
There are several patterns for reading CSV files provided. In general, for most use cases you'll want to use one of the allocating parsers - especially when CSV files are very small.
The <code>map</code> parser is for CSV files where the first row is a header row (a list of column names). The <code>column</code> parser is for CSV files where the header row is missing. There is one additional niche parser called <code>map_temporary</code>.
The <code>map_temporary</code> parser is for situations where you can guarantee that the row data will never outlive the parser memory. It provides a small performance increase, but can lead to trickier memory-related bugs.
As for non-allocating parsers, there are only two: <code>slice</code> and <code>stream</code>. The <code>slice</code> parser is for when the CSV file is loaded into a slice of bytes. The <code>stream</code> parser is for reading directly from a reader.
We'll discuss each parser in more detail.
Map Parser
The map parser will parse a CSV file into a series of hash maps. Each map will be returned one at a time by an iterator. Additionally, any quoted CSV fields will be unquoted automatically, so the resulting array will be the field data.
Each row owns it's own memory (unless you're using <code>map_temporary</code> in which case some memory is shared). Each row will need to be deinitialized when no longer needed (including with <code>map_temporary</code>). Additionally, map parsers will need to be deinitialized once no longer used.
Additionally, map parsers will parse the header row immediately as part of their initialization. This means that their init function may fail (e.g. allocation error, reader error, invalid header, etc). It also means that if the underlying reader blocks, then the initialization method will block as well. Do keep this in mind as a potential side effect and source of bugs. Map parsers are the only parsers which eagerly parse, so if blocking is an issue then switch to a different parser (e.g. column parser).
Below is an example of using a map parser:
```zig
// Basic usage
const zcsv = @import("zcsv");
const std = @import("std");
// ...
// Get an allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Get a reader
const stdin = std.io.getStdIn().reader();
// Make a parse
// If we want to copy headers, simply change map_sk to map_ck
// We need a try since we will try to parse the headers immediately, which may fail
var parser = try zcsv.allocs.map.init(allocator, stdin, .{});
// Note: map parsers must be deinitialized!
// They are the only parsers (currently) which need to be deinitialized
defer parser.deinit();
// We're building a list of user structs
var res = std.ArrayList(User).init(alloc);
errdefer res.deinit();
// Iterate over rows
const fieldToInt = zcsv.decode.fieldToInt;
while (parser.next) |row| {
defer row.deinit();
<code>// Validate we have our columns
const id = row.data().get("userid") orelse return error.MissingUserId;
const name = row.data().get("name") orelse return error.MissingName;
const age = row.data().get("age") orelse return error.MissingAge;
// Validate and parse our user
try res.append(User{
.id = fieldToInt(i64, id, 10) catch {
return error.InvalidUserId;
} orelse return error.MissingUserId,
.name = try name.clone(allocator),
.age = fieldToInt(u16, age, 10) catch return error.InvalidAge,
});
</code>
}
```
Column Parser
The column parser will parse a CSV file and make fields accessible by index. The memory for a row is held by the row (i.e. calling <code>row.deinit()</code> will deallocate all associated memory). Additionally, the parser will unescape quoted strings automatically (i.e. "Johnny ""John"" Doe" will become <code>Johnny "John" Doe</code>). Deinitializing a column parser is not needed.
Lines are parsed one-by-one allowing for streaming CSV files. It also allows early termination of CSV parsing. Below is an example of parsing CSVs with the parser:
```zig
// Basic usage
const zcsv = @import("zcsv");
const std = @import("std");
// ...
// Get an allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Get a reader
const stdin = std.io.getStdIn().reader();
// Make a parser
var parser = zcsv.allocs.column.init(allocator, stdin, .{});
// Iterate over rows
while (parser.next()) |row| {
// Free row memory
defer row.deinit();
<code>std.debug.print("\nROW: ", .{});
var fieldIter = row.iter();
// Can also do for(row.fields()) |field|
while (fieldIter) |field| {
// No need to free field memory since that is handled by row.deinit()
// .data() will get the slice for the data
std.debug.print("\t{s}", .{field.data()});
</code>
}
}
// Check for a parsing error
if (column.err) |err| {
return err;
}
```
Slice Parser (zero-allocation)
The slice parser is designed for speed, but it does so with some usability costs. First, it cannot read from a reader, so it requires the CSV file to be loaded into memory first. Additionally, it does not automatically decode parsed fields, so any quoted CSV fields will remain quoted after being parsed.
On the flip side, the parser itself will do no heap allocations, so it may be used in allocation-free contexts.
Example usage:
```zig
const csv =
\productid,productname,productsales
\1238943,"""Juice"" Box",9238
\3892392,"I can't believe it's not chicken!",480
\5934810,"Win The Fish",-
;
const stderr = std.io.getStdErr().writer();
var parser = zcsv.zero_allocs.slice.init(csv, .{});
std.log.info("Enter CSV to parse", .{});
try stderr.print("> ", .{});
// The writer is passed to each call to next
// This allows us to use a different writer per field
while (parser.next()) |row| {
// iterate over fields
var iter = row.iter();
<code>while (iter.next()) |field| {
// we need to manually decode fields
try field.decode(stderr);
}
try stderr.print("\n> ", .{});
</code>
}
// check for errors
if (parser.err) |err| {
return err;
}
```
Stream Parser (zero-allocation)
The zero-allocation stream parser does come with a very different set of limitations. It is able to read directly from a reader, but it does not return field objects. Instead, it will write the decoded CSV value to an output writer.
Each iteration requries providing a writer - this allows you to use a new writer for each field if needed. Only a single field is parsed at a time. Furthermore, querying the parser is needed to know when a field has reached the end of a row.
This is by far the most difficult parser to use correctly. However, it is fast, does not perform allocations, and does not require the CSV file to be used in memory. For use cases with limited resources, this can be a good choice.
Below is an example on how to use it:
```zig
const reader = std.io.getStdIn().reader();
var tmp_bytes: [1024]u8 = undefined;
var tmp_buff = std.io.fixedBufferStream(&tmp_bytes);
var parser = zcsv.zero_allocs.stream.init(reader, @TypeOf(tmp_buff).Writer, .{});
std.log.info("Enter CSV to parse", .{});
try stderr.print("> ", .{});
// The writer is passed to each call to next
// This allows us to use a different writer per field
while (!parser.done()) {
// Error checks are handled by this try
try parser.next(tmp_buff.writer());
<code>// Use tmp_buff.getWritten() as needed
std.debug.print("Decode: {s}\n", .{tmp_buff.getWritten()});
// This is how you can tell if you're about to move to the next row
// Note that we aren't at the next row yet.
// This function just indicates if the next field will be on a separate row
if (parser.atRowEnd()) {
if (!parser.done()) {
try stderr.print("\n> ", .{});
} else {
try stderr.print("\nClosing...\n", .{});
}
} else {
try stderr.print("\t", .{});
}
</code>
}
```
Parser Loop Limit Options
All of the parsers have some sort of "infinite loop protection" built in. Generally, this is a limit to 65,536 maximum loop iteration (unless there's an internal stack buffer, then the internal stack buffer will dictate the limit). This limit can be changed by adjusting the options passed into the parser. This limit can be customized by changing the <code>max_iter</code> value of <code>CsvOpts</code>.
Changing delimiters, quotes, and newlines
Each parser and writer will take a <code>CsvOpts</code> struct which has options for customizing what tokens will be used when parsing and/or writing. The options are as follows:
<ul>
<li><code>column_delim</code><ul>
<li>This indicates the column delimiter character. Defaults to comma <code>,</code></li>
</ul>
</li>
<li><code>column_quote</code><ul>
<li>This indicates the column quote character. Defaults to double-quote <code>"</code></li>
</ul>
</li>
<li><code>column_line_end</code><ul>
<li>This indicates the last line ending character for a line ending. Defaults to <code>\n</code></li>
</ul>
</li>
<li><code>column_line_end_prefix</code><ul>
<li>This indicates the first line ending character for a line ending. It can be set to <code>null</code> if line endings should always be one character. This character is always optional when parsing line endings. Defaults to <code>\r</code></li>
</ul>
</li>
</ul>
Do note that the parsers and writers do expect each of the above options to be unique, including the line ending and line ending prefix. This means that line endings which require repeating characters (e.g. <code>\n\n</code>) are not supported.
Using invalid options is undefined behavior. In safe builds this will usually result in a panic. In non-safe builds the behavior is undefined (e.g. unusual parse behavior, weird errors, infinite loops, etc). Each <code>CsvOpts</code> has a <code>valid()</code> method which will return whether or not the options are valid. It is recommended that this method be used to validate any user or untrusted input prior to sending it to a parser or a writer.
Parser Builder
To help with in-code discovery of parsers, a parser builder is provided with <code>zcsv.ParserBuilder</code>. The builder provides options for choosing a parser and for setting CSV options (such as delimiter, quote, line ending, etc). Additionally, the builder will take an allocator whenever an allocating parser is chosen and won't take an allocator when a zero-allocation parser is chosen. The builder also distinguishes between reader and slice input types.
The builder also provides methods to cleanup parsers and rows. These methods will become no-ops if no work is needed. This helps minimize the amount of work needed to switch between parsers. Also, if the cleanup methods are consistently used it can help prevent memory leaks when switching between parser types (which can often happen when moving from a zero-allocation parser to an allocating parser).
Below is an example of how to use a parser builder:
```zig
// Get our allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = gpa.allocator();
// Get our reader
var fbs = std.io.fixedBufferStream(csv[0..]);
const reader = fbs.reader();
// Get our builder
const builder = zcsv.ParserBuilder
// These calls determine which parser we will use
// They are required
.withReaderInput(@TypeOf(reader))
.withHeaderRow(alloc)
// These calls customize the CSV tokens used for parsing
// These are optional and only shown for demonstration purposes
.withQuote('"')
.withDelimiter(',');
// Make our parser
var parser = try builder.build(reader);
// Ensures parser is cleaned up properly
// This works regardless of what type of parser is returned
// It will also continue to work if parser's cleanup gets changed
// in the future
defer builder.denitParser(parser);
std.debug.print("id\tname\tage\n-------------------\n", .{});
while (parser.next()) |row| {
// Ensure our row is cleaned up
defer builder.deinitRow(row);
<code>// Work with the row data
std.debug.print("{s}\t{s}\t{s}\n", .{
row.data().get("id").?.data(),
row.data().get("name").?.data(),
row.data().get("age").?.data(),
});
</code>
}
```
Memory Lifetimes
Fields returned by parsers have their underlying memory tied to the row's memory. This means deinitializing the row will automatically deinitialize the fields tied to that row.
It also means that the following will result in a use-after-free:
```zig
// Use after free example, Don't do this!
var firstField: []const u8 = undefined;
outer: while (parser.next()) |row| {
// Free row (and field) memory
defer row.deinit();
<code>var fieldIter = row.iter();
while (fieldIter) |field| {
// Set a pointer to the field's memory
// that will persist outside of the loop
firstField = field.data();
break :outer;
}
</code>
}
// Oh no! Use after free!
std.debug.print("{s}", .{firstField});
```
If you need to have the field memory last past the row lifetime, then use the <code>clone</code> method. <code>clone</code> takes in an allocator to use for cloning the memory to. It exists for both allocating and zero-allocating parser fields, and it will always copy the decoded value (with zero-allocating parsers this means decoding the value as part of the copy). Below is an example:
```zig
// get allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Copy the memory
var firstField: ?std.ArrayList(u8) = undefined;
defer {
if (firstField) |f| {
f.deinit();
}
}
outer: while (parser.next()) |row| {
// Free row (and field) memory
defer row.deinit();
<code>var fieldIter = row.iter();
while (fieldIter) |field| {
// Set a pointer to the field's memory
// that will persist outside of the loop
firstField = try field.clone(allocator);
break :outer;
}
</code>
}
// Okay! No more use after free
std.debug.print("{s}", .{firstField});
```
<blockquote>
Note: the <code>detachMemory</code> method was removed in version 0.4.0. <code>detachMemory</code> required that every field get a separate memory allocation, which caused a lot of memory allocations and was rather slow. In version 0.4.0 the field memory was merged with the row memory which resulted in fewer allocations and a significant speed up, but it also meant that simply "detaching" (or "moving") field memory was no longer possible.
</blockquote>
Utility Methods
There are several utility methods provided to help convert CSV data to Zig builtins. These methods are opinionated based on my use cases, so if they don't suit your needs they can be ignored (or used as a template to create your own version). Methods which work on fields do try to be usable on both allocating and non-allocating parser fields (with 2 exceptions). Methods which work on slices exist as well (useful if you're writing to memory with the stream parser).
All utility methods are under the <code>zcsv.decode</code> namespace.
Field Methods
These are the methods which work on CSV fields (usually retrieved from a row iterator). None of these methods perform allocations.
<ul>
<li><strong>fieldIsNull</strong><ul>
<li>Returns whether the field is considered "null" (can be an empty string or a dash)</li>
</ul>
</li>
<li><strong>fieldToInt</strong><ul>
<li>Parses a field into an integer, or returns <code>null</code> if <code>fieldIsNull</code> returns true</li>
</ul>
</li>
<li><strong>fieldToBool</strong><ul>
<li>Parses a field to a boolean value, or returns <code>null</code> if <code>fieldIsNull</code> returns true. This method is case insensitive.</li>
<li>Truthy values include: <code>yes</code>, <code>y</code>, <code>1</code>, <code>true</code>, <code>t</code></li>
<li>Falsey values include: <code>no</code>, <code>n</code>, <code>0</code>, <code>false</code>, <code>f</code></li>
</ul>
</li>
<li><strong>fieldToFloat</strong><ul>
<li>Parses a field into a float, or returns <code>null</code> if <code>fieldIsNull</code> returns true</li>
</ul>
</li>
<li><strong>fieldToStr</strong><ul>
<li>Returns the underlying string slice of the field</li>
<li>The slice will be unquoted if the field is from an allocating parser</li>
<li>The slice will be raw (e.g. quoted) if the field is from a zero-allocation parser</li>
<li>The result has the field <code>is_raw</code> which indicates if it is quoted (<code>true</code>) or unquoted (<code>false</code>)</li>
</ul>
</li>
<li><strong>writeFieldStrTo</strong><ul>
<li>Writes a field's unquoted value to a writer</li>
</ul>
</li>
<li><strong>fieldToDecodedStr</strong><ul>
<li><em>Only works on fields from allocating parsers!</em></li>
<li>Returns <code>null</code> if <code>fieldIsNull</code> returns true</li>
<li>Returns a slice to the unquoted string</li>
</ul>
</li>
<li><strong>fieldToRawStr</strong><ul>
<li><em>Only works on fields from zero-allocation parsers!</em></li>
<li>Returns <code>null</code> if <code>fieldIsNull</code> returns true</li>
<li>Returns a slice to the raw string</li>
</ul>
</li>
</ul>
Slice Methods
These are the methods that operate on slices of bytes. None of these methods perform memory allocations. All of these methods assume that the slice has been decoded (i.e. unquoted) prior to being called.
<ul>
<li><strong>sliceIsNull</strong><ul>
<li>Returns whether the slice is considered "null" (can be an empty string or a dash)</li>
</ul>
</li>
<li><strong>sliceToInt</strong><ul>
<li>Parses a slice into an integer, or returns <code>null</code> if <code>sliceIsNull</code> returns true</li>
</ul>
</li>
<li><strong>sliceToBool</strong><ul>
<li>Parses a slice to a boolean value, or returns <code>null</code> if <code>sliceIsNull</code> returns true. This method is case insensitive.</li>
<li>Truthy values include: <code>yes</code>, <code>y</code>, <code>1</code>, <code>true</code>, <code>t</code></li>
<li>Falsey values include: <code>no</code>, <code>n</code>, <code>0</code>, <code>false</code>, <code>f</code></li>
</ul>
</li>
<li><strong>sliceToFloat</strong><ul>
<li>Parses a field into a float, or returns <code>null</code> if <code>sliceIsNull</code> returns true</li>
</ul>
</li>
<li><strong>unquote</strong><ul>
<li>Decodes/unquotes a raw CSV slice into a writer</li>
</ul>
</li>
</ul>
License
This code is licensed under the MIT license. | [] |
https://avatars.githubusercontent.com/u/46653655?v=4 | snek | BitlyTwiser/snek | 2024-09-21T17:52:35Z | Snek - A simple CLI parser to build CLI applications in Zig | main | 0 | 25 | 1 | 25 | https://api.github.com/repos/BitlyTwiser/snek/tags | MIT | [
"cli",
"snek",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 307 | false | 2025-01-20T21:29:01Z | true | true | unknown | github | [] |
# 🐍snek🐍
A simple CLI parser building CLI applications in Zig
# Contents
[Usage](#usage) |
[Building the CLI](#build-your-cli) |
[Examples](#examples) |
[Optionals](#optionals) |
[Default Values](#default-values) |
[Help Menu](#help-menu) |
[What is not supported](#what-is-not-supported)
Usage
Add snek to your Zig project with Zon:
<code>zig fetch --save https://github.com/BitlyTwiser/snek/archive/refs/tags/v0.1.1.tar.gz</code>
Add the following to build.zig file:
<code>const snek = b.dependency("snek", .{});
exe.root_module.addImport("snek", snek.module("snek"));</code>
Build your CLI
Snek builds dynamic (yet simple) CLI's using zigs meta programming to infer the struct fields, the expected types, then insert the incoming data from the stdin arguments and serialize that data into the given struct mapping the data values to the given fields and marshalling the data into the proper type.
```
const T = struct {
bool_test: bool,
word: []const u8,
test_opt: ?u32,
test_default: []const u8 = "I am static if not set by user",
};
var snek = try Snek(T).init(std.heap.page_allocator);
const parsed = try snek.parse();
<code>// Do Stuff with the fields of the struct after parsing
std.debug.print("{any}", .{parsed});
</code>
```
When the user goes to interact with the application, they can now utilize the flags you have established to run specific commands.
See the <a>completed</a> and functional example below or checkout the <a>main file</a> in the repo for a full working example as well.
Items to note:
<ol>
<li>If the user does not supply a value and the field is <em>not</em> otional, that is a failure case and a message is displayed to the user</li>
<li>If there is a default value on the field of the struct and a vale is not passed for that field, it is treated as an <em>optional</em> case and will use the static value (i.e. no error message and value is set)</li>
<li>Simple structs only for now, no recursive struct fields at the moment. (i.e. no embeded structs)</li>
<li>If the users passed the wrong <em>type</em> which differes from what is expeected (i.e. the type of the struct field), this is an error case and a message will be displayed to the user.</li>
<li>If you want to handle the errors yourself, the CliError struct is public, so you can catch errors on the <code>parse()</code> call
```
const T = struct {
bool_test: bool,
word: []const u8,
test_opt: ?u32,
test_default: []const u8 = "I am static if not set by user",
};
var snek = try Snek(T).init(std.heap.page_allocator);
// Adjust to actually use value of course
_ = snek.parse() catch |err| {
switch(e) {
... do stuff with the Errors
}
}</li>
</ol>
```
Examples
Using the above struct as a reference, here are a few examples of calling the CLI:
Example - Help Command
```
./ -help
or
./ -h
```
Note: As you can see, the optionals are just that, <em>optional</em>. They are not required by your users and can be checked in the calling code in the standard ways that Zig handles optionals.
This is a design decisions allowing flexibility over the CLI to not lock users into using every flag etc..
Example - Optionals
<code>./<yourappname> -bool_test=true -word="I am a word!"</code>
Example - Defaults:
```
./ -bool_test=true -word="I am a word!"
or to override the default field
./ -bool_test=true -word="I am a word!" -test_defaults="I am a different word!"
```
Example - Full execution
```
const std = @import("std");
const snek = @import("lib.zig").Snek;
// Binary is also compiled for showcasing how to use the API
const T = struct {
name: []const u8,
location: u32,
exists: bool,
necessary: ?bool,
filled_optional: ?[]const u8,
default_name: []const u8 = "test default name",
};
// Example command after compilation:
// ./zig-out/bin/snek -name="test mctest" -location=420 -exists=true
pub fn main() !void {
var cli = try snek(T).init(std.heap.page_allocator);
const parsed_cli = try cli.parse();
<code>// Necessary is skipped here to showcase optional values being ignored
std.debug.print("Name: {s}\n Location: {d}\n Exists: {any}\n Defualt value: {s}\n Filled Optional: {s}\n", .{ parsed_cli.name, parsed_cli.location, parsed_cli.exists, parsed_cli.default_name, parsed_cli.filled_optional orelse "badvalue" });
</code>
}
<code>Compile with `zig build` then run the cli command:</code>
./zig-out/bin/snek -name="test mctest" -location=420 -exists=true
```
Optionals
Using zig optionals, you can set selected flags to be ignored on the CLI, thus giving flexibilitiy on the behalf of the CLI creator to use or not use selected flags at their whimsy
Default Values
You can use struct defaut values to set a static value if one is not parsed. This can be useful for certain flags for conditional logic branching later in program execution.
Help Menu
Snek dynaically builds the help menu for your users. By calling the <code>help()</code> function, you can display how to use your CLI:
```
const T = struct {
bool_test: bool,
word: []const u8,
test_opt: ?u32,
};
var snek = try Snek(T).init(std.heap.page_allocator);
const parsed = try snek.help();
<code>Output:</code>
CLI Flags Help Menu
-bool_test=Bool (optional: false)
-word=Pointer (optional: false)
-test_opt=Optional (optional: true)
```
Alternatively, if users call -help as the <em>first</em> arguments in the CLI, it will also display the help menu.
```
./ -help
or
./ -h
```
This will display the help menu and skip <em>all other parsing</em>. So its important to note that this is effectively an exit case for the parser and your program.
You should build your application to support this.
What is <em>not</em> supported
Recursive struct types for sub-command fields
At this time, no recursive flags are supported, i.e. you cannot use a slice of structs as a field in the primary CLI interface struct and have those fields parsed as sub-command fields.
Perhaps, if this is requested, we could work that into the application. It seemed slightly messy and unecessray for a simple CLI builder, but perhaps expansion will be necessary there if its requested :)
<a>Top</a> | [
"https://github.com/BitlyTwiser/nostro"
] |
https://avatars.githubusercontent.com/u/188725936?v=4 | discord.zig | discord-zig/discord.zig | 2024-11-10T03:06:27Z | Mirror of Discord.zig, submit PRs and issues at https://git.yuzucchii.xyz/yuzucchii/discord.zig | master | 0 | 23 | 5 | 23 | https://api.github.com/repos/discord-zig/discord.zig/tags | - | [
"discord",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 572 | false | 2025-05-21T23:35:45Z | true | true | 0.11.0 | github | [
{
"commit": null,
"name": "zlib",
"tar_url": null,
"type": "remote",
"url": "https://git.yuzucchii.xyz/yuzucchii/zlib/archive/master.tar.gz"
},
{
"commit": "refs",
"name": "websocket",
"tar_url": "https://github.com/karlseguin/websocket.zig/archive/refs.tar.gz",
"type": "remo... | Discord.zig
A high-performance bleeding edge Discord library in Zig, featuring full API coverage, sharding support, and fine-tuned parsing
* Sharding Support: Ideal for large bots, enabling distributed load handling.
* 100% API Coverage & Fully Typed: Offers complete access to Discord's API with strict typing for reliable and safe code.
* High Performance: Faster than whichever library you can name (WIP)
* Flexible Payload Parsing: Supports payload parsing through both zlib and zstd*.
* Proper error handling
```zig
const std = @import("std");
const Discord = @import("discord");
const Shard = Discord.Shard;
var session: *Discord.Session = undefined;
fn ready(_: *Shard, payload: Discord.Ready) !void {
std.debug.print("logged in as {s}\n", .{payload.user.username});
}
fn message_create(_: *Shard, message: Discord.Message) !void {
if (message.content != null and std.ascii.eqlIgnoreCase(message.content.?, "!hi")) {
var result = try session.api.sendMessage(message.channel_id, .{ .content = "hi :)" });
defer result.deinit();
<code> const m = result.value.unwrap();
std.debug.print("sent: {?s}\n", .{m.content});
}
</code>
}
pub fn main() !void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
const allocator = gpa.allocator();
<code>session = try allocator.create(Discord.Session);
session.* = Discord.init(allocator);
defer session.deinit();
const env_map = try allocator.create(std.process.EnvMap);
env_map.* = try std.process.getEnvMap(allocator);
defer env_map.deinit();
const token = env_map.get("DISCORD_TOKEN") orelse {
@panic("DISCORD_TOKEN not found in environment variables");
};
const intents = comptime blk: {
var bits: Discord.Intents = .{};
bits.Guilds = true;
bits.GuildMessages = true;
bits.GuildMembers = true;
// WARNING:
// YOU MUST SET THIS ON DEV PORTAL
// OTHERWISE THE LIBRARY WILL CRASH
bits.MessageContent = true;
break :blk bits;
};
try session.start(.{
.intents = intents,
.authorization = token,
.run = .{ .message_create = &message_create, .ready = &ready },
.log = .yes,
.options = .{},
.cache = .defaults(allocator),
});
</code>
}
```
Installation
```zig
// In your build.zig file
const exe = b.addExecutable(.{
.name = "beluga",
.root_source_file = b.path("src/main.zig"),
.target = target,
// just a suggestion, use .ReleaseSafe
.optimize = optimize,
// must always be on, hard dependency
.link_libc = true,
// self-hosted backed is unstable as of today 2025-05-16,
.use_llvm = true,
});
const dzig = b.dependency("discordzig", .{});
exe.root_module.addImport("discord.zig", dzig.module("discord.zig"));
```
<strong>Warning</strong>: the library is intended to be used with the latest dev version of Zig.
contributing
Contributions are welcome! Please open an issue or pull request if you'd like to help improve the library.
* Support server: https://discord.gg/RBHkBt7nP5
* The original repo: https://git.yuzucchii.xyz/yuzucchii/discord.zig
general roadmap
| Task | Status |
|-------------------------------------------------------------|--------|
| make the library scalable with a gateway proxy | ❌ |
| get a cool logo | ❌ |
missing structures
| feature | Status |
|--------------------------|--------|
| components V2 | ❌ |
| the tags beside ur name | ❌ |
missing events right now
| Event | Support |
|----------------------------------------|---------|
| voice_channel_effect_send | ❌ |
| voice_state_update | ❌ |
| voice_server_update | ❌ |
http methods missing
| Endpoint | Support |
|----------------------------------------|---------|
| Audit log | ❌ |
| Automod | ❌ |
| Guild Scheduled Event related | ❌ |
| Guild template related | ❌ |
| Soundboard related | ❌ |
| Stage Instance related | ❌ |
| Subscription related | ❌ |
| Voice related | ❌ |
| Webhook related | ❌ | | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zsdl | zig-gamedev/zsdl | 2024-11-04T21:35:24Z | Zig bindings for SDL libs. | main | 0 | 23 | 13 | 23 | https://api.github.com/repos/zig-gamedev/zsdl/tags | MIT | [
"bindings",
"gamedev",
"sdl",
"sdl2",
"sdl2-image",
"sdl2-ttf",
"sdl3",
"zig"
] | 1,123 | false | 2025-05-08T22:03:45Z | true | true | unknown | github | [
{
"commit": "e89207914a0f0163c0fb543da4f530f645ef5969.tar.gz",
"name": "sdl3_prebuilt_macos",
"tar_url": "https://github.com/zig-gamedev/sdl3-prebuilt-macos/archive/e89207914a0f0163c0fb543da4f530f645ef5969.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/sdl3-prebuilt-mac... | <a>zsdl</a>
Zigified bindings for SDL libs. Work in progress.
Getting started (SDL2)
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) !void {
<code>const exe = b.addExecutable(.{ ... });
exe.linkLibC();
const zsdl = b.dependency("zsdl", .{});
exe.root_module.addImport("zsdl2", zsdl.module("zsdl2"));
@import("zsdl").link_SDL2(exe);
exe.root_module.addImport("zsdl2_ttf", zsdl.module("zsdl2_ttf"));
@import("zsdl").link_SDL2_ttf(exe);
exe.root_module.addImport("zsdl2_image", zsdl.module("zsdl2_image"));
@import("zsdl").link_SDL2_image(exe);
// Optionally use prebuilt libs instead of relying on system installed SDL...
@import("zsdl").prebuilt_sdl2.addLibraryPathsTo(exe);
if (@import("zsdl").prebuilt_sdl2.install(b, target.result, .bin), .{
.ttf = true,
.image = true,
}) |install_sdl2_step| {
b.getInstallStep().dependOn(install_sdl2_step);
}
</code>
}
```
NOTE: If you want to use our prebuilt libraries also add the following to your <code>build.zig.zon</code>:
<code>zig
.@"sdl2-prebuilt-macos" = .{
.url = "https://github.com/zig-gamedev/sdl2-prebuilt-macos/archive/f14773fa3de719b3a399b854c31eb4139d63842f.tar.gz",
.hash = "12205cb2da6fb4a7fcf28b9cd27b60aaf12f4d4a55be0260b1ae36eaf93ca5a99f03",
.lazy = true,
},
.@"sdl2-prebuilt-x86_64-windows-gnu" = .{
.url = "https://github.com/zig-gamedev/sdl2-prebuilt-x86_64-windows-gnu/archive/8143e2a5c28dbace399cbff14c3e8749a1afd418.tar.gz",
.hash = "1220ade6b84d06d73bf83cef22c73ec4abc21a6d50b9f48875f348b7942c80dde11b",
.lazy = true,
},
.@"sdl2-prebuilt-x86_64-linux-gnu" = .{
.url = "https://github.com/zig-gamedev/sdl2-prebuilt-x86_64-linux-gnu/archive/2eccc574ad909b0d00b694b10c217a95145c47af.tar.gz",
.hash = "12200ecb91c0596d0356ff39d573af83abcd44fecb27943589f11c2cd172763fea39",
.lazy = true,
},</code>
Now in your code you may import and use <code>zsdl2</code>:
```zig
const std = @import("std");
const sdl = @import("zsdl2");
pub fn main() !void {
...
try sdl.init(.{ .audio = true, .video = true });
defer sdl.quit();
<code>const window = try sdl.Window.create(
"zig-gamedev-window",
sdl.Window.pos_undefined,
sdl.Window.pos_undefined,
600,
600,
.{ .opengl = true, .allow_highdpi = true },
);
defer window.destroy();
...
</code>
}
```
Getting started (SDL3)
TODO | [] |
https://avatars.githubusercontent.com/u/95168615?v=4 | clay-zig | raugl/clay-zig | 2024-12-31T04:11:58Z | Zig bindings for the library clay: A high performance UI layout library in C. | master | 1 | 22 | 4 | 22 | https://api.github.com/repos/raugl/clay-zig/tags | MIT | [
"layout",
"ui",
"zig",
"zig-binding",
"zig-package"
] | 161 | false | 2025-05-06T15:01:52Z | true | true | 0.14.0 | github | [
{
"commit": "c9e1a63378ecfba448ecd42796838264b10adafb",
"name": "clay_src",
"tar_url": "https://github.com/nicbarker/clay/archive/c9e1a63378ecfba448ecd42796838264b10adafb.tar.gz",
"type": "remote",
"url": "https://github.com/nicbarker/clay"
}
] | Zig Language Bindings
<blockquote>
<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span>
Zig 0.14.0 or higher is required.
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
This project currently is in beta.
</blockquote>
This directory contains bindings for the <a>Zig</a> programming language, as well as an example implementation of the <a>clay website</a> in Zig.
Special thanks to <a>johan0A</a> for the reference implementation.
If you haven't taken a look at the <a>full documentation for clay</a>, it's recommended that you take a look there first to familiarise yourself with the general concepts. This README is abbreviated and applies to using clay in Zig specifically.
The <strong>most notable difference</strong> between the C API and the Zig bindings is the use of if statements to open the scope for declaring child elements and then having to close it "manually" with a deferred function call.
Other changes include:
- minor naming changes
- ability to initialize a parameter by calling a function that is part of its type's namespace for example <code>.fixed()</code> or <code>.all()</code>
- ability to initialize a parameter by using a public constant that is part of its type's namespace for example <code>.grow</code>
TODO:
- Talk about integrations with raylib
- Talk about special <code>getOpenElementId()</code>, <code>element()</code>, and <code>hovered()</code> functions
<code>c
// C macro for creating a scope
CLAY(
CLAY_ID("SideBar"),
CLAY_LAYOUT({
.layoutDirection = CLAY_TOP_TO_BOTTOM,
.childAlignment = { .x = CLAY_ALIGN_X_CENTER, .y = CLAY_ALIGN_Y_TOP },
.sizing = { .width = CLAY_SIZING_FIXED(300), .height = CLAY_SIZING_GROW() },
.padding = {16, 16},
.childGap = 16,
}),
CLAY_RECTANGLE({ .color = COLOR_LIGHT })
) {
// Child elements here
}</code>
<code>zig
// Zig form of element macros
if (clay.open(.{
.id = clay.Id("SideBar"),
.layout = .{
.direction = .top_to_bottom,
.alignment = .center_top,
.sizing = .{ .w = .fixed(300), .h = .grow },
.padding = .all(16),
.child_gap = 16,
},
.rectangle = .{ .color = COLOR_LIGHT },
})) {
defer clay.close();
// Child elements here
}</code>
Install
Download and add <code>clay-zig</code> as a dependency by running the following command in your project root:
<code>sh
zig fetch --save https://github.com/raugl/clay-zig/archive/<commit sha>.tar.gz</code>
Then add <code>clay-zig</code> as a dependency and import its modules and artifact in your build.zig:
<code>zig
const clay_dep = b.dependency("clay-zig", .{
.target = target,
.optimize = optimize,
});
exe.linkLibrary(clay_dep.artifact("clay"));
exe.root_module.addImport("clay", clay_dep.module("clay"));</code>
To enable a builtin renderer you should first add its third party library to your project separately (eg: raylib, sdl2), then tell clay-zig about it. In this example we are using <a>raylib-zig</a>:
```zig
const cl = @import("clay-zig");
const raylib_dep = b.dependency("raylib-zig", .{ ... });
cl.enableRenderer(exe.root_module, clay_dep, .{ .raylib = raylib_dep.module("raylib") });
```
Quick Start
<ol>
<li>Ask clay for how much static memory it needs using <a>clay.minMemorySize()</a>, create an Arena for it to use with <a>clay.createArenaWithCapacityAndMemory(min_memory_size, memory)</a>, and initialize it with <a>clay.initialize(arena, layout_size, error_handler)</a>.</li>
</ol>
<code>zig
const memory = try allocator.alloc(u8, clay.minMemorySize());
defer allocator.free(memory);
const arena = clay.createArenaWithCapacityAndMemory(@intCast(memory.len), @ptrCast(memory));
clay.initialize(arena, .{}, .{});</code>
<ol>
<li>Provide a <code>measureText(text, config)</code> function with <a>clay.setMeasureTextFunction(function)</a> so that clay can measure and wrap text.</li>
</ol>
```zig
// Example measure text function
pub fn measureText(text: []const u8, config: *clay.TextConfig) clay.Dimensions {
// clay.TextConfig contains members such as font_id, font_size, letter_spacing etc
}
// Tell clay how to measure text
clay.setMeasureTextFunction(measureText)
```
<ol>
<li><strong>Optional</strong> - Call <a>clay.setPointerPosition(pointerPosition)</a> if you want to use mouse interactions.</li>
</ol>
<code>zig
clay.setPointerState(.{ .x = mouse_position_x, .y = mouse_position_y }, is_left_mouse_button_down);</code>
<ol>
<li>Call <a>clay.beginLayout()</a> and declare your layout using the provided functions.</li>
</ol>
```zig
const COLOR_LIGHT = clay.Color.init(224, 215, 210, 255);
const COLOR_RED = clay.Color.init(168, 66, 28, 255);
const COLOR_ORANGE = clay.Color.init(225, 138, 50, 255);
// Layout config is just a struct that can be declared statically, or inline
const sidebar_item_layout = clay.LayoutConfig{
.sizing = .{ .w = .grow, .h = .fixed(50) },
};
// Re-useable components are just normal functions
fn sidebarItemComponent(index: usize) void {
clay.element(.{
.id = clay.IdWithIndex("SidebarBlob", index),
.layout = sidebar_item_layout,
.rectangle = .{ .color = COLOR_ORANGE },
});
}
// An example function to begin the "root" of your layout tree
fn createLayout() clay.RenderCommandArray {
clay.beginLayout();
<code>// An example of laying out a UI with a fixed width sidebar and flexible width main content
if (clay.open(.{
.id = clay.Id("OuterContainer"),
.layout = .{ .sizing = .grow, .padding = .all(16), .child_gap = 16 },
.rectangle = .{ .color = .init(250, 250, 250, 255) },
})) {
defer clay.close();
if (clay.open(.{
.id = clay.Id("SideBar"),
.layout = .{ .direction = .top_to_bottom, .sizing = .{ .w = .fixed(300), .h = .grow }, .padding = .all(16), .child_gap = 16 },
.rectangle = .{ .color = COLOR_LIGHT },
})) {
defer clay.close();
if (clay.open(.{
.id = clay.Id("ProfilePictureOuter"),
.layout = .{ .sizing = .{ .w = .grow }, .padding = .all(16), .child_gap = 16, .alignment = .left_center },
.rectangle = .{ .color = COLOR_RED },
})) {
defer clay.close();
clay.element(.{
.id = clay.Id("ProfilePicture"),
.layout = .{ .sizing = .fixed(60) },
.image = .{ .image_data = &profile_picture, size = .all(60) },
});
clay.text("Clay - UI Library", .{ .font_size = 24, .text_color = .init(255, 255, 255, 255) });
}
// Standard Zig code like loops etc. work inside components
for (0..10) |i| sidebarItemComponent(i)
}
if (clay.open(.{
.id = clay.Id("MainContent"),
.layout = .{ .sizing = .grow },
.rectangle = .{ .color = COLOR_LIGHT },
})) {
defer clay.close();
// ...
}
}
return clay.endLayout();
</code>
}
```
<ol>
<li>Call <a>clay.endLayout()</a> and process the resulting <a>clay.RenderCommandArray</a> in your choice of renderer.</li>
</ol>
```zig
const render_commands = clay.endLayout();
for (render_commands.slice()) |render_command| {
switch (render_command.type) {
.rectangle => {
drawRectangle(render_command.bounding_box, render_command.config.rectangle.color);
},
// ... Implement handling of other command types
}
}
```
Please see the <a>full C documentation for clay</a> for API details. All public C functions and Macros have Zig binding equivalents, generally of the form <code>Clay_BeginLayoup</code> (C) -> <code>clay.beginLayout</code> (Zig) | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zflecs | zig-gamedev/zflecs | 2024-11-03T21:30:16Z | Zig build package and bindings for https://github.com/SanderMertens/flecs | main | 7 | 22 | 12 | 22 | https://api.github.com/repos/zig-gamedev/zflecs/tags | MIT | [
"bindings",
"ecs",
"flecs",
"gamedev",
"zig"
] | 935 | false | 2025-05-19T18:26:00Z | true | true | unknown | github | [] | <a>zflecs</a>
Zig build package and bindings for <a>flecs</a> ECS v4.0.4
Getting started
Example<code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ ... });
<code>const zflecs = b.dependency("zflecs", .{});
exe.root_module.addImport("zflecs", zflecs.module("root"));
exe.linkLibrary(zflecs.artifact("flecs"));
</code>
}
```
Now in your code you may import and use <code>zflecs</code>:
```zig
const std = @import("std");
const ecs = @import("zflecs");
const Position = struct { x: f32, y: f32 };
const Velocity = struct { x: f32, y: f32 };
const Eats = struct {};
const Apples = struct {};
fn move_system(positions: []Position, velocities: []const Velocity) void {
for (positions, velocities) |*p, v| {
p.x += v.x;
p.y += v.y;
}
}
//Optionally, systems can receive the components iterator (usually not necessary)
fn move_system_with_it(it: *ecs.iter_t, positions: []Position, velocities: []const Velocity) void {
const type_str = ecs.table_str(it.world, it.table).?;
std.debug.print("Move entities with [{s}]\n", .{type_str});
defer ecs.os.free(type_str);
<code>for (positions, velocities) |*p, v| {
p.x += v.x;
p.y += v.y;
}
</code>
}
pub fn main() !void {
const world = ecs.init();
defer _ = ecs.fini(world);
<code>ecs.COMPONENT(world, Position);
ecs.COMPONENT(world, Velocity);
ecs.TAG(world, Eats);
ecs.TAG(world, Apples);
ecs.ADD_SYSTEM(world, "move system", ecs.OnUpdate, move_system);
ecs.ADD_SYSTEM(world, "move system with iterator", ecs.OnUpdate, move_system_with_it);
const bob = ecs.new_entity(world, "Bob");
_ = ecs.set(world, bob, Position, .{ .x = 0, .y = 0 });
_ = ecs.set(world, bob, Velocity, .{ .x = 1, .y = 2 });
ecs.add_pair(world, bob, ecs.id(Eats), ecs.id(Apples));
_ = ecs.progress(world, 0);
_ = ecs.progress(world, 0);
const p = ecs.get(world, bob, Position).?;
std.debug.print("Bob's position is ({d}, {d})\n", .{ p.x, p.y });
</code>
}
```
<code>zig build run</code> should result in:
<code>Move entities with [main.Position, main.Velocity, (Identifier,Name), (main.Eats,main.Apples)]
Move entities with [main.Position, main.Velocity, (Identifier,Name), (main.Eats,main.Apples)]
Bob's position is (4, 8)</code> | [
"https://github.com/azillion/gravitas",
"https://github.com/cyberegoorg/cetech1",
"https://github.com/foxnne/aftersun",
"https://github.com/zig-gamedev/zig-gamedev"
] |
https://avatars.githubusercontent.com/u/113083639?v=4 | ztracy | zig-gamedev/ztracy | 2024-11-04T21:45:01Z | Performance markers for Tracy Frame Profiler in Zig. | main | 3 | 21 | 10 | 21 | https://api.github.com/repos/zig-gamedev/ztracy/tags | MIT | [
"bindings",
"profiling",
"tracy",
"zig"
] | 340 | false | 2025-05-13T04:19:43Z | true | true | unknown | github | [
{
"commit": "c0dbf11cdc17da5904ea8a17eadc54dee26567ec.tar.gz",
"name": "system_sdk",
"tar_url": "https://github.com/zig-gamedev/system_sdk/archive/c0dbf11cdc17da5904ea8a17eadc54dee26567ec.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/system_sdk"
}
] | <a>ztracy</a>
Performance markers for <a>Tracy 0.11.1</a> in Zig
Initial Zig bindings created by <a>Martin Wickham</a>
Getting started
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const options = .{
.enable_ztracy = b.option(
bool,
"enable_ztracy",
"Enable Tracy profile markers",
) orelse false,
.enable_fibers = b.option(
bool,
"enable_fibers",
"Enable Tracy fiber support",
) orelse false,
.on_demand = b.option(
bool,
"on_demand",
"Build tracy with TRACY_ON_DEMAND",
) orelse false,
};
<code>const exe = b.addExecutable(.{ ... });
const ztracy = b.dependency("ztracy", .{
.enable_ztracy = options.enable_ztracy,
.enable_fibers = options.enable_fibers,
.on_demand = options.on_demand,
});
exe.root_module.addImport("ztracy", ztracy.module("root"));
exe.linkLibrary(ztracy.artifact("tracy"));
</code>
}
```
Now in your code you may import and use <code>ztracy</code>. To build your project with Tracy enabled run:
<code>zig build -Denable_ztracy=true</code>
```zig
const ztracy = @import("ztracy");
pub fn main() !void {
{
const tracy_zone = ztracy.ZoneNC(@src(), "Compute Magic", 0x00_ff_00_00);
defer tracy_zone.End();
...
}
}
```
Async "Fibers" support
Tracy has support for marking fibers (also called green threads,
coroutines, and other forms of cooperative multitasking). This support requires
an additional option passed through when compiling the Tracy library, so:
```zig
...
const optimize = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
<code>const ztracy_pkg = ztracy.package(b, target, optimize, .{
.options = .{ .enable_ztracy = true, .enable_fibers = true },
});
ztracy_pkg.link(exe);
</code>
``` | [
"https://github.com/Avokadoen/ecez",
"https://github.com/Avokadoen/zig_vulkan",
"https://github.com/cyberegoorg/cetech1",
"https://github.com/jcalabro/uscope",
"https://github.com/jrachele/zsynth",
"https://github.com/nfginola/vk-zig",
"https://github.com/zig-gamedev/zig-gamedev"
] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zgpu | zig-gamedev/zgpu | 2024-11-03T22:07:58Z | Cross-platform graphics lib for Zig built on top of Dawn native WebGPU implementation. | main | 6 | 21 | 14 | 21 | https://api.github.com/repos/zig-gamedev/zgpu/tags | MIT | [
"cross-platform",
"dawn",
"gamedev",
"graphics",
"native",
"webgpu",
"zig"
] | 114 | false | 2025-05-16T07:50:25Z | true | true | 0.14.0 | github | [
{
"commit": "99a4c74ec26b1f327209782565b4adaf1c1d610f.tar.gz",
"name": "zpool",
"tar_url": "https://github.com/zig-gamedev/zpool/archive/99a4c74ec26b1f327209782565b4adaf1c1d610f.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zpool"
},
{
"commit": "c0dbf11cdc17da... | <a>zgpu</a>
Cross-platform graphics lib for Zig built on top of <a>Dawn</a> native WebGPU implementation.
Supports Windows 10+ (DirectX 12), macOS 12+ (Metal) and Linux (Vulkan).
Features
<ul>
<li>Zero-overhead wgpu API bindings (<a>source code</a>)</li>
<li>Uniform buffer pool for fast CPU->GPU transfers</li>
<li>Resource pools and handle-based GPU resources</li>
<li>Async shader compilation</li>
<li>GPU mipmap generator</li>
</ul>
Getting started
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ ... });
<code>@import("zgpu").addLibraryPathsTo(exe);
const zgpu = b.dependency("zgpu", .{});
exe.root_module.addImport("zgpu", zgpu.module("root"));
if (target.result.os.tag != .emscripten) {
exe.linkLibrary(zgpu.artifact("zdawn"));
}
</code>
}
```
Sample applications
<ul>
<li><a>gui test (wgpu)</a></li>
<li><a>physically based rendering (wgpu)</a></li>
<li><a>bullet physics test (wgpu)</a></li>
<li><a>procedural mesh (wgpu)</a></li>
<li><a>textured quad (wgpu)</a></li>
<li><a>triangle (wgpu)</a></li>
</ul>
Library overview
Below you can find an overview of main <code>zgpu</code> features.
Compile-time options
You can override default options in your <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
...
<code>const zgpu = @import("zgpu").package(b, target, optimize, .{
.options = .{
.uniforms_buffer_size = 4 * 1024 * 1024,
.dawn_skip_validation = false,
.buffer_pool_size = 256,
.texture_pool_size = 256,
.texture_view_pool_size = 256,
.sampler_pool_size = 16,
.render_pipeline_pool_size = 128,
.compute_pipeline_pool_size = 128,
.bind_group_pool_size = 32,
.bind_group_layout_pool_size = 32,
.pipeline_layout_pool_size = 32,
},
});
zgpu.link(exe);
...
</code>
}
```
Graphics Context
Create a <code>GraphicsContext</code> using a <code>WindowProvider</code>. For example, using <a>zglfw</a>:
```zig
const gctx = try zgpu.GraphicsContext.create(
allocator,
.{
.window = window,
.fn_getTime = @ptrCast(&zglfw.getTime),
.fn_getFramebufferSize = @ptrCast(&zglfw.Window.getFramebufferSize),
<code> // optional fields
.fn_getWin32Window = @ptrCast(&zglfw.getWin32Window),
.fn_getX11Display = @ptrCast(&zglfw.getX11Display),
.fn_getX11Window = @ptrCast(&zglfw.getX11Window),
.fn_getWaylandDisplay = @ptrCast(&zglfw.getWaylandDisplay),
.fn_getWaylandSurface = @ptrCast(&zglfw.getWaylandWindow),
.fn_getCocoaWindow = @ptrCast(&zglfw.getCocoaWindow),
},
.{}, // default context creation options
</code>
);
```
Uniforms
<ul>
<li>Implemented as a uniform buffer pool</li>
<li>Easy to use</li>
<li>Efficient - only one copy operation per frame</li>
</ul>
```zig
struct DrawUniforms = extern struct {
object_to_world: zm.Mat,
};
const mem = gctx.uniformsAllocate(DrawUniforms, 1);
mem.slice[0] = .{ .object_to_world = zm.transpose(zm.translation(...)) };
pass.setBindGroup(0, bind_group, &.{mem.offset});
pass.drawIndexed(...);
// When you are done encoding all commands for a frame:
gctx.submit(...); // Injects <em>one</em> copy operation to transfer <em>all</em> allocated uniforms
```
Resource pools
<ul>
<li>Every GPU resource is identified by 32-bit integer handle</li>
<li>All resources are stored in one system</li>
<li>We keep basic info about each resource (size of the buffer, format of the texture, etc.)</li>
<li>You can always check if resource is valid (very useful for async operations)</li>
<li>System keeps basic info about resource dependencies, for example, <code>TextureViewHandle</code> knows about its
parent texture and becomes invalid when parent texture becomes invalid; <code>BindGroupHandle</code> knows
about all resources it binds so it becomes invalid if any of those resources become invalid</li>
</ul>
```zig
const buffer_handle = gctx.createBuffer(...);
if (gctx.isResourceValid(buffer_handle)) {
const buffer = gctx.lookupResource(buffer_handle).?; // Returns <code>wgpu.Buffer</code>
<code>const buffer_info = gctx.lookupResourceInfo(buffer_handle).?; // Returns `zgpu.BufferInfo`
std.debug.print("Buffer size is: {d}", .{buffer_info.size});
</code>
}
// If you want to destroy a resource before shutting down graphics context:
gctx.destroyResource(buffer_handle);
```
Async shader compilation
<ul>
<li>Thanks to resource pools and resources identified by handles we can easily async compile all our shaders</li>
</ul>
```zig
const DemoState = struct {
pipeline_handle: zgpu.PipelineLayoutHandle = .{},
...
};
const demo = try allocator.create(DemoState);
// Below call schedules pipeline compilation and returns immediately. When compilation is complete
// valid pipeline handle will be stored in <code>demo.pipeline_handle</code>.
gctx.createRenderPipelineAsync(allocator, pipeline_layout, pipeline_descriptor, &demo.pipeline_handle);
// Pass using our pipeline will be skipped until compilation is ready
pass: {
const pipeline = gctx.lookupResource(demo.pipeline_handle) orelse break :pass;
...
<code>pass.setPipeline(pipeline);
pass.drawIndexed(...);
</code>
}
```
Mipmap generation on the GPU
<ul>
<li>wgpu API does not provide mipmap generator</li>
<li>zgpu provides decent mipmap generator implemented in a compute shader</li>
<li>It supports 2D textures, array textures and cubemap textures of any format
(<code>rgba8_unorm</code>, <code>rg16_float</code>, <code>rgba32_float</code>, etc.)</li>
<li>Currently it requires that: <code>texture_width == texture_height and isPowerOfTwo(texture_width)</code></li>
<li>It takes ~260 microsec to generate all mips for 1024x1024 <code>rgba8_unorm</code> texture on GTX 1660</li>
</ul>
<code>zig
// Usage:
gctx.generateMipmaps(arena, command_encoder, texture_handle);</code> | [
"https://github.com/Senryoku/Deecy",
"https://github.com/azillion/gravitas",
"https://github.com/braheezy/zonk",
"https://github.com/yusdacra/levent",
"https://github.com/zig-gamedev/zgui",
"https://github.com/zig-gamedev/zig-gamedev"
] |
https://avatars.githubusercontent.com/u/20110944?v=4 | misshod | ringtailsoftware/misshod | 2024-12-28T02:56:39Z | MiSSHod is a minimal, experimental SSH client and server implemented as a library | main | 0 | 20 | 1 | 20 | https://api.github.com/repos/ringtailsoftware/misshod/tags | MIT | [
"ssh",
"ssh-client",
"ssh-server",
"zig",
"zig-package",
"ziglang"
] | 398 | false | 2025-05-14T04:35:00Z | true | true | 0.14.0 | github | [] | MiSSHod
<em>misshod. (ˌmɪsˈʃɒd). adj. badly shod</em>
About
MiSSHod is a minimal, experimental SSH client and server implemented as a library.
It has been tested with both <a>OpenSSH</a> and <a>Dropbear</a>.
<strong>MiSSHod is not secure, it should not be used in real world systems</strong>
It aims to be:
<ul>
<li>Transport and I/O agnostic - TCP would be normal, but MiSShod can be run over any reliable stream protocol</li>
<li>Asynchronous - MiSShod never blocks execution for I/O, it enters a wait state and can be resumed when data arrives</li>
<li>Callback free - asynchronous message passing prevents the caller needing callbacks and context structs</li>
<li>Very lightweight, opening up the possibility of running on small embedded devices</li>
</ul>
<strong>Features</strong>
<ul>
<li>Public key auth</li>
<li>Password auth</li>
<li>Supports exactly one of each of the required protocols<ul>
<li>hmac-sha2-256 (hmac)</li>
<li>curve25519-sha256 (key exchange)</li>
<li>ssh-ed25519 (key)</li>
<li>aes256-ctr (cipher)</li>
</ul>
</li>
</ul>
Building
MiSSHod requires <a>Zig 0.14.0</a>.
Client
To build <code>mssh</code>, a command line SSH client for Mac/Linux
<code>bash
zig build test</code>
<code>bash
cd mssh
zig build
./zig-out/bin/mssh
./zig-out/bin/mssh <username@host> <port> [idfile]</code>
To run a test SSH server (dropbear) in docker
<code>bash
cd testserver
./sshserver</code>
Login with password auth, ("password")
```bash
./zig-out/bin/mssh testuser@127.0.0.1 2022
Same as: ssh -p 2022 testuser@127.0.0.1
```
Login with pubkey auth using a passwordless private key
```bash
./zig-out/bin/mssh testuser@127.0.0.1 2022 ../testserver/id_ed25519_passwordless
Same as: ssh -p 2022 testuser@127.0.0.1 -i ../testserver/id_ed25519_passwordless
```
Login with pubkey auth using a password protected private key ("secretpassword")
```bash
./zig-out/bin/mssh testuser@127.0.0.1 2022 ../testserver/id_ed25519_passworded
Same as: ssh -p 2022 testuser@127.0.0.1 -i ../testserver/id_ed25519_passworded
```
Server
<code>msshd</code> is a toy ssh server. It handles one connection at a time and echoes back received data with "You said X".
To build <code>msshd</code>
<code>bash
cd msshd
zig build
./zig-out/bin/msshd
./zig-out/bin/msshd <port> <hostkey></code>
To run the server
<code>bash
./zig-out/bin/msshd 2022 ../testserver/id_ed25519_passwordless
Server listening on port 2022</code>
Connect using OpenSSH
<code>bash
ssh -p 2022 foo@127.0.0.1</code>
By default the server will accept any public key offered. Typically, OpenSSH offers all available keys, so it will be able to login immediately. This can be changed in <code>msshd/src/main.zig</code>. Typically, a real server would check the user's <code>authorized_keys</code> file.
Connect using <code>mssh</code> using pubkey auth (key password is "secretpassword")
<code>bash
cd mssh
zig build run -- foo@127.0.0.1 2022 ../testserver/id_ed25519_passworded</code>
Connect using <code>mssh</code> using password auth (any password matching username will be accepted, so "foo" here)
<code>bash
cd mssh
zig build run -- foo@127.0.0.1 2022</code>
Tiny client example
As a proof of concept, the <code>tiny</code> example logs into the test server but contains no socket code. Instead, it uses stdout and stdin. To run it via <code>socat</code>:
<code>bash
zig build && socat TCP4:127.0.0.1:2022 EXEC:./zig-out/bin/tiny</code>
Tiny uses a weaker PRNG, a fixed buffer allocator and does no file I/O.
Security
<strong>MiSSHod is not secure, it should not be used in real world systems</strong>
<ul>
<li>Very little testing has been done and not all code paths have been exercised</li>
<li>No efforts have been made to prevent timing attacks</li>
<li>Sensitive data is held in RAM for longer than is strictly necessary</li>
<li>MiSSHod relies on Zig's standard library for all crypto algorithms, which is still relatively young</li>
<li>Most importantly, I am not a cryptographer and I have no idea what I'm doing</li>
</ul>
Status
MiSSHod was developed rapidly. The main aim was to get it working and learn something along the way. I don't know what's next, but hopefully you can learn something too by looking at a small SSH implementation.
It's entirely undocumented and there aren't enough tests. The IO systems are a bit arcane, as I've tried wherever possible to avoid using excess RAM. | [] |
https://avatars.githubusercontent.com/u/10101283?v=4 | bunv | aklinker1/bunv | 2024-09-14T00:55:37Z | Corepack for Bun. PoC for implementing version management inside bun itself. | main | 2 | 20 | 0 | 20 | https://api.github.com/repos/aklinker1/bunv/tags | MIT | [
"bun",
"zig"
] | 11,691 | false | 2025-05-21T00:08:45Z | true | false | unknown | github | [] | Bunv
<a></a>
<a></a>
<code>sh
curl -sL https://raw.githubusercontent.com/aklinker1/bunv/main/install.sh | sh</code>
Zero config wrapper around <a>Bun</a> that automatically downloads, manages, and executes the version of <code>bun</code> required by each of your projects.
Basically <a><code>corepack</code></a> for Bun! But written in Zig for <a>basically zero overhead</a>.
Features
<ul>
<li>Automatic version selection for <code>bun</code> and <code>bunx</code></li>
<li>Manage installed versions with <code>bunv</code></li>
<li>Read project version from <code>package.json</code>'s <code>packageManager</code> field, just like Corepack</li>
</ul>
Roadmap
Goal of <code>bunv</code> is to provide a PoC for what version management might look like built into Bun. At the time of writing, that's basically done.
Installation
Use Brew
<code>sh
brew install simnalamburt/x/bunv</code>
Use Prebuilt Binaries
<ol>
<li>Uninstall <a><code>bun</code></a> and/or remove <code>~/.bun/bin</code> from your path</li>
<li>Run installer:
<code>sh
curl -sL https://raw.githubusercontent.com/aklinker1/bunv/main/install.sh | sh</code></li>
<li>Add <code>~/.bunv/bin</code> to your <code>PATH</code></li>
<li>Ensure <code>which bun</code> outputs <code>~/.bunv/bin/bun</code></li>
</ol>
Build from source
<ol>
<li>Uninstall <a><code>bun</code></a> or remove <code>~/.bun/bin</code> from your path</li>
<li>Install <a>Zig</a></li>
<li>Build the executables (<code>bun</code>, <code>bunx</code>, <code>bunv</code>)
<code>sh
zig build -Doptimize=ReleaseFast --prefix ~/.bunv</code></li>
<li>Add <code>~/.bunv/bin</code> to your path:
<code>sh
export PATH="$HOME/.bunv/bin:$PATH"</code></li>
<li>Double check that <code>which bun</code> outputs <code>~/.bunv/bin/bun</code></li>
</ol>
Usage
To use <code>bun</code> or <code>bunx</code>, just use it like normal:
<code>sh
$ bun i
$ bunx oxlint@latest</code>
If you haven't installed the version of Bun required by your project, you'll be prompted to install it when running any <code>bun</code> or <code>bunx</code> commands.
Bunv also ships its own executable: <code>bunv</code>. Right now, it just lists the versions of Bun it has installed:
<code>sh
$ bunv
Installed versions:
v1.1.26
│ Directory: /home/aklinker1/.bunv/versions/1.1.26
│ Bin Dir: /home/aklinker1/.bunv/versions/1.1.26/bin
└─ Bin: /home/aklinker1/.bunv/versions/1.1.26/bin/bun</code>
To delete a version of Bun, just delete it's directory:
<code>sh
$ rm -rf ~/.bunv/versions/1.1.26</code>
If you're not in a project, Bunv will use the newest version installed locally or if there are none, it will download and install the latest release.
Upgrading Bun
<code>bun upgrade</code> isn't going to do anything. Instead, update the version of bun in your <code>package.json</code>, <code>.bun-version</code>, or <code>.tool-versions</code> file and it will be installed the next time you run a <code>bun</code> command.
GitHub Actions
The <code>setup/bun</code> action already supports all the version files Bunv supports - that means you don't have to install Bunv in CI - just use it locally.
```yml
.github/workflows/validate
on:
pull_request:
jobs:
validate:
runs_on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: oven-sh/setup-bun@v2
with:
bun-version-file: "package.json" # or ".tool-versions" or ".bun-version"
# ...
```
Benchmark
If you're using Bun, you probably love the CLI's incredible speed - so do I. That's why the only benchmark I focused on is how much overhead it takes for Bunv to lookup and execute the correct version of Bun.
So this benchmark measures the time it takes for <code>bun --version</code> to run.
```sh
$ hyperfine -N --warmup 10 --runs 1000 '/home/aklinker1/.bunv/versions/1.1.26/bin/bun --version' '/home/aklinker1/.bunv/bin/bun --version'
Benchmark 1: /home/aklinker1/.bunv/versions/1.1.26/bin/bun --version
Time (mean ± σ): 1.5 ms ± 0.1 ms [User: 1.0 ms, System: 0.4 ms]
Range (min … max): 1.3 ms … 2.3 ms 1000 runs
Benchmark 2: /home/aklinker1/.bunv/bin/bun --version
Time (mean ± σ): 2.0 ms ± 0.1 ms [User: 1.0 ms, System: 0.9 ms]
Range (min … max): 1.7 ms … 2.3 ms 1000 runs
Summary
/home/aklinker1/.bunv/versions/1.1.26/bin/bun --version ran
1.37 ± 0.12 times faster than /home/aklinker1/.bunv/bin/bun --version
```
1.5ms without <code>bunv</code> vs 2.0ms with it. While it's technically 1.37x slower, it's only <strong><em>0.5ms of overhead</em></strong> - unnoticable to a human.
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
<code>hyperfine</code> struggles to accurately benchmark commands that exit in less than 5ms... If anyone knows a better way to benchmark this, please open a PR!
</blockquote>
Debugging
To print debug logs, set the <code>DEBUG</code> environment variable to <code>bunv</code>:
<code>sh
$ DEBUG=bunv bun --version</code>
Development
```sh
Build all executables (bun, bunx, bunv) to ./zig-out/bin
$ zig build
Build and run an executable
$ zig build bun
$ zig build bunx
$ zig build bunv
Pass args to the executable
$ zig build
$ ./zig-out/bin/bun --version
$ ./zig-out/bin/bunx --version
$ ./zig-out/bin/bunv --version
Build and install production executables to ~/.bunv/bin
$ zig build --release=fast --prefix ~/.bunv
```
Release
To create a release, run the <a>"Release" action</a>.
This project uses conventional commits, so the release workflow will bump the version and create the GitHub release automatically. | [] |
https://avatars.githubusercontent.com/u/41784264?v=4 | zig-lamp | jinzhongjia/zig-lamp | 2025-02-06T05:05:07Z | Improve the zig experience in neovim | main | 1 | 20 | 1 | 20 | https://api.github.com/repos/jinzhongjia/zig-lamp/tags | - | [
"neovim",
"neovim-lua-plugin",
"neovim-plugin",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 84 | false | 2025-05-17T17:30:39Z | true | true | 0.14.0 | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/5316157?v=4 | zircon | vascocosta/zircon | 2024-09-18T07:40:40Z | A simple IRC library written in Zig. | main | 0 | 19 | 0 | 19 | https://api.github.com/repos/vascocosta/zircon/tags | MIT | [
"irc",
"irc-protocol",
"network",
"tls",
"zig",
"zig-lib",
"zig-library",
"zig-package",
"ziglang"
] | 6,482 | false | 2025-05-02T12:58:50Z | true | true | 0.14.0 | github | [
{
"commit": "1b0228642771ba3efddb92279294e734776191e9.tar.gz",
"name": "tls",
"tar_url": "https://github.com/ianic/tls.zig/archive/1b0228642771ba3efddb92279294e734776191e9.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ianic/tls.zig"
}
] | zircon
A simple IRC library written in Zig.
The <code>zircon</code> library is easy to use, allowing the creation of either general IRC clients or bots. One of its core concepts is the use of threads for better performance. However this is done behind the scenes in a simple way, with a dedicated thread to write messages to the server, using the main thread to read messages from the server in the main client loop (<code>zircon.Client.loop</code>) and providing a callback mechanism to the user code.
Features
<ul>
<li>Multithreaded design</li>
<li>Good network performance</li>
<li>Simple API (callback based)</li>
<li>TLS connection support</li>
<li>Minimal dependencies (TLS)</li>
<li>Extensive documentation</li>
</ul>
Installation
Save zircon as a dependency in <code>build.zig.zon</code> with zig fetch
<code>sh
zig fetch --save git+https://github.com/vascocosta/zircon.git</code>
Configure zircon as a module in <code>build.zig</code>
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const exe = b.addExecutable(.{
.name = "myproject",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
const zircon = b.dependency("zircon", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zircon", zircon.module("zircon"));
exe.linkLibC();
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
</code>
}
```
Import zircon into your code
<code>zig
const zircon = @import("zircon");</code>
Usage
<a>API Documentation</a>
By design, the user isn't required to create any threads for simple applications like a bot. The main client loop runs on the main thread and that loop calls the callback function pointed to by <code>msg_callback</code>. One way to use this library is to define this callback in the user code to customise how to reply to incoming IRC messages with your own IRC messages making use of <code>zircon.Message</code>. You can think of this callback pattern as something that triggers when a message event happens, letting you react with another message.
By default this callback you define also runs on the main thread, but you can use the <code>spawn_thread</code> callback to override this quite easily, by returning true to automatically enable a worker thread depending on the kind of message received. This is especially useful for creating long running commands in a background thread, without the need to spawn it yourself.
For more complex use cases, like a general purpose client, you may want to create your own thread(s) to handle user input like commands. However, you should still use the main client loop and its <code>msg_callback</code> to handle incoming IRC messages. Make sure you read the two examples below to understand in more detail how <code>zircon</code> works in both scenarios...
Examples
Simple IRC bot
```zig
const std = @import("std");
const zircon = @import("zircon");
/// Constants used to configure the bot.
const user = "zirconbot";
const nick = "zirconbot";
const real_name = "zirconbot";
const server = "irc.quakenet.org";
const port = 6667;
const tls = false;
var join_channels = [_][]const u8{"#geeks"};
const prefix_char = "!";
/// Global Debug Allocator singleton.
var debug_allocator = std.heap.DebugAllocator(.{}).init;
pub fn main() !void {
const allocator = debug_allocator.allocator();
defer _ = debug_allocator.deinit();
<code>// Create a zircon.Client with a given configuration.
var client = try zircon.Client.init(allocator, .{
.user = user,
.nick = nick,
.real_name = real_name,
.server = server,
.port = port,
.tls = tls,
.channels = &join_channels,
});
defer client.deinit();
// Connect to the IRC server and perform registration.
try client.connect();
try client.register();
// Enter the main loop that keeps reading incoming IRC messages forever.
// The client loop accepts a LoopConfig struct with two optional fields.
// These two fields, .msg_callback and .spawn_thread are callback pointers.
// You set them to custom functions you define to customise the main loop.
// .msg_callback lets you answer any received IRC message with another one.
// .spawn_thread lets you tweak if you spawn a thread to run .msg_callback.
try client.loop(.{
.msg_callback = msgCallback,
.spawn_thread = spawnThread,
});
</code>
}
/// msgCallback is called by zircon.Client.loop when a new IRC message arrives.
/// The message parameter holds the IRC message that arrived from the server.
/// You can switch on the message tagged union to reply based on its kind.
/// On this example we only care about messages of type JOIN, PRIVMSG or PART.
/// To reply to each message we finally return another message to the loop.
fn msgCallback(message: zircon.Message) ?zircon.Message {
switch (message) {
.JOIN => |msg| {
return zircon.Message{
.PRIVMSG = .{
.targets = msg.channels,
.text = "Welcome to the channel!",
},
};
},
.PRIVMSG => |msg| {
if (std.mem.indexOf(u8, msg.text, prefix_char) != 0) return null;
<code> if (Command.parse(msg.prefix, msg.targets, msg.text)) |command| {
return command.handle();
}
return null;
},
.PART => |msg| {
if (msg.reason) |msg_reason| {
if (std.mem.containsAtLeast(u8, msg_reason, 1, "goodbye")) {
return zircon.Message{
.PRIVMSG = .{
.targets = msg.channels,
.text = "Goodbye for you too!",
},
};
}
}
},
.NICK => |msg| {
return zircon.Message{ .PRIVMSG = .{
.targets = "#geeks",
.text = msg.nickname,
} };
},
else => return null,
}
return null;
</code>
}
/// spawnThread is called by zircon.Client.loop to decide when to spawn a thread.
/// The message parameter holds the IRC message that arrived from the server.
/// You can switch on the message tagged union to decide based on its kind.
/// On this example we only care about messages of type PRIVMSG or PART.
/// To spawn a thread we return true to the loop or false otherwise.
/// We should spawn a thread for long running tasks like for instance a bot command.
/// Otherwise we might block the main thread where zircon.Client.loop is running.
fn spawnThread(message: zircon.Message) bool {
switch (message) {
.PRIVMSG => |data| {
if (std.ascii.startsWithIgnoreCase(data.text, prefix_char)) {
return true;
} else {
return false;
}
},
.PART => return true,
else => return false,
}
}
/// Command encapsulates each command that our IRC bot supports.
pub const Command = struct {
name: CommandName,
prefix: ?zircon.Prefix,
params: []const u8,
targets: []const u8,
<code>pub const CommandName = enum {
echo,
help,
quit,
};
const map = std.StaticStringMap(Command.CommandName).initComptime(.{
.{ "echo", CommandName.echo },
.{ "help", CommandName.help },
.{ "quit", CommandName.quit },
});
pub fn parse(prefix: ?zircon.Prefix, targets: []const u8, text: []const u8) ?Command {
var iter = std.mem.tokenizeAny(u8, text, &std.ascii.whitespace);
const name = iter.next() orelse return null;
if (name.len < 2) return null;
return .{
.name = map.get(name[1..]) orelse return null,
.prefix = prefix,
.params = iter.rest(),
.targets = targets,
};
}
pub fn handle(self: Command) ?zircon.Message {
switch (self.name) {
.echo => return echo(self.targets, self.params),
.help => return help(self.prefix, self.targets),
.quit => return quit(self.params),
}
}
fn echo(targets: []const u8, params: []const u8) ?zircon.Message {
return zircon.Message{
.PRIVMSG = .{
.targets = targets,
.text = params,
},
};
}
fn help(prefix: ?zircon.Prefix, targets: []const u8) ?zircon.Message {
return zircon.Message{
.PRIVMSG = .{
.targets = if (prefix) |p| p.nick orelse targets else targets,
.text = "This is the help message!",
},
};
}
fn quit(params: []const u8) ?zircon.Message {
return zircon.Message{
.QUIT = .{
.reason = params,
},
};
}
</code>
};
```
Build simple IRC bot example
<code>git clone https://github.com/vascocosta/zircon.git
cd zircon/examples/simplebot
zig build -Doptimize=ReleaseSafe</code>
Simple IRC client
```zig
const std = @import("std");
const zircon = @import("zircon");
/// Constants used to configure the client.
const user = "zirconclient";
const nick = "zirconclient";
const real_name = "zirconclient";
const server = "irc.quakenet.org";
const port = 6667;
const tls = false;
var join_channels = [_][]const u8{"#aviation"};
/// Global Debug Allocator singleton.
var debug_allocator = std.heap.DebugAllocator(.{}).init;
pub fn main() !void {
const allocator = debug_allocator.allocator();
defer _ = debug_allocator.deinit();
<code>// Create a zircon.Client with a given configuration.
var client = try zircon.Client.init(allocator, .{
.user = user,
.nick = nick,
.real_name = real_name,
.server = server,
.port = port,
.tls = tls,
.channels = &join_channels,
});
defer client.deinit();
// Connect to the IRC server and perform registration.
try client.connect();
try client.register();
std.debug.print("Connected...\n", .{});
// Spawn a thread to execute clientWorker with our client logic.
std.Thread.sleep(6000_000_000);
const client_worker = try std.Thread.spawn(.{}, clientWorker, .{&client});
client_worker.detach();
// Enter the main loop that keeps reading incoming IRC messages forever.
// The client loop accepts a LoopConfig struct with two optional fields.
// These two fields, .msg_callback and .spawn_thread are callback pointers.
// You set them to custom functions you define to customise the main loop.
// .msg_callback lets you answer any received IRC message with another one.
// .spawn_thread lets you tweak if you spawn a thread to run .msg_callback.
try client.loop(.{
.msg_callback = msgCallback,
.spawn_thread = spawnThread,
});
</code>
}
/// msgCallback is called by zircon.Client.loop when a new IRC message arrives.
/// The message parameter holds the IRC message that arrived from the server.
/// You can switch on the message tagged union to reply based on its kind.
/// On this example we only care about messages of type JOIN, PART or PRIVMSG.
/// We print the targets, nick and text of every message of type PRIVMSG.
fn msgCallback(message: zircon.Message) ?zircon.Message {
switch (message) {
.JOIN => |msg| {
const msg_nick = extractNick(msg.prefix);
std.debug.print("\n[{s}] {s} has joined.\n", .{ msg.channels, msg_nick });
},
.PART => |msg| {
const msg_nick = extractNick(msg.prefix);
std.debug.print("\n[{s}] {s} has left [{s}].\n", .{ msg.channels, msg_nick, msg.reason orelse "" });
},
.PRIVMSG => |msg| {
const msg_nick = extractNick(msg.prefix);
std.debug.print("\n[{s}] <{s}>: {s}\n", .{ msg.targets, msg_nick, msg.text });
},
else => return null,
}
<code>std.debug.print("[#] <{s}>: ", .{nick});
return null;
</code>
}
/// Helper function to extract the nick from a prefix.
fn extractNick(prefix: ?zircon.Prefix) []const u8 {
return if (prefix) |p|
if (p.nick) |n| n else "N/A"
else
"NA";
}
/// spawnThread is called by zircon.Client.loop to decide when to spawn a thread.
/// The message parameter holds the IRC message that arrived from the server.
/// You can switch on the message tagged union to decide based on its kind.
/// On this example we don't care about any particular kind of message.
/// Since this is a more general client, the threading logic happens elsewhere.
/// To spawn a thread we return true to the loop or false otherwise.
fn spawnThread(_: zircon.Message) bool {
return false;
}
/// This is where we define the logic of our IRC client (handling commands).
fn clientWorker(client: *zircon.Client) !void {
const allocator = debug_allocator.allocator();
const stdin_reader = std.io.getStdIn().reader();
while (true) {
std.debug.print("[#] <{s}>: ", .{nick});
const raw_command = try stdin_reader.readUntilDelimiterAlloc(allocator, '\n', 512);
defer allocator.free(raw_command);
<code> const command = Command.parse(raw_command) orelse continue;
switch (command.name) {
// /say <#target(s)> <text>
.say => {
var iter = std.mem.tokenizeAny(u8, command.params, &std.ascii.whitespace);
const targets = iter.next() orelse continue;
const text = iter.rest();
try client.privmsg(targets, text);
},
// /join <#channel(s)>
.join => {
try client.join(command.params);
},
// /part <#channel(s)> [reason]
.part => {
var iter = std.mem.tokenizeAny(u8, command.params, &std.ascii.whitespace);
const channels = iter.next() orelse continue;
const reason = iter.rest();
try client.part(channels, reason);
},
// /quit [reason]
.quit => try client.quit(command.params),
}
}
</code>
}
/// Command encapsulates each command that our IRC client supports.
const Command = struct {
name: CommandName,
params: []const u8,
<code>const CommandName = enum {
join,
part,
quit,
say,
};
const map = std.StaticStringMap(Command.CommandName).initComptime(.{
.{ "/join", CommandName.join },
.{ "/part", CommandName.part },
.{ "/quit", CommandName.quit },
.{ "/say", CommandName.say },
});
fn parse(raw_command: []const u8) ?Command {
var iter = std.mem.tokenizeAny(u8, raw_command, &std.ascii.whitespace);
const name = iter.next() orelse return null;
if (name.len < 2) return null;
return .{
.name = map.get(name) orelse return null,
.params = iter.rest(),
};
}
</code>
};
```
Build simple IRC client example
<code>git clone https://github.com/vascocosta/zircon.git
cd zircon/examples/simpleclient
zig build -Doptimize=ReleaseSafe</code> | [] |
https://avatars.githubusercontent.com/u/47111091?v=4 | writing-hypervisor-in-zig | smallkirby/writing-hypervisor-in-zig | 2024-10-13T10:58:34Z | Writing Type-1 Hypervisor in Zig from scratch. | master | 3 | 18 | 3 | 18 | https://api.github.com/repos/smallkirby/writing-hypervisor-in-zig/tags | CC0-1.0 | [
"hypervisor",
"zig"
] | 9,852 | false | 2025-04-07T12:43:25Z | false | false | unknown | github | [] | Writing Hypervisor in Zig
Blog series where we write a hypervisor from scratch in Zig.
Refer to <a>smallkirby/ymir</a>'s <code>whiz-*</code> branches for the reference implementation.
Note that these branches might be not necessarily up-to-date.
Please refer to <code>master</code> branch to check available fixes and updates.
Development
<code>sh
mdbook serve --open</code>
Improvement
以下のような場合には、筆者に対して更新をリクエストしてください:
<ul>
<li>説明に技術的な誤りがある</li>
<li>分かりにくい表現がある</li>
<li>誤字・脱字等を見つけた</li>
<li>提示されたコードが動かない、または分かりにくい</li>
<li>本シリーズでは扱っていない内容を新たに扱ってほしい</li>
</ul>
更新リクエストは <a>GitHub</a> の Issue や Pull Request で受け付けています。
PR を作る前に Issue を建てる必要はありません。
リクエストの大小や内容の正誤に関わらず修正依頼やリクエスト等を歓迎します。
LICENSE
<a>CC0-1.0</a> except where otherwise <a>noted</a>. | [] |
https://avatars.githubusercontent.com/u/14295318?v=4 | ollama-zig | dravenk/ollama-zig | 2025-01-07T11:18:13Z | Ollama Zig library | main | 0 | 17 | 2 | 17 | https://api.github.com/repos/dravenk/ollama-zig/tags | MIT | [
"deepseek",
"llama",
"llm",
"llms",
"ollama",
"ollama-api",
"ollama-client",
"zig",
"zig-library",
"zig-package"
] | 81 | false | 2025-05-20T00:03:18Z | true | true | unknown | github | [] | Ollama Zig Library
The Ollama Zig library provides the easiest way to integrate Zig 0.14+ projects with <a>Ollama</a>.
Prerequisites
<ul>
<li><a>Ollama</a> should be installed and running</li>
<li>Pull a model to use with the library: <code>ollama pull <model></code> e.g. <code>ollama pull llama3.2</code></li>
<li>See <a>Ollama.com</a> for more information on the models available.</li>
</ul>
Install
<code>sh
zig fetch --save git+https://github.com/dravenk/ollama-zig.git</code>
Usage
Adding to build.zig
<code>zig
const ollama = b.dependency("ollama-zig", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("ollama", ollama.module("ollama"));</code>
Import it in your code:
<code>zig
const ollama = @import("ollama");</code>
See <a>types.zig</a> for more information on the response types.
Streaming responses
Response streaming can be enabled by setting <code>.stream = true</code>.
<code>zig
try ollama.chat(.{ .model = "llama3.2", .stream = true, .messages = &.{
.{ .role = .user, .content = "Why is the sky blue?" },
} });</code>
API
The Ollama Zig library's API is designed around the <a>Ollama REST API</a>
Chat
<code>zig
var responses = try ollama.chat(.{ .model = "llama3.2", .stream = false, .messages = &.{
.{ .role = .user, .content = "Why is the sky blue?" },
} });
while (try responses.next()) |chat| {
const content = chat.message.content;
std.debug.print("{s}", .{content});
}</code>
Generate
```zig
var responses = try ollama.generate(.{ .model = "llama3.2", .prompt = "Why is the sky blue?" });
while (try responses.next()) |response| {
const content = response.response;
std.debug.print("{s}", .{content});
}
```
Show
<code>zig
try ollama.show("llama3.2");</code>
Create
<code>zig
try ollama.create(.{ .model = "mario", .from = "llama3.2", .system = "You are Mario from Super Mario Bros." });</code>
Copy
<code>zig
try ollama.copy("llama3.2", "user/llama3.2");</code>
Delete
(In plan)Wait for the upstream update. see https://github.com/ollama/ollama/issues/8753
<code>zig
try ollama.delete("llama3.2")</code>
Pull
<code>zig
try ollama.pull("llama3.2")</code>
Push
<code>zig
try ollama.push(.{ .model = "dravenk/llama3.2"});</code>
Embed or Embed (batch)
```zig
var input = std.ArrayList([]const u8).init(allocator);
try input.append("The sky is blue because of rayleigh scattering");
try input.append("Grass is green because of chlorophyll");
<code>var responses = try ollama.embed(.{
.model = "dravenk/llama3.2",
.input = try input.toOwnedSlice(),
});
while (try responses.next()) |response| {
std.debug.print("total_duration: {d}\n", .{response.total_duration.?});
std.debug.print("prompt_eval_count: {d}\n", .{response.prompt_eval_count.?});
}
</code>
```
Ps
<code>zig
try ollama.ps()</code>
Version
<code>zig
try ollama.version()</code>
Errors
Errors are raised if requests return an error status or if an error is detected while streaming.
<code>zig</code> | [] |
https://avatars.githubusercontent.com/u/146810011?v=4 | TerrainZigger | JosefAlbers/TerrainZigger | 2024-08-10T05:36:35Z | TerrainZigger: A procedural 3D terrain generator and visualizer written in Zig using Raylib | main | 0 | 17 | 1 | 17 | https://api.github.com/repos/JosefAlbers/TerrainZigger/tags | MIT | [
"3d",
"3d-engine",
"3d-game",
"3d-graphics",
"3d-models",
"procedural-generation",
"procedural-terrain",
"raylib",
"raylib-zig",
"wasm",
"zig",
"ziglang"
] | 7,284 | false | 2025-05-20T22:58:52Z | false | false | unknown | github | [] | TerrainZigger
TerrainZigger is a 3D terrain generator written in Zig using the Raylib library. It creates procedurally generated landscapes with dynamic water features, offering an interactive 3D visualization.
Features
<ul>
<li>Procedural terrain generation using Fractional Brownian Motion (FBM)</li>
<li>Real-time 3D rendering with Raylib</li>
<li>Interactive camera controls for exploring the terrain</li>
<li>Dynamic water level adjustment</li>
<li>On-the-fly terrain regeneration</li>
<li>Customizable terrain parameters</li>
</ul>
Prerequisites
To build and run TerrainZigger, you'll need:
<ul>
<li><a>Zig</a> (version 0.13.0 recommended)</li>
<li><a>Raylib</a></li>
</ul>
Building and Running
<ol>
<li>
Clone the repository:
<code>git clone https://github.com/JosefAlbers/TerrainZigger.git
cd TerrainZigger</code>
</li>
<li>
Build the project:
<code>zig build-exe terrain_zigger.zig -lc $(pkg-config --libs --cflags raylib)</code>
</li>
<li>
Run the executable:
<code>./terrain_zigger</code>
</li>
</ol>
Controls
<ul>
<li><strong>R</strong> or <strong>Right Mouse Button</strong>: Regenerate terrain</li>
<li><strong>Left Mouse Button</strong>: Rotate camera</li>
<li><strong>Mouse Wheel</strong>: Zoom in/out</li>
<li><strong>Z</strong>: Reset camera</li>
<li><strong>, (Comma)</strong>: Decrease water level</li>
<li><strong>. (Period)</strong>: Increase water level</li>
</ul>
Customization
You can adjust various parameters in the <code>terrain_zigger.zig</code> file to customize the terrain generation:
<ul>
<li><code>TERRAIN_SIZE</code>: Changes the size of the terrain grid</li>
<li><code>INITIAL_WATER_LEVEL</code>: Sets the initial height of the water plane</li>
<li><code>CUBE_SIZE</code>: Modifies the size of individual terrain cubes</li>
</ul>
Feel free to experiment with the <code>fbm</code> function parameters in <code>generateTerrain</code> to create different terrain styles.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is open source and available under the <a>MIT License</a>.
Acknowledgments
<ul>
<li>Terrain generation algorithm inspired by <a>Perlin Noise</a></li>
<li>3D rendering made possible by <a>Raylib</a></li>
</ul>
Happy terrain generating! 🏞️ | [] |
https://avatars.githubusercontent.com/u/42583079?v=4 | zig-prompter | GabrieleInvernizzi/zig-prompter | 2024-12-11T20:13:44Z | zig-prompter is a lightweight and flexible library for building and managing interactive text-based prompts. | main | 0 | 17 | 1 | 17 | https://api.github.com/repos/GabrieleInvernizzi/zig-prompter/tags | MIT | [
"cli",
"prompt",
"terminal",
"zig",
"zig-package"
] | 54 | false | 2025-04-18T13:50:42Z | true | true | unknown | github | [
{
"commit": "b001662c929e2719ee24be585a3120640f946337",
"name": "mibu",
"tar_url": "https://github.com/xyaman/mibu/archive/b001662c929e2719ee24be585a3120640f946337.tar.gz",
"type": "remote",
"url": "https://github.com/xyaman/mibu"
}
] | zig-prompter
<strong>zig-prompter</strong> is a lightweight and flexible library for building and managing interactive text-based prompts in the <a>Zig programming language</a>. Whether you're creating command-line tools, text-based games, or utilities requiring user input, <strong>zig-prompter</strong> simplifies the process with intuitive APIs and a robust feature set.
Installation
First, add zig-prompter to your <code>build.zig.zon</code> file:
<code>bash
zig fetch --save git+https://github.com/GabrieleInvernizzi/zig-prompter/</code>
Update your <code>build.zig</code> file to include the dependency:
```zig
const prompter_dep = b.dependency("prompter", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("prompter", prompter_dep.module("prompter"));
```
Here’s an example of using <strong>zig-prompter</strong> to create a simple selection prompt:
```zig
const std = @import("std");
const Prompter = @import("prompter");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const stdout = std.io.getStdOut();
<code>const theme = Prompter.Themes.SimpleTheme{};
var p = Prompter.Prompt.init(allocator, theme.theme());
const opts = [_][]const u8{ "Option 1", "Option 2", "Option 3" };
const sel_opt = try p.option("Select an option", &opts, 1);
if (sel_opt) |o| {
try stdout.writer().print("The selected option was: {s} (idx: {d})\n", .{ opts[o], o });
} else {
try stdout.writer().writeAll("The selection was aborted.\n");
}
</code>
}
```
For a more exhaustive example, take a look at the <a>example</a> directory.
Features
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> String prompt
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Interactive option selection prompt
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Confirmation prompt
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Password prompt
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Input validation
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Advanced support for themes and personalization
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Include more themes
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Windows support
Contributions
Contributions are always welcome and greatly appreciated! Whether it's fixing bugs, adding features, improving documentation, or enhancing examples, your input helps make <strong>zig-prompter</strong> even better. Feel free to open issues to discuss potential improvements or submit pull requests directly.
Thank you for your support!
Acknowledgments
This library was inspired by the fantastic <strong>Rust</strong> library <a>Dialoguer</a>. | [] |
https://avatars.githubusercontent.com/u/124872?v=4 | zig-hiae | jedisct1/zig-hiae | 2025-02-06T00:31:55Z | HiAE - A High-Throughput Authenticated Encryption Algorithm for Cross-Platform Efficiency. | master | 0 | 16 | 0 | 16 | https://api.github.com/repos/jedisct1/zig-hiae/tags | - | [
"aead",
"aes",
"encryption",
"hiae",
"zig",
"zig-package"
] | 1,706 | false | 2025-05-14T19:19:55Z | true | true | 0.14.0 | github | [] | HiAE: A High-Throughput Authenticated Encryption Algorithm for Cross-Platform Efficiency
A Zig implementation of HiAE, along with support for parallel variants.
Benchmarks
Encryption
Zen4
| Variant | Throughput |
| :------ | ---------: |
| HiAE | 252.0 Gb/s |
| HiAEX2 | 449.9 Gb/s |
| HiAEX4 | 472.8 Gb/s |
Apple M1
| Variant | Throughput |
| :------ | ---------: |
| HiAE | 169.5 Gb/s |
| HiAEX2 | 133.9 Gb/s |
| HiAEX4 | 98.3 Gb/s |
WebAssembly (lime1+simd128)
| Variant | Throughput |
| :------ | ---------: |
| HiAE | 9.2 Gb/s |
| HiAEX2 | 11.0 Gb/s |
| HiAEX4 | 7.7 Gb/s |
MAC
Zen4 (likely limited by the memory bandwidth)
| Variant | Throughput |
| :--------- | ---------: |
| HiAE-MAC | 315.8 Gb/s |
| HiAEX2-MAC | 530.4 Gb/s |
| HiAEX4-MAC | 522.2 Gb/s |
| LeMAC | 345.0 Gb/s |
Apple M1
| Variant | Throughput |
| :--------- | ---------: |
| HiAE-MAC | 163.1 Gb/s |
| HiAEX2-MAC | 182.9 Gb/s |
| HiAEX4-MAC | 138.8 Gb/s |
| LeMAC | 219.2 Gb/s |
WebAssembly (lime1+simd128)
| Variant | Throughput |
| :------ | ---------: |
| HiAE | 9.8 Gb/s |
| HiAEX2 | 12.0 Gb/s |
| HiAEX4 | 7.7 Gb/s |
| LeMAC | 10.0 Gb/s |
Circuits
Absorption
Encryption
Inversion
| [] |
https://avatars.githubusercontent.com/u/35976402?v=4 | fzwatch | freref/fzwatch | 2024-11-03T22:33:03Z | A lightweight and cross-platform file watcher for your Zig projects | master | 1 | 16 | 3 | 16 | https://api.github.com/repos/freref/fzwatch/tags | MIT | [
"zig",
"zig-package"
] | 22 | false | 2025-05-14T22:41:55Z | true | true | unknown | github | [] | fzwatch
A lightweight and cross-platform file watcher for your Zig projects.
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
This project exists to support <a>fancy-cat</a> and has limited features.
</blockquote>
Instructions
Run example
You can run the <a>examples</a> like so:
<code>sh
zig build run-<filename></code>
Usage
A basic example can be found under <a>examples</a>. The API is defined as follows:
```zig
pub const Event = enum { modified };
pub const Callback = fn (context: *anyopaque, event: Event) void;
pub const Opts = struct { latency: f16 = 1.0 };
pub fn init(allocator: std.mem.Allocator) !Watcher;
pub fn deinit(self: <em>Watcher) void;
pub fn addFile(self: </em>Watcher, path: []const u8) !void;
pub fn removeFile(self: <em>Watcher, path: []const u8) !void;
pub fn setCallback(self: </em>Watcher, callback: Callback) void;
pub fn start(self: <em>Watcher, opts: Opts) !void;
pub fn stop(self: </em>Watcher) !void;
```
Testing
Run the test suite:
<code>sh
zig build test</code> | [
"https://github.com/freref/fancy-cat"
] |
https://avatars.githubusercontent.com/u/34311583?v=4 | osdialog-zig | ttytm/osdialog-zig | 2024-10-18T13:35:04Z | Cross-platform utility module for Zig to open native dialogs for the filesystem, message boxes, color-picking. | main | 0 | 16 | 1 | 16 | https://api.github.com/repos/ttytm/osdialog-zig/tags | ISC | [
"bindings",
"color-picker",
"dialog",
"filesystem",
"library",
"linux",
"macos",
"module",
"native",
"windows",
"zig",
"zig-package",
"ziglang"
] | 11 | false | 2025-03-29T14:30:50Z | true | true | unknown | github | [
{
"commit": "989a270.tar.gz",
"name": "osdialog",
"tar_url": "https://github.com/ttytm/osdialog/archive/989a270.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ttytm/osdialog"
}
] | osdialog-zig
<a></a>
<a></a>
<a></a>
Cross-platform utility module for Zig to open native dialogs for the filesystem, message boxes, color-picking.
Quickstart
<ul>
<li><a>Installation</a></li>
<li><a>Usage</a></li>
<li><a>Example</a></li>
<li><a>Credits</a></li>
</ul>
Showcase
Linux
Windows
macOS
<b>More Examples</b> Toggle visibility...
Linux
Windows
macOS
Installation
```sh
~//your-awesome-projct
zig fetch --save https://github.com/ttytm/osdialog-zig/archive/main.tar.gz
```
```zig
// your-awesome-projct/build.zig
const std = @import("std");
pub fn build(b: *std.Build) void {
// ..
const osdialog_dep = b.dependency("osdialog", .{});
const exe = b.addExecutable(.{
.name = "your-awesome-projct",
// ..
});
exe.root_module.addImport("osdialog", osdialog_dep.module("osdialog"));
// ...
}
```
Usage
Ref.: <a><code>osdialog-zig/src/lib.zig</code></a>
<code>``zig
/// Opens a message box and returns</code>true<code>if</code>OK<code>or</code>Yes` was pressed.
pub fn message(text: [*:0]const u8, opts: MessageOptions) bool
/// Opens an input prompt with an "OK" and "Cancel" button.
pub fn prompt(allocator: std.mem.Allocator, text: [*:0]const u8, opts: PromptOptions) ?[:0]u8
/// Opens an RGBA color picker and returns the selected <code>Color</code> or <code>null</code> if the selection was canceled.
pub fn color(options: ColorPickerOptions) ?Color
/// Opens a file dialog and returns the selected path or <code>null</code> if the selection was canceled.
pub fn path(allocator: std.mem.Allocator, action: PathAction, options: PathOptions) ?[:0]u8
```
Example
Ref.: <a><code>osdialog-zig/examples/src/main.zig</code></a>
```zig
const std = @import("std");
const osd = @import("osdialog");
pub fn main() void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
<code>_ = osd.message("Hello, World!", .{});
if (!osd.message("Do you want to continue?", .{ .buttons = .yes_no })) {
std.process.exit(0);
}
if (osd.prompt(allocator, "Give me some input", .{})) |input| {
defer allocator.free(input);
std.debug.print("Input: {s}\n", .{input});
}
if (osd.color(.{ .color = .{ .r = 247, .g = 163, .b = 29, .a = 255 } })) |selected| {
std.debug.print("Color RRR,GGG,BBB,AAA: {d},{d},{d},{d}\n", .{ selected.r, selected.g, selected.b, selected.a });
}
if (osd.path(allocator, .open, .{})) |path| {
defer allocator.free(path);
std.debug.print("Selected file: {s}\n", .{path});
}
if (osd.path(allocator, .open_dir, .{})) |path| {
defer allocator.free(path);
}
if (osd.path(allocator, .save, .{ .path = ".", .filename = "myfile.txt" })) |path| {
defer allocator.free(path);
std.debug.print("Save location: {s}\n", .{path});
}
</code>
}
```
```sh
osdialog/examples
zig build run
```
Credits
<ul>
<li><a>AndrewBelt/osdialog</a> - The C project this library is leveraging</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/42317655?v=4 | blackjack-zig | gdonald/blackjack-zig | 2024-09-28T16:24:36Z | Console Blackjack written in Zig | main | 0 | 16 | 1 | 16 | https://api.github.com/repos/gdonald/blackjack-zig/tags | MIT | [
"21",
"blackjack",
"blackjack-game",
"console",
"zig",
"zig-lang"
] | 147 | false | 2025-04-15T11:57:19Z | false | false | unknown | github | [] | blackjack-zig
Console Blackjack written in Zig
Running
<code>sh
zig run main.zig</code>
License
<a></a>
Other Blackjack Implementations:
I've written Blackjack in <a>some other programming languages</a> too. Check them out! | [] |
https://avatars.githubusercontent.com/u/8091245?v=4 | zimq | uyha/zimq | 2024-10-26T08:55:26Z | Zig binding for ZeroMQ | main | 0 | 16 | 2 | 16 | https://api.github.com/repos/uyha/zimq/tags | MIT | [
"bindings",
"zeromq",
"zig",
"zig-package"
] | 92 | false | 2025-05-10T10:53:40Z | true | true | 0.14.0 | github | [
{
"commit": "34f7fa22022bed9e0e390ed3580a1c83ac4a2834.tar.gz",
"name": "libzmq",
"tar_url": "https://github.com/zeromq/libzmq/archive/34f7fa22022bed9e0e390ed3580a1c83ac4a2834.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/zeromq/libzmq"
}
] |
Zig binding for ZeroMQ
<ul>
<li><a>Zig binding for ZeroMQ</a></li>
<li><a>How to use</a></li>
<li><a>Example</a></li>
<li><a>Binding map</a></li>
</ul>
A ZeroMQ wrapper that covers nearly 100% of ZeroMQ's API (skipped functions are
to be deprecated or superseded).
How to use
<ol>
<li>Run the following command to add this project as a dependency</li>
</ol>
<code>sh
zig fetch --save git+https://github.com/uyha/zimq.git</code>
<ol>
<li>In your <code>build.zig</code>, add the following</li>
</ol>
<code>zig
const zimq = b.dependency("zimq", .{
.target = target,
.optimize = optimize,
});
// Replace `exe` with your actual library or executable
exe.root_module.addImport("zimq", zimq.module("zimq"));</code>
Example
```zig
const std = @import("std");
const zimq = @import("zimq");
pub fn main() !void {
const context: *zimq.Context = try .init();
defer context.deinit();
<code>const pull: *zimq.Socket = try .init(context, .pull);
defer pull.deinit();
const push: *zimq.Socket = try .init(context, .push);
defer push.deinit();
try pull.bind("inproc://#1");
try push.connect("inproc://#1");
try push.sendSlice("hello", .{});
var buffer: zimq.Message = .empty();
_ = try pull.recvMsg(&buffer, .{});
std.debug.print("{s}\n", .{buffer.slice().?});
</code>
}
```
Binding map
All the binding functions live in the <code>zimq</code> module.
Context
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> ~~`zmq_ctx_get`~~ (`zmq_ctx_get_ext` is used instead)
- [X] `zmq_ctx_get_ext` -> `Context.get`
- [X] `zmq_ctx_new` -> `Context.init`
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> ~~`zmq_ctx_set`~~ (`zmq_ctx_set_ext` is used instead)
- [X] `zmq_ctx_set_ext` -> `Context.set`
- [X] `zmq_ctx_shutdown` -> `Context.shutdown`
- [X] `zmq_ctx_term` -> `Context.deinit`
Socket
- [X] `zmq_bind` -> `Socket.bind`
- [X] `zmq_close` -> `Socket.deinit`
- [X] `zmq_connect` -> `Socket.connect`
- [X] `zmq_connect_peer` -> `Socket.connectPeer`
- [X] `zmq_disconnect` -> `Socket.disconnect`
- [X] `zmq_getsockopt` -> `Socket.get`
- [X] `zmq_recv` -> `Socket.recv`
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> ~~`zmq_recvmsg`~~ (to be deprecated, `zmq_msg_recv` is used instead)
- [X] `zmq_msg_recv` -> `Socket.recvMsg`
- [X] `zmq_send` -> `Socket.sendBuffer`
- [X] `zmq_send_const` -> `Socket.sendConst`
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> ~~`zmq_sendmsg`~~ (to be deprecated, `zmq_msg_send` is used instead)
- [X] `zmq_msg_send` -> `Socket.sendMsg`
- [X] `zmq_setsockopt` -> `Socket.set`
- [X] `zmq_socket` -> `Socket.init`
- [X] `zmq_socket_monitor` -> `Socket.monitor`
- [X] `zmq_socket_monitor_versioned` -> `Socket.monitorVersioned`
- [X] `zmq_socket_monitor_pipes_stats` -> `Socket.pipesStats`
- [X] `zmq_unbind` -> `Socket.unbind`
Message
- [X] `zmq_msg_close` -> `Message.deinit`
- [X] `zmq_msg_copy` -> `Message.copy`
- [X] `zmq_msg_data` -> `Message.data` (`Message.slice` provides better access to
the underlying data)
- [X] `zmq_msg_get` -> `Message.get`
- [X] `zmq_msg_gets` -> `Message.gets`
- [X] `zmq_msg_init` -> `Message.empty`
- [X] `zmq_msg_init_buffer` -> `Message.withBuffer`
- [X] `zmq_msg_init_data` -> `Message.withData`
- [X] `zmq_msg_init_size` -> `Message.withSize`
- [X] `zmq_msg_more` -> `Message.more`
- [X] `zmq_msg_move` -> `Message.move`
- [X] `zmq_msg_routing_id` -> `Message.getRoutingId`
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> `zmq_msg_set` (currently useless)
- [X] `zmq_msg_set_routing_id` -> `Message.setRoutingId`
- [X] `zmq_msg_size` -> `Message.size`
Polling
- [X] `zmq_poll` -> `poll.poll`
- [X] `zmq_ppoll` -> `poll.ppoll`
Poller
- [X] `zmq_poller_new` -> `Poller.init`
- [X] `zmq_poller_destroy` -> `Poller.deinit`
- [X] `zmq_poller_size` -> `Poller.size`
- [X] `zmq_poller_add` -> `Poller.add`
- [X] `zmq_poller_modify` -> `Poller.modify`
- [X] `zmq_poller_remove` -> `Poller.remove`
- [X] `zmq_poller_add_fd` -> `Poller.add_fd`
- [X] `zmq_poller_modify_fd` -> `Poller.modify_fd`
- [X] `zmq_poller_remove_fd` -> `Poller.remove_fd`
- [X] `zmq_poller_wait` -> `Poller.wait`
- [X] `zmq_poller_wait_all` -> `Poller.wait_all`
- [X] `zmq_poller_fd` -> `Poller.fd`
Proxy
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> `zmq_proxy` -> `proxy`
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> `zmq_proxy_steerable` -> `proxySteerable`
Timer
- [X] `zmq_timers_new` -> `Timers.init`
- [X] `zmq_timers_destroy` -> `Timers.deinit`
- [X] `zmq_timers_add` -> `Timers.add`
- [X] `zmq_timers_cancel` -> `Timers.cancel`
- [X] `zmq_timers_set_interval` -> `Timers.setInterval`
- [X] `zmq_timers_reset` -> `Timers.reset`
- [X] `zmq_timers_timeout` -> `Timers.timeout`
- [X] `zmq_timers_execute` -> `Timers.execute`
Runtime inspection
- [X] `zmq_has` -> `has`
- [X] `zmq_version` -> `version`
Atomic Counter
- [X] `zmq_atomic_counter_dec` -> `AtomicCounter.dec`
- [X] `zmq_atomic_counter_destroy` -> `AtomicCounter.deinit`
- [X] `zmq_atomic_counter_inc` -> `AtomicCounter.inc`
- [X] `zmq_atomic_counter_new` -> `AtomicCounter.init`
- [X] `zmq_atomic_counter_set` -> `AtomicCounter.set`
- [X] `zmq_atomic_counter_value` -> `AtomicCounter.value`
Utilities
- [X] `zmq_errno` -> `errno`
- [X] `zmq_strerror` -> `strerror`
Curve
- [X] `zmq_curve_keypair` -> `curve.keypair`
- [X] `zmq_curve_public` -> `curve.publicKey`
Z85
- [X] `zmq_z85_encode` -> `z85.encode`
- [X] `zmq_z85_decode` -> `z85.decode`
| [] |
https://avatars.githubusercontent.com/u/17029738?v=4 | pomodozig | jecaro/pomodozig | 2025-01-03T13:01:17Z | Terminal based pomodoro timer | main | 0 | 16 | 0 | 16 | https://api.github.com/repos/jecaro/pomodozig/tags | - | [
"polybar",
"pomodoro",
"zig"
] | 82 | false | 2025-03-17T11:26:16Z | true | true | unknown | github | [] | pomodozig
<a></a>
<code>pomodozig</code> is a simple terminal based pomodoro timer written in <code>Zig</code>. It can
be used in the terminal or embedded in a status bar such as <code>polybar</code> as shown
below.
Installation
A static binary is available in the <a>releases</a> page. It should work
on any linux distribution. For nix users, an overlay is available in <a>the flake
file</a>.
Usage
<code>$ pomodozig -h
Usage: pomodozig
[-t <task_length>] Task length in minutes (default: 25 mins)
[-sb <short_break>] Short break length in minutes (default: 5 mins)
[-n <num_pomodoros>] Number of pomodoros before long break (default: 4)
[-lb <long_break>] Long break length in minutes (default: 15 mins)
[-s] Disable notifications
[-h] Show this help message</code>
Use in Polybar
Here is an example of how to embed <code>pomodozig</code> in <code>polybar</code>:
<code>ini
[module/pomodozig]
type = custom/script
label = 🍅 %output%
interval = 1
exec = pomodozig
tail = true
; pause/resume
click-left = kill -USR1 %pid%
; reset
click-right = kill -USR2 %pid%</code>
Controls
<code>pomodozig</code> can be controlled with the following keys:
<ul>
<li><code>q</code> Quit</li>
<li><code>p</code> Pause/Resume</li>
<li><code>r</code> Reset the current task/break. Hit twice to reset the whole session.</li>
</ul>
or with signals:
<ul>
<li><code>SIGUSR1</code> Pause/Resume</li>
<li><code>SIGUSR2</code> Reset the current task/break. Send twice to reset the whole
session.</li>
</ul>
Notifications
<code>pomodozig</code> notifies you when a task or break is over, using <code>notify-send</code> the
program shipped with <code>libnotify</code>. It can be disabled with the <code>-s</code> flag. | [] |
https://avatars.githubusercontent.com/u/12397229?v=4 | zgroup | flowerinthenight/zgroup | 2024-08-17T04:20:30Z | Cluster membership manager using the SWIM Protocol and Raft's leader election sub-protocol. | main | 0 | 15 | 0 | 15 | https://api.github.com/repos/flowerinthenight/zgroup/tags | MIT | [
"cluster-manager",
"distributed-systems",
"gossip",
"gossip-protocol",
"leader-election",
"memberlist",
"raft",
"swim-protocol",
"udp",
"zig",
"ziglang"
] | 282 | false | 2025-03-30T14:29:04Z | true | true | unknown | github | [
{
"commit": "v0.1.2.tar.gz",
"name": "zbackoff",
"tar_url": "https://github.com/flowerinthenight/zbackoff/archive/v0.1.2.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/flowerinthenight/zbackoff"
}
] | <strong>NOTE</strong>: Still in alpha stage. APIs may change.
<a></a>
<a></a>
(This repo is mirrored to <a>https://codeberg.org/flowerinthenight/zgroup</a>).
Overview
<strong>zgroup</strong> is a <a>Zig</a> library that can manage cluster membership and member failure detection. It uses a combination of <a>SWIM Protocol</a>'s gossip-style information dissemination, and <a>Raft</a>'s leader election algorithm (minus the log management) to track cluster changes.
On payload size
One of zgroup's main goal is to be able to track clusters with sizes that can change dynamically over time (e.g. <a>Kubernetes Deployments</a>, <a>GCP Instance Groups</a>, <a>AWS Autoscaling Groups</a>, etc.) with minimal dependencies and network load. All of my previous related works so far, depend on some external service (see <a>spindle</a>, <a>hedge</a>), using traditional heartbeating, to achieve this. This heartbeating technique usually suffers from increasing payload sizes (proportional to cluster sizes) as clusters get bigger. But I wanted a system that doesn't suffer from that side effect. Enter <a>SWIM</a>'s infection-style information dissemination. It can use a constant payload size regardless of the cluster size. SWIM uses a combination of <code>PING</code>s, <code>INDIRECT-PING</code>s, and <code>ACK</code>s to detect member failures while piggybacking on these same messages to propagate membership updates (gossip protocol). Currently, zgroup only uses SWIM's direct probing protocol; it doesn't fully implement the Suspicion sub-protocol (yet).
At the moment, zgroup uses a single, 64-byte payload for all its messages, including leader election (see below).
On leader election
I also wanted some sort of leader election capability without depending on an external lock service. At the moment, zgroup uses <a>Raft</a>'s leader election algorithm sub-protocol (without the log management) to achieve this. I should note that Raft's leader election algorithm depends on stable membership for it work properly, so zgroup's leader election is a best-effort basis only; split-brain can still happen while the cluster size is still changing. Additional code guards are added to minimize split-brain in these scenarios but it's not completely eliminated. In my use-case (and testing), gradual cluster size changes are mostly stable, while sudden changes with huge size deltas are not. For example, a big, sudden jump from three nodes (zgroup's minimum size) to, say, a hundred, due to autoscaling, would cause a split-brain. Once the target size is achieved however, a single leader will always be elected.
A note on Raft's random timeout range during leader election: zgroup's leader tracks ping latency averages and attempts to adjust the timeout range accordingly to accomodate for cluster size changes overtime.
Join address
For a node to join an existing cluster, it needs a joining address. While zgroup exposes a <code>join()</code> function for this, it also provides a callback mechanism, providing callers with a join address. This address can then be stored to an external store for the other nodes to use. Internally, zgroup uses the node with the highest IP(v4) address in the group.
Sample binary
A <a>sample</a> binary is provided to show a way to use the library. There are two ways to run the sample:
<ul>
<li>Specifying the join address manually</li>
<li>Using an external service to get the join address</li>
</ul>
Local with join address
```sh
Build the sample binary:
$ zig build --summary all
Run the 1st process. The expected args look like:
./zgroup groupname member_ip:port [join_ip:port]
Run the first process (join to self).
$ ./zig-out/bin/zgroup group1 0.0.0.0:8080 0.0.0.0:8080
Then you can run additional instances.
Join through the 1st process/node (different terminal):
$ ./zig-out/bin/zgroup group1 0.0.0.0:8081 0.0.0.0:8080
Join through the 2nd process/node (different terminal):
$ ./zig-out/bin/zgroup group1 0.0.0.0:8082 0.0.0.0:8081
Join through the 1st process/node (different terminal):
$ ./zig-out/bin/zgroup group1 0.0.0.0:8083 0.0.0.0:8080
and so on...
```
Local with an external service
If configured, the sample binary uses a free service, <a>https://keyvalue.immanuel.co/</a>, as a store for the join address.
```sh
Build the sample binary:
$ zig build --summary all
Generate UUID:
$ uuidgen
{output}
Run the 1st process. The expected args look like:
./zgroup groupname member_ip:port
Run the first process:
$ ZGROUP_JOIN_PREFIX={output} ./zig-out/bin/zgroup group1 0.0.0.0:8080
Add a second node (different terminal):
$ ZGROUP_JOIN_PREFIX={output} ./zig-out/bin/zgroup group1 0.0.0.0:8081
Add a third node (different terminal):
$ ZGROUP_JOIN_PREFIX={output} ./zig-out/bin/zgroup group1 0.0.0.0:8082
Add a fourth node (different terminal):
$ ZGROUP_JOIN_PREFIX={output} ./zig-out/bin/zgroup group1 0.0.0.0:8083
and so on...
```
Kubernetes (Deployment)
A sample Kubernetes <a>deployment file</a> is provided to try zgroup on <a>Kubernetes Deployments</a>. Before deploying though, make sure to update the <code>ZGROUP_JOIN_PREFIX</code> environment variable, like so:
```sh
Generate UUID:
$ uuidgen
{output}
Update the 'value' part with your output.
...
- name: ZGROUP_JOIN_PREFIX
value: "{output}"
...
Deploy to Kubernetes:
$ kubectl create -f k8s.yaml
You will notice some initial errors in the logs.
Wait for a while before the K/V store is updated.
```
GCP Managed Instance Group (MIG)
A sample <a>startup script</a> is provided to try zgroup on a <a>GCP MIG</a>. Before deploying though, make sure to update the <code>ZGROUP_JOIN_PREFIX</code> value in the script, like so:
```sh
Generate UUID:
$ uuidgen
{output}
Update the 'value' part of ZGROUP_JOIN_PREFIX with your output.
...
ZGROUP_JOIN_PREFIX={output} ./zgroup group1 ...
Create an instance template:
$ gcloud compute instance-templates create zgroup-tmpl \
--machine-type e2-micro \
--metadata=startup-script=''"$(cat startup-gcp-mig.sh)"''
Create a regional MIG:
$ gcloud compute instance-groups managed create rmig \
--template zgroup-tmpl --size 3 --region {your-region}
You can view the logs through:
$ tail -f /var/log/messages
```
AWS Autoscaling Group
A sample <a>startup script</a> is provided to try zgroup on an <a>AWS ASG</a>. Before deploying though, make sure to update the <code>ZGROUP_JOIN_PREFIX</code> value in the script, like so:
```sh
Generate UUID:
$ uuidgen
{output}
Update the 'value' part of ZGROUP_JOIN_PREFIX with your output.
...
ZGROUP_JOIN_PREFIX={output} ./zgroup group1 ...
Create a launch template. ImageId here is Amazon Linux, default VPC.
(Added newlines for readability. Might not run when copied as is.)
$ aws ec2 create-launch-template \
--launch-template-name zgroup-lt \
--version-description version1 \
--launch-template-data '
{
"UserData":"'"$(cat startup-aws-asg.sh | base64 -w 0)"'",
"ImageId":"ami-0f75d1a8c9141bd00",
"InstanceType":"t2.micro"
}'
Create the ASG:
$ aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name zgroup-asg \
--launch-template LaunchTemplateName=zgroup-lt,Version='1' \
--min-size 3 \
--max-size 3 \
--availability-zones {target-zone}
You can view the logs through:
$ [sudo] journalctl -f
```
Getting the list of members
To get the current members of the group, you can try something like:
```zig
const members = try fleet.getMembers(gpa.allocator());
defer members.deinit();
for (members.items, 0..) |v, i| {
defer gpa.allocator().free(v);
log.info("member[{d}]: {s}", .{ i, v });
}
```
The tricky part of using zgroup is configuring the timeouts to optimize state dissemination and convergence. The current implementation was only tested within a local network.
TODOs
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> - Provide callbacks for membership changes
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> - Provide an API to get the current leader
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> - Provide an interface for other processes (non-Zig users)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> - Use multicast (if available) for the join address
PR's are welcome. | [] |
https://avatars.githubusercontent.com/u/9796623?v=4 | zui | thienpow/zui | 2024-11-24T07:18:50Z | fullstack mobile friendly web app built with jetzig framework -- ziglang | main | 0 | 14 | 1 | 14 | https://api.github.com/repos/thienpow/zui/tags | - | [
"boilerplate",
"fullstack",
"jetzig",
"uikit",
"zig"
] | 309 | false | 2025-05-02T04:25:13Z | true | true | 0.14.0-dev.3470+711b0fef5 | github | [
{
"commit": null,
"name": "jetzig",
"tar_url": null,
"type": "relative",
"url": "../jetzig-framework/jetzig/"
}
] | zUI - A UI Kit for JetZig Framework 🚀
zUI is a modern and lightweight UI kit designed for the <a>JetZig</a> framework, leveraging the power and simplicity of Zig. zUI provides a collection of reusable components, styles, and utilities to speed up your development process and deliver beautiful, consistent user interfaces.
Basic Features
<ul>
<li><strong>Super Lightweight:</strong> Minimal overhead for fast performance. Targeting less than 50kb load for whole page.</li>
<li><strong>Customizable:</strong> Easily adaptable to your design needs.</li>
<li><strong>Component-Based:</strong> Ready-to-use, pre-styled components, pages, partials, and icons.</li>
<li><strong>Seamless Integration:</strong> Built specifically for the JetZig framework.</li>
</ul>
Pro Features / Work in Progress ✨
<ul>
<li><strong>Database Integration:</strong> Support for PostgreSQL with ready-made CRUD operations, infinite scroll, pagination, and more.</li>
<li><strong>Themes:</strong> Multi-color options with dark/light mode support.</li>
<li><strong>Built-in Auth/Security:</strong> Features like JWT, session cookies, and role-based workflows.</li>
<li><strong>Premium Fully-Integrated Features:</strong> Components for blogs, product catalogs, premium dashboards with charts, and more.</li>
<li><strong>Docker Compose & Kubernetes Configurations:</strong> Comprehensive guides, bash scripts, and full-fledged Kubernetes setup.</li>
</ul>
Getting Started 🛠️
Follow these steps to set up zUI and integrate it into your JetZig project.
Prerequisites
<ul>
<li><strong>Zig Compiler</strong>: <a>Download Zig</a></li>
<li><strong>JetZig Framework</strong>: <a>JetZig Installation Guide</a></li>
</ul>
Installation
Clone the repository into your project:
<code>bash
git clone https://github.com/thienpow/zui.git
cd zui
nano build.zig.zon</code>
<ol>
<li>Ensure the JetZig framework path is correctly configured in the build.zig.zon file.</li>
<li>If the JetZig framework is not installed on your system, download the latest version from the JetZig source repository and update the path in the configuration file.</li>
<li>Save your changes and exit the editor.</li>
</ol>
Next, start the server with the following command:
<code>bash
jetzig server</code>
Contributing 🤝
We welcome contributions! Please follow the steps below:
<code>Fork the repository.
Create a new branch (git checkout -b feature-branch).
Commit your changes (git commit -m 'Add new feature').
Push the branch (git push origin feature-branch).
Open a Pull Request.
</code>
License 📄
zUI is open-sourced under the MIT License.
Feedback and Support 🙌
Have suggestions or need help? Feel free to open an issue or contact us at thienpow@gmail.com. | [] |
https://avatars.githubusercontent.com/u/206480?v=4 | otp.zig | karlseguin/otp.zig | 2024-11-08T01:47:11Z | An TOTP library for Zig | master | 0 | 14 | 0 | 14 | https://api.github.com/repos/karlseguin/otp.zig/tags | MIT | [
"zig",
"zig-library",
"zig-package"
] | 13 | false | 2025-04-25T12:13:53Z | true | false | unknown | github | [] | OTP for Zig
Currently only supports TOTP with SHA1 or SHA256.
```zig
const std = @import("std");
const otp = @import("otp");
pub fn main() !void {
// You would store secret in the DB with the user
var secret: [20]u8 = undefined;
otp.generateSecret(&secret);
<code>// base32 encode the secret
// (for a 20-byte secret, you need a 32 byte buffer)
var code_buf: [32]u8 = undefined;
std.debug.print("{s}\n", .{otp.bufEncodeSecret(&code_buf, &secret)});
// verify a user-supplied totp
const user_topt = "123456";
if (otp.totp.verify(user_topt, &secret, .{})) {
std.debug.print("GOOD!\n", .{});
}
</code>
}
```
Install
1) Add otp.zig as a dependency in your <code>build.zig.zon</code>:
<code>bash
zig fetch --save git+https://github.com/karlseguin/otp.zig#master</code>
2) In your <code>build.zig</code>, add the <code>otp</code> module as a dependency you your program:
```zig
const otp = b.dependency("otp", .{
.target = target,
.optimize = optimize,
});
// the executable from your call to b.addExecutable(...)
exe.root_module.addImport("otp", otp.module("otp"));
```
Secrets
The first thing to do is to generate a secret:
<code>zig
var secret: [20]u8 = undefined;
otp.generateSecret(&secret);</code>
You can pick any size, but 20 bytes, as above, is recommended. You should store the secret along with a user.
<code>generateSecret</code> fills the supplied slice with raw bytes. You can base32 encode the secret using:
```zig
// write the base32 encoded secret to the writer
try otp.encodeSecret(writer, secret);
// OR
// write the base32 encoded secret into "encoded_buf"
var encoded_buf: [32]u8 = undefined;
const encoded = otp.bufEncodeSecret(&encoded_buf, secret);
```
When using <code>bufEncodedSecret</code>, the supplied buffer <em>must</em> be large enough to hold the encoded value. You can use <code>const len = otp.encodeSecretLen(secret.len)</code> to get the required length.
TOTP
Config
Passed to various totp functions:
<ul>
<li><code>interval: u32</code> - How long a code should be valid for in seconds. Defaults to 30</li>
<li><code>digits: u8</code> - Number of digits. Defaults to 6.</li>
<li><code>algorithm: otp.totp.Algorithm</code> - The hash algorithm to use. Defaults to <code>.sha1</code> (other supported value is <code>.sha256</code>)</li>
</ul>
otp.totp.generate(buf: []u8, secret: []const u8, config: Config) []u8
Generate a new TOTP code for the current time. <code>buf</code> must be at least <code>config.digits</code>. A slice of <code>buf[0..config.digits]</code> is returned.
otp.totp.generateAt(buf: []u8, secret: []const u8, timestamp: i64, config: Config) []u8
Generate a new TOTP code for the specified time. <code>buf</code> must be at least <code>config.digits</code>. A slice of <code>buf[0..config.digits]</code> is returned.
otp.totp.verify(code: []const u8, secret: []const u8, config: Config) bool
Verifies that the given code is valid for the current time.
otp.totp.verifyAt(code: []const u8, secret: []const u8, timestamp: i64, config: Config) bool
Verifies that the given code is valid for the given time.
Example
<code>zig
var code_buf: [6]u8 = undefined;
const code = otp.totp.generate(&code, &secret, .{});
std.debug.assert(otp.totp.verify(code, &secret, .{}) == true);</code>
Which is a shorthand for:
<code>zig
var code_buf: [6]u8 = undefined;
const now = std.time.timestamp()
const config = otp.TOTP.Config{
.digits = 6,
.interval = 30,
.algorithm = .sha1,
};
const code = otp.totp.generateAt(&code, &secret, now, config);
std.debug.assert(otp.totp.verifyAt(code, &secret, now config) == true);</code>
When generating a code, the buffer, <code>code_buf</code> above, must be at least <code>config.digits</code> long.
URL
You can generate a URL (which is what would be put in a QR code) using either the <code>url</code> or <code>bufUrl</code> functions. These functions take their own type of config object:
<ul>
<li><code>account: []const u8</code> - The account name. Required</li>
<li><code>issuer: ?[]const u8</code> - Optional issuer name. Defaults to <code>null</code></li>
<li><code>config: Config</code> - The TOTP configuration. Default to <code>.{}</code></li>
</ul>
bufUrl(buf: []u8, secret: []const u8, uc: URLConfig) ![]u8
Writes the URL into <code>buf</code>. Returns an error if <code>buf</code> isn't large enough. Returns the URL on success.
url(writer: anytype, secret: []const u8, uc: URLConfig) !void
Writes the URL using the writer.
<code>zig
// min length of buf will largely depend on the account name, issuer name and length of secret.
var buf: [200]u8 = undefined;
const url = try bufUrl(&buf, secret, .{.account = "Leto", .issuer = "spice.gov", .config = .{.digits = 8} });</code> | [] |
https://avatars.githubusercontent.com/u/116976902?v=4 | zig-torch | kitajusSus/zig-torch | 2025-01-04T21:14:45Z | implementation of zig-BUILD lib to python to make working with matrices faster, for fun lets see what is going to happen | main | 0 | 14 | 0 | 14 | https://api.github.com/repos/kitajusSus/zig-torch/tags | BSD-3-Clause | [
"i",
"love",
"python",
"pytorch",
"pytorch-implementation",
"zig"
] | 28,516 | false | 2025-05-20T17:14:06Z | true | true | unknown | github | [
{
"commit": null,
"name": "zigtorch",
"tar_url": null,
"type": "relative",
"url": "zigtorch"
}
] | important 27.02.2025
Ive changed few things, now I preffere to do firstyly something in zig and later on I will look for options to make bindings to python.
mm.zig is main file with matrix multiplication function. the main problem is that i dont know how to build this, to make it work as a independent library in python, I lost an idea to make "faster pytorch", now im focused to something that can be used with or without pytorch.
zig-pytorch
As a man who is trying to understand zig and write usefull code in other language than python (or try to write something usefull), I get an idea of creating something what is using zig to optize pytorch, make is faster, more reliable. I don't know if it's going to work, but I need to do it my own as a motivation do study.
I've seen this in my dream
0. Basic know-how
PyTorch is written in C++ and gives API in this language, BUT ZIG GIVES US built in tools to compile code in C/C++. I can define functions from C++ in zig and use it in my code. <a>000_example.zig</a>. As you see, something works, and the plan is rewrite/build from scrach pytorch functions in zig and do something with it.
What do I need
<ul>
<li>Write pytorch functions in zig.</li>
<li>Check it everything work on python </li>
</ul>
1. Creating basic functions from pytorch
<code>torch.mm(input, mat2) -> Tensor</code>
This function takes two tensors 2d (matrix).
Development Workflow
<ol>
<li><strong>Plan</strong>: Define the functionality you want to implement</li>
<li><strong>Test-Driven Development</strong>: Write tests in Zig first</li>
<li><strong>Implement</strong>: Create the Zig implementation</li>
<li><strong>Benchmark</strong>: Compare performance with PyTorch</li>
<li><strong>C API</strong>: Expose functionality through C API</li>
<li><strong>Python Bindings</strong>: Create Python wrappers</li>
<li><strong>Document</strong>: Update documentation</li>
</ol>
Building the Project
Building the Zig Library
```bash
Build the Zig library
zig build
Run Zig tests
zig build test
Build in release mode for better performance
zig build -Drelease-fast
```
00. notes
<strong>zig build command</strong>
- <code>zig build-obj -OReleaseFast -fPIC mm.zig</code>
- <code>zig build-obj -fcompiler-rt mm.zig -fPIC -lpthread</code>
<strong>important to create module</strong>
- <code>pip install -e .</code> // <code>python setup.py install</code>
<strong>Building the Python Package</strong>
```bash
Install in development mode
pip install -e .
Build and install
python setup.py install
```
Adding New functions
ex: Creating a New Operation
<ul>
<li>create a new file in src/ (e.g., src/add.zig) <a>example add.zig</a></li>
<li>Implement your function</li>
<li>Create a test file in tests/ (e.g., tests/testadd.zig)</li>
<li>Update build.zig to include your new files</li>
<li>Expose through C API in src/native.zig</li>
</ul>
```bash
Basic build
zig build
Build with optimization for release
zig build -Drelease-fast
Run tests
zig build test
Clean build artifacts
rm -rf zig-out/
```
Testing 19.05.2025
ZIG 0.15.Development
```bash
Ładowanie biblioteki z: /home/kitajussus/github/zig-torch/src/libmm.so
Creating Matrix A (50x50) and B (50x50) type float32...
ZIG MULTIPLYING : !!!!!!!!!!!!!!!!!
Multiply with zig (50x50) x (50x50) took : 0.713 ms
Multiply with Numpy (for comparison):
Time for numpy: 2.430 ms
Checking...
ZIG IS NOT MULTYPLYING ONLY ZEROES!!!! IT IS WORKING
Zig matrix ( first 5x5 OR LESS):
[[13.51593 10.569702 13.364006 12.218889 9.840366 ]
[12.826249 9.629739 14.659329 10.829753 10.374571 ]
[13.49235 10.976502 14.516691 12.262626 11.237597 ]
[11.469961 9.874568 11.2643795 10.609412 10.377689 ]
[12.426827 10.05384 12.000959 11.205995 9.461213 ]]
Numpy Matrix ( first 5x5 OR LESS):
[[13.51593 10.569702 13.364005 12.218888 9.840365 ]
[12.826249 9.629739 14.659329 10.829753 10.374571 ]
[13.49235 10.976501 14.516692 12.262625 11.2375965]
[11.469961 9.874568 11.2643795 10.609412 10.377689 ]
[12.426826 10.053841 12.000959 11.205995 9.461213 ]]
Test FFI zakończony.
``` | [] |
https://avatars.githubusercontent.com/u/126450436?v=4 | Zeys | rullo24/Zeys | 2025-01-26T03:46:25Z | A Windows-ready, Zig keyboard library for seamlessly interacting with low-level keyboard functionality through higher-level Zig functions. | main | 0 | 14 | 0 | 14 | https://api.github.com/repos/rullo24/Zeys/tags | MIT | [
"hotkeys",
"input-injection",
"key-events",
"key-mapping",
"keyboard",
"keyboard-input",
"zig",
"zig-keyboard",
"ziglang"
] | 46 | false | 2025-02-09T15:04:40Z | true | true | unknown | github | [] | Zeys - A Zig Keyboard Module
Zeys provides a set of functions for simulating keyboard events, handling hotkeys, and interacting with the Windows API to manage keyboard inputs. It supports binding, unbinding, and triggering hotkeys, simulating key presses and releases, checking key states, and more. This module is intended for use in Windows-based applications.
Current Operating System Support
| Platform | Support |
|----------|---------|
| Windows | ✔ |
| Linux | ❌ |
| Mac | ❌ |
NOTE: Currently, the module only supports Windows. Linux support will be considered in future updates (if people would like this).
Features
<ul>
<li>Simulate Key Presses: Simulate pressing and releasing keys using the pressAndReleaseKey() function.</li>
<li>Hotkey Management: Bind and unbind hotkeys that trigger functions when pressed.</li>
<li>Blocking User Input: Block and unblock user input (keyboard and mouse) system-wide.</li>
<li>Key State Checking: Check whether a key is pressed or toggled (e.g., Caps Lock).</li>
<li>Locale Information: Retrieve the current keyboard locale and map it to a human-readable format.</li>
<li>Custom Callbacks: Set up custom functions that will be executed when specific keys or hotkeys are pressed.</li>
</ul>
Installation
NOTE: At the time of Zeys v1.1.0's release, this code works on Zig v0.13.0 (the latest release).
Thanks to SuSonicTH, I have had some help in updating this repo (v1.1.0) to allow for it to be downloaded via Zig's built-in package manager (zon).
To use Zeys in your project, simply follow the process below:
1. Fetch the Zeys repo from within one of the project's folders (must have a build.zig). This will automatically add the dependency to your project's build.zig.zon file (or create one if this currently does not exist).
- An example for importing Zeys v1.1.0 is shown below
<code>zig
zig fetch --save "https://github.com/rullo24/Zeys/archive/refs/tags/v1.1.0.tar.gz"</code>
2. Add the Zeys dependency to your build.zig file
- An example is shown below (build.zig)
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const optimise = b.standardOptimizeOption(.{});
const target = b.standardTargetOptions(.{});
<code>const zeys = b.dependency("Zeys", .{
.target = target,
.optimize = optimise,
});
const exe = b.addExecutable(.{
.name = "tester",
.root_source_file = b.path("test_zeys.zig"),
.optimize = optimise,
.target = target,
});
exe.root_module.addImport("zeys", zeys.module("zeys"));
b.installArtifact(exe);
</code>
}
<code>3. Import the Zeys module at the top of your code using the "@import" method
- An example is shown below (test_zeys.zig)</code>zig
const std = @import("std");
const zeys = @import("zeys");
pub fn main() void {
while (true) {
if (zeys.isPressed(zeys.VK.VK_A) == true) {
std.debug.print("ON\n", .{});
}
}
<code>return;
</code>
}
```
API
<code>``zig
/// Binds a hotkey to a Windows WM_HOTKEY message.
///
/// -</code>keys<code>: The virtual keys to bind.
/// -</code>p_func<code>: The callback function to invoke when the hotkey is triggered.
/// -</code>p_args_struct<code>: The arguments to pass to the callback.
/// -</code>repeat`: Whether the hotkey should repeat more than once when held down.
bindHotkey(keys: []const VK, p_func: <em>const fn (</em>anyopaque) void, p_args_struct: *?anyopaque, repeat: bool) !void
/// Unbinds a hotkey, preventing the associated WM_HOTKEY messages from being sent.
///
/// - <code>keys</code>: The virtual keys of the hotkey to unbind.
unbindHotkey(keys: []const VK) !void
/// Simulates an infinite wait loop while calling callback functions when hotkeys are triggered.
zeysInfWait() void
/// Waits for the specified keys to be pressed (simulates a while (not_pressed)) and triggers the corresponding hotkey callback functions.
///
/// - <code>virt_keys</code>: The virtual keys to wait for before passing over this function
waitUntilKeysPressed(virt_keys: []const VK) !void
/// Checks if the specified key is currently pressed.
///
/// - <code>virt_key</code>: The virtual key to check.
///
/// Returns true if the key is pressed, false otherwise.
isPressed(virt_key: VK) bool
/// Checks if the specified toggle key is active (e.g., Caps Lock, Num Lock).
///
/// - <code>virt_key</code>: The toggle key to check.
///
/// Returns true if the toggle key is active, false otherwise.
isToggled(virt_key: VK) !bool
/// Simulates pressing and releasing a key once, with a 1ms delay to avoid undefined behavior.
///
/// - <code>virt_key</code>: The virtual key to press and release.
pressAndReleaseKey(virt_key: VK) !void
/// Simulates pressing a sequence of keys corresponding to the characters in the provided string.
///
/// - <code>str</code>: The string of characters to simulate as key presses.
pressKeyString(str: []const u8) !void
/// Checks if the specified key is a modifier key (e.g., Ctrl, Shift, Alt).
///
/// - <code>virt_key</code>: The key to check.
///
/// Returns true if the key is a modifier, false otherwise.
keyIsModifier(virt_key: VK) bool
/// Retrieves the current keyboard's locale ID (hexadecimal string).
///
/// - <code>alloc</code>: The memory allocator to use for the locale ID string.
///
/// Returns the keyboard locale ID.
getKeyboardLocaleIdAlloc(alloc: std.mem.Allocator) ![]u8
/// Converts a Windows locale ID (hex string) to a human-readable string.
///
/// - <code>u8_id</code>: The locale ID in hexadecimal string format.
///
/// Returns the keyboard layout string corresponding to the locale ID.
getKeyboardLocaleStringFromWinLocale(u8_id: []const u8) ![]const u8
/// Blocks all user input (keyboard and mouse) system-wide. Requires admin privileges.
blockAllUserInput() !void
/// Unblocks all user input (keyboard and mouse) system-wide. Requires admin privileges.
unblockAllUserInput() !void
```
Important Background Information - Virtual Keys (VK)
Virtual keys are constants used by the Windows API to represent keyboard keys. These constants are part of the enum(c_short) declaration in Zeys and correspond to both standard and special keys i.e. function keys (F1-F12), numeric keypad keys, and modifier keys (e.g., Shift, Ctrl, Alt).
This enum allows for more manageable code when working with keyboard inputs, as you can use meaningful names like VK_A, VK_RETURN (enter), and VK_SHIFT instead of raw numeric values. Virtual keys are essential for simulating key presses and managing hotkeys in the Zeys module.
List of Common Virtual Keys
- Standard Keys: VK_A, VK_B, VK_C, ..., VK_Z
- Numeric Keys: VK_0, VK_1, VK_2, ..., VK_9
- Function Keys: VK_F1, VK_F2, VK_F3, ..., VK_F24
- Modifiers: VK_SHIFT, VK_CONTROL, VK_MENU, VK_LSHIFT, VK_RSHIFT
- Navigation Keys: VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT
- Toggle Keys: VK_CAPITAL (Caps Lock), VK_NUMLOCK, VK_SCROLL
- More VKs (view zeys.zig)
Virtual Keys - Example Usage
Here’s how you can use the virtual keys in Zeys to simulate key presses or bind hotkeys:
```zig
// Simulating a key press of the "A" key
pressAndReleaseKey(zeys.VK.VK_A); // Simulates pressing and releasing the 'A' key
// Binding a hotkey to Ctrl+Shift+Z
try zeys.bindHotkey( &[_]zeys.VK{ zeys.VK.VK_Z, zeys.VK.VK_CONTROL, zeys.VK.VK_SHIFT, }, &tester_func_1, @constCast(&.{}), false);
```
These virtual keys are used throughout the Zeys module for functions like bindHotkey(), pressAndReleaseKey(), isPressed(), and more. They help to ensure that the module can interact with the system in a way that aligns with Windows' key-coding conventions.
Usage
Binding a Hotkey
To bind a hotkey, use the bindHotkey() function. This will associate a specific combination of keys with a function to be called when the hotkey is pressed.
Binding a Hotkey - Example
```zig
fn tester_func_1(args: *anyopaque) void {
_ = args;
std.debug.print("You're working in tester_func_1() :)\n", .{});
}
pub fn main() {
std.debug.print("Press Z + CTRL + SHIFT to run tester_func_1\n", .{});
std.debug.print("Press 0 to move to the next example\n", .{});
// var tester_1: test_struct_1 = .{};
try zeys.bindHotkey( &[<em>]zeys.VK{ zeys.VK.VK_Z, zeys.VK.VK_CONTROL, zeys.VK.VK_SHIFT, },
&tester_func_1,
@constCast(&.{}), // need to parse an empty struct for no arguments --> casting struct to pointer
false);
try zeys.waitUntilKeysPressed( &[</em>]zeys.VK{ zeys.VK.VK_0, });
try zeys.unbindHotkey( &[_]zeys.VK{ zeys.VK.VK_Z, zeys.VK.VK_CONTROL, zeys.VK.VK_SHIFT, });
}
```
Unbinding a Hotkey
To unbind a hotkey, use the unbindHotkey() function and provide the same key combination used during binding.
Unbinding a Hotkey - Example
<code>zig
unbindHotkey( &[_]zeys.VK{ zeys.VK.VK_B, } );</code>
Simulating a Key Press
To simulate a key press, you can use the pressAndReleaseKey() function.
Simulating a Key Press - Example
<code>zig
pressAndReleaseKey(zeys.VK.VK_A); // Simulate pressing and releasing the 'A' key</code>
Blocking User Input
To block all user input (keyboard and mouse), use the blockAllUserInput() function.
Blocking User Input - Example
<code>zig
blockAllUserInput();</code>
More Examples
For more example usage of the library, please check the <em>./example</em> directory included in this repo. This folder explains in higher detail the intricacies of the project.
Windows API Functions Used
This module relies on several Windows API functions to interact with the system's keyboard and input functionality. Some of the key functions used include:
- RegisterHotKey
- SendInput
- GetAsyncKeyState
- BlockInput
For more information about these functions, refer to the Windows API documentation.
Error Handling
Zeys uses Zig's built-in error handling for common failure scenarios, such as:
- Too many keys provided for a hotkey binding.
- Failed to register or unregister a hotkey.
- Issues with sending key inputs or blocking/unblocking input.
- And more
License
This module is provided as-is. I am not responsible for any misuse or unintended consequences that may result from using this module. Please use it responsibly and ensure you have proper safeguards in place before using any functions that block input or simulate key presses.
This project is licensed under the MIT License - see the LICENSE file for details. | [] |
https://avatars.githubusercontent.com/u/20110944?v=4 | zeptolibc | ringtailsoftware/zeptolibc | 2024-12-05T11:55:40Z | Some basic libc functions for working with C code in Zig | main | 0 | 13 | 0 | 13 | https://api.github.com/repos/ringtailsoftware/zeptolibc/tags | - | [
"libc",
"zig",
"zig-package"
] | 54 | false | 2025-05-20T14:16:32Z | true | true | unknown | github | [] | ZeptoLibC
A few of the most essential libc functions needed when working with C code in Zig.
Much of the code is taken from <a>ziglibc</a>.
ZeptoLibC provides, among others:
<ul>
<li><code>malloc()</code>, <code>calloc()</code>, <code>realloc()</code>, <code>free()</code></li>
<li><code>printf()</code>, <code>fprintf()</code>, <code>snprintf()</code></li>
<li><code>strncmp()</code>, <code>strchr()</code>, <code>strncpy()</code></li>
<li><code>abs()</code>, <code>fabs()</code>, <code>sin()</code>, <code>cos()</code>, <code>sqrt()</code>, <code>pow()</code>, <code>floor()</code>, <code>ceil()</code></li>
<li><code>memset()</code>, <code>memmove()</code></li>
</ul>
ZeptoLibC is not intended to implement the full C library and does the bare minimum to support I/O operations (just <code>printf()</code>). The aim is to allow simple porting of existing C code to freestanding/baremetal environments such as WASM and embedded systems.
All ZeptoLibC functions start with the prefix <code>zepto_</code>, eg. <code>zepto_malloc()</code> so as to not clash with any existing C functions. The file <code>zeptolibc.h</code> provides <code>#define</code>s for mapping <code>malloc()</code> -> <code>zepto_malloc()</code>.
How to use
For a complete example, see https://github.com/ringtailsoftware/zeptolibc-example
First we add the library as a dependency in our <code>build.zig.zon</code> file.
<code>zig fetch --save git+https://github.com/ringtailsoftware/zeptolibc.git</code>
And we add it to <code>build.zig</code> file.
```zig
const zeptolibc_dep = b.dependency("zeptolibc", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zeptolibc", zeptolibc_dep.module("zeptolibc"));
exe.addIncludePath(zeptolibc_dep.path("src/"));
```
Usage:
Add <code>#include "zeptolibc.h"</code> to your C code.
```c
#include "zeptolibc.h"
<code>void my_greeting(void) {
printf("Hello world\n");
}
</code>
```
Setup ZeptoLibC from Zig and call the C code.
<code>zeptolibc.init()</code> may be passed <code>null</code> for both write function and allocator. A <code>null</code> allocator will cause <code>malloc()</code> to always return <code>NULL</code>. A <code>null</code> write function will silently drop written data.
```zig
const std = @import("std");
const zeptolibc = @import("zeptolibc");
<code>const c = @cImport({
@cInclude("greeting.c");
});
fn writeFn(data:[]const u8) void {
_ = std.io.getStdOut().writer().write(data) catch 0;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
// init zepto with a memory allocator and a write function (used for stdout and stderr)
zeptolibc.init(allocator, writeFn);
c.my_greeting();
}
</code>
``` | [
"https://github.com/ringtailsoftware/zig-wasm-audio-framebuffer"
] |
https://avatars.githubusercontent.com/u/94393292?v=4 | zigCraft | SnoopyPlayz/zigCraft | 2025-01-07T09:08:51Z | minecraft made in zig with raylib | main | 0 | 13 | 2 | 13 | https://api.github.com/repos/SnoopyPlayz/zigCraft/tags | MIT | [
"raylib",
"zig"
] | 475 | false | 2025-04-02T00:58:09Z | true | true | 0.14.0 | github | [
{
"commit": "b684c3c46c2c3e7e1ba69c068bdc34e873b3e7bc",
"name": "raylib_zig",
"tar_url": "https://github.com/SnoopyPlayz/raylib-zig-fork/archive/b684c3c46c2c3e7e1ba69c068bdc34e873b3e7bc.tar.gz",
"type": "remote",
"url": "https://github.com/SnoopyPlayz/raylib-zig-fork"
}
] | zigCraft
minecraft made in zig with <a>raylib</a>.
zig version: <code>1.14.0</code>
example Image:
building
install zig version <code>1.14.0</code>
<code>git clone https://github.com/SnoopyPlayz/zigCraft.git
cd zigCraft
zig build run -Doptimize=ReleaseFast --release=fast</code>
controls
0 - 9 - select block
right click - place block
left clock - remove block
wasd - move | [] |
https://avatars.githubusercontent.com/u/46653655?v=4 | zinger | BitlyTwiser/zinger | 2024-12-01T01:18:42Z | Simple HTTP request library for Zig applications | main | 0 | 13 | 1 | 13 | https://api.github.com/repos/BitlyTwiser/zinger/tags | Apache-2.0 | [
"http",
"http-requests",
"zig",
"zig-package",
"ziglang"
] | 231 | false | 2025-04-17T10:53:37Z | true | true | unknown | github | [] |
# Zinger
A Simple HTTP request library
# Contents
[Usage](#usage) |
[Make Requests](#make-requests) |
[GET](#get) |
[POST](#post) |
[PUT and DELETE](#put-and-delete) |
[Supported Requests](#supports) |
Usage
Add Zinger to your Zig project with Zon:
<code>sh
zig fetch --save https://github.com/BitlyTwiser/zinger/archive/refs/tags/v0.1.1.tar.gz</code>
Add the following to build.zig file:
<code>zig
const zinger = b.dependency("zinger", .{});
exe.root_module.addImport("zinger", zinger.module("zinger"));</code>
Import Zinger and you should be set!
<code>zig
const zinger = @import("zinger").Zinger;</code>
Please see the examples in the main.zig file or below to view using the package
Make requests
Any of the requsts can be made with a body utilizing the optional values. Additionally, any body can be converted to JSON by utilizing the anytype passed into the <code>json</code> function call.
The example in main shows how to make a request and check for errors in the query
max_append_size
Note: The std.http.Client.FetchOptions, by default, sets a max body size (if not defined) to: <code>2 * 1024 * 1024</code>.
If this is enough for your use cases (most general HTTP requests with a smaller JSON body would fit within this allotment), then everything is fine. Overwise, you will need to pass in the alloted/desired amount into Zinger init.
Example:
```zig
var z = zinger.Zinger.init(allocator, null);
// OR
// The numerical value here should be carefully considered to avoid over allocation.
var z = zinger.Zinger.init(allocator, 1024 * 10);
```
```zig
const allocator = std.heap.page_allocator;
var z = zinger.Zinger.init(allocator, null);
<code>defer z.deinit();
var headers = [_]std.http.Header{};
const resp = try z.get("<some api>", null, &headers);
if (resp.err()) |err_data| {
std.debug.print("{s}", .{err_data.phrase});
}
if (resp.err() != null) {
try resp.printErr();
}
</code>
```
This is the most <em>basic</em> example there is for curating requests. A simple get request, but otherwiese does not display anything as we pass in a null body. (Perhaps useful if all you want to check is the status of the response which is done in the resp.err() check)
GET
```zig
const allocator = std.heap.page_allocator;
var z = zinger.Zinger.init(allocator, 1024 * 2 * 2);
<code>defer z.deinit();
var headers = [_]std.http.Header{};
const resp = try z.get("<some api>", null, &headers);
if (resp.err()) |err_data| {
std.debug.print("{s}", .{err_data.phrase});
}
if (resp.err() != null) {
try resp.printErr();
}
// Serialize the JSON data from the body using the json(anytype) method.
// Pass any struct type here to marshal the body into the struct.
// Obviously, ensure that the struct attributes match the returned JSON data from the endpoint
const json_resp = try resp.json(test_resp_type);
std.debug.print("{any}", .{json_resp});
</code>
```
POST
You can denote whatever type you want for the JSON data in a custom struct
<code>zig
const test_resp_type = struct {
test_data: []const u8,
};</code>
```zig
fn post(allocator: std.mem.Allocator) !void {
// Create Zinger instance for POST
var z = zinger.Zinger.init(allocator, null);
<code>const test_data = struct {
example_string: []const u8,
}{
.example_string = "testing",
};
const json_body = std.json.stringifyAlloc(allocator, test_data, .{});
defer allocator.free(json_body);
var headers = [_]std.http.Header{.{ .name = "content-type", .value = "application/json" }};
const resp = try z.get("<api endpoint>", test_data, &headers);
if (resp.err()) |err_data| {
std.debug.print("{s}", .{err_data.phrase});
}
if (resp.err() != null) {
try resp.printErr();
}
// Serialize the JSON data from the body using the json(anytype) method using the custom struct above
const resp_data = struct {
example_string: []const u8,
}{};
const json_resp = try resp.json(resp_data);
std.debug.print("{any}", .{json_resp});
</code>
}
```
PUT and DELETE
Following the same pattern above, you <em>can</em> unclude a body as part of the DELETE/PUT requests. The library is really designed around however the user wants to present the data, attempting to make it as simple as possible to make all the general requests you need.
For PUT/DELETE, simply change the HTTP verb in the above examples and you are set!
PUT/DELETE:
```zig
fn delete(allocator: std.mem.Allocator) !void {
// Create Zinger instance for POST
// The value for the max_override here is just symbolic for reference,
// this would generally be null unless you <em>need</em> to override this value
var z = zinger.Zinger.init(allocator, 2048 * 10);
<code>const test_data = struct {
example_string: []const u8,
}{
.example_string = "testing",
};
const json_body = try std.json.stringifyAlloc(allocator, test_data, .{});
defer allocator.free(json_body);
var headers = [_]std.http.Header{.{ .name = "content-type", .value = "application/json" }};
var resp = try z.delete("<api endpoint>", json_body, &headers);
if (resp.err() != null) {
try resp.printErr();
return;
}
// Serialize the JSON data from the body using the json(anytype) method.
const json_resp = try resp.json(test_resp_type);
std.debug.print("{any}", .{json_resp});
</code>
}
fn put(allocator: std.mem.Allocator) !void {
// Create Zinger instance for POST
var z = zinger.Zinger.init(allocator, null);
<code>const test_data = struct {
example_string: []const u8,
}{
.example_string = "testing",
};
const json_body = try std.json.stringifyAlloc(allocator, test_data, .{});
defer allocator.free(json_body);
var headers = [_]std.http.Header{.{ .name = "content-type", .value = "application/json" }};
var resp = try z.put("<api endpoint>", json_body, &headers);
if (resp.err()) |err_data| {
std.debug.print("{s}", .{err_data.phrase});
return;
}
// Serialize the JSON data from the body using the json(anytype) method.
const json_resp = try resp.json(test_resp_type);
std.debug.print("{any}", .{json_resp});
</code>
}
```
Supports
GET, POST, PUT, and DELETE requests | [] |
https://avatars.githubusercontent.com/u/16590917?v=4 | zigscient-next | llogick/zigscient-next | 2025-01-26T06:32:30Z | Using the Zig Compiler's Incremental Semantic Analysis as a Foundation for Near-instant Code Feedback via LSP | dev | 3 | 13 | 0 | 13 | https://api.github.com/repos/llogick/zigscient-next/tags | NOASSERTION | [
"language-server",
"language-server-protocol",
"zig",
"zig-auto-complete",
"zig-language",
"zig-language-server"
] | 297,272 | false | 2025-04-04T22:34:19Z | true | true | 0.14.0 | github | [
{
"commit": null,
"name": "standalone_test_cases",
"tar_url": null,
"type": "relative",
"url": "test/standalone"
},
{
"commit": null,
"name": "link_test_cases",
"tar_url": null,
"type": "relative",
"url": "test/link"
},
{
"commit": "aa24df42183ad415d10bc0a33e6238c... | Using the Zig Compiler's Incremental Semantic Analysis as a Foundation for Near-instant Code Feedback via LSP
<strong>Status</strong>
This project is a proof-of-concept/viability effort. The intention is to demonstrate the potential of using Zig's incremental semantic analysis for near-instant code feedback via LSP, and as a potential bridge between today and when the Zig Compile Server emerges.
<strong>Important Notes</strong>
Server Requirements
The server requires a valid workspace folder path to be passed in the <code>initialize</code> request by the editor. If an editor does not provide this information, the server will fall back to basic functionality.
Correct Modules Lookup
To ensure correct modules lookup, please refer to the <a>wiki page</a>.
Keep In Mind
Conditionals like <code>if</code> and <code>else</code> can influence what is analyzed. Make sure you're aware of the implications when editing code within these blocks.
https://github.com/user-attachments/assets/9e47daca-1d6d-492e-b840-85fbfb83e4c8
Building
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
This is a resource-intensive piece of software, so a capable CPU with good single-thread performance is recommended.
</blockquote>
<code>bash
zig build -Doptimize=ReleaseFast --zig-lib-dir ./lib/</code> | [] |
https://avatars.githubusercontent.com/u/23142073?v=4 | zsynth | jrachele/zsynth | 2024-12-07T00:09:20Z | Synthesizer plugin written in Zig | main | 0 | 12 | 0 | 12 | https://api.github.com/repos/jrachele/zsynth/tags | MIT | [
"audio",
"bitwig",
"clap",
"dsp",
"plugin",
"synthesizer",
"vst",
"zig"
] | 727 | false | 2025-04-05T11:09:41Z | true | true | unknown | github | [
{
"commit": "7bc0fd7.tar.gz",
"name": "regex",
"tar_url": "https://github.com/tiehuis/zig-regex/archive/7bc0fd7.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/tiehuis/zig-regex"
},
{
"commit": null,
"name": "clap-bindings",
"tar_url": null,
"type": "remote",
... |
ZSynth is a light-weight digital synthesizer audio plugin written in <a>Zig</a>.
It uses
Zig-friendly <a>CLAP</a> <a>bindings</a>, and
leverages ImGui to render the plugin GUI.
Features
<ul>
<li>Very lightweight CPU load</li>
<li>2 oscillators powered by anti-aliased wave tables: Sine, Saw, Triangle, Square</li>
<li>Intuitive GUI with accurate visual of waveform</li>
<li>Biquad filter with low pass, high pass, and band pass</li>
<li>ADSR with flexibility within a time domain of 0ms to 20s</li>
<li>Optional compile-time embedding of wave tables with <code>-Dgenerate_wavetables_comptime</code></li>
<li>No oversampling.</li>
</ul>
Planned Work
This is just a hobby project / proof of concept for now, but I have some grand designs regardless:
<ul>
<li>Custom wave table integration</li>
<li>On-board delay and reverb</li>
</ul>
Installation
Prerequisites
<ul>
<li>ZSynth requires Zig nightly. It was last tested with version <code>0.14.0-dev.2546+0ff0bdb4a</code></li>
<li>Git</li>
</ul>
Steps
<ol>
<li>Clone the repository with <code>git clone https://github.com/jrachele/zsynth.git</code></li>
<li>Run <code>zig build -Doptimize=ReleaseFast</code> to generate the CLAP plugin. It will be in the <code>zig-out/lib</code> folder.<ul>
<li>Optionally, if you want to embed the wave tables into the binary directly at compile time, run
<code>zig build -Doptimize=ReleaseFast -Dgenerate_wavetables_comptime=true</code> instead.</li>
</ul>
</li>
<li>The build process should move the resulting <code>ZSynth.clap</code> plugin to your DAW's CLAP plugin folder. </li>
</ol> | [] |
https://avatars.githubusercontent.com/u/192897928?v=4 | zig-luajit-build | sackosoft/zig-luajit-build | 2025-01-12T21:13:06Z | A package to compile LuaJIT using the Zig toolchain. Install to access the LuaJIT C API. For Zig API see https://github.com/sackosoft/zig-luajit | main | 1 | 12 | 4 | 12 | https://api.github.com/repos/sackosoft/zig-luajit-build/tags | MIT | [
"luajit",
"zig",
"zig-package"
] | 59 | false | 2025-05-18T02:02:20Z | true | true | unknown | github | [
{
"commit": "538a82133ad6fddfd0ca64de167c4aca3bc1a2da",
"name": "upstream",
"tar_url": "https://github.com/LuaJIT/LuaJIT/archive/538a82133ad6fddfd0ca64de167c4aca3bc1a2da.tar.gz",
"type": "remote",
"url": "https://github.com/LuaJIT/LuaJIT"
}
] |
# zig-luajit-build
Used to compile and link the native [LuaJIT][LUAJIT] C API into Zig ⚡ applications.



LuaJIT is a fork from the <a>Lua</a> project -- "Lua is a powerful, efficient, lightweight, embeddable scripting language."
Are you looking for a Zig interface to the LuaJIT C API?
This package does not contain Zig language bindings to the C API. This package only handles building and linking the
LuaJIT library into a Zig application.
If you're looking to run Lua on LuaJIT in your Zig application, you're probably looking for one of these projects:
<ol>
<li><a>sackosoft/zig-luajit</a> <strong>- Zig language bindings LuaJIT.</strong><ul>
<li>Preferred solution when only one Lua runtime (LuaJIT) is required; built on top of <code>zig-luajit-build</code>.</li>
</ul>
</li>
<li><a>natecraddock/ziglua</a> - Zig language bindings for Lua 5.x and Luau and LuaJIT.<ul>
<li>More mature project, maintained by Nathan Craddock. Has some quirks as a result of supporting all Lua runtimes
with the same Zig API.</li>
</ul>
</li>
</ol>
Zig Version
The <code>main</code> branch targets Zig's <code>master</code> (nightly) deployment (last tested with <code>0.15.0-dev.565+8e72a2528</code>).
Installation & Usage
Install using <code>zig fetch</code>. This will add a <code>luajit_build</code> dependency to your <code>build.zig.zon</code> file.
<code>bash
zig fetch --save=luajit_build git+https://github.com/sackosoft/zig-luajit-build</code>
Next, in order for your code to import the LuaJIT C API, you'll need to update your <code>build.zig</code> to:
<ol>
<li>get a reference to the <code>luajit-build</code> dependency which was added by zig fetch.</li>
<li>get a reference to the <code>luajit-build</code> module, containing the native LuaJIT C API.</li>
<li>attach that module as an import to your library or executable, so that your code can reference the C API.</li>
</ol>
```zig
// (1) Reference the dependency
const luajit_build_dep = b.dependency("luajit_build", .{
.target = target,
.optimize = optimize,
.link_as = .static // Or .dynamic to link as a shared library
});
// (2) Reference the module containing the LuaJIT C API.
const luajit_build = luajit_build_dep.module("luajit-build");
// Set up your library or executable
const lib = // ...
const exe = // ...
// (3) Add the module as an import, available via <code>@import("c")</code>, or any other name you choose here.
lib.root_module.addImport("c", luajit_build);
// Or
exe.root_module.addImport("c", luajit_build);
```
Now the code in your library or executable can import and access the LuaJIT C API!
```zig
const c = @import("c"); // Access LuaJIT functions via 'c'
pub fn main() !void {
const state: ?*c.lua_State = c.luaL_newstate();
if (state) |L| {
c.luaL_openlibs(L);
c.luaL_dostring(
L,
\ print("Hello, world!")
);
}
}
```
Configuration
This package supports one configuration option, shown in the example above.
<ul>
<li><code>link_as</code>: Controls how LuaJIT is linked</li>
<li><code>.static</code>: Build and link LuaJIT as a static library (default).</li>
<li><code>.dynamic</code>: Build and link LuaJIT as a shared library.</li>
</ul>
License
Some files in this repository were copied or adapted from the <a>natecraddock/ziglua</a> project.
Any files copied or adapted from that project have a comment describing the attribution at the top. Such files are shared by Nathan
Craddock under the MIT License in <a>ziglua/license</a>.
All other files are released under the MIT License in <a>zig-luajit-build/LICENSE</a>. | [] |
https://avatars.githubusercontent.com/u/30970706?v=4 | mpack-zig | theseyan/mpack-zig | 2024-12-07T06:34:07Z | MessagePack bindings for Zig / msgpack.org[Zig] | main | 0 | 12 | 0 | 12 | https://api.github.com/repos/theseyan/mpack-zig/tags | MIT | [
"messagepack",
"mpack",
"zig",
"zig-package"
] | 132 | false | 2025-02-15T12:00:00Z | true | true | 0.13.0 | github | [
{
"commit": "master",
"name": "mpack",
"tar_url": "https://github.com/ludocode/mpack/releases/download/v1.1.1/mpack-amalgamation-1.1.1.tar.gz/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/ludocode/mpack/releases/download/v1.1.1/mpack-amalgamation-1.1.1.tar.gz"
},
{
... | MessagePack for Zig
High-level APIs for <a>MPack</a>, a fast compliant encoder/decoder for the <a>MessagePack</a> binary format.
Built and tested with Zig version <code>0.13.0</code>.
<blockquote>
<ul>
<li>Simple and easy to use</li>
<li>Secure against untrusted data</li>
<li>Lightweight, suitable for embedded</li>
<li><a>Extremely fast</a></li>
</ul>
</blockquote>
Table of Contents
<ul>
<li><a>Installation</a></li>
<li><a>Usage</a></li>
<li><a>API</a></li>
<li><a><code>Writer</code></a></li>
<li><a><code>Tree</code></a></li>
<li><a><code>TreeCursor</code></a></li>
<li><a><code>Reader</code></a></li>
<li><a><code>Cursor</code></a></li>
<li><a>Testing</a></li>
<li><a>Benchmarks</a></li>
</ul>
Installation
```bash
replace {VERSION} with the latest release eg: v0.1.0
zig fetch https://github.com/theseyan/mpack-zig/archive/refs/tags/{VERSION}.tar.gz
```
Copy the hash generated and add mpack-zig to <code>build.zig.zon</code>:
<code>zig
.{
.dependencies = .{
.mpack = .{
.url = "https://github.com/theseyan/mpack-zig/archive/refs/tags/{VERSION}.tar.gz",
.hash = "{HASH}",
},
},
}</code>
API
As there is currently no proper documentation, I recommend checking out the <a>tests</a> to refer for examples. The source code is also well-commented.
<code>Writer</code>
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
Zero-allocating API, all writes are flushed to user-provided buffer.
</blockquote>
The simplest way to incrementally write a MessagePack encoded message to a buffer. Writing should always start with <code>startMap</code> and end with <code>finishMap</code>. Values should always be written immediately after respective keys.
After writing is done, call <code>deinit</code> to flush the written bytes to the underlying buffer.
For pure-Zig code, it can be useful to directly encode a struct (or any supported type) using the <code>writeAny</code>/<code>writeAnyExplicit</code> methods.
If you already have a parsed tree of nodes (using <code>Tree</code> API), and need to serialize a nested child <code>Map</code> node to it's own MessagePack buffer, use the <code>writeMapNode</code> method which accepts a <code>Tree.Node</code> (internally, it uses the <code>Writer</code> and <code>TreeCursor</code> APIs).
It is also possible to write pre-encoded MessagePack object bytes as value to a larger object via <code>writeEncodedObject</code>. This is particularly useful when creating a larger structure that embeds smaller encoded structures, wihout having to decode and re-encode everything.
```zig
const Writer = mpack.Writer;
var buffer: [1024]u8 = undefined;
var writer = Writer.init(&buffer);
try writer.startMap(3);
try writer.writeString("name"); // Key
try writer.writeString("Sayan"); // Value
try writer.writeString("age"); // Key
try writer.writeUint32(100); // Value
try writer.writeString("location"); // and so on...
try writer.startMap(2);
try writer.writeString("x");
try writer.writeDouble(123.535);
try writer.writeString("y");
try writer.writeDouble(1234.1234);
try writer.finishMap();
try writer.finishMap();
// Flush buffered writes to stream
try writer.deinit();
<code>Results in an encoded message equivalent to the following JSON:</code>json
{
"name": "Sayan",
"age": 100,
"location": {
"x": 123.535,
"y": 1234.1234
}
}
```
The following <code>Writer</code> methods are available:
- <code>writeAny</code> - Serialize any supported data type, including structs, value must be known at comptime.
- <code>writeHashMap</code> - Write a <code>StringArrayHashMap</code> as a <code>Map</code> value.
- <code>writeNumber</code> - Infer the type of number at comptime.
- <code>writeNull</code>
- <code>writeBool</code>
- <code>writeInt8</code>, <code>writeInt16</code>, <code>writeInt32</code>, <code>writeInt64</code>
- <code>writeUint8</code>, <code>writeUint16</code>, <code>writeUint32</code>, <code>writeUint64</code>
- <code>writeFloat</code>, <code>writeDouble</code>
- <code>writeNumberExplicit</code> - Infer the type of number at comptime, but value is runtime-known.
- <code>writeString</code>
- <code>writeBytes</code>
- <code>writeExtension</code> - Read more on <a>MessagePack Extensions</a>.
- <code>startArray</code> - Start writing an array. <code>count</code> must be known upfront.
- <code>startMap</code> - Start writing a map. <code>length</code> must be known upfront.
- <code>finishArray</code>, <code>finishMap</code> - Close the last opened array/map.
- <code>writeAnyExplicit</code> - When value is unknown at comptime, but type is known.
- <code>writeMapNode</code> - Encode a parsed <code>NodeType.Map</code> node back to binary.
- <code>writeEncodedObject</code> - Write a pre-encoded MessagePack object as value.
- <code>stat</code> - Returns information about underlying buffer.
<code>Tree</code>
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
By default, nodes of the parsed tree are allocated on the heap as required automatically.
To avoid dynamic allocations, you can create a re-useable <code>Pool</code> with pre-allocated nodes.
Strings/Binary/Extension values are zero-copy and point to the original buffer, hence are only valid as long as the buffer lives.
</blockquote>
Tree-based reader, can be used to read data explicitly and with random access, get a item by path (eg. <code>parents.mother.children[0].name</code>), de-serialize a message to a Zig struct, or traverse the tree using <code>TreeCursor</code>.
```zig
pub const Tree = struct {
pub fn init(allocator: std.mem.Allocator, data: []const u8, pool: ?Pool) !Tree
pub fn deinit(self: *Tree) !void
pub fn getByPath(self: <em>Tree, path: []const u8) !Node
pub fn readAny(self: </em>Tree, comptime T: type) !struct { value: T, arena: std.heap.ArenaAllocator }
pub fn cursor(self: *Tree) !Cursor
/// A pre-allocated pool of nodes to avoid dynamic allocations in hot paths.
pub const Pool = struct {
/// Creates a pool of pre-allocated nodes for use with <code>init</code>.
/// This helps avoid slow dynamic allocations in hot paths.
pub fn init(allocator: std.mem.Allocator, size: usize) !Pool
<code>/// Destroys the pool and frees the underlying memory.
pub fn deinit(self: *Pool) void
</code>
};
};
pub const Node = {
pub const NodeType = enum {
Null,
Bool,
Int,
Uint,
Float,
Double,
String,
Bytes,
Array,
Map,
Extension,
Missing
};
pub fn getType(self: Node) NodeType
pub fn isValid(self: Node) bool
pub fn isNull(self: Node) bool
pub fn getBool(self: Node) !bool
pub fn getInt(self: Node) !i64
pub fn getUint(self: Node) !u64
pub fn getFloat(self: Node) !f32
pub fn getDouble(self: Node) !f64
pub fn getString(self: Node) ![]const u8
pub fn getBytes(self: Node) ![]const u8
pub fn getExtensionType(self: Node) !i8
pub fn getExtensionBytes(self: Node) ![]const u8
pub fn getArrayLength(self: Node) !u32
pub fn getArrayItem(self: Node, index: u32) !Node
pub fn getMapLength(self: Node) !u32
pub fn getMapKeyAt(self: Node, index: u32) !Node
pub fn getMapValueAt(self: Node, index: u32) !Node
pub fn getMapKey(self: Node, key: []const u8) !Node
};
```
<code>TreeCursor</code>
A <code>TreeCursor</code> can be used to traverse through a tree's nodes in order.
```zig
var cursor = try tree.cursor();
// ... or a cursor starting from any nested Map node
var cursor = try TreeCursor.init(nested_map_node);
```
It is non-allocating, and returns items one-by-one via the <code>next</code> method. When all items are exhausted, <code>null</code> is returned.
```zig
pub const TreeCursor = struct {
pub const MAX_STACK_DEPTH = 512;
pub const Event = union(enum) {
// Value events
null,
bool: bool,
int: i64,
uint: u64,
float: f32,
double: f64,
string: []const u8,
bytes: []const u8,
<code>// Container events
mapStart: u32, // Count of map
mapEnd,
arrayStart: u32, // Length of array
arrayEnd,
// Extensions
extension: struct {
type: i8,
data: []const u8,
},
</code>
};
pub fn init(root: Node) TreeCursor
pub fn next(self: *TreeCursor) !?Event
};
```
<code>Reader</code>
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
Simple, zero-allocating, single-pass reader.
Strings/Binary/Extension values are "views" into the original buffer, and hence only valid as long as the buffer lives.
</blockquote>
Simple primitive reader API that reads tags from the encoded buffer one-by-one. This is the fastest way to traverse through the message but cannot go backwards nor provide random-access. Each read tag advances the reader automatically.
Use the <code>Tree</code> API if elements are to be accessed multiple times or random-access is required.
Otherwise, it is recommended to use the traversing <code>Cursor</code> API instead of using this directly.
```zig
pub const Reader = struct {
pub const TagType = enum {
Null,
Bool,
Int,
Uint,
Float,
Double,
String,
Bytes,
Array,
Map,
};
pub const Tag = struct {
pub fn getType(self: *Tag) TagType,
<code>pub fn isNull(self: *Tag) bool,
pub fn getBool(self: *Tag) bool,
pub fn getInt(self: *Tag) i64,
pub fn getUint(self: *Tag) u64,
pub fn getFloat(self: *Tag) f32,
pub fn getDouble(self: *Tag) f64,
pub fn getStringValue(self: *Tag, reader: *Reader) ![]const u8,
pub fn getBinaryBytes(self: *Tag, reader: *Reader) ![]const u8,
pub fn getExtensionBytes(self: *Tag, reader: *Reader) ![]const u8
pub fn getStringLength(self: *Tag) u32,
pub fn getArrayLength(self: *Tag) u32,
pub fn getMapLength(self: *Tag) u32,
pub fn getBinLength(self: *Tag) u32,
pub fn getExtensionLength(self: *Tag) u32,
pub fn getExtensionType(self: *Tag) i8
</code>
}
pub fn init(data: []const u8) Reader
pub fn readTag(self: <em>Reader) !Tag
pub fn finishArray(self: </em>Reader) void
pub fn finishMap(self: <em>Reader) void
pub fn cursor(self: </em>Reader) Cursor
pub fn deinit(self: *Reader) !void
};
```
<code>Cursor</code>
Cursor based on the <code>Reader</code> API. Faster than <code>TreeCursor</code> but subject to the same limitations as <code>Reader</code>.
The API is very similar to <code>TreeCursor</code>.
```zig
pub const Cursor = struct {
pub const MAX_STACK_DEPTH = 512;
pub const Event = union(enum) {
// Value events
null,
bool: bool,
int: i64,
uint: u64,
float: f32,
double: f64,
string: []const u8,
bytes: []const u8,
<code>// Container events
mapStart: u32, // Count of map
mapEnd,
arrayStart: u32, // Length of array
arrayEnd,
// Extensions
extension: struct {
type: i8,
data: []const u8,
},
</code>
};
pub fn init(reader: <em>Reader) Cursor
pub fn next(self: </em>Cursor) !?Event
};
```
Testing
Unit tests are present in the <code>test/</code> directory.
Currently, the tests are limited and do not cover everything.
PRs to improve the quality of these tests are welcome.
<code>bash
zig build test</code>
Benchmarks
Benchmarks are present in <code>benchmark/</code> and use the <a>zBench</a> library.
Run the benchmarks:
<code>bash
zig build bench</code>
Results on my personal PC (Intel i5-11400H, Debian, 32 GiB RAM):
```
benchmark runs total time time/run (avg ± σ) (min ... max) p75 p99 p995
explicit write x 100 65535 625.421ms 9.543us ± 1.091us (8.976us ... 82.607us) 9.808us 13.675us 15.594us
serialize struct x 100 65535 585.208ms 8.929us ± 1.517us (7.551us ... 52.956us) 9.685us 12.922us 13.962us
tree: parse 65535 10.195ms 155ns ± 93ns (136ns ... 19.05us) 158ns 186ns 188ns
tree: parse w/ pool 65535 10.901ms 166ns ± 1.222us (129ns ... 211.649us) 166ns 247ns 248ns
tree: read by path 65535 23.742ms 362ns ± 183ns (324ns ... 31.989us) 367ns 413ns 526ns
tree: cursor iterate 65535 23.694ms 361ns ± 234ns (328ns ... 35.133us) 363ns 410ns 421ns
reader: cursor iterate 65535 11.166ms 170ns ± 41ns (158ns ... 5.897us) 175ns 187ns 190ns
``` | [] |
https://avatars.githubusercontent.com/u/26848022?v=4 | fsharp-native-dll | deadblackclover/fsharp-native-dll | 2025-02-02T06:53:32Z | Example of using native libraries in F# | master | 0 | 11 | 0 | 11 | https://api.github.com/repos/deadblackclover/fsharp-native-dll/tags | MIT | [
"dll",
"fsharp",
"native",
"rust",
"zig"
] | 13 | false | 2025-03-26T17:00:01Z | false | false | unknown | github | [] | fsharp-native-dll
Example of using native libraries in F#
Build native_rust
<code>sh
cargo build</code>
Build native_zig
Use version 0.13.0 to compile the library
<code>sh
zig build</code>
Build native_fsharp
<code>sh
dotnet publish -c Release -r <RUNTIME_IDENTIFIER> --self-contained</code> | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zwindows | zig-gamedev/zwindows | 2024-08-10T13:23:05Z | Windows development SDK for Zig game developers. | main | 1 | 11 | 4 | 11 | https://api.github.com/repos/zig-gamedev/zwindows/tags | MIT | [
"bindings",
"gamedev",
"win32",
"zig"
] | 356 | false | 2025-04-22T18:55:37Z | true | true | 0.14.0 | github | [] | <a>zwindows</a>
Windows development SDK for Zig game developers.
<ul>
<li>Vendored DirectX Compiler binaries for Windows and Linux</li>
<li>Vendored DirectX and DirectML runtime libraries</li>
<li>Lightweight partial bindings for:<ul>
<li>Win32 API (extends std.os.windows)</li>
<li>Direct3D 12</li>
<li>Direct3D 11</li>
<li>DXGI</li>
<li>DirectML</li>
<li>Direct2D</li>
<li>XAudio2</li>
<li>Wincodec (WIC)</li>
<li>WASAPI</li>
<li>Media Foundation</li>
<li>DirectWrite</li>
</ul>
</li>
<li>Optional D3D12 helper library (zd3d12)</li>
<li>Optional XAudio2 helper library (zxaudio2)</li>
</ul>
Using the Zig package
Example build.zig
```zig
pub fn build(b: *std.Build) !void {
<code>...
const zwindows = b.dependency("zwindows", .{
.zxaudio2_debug_layer = (builtin.mode == .Debug),
.zd3d12_debug_layer = (builtin.mode == .Debug),
.zd3d12_gbv = b.option("zd3d12_gbv", "Enable GPU-Based Validation") orelse false,
});
// Activate the sdk. This does things like ensure executables are executable by the system user.
const activate_zwindows = @import("zwindows").activateSdk(b, zwindows);
exe.step.dependOn(activate_zwindows);
// Import the Windows API bindings
exe.root_module.addImport("zwindows", zwindows.module("zwindows"));
// Import the optional zd3d12 helper library
exe.root_module.addImport("zd3d12", zwindows.module("zd3d12"));
// Import the optional zxaudio2 helper library
exe.root_module.addImport("zxaudio2", zwindows.module("zxaudio2"));
// Install vendored binaries
try @import("zwindows").install_xaudio2(&exe.step, zwindows, .bin);
try @import("zwindows").install_d3d12(&exe.step, zwindows, .bin);
try @import("zwindows").install_directml(&exe.step, zwindows, .bin);
</code>
}
```
Bindings Usage Example
```zig
const zwindows = @import("zwindows");
const windows = zwindows.windows;
const dwrite = zwindows.dwrite;
const dxgi = zwindows.dxgi;
const d3d12 = zwindows.d3d12;
const d3d12d = zwindows.d3d12d;
const dml = zwindows.directml;
// etc
pub fn main() !void {
...
const winclass = windows.WNDCLASSEXA{
.style = 0,
.lpfnWndProc = processWindowMessage,
.cbClsExtra = 0,
.cbWndExtra = 0,
.hInstance = @ptrCast(windows.HINSTANCE, windows.GetModuleHandleA(null)),
.hIcon = null,
.hCursor = windows.LoadCursorA(null, @intToPtr(windows.LPCSTR, 32512)),
.hbrBackground = null,
.lpszMenuName = null,
.lpszClassName = name,
.hIconSm = null,
};
_ = windows.RegisterClassExA(&winclass);
}
```
zd3d12
zd3d12 is an optional helper library for Direct3d 12 build ontop of the zwindows bindings
Features
<ul>
<li>Basic DirectX 12 context management (descriptor heaps, memory heaps, swapchain, CPU and GPU sync, etc.)</li>
<li>Basic DirectX 12 resource management (handle-based resources and pipelines)</li>
<li>Basic resource barriers management with simple state-tracking</li>
<li>Transient and persistent descriptor allocation</li>
<li>Fast image loading using WIC (Windows Imaging Component)</li>
<li>Helpers for uploading data to the GPU</li>
<li>Fast mipmap generator running on the GPU</li>
<li>Interop with Direct2D and DirectWrite for high-quality vector graphics and text rendering (optional)</li>
</ul>
Example applications
<ul>
<li>https://github.com/zig-gamedev/zig-gamedev/tree/main/samples/triangle</li>
<li>https://github.com/zig-gamedev/zig-gamedev/tree/main/samples/textured_quad</li>
<li>https://github.com/zig-gamedev/zig-gamedev/tree/main/samples/vector_graphics_test</li>
<li>https://github.com/zig-gamedev/zig-gamedev/blob/main/samples/rasterization</li>
<li>https://github.com/zig-gamedev/zig-gamedev/tree/main/samples/bindless</li>
<li>https://github.com/zig-gamedev/zig-gamedev/blob/main/samples/mesh_shader_test</li>
<li>https://github.com/zig-gamedev/zig-gamedev/blob/main/samples/directml_convolution_test</li>
</ul>
Usage Example
```zig
const zd3d12 = @import("zd3d12");
// We need to export below symbols for DirectX 12 Agility SDK.
pub export const D3D12SDKVersion: u32 = 610;
pub export const D3D12SDKPath: [*:0]const u8 = ".\d3d12\";
pub fn main() !void {
...
var gctx = zd3d12.GraphicsContext.init(.{
.allocator = allocator,
.window = win32_window,
});
defer gctx.deinit(allocator);
<code>while (...) {
gctx.beginFrame();
const back_buffer = gctx.getBackBuffer();
gctx.addTransitionBarrier(back_buffer.resource_handle, .{ .RENDER_TARGET = true });
gctx.flushResourceBarriers();
gctx.cmdlist.OMSetRenderTargets(
1,
&.{back_buffer.descriptor_handle},
TRUE,
null,
);
gctx.cmdlist.ClearRenderTargetView(back_buffer.descriptor_handle, &.{ 0.2, 0.4, 0.8, 1.0 }, 0, null);
gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATES.PRESENT);
gctx.flushResourceBarriers();
gctx.endFrame();
}
</code>
}
```
zxaudio2
zxaudio2 is an optional helper library for XAudio2 build ontop of the zwindows bindings
Usage Example
```zig
const zxaudio2 = @import("zxaudio2");
pub fn main() !void {
...
var actx = zxaudio2.AudioContext.init(allocator);
<code>const sound_handle = actx.loadSound("content/drum_bass_hard.flac");
actx.playSound(sound_handle, .{});
var music = zxaudio2.Stream.create(allocator, actx.device, "content/Broke For Free - Night Owl.mp3");
hrPanicOnFail(music.voice.Start(0, xaudio2.COMMIT_NOW));
...
</code>
}
``` | [
"https://github.com/zig-gamedev/zig-gamedev",
"https://github.com/zig-gamedev/zopenvr"
] |
https://avatars.githubusercontent.com/u/36760800?v=4 | bpe.zig | alvarobartt/bpe.zig | 2025-01-22T12:03:53Z | Minimal implementation of a Byte Pair Encoding (BPE) tokenizer in Zig | main | 0 | 11 | 0 | 11 | https://api.github.com/repos/alvarobartt/bpe.zig/tags | Apache-2.0 | [
"bpe",
"gpt-2",
"tokenizer",
"zig"
] | 129 | false | 2025-04-07T14:11:25Z | true | true | unknown | github | [] | bpe.zig
<code>bpe.zig</code> is a minimal implementation of a Byte Pair Encoding (BPE) tokenizer in Zig.
<blockquote>
<span class="bg-yellow-100 text-yellow-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300">WARNING</span>
This implementation is currently an educational project for exploring Zig and
tokenizer internals (particularly BPE used in models like e.g. GPT-2).
</blockquote>
Usage
First you need to download the <code>tokenizer.json</code> file from the Hugging Face Hub
at <a><code>openai-community/gpt2</code></a>.
```zig
const std = @import("std");
const Tokenizer = @import("bpe.Tokenizer");
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
<code>// https://huggingface.co/openai-community/gpt2/tree/main/tokenizer.json
var tokenizer = try Tokenizer.init("tokenizer.json", allocator);
defer tokenizer.deinit();
const text = "Hello, I'm a test string with numbers 123 and symbols @#$!<|endoftext|>";
const encoding = try tokenizer.encode(text);
defer allocator.free(encoding);
std.debug.print("Encoded tokens: {any}\n", .{encoding});
</code>
}
```
License
This project is licensed under either of the following licenses, at your option:
<ul>
<li><a>Apache License, Version 2.0</a></li>
<li><a>MIT License</a></li>
</ul>
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this project by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions. | [] |
https://avatars.githubusercontent.com/u/182033383?v=4 | zig-cheatsheet | grokkhub/zig-cheatsheet | 2024-09-18T23:38:14Z | An overview of Zig syntax and design | main | 1 | 11 | 1 | 11 | https://api.github.com/repos/grokkhub/zig-cheatsheet/tags | - | [
"zig"
] | 50 | false | 2025-05-06T14:45:47Z | false | false | unknown | github | [] | Zig Cheat Sheet
Table of Contents
<ol>
<li><a>Introduction</a></li>
<li><a>Installation</a></li>
<li><a>Hello, World!</a></li>
<li><a>Basic Syntax</a></li>
<li><a>Variables and Data Types</a></li>
<li><a>Control Flow</a></li>
<li><a>Functions</a></li>
<li><a>Error Handling</a></li>
<li><a>Memory Management</a></li>
<li><a>Structs and Enums</a></li>
<li><a>Pointers and Slices</a></li>
<li><a>Packages and Imports</a></li>
<li><a>Testing</a></li>
<li><a>Concurrency</a></li>
<li><a>Interoperability with C</a></li>
<li><a>Build System</a></li>
<li><a>Useful Resources</a></li>
</ol>
Introduction
Zig is a general-purpose programming language designed for robustness, optimality, and maintainability. It's statically typed and provides low-level control with high-level features.
Installation
To install Zig, follow these steps:
<ol>
<li>Visit the official Zig website: https://ziglang.org/</li>
<li>Go to the "Download" section</li>
<li>Choose the appropriate version for your operating system</li>
<li>Extract the downloaded archive</li>
<li>Add the Zig binary to your system's PATH</li>
</ol>
Alternatively, you can use package managers:
<ul>
<li>On macOS with Homebrew:
<code>brew install zig</code></li>
<li>On Linux with your package manager (e.g., for Ubuntu):
<code>sudo apt-get install zig</code></li>
</ul>
Verify the installation by running:
<code>zig version</code>
Hello, World!
Let's start with a simple "Hello, World!" program in Zig:
```zig
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, World!\n", .{});
}
```
Save this in a file named <code>hello.zig</code> and run it with:
<code>zig run hello.zig</code>
Basic Syntax
Zig's syntax is designed to be clear and unambiguous. Here are some key points:
<ul>
<li>Statements don't need semicolons at the end</li>
<li>Blocks are denoted by <code>{}</code> </li>
<li>Comments start with <code>//</code> for single-line and <code>//\\</code> for multi-line</li>
<li>Variables are declared with <code>var</code> (mutable) or <code>const</code> (immutable)</li>
</ul>
Example:
```zig
const std = @import("std");
pub fn main() void {
// This is a comment
const x = 5; // Immutable
var y = 10; // Mutable
<code>//\\ This is a
multi-line comment //\\
std.debug.print("x = {}, y = {}\n", .{x, y});
</code>
}
```
Variables and Data Types
Zig has several built-in types:
<ul>
<li>Integers: <code>i8</code>, <code>u8</code>, <code>i16</code>, <code>u16</code>, <code>i32</code>, <code>u32</code>, <code>i64</code>, <code>u64</code>, <code>i128</code>, <code>u128</code></li>
<li>Floating-point: <code>f16</code>, <code>f32</code>, <code>f64</code>, <code>f128</code></li>
<li>Boolean: <code>bool</code></li>
<li>Null: <code>null</code></li>
<li>Undefined: <code>undefined</code></li>
</ul>
Examples:
```zig
const std = @import("std");
pub fn main() void {
const a: i32 = 42;
var b: f64 = 3.14;
const c: bool = true;
var d: ?i32 = null; // Optional type
<code>std.debug.print("a = {}, b = {}, c = {}, d = {?}\n", .{a, b, c, d});
</code>
}
```
Control Flow
Zig provides familiar control flow structures:
If statement
<code>zig
const x = 10;
if (x > 5) {
std.debug.print("x is greater than 5\n", .{});
} else if (x == 5) {
std.debug.print("x is equal to 5\n", .{});
} else {
std.debug.print("x is less than 5\n", .{});
}</code>
While loop
<code>zig
var i: u32 = 0;
while (i < 5) : (i += 1) {
std.debug.print("{} ", .{i});
}
// Prints: 0 1 2 3 4</code>
For loop
<code>zig
const items = [_]i32{ 4, 5, 6 };
for (items) |item, index| {
std.debug.print("items[{}] = {}\n", .{index, item});
}</code>
Functions
Functions in Zig are defined using the <code>fn</code> keyword:
```zig
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
const result = add(5, 3);
std.debug.print("5 + 3 = {}\n", .{result});
}
```
Error Handling
Zig uses a unique error handling approach:
```zig
const FileOpenError = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
fn openFile(filename: []const u8) FileOpenError!File {
if (outOfMemory()) return FileOpenError.OutOfMemory;
if (accessDenied()) return FileOpenError.AccessDenied;
if (fileNotFound()) return FileOpenError.FileNotFound;
return File{};
}
pub fn main() void {
const file = openFile("test.txt") catch |err| {
std.debug.print("Error: {}\n", .{err});
return;
};
// Use file...
}
```
Memory Management
Zig gives you fine-grained control over memory:
```zig
const std = @import("std");
pub fn main() void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = general_purpose_allocator.allocator();
<code>const bytes = gpa.alloc(u8, 100) catch |err| {
std.debug.print("Failed to allocate memory: {}\n", .{err});
return;
};
defer gpa.free(bytes);
// Use bytes...
</code>
}
```
Structs and Enums
Structs and enums are key to organizing data in Zig:
```zig
const std = @import("std");
const Color = enum {
Red,
Green,
Blue,
};
const Person = struct {
name: []const u8,
age: u32,
favorite_color: Color,
<code>fn introduce(self: Person) void {
std.debug.print("Hi, I'm {s}, I'm {} years old, and my favorite color is {}\n", .{
self.name, self.age, self.favorite_color,
});
}
</code>
};
pub fn main() void {
const bob = Person{
.name = "Bob",
.age = 30,
.favorite_color = Color.Blue,
};
bob.introduce();
}
```
Pointers and Slices
Zig provides low-level control with pointers and high-level convenience with slices:
```zig
const std = @import("std");
pub fn main() void {
var x: i32 = 42;
var y: *i32 = &x; // Pointer to x
<code>std.debug.print("x = {}, *y = {}\n", .{x, y.*});
var arr = [_]i32{ 1, 2, 3, 4, 5 };
var slice = arr[1..4]; // Slice of arr from index 1 to 3
for (slice) |item| {
std.debug.print("{} ", .{item});
}
// Prints: 2 3 4
</code>
}
```
Packages and Imports
Zig uses a straightforward module system:
```zig
// In math.zig
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
// In main.zig
const std = @import("std");
const math = @import("math.zig");
pub fn main() void {
const result = math.add(5, 3);
std.debug.print("5 + 3 = {}\n", .{result});
}
```
Testing
Zig has built-in support for testing:
```zig
const std = @import("std");
const expect = std.testing.expect;
fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic addition" {
try expect(add(3, 4) == 7);
}
test "negative numbers" {
try expect(add(-1, -1) == -2);
}
```
Run tests with:
<code>zig test your_file.zig</code>
Concurrency
Zig provides low-level primitives for concurrency:
```zig
const std = @import("std");
fn printNumbersThread(context: void) void {
for (0..5) |i| {
std.debug.print("Thread: {}\n", .{i});
std.time.sleep(1 * std.time.ns_per_s);
}
}
pub fn main() !void {
var thread = try std.Thread.spawn(.{}, printNumbersThread, .{});
for (0..5) |i| {
std.debug.print("Main: {}\n", .{i});
std.time.sleep(1 * std.time.ns_per_s);
}
thread.join();
}
```
Interoperability with C
Zig can easily interoperate with C code:
```zig
const c = @cImport({
@cInclude("stdio.h");
});
pub fn main() void {
_ = c.printf("Hello from C!\n");
}
```
Compile with:
<code>zig build-exe your_file.zig -lc</code>
Build System
Zig comes with its own build system. Here's a simple <code>build.zig</code>:
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const exe = b.addExecutable(.{
.name = "my-project",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
</code>
}
```
Build and run with:
<code>zig build run</code>
Useful Resources
<ul>
<li><a>Official Zig Documentation</a></li>
<li><a>Zig Learn</a></li>
<li><a>Zig Standard Library Documentation</a></li>
</ul>
Remember, Zig is a rapidly evolving language, so always refer to the latest official documentation for the most up-to-date information. | [] |
https://avatars.githubusercontent.com/u/8823448?v=4 | jaysan | lawrence-laz/jaysan | 2024-09-18T23:20:56Z | A fast json serializer | main | 0 | 11 | 0 | 11 | https://api.github.com/repos/lawrence-laz/jaysan/tags | MIT | [
"json",
"json-serializer",
"zig",
"zig-package"
] | 26 | false | 2025-01-02T16:43:37Z | true | true | unknown | github | [] |
Jayさん
Jaysan is a fast json library written in Zig. Currently supports serialization only.
```zig
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const Foo = struct {
foo: i32,
bar: []const u8,
};
const string = try json.stringifyAlloc(
gpa.allocator(),
Foo{
.foo = 123,
.bar = "Hello, world!",
},
);
// {"foo":123,"bar":"Hello, world!"}
```
```md
Benchmark 1: zig-stdjson
Time (mean ± σ): 141.9 ms ± 1.1 ms [User: 140.4 ms, System: 1.0 ms]
Range (min … max): 140.1 ms … 144.1 ms 20 runs
Benchmark 2: zig-jaysan
Time (mean ± σ): 46.8 ms ± 1.3 ms [User: 46.2 ms, System: 0.4 ms]
Range (min … max): 43.1 ms … 49.2 ms 61 runs
Benchmark 3: rust-serde
Time (mean ± σ): 46.9 ms ± 0.9 ms [User: 45.8 ms, System: 0.9 ms]
Range (min … max): 45.9 ms … 50.9 ms 62 runs
Summary
zig-jaysan
1.00 ± 0.03 times faster than rust-serde
3.03 ± 0.09 times faster than zig-stdjson
``` | [] |
https://avatars.githubusercontent.com/u/56497124?v=4 | lizpack | kj4tmp/lizpack | 2024-12-19T07:19:26Z | A MessagePack Library for Zig | main | 0 | 11 | 0 | 11 | https://api.github.com/repos/kj4tmp/lizpack/tags | MIT | [
"zig",
"zig-package"
] | 102 | false | 2025-04-19T09:57:56Z | true | true | 0.14.0 | github | [] | lizpack
A MessagePack Library for Zig
<ol>
<li>Zero allocations.</li>
<li>Zero encoding errors.</li>
<li>Simple control flow.</li>
<li>All messages validated for you.</li>
</ol>
A simple API:
<code>zig
lizpack.encode(...)
lizpack.encodeBounded(...)
lizpack.encodeAlloc(...)
lizpack.decode(...)
lizpack.decodeAlloc(...)</code>
Combines with your definition of your message structure:
<code>zig
const CustomerComplaint = struct {
user_id: u64,
status: enum(u8) {
received,
reviewed,
awaiting_response,
finished,
},
};</code>
Default Formats
| Zig Type | MessagePack Type |
| ---------------------------------- | ----------------------------------- |
| <code>bool</code> | bool |
| <code>null</code> | nil |
| <code>u3</code>,<code>u45</code>, <code>i6</code> | integer |
| <code>?T</code> | nil or T |
| <code>enum</code> | integer |
| <code>[N]T</code> | N length array of T |
| <code>[N:x]T</code> | N+1 length array of T ending in x |
| <code>[N]u8</code> | str |
| <code>@Vector(N, T)</code> | N length array of T |
| <code>struct</code> | map, str: field value |
| <code>union (enum)</code> | map (single key-value pair) |
| <code>[]T</code> | N length array of T |
| <code>[:x]T</code> | N + 1 length array of T ending in x |
| <code>[]u8</code> | str |
| <code>[:x]u8</code> | str ending in x |
| <code>*T</code> | T |
<blockquote>
<code>str</code> is the default MessagePack type for <code>[]u8</code> because it is the smallest for short slices.
</blockquote>
Unsupported types:
| Zig Type | Reason |
| ------------------ | ------------------------------------------------------------ |
| <code>union</code> (untagged) | Decoding cannot determine active field, and neither can you. |
| <code>error</code> | I can add this, if someone asks. Perhaps as <code>str</code>? |
Note: pointer types require allocation to decode.
Customizing Formats
You can customize how types are formatted in message pack:
| Zig Type | Available Encodings |
| ----------------------------------- | ----------------------------------------- |
| <code>enum</code> | string, int |
| <code>[]u8</code>,<code>[N]u8</code>, <code>@Vector(N, u8)</code> | string, int, array |
| <code>struct</code> | map, array |
| <code>union (enum)</code> | map (single key-value pair), active field |
| <code>[] struct {key: ..., value: ...}</code> | map, array |
| <code>[N] struct {key: ..., value: ...}</code> | map, array |
See <a>examples</a> for how to do it.
Manual Encoding / Decoding
If you require the finest level of control over how data is encoded and decoded, the <code>lizpack.manual</code> API
may suit your use case.
See <a>examples</a> for how to do it.
Examples
```zig
const std = @import("std");
const lizpack = @import("lizpack");
test {
const CustomerComplaint = struct {
user_id: u64,
status: enum(u8) {
received,
reviewed,
awaiting_response,
finished,
},
};
<code>var out: [1000]u8 = undefined;
const expected: CustomerComplaint = .{ .user_id = 2345, .status = .reviewed };
const slice: []u8 = try lizpack.encode(expected, &out, .{});
try std.testing.expectEqual(expected, lizpack.decode(@TypeOf(expected), slice, .{}));
</code>
}
```
More examples can be found in <a>examples/</a>.
Installation
To add lizpack to your project as a dependency, run:
<code>sh
zig fetch --save git+https://github.com/kj4tmp/lizpack</code>
Then add the following to your build.zig:
<code>zig
// assuming you have an existing executable called `exe`
const lizpack = b.dependency("lizpack", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("lizpack", lizpack.module("lizpack"));</code>
And import the library to begin using it:
<code>zig
const lizpack = @import("lizpack");</code>
Zig Version
Please refer to the <code>minimum_zig_version</code> field of the <a><code>build.zig.zon</code></a>.
TODO
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> refactor: use of has_sentinel
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> refactor: use of std.builtin.Type.Pointer.Sentinel | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zmesh | zig-gamedev/zmesh | 2024-11-03T23:16:59Z | Zig library for loading, generating, processing and optimising triangle meshes. | main | 1 | 11 | 8 | 11 | https://api.github.com/repos/zig-gamedev/zmesh/tags | MIT | [
"3d",
"gamedev",
"mesh-generation",
"mesh-optimization",
"mesh-processing",
"zig"
] | 594 | false | 2025-05-06T22:04:43Z | true | true | unknown | github | [] |
<a>zmesh</a>
Zig library for loading, generating, processing and optimising triangle meshes.
Under the hood this library uses below C/C++ libraries:
<ul>
<li><a>par shapes</a></li>
<li><a>meshoptimizer</a></li>
<li><a>cgltf</a></li>
</ul>
All memory allocations go through user-supplied, Zig allocator.
As an example program please see <a>procedural mesh (wgpu)</a>.
Getting started
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ ... });
<code>const zmesh = b.dependency("zmesh", .{});
exe.root_module.addImport("zmesh", zmesh.module("root"));
exe.linkLibrary(zmesh.artifact("zmesh"));
</code>
}
```
Now in your code you may import and use <code>zmesh</code>:
```zig
const zmesh = @import("zmesh");
pub fn main() !void {
...
zmesh.init(allocator);
defer zmesh.deinit();
<code>var custom = zmesh.Shape.init(indices, positions, normals, texcoords);
defer custom.deinit();
var disk = zmesh.Shape.initParametricDisk(10, 2);
defer disk.deinit();
disk.invert(0, 0);
var cylinder = zmesh.Shape.initCylinder(10, 4);
defer cylinder.deinit();
cylinder.merge(disk);
cylinder.translate(0, 0, -1);
disk.invert(0, 0);
cylinder.merge(disk);
cylinder.scale(0.5, 0.5, 2);
cylinder.rotate(math.pi * 0.5, 1.0, 0.0, 0.0);
cylinder.unweld();
cylinder.computeNormals();
...
</code>
}
```
```zig
const zmesh = @import("zmesh");
pub fn main() !void {
zmesh.init(allocator);
defer zmesh.deinit();
<code>//
// Load mesh
//
const data = try zmesh.io.zcgltf.parseAndLoadFile(content_dir ++ "cube.gltf");
defer zmesh.io.zcgltf.freeData(data);
var mesh_indices = std.ArrayList(u32).init(allocator);
var mesh_positions = std.ArrayList([3]f32).init(allocator);
var mesh_normals = std.ArrayList([3]f32).init(allocator);
zmesh.io.zcgltf.appendMeshPrimitive(
data,
0, // mesh index
0, // gltf primitive index (submesh index)
&mesh_indices,
&mesh_positions,
&mesh_normals, // normals (optional)
null, // texcoords (optional)
null, // tangents (optional)
);
...
//
// Optimize mesh
//
const Vertex = struct {
position: [3]f32,
normal: [3]f32,
};
var remap = std.ArrayList(u32).init(allocator);
remap.resize(src_indices.items.len) catch unreachable;
const num_unique_vertices = zmesh.opt.generateVertexRemap(
remap.items, // 'vertex remap' (destination)
src_indices.items, // non-optimized indices
Vertex, // Zig type describing your vertex
src_vertices.items, // non-optimized vertices
);
var optimized_vertices = std.ArrayList(Vertex).init(allocator);
optimized_vertices.resize(num_unique_vertices) catch unreachable;
zmesh.opt.remapVertexBuffer(
Vertex, // Zig type describing your vertex
optimized_vertices.items, // optimized vertices (destination)
src_vertices.items, // non-optimized vertices (source)
remap.items, // 'vertex remap' generated by generateVertexRemap()
);
// More optimization steps are available - see `zmeshoptimizer.zig` file.
</code>
}
``` | [
"https://github.com/zig-gamedev/zig-gamedev"
] |
https://avatars.githubusercontent.com/u/231785?v=4 | ztap | mnemnion/ztap | 2024-09-12T01:42:44Z | ZTAP: TAP producer for zig build test | trunk | 0 | 11 | 1 | 11 | https://api.github.com/repos/mnemnion/ztap/tags | MIT | [
"tap",
"testing",
"zig",
"zig-package"
] | 35 | false | 2025-05-19T19:54:40Z | true | true | unknown | github | [] | ZTAP
The <a>Test Anything Protocol</a> is a simple,
venerable, and widely-used format for reporting the output of tests.
ZTAP is a Zig library for running and reporting tests in the TAP 14
format.
Compatibility
ZTAP requires Zig 0.14.
Use
This can be used as the main unit testing step, or as a custom step.
Instructions will assume the latter, but are easily adapted for the
former case.
Add to <code>build.zig.zon</code> in the usual fashion:
<code>sh
zig fetch --save "https://github.com/mnemnion/ztap/archive/refs/tags/v0.9.1.tar.gz"</code>
You'll need a test runner. A default one is included, and looks like this:
```zig
const std = @import("std");
const builtin = @import("builtin");
const ztap = @import("ztap");
// This gives TAP-compatible panic handling
pub const panic = std.debug.FullPanic(ztap.ztap_panic);
pub fn main() !void {
ztap.ztap_test(builtin);
std.process.exit(0);
}
```
Which you could customize, on the off chance that you need that.
Do be sure to exit with <code>0</code>, since the protocol interprets non-zero as
a test failure.
Next, set up your <code>build.zig</code>. We'll assume you want to use the
default test runner, and make this a custom step.
```zig
// If you want to filter tests, add this. It works with the stock
// unit test runner as well.
const test_filters: []const []const u8 = b.option(
[]const []const u8,
"test-filter",
"Skip tests that do not match any of the specified filters",
) orelse &.{};
<code>const ztap_dep = b.dependency("ztap", .{
.target = target,
.optimize = optimize,
});
// ZTAP test runner step.
const ztap_unit_tests = b.addTest(.{
.name = "ztap-run",
.root_source_file = b.path("src/test-root-file.zig"),
.target = target,
.optimize = optimize,
.filters = test_filters,
// With the provided test runner:
.test_runner = .{ .path = ztap_dep.namedLazyPath("runner"), .mode = .simple},
// Or you can use your own:
// .test_runner = .{ .path = b.path("src/ztap_custom_runner.zig"), .mode = .simple },
});
ztap_unit_tests.root_module.addImport("ztap", ztap_dep.module("ztap"));
// To put the runner in zig-out etc.
b.installArtifact(ztap_unit_tests);
const run_ztap_tests = b.addRunArtifact(ztap_unit_tests);
// To always run tests, even if nothing changed, add this:
// run_ztap_tests.has_side_effects = true;
// TAP producers write to stdout.
//
// To suppress stderr chatter, you can uncomment this:
// _ = run_ztap_tests.captureStdErr();
// Just call this "test" to make ZTAP the main test runner.
const ztap_step = b.step("ztap", "Run tests with ZTAP");
ztap_step.dependOn(&run_ztap_tests.step);
// Otherwise you can set up default tests as well, in the
// expected manner. It's nice to have options.
</code>
```
That should do the trick. See the first link for an example of what to
expect in the way of output.
Use Notes
ZTAP is simply an output format for Zig's test system, and no changes
should be necessary to use it as such. If <code>error.SkipZigTest</code> is
returned, ZTAP will issue the <code># Skip</code> directive. Zig doesn't support
a TODO for tests (not that it should necessarily), but TAP does, so if
<code>error.ZTapTodo</code> is returned, ZTAP will issue <code># Todo</code>. Zig's test
runner will treat the latter as any other error. In the event that Zig
adds a TODO error to the test system, ZTAP will support that also.
The <code>ztap_panic</code> function will add a comment to the TAP output naming
the test, and issue the <code>Bail out!</code> directive which is proper for a
fatal error. It then calls the default panic handler, which does the
accustomed things using <code>stderr</code>.
Roadmap
ZTAP does what it needs to. There is no visible need for additional
functionality, the library is stable and in use.
The only contemplated change is in the event that Zig does add a TODO
type error to the test system. In that event, ZTAP will support both,
with a deprecation notice for <code>error.ZTapTodo</code>, and the custom error
will be removed in 1.0.
Speaking of 1.0, an earlier version of the README suggested that ZTAP
would declare 1.0 under conditions which have in fact been achieved.
However, changes to the panic handling in Zig 0.14 required ZTAP to
make changes to its public interface. In recognition of this, ZTAP
will not declare a 1.0 edition before Zig itself does.
However, the only breaking changes I will countenance are those needed
to keep up with changes in Zig. Other than that, consider ZTAP to have
reached release status.
Why Though?
Everything speaks TAP. CI speaks TAP, distros speak TAP, your editor
speaks TAP. If you find yourself wanting to integrate with some or all
of these things, ZTAP will TAP your Zig.
Also, if you print to <code>stdout</code>, ZTAP will not hang your unit tests. That
doesn't make it a good idea, TAP harnesses ignore what they don't grok,
but it can't help things, and it can screw them up. It does mean that
tests will complete in the event that <code>stdout</code> is printed to. | [
"https://github.com/mnemnion/runeset"
] |
https://avatars.githubusercontent.com/u/24697112?v=4 | example-multi-language | goreleaser/example-multi-language | 2024-12-15T02:14:04Z | Example project using all 3 currently available builders: Go, Rust, and Zig | main | 0 | 11 | 0 | 11 | https://api.github.com/repos/goreleaser/example-multi-language/tags | MIT | [
"cargo",
"golang",
"goreleaser",
"rust",
"zig"
] | 6 | false | 2024-12-19T02:14:10Z | false | false | unknown | github | [] | example-multi-language
This example uses all 3 currently available builders: Go, Rust, and Zig. | [] |
https://avatars.githubusercontent.com/u/87213748?v=4 | terraria-classic | JamzOJamz/terraria-classic | 2024-12-09T02:31:38Z | A WIP remake of Terraria 1.0 | main | 0 | 11 | 0 | 11 | https://api.github.com/repos/JamzOJamz/terraria-classic/tags | - | [
"fanmade-remake",
"raylib",
"remake",
"terraria",
"zig",
"ziglang"
] | 64,302 | false | 2025-02-06T09:08:24Z | true | true | unknown | github | [
{
"commit": null,
"name": "raylib-zig",
"tar_url": null,
"type": "relative",
"url": "libs/raylib-zig"
},
{
"commit": null,
"name": "zig-ecs",
"tar_url": null,
"type": "relative",
"url": "libs/zig-ecs"
},
{
"commit": null,
"name": "zigwin32",
"tar_url": nul... | Terraria Classic
A work-in-progress remake of Terraria 1.0, written in <a>Zig</a> and using <a>raylib</a> for rendering.
Web Demo
There is a web demo playable <a>here.</a> | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zjobs | zig-gamedev/zjobs | 2024-11-03T23:03:29Z | Generic job queue implementation for Zig. | main | 2 | 10 | 3 | 10 | https://api.github.com/repos/zig-gamedev/zjobs/tags | MIT | [
"gamedev",
"job-queue",
"multithreading",
"zig"
] | 15 | false | 2025-05-06T22:04:42Z | true | true | unknown | github | [] | <a>zjobs</a>
Generic job queue implementation for Zig.
In order to take full advantage of modern multicore CPUs, it is necessary to
run much of your application logic on separate threads. This <code>JobQueue</code>
provides a simple API to schedule "jobs" to run on a pool of threads, typically
as many threads as your CPU supports, less 1 (the main thread).
Each "job" is a user-defined struct that declares a <code>exec</code> function that will
be executed on a background thread by the <code>JobQueue</code>.
Getting started
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ ... });
<code>const zjobs = b.dependency("zjobs", .{});
exe.root_module.addImport("zjobs", zjobs.module("root"));
</code>
}
```
Example Usage
The following example is also a <code>test</code> case in <code>zjobs.zig</code>:
<code>``zig
const Jobs = JobQueue(.{}); // a default-configured</code>JobQueue` type
var jobs = Jobs.init(); // initialize an instance of <code>Jobs</code>
defer jobs.deinit(); // ensure that <code>jobs</code> is cleaned up when we're done
// First we will define a job that will print "hello " when it runs.
// The job must declare a <code>exec</code> function, which defines the code that
// will be executed on a background thread by the <code>JobQueue</code>.
// Our <code>HelloJob</code> doesn't contain any member variables, but it could.
// We will see an example of a job with some member variables below.
const HelloJob = struct {
pub fn exec(_: *@This()) void {
print("hello ", .{});
}
};
// Now we will schedule an instance of <code>HelloJob</code> to run on a separate
// thread.
// The <code>schedule()</code> function returns a <code>JobId</code>, which is how we can refer
// to this job to determine when it is done.
// The first argument to <code>schedule()</code> is the <code>prereq</code>, which
// specifies a job that must be completed before this job can run.
// Here, we specify the <code>prereq</code> of <code>JobId.none</code>, which means that
// this job does not need to wait for any other jobs to complete.
// The second argument to <code>schedule()</code> is the <code>job</code>, which is a user-
// defined struct that declares a <code>exec</code> function that will be executed
// on a background thread.
// Here we are providing an instance of our <code>HelloJob</code> defined above.
const hello_job_id: JobId = try jobs.schedule(
JobId.none, // does not wait for any other job
HelloJob{}, // runs <code>HelloJob.exec()</code> on another thread
);
// Scheduled jobs will not execute until <code>start()</code> is called.
// The <code>start()</code> function spawns the threads that will run the jobs.
// Note that we can schedule jobs before and after calling <code>start()</code>.
jobs.start();
// Now we will schedule a second job that will print "world!" when it runs.
// We want this job to run after the <code>HelloJob</code> completes, so we provide
// <code>hello_job_id</code> as the <code>prereq</code> when scheduling this job.
// This ensures that the string "hello " will be printed before we print
// the string "world!\n"
// This time, we will use an anonymous struct to declare the job directly
// within the call to <code>schedule()</code>.
// Note the trailing empty braces, <code>{}</code>, which initialize an instance of
// this anonymous struct.
const world_job_id: JobId = try jobs.schedule(
hello_job_id, // waits for <code>hello_job_id</code> to be completed
struct {
fn exec(_: *@This()) void {
print("world!\n", .{});
}
}{}, // trailing <code>{}</code> initializes an instance of this anonymous struct
);
// When we want to shut down all of the background threads, we can call
// the <code>stop()</code> function.
// Here we will schedule a job to call <code>stop()</code> after our "world!" job
// completes.
// This ensures that the string "hello world!\n" will be printed before
// we stop running our jobs.
// Note that our anonymous "stop job" captures a pointer to <code>jobs</code> so that
// it can call <code>stop()</code>.
_ = try jobs.schedule(
world_job_id, // waits for <code>world_job_id</code> to be completed
struct {
jobs: <em>Jobs, // stores a pointer to <code>jobs</code>
fn exec(self: </em>@This()) void {
self.jobs.stop();
}
}{ // trailing <code>{}</code> initializes an instance of this anonymous struct
.jobs = &jobs, // and initializes a pointer to <code>jobs</code> here
},
);
// Now that we're done, we can call <code>join()</code> to wait for all of the
// background threads to finish processing scheduled jobs.
jobs.join();
``` | [
"https://github.com/azillion/gravitas",
"https://github.com/zig-gamedev/zig-gamedev"
] |
https://avatars.githubusercontent.com/u/20110944?v=4 | zoridor | ringtailsoftware/zoridor | 2024-11-24T08:30:36Z | A Quoridor game for terminal and web | main | 0 | 10 | 1 | 10 | https://api.github.com/repos/ringtailsoftware/zoridor/tags | MIT | [
"game",
"quoridor",
"zig",
"zig-package"
] | 1,709 | false | 2025-02-15T10:35:46Z | true | true | unknown | github | [
{
"commit": "b001662c929e2719ee24be585a3120640f946337",
"name": "mibu",
"tar_url": "https://github.com/xyaman/mibu/archive/b001662c929e2719ee24be585a3120640f946337.tar.gz",
"type": "remote",
"url": "https://github.com/xyaman/mibu"
},
{
"commit": "c2e3122d5dd6192513ba590f229dbc535110efb8"... | Zoridor
A terminal and web version of the <a>Quoridor</a> board game
<a>WASM4</a> version on <a>wasm4 branch</a>.
Play on the web at https://ringtailsoftware.github.io/zoridor/
Or play the WASM4 cart at https://ringtailsoftware.github.io/zoridor/cart.html
Quoridor tutorials:
<ul>
<li>https://www.youtube.com/watch?v=39T3L6hNfmg</li>
<li>https://www.youtube.com/watch?v=FDdm-EgRy9g</li>
<li>https://www.youtube.com/watch?v=6ISruhN0Hc0</li>
</ul>
Running
Get <a>Zig</a>
Terminal version:
<code>zig build run
</code>
Web version:
<code>zig build -Dweb=true && zig build serve -- zig-out -p 8000
</code>
Browse to http://localhost:8000
Development
Auto-rebuild and reload on change
<code>watchexec -r --stop-signal SIGKILL -e zig,html,css,js,zon -w src 'zig build -Dweb=true && zig build serve -- zig-out -p 8000'
</code>
Terminal mode controls
<ul>
<li>You are Player 1. Your objective is to move your red pawn from the top of the board to the bottom of the board</li>
<li>Player 2 starts at the bottom and is attempting to reach the top of the board</li>
<li>On each turn you can either move your pawn or add one fence piece to the board (you have 10 to start with)</li>
</ul>
Moving a pawn
<ul>
<li>Use the cursor keys to choose where to move to. Your pawn may only move one square on each turn and cannot move diagonally</li>
<li>The "[ ]" mark where your pawn will move and is coloured green for a valid move and red for invalid</li>
<li>Once you have selected a move, press enter to move the pawn</li>
</ul>
Adding a fence
<ul>
<li>Press tab to switch from pawn to fence mode</li>
<li>Use the cursor keys to choose where to add the fence</li>
<li>Fences must not cross other fences, or completely block either player from reaching their goal. An invalid fence position will be shown in red</li>
<li>To rotate the fence, press space</li>
<li>Once you have positioned the fence, press enter to place it</li>
</ul>
Command line options
Help
<code>zig build run -- -h
</code>
To watch machine vs machine matches forever:
<code>zig build run -- -1 machine -2 machine -f
</code>
On exit, a record of all moves is printed in both Glendenning format and base64. The base64 format can be reloaded with <code>zig build run -- -l jcNJujqxKRY2sA==</code>
Theory
For a comprehensive examination of playing Quoridor, see <a>Lisa Glendenning's Thesis</a> | [] |
https://avatars.githubusercontent.com/u/104849437?v=4 | uuid.zig | octopus-foundation/uuid.zig | 2024-11-15T14:06:00Z | UUID v4 implementation in pure Zig. No allocations | master | 1 | 10 | 0 | 10 | https://api.github.com/repos/octopus-foundation/uuid.zig/tags | MIT | [
"zig",
"zig-package"
] | 4 | false | 2025-04-29T07:52:31Z | true | true | 0.14.0 | github | [] | UUID v4
RFC 4122 compliant UUID v4 implementation in Zig.
Features
<ul>
<li>Zero dependencies</li>
<li>Generate random UUIDs (v4)</li>
<li>Parse from string/bytes</li>
<li>Format to string/bytes</li>
<li>No allocations</li>
<li>Supports cryptographic RNG</li>
<li>Tested on Zig 0.14.0-dev</li>
</ul>
Install
<code>bash
zig fetch --save https://github.com/octopus-foundation/uuid.zig/archive/refs/tags/0.0.0.tar.gz</code>
In your <code>build.zig</code>:
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const uuid = b.dependency("uuid", .{
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable(.{
.name = "example",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("uuid", uuid.module("uuid"));
b.installArtifact(exe);
</code>
}
```
Usage
```zig
const uuid = @import("uuid").v4;
// Generate random UUID
var prng = std.Random.DefaultPrng.init(0);
const id = uuid.random(prng.random());
// Format as string
var buf: [36]u8 = undefined;
uuid.toString(id, &buf);
// "550e8400-e29b-41d4-a716-446655440000"
// Parse from string
const parsed = try uuid.fromString("550e8400-e29b-41d4-a716-446655440000");
// Convert to/from bytes
var bytes: [16]u8 = undefined;
uuid.toBytes(id, &bytes);
const fromBytes = try uuid.fromBytes(&bytes);
// With crypto random
const crypto_id = uuid.random(std.crypto.random);
``` | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | wayland | allyourcodebase/wayland | 2024-12-18T19:07:19Z | wayland ported to the zig build system | master | 0 | 10 | 1 | 10 | https://api.github.com/repos/allyourcodebase/wayland/tags | MIT | [
"zig",
"zig-package"
] | 24 | false | 2025-05-20T23:58:32Z | true | true | 0.14.0 | github | [
{
"commit": null,
"name": "wayland",
"tar_url": null,
"type": "remote",
"url": "git+https://gitlab.freedesktop.org/wayland/wayland.git?ref=1.23.1#a9fec8dd65977c57f4039ced34327204d9b9d779"
},
{
"commit": "master",
"name": "libffi",
"tar_url": "https://github.com/vezel-dev/libffi/a... | <a></a>
Wayland
This is <a>Wayland</a>, packaged for <a>Zig</a>.
Installation
First, update your <code>build.zig.zon</code>:
```
Initialize a <code>zig build</code> project if you haven't already
zig init
zig fetch --save git+https://github.com/allyourcodebase/wayland.git#1.23.1-3
```
You can then import <code>wayland</code> in your <code>build.zig</code> with:
```zig
const wayland = b.dependency("wayland", .{
.target = target,
.optimize = optimize,
});
const wayland_server = wayland.artifact("wayland-server");
const wayland_client = wayland.artifact("wayland-client");
const wayland_egl = wayland.artifact("wayland-egl");
const wayland_cursor = wayland.artifact("wayland-cursor");
// Makes sure we get <code>wayland-scanner</code> for the host platform even when cross-compiling
const wayland_host = b.dependency("wayland", .{
.target = b.host,
.optimize = std.builtin.OptimizeMode.Debug,
});
const wayland_scanner = wayland_host.artifact("wayland-scanner");
``` | [
"https://github.com/Games-by-Mason/glfw-zig",
"https://github.com/allyourcodebase/tracy",
"https://github.com/allyourcodebase/wayland",
"https://github.com/ifreund/waylock",
"https://github.com/nmeum/creek",
"https://github.com/swaywm/zig-wlroots"
] |
https://avatars.githubusercontent.com/u/113565070?v=4 | ZWL | Darkfllame/ZWL | 2024-08-13T20:24:53Z | Zig cross platform Windowing Library | main | 1 | 10 | 0 | 10 | https://api.github.com/repos/Darkfllame/ZWL/tags | MIT | [
"cross-platform",
"opengl",
"zig"
] | 385 | false | 2025-03-05T03:26:55Z | true | true | unknown | github | [
{
"commit": "3f7d62dcab0d59242f0a49092687cf2ad3a9b308.tar.gz",
"name": "zgll",
"tar_url": "https://github.com/Darkfllame/zgll/archive/3f7d62dcab0d59242f0a49092687cf2ad3a9b308.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/Darkfllame/zgll"
}
] | Zig Windowing Library
ZWL (Zig Windowing Library, /zwil/) is a cross-platform zig windowing library with loop-based event polling (like SDL) and aimed to be lightweight thanks to zig's conditional compilation/lazy evaluation.
Current state:
Win32
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Window
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Event
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> OpenGL Context
Linux
- X11 
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Window
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Event
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> OpenGL Context
- Wayland 
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Window
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Event
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> OpenGL Context
MacOS
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Window
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Event
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> OpenGL Context
ZWL is very WIP, so expect bugs, inconsistencies and lack of support on certain platforms. If you wish you can help me by <a>contributing</a> to this project via pull requests or filing issues.
Contributing
Feel free to contribute to the library by making PRs or by filing issues. My machine is a windows one, so I'll prioritize my work (and might only work) on the Win32 implementation. | [] |
https://avatars.githubusercontent.com/u/45130910?v=4 | zpotify | Ratakor/zpotify | 2024-09-05T17:37:00Z | A CLI for Spotify | master | 0 | 10 | 0 | 10 | https://api.github.com/repos/Ratakor/zpotify/tags | GPL-3.0 | [
"cli",
"spotify",
"tui",
"zig"
] | 363 | false | 2025-01-08T20:06:28Z | true | true | 0.13.0 | github | [
{
"commit": null,
"name": "zig-spoon",
"tar_url": null,
"type": "relative",
"url": "vendor/zig-spoon"
}
] | zpotify
zpotify is a CLI for controlling Spotify playback and much more!
https://github.com/user-attachments/assets/5a97453a-db8a-4689-b2d0-ab1f2009fcb0
Installation
<a>AUR</a>
Using your favorite AUR helper or manually:
<code>git clone https://aur.archlinux.org/zpotify
cd zpotify
makepkg -si</code>
Building
Requires zig 0.13.0, libjpeg and chafa.
<code>git clone https://github.com/ratakor/zpotify
cd zpotify
zig build -Doptimize=ReleaseFast</code>
Zsh completions are available <a>here</a>!
Usage
Requires Spotify premium.
```
Usage: zpotify [command] [options]
Commands:
print | Display current track info in a specific format
search | Search a track, playlist, album, or artist with a TUI
play | Play a track, playlist, album, or artist from your library
pause | Toggle pause state
prev | Skip to previous track
next | Skip to next track
repeat | Get/Set repeat mode
shuffle | Toggle shuffle mode
seek | Get/Set the position of the current track
vol | Get/Set volume or increase/decrease volume by 10%
like | Add the current track to your liked songs
devices | List all available devices
transfer | Transfer playback to another device
waybar | Display infos about the current playback for a waybar module
logout | Remove the stored credentials from the config file
help | Display information about a command
version | Display program version
```
Performance
More than 2x times faster than the only good alternative <a>baton</a>!
```
% cat run
!/bin/sh
$1 play artist GPF
$1 next
$1 prev
$1 pause
$1 repeat
$1 shuffle
$1 vol down
% poop "./run baton" "./run zpotify" --duration 60000
Benchmark 1 (15 runs): ./run baton
measurement mean ± σ min … max outliers delta
wall_time 4.18s ± 88.4ms 3.99s … 4.32s 0 ( 0%) 0%
peak_rss 100.0MB ± 96.6KB 99.7MB … 100MB 1 ( 7%) 0%
cpu_cycles 14.5G ± 285M 14.1G … 15.2G 1 ( 7%) 0%
instructions 27.1G ± 303M 26.5G … 27.8G 0 ( 0%) 0%
cache_references 330M ± 11.9M 310M … 353M 0 ( 0%) 0%
cache_misses 75.2M ± 4.46M 67.9M … 84.4M 0 ( 0%) 0%
branch_misses 40.8M ± 512K 40.0M … 41.7M 0 ( 0%) 0%
Benchmark 2 (43 runs): ./run zpotify
measurement mean ± σ min … max outliers delta
wall_time 1.40s ± 87.3ms 1.21s … 1.64s 0 ( 0%) ⚡- 66.5% ± 1.3%
peak_rss 2.24MB ± 10.3KB 2.24MB … 2.28MB 9 (21%) ⚡- 97.8% ± 0.0%
cpu_cycles 2.11G ± 98.1M 2.03G … 2.38G 4 ( 9%) ⚡- 85.5% ± 0.7%
instructions 6.70G ± 6.02K 6.70G … 6.70G 1 ( 2%) ⚡- 75.3% ± 0.3%
cache_references 713K ± 23.2K 675K … 779K 0 ( 0%) ⚡- 99.8% ± 1.1%
cache_misses 193K ± 31.6K 130K … 275K 1 ( 2%) ⚡- 99.7% ± 1.8%
branch_misses 5.97M ± 1.93M 4.60M … 11.4M 6 (14%) ⚡- 85.4% ± 2.5%
```
Credits
<ul>
<li><a>baton</a></li>
<li><a>zig-spoon</a></li>
<li><a>chafa</a></li>
</ul>
TODO
<ul>
<li>add <code>zpotify play liked</code> cmd which play liked songs</li>
<li>add a way to save track / album to a playlist</li>
<li>embed <a>librespot</a></li>
<li>need to create bindings</li>
<li>use <a>build.crab</a> for build integration</li>
<li>use <a>ziggy</a> for config</li>
<li>librespot alternative?: <a>cspot</a></li>
<li>add man page with <a>zzdoc</a></li>
<li>redo the perf analysis</li>
<li>add test coverage</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/5521491?v=4 | fizz | wmedrano/fizz | 2024-08-11T17:13:36Z | Lispy interpreter for Zig | main | 1 | 10 | 0 | 10 | https://api.github.com/repos/wmedrano/fizz/tags | MIT | [
"lisp",
"lisp-interpreter",
"zig",
"ziglang"
] | 164 | false | 2025-03-30T00:21:08Z | true | true | unknown | github | [] | site/index.md | [] |
https://avatars.githubusercontent.com/u/60558183?v=4 | abyssbook | aldrin-labs/abyssbook | 2025-01-14T19:30:17Z | first zig orderbook in history // benchmark prolly wrong its ai estimate | main | 1 | 10 | 2 | 10 | https://api.github.com/repos/aldrin-labs/abyssbook/tags | NOASSERTION | [
"clob",
"dex",
"orderbook",
"serum",
"solana",
"svm",
"zig",
"zig-orderbook"
] | 127 | false | 2025-04-04T15:12:18Z | true | false | unknown | github | [] | 🌊 AbyssBook: Next-Generation DEX Infrastructure
<a></a>
<a></a>
<a></a>
🚀 Revolutionary Performance
AbyssBook represents a quantum leap in DEX infrastructure, achieving performance metrics previously thought impossible in decentralized systems:
| Metric | AbyssBook | Traditional DEX | CEX |
|--------|-----------|----------------|-----|
| Order Latency | 0.3μs | 500ms | 50μs |
| Throughput | 1M+ orders/sec | 5K orders/sec | 100K orders/sec |
| Price Levels | Unlimited | Limited | Limited |
| Slippage | Near-Zero | High | Low |
🔥 Key Innovations
1. Hyper-Optimized Architecture
<ul>
<li><strong>Sharded Orderbook</strong>: Parallel processing with price-based sharding</li>
<li><strong>SIMD Acceleration</strong>: Vectorized operations for bulk order processing</li>
<li><strong>Zero-Copy Design</strong>: Direct memory access without redundant copying</li>
<li><strong>Cache Optimization</strong>: Cache-aligned data structures and prefetching</li>
</ul>
2. Advanced Order Types
```zig
// Time-Weighted Average Price (TWAP)
try book.placeTWAPOrder(
.Buy, price, total_amount,
num_intervals, interval_seconds
);
// Trailing Stop with Dynamic Adjustment
try book.placeTrailingStopOrder(
.Sell, price, amount,
trailing_distance
);
// Peg Orders with Multiple Reference Points
try book.placePegOrder(
.Buy, amount, .BestBid,
offset, limit_price
);
```
3. Performance Monitoring
<ul>
<li>Real-time SIMD utilization tracking</li>
<li>Cache hit rate optimization</li>
<li>Latency percentile analysis</li>
<li>Throughput metrics</li>
</ul>
💫 Technical Advantages
1. Memory Optimization
<ul>
<li>Cache-line aligned structures</li>
<li>Prefetching for predictive loading</li>
<li>Efficient memory pooling</li>
<li>Zero-allocation hot paths</li>
</ul>
2. Parallel Processing
<code>zig
// Vectorized batch processing
const VECTOR_WIDTH = 8;
const PriceVector = @Vector(VECTOR_WIDTH, u64);
const matched = price_vec >= amount_vec;</code>
3. Market Making Features
<ul>
<li>Sub-tick spreads</li>
<li>Ultra-low latency updates</li>
<li>Bulk order modifications</li>
<li>Advanced order types</li>
</ul>
🔋 Performance Metrics
Latency Profile
<ul>
<li>P50: 0.3μs</li>
<li>P95: 0.5μs</li>
<li>P99: 0.8μs</li>
<li>P99.9: 1.2μs</li>
</ul>
Throughput Characteristics
<ul>
<li>Sustained: 1M+ orders/second</li>
<li>Burst: 2M+ orders/second</li>
<li>Match Rate: 500K+ matches/second</li>
<li>Settlement: 200K+ settlements/second</li>
</ul>
🛠 Integration Example
```zig
// Initialize high-performance orderbook
var book = try ShardedOrderbook.init(
allocator,
32 // shard count
);
// Place order with automatic price-time priority
try book.placeOrder(
.Buy, // side
1000, // price
10, // amount
order_id, // unique ID
);
// Execute market order with optimal matching
const result = try book.executeMarketOrder(
.Sell, // side
5 // amount
);
```
🔮 Roadmap
Our development roadmap is continuously evolving based on community feedback and market needs. Here's our current focus:
Current Focus
<ul>
<li>Performance optimization for high-frequency trading</li>
<li>Enhanced security measures and formal verification</li>
<li>Expanded API for easier integration</li>
<li>Comprehensive documentation and examples</li>
</ul>
Short-term Goals (Next 3-6 months)
<ul>
<li>Support for more complex order types</li>
<li>Improved analytics and monitoring tools</li>
<li>Enhanced testing infrastructure</li>
<li>Community contribution framework</li>
</ul>
Long-term Vision
<ul>
<li>Cross-chain integration capabilities</li>
<li>Advanced market making features</li>
<li>MEV protection mechanisms</li>
<li>Machine learning integration for predictive analytics</li>
</ul>
<blockquote>
Note: This roadmap is subject to change based on community feedback and market developments. For the most up-to-date information, please check our GitHub issues and discussions.
</blockquote>
🤝 Contributing
We welcome contributions in:
- Performance optimizations
- New order types
- Testing infrastructure
- Documentation
📚 Documentation
Detailed documentation available at:
- <a>Technical Architecture</a>
- <a>Integration Guide</a>
- <a>Performance Tuning</a>
- <a>API Reference</a>
🔒 Security
<ul>
<li>Formal verification of core components</li>
<li>Regular security audits</li>
<li>Comprehensive test coverage</li>
<li>Automated fuzzing</li>
</ul>
📈 Benchmarks
Run the comprehensive benchmark suite:
<code>bash
zig build bench</code>
This will execute tests across:
- Order placement/cancellation
- Market order execution
- Bulk operations
- Advanced order types
- Settlement processing
🧪 Testing
Unit Tests
Run the unit test suite:
<code>bash
zig build test</code>
End-to-End Tests
Run comprehensive end-to-end tests that simulate real-world trading scenarios:
<code>bash
zig build test-e2e</code>
All Tests
Run both unit and end-to-end tests:
<code>bash
zig build test-all</code>
Detailed documentation on the e2e tests is available at <a>E2E Tests Documentation</a>.
📄 License
AbyssBook is licensed under the Apache License 2.0 - see the <a>LICENSE</a> file for details. | [] |
https://avatars.githubusercontent.com/u/92009321?v=4 | chsim | basilysf1709/chsim | 2024-08-14T19:24:11Z | Consistent Hashing Ring Simulator made using raylib | main | 0 | 10 | 0 | 10 | https://api.github.com/repos/basilysf1709/chsim/tags | MIT | [
"raylib",
"zig"
] | 14 | false | 2025-01-27T22:15:39Z | true | false | unknown | github | [] | Consistent Hashing Simulator (chsim)
This project is a simulation of consistent hashing using Zig and Raylib. The application visualizes how a hash ring distributes nodes and routes requests to these nodes based on hash values. It demonstrates the addition and removal of nodes in the ring and shows how requests are routed.
https://github.com/user-attachments/assets/5771304e-3829-4fec-8e63-b2b97a8afa6c
Prerequisites
To build and run this project, you'll need:
<ul>
<li><strong>Zig</strong>: The Zig programming language. You can download it from <a>the official Zig website</a>.</li>
<li><strong>Raylib</strong>: A C library for creating games and multimedia applications. You need to have Raylib installed and properly set up for Zig. You can find the library <a>here</a>.</li>
</ul>
Building the Project
<ol>
<li><strong>Clone the Repository:</strong></li>
</ol>
<code>sh
git clone https://github.com/basilysf1709/chsim.git
cd https://github.com/basilysf1709/chsim.git</code>
<ol>
<li><strong>Install Raylib:</strong></li>
</ol>
Follow the instructions on the <a>Raylib installation page</a>. Ensure that <code>raylib.h</code> is accessible for your Zig build.
<ol>
<li><strong>Build & Run the Project:</strong></li>
</ol>
The project uses Zig’s build system. To build the application, run:
<code>sh
zig build run</code>
Usage
Once the application is running, you can interact with the simulation using the following controls:
<ul>
<li><strong>Press 'A'</strong>: Add a new virtual node to the hash ring.</li>
<li><strong>Press 'D'</strong>: Remove a virtual node from the hash ring.</li>
<li><strong>Press SPACE</strong>: Generate a request with a random key and visualize its routing to the appropriate node.</li>
</ul>
Application Overview
Data Structures
<ul>
<li><strong><code>VirtualNode</code></strong>: Represents a virtual node in the hash ring with properties like <code>id</code>, <code>parent_id</code>, <code>position</code>, <code>name</code>, and <code>ip</code>.</li>
<li><strong><code>HashRing</code></strong>: Manages the collection of virtual nodes and provides functionality to add, remove, and find nodes. It also sorts the nodes by their position on the ring.</li>
</ul>
Functions
<ul>
<li><strong><code>HashRing.init</code></strong>: Initializes the hash ring with an allocator and a specified number of virtual nodes per node.</li>
<li><strong><code>HashRing.addNode</code></strong>: Adds a new node to the hash ring and sorts the nodes.</li>
<li><strong><code>HashRing.removeNode</code></strong>: Removes nodes from the hash ring if the number exceeds the specified limit.</li>
<li><strong><code>HashRing.findNode</code></strong>: Finds the appropriate node for a given key based on its hash value.</li>
<li><strong><code>HashRing.hash</code></strong>: Computes a hash value for a given key.</li>
</ul>
Visualization
<ul>
<li><strong>Nodes</strong>: Displayed as purple circles on a ring. Their positions on the ring are determined by their hash values.</li>
<li><strong>Requests</strong>: Represented as red circles on the ring. The path from the request to the target node is visualized with a red arc.</li>
</ul>
Contributing
Feel free to contribute to this project by submitting issues, improvements, or pull requests. Your feedback and suggestions are welcome! Any kinds of contributions are welcome
License
This project is licensed under the MIT License. See the <a>LICENSE</a> file for details. | [] |
https://avatars.githubusercontent.com/u/66679118?v=4 | reticulum-zig | ion232/reticulum-zig | 2024-12-09T12:35:44Z | An implementation of Reticulum in Zig for operating systems and embedded devices | main | 0 | 10 | 1 | 10 | https://api.github.com/repos/ion232/reticulum-zig/tags | Apache-2.0 | [
"microzig",
"reticulum",
"zig"
] | 163 | false | 2025-01-28T07:58:18Z | true | true | 0.13.0 | github | [] | Overview
An implementation of <a>Reticulum</a> in <a>Zig</a> targeting operating systems and embedded devices.
Roadmap
<ul>
<li>Implement core transport.</li>
<li>Test core transport.</li>
<li>Implement a transport node pico build.</li>
<li>Test transport node pico build.</li>
<li>Implement app.</li>
<li>Test app.</li>
</ul>
Structure
App
<ul>
<li><code>app/</code> is the classic Reticulum app for standard operating systems.</li>
<li>Currently this is fairly empty as I work on the core functionality.</li>
</ul>
Core
<ul>
<li><code>core/</code> is the core functionality of Reticulum.</li>
<li>Provides the means to setup nodes and their interfaces without coupling to operating system calls.</li>
<li>Built as a module for use in embedded and operating systems.</li>
<li>The crypto implementation currently leverages std.crypto from the zig std library.</li>
<li>Eventually I will provide an option to use OpenSSL.</li>
</ul>
Hardware
<ul>
<li><code>hardware/</code> stores image setups for embedded devices that users can build with one command.</li>
<li>Makes use of <a>microzig</a> as a submodule for targeting embedded devices.</li>
<li>Currently there is a very simple proof of concept for the pico.</li>
<li>It makes an identity, endpoint and announce packet and sends it over serial.</li>
<li>The image can be built by running <code>zig build -Doptimize=ReleaseSafe pico</code> from <code>hardware</code>.</li>
<li>Note that the upstream USB CBC code is known to be buggy.</li>
</ul>
Test
<ul>
<li><code>test/</code> stores integration tests for core.</li>
<li>Eventually these will be done via deterministic simulation.</li>
<li>This will provide strong assurances on behaviour and make debugging much simpler. </li>
</ul>
Goals
<ul>
<li>Parity to reference implementation in core behaviour.</li>
<li>Cross-platform app for running on operating systems.</li>
<li>Providing one-line image builds of Reticulum for embedded devices.</li>
<li>Option of using OpenSSL for crypto.</li>
<li>Determinstic simulation testing.</li>
<li>Comprehensive integration tests.</li>
</ul>
Anti-goals
<ul>
<li>Exact parity to reference implementation in terminology/structure.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/193787365?v=4 | zindexer | openSVM/zindexer | 2025-01-28T01:25:04Z | solana indexer for clickhouse in zig | main | 4 | 10 | 2 | 10 | https://api.github.com/repos/openSVM/zindexer/tags | NOASSERTION | [
"zig",
"zig-package",
"ziglana",
"ziglang"
] | 156 | false | 2025-04-03T23:28:14Z | true | true | 0.14.0 | github | [
{
"commit": "refs",
"name": "c-questdb-client",
"tar_url": "https://github.com/openSVM/c-questdb-client/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/openSVM/c-questdb-client"
}
] | ZIndexer - Multi-Network SVM Indexer
ZIndexer is a high-performance indexer for Solana Virtual Machine (SVM) networks, capable of subscribing to and indexing data from multiple networks simultaneously.
Features
<ul>
<li><strong>Multi-Network Support</strong>: Index multiple SVM networks (mainnet, devnet, testnet, localnet) simultaneously</li>
<li><strong>Comprehensive Indexing</strong>:</li>
<li>Automated Market Makers (AMMs)</li>
<li>Metaplex NFTs and marketplaces</li>
<li>Token transfers and balances</li>
<li>Account balance changes</li>
<li>Transactions and instructions</li>
<li>Blocks and slots</li>
<li>Account activity</li>
<li><strong>Real-time and Historical Modes</strong>: Choose between real-time indexing or historical backfilling</li>
<li><strong>Database Integration</strong>: High-performance storage and querying of indexed data with support for ClickHouse and QuestDB</li>
<li><strong>Interactive TUI</strong>: Monitor indexing progress across all networks in real-time</li>
</ul>
Requirements
<ul>
<li>Zig 0.14.0 or later</li>
<li>ClickHouse server or QuestDB server</li>
<li>Internet connection to access SVM networks</li>
</ul>
Building
<code>bash
zig build</code>
Configuration
The indexer uses two configuration files:
<ul>
<li><code>src/rpc_nodes.json</code>: HTTP RPC endpoints for each network</li>
<li><code>src/ws_nodes.json</code>: WebSocket endpoints for each network</li>
</ul>
You can customize these files to add or remove networks, or to use different RPC providers.
Usage
```bash
Run in real-time mode (default)
./zig-out/bin/zindexer
Run in historical mode
./zig-out/bin/zindexer --mode historical
Customize ClickHouse connection
./zig-out/bin/zindexer --database-type clickhouse --database-url localhost:9000 --database-user default --database-password "" --database-name solana
Use QuestDB instead
./zig-out/bin/zindexer --database-type questdb --database-url localhost:9000 --database-user admin --database-password "quest" --database-name solana
Show help
./zig-out/bin/zindexer --help
```
Command Line Options
<ul>
<li><code>-m, --mode <mode></code>: Indexer mode (historical or realtime)</li>
<li><code>-r, --rpc-nodes <file></code>: RPC nodes configuration file</li>
<li><code>-w, --ws-nodes <file></code>: WebSocket nodes configuration file</li>
<li><code>-t, --database-type <type></code>: Database type (clickhouse or questdb)</li>
<li><code>-c, --database-url <url></code>: Database server URL</li>
<li><code>-u, --database-user <user></code>: Database username</li>
<li><code>-p, --database-password <pass></code>: Database password</li>
<li><code>-d, --database-name <db></code>: Database name</li>
<li><code>-b, --batch-size <size></code>: Batch size for historical indexing</li>
<li><code>--max-retries <count></code>: Maximum retry attempts</li>
<li><code>--retry-delay <ms></code>: Delay between retries in milliseconds</li>
</ul>
Legacy ClickHouse Options (for backward compatibility)
<ul>
<li><code>--clickhouse-url <url></code>: ClickHouse server URL</li>
<li><code>--clickhouse-user <user></code>: ClickHouse username</li>
<li><code>--clickhouse-password <pass></code>: ClickHouse password</li>
<li><code>--clickhouse-database <db></code>: ClickHouse database name</li>
</ul>
QuestDB Options
<ul>
<li><code>--questdb-url <url></code>: QuestDB server URL</li>
<li><code>--questdb-user <user></code>: QuestDB username</li>
<li><code>--questdb-password <pass></code>: QuestDB password</li>
<li><code>--questdb-database <db></code>: QuestDB database name</li>
<li><code>-h, --help</code>: Show help message</li>
</ul>
Schema Setup
The schema can be automatically applied to your database instance using the included script:
For ClickHouse
<code>bash
DB_TYPE=clickhouse CLICKHOUSE_URL="http://localhost:8123" ./scripts/apply_schema.sh</code>
For QuestDB
<code>bash
DB_TYPE=questdb QUESTDB_URL="http://localhost:9000" ./scripts/apply_schema.sh</code>
Architecture
ZIndexer is built with a modular architecture:
<ul>
<li><strong>Core Indexer</strong>: Manages connections to multiple networks and coordinates indexing</li>
<li><strong>RPC Client</strong>: Handles communication with SVM networks via HTTP and WebSocket</li>
<li><strong>Database Abstraction Layer</strong>: Provides a common interface for different database backends</li>
<li><strong>ClickHouse Client</strong>: Manages data storage and retrieval in ClickHouse</li>
<li><strong>QuestDB Client</strong>: Manages data storage and retrieval in QuestDB</li>
<li><strong>Indexing Modules</strong>:</li>
<li>Transaction Indexer: Processes transaction data</li>
<li>Instruction Indexer: Processes instruction data</li>
<li>Account Indexer: Tracks account changes</li>
<li>Token Indexer: Tracks token transfers and balances</li>
<li>DeFi Indexer: Tracks AMM and DeFi protocol activity</li>
<li>NFT Indexer: Tracks NFT mints, sales, and marketplace activity</li>
<li>Security Indexer: Monitors for suspicious activity</li>
</ul>
Database Schema
ZIndexer creates several tables in ClickHouse:
<ul>
<li><code>transactions</code>: Basic transaction data</li>
<li><code>instructions</code>: Instruction data with program IDs</li>
<li><code>accounts</code>: Account state changes</li>
<li><code>account_activity</code>: Account usage statistics</li>
<li><code>token_transfers</code>: Token transfer events</li>
<li><code>token_accounts</code>: Token account balances</li>
<li><code>token_holders</code>: Token holder information</li>
<li><code>nft_mints</code>: NFT mint events</li>
<li><code>nft_sales</code>: NFT sale events</li>
<li><code>pool_swaps</code>: AMM swap events</li>
<li><code>liquidity_pools</code>: AMM pool information</li>
</ul>
Continuous Integration & Deployment
ZIndexer uses GitHub Actions for CI/CD:
<ul>
<li><strong>CI Workflow</strong>: Automatically builds and tests the code on Ubuntu and macOS</li>
<li><strong>Lint Workflow</strong>: Checks code formatting using <code>zig fmt</code></li>
<li><strong>Release Workflow</strong>: Creates binary releases when a new tag is pushed</li>
</ul>
Status badges:
License
<a>MIT License</a> | [] |
https://avatars.githubusercontent.com/u/137664746?v=4 | zeon | n0thhhing/zeon | 2024-12-06T16:40:04Z | ARM/ARM64 Neon intrinsics implemented in zig | main | 0 | 9 | 0 | 9 | https://api.github.com/repos/n0thhhing/zeon/tags | MIT | [
"arm",
"arm64",
"assembly",
"implementation",
"inline-assembly",
"intrinsics",
"llvm",
"neon",
"pure-zig",
"simd",
"vectors",
"zig",
"ziglang"
] | 457 | false | 2025-03-26T06:23:18Z | true | true | unknown | github | [] | Zeon
ARM/ARM64 Neon intrinsics implemented in pure zig as well as in assembly!
Overview
Zeon aims to provide high-performance <code>Neon</code> intrinsics for <code>ARM</code> and <code>ARM64</code> architectures, implemented in both pure Zig and inline assembly. This project prioritizes portability, performance, and flexibility, ensuring compatibility across various environments.
Status
🚧 This project is under active development(522/3803 implemented). Contributions and feedback are welcome!
Roadmap
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Complete inline assembly/LLVM builtin implementations.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Write thorough tests for all functions to ensure correctness.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Refactor into multiple files.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Eliminate repetitive patterns to improve maintainability.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Implement fallbacks for non-ARM architectures.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Instruction Stripping e.g, Functions like <code>vget_lane_f64</code> should compile down to nothing more than accessing the appropriate register (e.g., s0 for vec in v0). Currently, we are explicitly inserting instructions, which prevents the compiler from optimizing them away when not needed.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Add support for Big Endian arm/aarch64, and add tests for it.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> For Vector Load intrinsics, dont assume the input length is the exact length of the output vector.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Test against C/C++ implementation.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Add a better way to switch between implementations(like assembly, builtins and the fallback).
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Use the fallback instead of assembly implementation when not in release.
Notes
<ul>
<li>When using <code>vld1*</code> on non-ARM architectures(or if use_asm and use_builtins is off), it assumes the underlying type fits the size of the vector.</li>
<li>Some intrinsics wont have inline assembly because the fallback implementation is either faster or the same as the assembly implementation. If the target function does not use inline assembly, then it wont be optimized to the target neon intrinsic unless your in <code>ReleaseFast</code>.</li>
</ul>
Getting Started
Requirements
To test and simulate ARM/ARM64 environments, <code>QEMU user mode</code> is required. Make sure QEMU is properly installed and configured before running tests. You'll also need <code>Make</code> for build and test automation.
For usage examples, see <a>examples</a>.
Installation and Usage
<ol>
<li>
Clone the repository:
<code>bash
git clone https://github.com/n0thhhing/zeon
cd zeon</code>
</li>
<li>
Run tests:
<code>bash
make test</code>
</li>
<li>
Run examples:
<code>bash
make examples</code>
</li>
</ol>
License
This project is licensed under the <code>MIT</code> License. See the <a>LICENSE</a> file for more information.
Resources
<ul>
<li><a>rust-lang</a>: Useful for function tests and reference.</li>
<li><a>official docs</a>: Official reference for ARM intrinsics and assembly.</li>
<li><a>godbolt</a>: Handy tool for examining and debugging assembly code.</li>
<li><a>LLVM Language Reference Manual</a> Helpful for using inline assembly.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/7820420?v=4 | zig-pico-cmake | flyfish30/zig-pico-cmake | 2025-01-19T12:50:07Z | A pico_sdk zig package that build zig projects by use the Raspberry PI Pico SDK | main | 0 | 9 | 1 | 9 | https://api.github.com/repos/flyfish30/zig-pico-cmake/tags | MIT | [
"pico-sdk",
"zig",
"zig-package"
] | 45 | true | 2025-03-09T05:23:07Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/179981696?v=4 | clickhouse-zig | ziglana/clickhouse-zig | 2024-10-31T10:29:33Z | blazigly fast Clickhouse client ⚡️ | main | 0 | 9 | 0 | 9 | https://api.github.com/repos/ziglana/clickhouse-zig/tags | Unlicense | [
"blazigly",
"clickhouse",
"clickstream",
"time-series",
"zig",
"ziglang"
] | 57 | true | 2025-03-30T00:53:17Z | true | true | unknown | github | [] | clickhouse-zig
clickhouse client for zig
Features
<ul>
<li>Native ClickHouse protocol implementation</li>
<li>High performance with zero allocations in hot paths</li>
<li>Support for complex ClickHouse types</li>
<li>Connection pooling</li>
<li>Async query support</li>
<li>Compression (LZ4, ZSTD)</li>
<li>Bulk insert optimization</li>
<li>Streaming support for large result sets</li>
<li>Comprehensive error handling</li>
</ul>
Running Examples
The project includes several examples demonstrating different features. To run a specific example:
```bash
Build and run an example
zig build run-$EXAMPLE_NAME
Available examples:
zig build run-basic_connection # Basic connection and query
zig build run-bulk_insert # Bulk data insertion
zig build run-streaming # Streaming large result sets
zig build run-compression # Data compression
zig build run-transaction # Transaction handling
zig build run-async_query # Async query execution
zig build run-materialized_view # Materialized view creation
zig build run-dictionary # Dictionary operations
zig build run-distributed_table # Distributed table setup
zig build run-query_profiling # Query profiling
zig build run-mutations # Data mutations
zig build run-sampling # Data sampling
zig build run-complex_types # Complex data types
zig build run-pool_config # Connection pool configuration
zig build run-query_control # Query monitoring and control
```
Each example demonstrates specific features and includes detailed comments explaining the functionality. | [] |
https://avatars.githubusercontent.com/u/113083639?v=4 | zopengl | zig-gamedev/zopengl | 2024-11-03T23:34:16Z | OpenGL loader and bindings for Zig. | main | 3 | 9 | 11 | 9 | https://api.github.com/repos/zig-gamedev/zopengl/tags | MIT | [
"gamedev",
"opengl",
"opengl-bindings",
"opengl-loader",
"opengl-wrapper",
"opengles",
"zig"
] | 208 | false | 2025-05-13T21:36:50Z | true | true | unknown | github | [] | <a>zopengl</a>
OpenGL loader, bindings and optional wrapper for Zig.
Supports:
* OpenGL Core Profile up to version 4.3
* OpenGL ES up to version 2.0
Getting started
Example <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const exe = b.addExecutable(.{ ... });
<code>const zopengl = b.dependency("zopengl", .{});
exe.root_module.addImport("zopengl", zopengl.module("root"));
</code>
}
```
Now in your code you may import and use <code>zopengl</code>:
```zig
const zopengl = @import("zopengl");
pub fn main() !void {
// Create window and OpenGL context here... (you can use our <code>zsdl</code> or <code>zglfw</code> libs for this)
<code>try zopengl.loadCoreProfile(getProcAddress, 4, 0);
const gl = zopengl.bindings; // or zopengl.wrapper (experimental)
gl.clearBufferfv(gl.COLOR, 0, &[_]f32{ 0.2, 0.4, 0.8, 1.0 });
</code>
}
fn getProcAddress(name: [:0]const u8) callconv(.c) ?*const anyopaque {
// Load GL function pointer here
// You could use <code>zsdl.gl.getProcAddress() or</code>zglfw.getProcAddress()`
}
``` | [
"https://github.com/Aryvyo/zigClipboard",
"https://github.com/jrachele/zsynth",
"https://github.com/zig-gamedev/zig-gamedev"
] |
https://avatars.githubusercontent.com/u/132974257?v=4 | zephyrus | optimism-java/zephyrus | 2024-09-05T03:34:14Z | Ethereum consensus client in Zig | main | 13 | 9 | 2 | 9 | https://api.github.com/repos/optimism-java/zephyrus/tags | MIT | [
"eth2",
"eth2-beacon-chain",
"eth2-clients",
"ethereum",
"zig",
"ziglang"
] | 349 | false | 2025-03-31T02:10:51Z | true | true | unknown | github | [] | zephyrus
This repo is development with zig, zig is a coding language for more <a>info</a> for basic coding <a>guide</a>
The current version being used in development is <code>0.14.0-dev.2079+ba2d00663</code>. You may use <a><code>zigup</code></a> to download and use this specific version.
Build
<code>bash
git clone --recursive https://github.com/optimism-java/zephyrus.git
cd zephyrus
git submodule update --init --recursive
cd bls
make -f Makefile.onelib ETH_CFLAGS=-DBLS_ETH LIB_DIR=lib
zig build</code>
Test
first you should build bls as described above
when you run <code>zig build test</code>, the spec tests are not run by default.
if you want to run spec tests, you need to download the test vectors and add <code>-Dspec=true</code> to the zig build command.
```bash
download test vectors
make deps_test
add -Dspec=true to run spec tests
zig build test -Dspec=true
``` | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | lz4 | allyourcodebase/lz4 | 2024-08-15T11:54:47Z | lz4 ported to the zig build system | master | 0 | 9 | 1 | 9 | https://api.github.com/repos/allyourcodebase/lz4/tags | MIT | [
"zig",
"zig-package"
] | 12 | false | 2025-05-03T17:34:43Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "lz4",
"tar_url": "https://github.com/lz4/lz4/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/lz4/lz4"
}
] | <a></a>
lz4
This is <a>lz4</a>, packaged for <a>Zig</a>.
Installation
First, update your <code>build.zig.zon</code>:
```
Initialize a <code>zig build</code> project if you haven't already
zig init
zig fetch --save git+https://github.com/allyourcodebase/lz4.git#1.10.0-5
```
You can then import <code>lz4</code> in your <code>build.zig</code> with:
<code>zig
const lz4_dependency = b.dependency("lz4", .{
.target = target,
.optimize = optimize,
});
your_exe.linkLibrary(lz4_dependency.artifact("lz4"));</code> | [
"https://github.com/Scythe-Technology/Zune",
"https://github.com/allyourcodebase/lz4",
"https://github.com/mgord9518/squashfuse-zig",
"https://github.com/vrischmann/zig-cassandra"
] |
https://avatars.githubusercontent.com/u/98805?v=4 | skia-zig | basdp/skia-zig | 2024-10-08T13:53:02Z | Zig bindings for the Skia 2D Graphics Library | main | 2 | 9 | 1 | 9 | https://api.github.com/repos/basdp/skia-zig/tags | MIT | [
"skia",
"zig",
"zig-package"
] | 8,364 | false | 2025-05-14T14:00:53Z | true | true | unknown | github | [] |
Skia Zig Bindings
<a></a>
Zig bindings for the famous <a>Skia 2D Graphics Library</a>.
Overview
This repository provides Zig bindings to the Skia C API. It builds Skia for multiple platforms and exposes the raw C headers to be used directly in Zig projects. <strong>No wrappers</strong> are provided—this is a low-level binding to the C layer only.
This repository is using the <a>Skia fork from the Mono project</a>, as they actively maintain a C wrapper for Skia (which is C++ only). We need C wrappers to bridge to Zig.
Features
<ul>
<li>Pre-built Skia binaries</li>
<li>Exposes the raw Skia C API headers to Zig</li>
<li>Easy to import and use directly from Zig code without any dependencies or extra build steps</li>
</ul>
Project status
<em>Warning</em>: This wrapper is in a very early stage and is <em>not</em> stable for production use. Also not all features and plaforms are implemented.
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Skia build for Windows x86_64
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Skia build for macOS x86_64
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Skia build for macOS Apple Silicon
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Skia build for Linux
Getting Started
Usage
<ol>
<li>
Import the <code>skia-zig</code> package into your project:
<code>bash
zig fetch --save https://github.com/basdp/skia-zig/releases/latest/download/skia-zig-package.zip</code>
</li>
<li>
Add the dependency to your <code>build.zig</code> file, somewhere below <code>b.addExecutable(...)</code> or whatever you are building:
</li>
</ol>
<code>zig
const skia_dep = b.dependency("skia-zig", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("skia-zig", skia_dep.module("skia-zig"));</code>
<ol>
<li>You can now import <code>skia-zig</code> in your Zig code:
```zig
const skia = @import("skia-zig");</li>
</ol>
pub fn main() !void {
const gr_glinterface = skia.gr_glinterface_create_native_interface();
defer skia.gr_glinterface_unref(gr_glinterface);
const gr_context = skia.gr_direct_context_make_gl(gr_glinterface) orelse return error.SkiaCreateContextFailed;
defer skia.gr_direct_context_free_gpu_resources(gr_context);
<code>const gl_info = skia.gr_gl_framebufferinfo_t{
.fFBOID = 0,
.fFormat = gl.RGBA8,
};
const samples: c_int = ... // get from GL or something
const stencil_bits: c_int = ... // get from GL or something
const backendRenderTarget = skia.gr_backendrendertarget_new_gl(640, 480, samples, stencil_bits, &gl_info) orelse return error.SkiaCreateRenderTargetFailed;
const color_type = skia.RGBA_8888_SK_COLORTYPE;
const colorspace = null;
const props = null;
const surface = skia.sk_surface_new_backend_render_target(@ptrCast(gr_context), backendRenderTarget, skia.BOTTOM_LEFT_GR_SURFACE_ORIGIN, color_type, colorspace, props) orelse return error.SkiaCreateSurfaceFailed;
defer skia.sk_surface_unref(surface);
const canvas = skia.sk_surface_get_canvas(surface) orelse unreachable;
while (/* app is running */) {
skia.sk_canvas_clear(canvas, 0xffffffff);
const fill = skia.sk_paint_new() orelse return error.SkiaCreatePaintFailed;
defer skia.sk_paint_delete(fill);
skia.sk_paint_set_color(fill, 0xff0000ff);
skia.sk_canvas_draw_paint(canvas, fill);
// Your Skia drawing here
skia.sk_canvas_flush(canvas);
}
</code>
}
```
Setting your ABI to MSVC on Windows
Skia requires the <code>msvc</code> ABI on Windows, so make sure you target that ABI. There are two possible
options to do so (only one of these is necessary):
<ol>
<li>
Set the target from the command line while building:
<code>bash
zig build -Dtarget=x86_64-windows-msvc</code>
</li>
<li>
Or better yet; replace the <code>const target = ...</code> line in your <code>build.zig</code> file:
<code>zig
const target = b.standardTargetOptions(.{ .default_target = .{
.abi = if (b.graph.host.result.os.tag == .windows) .msvc else null,
} });</code>
</li>
</ol> | [] |
https://avatars.githubusercontent.com/u/187213054?v=4 | image | refilelabs/image | 2024-11-05T23:38:39Z | Image layer repository holding all image tooling. | main | 2 | 8 | 0 | 8 | https://api.github.com/repos/refilelabs/image/tags | - | [
"image-processing",
"rust",
"wasm",
"zig"
] | 237 | false | 2025-03-12T23:28:26Z | false | false | unknown | github | [] | refilelabs/image
<a></a>
<a></a>
<a></a>
The <code>refilelabs/image</code> repository provides core utilities for image manipulation within the <a><strong>re;file labs</strong></a> platform. It offers robust, high-performance image processing features powered by WebAssembly (WASM) for secure, browser-based operations.
Features
<ul>
<li><strong>Image Conversion</strong>: Convert images between various formats (e.g., JPEG, PNG, WebP).</li>
<li><strong>Image Editing</strong>: Resize, crop, rotate, and flip images with ease. (Coming soon)</li>
<li><strong>Image Compression</strong>: Compress images to reduce file size while maintaining quality.</li>
<li><strong>Image Viewing</strong>: View images in a responsive, interactive viewer.</li>
<li><strong>Metadata Editing</strong>: View and edit metadata for supported image formats.</li>
<li><strong>WebAssembly-Powered</strong>: All operations run securely in the browser, leveraging WASM for speed and privacy.</li>
</ul>
Getting Started
Prerequisites
<ul>
<li><strong>bun</strong>: The package manager and runtime used within the <strong>re;file labs</strong> ecosystem.</li>
<li><strong>Rust</strong>: For compiling WebAssembly components.</li>
<li><strong>wasm-pack</strong>: For building and packaging WebAssembly modules.</li>
</ul>
Installation
<ol>
<li>
Clone the repository:
<code>bash
git clone https://github.com/refilelabs/image.git
cd image</code>
</li>
<li>
Install dependencies (also builds WebAssembly modules):
</li>
</ol>
<strong>Using Bun</strong>:
<code>bash
bun i</code>
<strong>Using npm</strong>:
<code>bash
npm install</code>
<strong>Using Yarn</strong>:
<code>bash
yarn install</code>
<strong>Using pnpm</strong>:
<code>bash
pnpm install</code>
<ol>
<li>Start the development server:</li>
</ol>
<strong>Using Bun</strong>:
<code>bash
bun dev</code>
<strong>Using npm</strong>:
<code>bash
npm run dev</code>
<strong>Using Yarn</strong>:
<code>bash
yarn dev</code>
<strong>Using pnpm</strong>:
<code>bash
pnpm dev</code>
Usage
Components
If you want to use the image utility components in your own project, either include this nuxt layer using the <a>extends feature</a>:
<code>ts
export default defineNuxtConfig({
extends: [
'github:refilelabs/image',
]
})</code>
Programmatic Usage
In case you want to use the actual wasm modules in your project, you can import them directly from the <a><code>@refilelabs/image</code></a> package.
Project Structure
<code>refilelabs/image
├── .playground/ # Temporary playground for testing
├── wasm/ # WebAssembly modules
├── components/ # Image processing components
├── composables/ # Shared Vue composables
├── workers/ # Web Workers for offloading compute-intensive tasks
└── tests/ # Unit tests</code>
License
This project is licensed under the MIT License. See the <a>LICENSE</a> file for details.
<a><strong>re;file labs</strong></a> — Your secure, private file utility suite. | [] |
https://avatars.githubusercontent.com/u/200686?v=4 | zigrdkafka | deckarep/zigrdkafka | 2024-09-13T20:01:06Z | This is librdkafka, hijacked and under the command and control of Zig, an easy Kafka client to tame your consumer and producer cluster. | main | 0 | 8 | 0 | 8 | https://api.github.com/repos/deckarep/zigrdkafka/tags | NOASSERTION | [
"api",
"client",
"consumer",
"distributed-systems",
"event-driven",
"kafka",
"librdkafka",
"producer",
"zig",
"ziglang"
] | 151 | false | 2024-11-30T19:56:44Z | true | true | 0.13.0 | github | [] | zigrdkafka
<em>All your codebase are belong to us.</em>
This is <code>librdkafka</code>, hijacked and under the command and control of Zig.
This project requires <code>Zig 0.13</code> and is developed currently on <code>macos-aarch64</code>.
Big Fat Caveat
I am building this Zig-flavored wrapper to librdkafka organically and as a
discovery project. Therefore, I'm skipping proper unit-testing for awhile as
the API is likely to change drastically. Additionally, I havn't yet put a lot
of thought into how I want to handle errors. Obviously, I will use Zig error-sets
but I need to figure out how to best map the librdkafka C error codes to the error-sets.
Sample Consumer
```zig
const std = @import("std");
const zrdk = @import("zigrdkafka");
pub fn main() !void {
// Create a fresh consumer configuration.
const conf = try zrdk.Conf.init();
try conf.set("bootstrap.servers", "localhost:9092");
try conf.set("group.id", "zig-cli-consumer");
// Create a new consumer.
const consumer = try zrdk.Consumer.init(conf);
defer consumer.deinit();
defer consumer.close();
// Define topics of interest to consume.
const topics = [_][]const u8{"topic.foo", "topic.bar"};
try consumer.subscribe(&topics);
while (true) {
const msg = consumer.poll(100);
defer msg.deinit();
<code>if (!msg.isOK()) {
std.log.warn("either message was empty or it had an error...", .{});
// Deal with it here.
continue;
}
// Log the message.
std.log.info("message => {s}\ntopic => {s}\npartition => {d}\noffset => {d}\n", .{
msg.payloadAsString(),
msg.topic().name(),
msg.partition(),
msg.offset(),
});
count += 1;
</code>
}
std.log.info("Consumer loop ended!", .{});
std.log.info("Yep, it's really that easy!", .{});
}
```
Currently Implemented
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Proper error-handling (not started) ⚠️
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Conf + TopicConf ✅
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Uuid ✅
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Topic ✅
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> TopicPartition ✅
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> TopicPartitionList (in-progress)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Headers collection (in-progress)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Message (in-progress)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Raw Consumer (in-progress, but works!)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Raw Producer (in-progress, but works!)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Full support for librdkafka callbacks (in-progress)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> logging callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> delivery report messages callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> rebalance callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> offset commits callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> stats callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> consume callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> background event callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> throttle callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> set socket callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> set connect callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> close socket callback
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> open callback
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> various others
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Admin client (not-started)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Variations on Consumers/Producers (such as high-level consumer) (not-started)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> etc. as there's a lot more to librdkafka than meets the eye just like Transformers!
Warning
<ul>
<li>While both the Consumer and Producer work, some things are still hard-coded as this lib is
currently in discovery phase.</li>
<li>⚠️⚠️ Unstable API ⚠️⚠️: This lib is under heavy active development and subject to heavy changes.</li>
<li>The api is far, from complete!</li>
<li>Use at your own risk, no warranty expressed or implied.</li>
<li>Until the API becomes more stable, I will not be worrying about unit-tests.</li>
</ul>
Contributions
<ul>
<li>This API is not intended to have 100% feature parity with the librdkafka C lib.<ul>
<li>One reason: Zig can provide a nicer experience over C so it should not be a 1 for 1 port.</li>
<li>If I don't use a feature, it may not get built out in this API so submit a PR!</li>
</ul>
</li>
</ul>
Getting up and running
```sh
1. Clone this repo and pull down any submodules.
git clone
git submodule update --init --recursive
2. Install deps for your operating system.
For MacOS
brew install openssl curl zlib zstd cyrus-sasl
3. Run cmake configuration for librdkafka
This generates a config.h header file.
cd lib/librdkafka
./configure
cd ../../
4. Build all examples projects.
zig build
5. Each of the binaries are now located in: zig-out/bin
Example:
# a. Prestep: Ensure your Kafka cluster is running.
# b. Navigate to the freshly built binaries.
cd zig-out/bin
# c. Run the producer in one window.
./producer
# d. Run the consumer in another window.
./consumer
```
Design Goals/Considerations
<ul>
<li>Provide a 1st class Zig-flavored wrapper around librdkafka</li>
<li>Consider auto-generation down the road, at least for some things.</li>
<li>Design choice: As it stands, all Zig structs are value-type and immutable, this may change for all or some structs.</li>
<li>The idea is that it makes the API even more user-friendly and all mutable state occurs in the librdkafka layer anyway.</li>
<li>Additionally, Zig/llvm often account for this and can often pass const value-types by reference anyway as an optimization.</li>
<li>All C ugliness should be hidden away</li>
<li>Zig namespacing more lightweight and less redundant. Example: <code>c.rd_kafka_conf_set</code> => <code>z.Conf.set</code> (something like this)</li>
<li>Only Zig style strings: <code>[]const u8</code> or null-terminated when required: <code>[:0]const u8</code></li>
<li>Utilize Zig-based struct methods where it makes sense.</li>
<li>No <code>[*c]</code> tags anywhere (in-progress), internal is ok.</li>
<li>C-based #defines, enums converted to Zig enums (not started)</li>
<li>C-based <code>new</code> or <code>create</code> => <code>init</code> for Zig.</li>
<li>C-based <code>_destroy()</code> => <code>.deinit()</code> for Zig.</li>
<li>Use of Zig-flavored callbacks so user doesn't need to declare fn with <code>callconv(.C)</code>.</li>
<li>librdkafka doesn't expose allocators the way Zig prefers, not sure if there is a way around this.</li>
</ul>
### Other implementations
* <a>Ruby</a> | [] |
https://avatars.githubusercontent.com/u/124217829?v=4 | zig-syslinfo | javiorfo/zig-syslinfo | 2024-12-03T15:06:25Z | Linux sysinfo Zig library | master | 0 | 8 | 2 | 8 | https://api.github.com/repos/javiorfo/zig-syslinfo/tags | MIT | [
"linux",
"sysinfo",
"zig",
"zig-package"
] | 42 | false | 2025-04-21T19:46:03Z | true | true | 0.13.0 | github | [] | zig-syslinfo
<em>Linux sysinfo Zig library</em>
Caveats
<ul>
<li>C libs dependencies: <code>asound</code>, <code>libnm</code>, <code>glib-2.0</code> </li>
<li>Required Zig version: <strong>0.13</strong></li>
<li>This library has been developed on and for Linux following open source philosophy.</li>
</ul>
Usage
```zig
const std = @import("std");
const syslinfo = @import("syslinfo");
pub fn main() !void {
// DISK
const disk = try syslinfo.disk.usage("/");
std.debug.print("DISK free {d}\n", .{disk.free});
std.debug.print("DISK blocks {d}\n", .{disk.blocks});
std.debug.print("DISK files {d}\n", .{disk.files});
std.debug.print("DISK files free {d}\n", .{disk.files_free});
std.debug.print("DISK perc used {d:.2}%\n", .{try disk.percentageUsed()});
<code>// CPU
const cpu = syslinfo.cpu;
const cpu_usage = try cpu.usage();
std.debug.print("CPU user {d}\n", .{cpu_usage.user});
std.debug.print("CPU nice {d}\n", .{cpu_usage.nice});
std.debug.print("CPU idle {d}\n", .{cpu_usage.idle});
std.debug.print("CPU system {d}\n", .{cpu_usage.system});
std.debug.print("CPU iowait {d}\n", .{cpu_usage.iowait});
const cpu_info = try cpu.info();
defer cpu_info.deinit();
std.debug.print("CPU vendor id {s}\n", .{cpu_info.vendor_id});
std.debug.print("CPU model {d}\n", .{cpu_info.model});
std.debug.print("CPU model name {s}\n", .{cpu_info.model_name});
std.debug.print("CPU microcode {s}\n", .{cpu_info.microcode});
std.debug.print("CPU cores {d}\n", .{cpu_info.cpu_cores});
std.debug.print("CPU family {d}\n", .{cpu_info.cpu_family});
std.debug.print("CPU cache size {s}\n", .{cpu_info.cache_size});
std.debug.print("CPU perc used {d:.2}%\n", .{try cpu.percentageUsed()});
// THERMAL
const thermal = syslinfo.thermal;
const thermal_info = try thermal.info();
std.debug.print("THERMAL zone0 {d}\n", .{thermal_info.zone0.?});
std.debug.print("THERMAL zone1 {d}\n", .{try thermal.getTemperatureFromZone(thermal.ZONE.one)});
std.debug.print("THERMAL zone2 {d}\n", .{try thermal.getTemperatureFromZoneId(2)});
// MEMORY
const memory = try syslinfo.memory.usage();
std.debug.print("MEM free {d}\n", .{memory.free});
std.debug.print("MEM total {d}\n", .{memory.total});
std.debug.print("MEM cached {d}\n", .{memory.cached});
std.debug.print("MEM buffers {d}\n", .{memory.buffers});
std.debug.print("MEM available {d}\n",.{ memory.available});
std.debug.print("MEM free swap {d}\n", .{memory.free_swap});
std.debug.print("MEM total swap {d}\n", .{memory.total_swap});
std.debug.print("MEM perc used {d:.2}%\n", .{try memory.percentageUsed()});
// VOLUME
const vol = try syslinfo.volume.state(.{}); // Receives a struct (default values are "default" and "Master")
std.debug.print("VOL card name {s}\n", .{vol.card_name});
std.debug.print("VOL volume {d}%\n", .{vol.volume});
std.debug.print("VOL minimum {d}\n", .{vol.min});
std.debug.print("VOL maximum {d}\n", .{vol.max});
std.debug.print("VOL is muted {b}\n", .{vol.muted});
// NETWORK
const net = try syslinfo.network.state();
std.debug.print("NET SSID {s}\n", .{net.?.SSID});
std.debug.print("NET SSID len {d}\n", .{net.?.SSID_len});
std.debug.print("NET IPv4 {s}\n", .{net.?.ipv4});
std.debug.print("NET IPv4 len {d}\n", .{net.?.ipv4_len});
std.debug.print("NET mask {d}\n", .{net.?.mask});
std.debug.print("NET signal strength {d}\n", .{net.?.signal_strength});
std.debug.print("NET connection speed {d}\n", .{net.?.connection_speed});
std.debug.print("NET connection type {d}\n", .{net.?.connection_type});
</code>
}
```
Installation
In your <code>build.zig.zon</code>:
<code>zig
.dependencies = .{
.syslinfo = .{
.url = "https://github.com/javiorfo/zig-syslinfo/archive/refs/heads/master.tar.gz",
// .hash = "hash suggested",
// the hash will be suggested by zig build
},
}</code>
In your <code>build.zig</code>:
```zig
const dep = b.dependency("syslinfo", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("syslinfo", dep.module("syslinfo"));
exe.linkLibC();
exe.linkSystemLibrary("asound");
exe.linkSystemLibrary("libnm");
exe.linkSystemLibrary("glib-2.0");
```
Donate
<ul>
<li><strong>Bitcoin</strong> <a>(QR)</a> <code>1GqdJ63RDPE4eJKujHi166FAyigvHu5R7v</code></li>
<li><a>Paypal</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/191039718?v=4 | fury | fury-lang/fury | 2025-01-11T14:10:55Z | Fury, a gradual, safe systems language | master | 10 | 8 | 0 | 8 | https://api.github.com/repos/fury-lang/fury/tags | MIT | [
"compiler",
"memory-management",
"programming-language",
"typechecker",
"zig"
] | 599 | false | 2025-05-05T15:07:52Z | true | true | 0.11.0 | github | [] | Fury, a gradual, safe systems language
Goals
<ul>
<li>Teachability | Learnability | Readability</li>
<li>Efficiency | Productivity</li>
<li>Systems and application programming</li>
</ul>
See a simple circular linked list example in fury,
```rs
struct Node {
data: i64
next: Node?
}
fun main() {
mut node3 = new Node(data: 3, next: none)
let node2 = new Node(data: 2, next: node3)
let node1 = new Node(data: 1, next: node2)
node3.next = node1
<code>mut curr: Node? = node2
let end = curr
// println(curr.data)
mut total = curr.data
while curr.next != end {
curr = curr.next
total -= curr.data
}
println(total)
</code>
}
```
Also see the <a>philosophy</a> for more info.
Status
The Fury project is still in its early days of development. While we have developed a compiler in tandem with designing the language, both should be considered experimental and pre-alpha in quality. Significant changes to both the language and the compiler should be expected.
Running the test suite
To run the Fury test suite, be sure you have <code>clang</code> installed.
<code>bash
zig build run -- <file-path> # codegen a output.c file
zig build gcc # emit executable using gcc
zig build exec # run executable
zig build coverage # run entire test suite</code>
The Fury compiler outputs C code, which you can then build with a C-compatible compiler. The test suite assumes <code>clang</code> is the compiler that is available. (Note for Windows users: Visual Studio can install 'clang' as an optional install)
The Fury language
For more information on the Fury language, check out <a>the Fury language documentation</a>
Roadmap
Our main goal with Fury is to build out an implementation of its initial design and to test it.
As we dogfood, we will likely change the design of the language where we see it doesn't meet the goals of the project.
We'll likely also work towards support in IDEs (using things like LSP) to make it easier to write larger Fury projects and get interactive feedback from the tools. | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | lua | allyourcodebase/lua | 2024-08-22T17:59:21Z | lua build system ported to Build.zig | main | 0 | 8 | 3 | 8 | https://api.github.com/repos/allyourcodebase/lua/tags | MIT | [
"zig",
"zig-package"
] | 19 | false | 2025-05-16T22:56:02Z | true | true | 0.14.0 | github | [
{
"commit": null,
"name": "lua",
"tar_url": null,
"type": "remote",
"url": "https://www.lua.org/ftp/lua-5.4.7.tar.gz"
}
] | Lua
5.4.7
Build Instructions
To build all targets run
<code>sh
zig build</code>
Build Artifacts
| Name | Artifact |
|:---------:| ------------------------- |
| "lua" | The main lua library |
| "lua_exe" | The lua interpreter |
| "luac" | The lua bytecode compiler |
Compile Options
| Name | Type | Description |
|:------------:| ---- | -------------------------- |
| release | bool | optimize for end users |
| shared | bool | build as shared library |
| use_readline | bool | readline support for linux |
Using in a zig project
To add to a zig project run:
<code>zig fetch --save https://github.com/allyourcodebase/lua/archive/refs/tags/5.4.7.tar.gz</code>
then add the following to your <code>build.zig</code>
<code>zig
const lua_dep = b.dependency("lua", .{
.target = target,
.release = optimize != .Debug,
});
const lua_lib = lua_dep.artifact(if (target.result.os.tag == .windows) "lua54" else "lua");</code> | [
"https://github.com/allyourcodebase/lua",
"https://github.com/lfcm64/z-tree-sitter"
] |
https://avatars.githubusercontent.com/u/126792083?v=4 | zigache | jaxron/zigache | 2024-09-10T10:17:45Z | A customizable cache library in Zig with multiple eviction policies. | main | 1 | 8 | 1 | 8 | https://api.github.com/repos/jaxron/zigache/tags | MIT | [
"zig",
"zig-lang",
"zig-library",
"zig-package",
"ziglang"
] | 1,176 | false | 2025-05-10T13:00:42Z | true | true | unknown | github | [] |
<a>
</a>
<a>
</a>
<a>
</a>
<a>
</a>
<em><b>Zigache</b> is an efficient caching library built in <a>Zig</a>, offering customizable cache eviction policies for various application needs.</em>
<blockquote>
<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span>
Zigache is <strong>not in active development</strong> but will be maintained. The library follows Zig version <code>0.14.0</code>.
</blockquote>
📚 Table of Contents
<ul>
<li><a>🚀 Features</a></li>
<li><a>⚡️ Quickstart</a></li>
<li><a>👀 Examples</a></li>
<li><a>⚙️ Configuration</a></li>
<li><a>📊 Benchmarks</a></li>
<li><a>📄 License</a></li>
<li><a>❓ FAQ</a></li>
</ul>
🚀 Features
Zigache offers a rich set of features to designed to meet various caching needs:
<ul>
<li><strong>Multiple Eviction Algorithms:</strong></li>
<li>W-TinyLFU | <a>TinyLFU: A Highly Efficient Cache Admission Policy</a></li>
<li>S3-FIFO | <a>FIFO queues are all you need for cache eviction</a></li>
<li>SIEVE | <a>SIEVE is Simpler than LRU: an Efficient Turn-Key Eviction Algorithm for Web Caches</a></li>
<li>LRU | Least Recently Used</li>
<li>FIFO | First-In-First-Out</li>
<li><strong>Extensive Configuration Options:</strong></li>
<li>Configurable cache size with pre-allocation for performance tuning</li>
<li>Ability to fine-tune cache policies (e.g., TinyLFU, S3FIFO)</li>
<li>Time-To-Live (TTL) support to expire cache entries</li>
<li>Thread safety and sharding settings for concurrent environments</li>
<li>Adjustable max load factor for the cache</li>
<li><strong>Heavy Testing and Benchmarking</strong> for <a>stability and performance</a> under various workloads</li>
</ul>
⚡️ Quickstart
To use Zigache in your project, follow these steps:
<ol>
<li>
Run this command in your project's root directory:
<code>sh
zig fetch --save git+https://github.com/jaxron/zigache.git</code>
</li>
<li>
In your <code>build.zig</code>, add:
```diff
pub fn build(b: *std.Build) void {
// Options
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>// Build
</code>
<ul>
<li>const zigache = b.dependency("zigache", .{</li>
<li>.target = target,</li>
<li>.optimize = optimize,</li>
<li>
}).module("zigache");
const exe = b.addExecutable(.{
.name = "your-project",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
+ exe.root_module.addImport("zigache", zigache);
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the program");
run_step.dependOn(&run_cmd.step);
}
```
</li>
</ul>
</li>
<li>
Now you can import and use Zigache in your code like this:
```zig
const std = @import("std");
const Cache = @import("zigache").Cache;
pub fn main() !void {
var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
<code>// Create a cache with string keys and values
var cache: Cache([]const u8, []const u8, .{}) = try .init(allocator, .{
.cache_size = 1,
.policy = .SIEVE,
});
defer cache.deinit();
// your code...
</code>
}
```
</li>
</ol>
<a>🔝 Back to top</a>
👀 Examples
Explore the usage scenarios in our examples directory:
<ul>
<li><a>01 | Key Types</a></li>
<li><a>02 | TTL Entries</a></li>
</ul>
To run an example:
<code>sh
zig build [example-id]
zig build 01</code>
<a>🔝 Back to top</a>
⚙️ Configuration
Zigache offers flexible configuration options to adjust the cache to your needs:
<code>zig
var cache: Cache([]const u8, []const u8, .{
.thread_safety = true, // Enable thread safety for multi-threaded environments
.ttl_enabled = true, // Enable Time-To-Live (TTL) functionality
.max_load_percentage = 60, // Set maximum load factor for the cache (60% occupancy)
}) = try .init(allocator, .{
.cache_size = 10000, // Maximum number of items the cache can store
.pool_size = 1000, // Pre-allocated nodes to optimize performance
.shard_count = 16, // Number of shards for concurrent access handling
.policy = .SIEVE, // Eviction policy in use
});</code>
<blockquote>
For more detailed information, refer to the <a>full documentation</a>.
</blockquote>
<a>🔝 Back to top</a>
📊 Benchmarks
This benchmark uses a <a>Zipfian distribution</a>, run on an Intel® Core™ i7-8700 CPU, using commit <code>7a12b1f</code> of this library.
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
These results are not conclusive, as performance depends on workload and environment. These benchmarks are comparing eviction policies within this library, and not comparisons with other languages or libraries. You can customize the benchmarks using various flags. For details, run <code>zig build -h</code>.
</blockquote>
Single Threaded (zipf 0.9, 10m keys)
## Benchmark Parameters
```sh
zig build bench -Doptimize=ReleaseFast
```
or
```sh
zig build bench -Doptimize=ReleaseFast -Dreplay=true -Dshards=1 -Dthreads=1 -Dauto='20:50000' -Dzipf='0.9' -Dkeys=10000000 -Dduration=10000
```
## Results
### Hit Rate (%)
### Average Operation Time (ns/op)
### Operations per Second (ops/s)
Single Threaded (zipf 0.7, 10m keys)
## Benchmark Parameters
```sh
zig build bench -Doptimize=ReleaseFast -Dzipf='0.7'
```
or
```sh
zig build bench -Doptimize=ReleaseFast -Dreplay=true -Dshards=1 -Dthreads=1 -Dauto='20:50000' -Dzipf='0.7' -Dkeys=10000000 -Dduration=10000
```
## Results
### Hit Rate (%)
### Average Operation Time (ns/op)
### Operations per Second (ops/s)
<a>🔝 Back to top</a>
❓ FAQ
<b>Is Zigache production-ready?</b>
Yes, Zigache is production-ready. It has been thoroughly tested and benchmarked for performance and stability. If you encounter any problems while using it in production, please report them so they can be addressed.
<b>Which eviction policy should I choose?</b>
It depends on your use case:
<ul>
<li><b>SIEVE</b>: Best for high throughput and high hit rate. (recommended)</li>
<li><b>TinyLFU</b>: Best for customizability and high hit rate.</li>
<li><b>S3FIFO</b>: Decent throughput with a decent hit rate.</li>
<li><b>LRU</b>: Reliable for standard needs but falls behind compared to other options.</li>
<li><b>FIFO</b>: High throughput, but lowest hit rates.</li>
</ul>
<b>Can I use Zigache in a multi-threaded environment?</b>
Yes, Zigache supports thread-safe operations and sharding. Sharding reduces contention and there are plans to improve performance further in the future.
<b>What type of keys does Zigache support?</b>
Zigache supports most key types like strings, integers, structs, arrays, pointers, enums, and optionals. However, floats are not supported due to precision issues.
<b>How can I contribute to Zigache?</b>
We welcome contributions! Please follow the <a>Zig Style Guide</a> and ensure that your changes include appropriate tests.
<a>🔝 Back to top</a>
📄 License
This project is licensed under the MIT License. See the <a>LICENSE.md</a> file for details. | [] |
https://avatars.githubusercontent.com/u/132709186?v=4 | zig-waybar-contrib | erffy/zig-waybar-contrib | 2025-01-12T17:08:03Z | ✨ Sleek and lightweight Waybar modules built with Zig | main | 0 | 8 | 1 | 8 | https://api.github.com/repos/erffy/zig-waybar-contrib/tags | GPL-3.0 | [
"sway",
"waybar",
"waybar-contrib",
"waybar-module",
"zig",
"ziglang",
"zls"
] | 165 | false | 2025-05-20T04:56:39Z | true | true | 0.14.0 | github | [] | <blockquote>
<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span>
I'm new to Zig, so it might take me some time to add or update modules. Your help and support mean a lot as I learn and grow with this project! 🥰
</blockquote>
zig-waybar-contrib
<strong>A collection of high-performance Waybar modules written in Zig.</strong>
🚀 Overview
<code>zig-waybar-contrib</code> offers lightweight, efficient Waybar modules built with <a>Zig</a>. By leveraging Zig’s speed and safety, these modules aim to deliver accurate system monitoring with minimal overhead.
✨ Features
<ul>
<li>⚡ <strong>High Performance</strong> – Optimized using Zig’s <code>ReleaseFast</code> + LTO.</li>
<li>🧩 <strong>Modular</strong> – Use only the modules you need.</li>
<li>📊 <strong>Real-Time Monitoring</strong> – Reliable and up-to-date metrics.</li>
<li>💡 <strong>Minimal Dependencies</strong> – Only essential tools required for specific modules.</li>
</ul>
📦 Available Modules
<blockquote>
All modules output a single-line JSON, fully compatible with Waybar’s <code>custom</code> module interface.
</blockquote>
| Module | Description | Status | Dependencies | Supported Systems |
|---------|-------------------------------------------|------------------|------------------------------|--------------------------|
| Updates | Tracks available system updates | ✅ Implemented | <code>pacman-contrib</code>, <code>fakeroot</code> | Arch Linux |
| GPU | Monitors GPU statistics and performance | ✅ Implemented | | AMD RX Series GPUs |
| Memory | Monitors system memory usage | ✅ Implemented | | |
| Ping | Network latency checker | ✅ Implemented | | |
📸 Screenshots
| Module | Preview |
|---------|--------------------------------------------------------------------------------|
| Updates | |
| GPU | |
| Memory | |
| Ping | |
🔧 Installation
Option 1: Download Release
<ol>
<li>Head to the <a>GitHub Releases</a> page.</li>
<li>Download the latest compiled binaries.</li>
</ol>
Option 2: Build from Source
<blockquote>
<strong>Requirements:</strong> Zig 0.14+
</blockquote>
<code>bash
git clone https://github.com/erffy/zig-waybar-contrib
cd zig-waybar-contrib
zig build</code>
⚙️ Configuration
Add module entries to your Waybar config (<code>~/.config/waybar/config</code>):
<code>json
{
"modules-right": [
"custom/updates",
"custom/gpu",
"custom/memory",
"custom/ping"
],
"custom/updates": {
"exec": "path/to/updates-module",
"return-type": "json",
"interval": 3600
}
// Add similar blocks for other modules
}</code>
🤝 Contributing
All contributions are welcome! You can help by:
<ul>
<li>Adding new modules</li>
<li>Improving current implementations</li>
<li>Fixing bugs</li>
<li>Enhancing documentation</li>
</ul>
Feel free to open a PR or an issue 😊
🛡️ License
Licensed under the <strong>GNU General Public License v3.0</strong>. See the <a>LICENSE</a> file for more info.
✨ Made with ❤️ by Me | [] |
https://avatars.githubusercontent.com/u/2773256?v=4 | wabt | dasimmet/wabt | 2024-12-22T18:03:06Z | WebAssembly Binary Toolkit (wabt) and Binaryen on the zig build system | main | 0 | 8 | 1 | 8 | https://api.github.com/repos/dasimmet/wabt/tags | Apache-2.0 | [
"wabt",
"wasm",
"wasm2wat",
"zig",
"zig-package"
] | 49 | false | 2025-05-21T08:42:29Z | true | true | 0.14.0 | github | [
{
"commit": "3e826ecde1adfba5f88d10d361131405637e65a3",
"name": "wabt",
"tar_url": "https://github.com/WebAssembly/wabt/archive/3e826ecde1adfba5f88d10d361131405637e65a3.tar.gz",
"type": "remote",
"url": "https://github.com/WebAssembly/wabt"
},
{
"commit": "27fcf6979298949e8a462e16d09a035... | WebAssembly Tools on the zig build system
uses the <a>Zig</a> build system to build WebAssembly's binary
C tools.
building
<code>zig build
zig build</code>
add to your zig project
<code>bash
zig fetch --save git+https://github.com/dasimmet/wabt.git</code>
<a>WebAssembly Binary Toolkit</a>
```
<blockquote>
./zig-out/bin/wasm2c --help
usage: wasm2c [options] filename
</blockquote>
Read a file in the WebAssembly binary format, and convert it to
a C source file and header.
```
<a>Binaryen</a>
```
<blockquote>
./zig-out/bin/wasm-merge --help
wasm-merge INFILE1 NAME1 INFILE2 NAME2 [..]
</blockquote>
Merge wasm files into one.
```
build.zig usage
```zig
const wabt = @import("wabt");
// wasm-opt
const optimized_wasm: LazyPath = wabt.wasm_opt(
b.path("my.wasm"), // source path
"optimized.wasm", // out_basename
.{"--mvp-features", "-Oz", "-c"}, // extra args
);
// wasm2wat
const my_wat: LazyPath = wabt.wasm2wat(
optimized_wasm, // source path
"my.wat", // out_basename
.{}, // extra args
);
``` | [
"https://github.com/dasimmet/ugtar",
"https://github.com/dasimmet/wabt",
"https://github.com/dasimmet/zware",
"https://github.com/malcolmstill/zware"
] |
https://avatars.githubusercontent.com/u/206480?v=4 | localize.zig | karlseguin/localize.zig | 2024-11-13T04:33:38Z | ICU Message Parser and Renderer | master | 0 | 7 | 0 | 7 | https://api.github.com/repos/karlseguin/localize.zig/tags | MIT | [
"localization",
"zig",
"zig-library",
"zig-package"
] | 22 | false | 2025-02-06T23:08:53Z | true | true | unknown | github | [] | ICU Message Format for Zig
Very basic support for parsing and rendering ICU message formats.
Install
1) Add localize.zig as a dependency in your <code>build.zig.zon</code>:
<code>bash
zig fetch --save git+https://github.com/karlseguin/localize.zig#master</code>
2) In your <code>build.zig</code>, add the <code>localize</code> module as a dependency you your program:
```zig
const localize = b.dependency("localize", .{
.target = target,
.optimize = optimize,
});
// the executable from your call to b.addExecutable(...)
exe.root_module.addImport("localize", localize.module("localize"));
```
Usage
First, create a <code>Resource</code>:
```zig
var resource = try localize.Resource(Locales).init(allocator);
defer resource.deinit();
const Locales = enum {
en,
fr,
};
```
This will likely be a long-lived object. Next, create a parser for each locale and add messages:
```zig
var parser = try resource.parser(.en, .{});
defer parser.deinit();
// loop over entries in a file, or something
// localize.zig currently doesn't "read" files
try parser.add("string_len_min", \ must be at least {min}
\ {min, plural,
\ =1 {character}
\ other {characters}
\ }
\ long
);
```
Once all messages have been loaded, you can use <code>resource.write</code> to write a localized message:
<code>zig
try resource.write(writer, .en, "string_len_min", .{.min = 6});</code>
The <code>write</code> method is thread-safe.
In cases where you'll be generating multiple message for a single locale, you can first get a <code>Locale</code> and then use its thread-safe write:</
```zig
// you very likely have logic in your code that makes it so that
// this could never return null
var locale = resource.getLocale(.en) orelse unreachable;
locale.write("string_len_min", .{.min = 6});
```
Limited Functionality
Currently, this only supports:
<ul>
<li>variables</li>
<li>plural<ul>
<li>=0 or zero</li>
<li>=1 or one</li>
<li>other</li>
</ul>
</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/94462076?v=4 | zigDOOM | lumi2021/zigDOOM | 2025-01-18T20:15:06Z | Can zig run DOOM? The 1997 DOOM engine, rewritten in the zig programming language. | main | 0 | 7 | 0 | 7 | https://api.github.com/repos/lumi2021/zigDOOM/tags | - | [
"c",
"doom",
"doom2",
"rewrite",
"zig",
"ziglang"
] | 2,572 | false | 2025-05-13T23:56:09Z | true | true | unknown | github | [] | zigDOOM
Can zig run DOOM? \
The 1997 DOOM engine, rewritten in the zig programming language.
Still in development! | [] |
https://avatars.githubusercontent.com/u/161890530?v=4 | zig-sec | soheil-01/zig-sec | 2024-08-15T15:20:42Z | Offensive Security Techniques in Zig: Research and Learning | main | 0 | 7 | 1 | 7 | https://api.github.com/repos/soheil-01/zig-sec/tags | - | [
"zig"
] | 550 | false | 2025-05-02T21:44:38Z | true | true | unknown | github | [
{
"commit": "407a4c7b869ee3d10db520fdfae8b9faf9b2adb5",
"name": "zigwin32",
"tar_url": "https://github.com/marlersoft/zigwin32/archive/407a4c7b869ee3d10db520fdfae8b9faf9b2adb5.tar.gz",
"type": "remote",
"url": "https://github.com/marlersoft/zigwin32"
}
] | 404 | [] |
https://avatars.githubusercontent.com/u/42496863?v=4 | hiillos | xor-bits/hiillos | 2024-11-14T02:19:47Z | microkernel in pure Zig | master | 0 | 7 | 0 | 7 | https://api.github.com/repos/xor-bits/hiillos/tags | AGPL-3.0 | [
"kernel",
"microkernel",
"osdev",
"zig"
] | 683 | false | 2025-05-22T06:05:04Z | true | true | 0.14.0 | github | [
{
"commit": "7b29b6e6f6d35052f01ed3831085a39aae131705.tar.gz",
"name": "limine",
"tar_url": "https://github.com/48cf/limine-zig/archive/7b29b6e6f6d35052f01ed3831085a39aae131705.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/48cf/limine-zig"
},
{
"commit": "refs",
"name"... |
# hiillos
hiillos is an operating system with its own microkernel
all written in pure Zig
The plan is for the kernel to be just a scheduler, IPC relay and a physical memory manager.
The system uses seL4-like capabilities, but on a global linear array instead of the CNode tree.
And physical memory allocation is managed by the kernel.
Running in QEMU
```bash
zig build run # thats it
read 'Project-Specific Options' from <code>zig build --help</code> for more options
zig build run -Dtest=true # include custom unit test runner
```
Building an ISO
<code>bash
zig build # generates the os.iso in zig-out/os.iso</code>
Development environment run cmd
<code>bash
zig build run --prominent-compile-errors --summary none -freference-trace \
-Doptimize=ReleaseSmall -Duefi=false -Ddebug=1 -Dgdb=false -Ddisplay=false -Dtest=true</code>
Stuff included here
<ul>
<li>kernel: <a>src/kernel</a></li>
<li>kernel/user interface: <a>src/abi</a></li>
<li>root process: <a>src/userspace/root</a></li>
</ul>
TODOs and roadmap
NOTE: /path/to/something is a short form for fs:///path/to/something
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> kernel
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> PMM
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> VMM
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> VMM arch implementation back in the kernel,
user-space vmm manages mapping of capabilities
to the (single per thread) vmem capability.
Frame should be the only mappable capability
and it is dynamically sized: <code>0x1000 * 2^size</code>.
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Mapping cache modes with PAT, uncacheable, write-combining,
write-through, write-protect, write-back and uncached
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> GDT, TSS, IDT
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> ACPI, APIC
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> SMP
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> HPET
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> TSC
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> scheduler
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> binary loader
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> stack tracer with line info
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> message IPC, shared memory IPC
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> multiple parallel recvs to the same endpoint
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> multiple parallel calls to the same endpoint
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> figure out userland interrupts (ps2 keyboard, ..)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> capabilities
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> allocate capabilities
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> deallocate capabilities
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> map capabilities
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> unmap capabilities
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> send capabilities
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> disallow mapping a frame twice without cloning the cap
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> disallow overlapping maps
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> restrict capability rights, ex: read-only frame can only create read-only frames
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> objects
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Memory
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Thread
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Vmem
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Frame
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> multiple Frame caps to the same physical memory (for shared memory)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> DeviceFrame
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Receiver
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Sender
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Reply
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Notify
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> syscalls
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> move all object methods to be syscalls
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> syscall tracker
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> method call tracker
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> user-space
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> stack traces with line info
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> root + initfsd process
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> decompress initfs.tar.gz
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> execute initfs:///sbin/init and give it a capability to IPC with the initfs
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> initfs:///sbin/vm server process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> handles virtual memory for everything
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> initfs:///sbin/pm server process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> handles individual processes and their threads
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> initfs:///sbin/rm server process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> launches a PS/2 keyboard driver if it detects a PS/2 keyboard
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> initfs:///sbin/timer server process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> launches a HPET driver
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> initfs:///sbin/vfs server process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> create fs://
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> exec required root filesystem drivers
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> read /etc/fstab before mounting root (root= kernel cli arg)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> mount everything according to /etc/fstab
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> exec other filesystem drivers lazily
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> initfs:///sbin/init process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> launch initfs:///sbin/rngd
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> launch initfs:///sbin/vfsd
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> launch services from initfs://
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> initfs:///sbin/fsd.fat32
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> initfs:///sbin/rngd process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/inputd process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/outputd process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/kbd process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/moused process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/timed process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/fbd process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/pcid process
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> /sbin/usbd process
IPC performance
Approximate synchronous IPC performance: <code>call</code> + <code>replyRecv</code>
loop takes about 10µs (100 000 per second):
<code>zig
// server
while (true) {
try rx.replyRecv(&msg);
}
// client
while (true) {
try tx.call(&msg);
}</code>
Gallery
| [] |
https://avatars.githubusercontent.com/u/179144860?v=4 | cricket.zig | furpu/cricket.zig | 2024-09-01T23:29:53Z | Zig library for encoding and decoding cryptographic data formats. | main | 3 | 6 | 1 | 6 | https://api.github.com/repos/furpu/cricket.zig/tags | MIT | [
"der",
"pem",
"pkcs",
"zig",
"zig-library"
] | 55 | false | 2025-02-14T15:18:13Z | true | true | 0.14.0-dev.1550+4fba7336a | github | [] | cricket.zig
Zig library for encoding and decoding cryptographic data formats.
<a></a> | [] |
https://avatars.githubusercontent.com/u/89275?v=4 | zig-htmx-tailwind-example | dgv/zig-htmx-tailwind-example | 2024-09-06T21:24:53Z | Example CRUD app written in Zig + HTMX + Tailwind CSS | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/dgv/zig-htmx-tailwind-example/tags | MIT | [
"crud",
"crud-application",
"htmx",
"htmx-app",
"tailwind",
"web",
"zig",
"ziglang",
"zmpl"
] | 160 | false | 2025-03-07T14:19:55Z | true | true | 0.13.0 | github | [
{
"commit": "master",
"name": "httpz",
"tar_url": "https://github.com/karlseguin/http.zig/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/karlseguin/http.zig"
},
{
"commit": "master",
"name": "zmpl",
"tar_url": "https://github.com/jetzig-framework/zmpl/archiv... | zig-htmx-tailwind-example
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
Example CRUD app written in Zig + HTMX + Tailwind CSS
This project implements a pure dynamic web app with SPA-like features but without heavy complex Javascript or frameworks to keep up with. Just HTML/CSS + Zig ⚡
Usage
```bash
Clone the repo
$ git clone https://github.com/dgv/zig-htmx-tailwind-example
$ cd zig-htmx-tailwind-example
Run the server
$ zig build run
Build the binary (default: ./zig-out/bin/zig-htmx-tailwind-example)
$ zig build
```
<strong>Environmental Variables</strong>
<code>ADDR Binding Address (default: 127.0.0.1)
PORT Binding Port (default: 3000)</code>
Dockerfile
I provide this just to easily deploy on a local server.
<code>bash shell
$ docker build -t zig-htmx-tailwind-example .
$ docker run -p 3000:3000 zig-htmx-tailwind-example</code>
Tailwind
You can use <a>tailwindcss cli</a> to regenerate the css asset:
<code>bash
$ tailwindcss -i css/input.css -o css/output.css --minify</code> | [] |
https://avatars.githubusercontent.com/u/10801140?v=4 | objective-zig-gen | colbyhall/objective-zig-gen | 2024-09-05T00:45:18Z | Obejctive-C to Zig bindgen. | main | 0 | 6 | 1 | 6 | https://api.github.com/repos/colbyhall/objective-zig-gen/tags | MIT | [
"bindgen",
"macos",
"objective-c",
"zig"
] | 184 | false | 2025-01-14T02:18:44Z | true | false | unknown | github | [] | Zig Objective-C Generator (objective-zig-gen)
<code>objective-zig-gen</code> is a work-in-progress tool for generating Objective-C bindings from Zig. This project aims to streamline the process of integrating Objective-C code with Zig, providing developers with a seamless way to interact with Objective-C APIs from Zig projects. You can find generated bindings in <a>objective-zig</a>.
Goals
<ul>
<li><strong>Objective-C Bindings Generation</strong>: Automatically generate Zig bindings for Objective-C code, enabling smooth integration between Zig and Objective-C.</li>
<li><strong>Type Mapping</strong>: Handles basic type conversions between Zig and Objective-C.</li>
<li><strong>Command Line Interface</strong>: Easy-to-use CLI for generating bindings directly from Objective-C header files.</li>
<li><strong>Comptime Zig to Objective C ABI</strong>: Allow users to write Objective-C compatible Zig so there is no need to write any Objective-C.</li>
</ul>
Getting Started
Prerequisites
<ul>
<li><a>Zig</a> (0.13.0)</li>
<li>llvm installed through homebrew for libclang (We currently have a naive way to find libclang which is why homebrew is required)</li>
<li>A working Objective-C toolchain (Xcode on macOS)</li>
</ul>
Installation
Since this project is under active development, it's recommended to clone the repository and build from source:
<code>bash
git clone https://github.com/colbyhall/zigobjcgen.git
cd zigobjcgen
zig build</code>
Usage
The program works off of a manifest file that list out xtool sdk frameworks, their dependencies, and other information for formatting the types.
<code>bash
objective-zig-gen <path/to/manifest.json></code>
Here is an example manifest file
```json
[
{
"name": "Security",
"output_file": "security"
},
{
"name": "CoreFoundation",
"output_file": "cf",
<code> "remove_prefix": "CF"
},
{
"name": "CoreServices",
"output_file": "cs",
"dependencies": [
"CoreFoundation"
]
},
{
"name": "Foundation",
"output_file": "ns",
"remove_prefix": "NS",
"dependencies": [
"CoreServices",
"CoreFoundation",
"Security"
]
}
</code>
]
```
Roadmap
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <strong>In Progress</strong> | Complete type mapping for all Objective-C types. (Protocols, Interfaces, Blocks)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Zig interface for writing Objective-C ABI compatible Zig.
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Comprehensive test and benchmarking.
Contributing
Contributions are welcome! Feel free to open issues or submit pull requests if you want to help improve the project.
License
This project is licensed under the MIT License - see the <a>LICENSE</a> file for details.
Acknowledgements
<ul>
<li>Thanks to the Zig community for their ongoing support and inspiration</li>
<li>Inspiration for this project comes from the ened to bridge the gap between Zig and the Objective-C ecosystem.</li>
<li>Mach and <a>mach-objc</a> for giving me the initial inspiration, resources, and some runtime code bindings.</li>
</ul>
<strong>Note</strong>: This project is actively being developed and is not ready for production use. Expect frequent changes and updates. | [] |
https://avatars.githubusercontent.com/u/4284735?v=4 | zig-nan-boxing | SimonMeskens/zig-nan-boxing | 2025-01-29T17:10:49Z | NaN boxing in Zig | main | 1 | 6 | 0 | 6 | https://api.github.com/repos/SimonMeskens/zig-nan-boxing/tags | MIT | [
"64-bit",
"box",
"double",
"dynamic",
"dynamic-types",
"dynamic-typing",
"nan-boxing",
"zig"
] | 9 | false | 2025-02-08T06:20:17Z | true | true | unknown | github | [] | ⚡ Zig NaN Boxing
This library provides a 64-bit dynamic box type that you can use for dynamically typed interpreters, that provides a number of types:
<ul>
<li>Doubles (including NaN)</li>
<li>Integers (signed and unsigned)</li>
<li>Booleans</li>
<li>Pointers (truncated at 48 bits), including Null</li>
<li>C Strings</li>
<li>Null</li>
</ul>
The project is complete and tested, but hasn't seen strong use yet. Your help could make it production ready.
Basic Usage
Example:
```zig
const maybe: ?bool = true; // Is this real life?
var box = Dyn64.from(@as(u32, 42)); // Box an integer
box = Dyn64.from(maybe); // Now it's a boolean
if (box.isNull()) unreachable; // Check if it's null
const truth: bool = box.isTrue(); // Take it back out
```
The project also contains fairly exhaustive tests that you can check for more examples.
<strong>Note:</strong> Strings won't automatically get coerced into boxed strings using <code>from</code>, you should instead use <code>fromString</code>, since it avoids having to guess at intent.
Installation
Add this to your build.zig.zon (you can also use a tag URL instead).
```zig
.dependencies = .{
.nan_boxing = .{
.url = "https://github.com/SimonMeskens/zig-nan-boxing/archive/refs/heads/master.tar.gz",
//the correct hash will be suggested by zig
}
}
```
And add this to you build.zig.
```zig
const nan_boxing = b.dependency("nan_boxing", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("nan-boxing", nan_boxing.module("nan-boxing"));
```
You can then import the library into your code like this
<code>zig
const Dyn64 = @import("nan-boxing").Dyn64;</code>
Run the tests
A comprehensive suite of tests is provided.
<code>shell
zig build test --summary all</code>
Contributing
I would love to get usage and bug reports if people use this, so I can gauge the production readiness.
PR's are welcome, but I'd like to keep the scope fairly narrow, so new features might get rejected for expanding the scope too much. Feel free to discuss first!
<strong>Q: Will you add 32bit dynamic boxes?</strong>
If I do, they probably wouldn't be NaN boxes, but instead tagged pointers, and that might not fit the scope of this project. I would likely instead make a separate library with 32bit and 64bit tagged pointers. | [] |
https://avatars.githubusercontent.com/u/30970706?v=4 | lmdbx-zig | theseyan/lmdbx-zig | 2024-11-05T15:46:55Z | Zig bindings for libMDBX (a fork of LMDB) | main | 1 | 6 | 0 | 6 | https://api.github.com/repos/theseyan/lmdbx-zig/tags | MIT | [
"database",
"libmdbx",
"lmdb",
"zig",
"zig-package"
] | 84 | false | 2025-05-10T16:26:56Z | true | true | 0.14.0 | github | [
{
"commit": null,
"name": "mdbx",
"tar_url": null,
"type": "remote",
"url": "https://libmdbx.dqdkfa.ru/release/libmdbx-amalgamated-0.14.1.tar.xz"
},
{
"commit": "refs",
"name": "cpu_features",
"tar_url": "https://github.com/slyshykO/cpu_model/archive/refs.tar.gz",
"type": "re... | lmdbx-zig
Zig bindings for <a>libMDBX</a> (a fork of LMDB), mostly ported from <a>zig-lmdb</a>.
Built and tested with Zig version <code>0.14.0</code>.
<blockquote>
<em>libmdbx</em> is an extremely fast, compact, powerful, embedded, transactional <a>key-value database</a> with a specific set of properties and capabilities,
focused on creating unique lightweight solutions.
<em>libmdbx</em> is superior to legendary <em><a>LMDB</a></em> in
terms of features and reliability, not inferior in performance. In
comparison to <em>LMDB</em>, <em>libmdbx</em> make things "just work" perfectly and
out-of-the-box, not silently and catastrophically break down.
</blockquote>
Table of Contents
<ul>
<li><a>Installation</a></li>
<li><a>Usage</a></li>
<li><a>API</a></li>
<li><a><code>Environment</code></a></li>
<li><a><code>Transaction</code></a></li>
<li><a><code>Database</code></a></li>
<li><a><code>Cursor</code></a></li>
<li><a>Benchmarks</a></li>
</ul>
Installation
```bash
replace {VERSION} with the latest release eg: v0.1.0
zig fetch https://github.com/theseyan/lmdbx-zig/archive/refs/tags/{VERSION}.tar.gz
```
Copy the hash generated and add lmdbx-zig to <code>build.zig.zon</code>:
<code>zig
.{
.dependencies = .{
.lmdbx = .{
.url = "https://github.com/theseyan/lmdbx-zig/archive/refs/tags/{VERSION}.tar.gz",
.hash = "{HASH}",
},
},
}</code>
Targets
<code>lmdbx-zig</code> officially supports cross-compiling to the following target triples:
- <code>x86_64-linux-gnu</code>, <code>x86_64-macos</code>, <code>x86_64-windows-gnu</code>
- <code>aarch64-linux-gnu</code>, <code>aarch64-macos</code>, <code>aarch64-windows-gnu</code>
Successful compilation on other targets is not guaranteed (but might work).
Usage
A libMDBX environment can either have multiple named databases, or a single unnamed database.
To use a single unnamed database, open a transaction and use the <code>txn.get</code>, <code>txn.set</code>, <code>txn.delete</code>, and <code>txn.cursor</code> methods directly.
```zig
const lmdbx = @import("lmdbx");
pub fn main() !void {
const env = try lmdbx.Environment.init("path/to/db", .{});
defer env.deinit();
<code>const txn = try lmdbx.Transaction.init(env, .{ .mode = .ReadWrite });
errdefer txn.abort();
try txn.set("aaa", "foo", .Create);
try txn.set("bbb", "bar", .Upsert);
try txn.commit();
</code>
}
```
To use named databases, open the environment with a non-zero <code>max_dbs</code> value. Then open each named database using <code>Transaction.database</code>, which returns a <code>Database</code> struct with <code>db.get</code>/<code>db.set</code>/<code>db.delete</code>/<code>db.cursor</code> methods. You don't have to close databases, but they're only valid during the lifetime of the transaction.
```zig
const lmdbx = @import("lmdbx");
pub fn main() !void {
const env = try lmdbx.Environment.init("path/to/db", .{ .max_dbs = 2 });
defer env.deinit();
<code>const txn = try lmdbx.Transaction.init(env, .{ .mode = .ReadWrite });
errdefer txn.abort();
const widgets = try txn.database("widgets", .{ .create = true });
try widgets.set("aaa", "foo", .Create);
const gadgets = try txn.database("gadgets", .{ .create = true });
try gadgets.set("aaa", "bar", .Create);
try txn.commit();
</code>
}
```
API
<code>Environment</code>
```zig
pub const Environment = struct {
pub const Options = struct {
geometry: ?DatabaseGeometry = null,
max_dbs: u32 = 0,
max_readers: u32 = 126,
read_only: bool = false,
write_map: bool = false,
no_sticky_threads: bool = false,
exclusive: bool = false,
no_read_ahead: bool = false,
no_mem_init: bool = false,
lifo_reclaim: bool = false,
no_meta_sync: bool = false,
safe_nosync: bool = false,
mode: u16 = 0o664
};
<code>pub const Info = struct {
map_size: usize,
max_readers: u32,
num_readers: u32,
autosync_period: u32,
autosync_threshold: u64,
db_pagesize: u32,
mode: u32,
sys_pagesize: u32,
unsync_volume: u64
};
pub const DatabaseGeometry = struct {
lower_size: isize = -1,
upper_size: isize = -1,
size_now: isize = -1,
growth_step: isize = -1,
shrink_threshold: isize = -1,
pagesize: isize = -1
};
pub fn init(path: [*:0]const u8, options: Options) !Environment
pub fn deinit(self: Environment) !void
pub fn transaction(self: Environment, options: Transaction.Options) !Transaction
pub fn sync(self: Environment) !void
pub fn stat(self: Environment) !Stat
pub fn info(self: Environment) !Info
pub fn setGeometry(self: Environment, options: DatabaseGeometry) !void
</code>
};
```
<code>Transaction</code>
```zig
pub const Transaction = struct {
pub const Mode = enum { ReadOnly, ReadWrite };
<code>pub const Options = struct {
mode: Mode,
parent: ?Transaction = null,
txn_try: bool = false
};
pub fn init(env: Environment, options: Options) !Transaction
pub fn abort(self: Transaction) !void
pub fn commit(self: Transaction) !void
pub fn get(self: Transaction, key: []const u8) !?[]const u8
pub fn set(self: Transaction, key: []const u8, value: []const u8, flag: Database.SetFlag) !void
pub fn delete(self: Transaction, key: []const u8) !void
pub fn cursor(self: Database) !Cursor
pub fn database(self: Transaction, name: ?[*:0]const u8, options: Database.Options) !Database
</code>
};
```
<code>Database</code>
```zig
pub const Database = struct {
pub const Options = struct {
reverse_key: bool = false,
integer_key: bool = false,
create: bool = false,
};
<code>pub const Stat = struct {
psize: u32,
depth: u32,
branch_pages: usize,
leaf_pages: usize,
overflow_pages: usize,
entries: usize,
};
pub const SetFlag = enum {
Create, Update, Upsert, Append, AppendDup
};
pub fn open(txn: Transaction, name: ?[*:0]const u8, options: Options) !Database
pub fn get(self: Database, key: []const u8) !?[]const u8
pub fn set(self: Database, key: []const u8, value: []const u8, flag: SetFlag) !void
pub fn delete(self: Database, key: []const u8) !void
pub fn cursor(self: Database) !Cursor
pub fn stat(self: Database) !Stat
</code>
};
```
<code>Cursor</code>
```zig
pub const Cursor = struct {
pub const Entry = struct { key: []const u8, value: []const u8 };
<code>pub fn init(db: Database) !Cursor
pub fn deinit(self: Cursor) void
pub fn getCurrentEntry(self: Cursor) !Entry
pub fn getCurrentKey(self: Cursor) ![]const u8
pub fn getCurrentValue(self: Cursor) ![]const u8
pub fn set(self: Cursor, key: []const u8, value: []const u8) !void
pub fn setCurrentValue(self: Cursor, value: []const u8) !void
pub fn deleteCurrentKey(self: Cursor) !void
pub fn goToNext(self: Cursor) !?[]const u8
pub fn goToPrevious(self: Cursor) !?[]const u8
pub fn goToLast(self: Cursor) !?[]const u8
pub fn goToFirst(self: Cursor) !?[]const u8
pub fn goToKey(self: Cursor, key: []const u8) !void
pub fn seek(self: Cursor, key: []const u8) !?[]const u8
</code>
};
```
<blockquote>
⚠️ Always close cursors <strong>before</strong> committing or aborting the transaction.
</blockquote>
Benchmarks
Run the benchmarks:
<code>zig build bench</code> | [] |
https://avatars.githubusercontent.com/u/34311583?v=4 | dmon-zig | ttytm/dmon-zig | 2024-10-19T18:12:33Z | Cross-platform Zig module to monitor changes in directories. | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/ttytm/dmon-zig/tags | BSD-2-Clause | [
"bindings",
"cross-platform",
"filesystem",
"library",
"linux",
"macos",
"monitor",
"monitoring",
"os",
"windows",
"zig",
"zig-package"
] | 24 | false | 2025-02-04T06:56:19Z | true | true | unknown | github | [
{
"commit": null,
"name": "standalone_test_cases",
"tar_url": null,
"type": "relative",
"url": "./src/bindings/dmon"
}
] | dmon-zig
<a></a>
<a></a>
Cross-platform Zig module to monitor changes in directories.
It utilizes the <a>dmon</a> C99 library.
Installation
```sh
~//your-awesome-projct
zig fetch --save https://github.com/ttytm/dmon-zig/archive/main.tar.gz
```
```zig
// your-awesome-projct/build.zig
const std = @import("std");
pub fn build(b: *std.Build) void {
// ..
const dmon_dep = b.dependency("dmon", .{});
const exe = b.addExecutable(.{
.name = "your-awesome-projct",
// ..
});
exe.root_module.addImport("dmon", dmon_dep.module("dmon"));
// ...
}
```
Usage Example
```v
const std = @import("std");
const dmon = @import("dmon");
const print = std.debug.print;
const Context = struct {
trigger_count: u32 = 0,
};
pub fn watchCb(
comptime Ctx: type,
_: dmon.WatchId,
action: dmon.Action,
root_dir: [<em>:0]const u8,
file_path: [</em>:0]const u8,
old_file_path: ?[<em>:0]const u8,
context: </em>Ctx,
) void {
print("Action: {}\n", .{action});
print("Root: {s}\n", .{root_dir});
print("File path: {s}\n", .{file_path});
print("Old file path: {s}\n", .{old_file_path orelse ""});
context.trigger_count += 1;
}
pub fn main() !void {
dmon.init();
defer dmon.deinit();
<code>const watch_path = "/home/user/Documents";
const id = dmon.watch(Context, watch_path, watchCb, .{ .recursive = true }, &ctx);
print("Starting to watch: {s}; Watcher ID: {d}\n", .{ watch_path, id });
while (true) {
if (ctx.trigger_count >= 3) break;
}
</code>
}
```
For a simple local example watching the cwd: <a><code>dmon-zig/examples/src/main.zig</code></a>
```sh
Perform a lightweight, filtered, yet complete clone
git clone --recursive --shallow-submodules --filter=blob:none \
https://github.com/ttytm/dmon-zig && \
cd dmon-zig/examples
```
```sh
dmon-zig/examples
zig build run
``` | [] |
https://avatars.githubusercontent.com/u/20323081?v=4 | zigscene | ngynkvn/zigscene | 2024-10-14T00:41:58Z | fun little music visualization, "demo scene" | main | 1 | 6 | 0 | 6 | https://api.github.com/repos/ngynkvn/zigscene/tags | MIT | [
"audio-player",
"audio-processing",
"audio-visualizer",
"demoscene",
"raylib",
"zig"
] | 4,476 | false | 2025-03-15T07:01:32Z | true | true | 0.14.0 | github | [
{
"commit": null,
"name": "raylib",
"tar_url": null,
"type": "relative",
"url": "./deps/raylib/"
},
{
"commit": null,
"name": "tracy",
"tar_url": null,
"type": "relative",
"url": "./deps/tracy/"
}
] | zigscene
Audio visualization experiment using zig and raylib.
Built against <code>0.14.0-dev.2605+136c5a916</code>
Getting Started
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
This project uses the nightly master build for zig, which frequently introduces breaking changes to the language. While this allows us to use the latest features and
improvements, it may:
<ul>
<li>Break unexpectedly when updating Zig versions</li>
<li>Contain code patterns that don't work in stable Zig releases</li>
<li>Require periodic updates to maintain compatibility</li>
</ul>
To build this project, you'll need to use Zig's master branch. You can download the latest nightly build from <a>https://ziglang.org/download/</a>.
I also recommend using <a>zigup</a> or <a>zvm</a> to install and manage zig versions.
</blockquote>
You should have:
<ul>
<li>This repository:</li>
</ul>
<code>bash
git clone https://github.com/ngynkvn/zigscene
cd zigscene</code>
<ul>
<li><code>zig</code> available in PATH.</li>
<li>Ensure <code>zig version</code> outputs <code>0.14.0-dev.2605+136c5a916</code></li>
</ul>
```bash
Build the project
zig build
Build and run
zig build run
Build with release optimization
zig build -Doptimize=ReleaseFast
Run tests
zig build test
```
Usage
<code>zig build run</code>, then drag and drop an audio file onto the window. Simple hotkeys are available: <strong>TODO</strong>
Screenshots
| [] |
https://avatars.githubusercontent.com/u/13835680?v=4 | todui | reykjalin/todui | 2024-10-26T02:43:35Z | Task management and note taking TUI powered by plaintext with full mouse support. Built with Zig. | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/reykjalin/todui/tags | MIT | [
"notes",
"task-manager",
"todo",
"tui",
"zig"
] | 1,397 | false | 2025-04-15T01:34:16Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "vaxis",
"tar_url": "https://github.com/rockorager/libvaxis/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/rockorager/libvaxis"
},
{
"commit": "1cceeb70e77dec941a4178160ff6c8d05a74de6f",
"name": "known-folders",
"tar_url": "https://... | Todui
<blockquote>
<strong>Note</strong>
I consider Todui to be mostly feature complete at this point.
Future development will be slow and mostly consist of minor quality-of-life improvements or fixing little annoyances and bugs that come up.
</blockquote>
A filesystem based TUI app for managing todo lists.
The <a><code>.todo</code> file specification</a> was created to fit this specific implementation.
The TUI is fully mouse aware so you can use both the keybindings listed below or the mouse to navigate the TUI.
You can find the planned list of future tasks, including details where applicable, in the <a>todo</a> directory.
View the list of tasks by running <code>todui .</code> from the root of the repo for the best experience viewing those.
Installation instructions
Download binaries
The tags and releases have binaries available for macOS (arm64 and x86_64), Linux (arm64 and x86_64), and Windows (x86_64).
You can download a pre-built binary for your system from there.
The binaries are static so you can store them wherever you like and run them from there.
Build from source
<ol>
<li>Clone this repository or download the source some other way.</li>
<li>Run <code>zig build -Doptimize=ReleaseSafe --prefix=~/.local</code> and the <code>todui</code> executable will be installed in <code>~/.local/bin/todui</code>.<ul>
<li>If you build without the <code>--prefix=~/.local</code> parameter the binary will be in <code>./zig-out/bin/todui</code>. It's static so you can move it wherever you want.</li>
</ul>
</li>
</ol>
CLI Help
```sh
$ todui --help
Usage: todui [storage_folder]
Positional options:
[storage_folder] The path to where todui data should be stored.
Defaults to ~/.local/share/todo/ when no path is provided.
General options:
-h, --help Print todui help
-v, --version Print todui version
```
The <code>storage_folder</code> positional argument can be used to change where tasks are stored.
The default path is <code>~/.local/share/</code> and tasks will be saved in <code>~/.local/share/todo/</code>.
If you'd like to, for example, have the tasks stored in <code>~/.config</code> you can run <code>todui ~/.config</code>.
If you do, tasks will be saved in <code>~/.config/todo/</code>.
This is very helpful for testing, but also if you'd like to maintain distinct lists for different
purposes.
For example, a complete separation between work and personal lists.
You could do the same with tags, but in that case the storage is the same for both.
Keybindings
Task List
| Key | Action |
|:---:|:---:|
| j / down | Move selection down |
| k / up | Move selection up|
| g | Move selection to top |
| G | Move selection to bottom |
| J / shift+down | Move selected task down |
| K / shift+up | Move selected task up |
| l / enter | Open task details view for the selected task |
| A | Create new task, appended to the bottom of the list |
| e | Edit selected task |
| c | Complete selected task |
| r | Reload task list |
| f | Open filter view |
| H | Hide the tags column |
| tab | Open completed task list view |
Completed Task List
| Key | Action |
|:---:|:---:|
| j / down | Move selection down |
| k / up | Move selection up|
| g | Move selection to top |
| G | Move selection to bottom |
| l / enter | Open task details view for the selected task |
| r | Reload task list |
| f | Open filter view |
| H | Hide the tags column |
| tab | Open task list view |
Task Details
| Key | Action |
|:---:|:---:|
| h / esc | Go back to previous view |
| e | Edit task |
| c | Complete task |
Task Filter
| Key | Action |
|:---:|:---:|
| enter | Save filter. Empty filter results in no filtering being applied |
Dev build instructions
This app is written in Zig and libvaxis and uses the Zig Build system.
To build, simply download Zig and run <code>zig build run</code>.
Dependencies will automatically be fetched and built for your system.
To make a release build run <code>zig build -Doptimize=ReleaseSafe</code>.
You'll find the built release executable in <code>./zig-out/bin/todui</code>.
Screenshots
| [] |
https://avatars.githubusercontent.com/u/998922?v=4 | Advent-of-Code | dbushell/Advent-of-Code | 2024-12-11T09:09:40Z | 🎄 My solutions to Advent of Code | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/dbushell/Advent-of-Code/tags | - | [
"advent-of-code",
"typescript",
"zig",
"ziglang"
] | 323 | false | 2025-04-17T19:42:38Z | false | false | unknown | github | [] | Advent of Code
My personal solutions to <a>Advent of Code</a>.
Coded mostly in brute force bad TypeScript (or worse) and some Zig.
I may return to re-implement aesthetic and/or code golf solutions if I'm bored or use another language. | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | Stockfish | allyourcodebase/Stockfish | 2024-12-11T16:56:53Z | Stockfish Built with Zig | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/allyourcodebase/Stockfish/tags | GPL-3.0 | [
"chess",
"stockfish",
"zig",
"ziglang"
] | 30 | false | 2025-04-18T22:36:48Z | true | true | 0.14.0 | github | [
{
"commit": "sf_17.1.tar.gz",
"name": "Stockfish",
"tar_url": "https://github.com/official-stockfish/Stockfish/archive/sf_17.1.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/official-stockfish/Stockfish"
}
] | Stockfish
<a></a>
Zig build for <a>Stockfish 17.1</a>. Requires zig 0.14.0.
Usage
```
Build Stockfish
zig build
Build and run
zig build run
Show build options
zig build -h
``` | [
"https://github.com/allyourcodebase/Stockfish"
] |
https://avatars.githubusercontent.com/u/50984334?v=4 | zigpwgen | francescoalemanno/zigpwgen | 2024-10-13T19:51:27Z | zigpwgen is for generating secure high-entropy, pronounceable passphrases. | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/francescoalemanno/zigpwgen/tags | MIT | [
"passphrase",
"passphrase-generator",
"password",
"password-generator",
"pronounceable-password",
"zig"
] | 96 | false | 2025-01-18T03:17:40Z | true | true | unknown | github | [] | Zig Password Generator (zigpwgen)
<code>zigpwgen</code> is a flexible password generator designed to produce passphrases that balance security and pronounceability. It is based on a pattern system where words, tokens, symbols, and digits can be flexibly combined. Built with the Zig programming language, <code>zigpwgen</code> ensures performance, clarity, and simplicity.
Features
<ul>
<li><strong>Pronounceable Words</strong>: Uses tokens from the EFF long word list to generate memorable passphrases.</li>
<li><strong>Customizable Patterns</strong>: Define your own password structure using a simple pattern syntax.</li>
<li><strong>Efficient and Fast</strong>: Built with Zig, ensuring minimal runtime overhead and clear, maintainable code.</li>
</ul>
Installation
Clone the repository and build with Zig:
<code>sh
git clone https://github.com/francescoalemanno/zigpwgen.git
cd zigpwgen
zig build -Doptimize=ReleaseFast</code>
or download one of the <a>precompiled release binaries</a>.
Usage
Command Syntax
```sh
Usage: zigpwgen [-p ] [-n ] [-e]
Flexible password generator using the EFF long word list for pronounceable words.
Built with Zig for performance and simplicity.
Options:
-p, --pattern string representing the desired structure of the generated passphrases,
defaults to <code>W-w-w-ds</code> (w = word; W = capital word; s = symbol; d = digit).
-n, --num number of passphrases to generate,
defaults to 5.
-e, --entropy print entropy in base log2 along with the generated password,
defaults to false.
-h, --help display usage information
-v, --version display version information
-- Example:
<blockquote>
zigpwgen -p w.w.w.w -n 3
</blockquote>
<ul>
<li>output:</li>
</ul>
jumnetion.pegmelf.dinhosure.vewwene
mobjering.pordipe.noclarita.hummern
jegmue.konhume.warpost.sotmative
-- Example:
<blockquote>
zigpwgen -p W-W-dd -n 4
</blockquote>
<ul>
<li>output:</li>
</ul>
Tatzight-Wustoil-54
Doggiarch-Vuntoses-86
Botbaw-Cixtosive-44
Borkandle-Vegber-98
author: Francesco Alemanno <a>francesco.alemanno.710@gmail.com</a>
repo: https://github.com/francescoalemanno/zigpwgen
```
License
MIT License
Copyright (c) 2024 Francesco Alemanno | [] |
https://avatars.githubusercontent.com/u/54124162?v=4 | benchmarks | gmitch215/benchmarks | 2024-09-13T01:19:21Z | 📊 Browsable Benchmarks for Programming Languages | master | 0 | 5 | 1 | 5 | https://api.github.com/repos/gmitch215/benchmarks/tags | Apache-2.0 | [
"benchmark",
"bun",
"c",
"clang",
"cpp",
"deno",
"gcc",
"gnu",
"go",
"golang",
"java",
"javascript",
"kotlin",
"kotlin-native",
"nodejs",
"php",
"ruby",
"rust",
"rustc",
"zig"
] | 5,415 | false | 2025-05-14T01:54:02Z | false | false | unknown | github | [] | ⌚ benchmarks
<blockquote>
Programming benchmarks
</blockquote>
<a></a>
<a></a>
<a></a>
<a></a>
This repository contains various benchmarks on different programming languages for different algorithms. The primary goal of this repository is to provide a comparison between different programming languages and their speeds.
You can navigate to the website <a>here</a>, or by clicking the linked website on the repository.
Local Benchmarking
This repository also features the ability to benchmark all the algorithms locally.
Running Specific Benchmarks
Benchmarks offers two gradle tasks: <code>compileBenchmark</code> and <code>runBenchmark</code>, to run specific benchmarks.
<code>bash
./gradlew compileBenchmark runBenchmark -Planguage={language} -Pfile={file}</code>
For example, to run <code>count-1M</code> for <code>c</code> using Clang, you would run:
<code>bash
./gradlew compileBenchmark runBenchmark -Planguage=c-llvm -Pfile=count-1M/main.c</code>
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
<code>compileBenchmark</code> is only required to be passed for compiled languages. Gradle will automatically skip interpreted languages passed,
like <code>python</code> and <code>ruby</code>.
</blockquote>
<code>bash
./gradlew runBenchmark -Planguage=ruby -Pfile=count-1M/main.rb</code>
<code>compileBenchmark</code>
Any language with a <code>compile</code> command in the <a><code>config.yml</code></a> file needs to be compiled first before it can run with the <code>run</code> commmand.
To compile the code, you can run the <code>compileBenchmark</code> task in the root directory for the repository:
<code>bash
./gradlew compileBenchmark -Planguage={language} -Pfile={file}</code>
The task accepts two parameters:
<code>language</code> - ID of the language in the <a><code>config.yml</code></a> file
<code>file</code> - File to compile relative to the <code>benchmarks</code> directory
For example, to compile the HTTP GET benchmark for Kotlin/Native, you would run:
<code>bash
./gradlew compileBenchmark -Planguage=kotlin-native -Pfile=http-get/main.kt</code>
<code>runBenchmark</code>
After compiling the benchmarks, you can run them using the <code>runBenchmark</code> task:
<code>bash
./gradlew runBenchmark -Planguage={language} -Pfile={file}</code>
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
<code>compileBenchmark</code> is only required to be passed for compiled languages. You can use <code>runBenchmark</code> for interpreted languages:
</blockquote>
<code>bash
./gradlew runBenchmark -Planguage=ruby -Pfile=count-1M/main.rb</code>
The task accepts the same parameters as the <code>compileBenchmark</code> task.
For example, to run the HTTP GET benchmark for Kotlin/Native, you do:
<code>bash
./gradlew compileBenchmark runBenchmark -Planguage=kotlin-native -Pfile=http-get/main.kt</code>
<code>http-get</code> measures in <code>ms</code> according to its benchmark <a><code>config.yml</code></a>, so the output will be in milliseconds.
Running All Benchmarks
Prerequisites
<strong>All</strong> command line tools present in <a><code>config.yml</code></a> must be installed. You can determine if you meet them by running
the <code>version</code>, <code>compile</code>, and/or <code>run</code> commands in the terminal.
Here are some notable examples:
<ul>
<li><code>python</code> for Python</li>
<li><code>java</code> for Java</li>
<li>Using the JDK for Gradle requires Java 21 or higher.</li>
<li>Using the <code>java</code> command on the command line requires Java 8 or higher.</li>
<li><code>kotlinc</code> for Kotlin JVM</li>
<li>This requires the <code>KOTLIN_HOME</code> environment variable to be set to the Kotlin compiler directory (<strong>not</strong> the bin directory).</li>
<li><code>kotlinc-native</code> for Kotlin Native</li>
<li>This requires the <code>KOTLIN_NATIVE_HOME</code> environment variable to be set to the Kotlin Native compiler directory (<strong>not</strong> the bin directory).</li>
<li><code>ruby</code> for Ruby</li>
<li><code>native-image</code> for GraalVM</li>
<li>This requires the <code>GRAALVM_HOME</code> environment variable to be set to the GraalVM directory (<strong>not</strong> the bin directory).</li>
<li><code>gcc</code>/<code>g++</code> <strong>and</strong> <code>clang</code>/<code>clang++</code> for C/C++</li>
<li><code>rustc</code> for Rust</li>
<li><code>go</code> for Go</li>
<li><code>node</code>, <code>deno</code> <strong>and</strong> <code>bun</code> for JavaScript</li>
<li><code>ruby</code> for Ruby</li>
<li><code>php</code> for PHP</li>
<li><code>zig</code> for Zig</li>
</ul>
You can test if you have the necessary tools and setup by running the <code>validate</code> gradle task:
<code>bash
./gradlew validate</code>
IntelliJ IDEA
The repository comes with two IntelliJ IDEA run configuration that allows you to run benchmarks directly from the IDE:
<ul>
<li><code>benchmark</code> - Runs and graphs the benchmarks</li>
<li><code>all</code> - Runs and graphs the benchmarks, then prepares and serves the website</li>
</ul>
CLI
To both run and graph the benchmarks, you can use the following command:
<code>bash
./gradlew benchmark</code>
Benchmarks will be generated in JSON format in the <code>benchmarks/output</code> directory.
Interactive HTML graphs are available in the <code>benchmarks/output/graphs</code> directory.
After that, you can prepare and serve the website by running:
<code>bash
./gradlew preview</code>
You can navigate to the website by visiting <code>http://localhost:4000</code>.
The preview output only creates benchmarks for your hosting operating system.
For example, if you're benchmarking your computer on a Windows machine, clicking on <code>macOS</code> or <code>Linux</code> will report a 404 error.
Otherwise, you can navigate through the website as if it were live.
Contributing
Contributors are always welcome.
If you would like to contribute to this repository, please read the <a>CONTRIBUTING.md</a> file.
License
This repository is licensed under the <a>Apache License 2.0</a>.
As per outlined in the license, you are free to use, modify, distribute, and sublicense this repository for personal or commercial use.
However, you must include the <strong>original copyright</strong> and <strong>license</strong> in any copy of the software.
By using the software, locally or on its <a>website</a>, you agree to the terms and conditions outlined in the license. | [] |
https://avatars.githubusercontent.com/u/11708465?v=4 | PWA-Liveview | dwyl/PWA-Liveview | 2024-12-28T16:49:09Z | PWA demo with Phoenix Liveview | main | 4 | 5 | 0 | 5 | https://api.github.com/repos/dwyl/PWA-Liveview/tags | GPL-3.0 | [
"elixir",
"leaflet",
"phoenix-liveview",
"pwa",
"pwa-apps",
"solidjs",
"wasm",
"webassembly",
"y-indexeddb",
"yjs",
"zig"
] | 18,977 | false | 2025-05-22T02:38:15Z | false | false | unknown | github | [] | Offline first Phoenix LiveView PWA
An example of a real-time, collaborative multi-page web app built with <code>Phoenix LiveView</code>.
It is designed for offline-first ready; it is packaged as a <a>PWA</a> and uses op-based CRDTs or local state and reactive components.
Offline first solutions naturally offloads most of the reactive UI logic to JavaScript.
When online, we use LiveView "hooks", while when offline, we render the reactive components.
It uses <code>Vite</code> as the bundler.
<blockquote>
While it can be extended to support multiple pages, dynamic page handling has not yet been tested nor implemented.
</blockquote>
<strong>Results</strong>:
<ul>
<li>deployed on Fly.io at: <a>https://solidyjs-lively-pine-4375.fly.dev/</a></li>
<li>standalone Phoenix LiveView app of 2.1 MB</li>
<li>memory usage: 220MB</li>
<li>image weight: 52MB of Fly.io, 126MB on Docker Hub (<code>Debian</code> based)</li>
<li>client code can be updated via the Service Worker lifecycle</li>
</ul>
QRCode to check multi users, from on a mobile device:
Table of Contents
<ul>
<li><a>Offline first Phoenix LiveView PWA</a></li>
<li><a>Table of Contents</a></li>
<li><a>What?</a></li>
<li><a>Why?</a></li>
<li><a>Design goals</a></li>
<li><a>Common pitfall of combining LiveView with CSR components</a></li>
<li><a>Tech overview</a><ul>
<li><a>Implementation highlights</a></li>
</ul>
</li>
<li><a>About the Yjs-Stock page</a></li>
<li><a>About PWA</a><ul>
<li><a>Updates life-cycle</a></li>
</ul>
</li>
<li><a>Usage</a></li>
<li><a>Details of Pages</a><ul>
<li><a>Yjs-Stock</a></li>
<li><a>Pg-Sync-Stock</a></li>
<li><a>FlightMap</a></li>
</ul>
</li>
<li><a>Navigation</a></li>
<li><a>Vite</a><ul>
<li><a>Configuration and settings</a></li>
<li><a>Watcher</a></li>
<li><a>Tailwind</a></li>
<li><a>Client Env</a></li>
<li><a>Static assets</a></li>
<li><a>VitePWA plugin and Workbox Caching Strategies</a></li>
</ul>
</li>
<li><a>Yjs</a></li>
<li><a>Misc</a><ul>
<li><a>Presence through Live-navigation</a></li>
<li><a>CSP rules and evaluation</a></li>
<li><a>Icons</a></li>
<li><a>Manifest</a></li>
<li><a>Performance</a></li>
<li><a>[Optional] Page Caching</a></li>
</ul>
</li>
<li><a>Publish</a></li>
<li><a>Fly volumes</a></li>
<li><a>Documentation source</a></li>
<li><a>Resources</a></li>
<li><a>License</a></li>
<li><a>Credits</a></li>
</ul>
What?
<strong>Context</strong>: we want to experiment PWA collaborative webapps using Phoenix LiveView.
What are we building? A three pages webap:
<ul>
<li>Yjs-Stock. On the first page, we mimic a shopping cart where users can pick items until stock is depleted, at which point the stock is replenished. Every user will see and can interact with this counter</li>
<li>PgSync-Stock. This page features <code>phoenix_sync</code> in <em>embedded</em> mode streaming logical replicates of a Postgres table. [Building offline features]</li>
<li>FlightMap. On the second page, we propose an interactive map with a form with two inputs where <strong>two</strong> users can edit collaboratively a form to display markers on the map and then draw a great circle between the two points.</li>
</ul>
<blockquote>
You need an api key to render the Maptiler vector tiles. You can see the Service Worker in action in the LiveMap page when you go offline as the tiles are cached. This is naturally only true if you already visited these tiles, thus loaded them.
</blockquote>
Why?
Traditional Phoenix LiveView applications face several challenges in offline scenarios:
<ol>
<li>
<strong>no Offline Interactivity</strong>:
Some applications need to maintain interactivity even when offline, preventing a degraded user experience.
</li>
<li>
<strong>no Offline Navigation</strong>:
User may need to navigate through pages.
</li>
<li>
<strong>WebSocket Limitations</strong>:
LiveView's WebSocket architecture isn't naturally suited for PWAs, as it requires constant connection for functionality. When online, we use <code>Phoenix.Channel</code> for real-time collaboration.
</li>
<li>
<strong>State Management</strong>:
It is challenging to maintain consistent state across network interruptions between the client and the server.
</li>
<li>
<strong>Build tool</strong>:
We need to setup a Service Worker to cache HTML pages and static assets to work offline, out of the LiveView goodies.
</li>
</ol>
Design goals
<ul>
<li><strong>collaborative</strong> (online): Clients sync via <em>pubsub updates</em> when connected, ensuring real-time consistency.</li>
<li><strong>optimistic UI</strong>: The function "click on stock" assumes success and will reconciliate later.</li>
<li><strong>database</strong>:</li>
<li>We use <code>SQLite</code> as the "canonical" source of truth for the Yjs-Stock counter.</li>
<li><code>Postgres</code> is used for the <code>Phoenix_sync</code> process for the PgSync-Stock counter.</li>
<li><strong>Offline-First</strong>: The app remains functional offline (through the <code>Cache</code> API and reactive JS components), with clients converging to the correct state on reconnection.</li>
<li><strong>PWA</strong>: Full PWA features, meaning it can be <em>installed</em> as a standalone app and can be <em>updated</em>. A <code>Service Worker</code> runs in a separate thread and caches the assets. It is setup with <code>VitePWA</code>.</li>
</ul>
Common pitfall of combining LiveView with CSR components
The client-side rendered components are - when online - mounted via hooks under the tag <code>phx-update="ignore"</code>.
These components have they own lifecycle. They can leak or stack duplicate components if you don't cleanup them properly.
The same applies to "subscriptions/observers" primitives from (any) the state manager. You must <em>unsubscribe</em>, otherwise you might get multiples calls and weird behaviours.
⭐️ LiveView hooks comes with a handy lifecyle and the <code>destroyed</code> callback is essential.
<code>SolidJS</code> makes this easy as it can return a <code>cleanupSolid</code> callback (where you take a reference to the SolidJS component in the hook).
You also need to clean <em>subscriptions</em> (when using a store manager).
The same applies when you navigate offline; you have to run cleanup functions, both on the components and on the subsriptions/observers from the state manager.
Tech overview
| Component | Role |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Vite | Build and bundling framework |
| SQLite | Embedded persistent storage of latest Yjs document |
| Phoenix LiveView | UI rendering, incuding hooks |
| PubSub / Phoenix.Channel | Broadcast/notifies other clients of updates / conveys CRDTs binaries on a separate websocket (from te LiveSocket) |
| Yjs / Y.Map | Holds the CRDT state client-side (shared) |
| Valtio | Holds local ephemeral state |
| y-indexeddb | Persists state locally for offline mode |
| SolidJS | renders reactive UI using signals, driven by Yjs observers |
| Hooks | Injects communication primitives and controls JavaScript code |
| Service Worker / Cache API | Enable offline UI rendering and navigation by caching HTML pages and static assets |
| Leaflet | Map rendering |
| MapTiler | enable vector tiles |
| WebAssembly container | high-performance calculations for map "great-circle" routes use <code>Zig</code> code compiled to <code>WASM</code> |
Implementation highlights
<ul>
<li>
<strong>Offline capabilities</strong>:
</li>
<li>
Yjs-Stock page: edits are saved to <code>y-indexeddb</code>
</li>
<li>PgSync-Stock: edits save in <em>localStorage</em> (TODO)</li>
<li>
FlightMap: the "airports" list is saved in <em>localStorage</em>
</li>
<li>
<strong>State Management</strong>:
We use different approaches based on the page requirements:
</li>
<li>
Yjs-Stock. Client-side: CRDT-based (op-based) synchronization with <code>Yjs</code> featuring <code>IndexedDB</code>. Server-side, it uses an embedded <code>SQLite</code> database as the canonical source of truth, even if Yjs is the local source of truth.
</li>
<li>PgSync-Stock. Client-side: <em>localStorage</em> persistence, and server-side, <code>Postgres</code> with logical replication.</li>
<li>
FlightMap. Local state management (<code>Valtio</code>) for the collaborative Flight Map page with no server-side persistence of the state
</li>
<li>
<strong>Build tool</strong>:
We use Vite as the build tool to bundle and optimize the application and enable PWA features seamlessly.
The Service Worker to cache HTML pages and static assets.
</li>
<li>
<strong>CRDT features used</strong> in Yjs-Stock page:
</li>
<li>
We are using the following features of CRDT:
<ul>
<li>Local change tracking: All changes are modeled as CRDT ops, so you can always merge them safely if needed.</li>
<li>Offline/online merging: If a user has multiple browser tabs, or is offline and comes back, Yjs/CRDT guarantees that the state will be consistent and no changes will be lost.</li>
<li>Persistence: Because CRDTs work by merging, you can safely persist and reload state at any time.</li>
</ul>
</li>
<li>
<strong>op-based CRDT Synchronization Flow</strong>:
This is essentially implementing the operation-based CRDT counter pattern.
Each client accumulates local ops (clicks), and only sends its local ops (since last sync) on reconnect.
Each client tracks only their local "clicks"/decrements since last sync (not the absolute counter value).
On reconnection, client sends the number of pending clicks to the server.
Server applies the delta to the shared counter in the database (e.g., counter = counter - clicks).
Server responds with the new counter value.
Client resets its local clicks to zero, and sets the local counter to the value from the server.
If a client has no pending clicks, it doesn't send anything, but receives the current counter from the server.
</li>
</ul>
The client updates his local <code>YDoc</code> with the server responses or from his own changes.
<code>YDoc</code> mutations are observed and trigger UI rendering, and reciprocally, UI modifications update the <code>YDoc</code> and propagate mutations to the server.
<ul>
<li>
<strong>FlightMap page</strong>:
We use a local state manager (<code>Valtio</code> using proxies).
The inputs (selected airports) are saved to a local state.
Local UI changes mutate the state and are sent to the server. The server broadcasts the data.
We have state observers which update the UI if the origin is not remote.
</li>
<li>
<strong>Data Transport</strong>:
</li>
<li>
Yjs-Stock page: we used <code>Phoenix.Channel</code> to decouples state handling from the LiveSocket.
</li>
<li>
FlightMap page:
We use the LiveSocket as the data flow is small.
</li>
<li>
<strong>Component Rendering Strategy</strong>:
</li>
<li>online: use LiveView hooks</li>
<li>offline: hydrate the HTML with cached documents and run reactive JavaScript components</li>
</ul>
About the Yjs-Stock page
```mermaid
sequenceDiagram
autonumber
participant User
participant SolidJS/Yjs Client
participant LiveView Hook
participant Phoenix Server
Note over SolidJS/Yjs Client: CRDT Initialized (Y.Map: {counter, clicks})
Note over SolidJS/Yjs Client, Phoenix Server: Shared topic: "counter"
User->>SolidJS/Yjs Client: Clicks +1
Note over SolidJS/Yjs Client: CRDT 'counter' += 1\nCRDT 'clicks' += 1 (local only)
SolidJS/Yjs Client-->>UI: Immediate update (Optimistic)
Note over SolidJS/Yjs Client: Yjs triggers <code>ydoc.on("update")</code>
SolidJS/Yjs Client->>LiveView Hook: handleYUpdate(origin="local")
LiveView Hook->>Phoenix Server: push("client-update", {clicks})
Phoenix Server->>Phoenix Server: counter += clicks
Phoenix Server->>LiveView Hook: reply("ok", {counter})
LiveView Hook->>SolidJS/Yjs Client: trigger counter-update
SolidJS/Yjs Client->>Yjs: ydoc.transact() to set counter\n& reset clicks = 0
SolidJS/Yjs Client-->>UI: CRDT triggers observer\nUI re-renders
Note over SolidJS/Yjs Client: Yjs (CRDT) is reactive and stateful
Note over Phoenix Server: Phoenix holds canonical "counter"
%% Sync from server on connect
SolidJS/Yjs Client->>LiveView Hook: syncWithServer()
LiveView Hook->>Phoenix Server: push("client-update", {clicks?})
Phoenix Server-->>LiveView Hook: reply("ok", {counter})
LiveView Hook->>SolidJS/Yjs Client: ydoc.set("counter", counter)\nydoc.set("clicks", 0)
%% Broadcasts to others
Phoenix Server->>Other Clients: broadcast "counter-update"
Other Clients->>Yjs: set("counter", counter)
Note over Other Clients: Observer triggers UI update
```
About PWA
A Progressive Web App (PWA) is a type of web application that provides an app-like experience directly in the browser.
It has:
<ul>
<li>offline support</li>
<li>is "instalable":</li>
</ul>
The core components are setup using <code>Vite</code> in the <em>vite.config.js</em> file.
<ul>
<li>
<strong>Service Worker</strong>:
A background script - separate thread - that acts as a proxy: intercepts network requests and enables offline caching and background sync.
We use the <code>VitePWA</code> plugin to enable the Service Worker life-cycle (manage updates)
</li>
<li>
Web App <strong>Manifest</strong> (manifest.webmanifest)
A JSON file that defines the app’s name, icons, theme color, start URL, etc., used to install the webapp.
We produce the Manifest with <code>Vite</code> via in the "vite.
</li>
<li>
HTTPS (or localhost):
Required for secure context: it enables Service Workers and trust.
</li>
</ul>
<code>Vite</code> builds the SW for us via the <code>VitePWA</code> plugin by declarations in "vite.config.js". Check <a>Vite</a>
The SW is started by the main script, early, and must preload all the build static assets as the main file starts before the SW runtime caching is active.
Since we want offline navigation, we precache the rendered HTML as well.
Updates life-cycle
A Service Worker (SW) runs in a <em>separate thread</em> from the main JS and has a unique lifecycle made of 3 key phases: install / activate / fetch
In action:
<ol>
<li>Make a change in the client code, git push/fly deploy:
-> a button appears and the dev console shows a push and waiting stage:</li>
</ol>
<ol>
<li>Click the "refresh needed"
-> the Service Worker and client claims are updated seamlessly, and the button is in the hidden "normal" state.</li>
</ol>
Service Workers don't automatically update unless:
<ul>
<li>
The sw.js file has changed (based on byte comparison).
</li>
<li>
The browser checks periodically (usually every 24 hours).
</li>
<li>
When a new SW is detected:
</li>
<li>
New SW enters installing state.
</li>
<li>
It waits until no existing clients are using the old SW.
</li>
<li>
Then it activates.
</li>
</ul>
```mermaid
sequenceDiagram
participant User
participant Browser
participant App
participant OldSW as Old Service Worker
participant NewSW as New Service Worker
Browser->>OldSW: Control App
App->>Browser: registerSW()
App->>App: code changes
Browser->>NewSW: Downloads New SW
NewSW->>Browser: waiting phase
NewSW-->>App: message: onNeedRefresh()
App->>User: Show onNeedRefresh()
User->>App: Clicks Update Button
App->>NewSW: skipWaiting()
NewSW->>Browser: Activates
NewSW->>App: Takes control (via clients.claim())
```
Usage
```elixir
mix.exs
server component of Yjs to manage Y_Doc server-side
{:y_ex, "~> 0.7.3"},
SQLite3
{:exqlite, "0.30.1"},
fetching the CSV airports
{:req, "~> 0.5.8"},
parsing the CSV airports
{:nimble_csv, "~> 1.2"},
```
Client package are setup with <code>pnpm</code>: check <a>▶️ package.json</a>
1/ <strong>dev</strong> setup with <em>IEX</em> session
```sh
install all dependencies including Vite
mix deps.get
mix ecto.create && mix ecto.migrate
pnpm install --prefix assets
start Phoenix server, it will also compile the JS
iex -S mix phx.server
```
2/ Run a local Docker container in <strong>mode=prod</strong>
<code>sh
docker compose up --build</code>
<a>▶️ Dockerfile</a>
<a>▶️ docker-compose.yml</a>
<blockquote>
You can take a look at the build artifacts by running into another terminal
</blockquote>
```sh
<blockquote>
docker compose exec -it web cat lib/solidyjs-0.1.0/priv/static/.vite/manifest.json
```
</blockquote>
3/ Pull from <code>Docker Hub</code>:
<code>sh
docker run -it -e SECRET_KEY_BASE=oi37wzrEwoWq4XgnSY3VRbKUhNxvdowJ7NOCrCECZ6V7WyPDNHuQp36oat+aqOkS -p 80:4000 --rm ndrean/pwa-liveview:latest</code>
and visit <a>http://localhost</a>
Details of Pages
Yjs-Stock
Available at <code>/</code>.
You click on a counter and it goes down..! The counter is broacasted and handled by a CRDT backed into a SQLite table.
A user can click offline, and on reconnection, all clients will get updated with the lowest value (business rule).
Pg-Sync-Stock
Available at "/elec"
FlightMap
Available at <code>/map</code>.
It displays an <em>interactive</em> and <em>collaborative</em> (two-user input) route planning with vector tiles.
The UI displays a form with two inputs, which are pushed to Phoenix and broadcasted via Phoenix PubSub. A marker is drawn by <code>Leaflet</code> to display the choosen airport on a vector-tiled map using <code>MapTiler</code>.
Key features:
<ul>
<li>collaborative input</li>
<li><code>Valtio</code>-based <em>local</em> (browser only) ephemeral state management (no complex conflict resolution needed)</li>
<li>WebAssembly-powered great circle calculations: CPU-intensive calculations works offline</li>
<li>Efficient map rendering with MapTiler and <em>vector tiles</em> with smaller cache size (vector data vs. raster image files)</li>
</ul>
<blockquote>
[<strong>Great circle computation</strong>] It uses a WASM module. <code>Zig</code> is used to compute a "great circle" between two points, as a list of <code>[lat, long]</code> spaced by 100km. The <code>Zig</code> code is compiled to WASM and available for the client JavaScript to run it. Once the list of successive coordinates are in JavaScript, <code>Leaflet</code> can use it to produce a polyline and draw it into a canvas. We added a WASM module to implement great circle route calculation as a showcase of WASM integration. A JAvascript alternative would be to use <a>turf.js</a>.
check the folder "/zig-wasm"
[<strong>Airport dataset</strong>] We use a dataset from <a>https://ourairports.com/</a>. We stream download a CSV file, parse it (<code>NimbleCSV</code>) and bulk insert into an SQLite table. When a user mounts, we read from the database and pass the data asynchronously to the client via the liveSocket on the first mount. We persist the data in <code>localStorage</code> for client-side search. The socket "airports" assign is then pruned to free the server's socket.
</blockquote>
▶️ <a>Airports</a>, <a>LiveMap</a>
<blockquote>
The Websocket is configured with <code>compress: true</code> (cf <a>https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#socket/3-websocket-configuration</a>) to enable compression of the 1.1MB airport dataset through the LiveSocket.
</blockquote>
Below a diagram showing the flow between the database, the server and the client.
```mermaid
sequenceDiagram
participant Client
participant LiveView
participant Database
<code>Client->>LiveView: mount (connected)
Client->>Client: check localStorage/Valtio
alt cached data exists and valid
Client->>LiveView: "cache-checked" (cached: true)
LiveView->>Client: verify hash
else no valid cache
Client->>LiveView: "cache-checked" (cached: false)
LiveView->>Database: fetch_airports()
Database-->>LiveView: airports data
LiveView->>Client: "airports" event with data
Client->>Client: update localStorage + Valtio
end
</code>
```
Navigation
The user use "live navigation" when online between two pages which use the same <em>live_session</em>, with no full page reload.
When the user goes offline, we have the same smooth navigation thanks to navigation hijack an the HTML and assets caching, as well as the usage of <code>y-indexeddb</code>.
<strong>Lifecycle</strong>:
<ul>
<li>Initial Load: App starts a continous server check. It determines if online/offline and sets up accordingly</li>
<li>Going Offline: Triggers component initialization and navigation setup</li>
<li>Navigating Offline: cleans up components, <em>fetch</em> the cached pages (request proxied by the SW and the page are cached iva the <code>additionalManifestEntries</code>), parse ahd hydrate the DOM to renders components</li>
<li>Going Online: when the polling detects a transistion off->on, the user expects a page refresh and Phoenix LiveView reinitializes.</li>
</ul>
<strong>Key point</strong>:
<ul>
<li>⚠️ <strong>memory leaks</strong>:
With this offline navigation, we never refresh the page. As said before, reactive components and subscriptions need to be cleaned before disposal. We store the cleanup functions and the subscriptions.</li>
</ul>
Vite
Configuration and settings
All the client code is managed by <code>Vite</code> and done (mostly) in a declarative way in the file <a>vite.config.js</a>.
<blockquote>
Most declarations are done programatically as it is run by <code>NodeJS</code>.
</blockquote>
Watcher
There is a watcher configured in "config/dev.exs" which replaces, thus removes, <code>esbuild</code> and <code>tailwindCSS</code> (which are also removed from the mix deps).
<code>elixir
watchers: [
npx: [
"vite",
"build",
"--mode",
"development",
"--watch",
"--config",
"vite.config.js",
cd: Path.expand("../assets", __DIR__)
]
]</code>
Tailwind
⚠️You can't use v4 but should <em>keep v3.4</em>. Indeed, Tailwind v4 drops the "tailwind.config.js" and there is no proper way to parse the SSR files (.ex, .heex) without it.
Tailwind is used as a PostCSS plugin. In the <code>Vite</code> config, it is set with the declaration:
<code>js
import tailwindcss from "tailwindcss";
[...]
// in `defineConfig`, add:
css: {
postcss: {
plugins: [tailwindcss()],
},
},</code>
and reads automatically the "tailwind.configjs" which sits next to "vite.config.js".
<blockquote>
Note. We use <code>lightningCSS</code> for further optimze the CSS and <code>autoprefixer</code> is built in (if "-weebkit" for flex/grid or "-moz" for transitions are needed).
</blockquote>
Client Env
The env arguments are loaded with <code>loadEnv</code>.
<ol>
<li>
Runtime access: <code>import.meta.env</code>
The client env vars are set in the ".env" placed, placed in the "/assets" folder (origin client code) next to "vite.config.js".
They need to be prefixed with <code>VITE_</code>.
They is injected by <code>Vite</code> at <em>runtime</em> when you use <code>import.meta.env</code>.
In particular, we use <code>VITE_API_KEY</code> for <code>Maptiler</code> to render the vector tiles.
</li>
<li>
Compile access: <code>define</code>
it is used at <em>compile time</em> .
The directive <code>define</code> is used to get <em>compile time</em> global constant replacement. This is valuable for dead code elimination.
For example:
</li>
</ol>
<code>js
define: {
__API_ENDPOINT__: JSON.stringify(
process.env.NODE_ENV === "production"
? "https://example.com"
: "http://localhost:4000"
);
}
[...]
// NODE_ENV="prodution"
// file.js
if (__API__ENDPOINT__ !== "https://example.com") {
// => dead code eliminated
}</code>
<ol>
<li>Docker:
In the Docker build stage, you copy the "assets" folder.
You therefor copy the ".env" file so the env vars variables are accessible at runtime.
When you deploy, we need to set an env variable <code>VITE_API_KEY</code> which will be used to build the image.</li>
</ol>
Static assets
We do not use the step <code>mix phx.digest</code> and removed from the Dockerfile.
We fingerprint and compress the static files via <code>Vite</code>.
<code>js
rollupOptions.output: {
assetFileNames: "assets/[name]-[hash][extname]",
chunkFileNames: "assets/[name]-[hash].js",
entryFileNames: "assets/[name]-[hash].js",
},</code>
We do this because we want the SW to be able to detect client code changes and update the app. The Phoenix work would interfer.
<strong>Caveat</strong>: versioned fils have dynamic so how to pass them to the "root.html.heex" component?
When assets are not fingerprinted, Phoenix can serve them "normally" as names are known:
<code>elixir
<link rel="icon" href="/favicon.ico" type="image/png" sizes="48x48" />
<link rel="manifest" href="/manifest.webmanifest" /></code>
When the asset reference is versioned, we use the <code>.vte/manifest</code> dictionary to find the new name.
We used a helper <a>ViteHelper</a> to map the original name to the versioned one (the one in "priv/static/assets").
```elixir
```
Not all assets need to be fingerprinted, such as "robotx.txt", icons.... To copy these files , we use the plugin <code>vite-plugin-static-copy</code>.
We also compress files to <em>ZSTD</em> known for its compression performance and deflating speed. We use the plugin <code>vite-plugin-compression2</code> and use <code>@mongodb-js/zstd</code>.
We modify "endpoint.ex" to accept these encodings:
<code>elixir
plug Plug.Static,
encodings: [{"zstd", ".zstd"}],
brotli: true,
gzip: true,
at: "/",
from: :liveview_pwa,
only: ~w(
assets
icons
robots.txt
sw.js
manifest.webmanifest
sitemap.xml
),
headers: %{
"cache-control" => "public, max-age=31536000"
}
[...]</code>
VitePWA plugin and Workbox Caching Strategies
We use the <a>VitePWA</a> plugin to generate the SW and the manifest.
The client code is loaded in a <code><script></code>. It will load the SW registration when the event DOMContentLoaded fires.
All of the hooks are loaded and attached to the LiveSocket, like an SPA.
If we don't <em>preload</em> the JS files in the SW, most of the js files will never be cached, thus the app won't work offline.
For this, we define that we want to preload all static assets in the directive <code>globPattern</code>.
Once the SW activated, you should see (in dev mode):
We also cache the rendered HTML pages as we inject them when offline, via <code>additionalManifestEntries</code>.
```js
PWAConfig = {
// Don't inject to register SW (handled manually)
// and there no client generated "index.html" by Phoenix
injectRegister: false, // no client generated "index.html" by Phoenix
// Let Workbox auto-generate the service worker from config
strategies: "generateSW",
// App manually prompts user to update SW when available
registerType: "prompt",
// SW lifecycle ---
// Claim control over all uncontrolled pages as soon as the SW is activated
clientsClaim: true,
// Let app decide when to update; user must confirm or app logic must apply update
skipWaiting: false,
workbox: {...}
}
```
❗️ It is important <em>not to split</em> the "sw.js" file because <code>Vite</code> produces a fingerprint from the splitted files. However, Phoenix serves hardcoded nmes and can't know the name in advance.
```js
workbox: {
// Disable to avoid interference with Phoenix LiveView WebSocket negotiation
navigationPreload: false
// ❗️ no fallback to "index.html" as it does not exist
navigateFallback: null
// ‼️ tell Workbox not to split te SW as the other is fingerprinted, thus unknown to Phoenix.
inlineWorkboxRuntime: true,
// preload all the built static assets
globPatterns: ["assets/<em><em>/</em>.</em>"],
// cached the HTML for offline rendering
additionalManifestEntries: [
{ url: "/", revision: <code>${Date.now()}</code> }, // Manually precache root route
{ url: "/map", revision: <code>${Date.now()}</code> }, // Manually precache map route
],
}
```
For the Service Worker lifecycle, set:
<code>js
defineConfig = {
// Disable default public dir (using Phoenix's)
publicDir: false,
};</code>
Yjs
[TODO something smart...?]
Misc
Presence through Live-navigation
It is implemented using a <code>Channel</code> and a <code>JavaScript</code> snippet used in the main script.
The reason is that if we implement it with "streams", it will wash away the current stream
used by <code>Phoenix_sync</code>.
It also allows to minimise rendering when navigating to the different Liveviews.
The relevant module is: <code>setPresenceChannel.js</code>. It uses a reactive JS component (<code>SolidJS</code>).
It returns a "dispose" and an "update" function.
This snippet runs in "main.js".
The key points are:
<ul>
<li>a simple Channel with <code>Presence.track</code> and a <code>push</code> of the <code>Presence.list</code>,</li>
<li>use <code>presence.onSync</code> listener to get a <code>Presence</code> list up-to-date and render the UI with this list</li>
<li>a <code>phx:page-loading-stop</code> listener to udpate the UI when navigating between Liveviews because we target DOM elements to render the reactive component.</li>
</ul>
CSP rules and evaluation
The application implements security CSP headers set by a plug: <code>BrowserCSP</code>.
We mainly protect the "main.js" file - run as a script in the "root.html" template - is protected with a <strong>dynamic nonce</strong>.
Detail of dynamic nonce
```elixir
defmodule SoldiyjsWeb.BrowserCSP do
@behaviour Plug
def init(opts), do: opts
def call(conn, _opts) do
nonce = :crypto.strong_rand_bytes(16) |> Base.encode16(case: :lower)
Plug.Conn.assign(conn, :csp_nonce, nonce)
end
end
```
````elixir
# root.html.heex
// Your inline script here
```elixir
defp put_csp_headers(conn) do
nonce = conn.assigns[:csp_nonce] || ""
csp_policy = """
script-src 'self' 'nonce-#{nonce}' 'wasm-unsafe-eval' https://cdn.maptiler.com;
object-src 'none';
connect-src 'self' http://localhost:* ws://localhost:* https://api.maptiler.com https://*.maptiler.com;
img-src 'self' data: https://*.maptiler.com https://api.maptiler.com;
worker-src 'self' blob:;
style-src 'self' 'unsafe-inline';
default-src 'self';
frame-ancestors 'self' http://localhost:*;
base-uri 'self'
"""
|> String.replace("\n", " ")
put_resp_header(conn, "content-security-policy", csp_policy)
end
````
The nonce-xxx attribute is an assign populated in the plug BrowserCSP.
Indeed, the "root" template is rendered on the first mount, and has access to the <code>conn.assigns</code>.
➡️ Link to check the endpoint: <a>https://csp-evaluator.withgoogle.com/</a>
The WASM module needs <code>'wasm-unsafe-eval'</code> as the browser runs <code>eval</code>.
Icons
You will need is to have at least two very low resolution icons of size 192 and 512, one extra of 180 for OSX and one 62 for Microsoft, all placed in "/priv/static".
Check <a>Resources</a>
Manifest
The "manifest.webmanifest" file will be generated from "vite.config.js".
Source: check <a>PWABuilder</a>
<code>json
{
"name": "LivePWA",
"short_name": "LivePWA",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"lang": "en",
"scope": "/",
"description": "A Phoenix LiveView PWA demo app",
"theme_color": "#ffffff",
"icons": [
{ "src": "/images/icon-192.png", "sizes": "192x192", "type": "image/png" },
...
]
}</code>
✅ Insert the links to the icons in the (root layout) HTML:
```html
[...] [...] [...]
```
Performance
Lighthouse results:
[Optional] Page Caching
Direct usage of Cache API instead of Workbox
We can use the `Cache API` as an alternative to `Workbox` to cache pages. The important part is to calculate the "Content-Length" to be able to cache it.
> Note: we cache a page only once by using a `Set`
```javascript
// Cache current page if it's in the configured routes
async function addCurrentPageToCache({ current, routes }) {
await navigator.serviceWorker.ready;
const newPath = new URL(current).pathname;
// Only cache configured routes once
if (!routes.includes(newPath) || AppState.paths.has(newPath)) return;
if (newPath === window.location.pathname) {
AppState.paths.add(newPath);
const htmlContent = document.documentElement.outerHTML;
const contentLength = new TextEncoder().encode(htmlContent).length;
const response = new Response(htmlContent, {
headers: {
"Content-Type": "text/html",
"Content-Length": contentLength,
},
status: 200,
});
const cache = await caches.open(CONFIG.CACHE_NAME);
return cache.put(current, response);
}
}
// Monitor navigation events
navigation.addEventListener("navigate", async ({ destination: { url } }) => {
return addCurrentPageToCache({ current: url, routes: CONFIG.ROUTES });
});
```
Publish
The site <a>https://docs.pwabuilder.com/#/builder/android</a> helps to publish PWAs on Google Play, Ios and other plateforms.
Fly volumes
In the "fly.toml", the settings for the volume are:
```toml
[env]
DATABASE_PATH = '/mnt/db/main.db'
MIX_ENV = 'prod'
PHX_HOST = 'solidyjs-lively-pine-4375.fly.dev'
PORT = '8080'
[[mounts]]
source = 'name'
destination = '/mnt/db'
```
This volume is made persistent through build with <code>source = 'name'</code>.
We set the Fly secret: <code>DATABASE_PATH=mnt/db/main.db</code>.
Documentation source
<ul>
<li>Update API: <a>https://docs.yjs.dev/api/document-updates#update-api</a></li>
<li>Event handler "on": <a>https://docs.yjs.dev/api/y.doc#event-handler</a></li>
<li>local persistence with IndexedDB: <a>https://docs.yjs.dev/getting-started/allowing-offline-editing</a></li>
<li>Transactions: <a>https://docs.yjs.dev/getting-started/working-with-shared-types#transactions</a></li>
<li>Map shared type: <a>https://docs.yjs.dev/api/shared-types/y.map</a></li>
<li>observer on shared type: <a>https://docs.yjs.dev/api/shared-types/y.map#api</a></li>
</ul>
Resources
Besides Phoenix LiveView:
<ul>
<li><a>Yex with Channel</a></li>
<li><a>Yjs Documentation</a></li>
<li><a>Vite PWA Plugin Guide</a></li>
<li><a>MDN PWA</a></li>
<li><a>PWA builder</a></li>
<li><a>Favicon Generator</a> and <a>https://vite-pwa-org.netlify.app/assets-generator/#pwa-minimal-icons-requirements</a></li>
<li><a>CSP Evaluator</a></li>
<li><a>Haversine formula</a></li>
</ul>
License
<a>GNU License</a>
Credits
To enhance this project, you may want to use <code>y_ex</code>, the <code>Elixir</code> port of <code>y-crdt</code>.
Cf <a>Satoren</a> for <a>Yex</a> | [] |
https://avatars.githubusercontent.com/u/140198242?v=4 | nix-flake-templates | nulladmin1/nix-flake-templates | 2024-10-14T00:26:03Z | A collection of Nix Flake Templates for: Python, CMake, Poetry, uv, Rust, Fenix, Naersk, Vim, Zig, Bash etc. | main | 0 | 5 | 1 | 5 | https://api.github.com/repos/nulladmin1/nix-flake-templates/tags | - | [
"c",
"cmake",
"cplusplus",
"cpp",
"fenix",
"go",
"golang",
"linux",
"nix",
"nix-flake",
"nixpkgs",
"poetry",
"python",
"rust",
"template",
"template-project",
"templates",
"zig"
] | 582 | false | 2025-03-18T06:25:42Z | false | false | unknown | github | [] | ❄️ Nix Flake Templates
<a></a> <a></a>
A collection of Nix Flake Templates
<strong>Contributors, go to <a>CONTRIBUTING.md</a></strong>
Table of Contents
<ul>
<li><a>Usage</a></li>
<li><a>Examples</a></li>
</ul>
Usage
Use <a><code>getflake</code></a> to initialize flake (recommended)
<code>shell
nix run github:nulladmin1/getflake</code>
Or initialize using
<code>shell
nix flake init --template "github:nulladmin1/nix-flake-templates#${TYPE_KEYWORD}"</code>
Where <code>${TYPE_KEYWORD}</code> is the supported type keyword of template:
| Type Keyword | Type | Subdirectory | Documentation |
| ----------------------------------- | ------------------------------ | -------------------------------------------- | ---------------------------------------- |
| <code>bash</code>, <code>sh</code> | Bash using Nixpkgs Builders | <a>bash</a> | <a>README</a> |
| <code>bevy</code> | Bevy using Fenix and Crane | <a>bevy</a> | <a>README</a> |
| <code>cpp</code>, <code>cpp-cmake</code> | C++ using CMake | <a>cpp-cmake</a> | <a>README</a> |
| <code>default</code> | Development | <a>default</a> | <a>README</a> |
| <code>flutter</code>, <code>flutter-nix</code> | Flutter using Nixpkgs Builders | <a>flutter-nix</a> | <a>README</a> |
| <code>go</code>, <code>go-gomod2nix</code> | Go using gomod2nix | <a>go-gomod2nix</a> | <a>README</a> |
| <code>go-nix</code> | Go with Nixpkgs Builders | <a>go-nix</a> | <a>README</a> |
| <code>nixpkgs</code> | Nixpkgs Development | <a>nixpkgs</a> | <a>README</a> |
| <code>python</code>, <code>python-nix</code> | Python using Nixpkgs builders | <a>python-nix</a> | <a>README</a> |
| <code>poetry</code>, <code>python-poetry</code> | Python using Poetry | <a>python-poetry</a> | <a>README</a> |
| <code>pyproject</code>, <code>python-pyproject-nix</code> | Python using Pyproject-nix | <a>python-pyproject-nix</a> | <a>README</a> |
| <code>python-uv</code>, <code>uv</code> | Python using uv2nix | <a>python-uv</a> | <a>README</a> |
| <code>crane</code>, <code>rust</code>, <code>rust-fenix-crane</code> | Rust using Fenix and Crane | <a>rust-fenix-crane</a> | <a>README</a> |
| <code>rust-fenix-naersk</code> | Rust using Fenix and Naersk | <a>rust-fenix-naersk</a> | <a>README</a> |
| <code>rust-nix</code> | Rust using Nixpkgs Builders | <a>rust-nix</a> | <a>README</a> |
| <code>vim</code>, <code>vimPlugins</code> | vimPlugins | <a>vimPlugins</a> | <a>README</a> |
| <code>zig</code> | Zig using Nixpkgs Builders | <a>zig</a> | <a>README</a> |
Examples
<a><code>getflake</code></a> (using <code>rust-fenix-naersk</code>) - A simple to program to automatically instantiate my <a>Nix-Flake-Templates</a>
<a><code>eightQueens</code></a> (using <code>cpp-cmake</code>) - A rendition of the famous <a>Eight Queens Puzzle</a> in <code>C++</code>
<a><code>mp2ExtraCredit</code></a> (using <code>cpp-cmake</code>) - A solution of a plague simulation I had to do for Computer Science II, in <code>C++</code>
<a><code>josephus-rs</code></a> (using <code>rust-fenix-naersk</code>) - An implementation of the <a>Josephus problem</a> in <code>Rust</code>
<a><code>sha256_python_with_tests</code></a> - A simple Python program with testcases to encode a user-inputted string in SHA256 | [] |
https://avatars.githubusercontent.com/u/77928207?v=4 | llama.js | mattzcarey/llama.js | 2024-08-29T14:02:04Z | run LLMs (llama, mamba, nemo, mistral) at native speeds from Javascript, Typescript. | main | 0 | 5 | 0 | 5 | https://api.github.com/repos/mattzcarey/llama.js/tags | - | [
"ai",
"bun",
"javascript",
"js",
"llama",
"llamacpp",
"llms",
"machinelearning",
"pytorch",
"tensorflowjs",
"ts",
"typescript",
"zig"
] | 4 | false | 2024-09-18T22:24:31Z | false | false | unknown | github | [] | llama.js
<blockquote>
an experiment to run llama.cpp through a javascript runtime at near native speeds
</blockquote>
Installation
<ul>
<li>Clone the repo recursively</li>
<li>Install zig to the path</li>
<li>
cd into llama.cpp.zig
</li>
<li>
Download a model
</li>
</ul>
<code>bash
huggingface-cli download NousResearch Hermes-2-Pro-Mistral-7B-GGUF Hermes-2-Pro-Mistral-7B.Q4_0.gguf --local-dir models</code>
<ul>
<li>Run the model with llama.cpp.zig</li>
</ul>
<code>bash
zig build run-simple -Doptimize=ReleaseFast -- --model_path "./models/Hermes-2-Pro-Mistral-7B.Q4_0.gguf" --prompt "Hello! I am AI, and here are the 10 things I like to think about:"</code>
<ul>
<li>Build the library (zig bindings)</li>
</ul>
<code>bash
zig build</code>
Usage
<ul>
<li>cd back to root and run the index.ts</li>
</ul>
<code>bash
bun run index.ts</code> | [] |
https://avatars.githubusercontent.com/u/7109515?v=4 | zig-clap | ramonmeza/zig-clap | 2024-11-07T19:00:40Z | Zig bindings for free-audio's CLAP library. | main | 0 | 5 | 0 | 5 | https://api.github.com/repos/ramonmeza/zig-clap/tags | MIT | [
"audio",
"c",
"clap",
"library",
"plugin",
"vst",
"zig"
] | 124 | false | 2025-05-12T18:06:23Z | true | true | 0.14.0 | github | [] | <ul>
<li>
https://nakst.gitlab.io/tutorial/clap-part-1.html
I basically ported nakst's CLAP plugin to Zig. This article was extremely helpful in developing this binding.
</li>
<li>
https://github.com/Not-Nik/raylib-zig
I based a lot of my design decisions off of Not Nik's raylib-zig repo. This repo is great and really made me want to dive into Zig bindings in the first place.
</li>
</ul> | [
"https://github.com/paoda/bp-jit",
"https://github.com/paoda/turbo",
"https://github.com/paoda/zba"
] |
https://avatars.githubusercontent.com/u/124217829?v=4 | ztatusbar | javiorfo/ztatusbar | 2024-11-19T22:37:45Z | Configurable statusbar for Xorg server using xsetroot | master | 0 | 5 | 0 | 5 | https://api.github.com/repos/javiorfo/ztatusbar/tags | MIT | [
"linux",
"statusbar",
"window-manager",
"xorg",
"zig"
] | 54 | false | 2025-04-21T19:45:46Z | true | true | 0.13.0 | github | [
{
"commit": "refs",
"name": "syslinfo",
"tar_url": "https://github.com/javiorfo/zig-syslinfo/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/javiorfo/zig-syslinfo"
},
{
"commit": "refs",
"name": "tomlz",
"tar_url": "https://github.com/mattyhall/tomlz/archive/re... | ztatusbar
<em>Configurable statusbar developed in Zig for Xorg server using xsetroot</em>
Caveats
<ul>
<li>Zig version <strong>0.13.0</strong></li>
<li>C lib dependencies: <code>xorg-xsetroot</code>, <code>curl</code>, <code>alsa</code></li>
<li>This library has been developed on and for Linux following open source philosophy.</li>
</ul>
Installation
<ul>
<li>
Downloading, compiling and installing manually:
<code>bash
git clone https://github.com/javiorfo/ztatusbar
cd ztatusbar
sudo make clean install</code>
<strong>NOTE:</strong> variable OPTIMIZE could be pass as parameter to activate different Zig build modes (default is ReleaseFast).
</li>
<li>
From AUR Arch Linux:
<code>bash
yay -S ztatusbar</code>
</li>
</ul>
Setup
<ul>
<li>In your <strong>~/.xinitrc</strong> or <strong>~/.xprofile</strong> to start in every login
<code>bash
ztatusbar 2> ztatusbar.log &</code></li>
</ul>
Overview
| Component | rstatusbar | NOTE |
| ------- | ------------- | ---- |
| CPU usage | :heavy_check_mark: | Percentage |
| RAM usage | :heavy_check_mark: | Percentage |
| TEMPERATURE | :heavy_check_mark: | Celcious |
| DISK USAGE | :heavy_check_mark: | Percentage |
| VOLUME LEVEL | :heavy_check_mark: | Level and Mute status |
| BLUETOOTH | :x: | |
| BATTERY LEVEL | :heavy_check_mark: | Percentage |
| CUSTOM SCRIPT | :heavy_check_mark: | Execute a custom script.sh |
| NETWORK STATUS | :heavy_check_mark: | Up or down |
| WEATHER | :heavy_check_mark: | Celcious, using <a>wttr</a> |
| DATE | :heavy_check_mark: | Could be custimizable |
Customizable
<ul>
<li>By default the statusbar contains: <strong>cpu usage, memory usage, temperature, disk usage, volume and datetime</strong></li>
<li>For a custom configuration put this file <a>config.toml</a> in your <code>~/.config/ztatusbar/config.toml</code> and edit it to change values or delete a component.</li>
<li>Some configuration example in config.toml:
```toml
[memory]
time = 1000 # Time in miliseconds defines how often the process runs
name = "RAM" # Name of the component. Could be empty => name = ""
icon = "" # Icon of the component. Could be empty => icon = ""</li>
</ul>
[disk]
time = 2000
name = "DISK"
icon = " "
unit = "/"
[volume]
time = 100
name = "VOL"
icon = " "
icon_muted = " "
[temperature]
time = 1000
name = "TEMP"
icon = " "
zone = 1 # thermal zone which has the temperature in /sys/class/thermal_zone{variable here}/temp. If not set it uses thermal_zone0/temp
...
```
Donate
<ul>
<li><strong>Bitcoin</strong> <a>(QR)</a> <code>1GqdJ63RDPE4eJKujHi166FAyigvHu5R7v</code></li>
<li><a>Paypal</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | lmdb | allyourcodebase/lmdb | 2024-09-26T11:46:59Z | Lmdb using the zig build system | main | 2 | 5 | 1 | 5 | https://api.github.com/repos/allyourcodebase/lmdb/tags | BSD-3-Clause | [
"lmdb",
"zig",
"zig-package"
] | 32 | false | 2025-03-14T09:49:35Z | true | true | 0.14.0 | github | [
{
"commit": "f20e41de09d97e4461946b7e26ec831d0c24fac7.tar.gz",
"name": "lmdb",
"tar_url": "https://github.com/LMDB/lmdb/archive/f20e41de09d97e4461946b7e26ec831d0c24fac7.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/LMDB/lmdb"
}
] | lmdb
<a>Lmdb</a> using the <a>Zig</a> build system
Usage
First, update your <code>build.zig.zon</code>:
```elvish
Initialize a <code>zig build</code> project if you haven't already
zig init
Support for <code>lmdb</code> starts with v0.9.31 and future releases
zig fetch --save https://github.com/allyourcodebase/lmdb/archive/refs/tags/0.9.31+2.tar.gz
For latest git commit
zig fetch --save https://github.com/allyourcodebase/lmdb/archive/refs/heads/main.tar.gz
```
Import <code>lmdb</code> dependency into <code>build.zig</code> as follows:
<code>zig
const lmdb_dep = b.dependency("lmdb", .{
.target = target,
.optimize = optimize,
.strip = true,
.lto = true,
.linkage = .static,
});</code>
Using <code>lmdb</code> artifacts and module in your project
```zig
const exe = b.addExecutable(.{
.name = exe_name,
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
.strip = strip,
});
exe.want_lto = lto;
<code>const liblmdb = lmdb_dep.artifact("lmdb");
const lmdb_module = lmdb_dep.module("lmdb");
exe.root_module.addImport("mdb", lmdb_module);
exe.linkLibrary(liblmdb);
</code>
```
Supported on Linux, macOS and Windows
<ul>
<li>Zig 0.15.0-dev</li>
<li>Zig 0.14.0</li>
</ul> | [
"https://github.com/allyourcodebase/lmdb",
"https://github.com/bernardassan/recblock",
"https://github.com/canvasxyz/zig-lmdb",
"https://github.com/ikks/tldrtranslate"
] |
https://avatars.githubusercontent.com/u/65524156?v=4 | ESPAT | RecursiveError/ESPAT | 2024-10-08T20:58:33Z | simple driver to use ESP32 boards as WiFi module via AT command firmware | main | 4 | 5 | 0 | 5 | https://api.github.com/repos/RecursiveError/ESPAT/tags | MIT | [
"embedded",
"esp32",
"wifi",
"zig",
"zig-package"
] | 332 | false | 2025-03-06T20:40:04Z | true | true | unknown | github | [] | ESPAT
ZIG VERSION: 0.14.0
simple driver made in Zig to use ESP32 boards as WiFi module via AT command firmware
AT command firmware for ESP modules (32/8266) is a simple and inexpensive way to add wireless connection to embedded devices, although it is more limited than conventional RF modules, ESP modules abstract much of the network stack, allowing their use in more limited devices.
<strong><em>Important</em></strong>: This driver is still under development, invalid inputs may cause deadlocks or breaks
<strong>Recommended Espressif AT Firmware Version</strong>:4.0.0.0
<strong>Minimum Espressif AT Firmware Version</strong>: 3.4.0.0
<strong>Warning</strong>: for Ai-thinker modules such as ESP-01 or ESP-12.
Boantong AT firmware (AT =< 1.7) is not supported, and Espressif firmware (2.2.0.0) is not compatible with the pin layout of these boards, to use them it is necessary to customize the firmware to ESP8266, if you don't know how to do this follow this guide: <a>custom pin AT</a>
Supported Features
<ul>
<li>WiFi STA/AP/AP+STA modes</li>
<li>WiFi static IP and DHCP config</li>
<li>WiFi protocol config</li>
<li>Multi conn support</li>
<li>TCP/UDP Client</li>
<li>TCP Server</li>
<li>Server + Client mode</li>
<li>passive and active recv mode (for All sockets)</li>
<li>build-in HTTP/HTTPS client</li>
</ul>
Get started
<ul>
<li><a>ESP AT</a></li>
<li><a>Driver</a></li>
<li><a>Porting</a></li>
<li><a>Dvices</a></li>
<li><a>Error Handling</a></li>
<li><a>Examples</a></li>
</ul>
What is ESP-AT?
The <a>ESP-AT firmware</a> is an official firmware provided by Espressif Systems for their ESP8266 and ESP32 series of microcontrollers. It transforms the ESP module into a device that can be controlled via standard AT commands over a serial interface.
AT commands, which are simple text-based instructions, enable the configuration and operation of the ESP module without requiring the user to write custom firmware. These commands can be used to perform tasks such as:
<code>Configuring Wi-Fi connections (e.g., connecting to an access point or setting up as a Wi-Fi hotspot)
Sending and receiving data over TCP/UDP or HTTP protocols
Managing low-power modes
Accessing additional features, like Bluetooth (on ESP32) or GPIO control
</code>
The ESP-AT firmware is particularly suitable for applications where the ESP chip is used as a peripheral communication module controlled by another host device, such as a microcontroller or a computer. By using this firmware, developers can focus on the integration and higher-level functionalities of their system without delving into the complexities of programming the ESP chip itself.
How this driver works
This driver is made in a modular way, where parse of AT commands (Runner) are separated from the device features (Devices)
Allowing the user to choose between the implementations they want to use without additional memory cost
Porting
To start using this driver it is necessary to create a runner to communicate with the ESP, this can be done with the: <code>StandartRunner.runner(Config)</code>
<code>Config</code> is a struct that defines the inner workings of the driver, it contains the following fields:
- <code>RX_size</code>: input buffer size, minimum: 128 bytes, default value: 2046 bytes.
- <code>TX_event_pool</code>: Event buffer size, minimum: 10 events, default value: 25.
- <code>network_recv_size</code>: Network buffer size, minimum: 128 bytes, default value: 2046 bytes.
with the type created, just initialize it with: <code>init(TX_callback,RX_callback, user_data)</code>
<ul>
<li>
<code>TX_callback(data: []const u8, user_data: ?*anyopaque) void</code>: This function is responsible for sending the driver data to the module.
<ul>
<li>
<code>data</code>: a slice containing the bytes that need to be sent to the module, note: you don't need to send all the data at once.
</li>
<li>
<code>user_data</code>: An optional pointer to a user parameter
</li>
<li>
<code>Returns</code>: <code>Void</code>
</li>
</ul>
</li>
<li>
<code>RX_callback(free_size: usize, user_data: ?*anyopaque) []const u8</code>: This is an optional function used by the driver to request information.
<ul>
<li>
<code>free_size</code>: count of bytes that the driver can read, you can return any amount of bytes as long as it does not exceed that value (additional data will be lost)
</li>
<li>
<code>user_data</code>: An optional pointer to a user parameter
</li>
<li>
<code>returns</code>: a slice containing the read bytes, this slice must live until the next call of this function, after which it can be released
</li>
</ul>
</li>
<li>
<code>user_data</code>: An optional pointer to a user parameter for TX and RX callbacks
</li>
</ul>
Once the driver type is initialized, the first thing you should do is call the function: <code>init_driver()</code>, This function will clear any commands in the event queue and load the driver's startup sequence. To safely turn off the driver, use: <code>deinit_driver()</code>
To initialize the event loop, you should call the function <code>process()</code> periodically. This function returns internal driver errors.[TODO: Error Handling DOC]
Alternatively you can use the function: <code>feed([]const u8)</code> to notify data to the driver and leave RX_callback as null,In this case, it is not necessary to call <code>process()</code> periodically, before sending any data using this function it is necessary to check the amount of bytes available in the input buffer with: <code>get_rx_free_space()</code>
<code>feed</code> returns the amount of bytes saved in the buffer
<strong>Generic example</strong>:
```zig
const Driver = @import("ESPAT");
const StandartRunner = Driver.StandartRunner
fn TX_callback(data: []const u8, user_data: ?<em>anyopaque) <code>void</code> {
if (user_data) |userdata| {
const serial: </em>serial_type = @ptrCast(@alignCast(userdata));
serial.write(data);
}
}
var foo_buf: [4096]u8 = undefined;
fn rx_callback(free_size: usize, user_data: ?<em>anyopaque) []u8 {
var bytes_read: usize = 0;
if (user_data) |userdata| {
const serial: </em>serial_type = @ptrCast(@alignCast(userdata));
bytes_read = serial.read(foo_buf[0..free_size]);
}
return foo_buf[0..bytes_read];
}
fn main() !<code>void</code> {
var serial = Serial.lib;
var driver = StandartRunner.Runner(.{}).init(TX_callback, rx_callback, &serial);
defer driver.deinit_driver();
try driver.init_driver()
while(true){
my_drive.process() catch |err| {
_ = std.log.err("Driver got error: {}", .{err});
};
}
}
```
TODO: microzig port example
Devices
<ul>
<li><a>WiFi</a></li>
<li><a>Network</a></li>
<li><a>HTTP CLient</a></li>
</ul>
Examples:
complete example code:
<ul>
<li>
<a>Generic port</a>
</li>
<li>
<a>ESP8266 Support</a>
</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/124217829?v=4 | zig-epub | javiorfo/zig-epub | 2025-01-16T02:07:28Z | Minimal Zig library for creating EPUB 2.1 files | master | 0 | 5 | 1 | 5 | https://api.github.com/repos/javiorfo/zig-epub/tags | MIT | [
"epub",
"epub-library",
"zig",
"zig-library",
"zig-package"
] | 54 | false | 2025-04-21T19:45:33Z | true | true | 0.13.0 | github | [] | zig-epub
<em>Minimal Zig library for creating EPUB files</em>
Caveats
<ul>
<li>C libs dependencies: <a>libzip 1.11.2</a> </li>
<li>Required Zig version: <strong>0.13</strong></li>
<li>Epub version: <code>2.0.1</code></li>
<li>This library has been developed on and for <code>Linux</code> following open source philosophy.</li>
</ul>
Overview
This library will generate an epub with the following compressed files:
- <strong>META-INF/</strong>
- <strong>container.xml</strong>
- <strong>OEBPS/</strong>
- <strong>images/</strong>
- <strong>some_image.png</strong>
- <strong>toc.ncx</strong>
- <strong>content.opf</strong>
- <strong>SomeChapter.xhtml</strong>
- <strong>stylesheet.css</strong>
- <strong>mimetype</strong>
Usage
<ul>
<li>Simple example. More <a>examples here</a>
```zig
const std = @import("std");
const epub = @import("epub");</li>
</ul>
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit() != .ok) @panic("leak");
const allocator = gpa.allocator();
<code>var my_epub = epub.Epub.init(allocator, .{
.title = "Flying Circus",
.creator = "Johann Gambolputty",
.identifier = .{
.identifier_type = .UUID,
.value = "d5b2b585-566a-4b9c-9c5d-f99436e3a588",
},
});
defer my_epub.deinit();
var image_paths = [_][]const u8{
"/home/user/Downloads/image.jpg",
"/home/user/Downloads/image2.png",
};
var section = epub.Section.init(allocator, "Chapter 1", .{ .raw = "<h1>Chapter 1</h1>\n<p>Hello</p>\n<h1 id=\"chapter1.1\">Chapter 1.1</h1>" });
defer section.deinit();
try my_epub
.setStylesheet(.{ .raw = "body { background-color: #000000 }" })
.setCoverImage(.{ .path = "/home/user/Downloads/cats.jpg", .image_type = .jpg })
.setImages(&image_paths)
.setCover(.{ .raw = "<div class=\"cover\"><img src=\"images/cats.jpg\" alt=\"Cover Image\"/></div>" })
.addSectionType("Preface", .{ .raw = "<p>preface</p>\n" }, .Preface)
.add(section.addToc(.{ .text = "Chapter 1.1", .reference_id = "chapter1.1" }).build())
.addSection("Chapter 2", .{ .raw = "<h1>Chapter 2</h1>\n<p>Bye</p>\n" })
.generate("book.epub"); // This could be a existent path to some folder (absolute or relative). Ex: "/path/to/book.epub"
</code>
}
```
Some info
<ul>
<li>Only one level of subsection is available when using Table of Contents at the moment. Ex: Chapter 1 -> Chapter 1.1, Chapter 1.2, etc.</li>
<li>An Epub is just a compressed file. Using a tool like <code>unzip</code> or similar could be useful to see the content and files generated.</li>
<li>Every <strong>xhtml</strong> (cover and sections) will have the <strong></strong> tag with an id formed by the name of the section without spaces plus <strong>-body</strong>. Helpful when using some <strong>css</strong> on it.<ul>
<li>Ex: Section named "Chapter 1" will have <code><body id="Chapter1-body"></code></li>
</ul>
</li>
</ul>
Installation
In <code>build.zig.zon</code>:
<code>zig
.dependencies = .{
.epub = .{
.url = "https://github.com/javiorfo/zig-epub/archive/refs/heads/master.tar.gz",
// .hash = "hash suggested",
// the hash will be suggested by zig build
},
}</code>
In <code>build.zig</code>:
```zig
const dep = b.dependency("epub", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("epub", dep.module("epub"));
exe.linkLibC();
exe.linkSystemLibrary("zip");
```
Donate
<ul>
<li><strong>Bitcoin</strong> <a>(QR)</a> <code>1GqdJ63RDPE4eJKujHi166FAyigvHu5R7v</code></li>
<li><a>Paypal</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | nativefiledialog-extended | allyourcodebase/nativefiledialog-extended | 2024-08-15T14:26:36Z | nativefiledialog-extended ported to the zig build system | master | 0 | 5 | 1 | 5 | https://api.github.com/repos/allyourcodebase/nativefiledialog-extended/tags | MIT | [
"zig",
"zig-package"
] | 10 | false | 2025-04-11T16:49:22Z | true | true | 0.14.0 | github | [] | <a></a>
nativefiledialog-extended
This is <a>nativefiledialog-extended</a>, packaged for <a>Zig</a>.
Installation
First, update your <code>build.zig.zon</code>:
```
Initialize a <code>zig build</code> project if you haven't already
zig init
zig fetch --save git+https://github.com/allyourcodebase/nativefiledialog-extended.git#1.2.1-2
```
You can then import <code>nativefiledialog-extended</code> in your <code>build.zig</code> with:
<code>zig
const nfd_dependency = b.dependency("nativefiledialog-extended", .{
.target = target,
.optimize = optimize,
});
your_exe.linkLibrary(nfd_dependency.artifact("nfd"));</code>
Dependencies
See https://github.com/btzy/nativefiledialog-extended/tree/v1.2.1#dependencies | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.