avatar_url stringlengths 46 53 | name stringlengths 2 33 | full_name stringlengths 8 45 | created_at stringdate 2018-01-12 15:05:58 2025-05-18 21:51:14 | description stringlengths 7 327 ⌀ | default_branch stringclasses 11
values | open_issues int64 0 156 | stargazers_count int64 0 3.96k | forks_count int64 0 182 | watchers_count int64 0 3.96k | tags_url stringlengths 42 79 | license stringclasses 20
values | topics listlengths 0 18 | size int64 0 760k | fork bool 2
classes | updated_at stringdate 2021-04-12 07:17:39 2025-05-22 07:54:00 | has_build_zig bool 2
classes | has_build_zig_zon bool 2
classes | zig_minimum_version stringclasses 35
values | repo_from stringclasses 1
value | dependencies listlengths 0 121 | readme_content stringlengths 3 96.8k | dependents listlengths 0 21 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://avatars.githubusercontent.com/u/3759175?v=4 | zig-clap | Hejsil/zig-clap | 2018-03-14T13:06:16Z | Command line argument parsing library | master | 9 | 1,240 | 75 | 1,240 | https://api.github.com/repos/Hejsil/zig-clap/tags | MIT | [
"argument-parser",
"argument-parsing",
"command-line",
"command-line-parser",
"parsed-arguments",
"zig-package",
"ziglang"
] | 456 | false | 2025-05-21T11:29:52Z | true | true | 0.14.0 | github | [] | zig-clap
A simple and easy to use command line argument parser library for Zig.
Installation
Developers tend to either use
* The latest tagged release of Zig
* The latest build of Zigs master branch
Depending on which developer you are, you need to run different <code>zig fetch</code> commands:
```sh
Version of zig-clap that works with a tagged release of Zig
Replace <code><REPLACE ME></code> with the version of zig-clap that you want to use
See: https://github.com/Hejsil/zig-clap/releases
zig fetch --save https://github.com/Hejsil/zig-clap/archive/refs/tags/.tar.gz
Version of zig-clap that works with latest build of Zigs master branch
zig fetch --save git+https://github.com/Hejsil/zig-clap
```
Then add the following to <code>build.zig</code>:
<code>zig
const clap = b.dependency("clap", .{});
exe.root_module.addImport("clap", clap.module("clap"));</code>
Features
<ul>
<li>Short arguments <code>-a</code></li>
<li>Chaining <code>-abc</code> where <code>a</code> and <code>b</code> does not take values.</li>
<li>Multiple specifications are tallied (e.g. <code>-v -v</code>).</li>
<li>Long arguments <code>--long</code></li>
<li>Supports both passing values using spacing and <code>=</code> (<code>-a 100</code>, <code>-a=100</code>)</li>
<li>Short args also support passing values with no spacing or <code>=</code> (<code>-a100</code>)</li>
<li>This all works with chaining (<code>-ba 100</code>, <code>-ba=100</code>, <code>-ba100</code>)</li>
<li>Supports options that can be specified multiple times (<code>-e 1 -e 2 -e 3</code>)</li>
<li>Print help message from parameter specification.</li>
<li>Parse help message to parameter specification.</li>
</ul>
API Reference
Automatically generated API Reference for the project can be found at
https://Hejsil.github.io/zig-clap. Note that Zig autodoc is in beta; the website
may be broken or incomplete.
Examples
<code>clap.parse</code>
The simplest way to use this library is to just call the <code>clap.parse</code> function.
```zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>// First we specify what parameters our program can take.
// We can use `parseParamsComptime` to parse a string into an array of `Param(Help)`.
const params = comptime clap.parseParamsComptime(
\\-h, --help Display this help and exit.
\\-n, --number <usize> An option parameter, which takes a value.
\\-s, --string <str>... An option parameter which can be specified multiple times.
\\<str>...
\\
);
// Initialize our diagnostics, which can be used for reporting useful errors.
// This is optional. You can also pass `.{}` to `clap.parse` if you don't
// care about the extra information `Diagnostics` provides.
var diag = clap.Diagnostic{};
var res = clap.parse(clap.Help, &params, clap.parsers.default, .{
.diagnostic = &diag,
.allocator = gpa.allocator(),
}) catch |err| {
// Report useful error and exit.
diag.report(std.io.getStdErr().writer(), err) catch {};
return err;
};
defer res.deinit();
if (res.args.help != 0)
std.debug.print("--help\n", .{});
if (res.args.number) |n|
std.debug.print("--number = {}\n", .{n});
for (res.args.string) |s|
std.debug.print("--string = {s}\n", .{s});
for (res.positionals[0]) |pos|
std.debug.print("{s}\n", .{pos});
</code>
}
const clap = @import("clap");
const std = @import("std");
```
The result will contain an <code>args</code> field and a <code>positionals</code> field. <code>args</code> will have one field for
each non-positional parameter of your program. The name of the field will be the longest name of the
parameter. <code>positionals</code> will be a tuple with one field for each positional parameter.
The fields in <code>args</code> and <code>postionals</code> are typed. The type is based on the name of the value the
parameter takes. Since <code>--number</code> takes a <code>usize</code> the field <code>res.args.number</code> has the type <code>usize</code>.
Note that this is only the case because <code>clap.parsers.default</code> has a field called <code>usize</code> which
contains a parser that returns <code>usize</code>. You can pass in something other than <code>clap.parsers.default</code>
if you want some other mapping.
```zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>// First we specify what parameters our program can take.
// We can use `parseParamsComptime` to parse a string into an array of `Param(Help)`.
const params = comptime clap.parseParamsComptime(
\\-h, --help Display this help and exit.
\\-n, --number <INT> An option parameter, which takes a value.
\\-a, --answer <ANSWER> An option parameter which takes an enum.
\\-s, --string <STR>... An option parameter which can be specified multiple times.
\\<FILE>...
\\
);
// Declare our own parsers which are used to map the argument strings to other
// types.
const YesNo = enum { yes, no };
const parsers = comptime .{
.STR = clap.parsers.string,
.FILE = clap.parsers.string,
.INT = clap.parsers.int(usize, 10),
.ANSWER = clap.parsers.enumeration(YesNo),
};
var diag = clap.Diagnostic{};
var res = clap.parse(clap.Help, &params, parsers, .{
.diagnostic = &diag,
.allocator = gpa.allocator(),
// The assignment separator can be configured. `--number=1` and `--number:1` is now
// allowed.
.assignment_separators = "=:",
}) catch |err| {
diag.report(std.io.getStdErr().writer(), err) catch {};
return err;
};
defer res.deinit();
if (res.args.help != 0)
std.debug.print("--help\n", .{});
if (res.args.number) |n|
std.debug.print("--number = {}\n", .{n});
if (res.args.answer) |a|
std.debug.print("--answer = {s}\n", .{@tagName(a)});
for (res.args.string) |s|
std.debug.print("--string = {s}\n", .{s});
for (res.positionals[0]) |pos|
std.debug.print("{s}\n", .{pos});
</code>
}
const clap = @import("clap");
const std = @import("std");
```
Subcommands
There is an option for <code>clap.parse</code> and <code>clap.parseEx</code> called <code>terminating_positional</code>. It allows
for users of <code>clap</code> to implement subcommands in their cli application:
```zig
// These are our subcommands.
const SubCommands = enum {
help,
math,
};
const main_parsers = .{
.command = clap.parsers.enumeration(SubCommands),
};
// The parameters for <code>main</code>. Parameters for the subcommands are specified further down.
const main_params = clap.parseParamsComptime(
\-h, --help Display this help and exit.
\
\
);
// To pass around arguments returned by clap, <code>clap.Result</code> and <code>clap.ResultEx</code> can be used to
// get the return type of <code>clap.parse</code> and <code>clap.parseEx</code>.
const MainArgs = clap.ResultEx(clap.Help, &main_params, main_parsers);
pub fn main() !void {
var gpa_state = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = gpa_state.allocator();
defer _ = gpa_state.deinit();
<code>var iter = try std.process.ArgIterator.initWithAllocator(gpa);
defer iter.deinit();
_ = iter.next();
var diag = clap.Diagnostic{};
var res = clap.parseEx(clap.Help, &main_params, main_parsers, &iter, .{
.diagnostic = &diag,
.allocator = gpa,
// Terminate the parsing of arguments after parsing the first positional (0 is passed
// here because parsed positionals are, like slices and arrays, indexed starting at 0).
//
// This will terminate the parsing after parsing the subcommand enum and leave `iter`
// not fully consumed. It can then be reused to parse the arguments for subcommands.
.terminating_positional = 0,
}) catch |err| {
diag.report(std.io.getStdErr().writer(), err) catch {};
return err;
};
defer res.deinit();
if (res.args.help != 0)
std.debug.print("--help\n", .{});
const command = res.positionals[0] orelse return error.MissingCommand;
switch (command) {
.help => std.debug.print("--help\n", .{}),
.math => try mathMain(gpa, &iter, res),
}
</code>
}
fn mathMain(gpa: std.mem.Allocator, iter: *std.process.ArgIterator, main_args: MainArgs) !void {
// The parent arguments are not used here, but there are cases where it might be useful, so
// this example shows how to pass the arguments around.
_ = main_args;
<code>// The parameters for the subcommand.
const params = comptime clap.parseParamsComptime(
\\-h, --help Display this help and exit.
\\-a, --add Add the two numbers
\\-s, --sub Subtract the two numbers
\\<isize>
\\<isize>
\\
);
// Here we pass the partially parsed argument iterator.
var diag = clap.Diagnostic{};
var res = clap.parseEx(clap.Help, &params, clap.parsers.default, iter, .{
.diagnostic = &diag,
.allocator = gpa,
}) catch |err| {
diag.report(std.io.getStdErr().writer(), err) catch {};
return err;
};
defer res.deinit();
const a = res.positionals[0] orelse return error.MissingArg1;
const b = res.positionals[1] orelse return error.MissingArg1;
if (res.args.help != 0)
std.debug.print("--help\n", .{});
if (res.args.add != 0)
std.debug.print("added: {}\n", .{a + b});
if (res.args.sub != 0)
std.debug.print("subtracted: {}\n", .{a - b});
</code>
}
const clap = @import("clap");
const std = @import("std");
```
<code>streaming.Clap</code>
The <code>streaming.Clap</code> is the base of all the other parsers. It's a streaming parser that uses an
<code>args.Iterator</code> to provide it with arguments lazily.
```zig
pub fn main() !void {
const allocator = std.heap.page_allocator;
<code>// First we specify what parameters our program can take.
const params = [_]clap.Param(u8){
.{
.id = 'h',
.names = .{ .short = 'h', .long = "help" },
},
.{
.id = 'n',
.names = .{ .short = 'n', .long = "number" },
.takes_value = .one,
},
.{ .id = 'f', .takes_value = .one },
};
var iter = try std.process.ArgIterator.initWithAllocator(allocator);
defer iter.deinit();
// Skip exe argument.
_ = iter.next();
// Initialize our diagnostics, which can be used for reporting useful errors.
// This is optional. You can also leave the `diagnostic` field unset if you
// don't care about the extra information `Diagnostic` provides.
var diag = clap.Diagnostic{};
var parser = clap.streaming.Clap(u8, std.process.ArgIterator){
.params = &params,
.iter = &iter,
.diagnostic = &diag,
};
// Because we use a streaming parser, we have to consume each argument parsed individually.
while (parser.next() catch |err| {
// Report useful error and exit.
diag.report(std.io.getStdErr().writer(), err) catch {};
return err;
}) |arg| {
// arg.param will point to the parameter which matched the argument.
switch (arg.param.id) {
'h' => std.debug.print("Help!\n", .{}),
'n' => std.debug.print("--number = {s}\n", .{arg.value.?}),
// arg.value == null, if arg.param.takes_value == .none.
// Otherwise, arg.value is the value passed with the argument, such as "-a=10"
// or "-a 10".
'f' => std.debug.print("{s}\n", .{arg.value.?}),
else => unreachable,
}
}
</code>
}
const clap = @import("clap");
const std = @import("std");
```
Currently, this parser is the only parser that allows an array of <code>Param</code> that is generated at runtime.
<code>help</code>
<code>help</code> prints a simple list of all parameters the program can take. It expects the <code>Id</code> to have a
<code>description</code> method and an <code>value</code> method so that it can provide that in the output. <code>HelpOptions</code>
is passed to <code>help</code> to control how the help message is printed.
```zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const params = comptime clap.parseParamsComptime(
\\-h, --help Display this help and exit.
\\-v, --version Output version information and exit.
\\
);
var res = try clap.parse(clap.Help, &params, clap.parsers.default, .{
.allocator = gpa.allocator(),
});
defer res.deinit();
// `clap.help` is a function that can print a simple help message. It can print any `Param`
// where `Id` has a `description` and `value` method (`Param(Help)` is one such parameter).
// The last argument contains options as to how `help` should print those parameters. Using
// `.{}` means the default options.
if (res.args.help != 0)
return clap.help(std.io.getStdErr().writer(), clap.Help, &params, .{});
</code>
}
const clap = @import("clap");
const std = @import("std");
```
```
$ zig-out/bin/help --help
-h, --help
Display this help and exit.
<code>-v, --version
Output version information and exit.
</code>
```
<code>usage</code>
<code>usage</code> prints a small abbreviated version of the help message. It expects the <code>Id</code> to have a
<code>value</code> method so it can provide that in the output.
```zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const params = comptime clap.parseParamsComptime(
\\-h, --help Display this help and exit.
\\-v, --version Output version information and exit.
\\ --value <str> An option parameter, which takes a value.
\\
);
var res = try clap.parse(clap.Help, &params, clap.parsers.default, .{
.allocator = gpa.allocator(),
});
defer res.deinit();
// `clap.usage` is a function that can print a simple help message. It can print any `Param`
// where `Id` has a `value` method (`Param(Help)` is one such parameter).
if (res.args.help != 0)
return clap.usage(std.io.getStdErr().writer(), clap.Help, &params);
</code>
}
const clap = @import("clap");
const std = @import("std");
```
<code>$ zig-out/bin/usage --help
[-hv] [--value <str>]</code> | [
"https://github.com/paoda/bp-jit",
"https://github.com/paoda/turbo",
"https://github.com/paoda/zba"
] |
https://avatars.githubusercontent.com/u/1699414?v=4 | sokol-zig | floooh/sokol-zig | 2018-05-31T17:10:41Z | Zig bindings for the sokol headers (https://github.com/floooh/sokol) | master | 10 | 513 | 66 | 513 | https://api.github.com/repos/floooh/sokol-zig/tags | Zlib | [
"crossplatform",
"sokol",
"zig",
"zig-package"
] | 3,194 | false | 2025-05-21T16:08:15Z | true | true | 0.14.0 | github | [
{
"commit": "4.0.3",
"name": "emsdk",
"tar_url": "https://github.com/emscripten-core/emsdk/archive/4.0.3.tar.gz",
"type": "remote",
"url": "https://github.com/emscripten-core/emsdk"
},
{
"commit": "9b5a3e2b57fe9783ba4d1f3249059bc4720b592f",
"name": "shdc",
"tar_url": "https://git... | <a></a><a></a>
Auto-generated Zig bindings for the <a>sokol headers</a>.
<a>Auto-generated docs</a> (wip)
For Zig version 0.14.0+
In case of breaking changes in Zig, the bindings might fall behind. Please don't hesitate to
ping me via a Github issue, or even better, provide a PR :)
Support for stable Zig versions is in branches (e.g. <code>zig-0.12.0</code>), those versions are 'frozen in time' though.
Related projects:
<ul>
<li><a>pacman.zig</a></li>
<li><a>chipz emulators</a></li>
<li><a>Dear ImGui sample project</a></li>
</ul>
Building the samples
Supported platforms are: Windows, macOS, Linux (with X11) and web
On Linux install the following packages: libglu1-mesa-dev, mesa-common-dev, xorg-dev, libasound-dev
(or generally: the dev packages required for X11, GL and ALSA development)
To build the platform-native samples:
```sh
build all examples:
zig build examples
build and run individual examples
zig build run-clear
zig build run-triangle
zig build run-quad
zig build run-bufferoffsets
zig build run-cube
zig build run-noninterleaved
zig build run-texcube
zig build run-offscreen
zig build run-instancing
zig build run-mrt
zig build run-saudio
zig build run-sgl
zig build run-sgl-context
zig build run-sgl-points
zig build run-debugtext
zig build run-debugtext-print
zig build run-debugtext-userfont
zig build run-shapes
```
(also run <code>zig build -l</code> to get a list of build targets)
By default, the backend 3D API will be selected based on the target platform:
<ul>
<li>macOS: Metal</li>
<li>Windows: D3D11</li>
<li>Linux: GL</li>
</ul>
To force the GL backend on macOS or Windows, build with <code>-Dgl=true</code>:
```
<blockquote>
zig build -Dgl=true run-clear
```
</blockquote>
The <code>clear</code> sample prints the selected backend to the terminal:
<code>sokol-zig ➤ zig build -Dgl=true run-clear
Backend: .sokol.gfx.Backend.GLCORE33</code>
For the web-samples, run:
```sh
zig build examples -Dtarget=wasm32-emscripten
or to build and run one of the samples
zig build run-clear -Dtarget=wasm32-emscripten
...
```
When building with target <code>wasm32-emscripten</code> for the first time, the build script will
install and activate the Emscripten SDK into the Zig package cache for the latest SDK
version. There is currently no build system functionality to update or delete the Emscripten SDK
after this first install. The current workaround is to delete the global Zig cache
(run <code>zig env</code> to see where the Zig cache resides).
Improving the Emscripten SDK integration with the Zig build system is planned for the future.
How to integrate sokol-zig into your project
Add a build.zig.zon file to your project which has at least a <code>.sokol</code> dependency:
<code>zig
.{
.name = "my_project",
.version = "0.1.0",
.paths = .{
"src",
"build.zig",
"build.zig.zon",
},
.dependencies = .{
.sokol = .{
.url = "git+https://github.com/floooh/sokol-zig.git#[commit-hash]",
.hash = "[content-hash]",
},
},
}</code>
The easiest way to populate or update the <code>sokol</code> dependency is to run this on the cmdline:
<code>zig fetch --save=sokol git+https://github.com/floooh/sokol-zig.git</code>
This will automatically use the latest sokol-zig commit.
For a native-only project, a <code>build.zig</code> file looks entirely vanilla:
```zig
const std = @import("std");
const Build = std.Build;
const OptimizeMode = std.builtin.OptimizeMode;
pub fn build(b: *Build) !void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const dep_sokol = b.dependency("sokol", .{
.target = target,
.optimize = optimize,
});
const hello = b.addExecutable(.{
.name = "hello",
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/hello.zig"),
});
hello.root_module.addImport("sokol", dep_sokol.module("sokol"));
b.installArtifact(hello);
const run = b.addRunArtifact(hello);
b.step("run", "Run hello").dependOn(&run.step);
}
```
If you also want to run on the web via <code>-Dtarget=wasm32-emscripten</code>, the web platform
build must look special, because Emscripten must be used for linking, and to run
the build result in a browser, a special run step must be created.
Such a 'hybrid' build script might look like this (copied straight from <a>pacman.zig</a>):
```zig
const std = @import("std");
const Build = std.Build;
const OptimizeMode = std.builtin.OptimizeMode;
const sokol = @import("sokol");
pub fn build(b: *Build) !void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const dep_sokol = b.dependency("sokol", .{
.target = target,
.optimize = optimize,
});
<code>// special case handling for native vs web build
if (target.result.cpu.arch.isWasm()) {
try buildWeb(b, target, optimize, dep_sokol);
} else {
try buildNative(b, target, optimize, dep_sokol);
}
</code>
}
// this is the regular build for all native platforms, nothing surprising here
fn buildNative(b: <em>Build, target: Build.ResolvedTarget, optimize: OptimizeMode, dep_sokol: </em>Build.Dependency) !void {
const pacman = b.addExecutable(.{
.name = "pacman",
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/pacman.zig"),
});
pacman.root_module.addImport("sokol", dep_sokol.module("sokol"));
b.installArtifact(pacman);
const run = b.addRunArtifact(pacman);
b.step("run", "Run pacman").dependOn(&run.step);
}
// for web builds, the Zig code needs to be built into a library and linked with the Emscripten linker
fn buildWeb(b: <em>Build, target: Build.ResolvedTarget, optimize: OptimizeMode, dep_sokol: </em>Build.Dependency) !void {
const pacman = b.addStaticLibrary(.{
.name = "pacman",
.target = target,
.optimize = optimize,
.root_source_file = b.path("src/pacman.zig"),
});
pacman.root_module.addImport("sokol", dep_sokol.module("sokol"));
<code>// create a build step which invokes the Emscripten linker
const emsdk = dep_sokol.builder.dependency("emsdk", .{});
const link_step = try sokol.emLinkStep(b, .{
.lib_main = pacman,
.target = target,
.optimize = optimize,
.emsdk = emsdk,
.use_webgl2 = true,
.use_emmalloc = true,
.use_filesystem = false,
.shell_file_path = dep_sokol.path("src/sokol/web/shell.html"),
});
// attach Emscripten linker output to default install step
b.getInstallStep().dependOn(&link_step.step);
// ...and a special run step to start the web build output via 'emrun'
const run = sokol.emRunStep(b, .{ .name = "pacman", .emsdk = emsdk });
run.step.dependOn(&link_step.step);
b.step("run", "Run pacman").dependOn(&run.step);
</code>
}
```
Using sokol headers in C code
The sokol-zig build.zig exposes a C library artifact called <code>sokol_clib</code>.
You can lookup the build step for this library via:
<code>zig
const dep_sokol = b.dependency("sokol", .{
.target = target,
.optimize = optimize,
});
const sokol_clib = dep_sokol.artifact("sokol_clib");</code>
...once you have that library artifact, 'link' it to your compile step which contains
your own C code:
<code>zig
const my_clib = ...;
my_clib.linkLibrary(sokol_clib);</code>
This makes the Sokol C headers available to your C code in a <code>sokol/</code> subdirectory:
```c
include "sokol/sokol_app.h"
include "sokol/sokol_gfx.h"
// etc...
```
Keep in mind that the implementation is already provided in the <code>sokol_clib</code>
static link library (e.g. don't try to build the Sokol implementations yourself
via the <code>SOKOL_IMPL</code> macro).
wasm32-emscripten caveats
<ul>
<li>Zig allocators use the <code>@returnAddress</code> builtin, which isn't supported in the Emscripten
runtime out of the box (you'll get a runtime error in the browser's Javascript console
looking like this: <code>Cannot use convertFrameToPC (needed by __builtin_return_address) without -sUSE_OFFSET_CONVERTER</code>.
To link with <code>-sUSE_OFFSET_CONVERTER</code>, simply set the <code>.use_offset_converter</code> option
in the Emscripten linker step in your build.zig:</li>
</ul>
<code>zig
const link_step = try sokol.emLinkStep(b, .{
// ...other settings here
.use_offset_converter = true,
});</code>
<ul>
<li>the Zig stdlib only has limited support for the <code>wasm32-emscripten</code>
target, for instance using <code>std.fs</code> functions will most likely fail
to compile (the sokol-zig bindings might add more sokol headers
in the future to fill some of the gaps)</li>
</ul>
Dear ImGui support
The sokol-zig bindings come with sokol_imgui.h (exposed as the Zig package
<code>sokol.imgui</code>), but integration into a project's build.zig requires some extra
steps, mainly because I didn't want to add a
<a>cimgui</a> dependency to the sokol-zig package
(especially since cimgui uses git submodule which are not supported by the Zig
package manager).
The main steps to create Dear ImGui apps with sokol-zig are:
<ol>
<li>'bring your own cimgui'</li>
<li>tell the sokol dependency that it needs to include sokol_imgui.h into
the compiled C library:
<code>zig
const dep_sokol = b.dependency("sokol", .{
.target = target,
.optimize = optimize,
.with_sokol_imgui = true,
});</code></li>
<li>
inject the path to the cimgui directory into the sokol dependency so
that C compilation works (this needs to find the <code>cimgui.h</code> header)
<code>zig
dep_sokol.artifact("sokol_clib").addIncludePath(cimgui_root);</code>
</li>
</ol>
Also see the following example project:
https://github.com/floooh/sokol-zig-imgui-sample/ | [] |
https://avatars.githubusercontent.com/u/3759175?v=4 | zig-bench | Hejsil/zig-bench | 2018-12-05T09:26:06Z | Simple benchmarking library | master | 2 | 64 | 8 | 64 | https://api.github.com/repos/Hejsil/zig-bench/tags | MIT | [
"benchmarking",
"zig",
"zig-package"
] | 41 | false | 2025-05-13T04:06:33Z | false | false | unknown | github | [] | zig-bench
A simple benchmarking lib in Zig
```
Test [0/2] test "Debug benchmark"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_slice(block=16) 100000 90 2690 243 107
sum_slice(block=32) 100000 170 1760 338 190
sum_slice(block=64) 100000 320 2340 476 352
sum_slice(block=128) 100000 630 2290 862 678
sum_slice(block=256) 100000 1270 3170 2402 1336
sum_slice(block=512) 100000 2550 8490 4835 2651
sum_reader(block=16) 100000 990 2640 1592 1039
sum_reader(block=32) 100000 1930 3890 3292 2012
sum_reader(block=64) 100000 3830 6250 6806 3962
sum_reader(block=128) 63673 7660 12830 15703 7852
sum_reader(block=256) 31967 15360 22190 31847 15641
sum_reader(block=512) 16031 30800 34690 59444 31191
Test [1/2] test "Debug benchmark generics"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_vectors(vec4f16) 100000 2730 13390 3620 2775
sum_vectors(vec4f32) 100000 1289 5800 1277 1296
sum_vectors(vec4f64) 100000 1389 6870 1358 1400
sum_vectors(vec8f16) 100000 4400 9680 4613 4479
sum_vectors(vec8f32) 100000 1389 5180 1231 1400
sum_vectors(vec8f64) 100000 1390 6170 2260 1457
sum_vectors(vec16f16) 61088 8090 13980 15455 8184
sum_vectors(vec16f32) 100000 1399 4560 2069 1441
sum_vectors(vec16f64) 100000 1440 6080 1664 1475
All 2 tests passed.
Test [0/2] test "ReleaseSafe benchmark"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_slice(block=16) 100000 9 3550 164 18
sum_slice(block=32) 100000 9 940 22 18
sum_slice(block=64) 100000 49 1530 66 52
sum_slice(block=128) 100000 89 1280 102 92
sum_slice(block=256) 100000 169 1690 210 171
sum_slice(block=512) 100000 319 5530 724 329
sum_reader(block=16) 100000 60 2840 180 69
sum_reader(block=32) 100000 110 3059 288 121
sum_reader(block=64) 100000 209 2810 323 224
sum_reader(block=128) 100000 400 1780 387 431
sum_reader(block=256) 100000 790 2220 681 843
sum_reader(block=512) 100000 1550 4300 3805 1669
Test [1/2] test "ReleaseSafe benchmark generics"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_vectors(vec4f16) 100000 1269 3790 1799 1283
sum_vectors(vec4f32) 100000 319 1680 300 328
sum_vectors(vec4f64) 100000 319 1860 355 329
sum_vectors(vec8f16) 100000 2399 5010 5014 2420
sum_vectors(vec8f32) 100000 319 2660 641 329
sum_vectors(vec8f64) 100000 319 7740 1019 330
sum_vectors(vec16f16) 100000 4599 9970 22580 4636
sum_vectors(vec16f32) 100000 319 4310 1231 330
sum_vectors(vec16f64) 100000 429 4070 1783 439
All 2 tests passed.
Test [0/2] test "ReleaseFast benchmark"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_slice(block=16) 100000 19 2840 128 21
sum_slice(block=32) 100000 19 1600 78 20
sum_slice(block=64) 100000 19 1970 74 21
sum_slice(block=128) 100000 19 1530 68 21
sum_slice(block=256) 100000 39 1250 74 44
sum_slice(block=512) 100000 59 1150 85 68
sum_reader(block=16) 100000 19 1170 21 20
sum_reader(block=32) 100000 19 1650 74 20
sum_reader(block=64) 100000 19 1250 34 20
sum_reader(block=128) 100000 19 1240 32 20
sum_reader(block=256) 100000 39 2180 177 44
sum_reader(block=512) 100000 59 2470 148 68
Test [1/2] test "ReleaseFast benchmark generics"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_vectors(vec4f16) 100000 1259 8590 1678 1284
sum_vectors(vec4f32) 100000 319 1440 279 327
sum_vectors(vec4f64) 100000 319 1760 303 327
sum_vectors(vec8f16) 100000 2399 5260 1861 2417
sum_vectors(vec8f32) 100000 319 2080 434 327
sum_vectors(vec8f64) 100000 319 1710 329 328
sum_vectors(vec16f16) 100000 4599 9010 3883 4634
sum_vectors(vec16f32) 100000 319 2800 356 329
sum_vectors(vec16f64) 100000 429 1750 404 436
All 2 tests passed.
Test [0/2] test "ReleaseSmall benchmark"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_slice(block=16) 100000 19 2760 247 27
sum_slice(block=32) 100000 29 5090 363 37
sum_slice(block=64) 100000 50 2640 177 63
sum_slice(block=128) 100000 90 1830 157 102
sum_slice(block=256) 100000 169 5860 733 201
sum_slice(block=512) 100000 330 3690 1560 365
sum_reader(block=16) 100000 219 1430 276 226
sum_reader(block=32) 100000 420 1870 460 432
sum_reader(block=64) 100000 819 2690 770 837
sum_reader(block=128) 100000 1629 5390 1696 1649
sum_reader(block=256) 100000 3240 9080 3240 3274
sum_reader(block=512) 76638 6469 9780 5302 6524
Test [1/2] test "ReleaseSmall benchmark generics"...
Benchmark Iterations Min(ns) Max(ns) Variance Mean(ns)
sum_vectors(vec4f16) 100000 4859 16710 5250 4902
sum_vectors(vec4f32) 100000 319 1650 326 328
sum_vectors(vec4f64) 100000 319 1470 295 327
sum_vectors(vec8f16) 100000 3980 9070 3382 4254
sum_vectors(vec8f32) 100000 319 3740 459 328
sum_vectors(vec8f64) 100000 319 4100 534 330
sum_vectors(vec16f16) 79800 6219 15130 10000 6265
sum_vectors(vec16f32) 100000 319 3340 455 330
sum_vectors(vec16f64) 100000 429 2020 454 438
All 2 tests passed.
``` | [] |
https://avatars.githubusercontent.com/u/3759175?v=4 | zig-midi | Hejsil/zig-midi | 2018-08-17T09:04:10Z | null | master | 1 | 35 | 3 | 35 | https://api.github.com/repos/Hejsil/zig-midi/tags | MIT | [
"midi",
"zig",
"zig-library",
"zig-package"
] | 77 | false | 2025-05-04T08:50:05Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/3759175?v=4 | zig-crc | Hejsil/zig-crc | 2018-01-12T15:05:58Z | null | master | 0 | 5 | 1 | 5 | https://api.github.com/repos/Hejsil/zig-crc/tags | MIT | [
"crc",
"zig",
"zig-library",
"zig-package"
] | 37 | false | 2024-09-13T12:24:10Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/62312094?v=4 | zigimg | zigimg/zigimg | 2019-12-29T22:52:29Z | Zig library for reading and writing different image formats | master | 43 | 607 | 100 | 607 | https://api.github.com/repos/zigimg/zigimg/tags | MIT | [
"bitmap",
"bmp",
"image",
"image-processing",
"netpbm",
"pcx",
"png",
"png-decoder",
"zig",
"zig-library",
"zig-package"
] | 1,100 | false | 2025-05-21T20:54:56Z | true | true | unknown | github | [] | Zig Image library
This is a work in progress library to create, process, read and write different image formats with <a>Zig</a> programming language.
<a></a>
Install & Build
This library uses zig nominated <a>2024.11.0-mach</a>. To install using <a><code>zigup</code></a>:
<code>sh
zigup 0.14.0-dev.2577+271452d22</code>
Use zigimg in your project
How to add to your project:
As a submodule
<ol>
<li>Clone this repository or add as a submodule</li>
<li>Add to your <code>build.zig</code>
<code>pub fn build(b: *std.Build) void {
exe.root_module.addAnonymousModule("zigimg", .{ .root_source_file = b.path("zigimg.zig") });
}</code></li>
</ol>
Through the package manager
<ol>
<li>Run this command in your project folder to add <code>zigimg</code> to your <code>build.zig.zon</code></li>
</ol>
<code>sh
zig fetch --save git+https://github.com/zigimg/zigimg.git</code>
<ol>
<li>Get the module in your <code>build.zig</code> file</li>
</ol>
```zig
const zigimg_dependency = b.dependency("zigimg", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zigimg", zigimg_dependency.module("zigimg"));
```
After you are done setting up, you can look at the user guide below.
Test suite
To run the test suite, checkout the <a>test suite</a> and run
<ol>
<li>Checkout zigimg</li>
<li>Go back one folder and checkout the <a>test suite</a> </li>
<li>Run the tests with <code>zig build</code>
<code>zig build test</code></li>
</ol>
Supported image formats
| Image Format | Read | Write |
| ------------- |:-------------:|:--------------:|
| ANIM | ❌ | ❌ |
| BMP | ✔️ (Partial) | ✔️ (Partial) |
| Farbfeld | ✔️ | ✔️ |
| GIF | ✔️ | ❌ |
| ICO | ❌ | ❌ |
| IFF | ✔️ | ❌ |
| JPEG | ✔️ (Partial) | ❌ |
| PAM | ✔️ | ✔️ |
| PBM | ✔️ | ✔️ |
| PCX | ✔️ | ✔️ |
| PGM | ✔️ (Partial) | ✔️ (Partial) |
| PNG | ✔️ | ✔️ (Partial) |
| PPM | ✔️ (Partial) | ✔️ (Partial) |
| QOI | ✔️ | ✔️ |
| SGI | ✔️ | ❌ |
| SUN | ✔️ | ❌ |
| TGA | ✔️ | ✔️ |
| TIFF | ✔️ (Partial) | ❌ |
| XBM | ❌ | ❌ |
| XPM | ❌ | ❌ |
BMP - Bitmap
<ul>
<li>version 4 BMP</li>
<li>version 5 BMP</li>
<li>24-bit RGB read & write</li>
<li>32-bit RGBA read & write</li>
<li>Doesn't support any compression</li>
</ul>
GIF - Graphics Interchange Format
<ul>
<li>Support GIF87a and GIF89a</li>
<li>Support animated GIF with Netscape application extension for looping information</li>
<li>Supports interlaced</li>
<li>Supports tiled and layered images used to achieve pseudo true color and more.</li>
<li>The plain text extension is not supported</li>
</ul>
IFF - InterchangeFileFormat
<ul>
<li>Supports 1-8 bit, 24 bit, HAM6/8, EHB ILBM files</li>
<li>Supports uncompressed, byterun 1 & 2 (Atari) compressed ILBM files</li>
<li>Supports PBM (Deluxe Paint DOS) encoded files</li>
<li>Supports ACBM (Amiga Basic) files</li>
<li>Color cycle chunks are ignored</li>
<li>Mask is not supported (skipped)</li>
</ul>
JPEG - Joint Photographic Experts Group
<ul>
<li>8-bit baseline and progressive</li>
</ul>
PAM - Portable Arbitrary Map
Currently, this only supports a subset of PAMs where:
* The tuple type is official (see <code>man 5 pam</code>) or easily inferred (and by extension, depth is 4 or less)
* All the images in a sequence have the same dimensions and maxval (it is technically possible to support animations with different maxvals and tuple types as each <code>AnimationFrame</code> has its own <code>PixelStorage</code>, however, this is likely not expected by users of the library)
* Grayscale,
* Grayscale with alpha
* Rgb555
* Rgb24 and Rgba32
* Bgr24 and Bgra32
* Rgb48 and Rgba64
PBM - Portable Bitmap format
<ul>
<li>Everything is supported</li>
</ul>
PCX - ZSoft Picture Exchange format
<ul>
<li>Support monochrome, 4 color, 16 color and 256 color indexed images</li>
<li>Support 24-bit RGB images</li>
</ul>
PGM - Portable Graymap format
<ul>
<li>Support 8-bit and 16-bit grayscale images</li>
<li>16-bit ascii grayscale loading not tested</li>
</ul>
PNG - Portable Network Graphics
<ul>
<li>Support all pixel formats supported by PNG (grayscale, grayscale+alpha, indexed, truecolor, truecolor with alpha) in 8-bit or 16-bit.</li>
<li>Support the mininal chunks in order to decode the image.</li>
<li>Can write all supported pixel formats but writing interlaced images is not supported yet.</li>
</ul>
PPM - Portable Pixmap format
<ul>
<li>Support 24-bit RGB (8-bit per channel)</li>
<li>Missing 48-bit RGB (16-bit per channel)</li>
</ul>
QOI - Quite OK Image format
<ul>
<li>Imported from https://github.com/MasterQ32/zig-qoi with blessing of the author</li>
</ul>
SGI - Silicon Graphics Image
<ul>
<li>Supports 8-bit, RGB (24/48-bit), RGBA(32/64-bit) files</li>
<li>Supports RLE and uncompressed files</li>
</ul>
SUN - Sun Raster format
<ul>
<li>Supports 1/8/24/32-bit files</li>
<li>Supports uncompressed & RLE files</li>
<li>Supports BGR/RGB encoding</li>
<li>TIFF/IFF/Experimental encoding is not supported</li>
</ul>
TGA - Truevision TGA format
<ul>
<li>Supports uncompressed and compressed 8-bit grayscale, indexed with 16-bit and 24-bit colormap, truecolor with 16-bit(RGB555), 24-bit or 32-bit bit depth.</li>
<li>Supports reading version 1 and version 2</li>
<li>Supports writing version 2</li>
</ul>
TIFF - Tagged Image File Format
What's supported:
<ul>
<li>bilevel, grayscale, palette and RGB(A) files</li>
<li>most <em>baseline</em> tags</li>
<li>Raw, LZW, Deflate, PackBits, CCITT 1D files</li>
<li>big-endian (MM) and little-endian (II) files should both be decoded fine</li>
</ul>
What's missing:
<ul>
<li>Tile-based files are not supported</li>
<li>YCbCr, CMJN and CIE Lab files are not supported</li>
<li>JPEG, CCITT Fax 3 / 4 are not supported yet</li>
</ul>
Notes
<ul>
<li>Only the first IFD is decoded</li>
<li>Orientation tag is not supported yet</li>
</ul>
Supported Pixel formats
<ul>
<li><strong>Indexed</strong>: 1bpp (bit per pixel), 2bpp, 4bpp, 8bpp, 16bpp</li>
<li><strong>Grayscale</strong>: 1bpp, 2bpp, 4bpp, 8bpp, 16bpp, 8bpp with alpha, 16bpp with alpha</li>
<li><strong>Truecolor</strong>: RGB332, RGB555, RGB565, RGB24 (8-bit per channel), RGBA32 (8-bit per channel), BGR555, BGR24 (8-bit per channel), BGRA32 (8-bit per channel), RGB48 (16-bit per channel), RGBA64 (16-bit per channel)</li>
<li><strong>float</strong>: 32-bit float RGBA, this is the neutral format.</li>
</ul>
User Guide
Design philosophy
zigimg offers color and image functionality. The library is designed around either using the convenient <code>Image</code> (or <code>ImageUnmanaged</code>) struct that can read and write image formats no matter the format.
Or you can also use the image format directly in case you want to extract more data from the image format. So if you find that <code>Image</code> does not give you the information that you need from a PNG or other format, you can use the PNG format albeit with a more manual API that <code>Image</code> hide from you.
<code>Image</code> vs <code>ImageUnmanaged</code>
<code>Image</code> bundle a memory allocator and <code>ImageUnmanaged</code> does not. Similar to <code>std.ArrayList()</code> and <code>std.ArrayListUnmanaged()</code> in Zig standard library. For all the examples we are going to use <code>Image</code> but it is similar with <code>ImageUnmanaged</code>.
Read an image
It is pretty straightforward to read an image using the <code>Image</code> struct.
From a file
You can use either a file path
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
var image = try zigimg.Image.fromFilePath(allocator, "my_image.png");
defer image.deinit();
// Do something with your image
</code>
}
```
or a <code>std.fs.File</code> directly
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
var file = try std.fs.cwd().openFile(file_path, .{});
defer file.close();
var image = try zigimg.Image.fromFile(allocator, file);
defer image.deinit();
// Do something with your image
</code>
}
```
From memory
```zig
const std = @import("std");
const zigimg = @import("zigimg");
const image_data = @embedFile("test.bmp");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
const image = try zigimg.Image.fromMemory(allocator, image_data[0..]);
defer image.deinit();
// Do something with your image
</code>
}
```
Accessing pixel data
For a single image, they are two ways to get access to the pixel data.
Accessing a specific format directly
You can access the pixel data directly using <code>Image.pixels</code>. <code>pixels</code> is an union of all supported pixel formats.
For RGB pixel formats, just use the pixel format enum value and addresss the data directly.
```zig
pub fn example() void {
// [...]
// Assuming you already have an image loaded
<code>const first_pixel = image.pixels.rgb24[0];
</code>
}
```
For grayscale formats, you need to use .value to get the grayscale value. It can also contain the alpha value if you use the grayscale with alpha.
```zig
pub fn example() void {
// [...]
// Assuming you already have an image loaded
<code>const first_pixel = image.pixels.grayscale8Alpha[0];
const grayscale = first_pixel.value;
const alpha = grayscale.alpha;
</code>
}
```
For indexed formats, you need to first access the union value then either the indices or the palette. The palette color are stored in the <code>Rgba32</code> pixel format.
```zig
pub fn example() void {
// [...]
// Assuming you already have an image loaded
<code>const first_color_palette = image.pixels.indexed8.palette[0];
const first_pixel = image.pixels.indexed8.indices[0];
</code>
}
```
If you want to know the current pixel format use <code>Image.pixelFormat()</code>.
Using the color iterator
You can use the iterator to get each pixel as the universal <code>Colorf32</code> pixel format. (32-bit floating ploint RGBA)
```zig
pub fn example() void {
// [...]
// Assuming you already have an image loaded
<code>const color_it = image.iterator();
while (color_it.next()) |color| {
// Do something with color
}
</code>
}
```
Accessing animation frames
In the case of an <code>Image</code> containing multiple frames, you can use <code>Image.animation</code> to get access to the animation information. Use <code>Image.animation.frames</code> to access each indivial frame. Each frame contain the pixel data and a frame duration in seconds (32-bit floating point).
<code>Image.pixels</code> will always point to the first frame of an animation also.
```zig
pub fn example() void {
// [...]
// Assuming you already have an image loaded
<code>const loop_count = image.animation.loop_count;
for (image.animation.frames) |frame| {
const rgb24_data = frame.pixels.rgb24;
const frame_duration = frame.duration;
}
</code>
}
```
Get raw bytes for texture transfer
<code>Image</code> has helper functions to help you get the right data to upload your image to the GPU.
```zig
pub fn example() void {
// [...]
// Assuming you already have an image loaded
<code>const image_data = image.rawBytes();
const row_pitch = image.rowByteSize();
const image_byte_size = image.imageByteSize();
</code>
}
```
Detect image format
You can query the image format used by a file or a memory buffer.
From a file
You can use either a file path
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
const image_format = try zigimg.Image.detectFormatFromFilePath(allocator, "my_image.png");
<code>// Will print png
std.log.debug("Image format: {}", .{image_format});
</code>
}
```
or a <code>std.fs.File</code> directly
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var file = try std.fs.cwd().openFile("my_image.gif", .{});
defer file.close();
<code>const image_format = try zigimg.Image.detectFormatFromFile(allocator, file);
// Will print gif
std.log.debug("Image format: {}", .{image_format});
</code>
}
```
From memory
```zig
const std = @import("std");
const zigimg = @import("zigimg");
const image_data = @embedFile("test.bmp");
pub fn main() !void {
const image_format = try zigimg.Image.detectFormatFromMemory(allocator, image_data[0..]);
<code>// Will print bmp
std.log.debug("Image format: {}", .{image_format});
</code>
}
```
Write an image
Each 3 functions to write an image take a union of encoder options for the target format. To know the actual options you'll need to consult the source code. The active tag of the union determine the target format, not the file extension.
Write to a file path
```zig
pub fn example() !void {
// [...]
// Assuming you already have an image loaded
<code>try image.writeToFilePath("my_new_image.png", .{ .png = .{} });
// Or with encoder options
try image.writeToFilePath("my_new_image.png", .{ .png = .{ .interlaced = true } });
</code>
}
```
Write to <code>std.fs.File</code>
```zig
pub fn example() !void {
// [...]
// Assuming you already have an image loaded and the file already created
<code>try image.writeToFile(file, .{ .bmp = .{} });
</code>
}
```
Write to a memory buffer
Ensure that you have enough place in your buffer before calling <code>writeToMemory()</code>
```zig
pub fn example() !void {
// [...]
// Assuming you already have an image loaded and the buffer already allocated
<code>try image.writeToMemory(buffer[0..], .{ .tga = .{} });
</code>
}
```
Create an image
Use <code>Image.create()</code> and pass the width, height and the pixel format that you want.
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
var image = try zigimg.Image.create(allocator, 1920, 1080, .rgba32);
defer image.deinit();
// Do something with your image
</code>
}
```
Interpret raw pixels
If you are not dealing with a image format, you can import your pixel data using <code>Image.fromRawPixels()</code>. It will create a copy of the pixels data. If you want the image to take ownership or just pass the data along to write it to a image format, use <code>ImageUnmanaged.fromRawPixelsOwned()</code>.
Using <code>fromRawPixel()</code>:
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
const my_raw_pixels = @embedData("raw_bgra32.bin");
var image = try zigimg.Image.fromRawPixels(allocator, 1920, 1080, my_raw_pixels[0..], .bgra32);
defer image.deinit();
// Do something with your image
</code>
}
```
Using <code>fromRawPixelsOwned()</code>:
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
const my_raw_pixels = @embedData("raw_bgra32.bin");
var image = try zigimg.ImageUnmanaged.fromRawPixelsOwned(1920, 1080, my_raw_pixels[0..], .bgra32);
// Do something with your image
</code>
}
```
Use image format directly
In the case you want more direct access to the image format, all the image formats are accessible from the <code>zigimg</code> module. However, you'll need to do a bit more manual steps in order to retrieve the pixel data.
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
<code>const allocator = gpa.allocator();
const image_data = @embedFile("windows_rgba_v5.bmp");
var stream_source = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(image_data) };
var bmp = zigimg.formats.bmp.BMP{};
const pixels = try bmp.read(allocator, &stream_source);
defer pixels.deinit(allocator);
std.log.info("BMP info header: {}", .{bmp.info_header});
</code>
}
```
For the curious, the program above generate the following output:
<code>info: BMP info header: src.formats.bmp.BitmapInfoHeader{ .v5 = src.formats.bmp.BitmapInfoHeaderV5{ .header_size = 124, .width = 240, .height = 160, .color_plane = 1, .bit_count = 32, .compression_method = src.formats.bmp.CompressionMethod.bitfields, .image_raw_size = 153600, .horizontal_resolution = 2835, .vertical_resolution = 2835, .palette_size = 0, .important_colors = 0, .red_mask = 16711680, .green_mask = 65280, .blue_mask = 255, .alpha_mask = 4278190080, .color_space = src.formats.bmp.BitmapColorSpace.srgb, .cie_end_points = src.formats.bmp.CieXyzTriple{ .red = src.formats.bmp.CieXyz{ ... }, .green = src.formats.bmp.CieXyz{ ... }, .blue = src.formats.bmp.CieXyz{ ... } }, .gamma_red = 0, .gamma_green = 0, .gamma_blue = 0, .intent = src.formats.bmp.BitmapIntent.graphics, .profile_data = 0, .profile_size = 0, .reserved = 0 } }</code>
Convert between pixel formats
You can use <code>Image.convert()</code> to convert between pixel formats. It will allocate the new pixel data and free the old one for you. It supports conversion from and to any pixel format. When converting down to indexed format, no dithering is done.
```zig
pub fn example() !void {
// [...]
// Assuming you already have an image loaded
<code>try image.convert(.float32);
</code>
}
```
PixelFormatConverter
If you prefer, you can use <code>PixelFormatConverter</code> directly.
```zig
pub fn example(allocator: std.mem.Allocator) !void {
const indexed2_pixels = try zigimg.color.PixelStorage.init(allocator, .indexed2, 4);
defer indexed2_pixels.deinit(allocator);
<code>// [...] Setup your indexed2 pixel data
const bgr24_pixels = try zigimg.PixelFormatConverter.convert(allocator, &indexed2_pixels, .bgr24);
defer bgr24_pixels.deinit(allocator);
</code>
}
```
OctTreeQuantizer
If you prefer more granular control to create an indexed image, you can use the <code>OctTreeQuantizer</code> directly.
```zig
pub fn example(allocator: std.mem.Allocator) !void {
const image_data = @embedFile("windows_rgba_v5.bmp");
<code>var image = try zigimg.Image.fromMemory(allocator, image_data[0..]);
defer image.deinit();
var quantizer = zigimg.OctTreeQuantizer.init(allocator);
defer quantizer.deinit();
var color_it = image.iterator();
while (color_it.next()) |pixel| {
try quantizer.addColor(pixel);
}
var palette_storage: [256]zigimg.color.Rgba32 = undefined;
const palette = quantizer.makePalette(255, palette_storage[0..]);
const palette_index = try quantizer.getPaletteIndex(zigimg.color.Rgba32.initRgba(110, 0, 0, 255));
</code>
}
```
Get a color from a HTML hex string
You can get a color from a HTML hex string. The alpha component is always last. It also supports the shorthand version.
```zig
pub fn example() !void {
const rgb24 = try zigimg.color.Rgb24.fromHtmlHex("#123499");
const rgba32 = try zigimg.color.Rgba32.fromHtmlHex("FF000045");
<code>const red_rgb24 = try zigimg.color.Rgb24.fromHtmlHex("#F00");
const blue_rgba32 = try zigimg.clor.Rgba32.fromHtmlHex("#00FA");
</code>
}
```
Predefined colors
You can access predefined colors for any pixel format using <code>Colors()</code>.
```zig
const std = @import("std");
const zigimg = @import("zigimg");
pub fn main() !void {
const red_float32 = zigimg.Colors(zigimg.color.Colorf32).Red;
const blue_rgb24 = zigimg.Colors(zigimg.color.Rgb24).Blue;
}
```
Color management & color space
While zigimg does not support ICC profile yet (see #36) it does support a variety of color models and color spaces. All color space and color model are done in 32-bit floating point. So if you are not using <code>Colorf32</code> / <code>float32</code> as your pixel format, you'll need to convert to that format first.
The following device-dependent color model are supported:
* HSL (Hue, Saturation, Luminance)
* HSV (Hue, Saturation, Value) or also known as HSB (Hue, Saturation, Brightness)
* CMYK (Cyan-Magenta-Yellow-Black)
The following device-inpendent color spaces are supported, with or without alpha:
* CIE XYZ
* CIE Lab
* CIE LCh(ab), the cylindral representation of CIE Lab
* CIE Luv
* CIE LCh(uv), the cylindral representation of CIE Luv
* <a>HSLuv</a>, a HSL representation of CIE LCh(uv) which is a cylindrical representation of CIE Luv color space
* <a>Oklab</a>
* Oklch, the cylindrical representation of Oklab
Convert between linear and gamma-corrected color
All color space transformation are done assuming a linear version of the color. To convert between gamma-converted and linear, you need to use any RGB colorspace and then call <code>toGamma()</code> or <code>toLinear()</code>, in this example I'm using both <code>sRGB</code> and <code>BT709</code> (aka Rec.709).
You can use either the accurate version or the fast version. For example the sRGB transfer function is linear below a threshold and an exponent curve above the threshold but the fast version will use the approximate exponent curve for the whole range.
```zig
pub fn example(linear_color: zigimg.color.Colorf32) {
const gamma_srgb = zigimg.color.sRGB.toGamma(linear_color);
const gamma_bt709 = zigimg.color.BT709.toGammaFast(linear_color);
<code>const linear_srgb = zigimg.color.sRGB.toLinearFast(gamma_srgb);
const linear_bt709 = zigimg.color.BT709.toLinear(gamma_bt609);
</code>
}
```
Convert a single color to a different color space
To convert to a device independant color space, you need first to use a reference RGB color space. Usually the most common for computer purposes is <code>sRGB</code>. Then each RGB colorspace has functions to convert from and to various color spaces. They support both non-alpha and alpha of the color space.
To a color space:
<code>zig
pub fn example(linear_color: zigimg.color.Colorf32) void {
const xyz = zigimg.color.sRGB.toXYZ(linear_color);
const lab_alpha = zigimg.color.sRGB.toLabAlpha(linear_color);
const lch_ab = zigimg.color.sRGB.toLCHab(linear_color);
const luv_alpha = zigimg.color.sRGB.toLuvAlpha(linear_color);
const lch_uv = zigimg.color.sRGB.toLCHuv(linear_color);
const hsluv = zigimg.color.sRGB.toHSLuv(linear_color);
const oklab = zigimg.color.sRGB.toOklab(linear_color);
const oklch = zigimg.color.sRGB.toOkLCh(linear_color);
}</code>
When converting from a color space to a RGB color space, you need to specify if you want the color to be clamped inside the RGB colorspace or not because the resulting color could be outside of the RGB color space.
<code>zig
pub fn example(oklab: zigimg.color.Oklab) {
const linear_srgb_clamped = zigimg.color.sRGB.fromOklab(oklab, .clamp);
const linear_srgb = zigimg.color.sRGB.fromOklab(oklab, .none);
}</code>
Convert a slice of color to a different color space
Converting each pixel individually will be tedious if you want to use image processing on the CPU. Almost all color space conversion offer
an slice in-place conversion or a slice copy conversion. The in-place will reuse the same memory but interpret the color data differently. When you are conversion from a color space to a RGB color space, you need to specify if you want clamping or not.
Those conversions are only available with the alpha version of each color space.
```zig
pub fn exampleInPlace(linear_srgb_image: []zigimg.color.Colorf32) void {
const slice_lab_alpha = zigimg.color.sRGB.sliceToLabAlphaInPlace(linear_srgb_image);
<code>// Do your image manipulation in CIE L*a*b*
// Convert back to linear sRGB
_ = zigimg.color.sRGB.sliceFromLabAlphaInPlace(slice_lab_alpha, .clamp);
// or without clamping
_ = zigimg.color.sRGB.sliceFromLabAlphaInPlace(slice_lab_alpha, .none);
</code>
}
pub fn exampleCopy(allocator: std.mem.Allocator, linear_srgb_image: []const zigimg.color.Colorf32) ![]zigimg.color.Colorf32 {
const slice_oklab_alpha = try zigimg.color.sRGB.sliceToOklabCopy(allocator, linear_srgb_image);
<code>// Do your image manipulatioon in Oklab
// Convert back to linear sRGB
return try zigimg.color.sRGB.sliceFromOklabCopy(allocator, slice_oklab_alpha, .clamp);
// Or without clamping
return try zigimg.color.sRGB.sliceFromOklabCopy(allocator, slice_oklab_alpha, .none);
</code>
}
```
Convert between some cylindrical representation
CIE Lab, CIE Luv and Oklab have cylindrical representation of their color space, each color has functions to convert from and to the cylindrical version.
```zig
pub fn example() void {
const lab = zigimg.color.CIELab{ .l = 0.12, .a = -0.23, .b = 0.56 };
const luv_alpha = zigimg.color.CIELuvAlpha { .l = 0.4, .u = 0.5, .v = -0.2, .alpha = 0.8 };
const oklab = zigimg.color.Oklab{ .l = 0.67, .a = 0.1, .b = 0.56 };
<code>const lch_ab = lab.toLCHab();
const lch_uv_alpha = luv_alpha.toLCHuvAlpha();
const oklch = oklab.toOkLCh();
const result_lab = lch_ab.toLab();
const result_luv_alpha = lch_uv_alpha.toLuvAlpha();
const result_oklab = oklch.toOklab();
</code>
}
```
Convert color between RGB color spaces
To convert a single color, use the <code>convertColor()</code> function on the <code>RgbColorspace</code> struct:
<code>zig
pub fn example(linear_color: zigimg.color.Colorf32) void {
const pro_photo_color = zigimg.color.sRGB.convertColor(zigimg.color.ProPhotoRGB, linear_color);
}</code>
If you want to convert a whole slice of pixels, use <code>convertColors()</code>, it will apply the conversion in-place:
<code>zig
pub fn example(linear_image: []zigimg.color.Colorf32) void {
const adobe_image = zigimg.color.sRGB.convertColors(zigimg.color.AdobeRGB, linear_image);
}</code>
If the target RGB colorspace have a different white point, it will do the <a>chromatic adapdation</a> for you using the Bradford method.
Predefined RGB color spaces
Here the list of predefined RGB color spaces, all accessible from <code>zigimg.color</code> struct:
<ul>
<li><code>BT601_NTSC</code></li>
<li><code>BT601_PAL</code></li>
<li><code>BT709</code></li>
<li><code>sRGB</code></li>
<li><code>DCIP3.Display</code></li>
<li><code>DCIP3.Theater</code></li>
<li><code>DCIP3.ACES</code></li>
<li><code>BT2020</code></li>
<li><code>AdobeRGB</code></li>
<li><code>AdobeWideGamutRGB</code></li>
<li><code>ProPhotoRGB</code></li>
</ul>
Predefined white points
All predefined white point are accessed with <code>zigimg.color.WhitePoints</code>. All the standard illuminants are defined there.
Create your own RGB color space
You can create your own RGB color space using <code>zigimg.color.RgbColorspace.init()</code>. Each coordinate is in the 2D version of the CIE xyY color space.
If you don't care about linear and gamma conversion, just ignore those functions in the init struct.
```zig
fn myColorSpaceToGamma(value: f32) f32 {
return std.math.pow(f32, value, 1.0 / 2.4);
}
fn myColorSpaceToLinear(value: f32) f32 {
return std.math.pow(f32, value, 2.4);
}
pub fn example() void {
pub const my_color_space = zigimg.color.RgbColorspace.init(.{
.red = .{ .x = 0.6400, .y = 0.3300 },
.green = .{ .x = 0.3000, .y = 0.6000 },
.blue = .{ .x = 0.1500, .y = 0.0600 },
.white = zigimg.color.WhitePoints.D50,
.to_gamma = myColorSpaceToGamma,
.to_gamma_fast = myColorSpaceToGamma,
.to_linear = myColorSpaceToLinear,
.to_linear_fast = myColorSpaceToLinear,
});
}
``` | [
"https://github.com/ATTron/astroz",
"https://github.com/Harry-Heath/micro",
"https://github.com/Khitiara/imaginarium",
"https://github.com/PhantomUIx/core",
"https://github.com/SinclaM/ray-tracer-challenge",
"https://github.com/capy-ui/capy",
"https://github.com/chadwain/zss",
"https://github.com/deck... |
https://avatars.githubusercontent.com/u/3932972?v=4 | SDL.zig | ikskuh/SDL.zig | 2019-12-02T07:43:30Z | A shallow wrapper around SDL that provides object API and error handling | master | 17 | 402 | 88 | 402 | https://api.github.com/repos/ikskuh/SDL.zig/tags | MIT | [
"gamedev",
"sdl",
"sdl2",
"zig",
"zig-package",
"ziglang"
] | 995 | false | 2025-05-15T23:44:01Z | true | true | 0.14.0 | github | [] | SDL.zig
A Zig package that provides you with the means to link SDL2 to your project, as well as a Zig-infused header implementation (allows you to not have the SDL2 headers on your system and still compile for SDL2) and a shallow wrapper around the SDL apis that allow a more Zig-style coding with Zig error handling and tagged unions.
Getting started
Linking SDL2 to your project
This is an example <code>build.zig</code> that will link the SDL2 library to your project.
```zig
const std = @import("std");
const sdl = @import("sdl"); // Replace with the actual name in your build.zig.zon
pub fn build(b: *std.Build) !void {
// Determine compilation target
const target = b.standardTargetOptions(.{});
<code>// Create a new instance of the SDL2 Sdk
// Specifiy dependency name explicitly if necessary (use sdl by default)
const sdk = sdl.init(b, .{});
// Create executable for our example
const demo_basic = b.addExecutable(.{
.name = "demo-basic",
.root_source_file = b.path("my-game.zig"),
.target = target,
});
sdk.link(demo_basic, .dynamic, sdl.Library.SDL2); // link SDL2 as a shared library
// Add "sdl2" package that exposes the SDL2 api (like SDL_Init or SDL_CreateWindow)
demo_basic.root_module.addImport("sdl2", sdk.getNativeModule());
// Install the executable into the prefix when invoking "zig build"
b.installArtifact(demo_basic);
</code>
}
```
Using the native API
This package exposes the SDL2 API as defined in the SDL headers. Use this to create a normal SDL2 program:
```zig
const std = @import("std");
const SDL = @import("sdl2"); // Add this package by using sdk.getNativeModule
pub fn main() !void {
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_EVENTS | SDL.SDL_INIT_AUDIO) < 0)
sdlPanic();
defer SDL.SDL_Quit();
<code>var window = SDL.SDL_CreateWindow(
"SDL2 Native Demo",
SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
640, 480,
SDL.SDL_WINDOW_SHOWN,
) orelse sdlPanic();
defer _ = SDL.SDL_DestroyWindow(window);
var renderer = SDL.SDL_CreateRenderer(window, -1, SDL.SDL_RENDERER_ACCELERATED) orelse sdlPanic();
defer _ = SDL.SDL_DestroyRenderer(renderer);
mainLoop: while (true) {
var ev: SDL.SDL_Event = undefined;
while (SDL.SDL_PollEvent(&ev) != 0) {
if(ev.type == SDL.SDL_QUIT)
break :mainLoop;
}
_ = SDL.SDL_SetRenderDrawColor(renderer, 0xF7, 0xA4, 0x1D, 0xFF);
_ = SDL.SDL_RenderClear(renderer);
SDL.SDL_RenderPresent(renderer);
}
</code>
}
fn sdlPanic() noreturn {
const str = @as(?[*:0]const u8, SDL.SDL_GetError()) orelse "unknown error";
@panic(std.mem.sliceTo(str, 0));
}
```
Using the wrapper API
This package also exposes the SDL2 API with a more Zig-style API. Use this if you want a more convenient Zig experience.
<strong>Note:</strong> This API is experimental and might change in the future
```zig
const std = @import("std");
const SDL = @import("sdl2"); // Created in build.zig by using exe.root_module.addImport("sdl2", sdk.getWrapperModule());
pub fn main() !void {
try SDL.init(.{
.video = true,
.events = true,
.audio = true,
});
defer SDL.quit();
<code>var window = try SDL.createWindow(
"SDL2 Wrapper Demo",
.{ .centered = {} }, .{ .centered = {} },
640, 480,
.{ .vis = .shown },
);
defer window.destroy();
var renderer = try SDL.createRenderer(window, null, .{ .accelerated = true });
defer renderer.destroy();
mainLoop: while (true) {
while (SDL.pollEvent()) |ev| {
switch (ev) {
.quit => break :mainLoop,
else => {},
}
}
try renderer.setColorRGB(0xF7, 0xA4, 0x1D);
try renderer.clear();
renderer.present();
}
</code>
}
```
<code>build.zig</code> API
<code>``zig
/// Just call</code>Sdk.init(b, .{})<code>to obtain a handle to the Sdk!
/// Use</code>sdl` as dependency name by default.
const Sdk = @This();
/// Creates a instance of the Sdk and initializes internal steps.
/// Initialize once, use everywhere (in your <code>build</code> function).
///
/// const SdkOption = struct {
/// dep_name: ?[]const u8 = "sdl",
/// maybe_config_path: ?[]const u8 = null,
/// maybe_sdl_ttf_config_path: ?[]const u8 = null,
/// };
pub fn init(b: <em>Build, opt: SdkOption) </em>Sdk
/// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes
/// for a more <em>ziggy</em> feeling.
/// This is similar to the <em>C import</em> result.
pub fn getNativeModule(sdk: <em>Sdk) </em>Build.Module;
/// Returns a module with the raw SDL api with proper argument types, but no functional/logical changes
/// for a more <em>ziggy</em> feeling, with Vulkan support! The Vulkan module provided by <code>vulkan-zig</code> must be
/// provided as an argument.
/// This is similar to the <em>C import</em> result.
pub fn getNativeModuleVulkan(sdk: <em>Sdk, vulkan: </em>Build.Module) *Build.Module;
/// Returns the smart wrapper for the SDL api. Contains convenient zig types, tagged unions and so on.
pub fn getWrapperModule(sdk: <em>Sdk) </em>Build.Module;
/// Returns the smart wrapper with Vulkan support. The Vulkan module provided by <code>vulkan-zig</code> must be
/// provided as an argument.
pub fn getWrapperModuleVulkan(sdk: <em>Sdk, vulkan: </em>Build.Module) *Build.Module;
/// Links SDL2 or SDL2_ttf to the given exe and adds required installs if necessary.
/// <strong>Important:</strong> The target of the <code>exe</code> must already be set, otherwise the Sdk will do the wrong thing!
pub fn link(sdk: <em>Sdk, exe: </em>Build.Step.Compile, linkage: std.builtin.LinkMode, comptime library: Library) void;
```
Dependencies
All of those are dependencies for the <em>target</em> platform, not for your host. Zig will run/build the same on all source platforms.
Windows
For Windows, you need to fetch the correct dev libraries from the <a>SDL download page</a>. It is recommended to use the MinGW versions if you don't require MSVC compatibility.
MacOS
Right now, cross-compiling for MacOS isn't possible. On a Mac, install SDL2 via <code>brew</code>.
Linux
If you are cross-compiling, no dependencies exist. The build Sdk compiles a <code>libSDL2.so</code> stub which is used for linking.
If you compile to your target platform, you require SDL2 to be installed via your OS package manager.
Support Matrix
This project tries to provide you the best possible development experience for SDL2. Thus, this project supports
the maximum amount of cross-compilation targets for SDL2.
The following table documents this. The rows document the <em>target</em> whereas the columns are the <em>build host</em>:
| | Windows (x86_64) | Windows (i386) | Linux (x86_64) | MacOS (x86_64) | MacOS (aarch64) |
|-----------------------|------------------|----------------|----------------|----------------|-----------------|
| <code>i386-windows-gnu</code> | ✅ | ✅ | ✅ | ✅ | ⚠️ |
| <code>i386-windows-msvc</code> | ✅ | ✅ | ✅ | ✅ | ⚠️ |
| <code>x86_64-windows-gnu</code> | ✅ | ✅ | ✅ | ✅ | ⚠️ |
| <code>x86_64-windows-msvc</code> | ✅ | ✅ | ✅ | ✅ | ⚠️ |
| <code>x86_64-macos</code> | ❌ | ❌ | ❌ | ✅ | ❌ |
| <code>aarch64-macos</code> | ❌ | ❌ | ❌ | ❌ | ⚠️ |
| <code>x86_64-linux-gnu</code> | 🧪 | 🧪 | ✅ | 🧪 | ⚠️ |
| <code>aarch64-linux-gnu</code> | 🧪 | 🧪 | 🧪 | 🧪 | ⚠️ |
Legend:
- ✅ Cross-compilation is known to work and tested via CI
- 🧪 Experimental cross-compilation support, covered via CI
- ⚠️ Cross-compilation <em>might</em> work, but is not tested via CI
- ❌ Cross-compilation is not possible right now
Contributing
You can contribute to this project in several ways:
- Use it!
This helps me to track bugs (which i know that there are some), and usability defects (which we can resolve then). I want this library to have the best development experience possible.
- Implement/improve the linking experience:
Right now, it's not possible to cross-compile for MacOS, which is very sad. We might find a way to do so, though! Also VCPKG is not well supported on windows platforms.
- Improve the wrapper.
Just add the functions you need and make a PR. Or improve existing ones. I won't do it for you, so you have to get your own hands dirty! | [] |
https://avatars.githubusercontent.com/u/3932972?v=4 | LoLa | ikskuh/LoLa | 2019-07-17T17:56:20Z | LoLa is a small programming language meant to be embedded into games. | master | 15 | 207 | 11 | 207 | https://api.github.com/repos/ikskuh/LoLa/tags | MIT | [
"compiler",
"interpreter",
"language",
"lola-language",
"programming-language",
"script-language",
"zig",
"zig-package"
] | 13,512 | false | 2025-05-18T05:27:14Z | true | true | unknown | github | [
{
"commit": "9425b94c103a031777fdd272c555ce93a7dea581",
"name": "args",
"tar_url": "https://github.com/ikskuh/zig-args/archive/9425b94c103a031777fdd272c555ce93a7dea581.tar.gz",
"type": "remote",
"url": "https://github.com/ikskuh/zig-args"
},
{
"commit": "d068b14cd30577783de018e280428953d... | LoLa Programming Language
LoLa is a small programming language meant to be embedded into games to be programmed by the players. The compiler and runtime are implemented in Zig and C++.
Short Example
<code>js
var list = [ "Hello", "World" ];
for(text in list) {
Print(text);
}</code>
You can find more examples in the <a>examples</a> folder.
Why LoLa when there is <em>X</em>?
LoLa isn't meant to be your next best day-to-day scripting language. Its design is focused on embedding the language in environments where the users want/need/should write some small scripts like games or scriptable applications. In most script languages, you as a script host don't have control over the execution time of the scripts you're executing. LoLa protects you against programming errors like endless loops and such:
Controlled Execution Environment
Every script invocation gets a limit of instructions it might execute. When either this limit is reached or the script yields for other reasons (asynchronous functions), the execution is returned to the host.
This means, you can execute the following script "in parallel" to your application main loop without blocking your application <em>and</em> without requiring complex multithreading setups:
<code>js
var timer = 0;
while(true) {
Print("Script running for ", timer, " seconds.");
timer += 1;
Sleep(1.0);
}</code>
Native Asynchronous Design
LoLa features both synchronous and asynchronous host functions. Synchronous host function calls are short-lived and will be executed in-place. Asynchronous functions, in contrast, will be executed multiple times until they yield a value. When they don't yield a value, control will be returned to the script host.
This script will not exhaust the instruction limit, but will only increment the counter, then return control back to the host:
<code>js
var counter = 0;
while(true) {
counter += 1;
Yield();
}</code>
This behaviour can be utilized to wait for certain events in the host environment, for example to react to key presses, a script could look like this:
<code>js
while(true) {
var input = WaitForKey();
if(input == " ") {
Print("Space was pressed!");
}
}</code>
<em>Note that the current implementation is not thread-safe, but requires to use the limited execution for running scripts in parallel.</em>
Native "RPC" Design
LoLa also allows executing multiple scripts on the same <em>environment</em>, meaning that you can easily create cross-script communications:
```js
// script a:
var buffer;
function Set(val) { buffer = val; }
function Get() { return val; }
// script b:
// GetBuffer() returns a object referencing a environment for "script a"
var buffer = GetBuffer();
buffer.Set("Hello, World!");
// script c:
// GetBuffer() returns a object referencing a environment for "script a"
var buffer = GetBuffer();
Print("Buffer contains: ", buffer.Get());
```
With a fitting network stack and library, this can even be utilized cross-computer.
This example implements a small chat client and server that could work with LoLa RPC capabilities:
```js
// Chat client implementation:
var server = Connect("lola-rpc://random-projects.net/chat");
if(server == void) {
Print("Could not connect to chat server!");
Exit(1);
}
while(true) {
var list = server.GetMessages(GetUser());
for(msg in list) {
Print("< ", msg);
}
<code>Print("> ");
var msg = ReadLine();
if(msg == void)
break;
if(msg == "")
continue;
server.Send(GetUser(), msg);
</code>
}
```
```js
// Chat server implementation
var messages = CreateDictionary();
function Send(user, msg)
{
for(other in messages.GetKeys())
{
if(other != user) {
var log = messages.Get(other);
if(log != void) {
log = log ++ [ user + ": " + msg ];
} else {
log = [];
}
messages.Set(other, log);
}
}
}
function GetMessages(user)
{
var log = messages.Get(user);
if(log != void) {
messages.Set(user, []);
return log;
} else {
return [];
}
}
```
Serializable State
As LoLa has no reference semantics except for objects, it is easy to understand and learn. It is also simple in its implementation and does not require a complex garbage collector or advanced programming knowledge. Each LoLa value can be serialized/deserialized into a sequence of bytes (only exception are object handles, those require some special attention), so saving the current state of a environment/vm to disk and loading it at a later point is a first-class supported use case.
This is especially useful for games where it is favourable to save your script state into a save game as well without having any drawbacks.
Simple Error Handling
LoLa provides little to no in-language error handling, as it's not designed to be robust against user programming errors. Each error is passed to the host as a panic, so it can show the user that there was an error (like <code>OutOfMemory</code> or <code>TypeMismatch</code>).
In-language error handling is based on the dynamic typing: Functions that allow in-language error handling just return <code>void</code> instead of a actual return value or <code>true</code>/<code>false</code> for <em>success</em> or <em>failure</em>.
This allows simple error checking like this:
<code>js
var string = ReadFile("demo.data");
if(string != void) {
Print("File contained ", string);
}</code>
This design decision was made with the idea in mind that most LoLa programmers won't write the next best security critical software, but just do a quick hack in game to reach their next item unlock.
Smart compiler
As LoLa isn't the most complex language, the compiler can support the programmer. Even though the language has fully dynamic typing, the compiler can do some type checking at compile time already:
<code>js
// warning: Possible type mismatch detected: Expected number|string|array, found boolean
if(a < true) { }</code>
Right now, this is only used for validating expressions, but it is planned to extend this behaviour to annotate variables as well, so even more type errors can be found during compile time.
Note that this is a fairly new feature, it does not catch all your type mismatches, but can prevent the obvious ones.
Starting Points
To get familiar with LoLa, you can check out these starting points:
<ul>
<li><a>Documentation</a></li>
<li><a>LoLa Examples</a></li>
<li><a>Script Host Examples</a></li>
</ul>
When you want to contribute to the compiler, check out the following documents:
<ul>
<li><a>Source Code</a></li>
<li><a>Bison Grammar</a></li>
<li><a>Flex Tokenizer</a></li>
<li><a>Issue List</a></li>
</ul>
Visual Studio Code Extension
If you want syntax highlighting in VSCode, you can install the <a><code>lola-vscode</code></a> extension.
Right now, it's not published in the gallery, so to install the extension, you have to sideload it. <a>See the VSCode documentation for this</a>.
Building
Continous Integration
<a></a> <a></a>
Requirements
<ul>
<li>The <a>Zig Compiler</a> (Version 0.12.0-dev.3438+5c628312b or newer)</li>
</ul>
Building
<code>sh
zig build
./zig-cache/bin/lola</code>
Examples
To compile the host examples, you can use <code>zig build examples</code> to build all provided examples. These will be available in <code>./zig-cache/bin</code> then.
Running the test suite
When you change things in the compiler or VM implementation, run the test suite:
<code>sh
zig build test</code>
This will execute all zig tests, and also runs a set of predefined tests within the <a><code>src/test/</code></a> folder. These tests will verify that the compiler and language runtime behave correctly.
Building the website
The website generator is gated behind <code>-Denable-website</code> which removes a lot of dependencies for people not wanting to render a new version of the website.
If you still want to update/change the website or documentation, use the following command:
<code>sh
zig build -Denable-website "-Dversion=$(git describe --tags || git rev-parse --short HEAD)" website</code>
It will depend on <a>koino</a>, which is included as a git submodule. Adding new pages to the documentation is done by modifying the <code>menu_items</code> array in <code>src/tools/render-md-page.zig</code>. | [] |
https://avatars.githubusercontent.com/u/28556218?v=4 | linenoize | joachimschmidt557/linenoize | 2020-01-30T13:46:37Z | A port of linenoise to zig | master | 4 | 68 | 12 | 68 | https://api.github.com/repos/joachimschmidt557/linenoize/tags | MIT | [
"readline",
"zig",
"zig-package"
] | 122 | false | 2025-05-11T21:10:25Z | true | true | unknown | github | [
{
"commit": "master",
"name": "wcwidth",
"tar_url": "https://github.com/joachimschmidt557/zig-wcwidth/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/joachimschmidt557/zig-wcwidth"
}
] | linenoize
A port of <a>linenoise</a> to zig
aiming to be a simple readline for command-line applications written
in zig. It is written in pure zig and doesn't require
libc. <code>linenoize</code> works with the latest stable zig version (0.14.0).
In addition to being a full-fledged zig library, <code>linenoize</code> also
serves as a drop-in replacement for linenoise. As a proof of concept,
the example application from linenoise can be built with <code>zig build
c-example</code>.
Features
<ul>
<li>Line editing</li>
<li>Completions</li>
<li>Hints</li>
<li>History</li>
<li>Multi line mode</li>
<li>Mask input mode</li>
</ul>
Supported platforms
<ul>
<li>Linux</li>
<li>macOS</li>
<li>Windows</li>
</ul>
Add linenoize to a project
Add linenoize as a dependency to your project:
<code>bash
zig fetch --save git+https://github.com/joachimschmidt557/linenoize.git#v0.1.0</code>
Then add the following code to your <code>build.zig</code> file:
<code>zig
const linenoize = b.dependency("linenoize", .{
.target = target,
.optimize = optimize,
}).module("linenoise");
exe.root_module.addImport("linenoize", linenoize);</code>
Examples
Minimal example
```zig
const std = @import("std");
const Linenoise = @import("linenoise").Linenoise;
pub fn main() !void {
const allocator = std.heap.page_allocator;
<code>var ln = Linenoise.init(allocator);
defer ln.deinit();
while (try ln.linenoise("hello> ")) |input| {
defer allocator.free(input);
std.debug.print("input: {s}\n", .{input});
try ln.history.add(input);
}
</code>
}
```
Example of more features
``` zig
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const log = std.log.scoped(.main);
const Linenoise = @import("linenoise").Linenoise;
fn completion(allocator: Allocator, buf: []const u8) ![]const []const u8 {
if (std.mem.eql(u8, "z", buf)) {
var result = ArrayList([]const u8).init(allocator);
try result.append(try allocator.dupe(u8, "zig"));
try result.append(try allocator.dupe(u8, "ziglang"));
return result.toOwnedSlice();
} else {
return &[_][]const u8{};
}
}
fn hints(allocator: Allocator, buf: []const u8) !?[]const u8 {
if (std.mem.eql(u8, "hello", buf)) {
return try allocator.dupe(u8, " World");
} else {
return null;
}
}
var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
pub fn main() !void {
defer _ = debug_allocator.deinit();
const allocator = debug_allocator.allocator();
<code>var ln = Linenoise.init(allocator);
defer ln.deinit();
// Load history and save history later
ln.history.load("history.txt") catch log.err("Failed to load history", .{});
defer ln.history.save("history.txt") catch log.err("Failed to save history", .{});
// Set up hints callback
ln.hints_callback = hints;
// Set up completions callback
ln.completions_callback = completion;
// Enable mask mode
// ln.mask_mode = true;
// Enable multiline mode
// ln.multiline_mode = true;
while (try ln.linenoise("hellö> ")) |input| {
defer allocator.free(input);
log.info("input: {s}", .{input});
try ln.history.add(input);
}
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/7283681?v=4 | zigdig | lun-4/zigdig | 2019-05-12T05:39:02Z | naive dns client library in zig | master | 1 | 40 | 7 | 40 | https://api.github.com/repos/lun-4/zigdig/tags | MIT | [
"dns",
"zig",
"zig-package"
] | 647 | false | 2025-05-02T17:20:51Z | true | true | 0.14.0 | github | [] | zigdig
naive dns client library in zig
help me decide if this api is good: https://github.com/lun-4/zigdig/issues/10
what does it do
<ul>
<li>serialization and deserialization of dns packets as per rfc1035</li>
<li>supports a subset of rdata (i do not have any plans to support 100% of DNS, but SRV/MX/TXT/A/AAAA
are there, which most likely will be enough for your use cases)</li>
<li>has helpers for reading <code>/etc/resolv.conf</code> (not that much, really)</li>
</ul>
what does it not do
<ul>
<li>no edns0</li>
<li>support all resolv.conf options</li>
<li>can deserialize pointer labels, but does not serialize into pointers</li>
<li>follow CNAME records, this provides only the basic
serialization/deserializtion</li>
</ul>
how do
<ul>
<li>zig 0.14.0: https://ziglang.org</li>
<li>have a <code>/etc/resolv.conf</code></li>
<li>tested on linux, should work on bsd i think</li>
</ul>
```
git clone ...
cd zigdig
zig build test
zig build install --prefix ~/.local/
```
and then
<code>bash
zigdig google.com a</code>
or, for the host(1) equivalent
<code>bash
zigdig-tiny google.com</code>
using the library
getAddressList-style api
```zig
const dns = @import("dns");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
var allocator = gpa.alloator();
<code>var addresses = try dns.helpers.getAddressList("ziglang.org", allocator);
defer addresses.deinit();
for (addresses.addrs) |address| {
std.debug.print("we live in a society {}\n", .{address});
}
</code>
}
```
full api
```zig
const dns = @import("dns");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer {
_ = gpa.deinit();
}
var allocator = gpa.alloator();
<code>var name_buffer: [128][]const u8 = undefined;
const name = try dns.Name.fromString("ziglang.org", &name_buffer);
var questions = [_]dns.Question{
.{
.name = name,
.typ = .A,
.class = .IN,
},
};
var packet = dns.Packet{
.header = .{
.id = dns.helpers.randomHeaderId(),
.is_response = false,
.wanted_recursion = true,
.question_length = 1,
},
.questions = &questions,
.answers = &[_]dns.Resource{},
.nameservers = &[_]dns.Resource{},
.additionals = &[_]dns.Resource{},
};
// use helper function to connect to a resolver in the systems'
// resolv.conf
const conn = try dns.helpers.connectToSystemResolver();
defer conn.close();
try conn.sendPacket(packet);
// you can also do this to support any Writer
// const written_bytes = try packet.writeTo(some_fun_writer_goes_here);
const reply = try conn.receivePacket(allocator, 4096);
defer reply.deinit();
// you can also do this to support any Reader
// const packet = try dns.Packet.readFrom(some_fun_reader, allocator);
// defer packet.deinit();
const reply_packet = reply.packet;
logger.info("reply: {}", .{reply_packet});
try std.testing.expectEqual(packet.header.id, reply_packet.header.id);
try std.testing.expect(reply_packet.header.is_response);
// ASSERTS that there's one A resource in the answer!!! you should verify
// reply_packet.header.opcode to see if there's any errors
const resource = reply_packet.answers[0];
var resource_data = try dns.ResourceData.fromOpaque(
reply_packet,
resource.typ,
resource.opaque_rdata,
allocator
);
defer resource_data.deinit(allocator);
// you now have an std.net.Address to use to your hearts content
const ziglang_address = resource_data.A;
</code>
}
```
it is recommended to look at zigdig's source on <code>src/main.zig</code> to understand
how things tick using the library, but it boils down to three things:
- packet generation and serialization
- sending/receiving (via a small shim on top of std.os.socket)
- packet deserialization | [] |
https://avatars.githubusercontent.com/u/1327032?v=4 | zig-win32 | GoNZooo/zig-win32 | 2019-09-06T08:02:55Z | Bindings for win32, with and without WIN32_LEAN_AND_MEAN | master | 1 | 31 | 2 | 31 | https://api.github.com/repos/GoNZooo/zig-win32/tags | MIT | [
"win32",
"win32api",
"zig",
"zig-package"
] | 1,335 | false | 2025-04-05T01:53:48Z | true | false | unknown | github | [] | zig-win32
Archived
I would suggest using <a>this library</a> instead.
If there is some reason you cannot, feel free to reach out and I'll unarchive this so
people can continue to work on it if they want.
Linking
You will need to add something like the following to your <code>build.zig</code> depending
on what you end up using:
If you're using the <code>win32.c</code> module, most functions are annotated with their
library information, so you don't need to link anything, but at the time of
writing the <code>lean_and_mean</code> module is not annotated. With that in mind, you may
have to add build instructions like the following, depending on which functions
you use:
<code>zig
const exe = b.addExecutable("executable-name", "src/main.zig");
exe.addPackagePath("win32", "./dependencies/zig-win32/src/main.zig");
exe.linkSystemLibrary("c");
exe.linkSystemLibrary("gdi32");
exe.linkSystemLibrary("user32");
exe.linkSystemLibrary("kernel32");</code>
Usage in files
A simple import will do it, access the sub-namespaces with <code>c</code> and
<code>lean_and_mean</code>:
<code>zig
const win32 = @import("win32");
_ = win32.c.MessageBoxA(...);</code>
Or import one of the sub-namespaces directly:
<code>zig
const win32 = @import("win32").lean_and_mean;
_ = win32.MessageBoxA(...);</code>
Macros not available in the FFI files
<code>MAKEINTRESOURCE{A,W}</code> is not available in the generated files, but is available
in the top namespace:
<code>zig
const win32 = @import("win32");
const resource: windows.LPSTR = win32.MAKEINTRESOURCEA(32512);</code> | [] |
https://avatars.githubusercontent.com/u/65570835?v=4 | lscolors | ziglibs/lscolors | 2019-11-03T15:47:57Z | A zig library for colorizing paths according to LS_COLORS | master | 0 | 16 | 1 | 16 | https://api.github.com/repos/ziglibs/lscolors/tags | MIT | [
"ls-colors",
"zig",
"zig-package",
"ziglang"
] | 98 | false | 2025-05-07T07:19:42Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "ansi_term",
"tar_url": "https://github.com/ziglibs/ansi_term/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/ziglibs/ansi_term"
}
] | lscolors
A zig library for colorizing paths according to the <code>LS_COLORS</code>
environment variable. Designed to work with Zig 0.14.0.
Quick Example
```zig
const std = @import("std");
const LsColors = @import("lscolors").LsColors;
pub fn main() !void {
var gpa: std.heap.DebugAllocator(.{}) = .init;
defer _ = gpa.deinit();
const allocator = gpa.allocator();
<code>var lsc = try LsColors.fromEnv(allocator);
defer lsc.deinit();
var dir = try std.fs.cwd().openDir(".", .{ .iterate = true });
defer dir.close();
var iterator = dir.iterate();
while (try iterator.next()) |itm| {
std.log.info("{}", .{try lsc.styled(itm.name)});
}
</code>
}
``` | [
"https://github.com/joachimschmidt557/zigfd"
] |
https://avatars.githubusercontent.com/u/1327032?v=4 | zig-editor-core | GoNZooo/zig-editor-core | 2019-11-13T08:45:45Z | Eventually the core of an editor, interactive shell put on top. | master | 0 | 5 | 0 | 5 | https://api.github.com/repos/GoNZooo/zig-editor-core/tags | - | [
"editor",
"vim",
"zig",
"zig-package",
"ziglang"
] | 482 | false | 2023-09-02T23:14:58Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/28556218?v=4 | zig-termbox | joachimschmidt557/zig-termbox | 2020-01-30T13:48:36Z | A termbox implementation in zig | master | 0 | 3 | 1 | 3 | https://api.github.com/repos/joachimschmidt557/zig-termbox/tags | MIT | [
"zig",
"zig-package"
] | 68 | false | 2025-04-04T18:07:52Z | true | true | unknown | github | [
{
"commit": "master",
"name": "wcwidth",
"tar_url": "https://github.com/joachimschmidt557/zig-wcwidth/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/joachimschmidt557/zig-wcwidth"
},
{
"commit": "master",
"name": "ansi_term",
"tar_url": "https://github.com/z... | zig-termbox
termbox-inspired library for creating terminal user interfaces
Works with Zig 0.14.0.
Concepts
<code>termbox</code> is a <em>double-buffered</em> terminal library. This means that
when you call functions to draw on the screen, you are not actually
sending data to the terminal, but instead act on an intermediate data
structure called the <em>back buffer</em>. Only when you call
<code>Termbox.present</code>, the terminal is actually updated to reflect the
state of the <em>back buffer</em>.
An advantage of this design is that repeated calls to
<code>Termbox.present</code> only update the parts of the terminal interface that
have actually changed since the last call. <code>termbox</code> achieves this by
tracking the current state of the terminal in the internal <em>front
buffer</em>.
Examples
```zig
const std = @import("std");
const termbox = @import("termbox");
const Termbox = termbox.Termbox;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
<code>var t = try Termbox.init(allocator);
defer t.shutdown() catch {};
var anchor = t.back_buffer.anchor(1, 1);
try anchor.writer().print("Hello {s}!", .{"World"});
anchor.move(1, 2);
try anchor.writer().print("Press any key to quit", .{});
try t.present();
_ = try t.pollEvent();
</code>
}
```
Further examples can be found in the <code>examples</code> subdirectory. | [] |
https://avatars.githubusercontent.com/u/1327032?v=4 | zig-humantime | GoNZooo/zig-humantime | 2019-08-07T14:41:51Z | Mini library for expressing integer time values in more human readable ways | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/GoNZooo/zig-humantime/tags | MIT | [
"zig",
"zig-package"
] | 8 | false | 2021-09-23T09:52:12Z | true | false | unknown | github | [] | zig-humantime
This library exports two functions to convert human readable time strings into integer values:
```zig
test "1h2m3s" {
const time = comptime seconds("1h2m3s");
// @compileLog(time) -> 7446
testing.expectEqual(time, 3723);
}
test "2h4m6s" {
const time = comptime seconds("2h4m6s");
testing.expectEqual(time, (3600 * 2) + (4 * 60) + 6);
}
test "1h2m3s in milliseconds" {
const format_string = "1h2m3s";
const time = milliseconds(format_string);
// @compileLog(time) -> runtime value
testing.expectEqual(time, comptime seconds(format_string) * 1000);
}
test "5d4h3m2s" {
testing.expectEqual(seconds("5d4h3m2s"), 446582);
}
``` | [] |
https://avatars.githubusercontent.com/u/28556218?v=4 | zig-walkdir | joachimschmidt557/zig-walkdir | 2019-06-26T07:40:29Z | Provides functions for walking directories recursively | master | 1 | 1 | 0 | 1 | https://api.github.com/repos/joachimschmidt557/zig-walkdir/tags | MIT | [
"zig",
"zig-package"
] | 45 | false | 2025-03-08T22:25:54Z | true | true | unknown | github | [] | zig-walkdir
A zig package providing functions for recursively traversing directories.
Works with zig 0.14.0.
Todo
<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> Breadth-first search
<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> Depth-first search
<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> Tests
<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> Following symlinks
<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> Correct error handling | [] |
https://avatars.githubusercontent.com/u/48649707?v=4 | zig-cookie | tensorush/zig-cookie | 2024-03-05T18:13:03Z | Zig port of cookie-rs library for HTTP cookie storage. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/tensorush/zig-cookie/tags | MIT | [
"zig-package"
] | 36 | false | 2025-03-18T06:57:17Z | true | true | 0.14.0 | github | [] | zig-cookie
Zig port of <a>cookie-rs library</a> for HTTP cookie storage.
Usage
<ul>
<li>Add <code>cookie</code> dependency to <code>build.zig.zon</code>.</li>
</ul>
<code>sh
zig fetch --save git+https://github.com/tensorush/zig-cookie</code>
<ul>
<li>Use <code>cookie</code> dependency in <code>build.zig</code>.</li>
</ul>
<code>zig
const cookie_dep = b.dependency("cookie", .{
.target = target,
.optimize = optimize,
});
const cookie_mod = cookie_dep.module("cookie");
<compile>.root_module.addImport("cookie", cookie_mod);</code> | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | druntime-zigbuild | kassane/druntime-zigbuild | 2024-06-22T16:32:24Z | D runtime build using zig-build | main | 3 | 1 | 0 | 1 | https://api.github.com/repos/kassane/druntime-zigbuild/tags | NOASSERTION | [
"build-system",
"cross-compile",
"d",
"dlang",
"zig-build",
"zig-package"
] | 4,636 | false | 2024-09-17T14:34:03Z | true | true | unknown | github | [
{
"commit": "c7e33a3b1dfb3b9ca8f5da3d7cb282852ad34547",
"name": "abs",
"tar_url": "https://github.com/kassane/anotherBuildStep/archive/c7e33a3b1dfb3b9ca8f5da3d7cb282852ad34547.tar.gz",
"type": "remote",
"url": "https://github.com/kassane/anotherBuildStep"
},
{
"commit": "788d4b0fed3c7ba4... | Druntime + phobos (standalone) for zig-build (ABS)
<blockquote>
[!Note]
A standalone runtime + stdlib (for easy cross-compile) using ABS is the goal of this project
</blockquote>
<strong>More info:</strong> <a>issue#6: cross-compile with Druntime + Phobos2</a>
<code>bash
Project-Specific Options:
-Dtarget=[string] The CPU architecture, OS, and ABI to build for
-Dcpu=[string] Target CPU features to add or subtract
-Ddynamic-linker=[string] Path to interpreter on the target system
-Doptimize=[enum] Prioritize performance, safety, or binary size
Supported Values:
Debug
ReleaseSafe
ReleaseFast
ReleaseSmall
-Dlinkage=[enum] Change linking mode (default: static)
Supported Values:
static
dynamic
-Dphobos=[bool] Build phobos library (default: false)</code> | [] |
https://avatars.githubusercontent.com/u/22280250?v=4 | zigStructPrint | Durobot/zigStructPrint | 2024-03-01T09:52:26Z | Small library to pretty-print Zig structs (and arrays) | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/Durobot/zigStructPrint/tags | MIT | [
"zig",
"zig-package",
"ziglang"
] | 14 | false | 2024-10-10T07:01:19Z | true | true | 0.12.0-dev.3097+5c0766b6c | github | [] | zigStructPrint
Small library to pretty-print Zig structs (and arrays)
<strong>zigStructPrint</strong> is licensed under under <a>the MIT License</a> and available from https://github.com/Durobot/zigStructPrint
Please note that only Zig <strong>0.14.0-dev.1421+f87dd43c1</strong> (give or take) and up is supported because of <a>this breaking change</a> in the Zig standard library. If you need zigStructPrint for an earlier version of Zig, get <a>this version</a> instead.
To use, either drop <a>zsp.zig</a> into your project, or, if you prefer Zig package manager:
<ol>
<li>In <code>build.zig.zon</code>, in <code>.dependencies</code>, add</li>
</ol>
<code>zig
.zigStructPrint =
.{
.url = "https://github.com/Durobot/zigStructPrint/archive/<COMMIT HASH, 40 HEX DIGITS>.tar.gz",
.hash = "<ZIG PACKAGE HASH, 68 HEX DIGITS>" // Use arbitrary hash, get correct hash from the error
}</code>
<ol>
<li>In <code>build.zig</code>, in <code>pub fn build</code>, before <code>b.installArtifact(exe);</code>, add</li>
</ol>
<code>zig
const zsp = b.dependency("zigStructPrint",
.{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zigStructPrint", zsp.module("zigStructPrint"));</code>
Build with <code>zig build</code>, as you normally do.
Actually printing out your struct:
```zig
const zsp = @import("zigStructPrint");
. . .
const MyStruct = struct
{
a: i8 = -10,
b: u32 = 10,
c: [3]u8 = [_]u8 { 1, 2, 3 },
d: [2]Nested = .{ .{ .f = 10.0, .g = "Hello" }, .{ .f = -20.0, .g = "Bye" }, },
e: [3]Color = .{ .red, .green, .yellow },
<code>const Nested = struct { f: f32, g: []const u8 };
const Color = enum { red, yellow, green };
</code>
};
const ms = MyStruct {};
zsp.printStruct(ms, true, 0); // try <code>false</code> to get full type names
```
And the output is:
<code>zig
{
a: i8 = -10
b: u32 = 10
c: [3]u8 = [ 1, 2, 3, ]
d: [2]Nested = [ { f: f32 = 10, g: []const u8 = "Hello", }, { f: f32 = -20, g: []const u8 = "Bye", }, ]
e: [3]Color = [ red, green, yellow, ]
}</code> | [] |
https://avatars.githubusercontent.com/u/48999343?v=4 | sysexits-zig | sorairolake/sysexits-zig | 2024-05-04T11:55:57Z | The system exit codes as defined by <sysexits.h> for Zig | develop | 0 | 1 | 1 | 1 | https://api.github.com/repos/sorairolake/sysexits-zig/tags | Apache-2.0 | [
"exitcode",
"sysexits",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 99 | false | 2025-05-12T22:03:00Z | true | true | 0.14.0 | github | [] |
sysexits-zig
<a></a>
<strong>sysexits-zig</strong> is a library that provides the system exit code constants as
defined by [<code><sysexits.h></code>].
This library is a port of <a>sysexits-rs</a>.
Usage
Add this package to your <code>build.zig.zon</code>:
<code>sh
zig fetch --save git+https://github.com/sorairolake/sysexits-zig.git</code>
Add the following to your <code>build.zig</code>:
<code>zig
const sysexits = b.dependency("sysexits", .{});
exe.root_module.addImport("sysexits", sysexits.module("sysexits"));</code>
Documentation
To build the documentation:
<code>sh
zig build doc</code>
The result is generated in <code>zig-out/doc/sysexits</code>.
If you want to preview this, run a HTTP server locally. For example:
<code>sh
python -m http.server -d zig-out/doc/sysexits</code>
Then open <code>http://localhost:8000/</code> in your browser.
Zig version
This library is compatible with Zig version 0.14.0.
Source code
The upstream repository is available at
<a>https://github.com/sorairolake/sysexits-zig.git</a>.
The source code is also available at:
<ul>
<li><a>https://gitlab.com/sorairolake/sysexits-zig.git</a></li>
<li><a>https://codeberg.org/sorairolake/sysexits-zig.git</a></li>
</ul>
Changelog
Please see <a>CHANGELOG.adoc</a>.
Contributing
Please see <a>CONTRIBUTING.adoc</a>.
Similar projects
<ul>
<li><a>https://github.com/sorairolake/Sysexits.jl</a> (Julia)</li>
<li><a>https://github.com/sorairolake/sysexits-rs</a> (Rust)</li>
</ul>
You can discover more projects at
<a>https://github.com/sorairolake/awesome-sysexits</a>.
License
Copyright (C) 2023 Shun Sakai (see <a>AUTHORS.adoc</a>)
This library is distributed under the terms of either the <em>Apache License 2.0</em>
or the <em>MIT License</em>.
This project is compliant with version 3.3 of the <a><em>REUSE Specification</em></a>. See
copyright notices of individual files for more details on copyright and
licensing information. | [] |
https://avatars.githubusercontent.com/u/48649707?v=4 | zig-exhaustigen | tensorush/zig-exhaustigen | 2024-07-17T18:44:59Z | Zig port of exhaustigen-rs library for exhaustive testing. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/tensorush/zig-exhaustigen/tags | MIT | [
"zig-package"
] | 12 | false | 2025-05-04T02:07:17Z | true | true | 0.14.0 | github | [] | zig-exhaustigen
Zig port of <a>exhaustigen-rs library</a> for exhaustive testing.
Usage
<ul>
<li>Add <code>exhaustigen</code> dependency to <code>build.zig.zon</code>.</li>
</ul>
<code>sh
zig fetch --save git+https://github.com/tensorush/zig-exhaustigen</code>
<ul>
<li>Use <code>exhaustigen</code> dependency in <code>build.zig</code>.</li>
</ul>
<code>zig
const exhaustigen_dep = b.dependency("exhaustigen", .{
.target = target,
.optimize = optimize,
});
const exhaustigen_mod = exhaustigen_dep.module("Gen");
<compile>.root_module.addImport("Gen", exhaustigen_mod);</code> | [] |
https://avatars.githubusercontent.com/u/25912761?v=4 | zigenity | r4gus/zigenity | 2024-03-03T15:07:13Z | Like zenity but in Zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/r4gus/zigenity/tags | MIT | [
"gtk",
"gtk3",
"gui",
"zig",
"zig-package"
] | 39 | false | 2025-05-11T21:44:52Z | true | true | 0.14.0 | github | [
{
"commit": "a1717e0d0758417cc59de63ab0d65592d08a03ff",
"name": "dvui",
"tar_url": "https://github.com/david-vanderson/dvui/archive/a1717e0d0758417cc59de63ab0d65592d08a03ff.tar.gz",
"type": "remote",
"url": "https://github.com/david-vanderson/dvui"
}
] | zigenity
Like <a>zenity</a> but in <a>Zig</a> and only for Linux.
Dialog Types
| Type | Supported |
|:----:|:---------:|
| calendar | |
| entry | |
| error | |
| info | |
| file-selection | |
| list | |
| notification | |
| progress | |
| question | ✅ |
| warning | |
| scale | |
| text-info | |
| color-selection | |
| password | ✅ |
| forms | |
Getting started
Run <code>zigenity --help</code> for a list of options.
This application uses the same return codes and options as <a>zenity</a>, including:
* <code>0</code> - Ok button was pressed
* <code>1</code> - Cancel button was pressed
* <code>5</code> - Timeout (this is only returned when using the <code>--timeout</code> option)
* <code>255</code> - Some other error (e.g., no dialog type has been selected) | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | cfitsio | allyourcodebase/cfitsio | 2024-07-16T10:22:37Z | Zig build of CFITSIO library. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/allyourcodebase/cfitsio/tags | MIT | [
"cfitsio",
"fits",
"fits-files",
"fits-image",
"fitsio",
"zig",
"zig-lang",
"zig-language",
"zig-library",
"zig-package",
"ziglang"
] | 12 | false | 2024-07-24T11:00:42Z | true | true | 0.13.0 | github | [
{
"commit": "cfitsio4_4_1_20240617.tar.gz",
"name": "cfitsio",
"tar_url": "https://github.com/HEASARC/cfitsio/archive/cfitsio4_4_1_20240617.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/HEASARC/cfitsio"
}
] | cfitsio
<a></a>
<a></a>
Zig build of <a>cfitsio library</a>.
:rocket: Usage
<ul>
<li>Add <code>cfitsio</code> dependency to <code>build.zig.zon</code>.</li>
</ul>
<code>sh
zig fetch --save https://github.com/allyourcodebase/cfitsio/archive/<git_tag_or_commit_hash>.tar.gz</code>
<ul>
<li>Use <code>cfitsio</code> dependency in <code>build.zig</code>.</li>
</ul>
<code>zig
const cfitsio_dep = b.dependency("cfitsio", .{
.target = target,
.optimize = optimize,
});
const cfitsio_mod = cfitsio_dep.module("cfitsio");
<compile>.root_module.addImport("cfitsio", cfitsio_mod);</code>
| [
"https://github.com/allyourcodebase/cfitsio"
] |
https://avatars.githubusercontent.com/u/4185906?v=4 | zig-ulid | Vemahk/zig-ulid | 2024-06-17T03:55:29Z | A binary, zero-allocation Ulid implementation written in Zig. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/Vemahk/zig-ulid/tags | MIT | [
"zig-package"
] | 12 | false | 2024-07-21T01:17:32Z | true | true | 0.12.0 | github | [] | zig-ulid
A binary, zero-alloc <a>zig</a> implementation of <a>Ulid</a>.
Tested with zig 0.12.0 and 0.13.0. If not for b.path(), it would probably work for 0.11.0.
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> No allocations
<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> To/From String
<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> Monotonicity
Examples
```zig
// Default usage
const Ulid = @import("ulid");
const id = Ulid.new();
const str = id.toString(); // e.g. "01J0J510YN2KZV7APEE1BQ8BYP"
const copy = try Ulid.parseString(str); // == id
const epoch_ms: u48 = ulid.timestamp();
const random_data: [10]u8 = ulid.data();
// Monotonic
var monotonic = Ulid.MonotonicFactory{};
const ulid_1 = try monotonic.next(); // e.g. "01J0JBY3EXAVVZ227VE93QJD2M"
const ulid_2 = try monotonic.next(); // e.g. "01J0JBY3EXAVVZ227VE93QJD2N"
// or using the global factory (not recommended but available)
const ulid_3 = try Ulid.newMonotonic(); // e.g. "01J0JC10BFE2CJB7M2SZXX98NH"
const ulid_4 = try Ulid.newMonotonic(); // e.g. "01J0JC10BFE2CJB7M2SZXX98NJ"
```
Use
build.zig.zon
<code>.ulid = .{
.url = "https://github.com/Vemahk/zig-ulid/archive/<git_commit_hash>.tar.gz",
},</code>
build.zig
```zig
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const root = b.path("src/main.zig");
const exe = b.addExecutable(.{
.name = "your_project",
.root_source_file = root,
.target = target,
.optimize = optimize,
});
const dep_opts = .{ .target = target, .optimize = optimize };
const ulid_mod = b.dependency("ulid", dep_opts).module("ulid");
exe.root_module.addImport("ulid", ulid_mod);
b.installArtifact(exe);
``` | [] |
https://avatars.githubusercontent.com/u/57362253?v=4 | wayland.zig | tiawl/wayland.zig | 2024-02-28T20:54:45Z | wayland headers packaged for @ziglang | trunk | 0 | 1 | 1 | 1 | https://api.github.com/repos/tiawl/wayland.zig/tags | Unlicense | [
"binding",
"spaceporn",
"wayland",
"wayland-protocol",
"zig",
"zig-package",
"ziglang"
] | 397 | false | 2025-05-09T12:11:20Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "toolbox",
"tar_url": "https://github.com/tiawl/toolbox/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/tiawl/toolbox"
}
] | wayland.zig
This is a fork of <a>hexops/wayland-headers</a> which itself gather various <a>Wayland</a> headers <a>GLFW</a> needs.
Why this forkception ?
The intention under this fork is the same as <a>hexops</a> had when they opened their repository: gather <a>Wayland</a> headers and package them to compile <a>GLFW</a> with <a>Zig</a>.
However this repository has subtle differences for maintainability tasks:
* No shell scripting,
* A cron runs every day to check <a>Wayland</a> repositories. Then it updates this repository if a new release is available.
How to use it
The current usage of this repository is centered around <a>tiawl/glfw.zig</a> compilation. But you could use it for your own projects. Headers are here and there are no planned evolution to modify them. See <a>tiawl/glfw.zig</a> to see how you can use it. Maybe for your own need, some headers are missing. If it happens, open an issue: this repository is open to potential usage evolution.
Dependencies
The <a>Zig</a> part of this package is relying on the latest <a>Zig</a> release (0.14.0) and will only be updated for the next one (so for the 0.14.1).
Here the repositories' version used by this fork:
* <a>wayland/wayland</a>
* <a>wayland/wayland-protocols</a>
CICD reminder
These repositories are automatically updated when a new release is available:
* <a>tiawl/glfw.zig</a>
This repository is automatically updated when a new release is available from these repositories:
* <a>wayland/wayland</a>
* <a>wayland/wayland-protocols</a>
* <a>tiawl/toolbox</a>
<code>zig build</code> options
These additional options have been implemented for maintainability tasks:
<code>-Dfetch Update .references folder and build.zig.zon then stop execution
-Dupdate Update binding</code>
License
This repository is not subject to a unique License:
The parts of this repository originated from this repository are dedicated to the public domain. See the LICENSE file for more details.
<strong>For other parts, it is subject to the License restrictions their respective owners choosed. By design, the public domain code is incompatible with the License notion. In this case, the License prevails. So if you have any doubt about a file property, open an issue.</strong> | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | Zig-fmtHelper | bcrist/Zig-fmtHelper | 2024-05-13T22:42:38Z | Some std.fmt helpers for Zig programs | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/bcrist/Zig-fmtHelper/tags | MIT | [
"formatting",
"gigabytes",
"kilobytes",
"megabytes",
"units",
"utilities",
"utility-library",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 20 | false | 2025-05-20T03:59:08Z | true | true | 0.14.0 | github | [] | Zig-fmtHelper
Includes several std.fmt helpers, including:
<ul>
<li><code>bytes</code>: automatically format large byte values in KB, MB, GB, TB, etc.</li>
<li><code>si</code>: automatically format large or small values using SI unit prefixes.</li>
</ul>
Installation
Add to your <code>build.zig.zon</code>:
<code>$ zig fetch --save git+https://github.com/bcrist/Zig-fmtHelper</code>
Add to your <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const fmt_module = b.dependency("fmt_helper", .{}).module("fmt");
<code>//...
const exe = b.addExecutable(.{
//...
});
exe.root_module.addImport("fmt", fmt_module);
//...
</code>
}
```
Example Usage
```zig
pub fn print_stats(some_number_of_bytes: usize, some_number_of_nanoseconds: usize) !void {
std.io.getStdOut().writer().print(
\ some number of bytes: {}
\ some duration: {}
\
, .{
fmt.bytes(some_number_of_bytes),
fmt.si.ns(some_number_of_nanoseconds),
});
}
const fmt = @import("fmt");
const std = @import("std");
<code>Possible output:</code>
some number of bytes: 3 KB
some duration: 47 ms
``` | [] |
https://avatars.githubusercontent.com/u/164784529?v=4 | ja3-spoof | bstrdlord/ja3-spoof | 2024-03-28T15:09:29Z | http client for zig that spoofs tls/ssl ja3 | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/bstrdlord/ja3-spoof/tags | - | [
"curl",
"ja3",
"spoof",
"ssl",
"tls",
"zig",
"zig-package"
] | 22 | false | 2024-03-30T01:25:30Z | true | true | unknown | github | [] | TTL/SSL JA3 Spoof
<strong>A curl-based zig http client that can spoof <a>tls/ssl ja3</a></strong>
📦 Installing
1. Install ja3_spoof
<code>zig fetch --save https://github.com/blockkwork/ja3-spoof/archive/refs/tags/[LATEST TAG].tar.gz</code>
Example
<code>zig fetch --save https://github.com/blockkwork/ja3-spoof/archive/refs/tags/0.0.1.tar.gz</code>
2. Add ja3_spoof to build.zig
Add to build.zig
<code>zig
const ja3_spoof = b.dependency("ja3_spoof", .{}).module("ja3_spoof");
exe.root_module.addImport("ja3_spoof", ja3_spoof);</code>
🚀 Examples
Example in ./examples folder
Run with command:
<code>make EXAMPLE</code>
```zig
const client = ja3_spoof.init(.{
.allocator = allocator,
.custom_cookies = "Cookie",
.custom_user_agent = "ja3 spoof",
.custom_ciphers = "AES256-SHA",
}) catch |err| {
std.debug.print("error: {}\n", .{err});
return;
};
const response = client.send("https://tools.scrapfly.io/api/tls") catch |err| {
std.debug.print("error: {}\n", .{err});
return;
};
std.debug.print("status_code: {}\nresponse: {s}\n", .{ response.status_code, response.response });
```
🛡️ Spoofing
To spoof ja3 you need to change .custom_ciphers to any other in Client Options | [] |
https://avatars.githubusercontent.com/u/41784264?v=4 | zTroy | jinzhongjia/zTroy | 2024-06-25T13:34:56Z | a zig library | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/jinzhongjia/zTroy/tags | - | [
"zig",
"zig-package"
] | 26 | false | 2025-05-03T19:19:22Z | true | true | 0.12.0 | github | [] | zTroy
A versatile libary.
The goal of this library is to create a general library of basic functional functions
<blockquote>
Now, this library is developing!
</blockquote>
Feature
<code>.ini</code> parse
Install
zig version: <code>0.12.0</code> or higher!
<ol>
<li>Add to <code>build.zig.zon</code></li>
</ol>
```sh
It is recommended to replace the following branch with commit id
zig fetch --save https://github.com/jinzhongjia/zTroy/archive/main.tar.gz
Of course, you can also use git+https to fetch this package!
```
<ol>
<li>Config <code>build.zig</code></li>
</ol>
Add this:
<code>``zig
// To standardize development, maybe you should use</code>lazyDependency()<code>instead of</code>dependency()`
// more info to see: https://ziglang.org/download/0.12.0/release-notes.html#toc-Lazy-Dependencies
const zTroy = b.dependency("zTroy", .{
.target = target,
.optimize = optimize,
});
// add module
exe.root_module.addImport("tory", zTroy.module("troy"));
```
Document
Waiting to be added! | [] |
https://avatars.githubusercontent.com/u/98696261?v=4 | sap | Reokodoku/sap | 2024-08-02T10:35:31Z | A simple argument parser library for zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/Reokodoku/sap/tags | MIT | [
"argument-parser",
"zig",
"zig-package"
] | 28 | false | 2024-09-05T19:27:20Z | true | true | 0.14.0-dev.1421+f87dd43c1 | github | [] | sap
sap is a simple argument parser library for zig that uses a tuple of flags to create a struct containing the value of the arguments.
How to add the library
<ol>
<li>Run in the terminal:
<code>sh
zig fetch --save git+https://github.com/Reokodoku/sap</code></li>
<li>Add in your <code>build.zig</code>:
<code>zig
const sap = b.dependency("sap", .{});
exe.root_module.addImport("sap", sap.module("sap"));</code></li>
</ol>
Examples
Minimal example:
```zig
const sap = @import("sap");
var arg_parser = sap.Parser(.{
sap.flag([]const u8, "hello", 'h', "world"),
}).init(allocator);
defer arg_parser.deinit();
const args = try arg_parser.parseArgs();
std.debug.print("Executable name: {s}\n", .{args.executable_name});
var positionals_iter = args.positionals.iterator();
std.debug.print("Positionals:\n", .{});
while (positionals_iter.next()) |str|
std.debug.print(" {s}\n", .{str});
std.debug.print("<code>hello</code>|<code>h</code> flag value: {s}\n", .{args.hello});
```
You can find more examples in the <code>examples/</code> folder.
For more information, see the source code or documentation (<code>zig build docs</code>).
Features
<ul>
<li>short arguments</li>
<li>long arguments</li>
<li>pass values after an equal (<code>--foo=bar</code>) or a space (<code>--foo bar</code>)</li>
<li>flags can be specified multiple times</li>
<li>flags that call a function</li>
<li>supported types:<ul>
<li>booleans</li>
<li>strings</li>
<li>ints (signed and unsigned)</li>
<li>floats</li>
<li>enums</li>
<li>and all optional variants of the above (<code>?bool</code>, <code>?[]const u8</code>, ...)</li>
</ul>
</li>
</ul>
Zig version
sap targets the master branch of zig.
In the <code>build.zig.zon</code> file, there is the <code>minimum_zig_version</code> field which specifies the latest version of zig in which sap compiles.
When the zig master branch breaks the compilation, a commit will be merged to:
<ul>
<li>fix the compilation errors</li>
<li>update the <code>minimum_zig_version</code> field with the new zig version</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/112193680?v=4 | zig-river-config | nitrogenez/zig-river-config | 2024-06-05T21:31:10Z | River configuration with the power of a programming language. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/nitrogenez/zig-river-config/tags | BSD-3-Clause | [
"configuration",
"river",
"riverwm",
"utility",
"wayland",
"wayland-compositor",
"zig",
"zig-lang",
"zig-language",
"zig-library",
"zig-package",
"ziglang"
] | 22 | false | 2024-06-09T07:00:17Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/28966224?v=4 | escalator | weskoerber/escalator | 2024-05-23T02:36:36Z | A library for privelege-escalation written in Zig. | main | 1 | 1 | 0 | 1 | https://api.github.com/repos/weskoerber/escalator/tags | MIT | [
"zig",
"zig-package"
] | 4 | false | 2024-08-09T03:29:37Z | true | true | 0.12.0 | github | [] | Escalator
A library for privelege-escalation written in Zig.
Requirements
<ul>
<li><a>zig</a> compiler (<code>0.12.0</code> or newer)</li>
</ul>
Install
First, add the dependency to your <code>build.zig.zon</code> using <code>zig fetch</code>:
<code>console
zig fetch --save git+https://github.com/weskoerber/escalator#main</code>
Then, import <code>escalator</code> into 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 escalator = b.dependency("escalator", .{
.target = target,
.optimize = optimize,
}).module("escalator");
const my_exe = b.addExecutable(.{
.name = "my_exe",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
my_exe.root_module.addImport(escalator);
</code>
}
```
Usage
Documentation can be found at https://weskoerber.github.io/escalator. The docs
are generated by Zig's autodoc feature and deployed via Github Actions.
Also see the <code>examples</code> directory for example usage. Example executables can be
built by setting the <code>examples</code> option to <code>true</code>:
<code>zig
const mac_address = b.dependency("escalator", .{
.target = target,
.optimize = optimize,
.examples = true,
}).module("escalator");</code>
Acknowlegments
<ul>
<li><a>dns2utf8/sudo.rs</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | rabbitmq-c | allyourcodebase/rabbitmq-c | 2024-08-03T17:29:16Z | RabbitMQ C client (zig build) | zig-build | 0 | 1 | 1 | 1 | https://api.github.com/repos/allyourcodebase/rabbitmq-c/tags | MIT | [
"librabbitmq-c",
"rabbitmq",
"rabbitmq-client",
"zig-build",
"zig-package"
] | 2,201 | true | 2025-05-17T14:46:59Z | true | false | unknown | github | [] | RabbitMQ C AMQP client library
<a></a>
<a></a>
<a></a>
Introduction
This is a C-language AMQP client library for use with v2.0+ of the
<a>RabbitMQ</a> broker.
<ul>
<li><a>http://github.com/alanxz/rabbitmq-c</a></li>
</ul>
Announcements regarding the library are periodically made on the
rabbitmq-c-users and cross-posted to rabbitmq-users.
<ul>
<li><a>https://groups.google.com/forum/#!forum/rabbitmq-c-users</a></li>
<li><a>https://groups.google.com/forum/#!forum/rabbitmq-users</a></li>
</ul>
Latest Stable Version
The latest stable release of rabbitmq-c can be found at:
<ul>
<li><a>https://github.com/alanxz/rabbitmq-c/releases/latest</a></li>
</ul>
Documentation
API documentation for v0.8.0+ can viewed from:
<a>http://alanxz.github.io/rabbitmq-c/docs/0.8.0/</a>
Getting started
Building and installing
Prereqs:
<ul>
<li><a>CMake v3.22 or better</a></li>
<li>A C compiler (GCC 4.4+, clang, and MSVC are test. Other compilers may also
work)</li>
<li><em>Optionally</em> <a>OpenSSL</a> v1.1.1+ to enable support for
connecting to RabbitMQ over SSL/TLS</li>
<li><em>Optionally</em> <a>POpt</a> to build some handy
command-line tools.</li>
<li><em>Optionally</em> <a>XmlTo</a> to build man pages for
the handy command-line tools</li>
<li><em>Optionally</em> <a>Doxygen</a> to build
developer API documentation.</li>
</ul>
After downloading and extracting the source from a tarball to a directory
(<a>see above</a>), the commands to build rabbitmq-c on most
systems are:
<code>mkdir build && cd build
cmake ..
cmake --build . [--config Release]
</code>
The --config Release flag should be used in multi-configuration generators e.g.,
Visual Studio or XCode.
It is also possible to point the CMake GUI tool at the CMakeLists.txt in the root of
the source tree and generate build projects or IDE workspace
Installing the library and optionally specifying a prefix can be done with:
<code>cmake -DCMAKE_INSTALL_PREFIX=/usr/local ..
cmake --build . [--config Release] --target install
</code>
More information on CMake can be found on its FAQ (http://www.cmake.org/Wiki/CMake_FAQ)
Other interesting flags that can be passed to CMake:
<ul>
<li><code>BUILD_EXAMPLES=ON/OFF</code> toggles building the examples. OFF by default.</li>
<li><code>BUILD_SHARED_LIBS=ON/OFF</code> toggles building rabbitmq-c as a shared library.
ON by default.</li>
<li><code>BUILD_STATIC_LIBS=ON/OFF</code> toggles building rabbitmq-c as a static library.
ON by default.</li>
<li><code>BUILD_TESTING=ON/OFF</code> toggles building test code. ON by default.</li>
<li><code>BUILD_TOOLS=ON/OFF</code> toggles building the command line tools. By default
this is ON if the build system can find the POpt header and library.</li>
<li><code>BUILD_TOOLS_DOCS=ON/OFF</code> toggles building the man pages for the command line
tools. By default this is ON if BUILD_TOOLS is ON and the build system can
find the XmlTo utility.</li>
<li><code>ENABLE_SSL_SUPPORT=ON/OFF</code> toggles building rabbitmq-c with SSL support. By
default this is ON if the OpenSSL headers and library can be found.</li>
<li><code>BUILD_API_DOCS=ON/OFF</code> - toggles building the Doxygen API documentation, by
default this is OFF</li>
<li><code>RUN_SYSTEM_TESTS=ON/OFF</code> toggles building the system tests (i.e. tests requiring
an accessible RabbitMQ server instance on localhost), by default this is OFF</li>
</ul>
Building RabbitMQ - Using vcpkg
You can download and install RabbitMQ using the <a>vcpkg</a>
dependency manager:
<code>git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
./vcpkg install librabbitmq
</code>
The RabbitMQ port in vcpkg is kept up to date by Microsoft team members and
community contributors. If the version is out of date,
please <a>create an issue or pull request</a> on the vcpkg repository.
Running the examples
Arrange for a RabbitMQ or other AMQP server to be running on
<code>localhost</code> at TCP port number 5672.
In one terminal, run
<code>./examples/amqp_listen localhost 5672 amq.direct test
</code>
In another terminal,
<code>./examples/amqp_sendstring localhost 5672 amq.direct test "hello world"
</code>
You should see output similar to the following in the listener's
terminal window:
<code>Delivery 1, exchange amq.direct routingkey test
Content-type: text/plain
----
00000000: 68 65 6C 6C 6F 20 77 6F : 72 6C 64 hello world
0000000B:
</code>
Writing applications using <code>librabbitmq</code>
Please see the <code>examples</code> directory for short examples of the use of
the <code>librabbitmq</code> library.
Threading
You cannot share a socket, an <code>amqp_connection_state_t</code>, or a channel
between threads using <code>librabbitmq</code>. The <code>librabbitmq</code> library is
built with event-driven, single-threaded applications in mind, and
does not yet cater to any of the requirements of <code>pthread</code>ed
applications.
Your applications instead should open an AMQP connection (and an
associated socket, of course) per thread. If your program needs to
access an AMQP connection or any of its channels from more than one
thread, it is entirely responsible for designing and implementing an
appropriate locking scheme. It will generally be much simpler to have
a connection exclusive to each thread that needs AMQP service.
License & Copyright
Portions created by Alan Antonuk are Copyright (c) 2012-2021
Alan Antonuk. All Rights Reserved.
Portions created by VMware are Copyright (c) 2007-2012 VMware, Inc.
All Rights Reserved.
Portions created by Tony Garnock-Jones are Copyright (c) 2009-2010
VMware, Inc. and Tony Garnock-Jones. All Rights Reserved.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. | [] |
https://avatars.githubusercontent.com/u/53385738?v=4 | zig-pkg | roastpie/zig-pkg | 2024-04-12T11:55:13Z | Zig Package Aggregator | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/roastpie/zig-pkg/tags | - | [
"zig-package",
"ziglang"
] | 0 | false | 2024-04-28T23:17:19Z | false | false | unknown | github | [] | Zig Package Aggregator | [] |
https://avatars.githubusercontent.com/u/57362253?v=4 | spirv.zig | tiawl/spirv.zig | 2024-04-08T17:05:20Z | spirv-tools packaged for @ziglang | trunk | 0 | 1 | 1 | 1 | https://api.github.com/repos/tiawl/spirv.zig/tags | Unlicense | [
"binding",
"spaceporn",
"spirv",
"spirv-tools",
"zig",
"zig-package",
"ziglang"
] | 3,225 | false | 2025-05-21T09:17:48Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "toolbox",
"tar_url": "https://github.com/tiawl/toolbox/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/tiawl/toolbox"
}
] | spirv.zig
This is a fork of <a>hexops/spirv-tools</a> which itself is a fork of <a>KhronosGroup/SPIRV-Tools</a>.
Why this forkception ?
The intention under this fork is the same as <a>hexops</a> had when they forked <a>KhronosGroup/SPIRV-Tools</a>: package the headers for <a>Zig</a>. So:
* Unnecessary files have been deleted,
* The build system has been replaced with <code>build.zig</code>.
However this repository has subtle differences for maintainability tasks:
* No shell scripting,
* A cron runs every day to check <a>KhronosGroup/SPIRV-Tools</a> and <a>KhronosGroup/SPIRV-Headers</a>. Then it updates this repository if a new release is available.
How to use it
The current usage of this repository is centered around <a>tiawl/shaderc.zig</a> compilation. But you could use it for your own projects. Headers are here and there are no planned evolution to modify them. See <a>tiawl/shaderc.zig</a> to see how you can use it. Maybe for your own need, some headers are missing. If it happens, open an issue: this repository is open to potential usage evolution.
Dependencies
The <a>Zig</a> part of this package is relying on the latest <a>Zig</a> release (0.14.0) and will only be updated for the next one (so for the 0.14.1).
Here the repositories' version used by this fork:
* <a>KhronosGroup/SPIRV-Tools</a>
* <a>KhronosGroup/SPIRV-Headers</a>
CICD reminder
These repositories are automatically updated when a new release is available:
* <a>tiawl/shaderc.zig</a>
This repository is automatically updated when a new release is available from these repositories:
* <a>KhronosGroup/SPIRV-Tools</a>
* <a>KhronosGroup/SPIRV-Headers</a>
* <a>tiawl/toolbox</a>
<code>zig build</code> options
These additional options have been implemented for maintainability tasks:
<code>-Dfetch Update .references folder and build.zig.zon then stop execution
-Dupdate Update binding</code>
License
This repository is not subject to a unique License:
The parts of this repository originated from this repository are dedicated to the public domain. See the LICENSE file for more details.
<strong>For other parts, it is subject to the License restrictions their respective owners choosed. By design, the public domain code is incompatible with the License notion. In this case, the License prevails. So if you have any doubt about a file property, open an issue.</strong> | [] |
https://avatars.githubusercontent.com/u/57362253?v=4 | glslang.zig | tiawl/glslang.zig | 2024-04-09T10:07:03Z | glslang packaged for @ziglang | trunk | 0 | 1 | 2 | 1 | https://api.github.com/repos/tiawl/glslang.zig/tags | Unlicense | [
"binding",
"glslang",
"spaceporn",
"zig",
"zig-package",
"ziglang"
] | 2,058 | false | 2025-05-21T09:18:50Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "toolbox",
"tar_url": "https://github.com/tiawl/toolbox/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/tiawl/toolbox"
}
] | glslang.zig
This is a fork of <a>KhronosGroup/glslang</a> packaged for <a>Zig</a>
Why this fork ?
The intention under this fork is to package <a>KhronosGroup/glslang</a> for <a>Zig</a>. So:
* Unnecessary files have been deleted,
* The build system has been replaced with <code>build.zig</code>,
* A cron runs every day to check <a>KhronosGroup/glslang</a>. Then it updates this repository if a new release is available.
How to use it
The goal of this repository is not to provide a <a>Zig</a> binding for <a>KhronosGroup/glslang</a>. There are at least as many legit ways as possible to make a binding as there are active accounts on Github. So you are not going to find an answer for this question here. The point of this repository is to abstract the <a>KhronosGroup/glslang</a> compilation process with <a>Zig</a> (which is not new comers friendly and not easy to maintain) to let you focus on your application. So you can use <strong>glslang.zig</strong>:
- as raw (no available example, open an issue if you are interested in, we will be happy to help you),
- as a daily updated interface for your <a>Zig</a> binding of <a>KhronosGroup/glslang</a> (again: no available example).
Important note
The current usage of this repository is centered around <a>tiawl/shaderc.zig</a> compilation. So for your usage it could break because some files have been filtered in the process. If it happens, open an issue: this repository is open to potential usage evolution.
Dependencies
The <a>Zig</a> part of this package is relying on the latest <a>Zig</a> release (0.14.0) and will only be updated for the next one (so for the 0.14.1).
Here the repositories' version used by this fork:
* <a>KhronosGroup/glslang</a>
CICD reminder
These repositories are automatically updated when a new release is available:
* <a>tiawl/shaderc.zig</a>
This repository is automatically updated when a new release is available from these repositories:
* <a>KhronosGroup/glslang</a>
* <a>tiawl/toolbox</a>
<code>zig build</code> options
These additional options have been implemented for maintainability tasks:
<code>-Dfetch Update .references folder and build.zig.zon then stop execution
-Dupdate Update binding</code>
License
This repository is not subject to a unique License:
The parts of this repository originated from this repository are dedicated to the public domain. See the LICENSE file for more details.
<strong>For other parts, it is subject to the License restrictions their respective owners choosed. By design, the public domain code is incompatible with the License notion. In this case, the License prevails. So if you have any doubt about a file property, open an issue.</strong> | [] |
https://avatars.githubusercontent.com/u/85372264?v=4 | zstd.zig | Syndica/zstd.zig | 2024-03-21T16:09:03Z | Zig binding of Z Standard | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/Syndica/zstd.zig/tags | MIT | [
"zig",
"zig-package"
] | 513 | true | 2024-11-08T12:27:37Z | true | true | unknown | github | [
{
"commit": "794ea1b0afca0f020f4e57b6732332231fb23c70.tar.gz",
"name": "zstd",
"tar_url": "https://github.com/facebook/zstd/archive/794ea1b0afca0f020f4e57b6732332231fb23c70.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/facebook/zstd"
}
] | zstd.zig
Zig binding of Z Standard based on <em><code>v1.5.2</code></em>
how to import
in your <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
// ...
<code>const zstd_dep = b.dependency("zstd", opts);
const zstd_mod = zstd_dep.module("zstd");
const zstd_c_lib = zstd_dep.artifact("zstd");
const exec = ...
// link it
exec.addModule("zstd", zstd_mod);
exec.linkLibrary(zstd_c_lib);
// ...
</code>
}
```
usage
```zig
const ZstdReader = @import("zstd").Reader;
...
pub fn main() {
const path = ...
<code>const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
const file_stat = try file.stat();
const file_size: u64 = @intCast(file_stat.size);
var memory = try std.os.mmap(
null,
file_size,
std.os.PROT.READ,
std.os.MAP.PRIVATE,
file.handle,
0,
);
var decompressed_stream = try ZstdReader.init(memory);
var reader = decompressed_stream.reader();
...
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/28365338?v=4 | concurrent-channel | ahmdhusam/concurrent-channel | 2024-05-22T23:22:00Z | A thread-safe communication channel for concurrent programming in Zig. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/ahmdhusam/concurrent-channel/tags | - | [
"zig-library",
"zig-package"
] | 7 | false | 2024-10-28T14:31:43Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | tempora | bcrist/tempora | 2024-03-09T02:04:51Z | Simple Zig Dates/Times/Timezones | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/bcrist/tempora/tags | MIT | [
"calendar",
"date",
"datetime",
"time",
"tz",
"tzdata",
"tzinfo",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 358 | false | 2025-02-14T02:25:44Z | true | true | 0.14.0-dev.3217+5b9b5e45c | github | [] | Tempora
Simple Zig Dates/Times/Timezones
Features
<ul>
<li>Efficient storage (32b <code>Time</code>, 32b <code>Date</code>, 64b <code>Date_Time</code>)</li>
<li>Composition and decomposition (year, ordinal day/week, month, day, weekday, hour, minute, second, ms)</li>
<li>Add/subtract days/hours/minutes/seconds/ms</li>
<li>Advance to the next weekday/day/ordinal day</li>
<li>Convert to/from unix timestamps</li>
<li>Embedded IANA timezone database and modified version of <a>zig-tzif</a> (adds about 200k to binary size when used)</li>
<li>Query current timezone on both unix and Windows systems</li>
<li>Moment.js style formatting and parsing (through <code>std.fmt</code>)</li>
</ul>
Limitations
<ul>
<li>It's not possible to store most "out of bounds" dates/times (e.g. Jan 32).</li>
<li>Localized month and weekday names are not supported; only English.</li>
<li>Non-Gregorian calendars are not supported.</li>
<li>Date/time values directly correspond to timestamps, so accurate durations that take leap seconds into account are not possible (but leap seconds are being abolished in 2035 anyway).</li>
<li>I am certain that there are more optimized algorithms for timestamp <--> calendar conversions (but performance should be fine for all but the most demanding use cases).</li>
</ul> | [
"https://github.com/bcrist/shittip"
] |
https://avatars.githubusercontent.com/u/16764864?v=4 | zigpokerhands | andy5995/zigpokerhands | 2024-03-12T07:04:23Z | A program that uses zigdeck to evaluate five cards to determine if it matches a poker hand | trunk | 1 | 1 | 0 | 1 | https://api.github.com/repos/andy5995/zigpokerhands/tags | MIT | [
"cards",
"mit-license",
"poker",
"simulations",
"zig",
"zig-package"
] | 36 | false | 2025-03-18T11:36:45Z | true | true | unknown | github | [
{
"commit": "master",
"name": "zigdeck",
"tar_url": "https://github.com/andy5995/zigdeck/releases/download/v0.1.0/zigdeck-0.1.0.tar.gz/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/andy5995/zigdeck/releases/download/v0.1.0/zigdeck-0.1.0.tar.gz"
}
] | <a></a>
zigpokerhands
A program that uses <a>zigdeck</a> to evaluate
five cards to determine if it matches a poker hand
Output examples
```
Evaluating 1000000 hands...
<code> Pair: 421692
TwoPair: 47047
ThreeOfAKind: 20578
Straight: 4090
Flush: 2514
FullHouse: 1450
FourOfAKind: 244
StraightFlush: 18
RoyalFlush: 1
</code>
```
```
Evaluating 1000000 hands...
<code> Pair: 421887
TwoPair: 47001
ThreeOfAKind: 20558
Straight: 4168
Flush: 2511
FullHouse: 1378
FourOfAKind: 225
StraightFlush: 21
RoyalFlush: 0
</code>
```
```
Evaluating 1000000 hands...
<code> Pair: 420623
TwoPair: 47240
ThreeOfAKind: 20832
Straight: 4136
Flush: 2587
FullHouse: 1391
FourOfAKind: 252
StraightFlush: 19
RoyalFlush: 2
</code>
``` | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | zig-scudo | kassane/zig-scudo | 2024-07-03T12:45:33Z | Scudo Allocator for Zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/kassane/zig-scudo/tags | Apache-2.0 | [
"allocator",
"scudo-allocator",
"zig-package"
] | 156 | false | 2024-07-05T21:52:38Z | true | true | 0.13.0 | github | [
{
"commit": null,
"name": "runner",
"tar_url": null,
"type": "remote",
"url": "git+https://gist.github.com/karlseguin/c6bea5b35e4e8d26af6f81c22cb5d76b/#f303e77231e14b405e4e800072e7deacac4a4881"
}
] | scudo-zig
Scudo Allocator for Zig
Requires
<ul>
<li><a>Zig</a> v0.13.0 or master</li>
</ul>
How to use
```bash
Create a project
$ mkdir project_name
$ cd project_name
$ zig init
get zig-scudo (add on zon file - overwrited)
zig fetch --save=scudo git+https://github.com/kassane/zig-scudo
```
In <code>build.zig</code>, add:
```zig
// pkg name (same in zon file)
const scudo_dep = b.dependency("scudo",.{.target = target, .optimize = optimize });
const scudo_module = scudo_dep.module("scudoAllocator"); // get lib + zig bindings
// my project (executable)
exe.root_module.addImport("scudoAllocator", scudo_module);
```
References
<ul>
<li><a>LLVM-Doc: Scudo Allocator</a></li>
<li><a>SCUDO Hardened Allocator — Unofficial Internals</a> authored by <a>Rodrigo Rubira</a></li>
<li><a>High level overview of Scudo</a> by Kostya</li>
<li><a>What is the Scudo hardened allocator?</a> by Kostya</li>
<li><a>google/rust-scudo</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/81112205?v=4 | zorsig | RohanVashisht1234/zorsig | 2024-06-20T18:09:44Z | null | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/RohanVashisht1234/zorsig/tags | NOASSERTION | [
"zig-package"
] | 22 | false | 2024-11-13T11:23:03Z | true | true | unknown | github | [] | Zorsig: a better morse library for Zig programming language
Features:
- minimum version of zig: 0.13.0
- Memory safe
- No allocators used
- High performance library
How to use?
```zig
const std = @import("std");
const Zorsig = @import("zorsig");
const print = std.debug.print;
pub fn main() void {
const res1 = Zorsig.char_to_morse('A');
print("{s}\n", .{res1});
<code>const res2 = Zorsig.morse_to_char(".-");
print("{c}\n", .{res2});
// No allocator
var res3 = Zorsig.morse_to_string(".... . .-.. .-.. --- --..-- / .-- --- .-. .-.. -.. -.-.--");
while (res3.next()) |next_element| {
print("{c}", .{next_element});
}
print("\n", .{});
var res4 = Zorsig.string_to_morse("HELLO, WORLD!");
while (res4.next()) |next_element| {
print("{s} ", .{next_element});
}
</code>
}
```
Output:
Get started:
<strong>Run the following command in your terminal:</strong>
<code>sh
zig fetch --save "https://github.com/RohanVashisht1234/zorsig/archive/refs/tags/v0.0.1.tar.gz"</code>
**Add the following to your build.zig (just above the line <code>b.installArtifact(exe);</code>): **
```zig
const zorsig = b.dependency("zorsig", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("zorsig", zorsig.module("zorsig"));
```
That's it, now use the Zorsig. | [] |
https://avatars.githubusercontent.com/u/109492796?v=4 | zig-todo-web-app | zigcc/zig-todo-web-app | 2024-07-19T06:03:04Z | A Single-page TODO app in Zig! | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/zigcc/zig-todo-web-app/tags | - | [
"zig",
"zig-library",
"zig-package",
"zig-programming-language",
"ziglang"
] | 47 | false | 2024-07-25T15:12:30Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/36482619?v=4 | zig-extras | jkoop/zig-extras | 2024-07-29T01:31:44Z | An assortment of random utility functions that aren't in std and don't need to be their own pacakge. | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/jkoop/zig-extras/tags | MIT | [
"zig-package"
] | 109 | true | 2024-07-29T01:42:39Z | true | true | 0.13.0 | github | [] | zig-extras
An assortment of random utility functions that aren't in std and don't deserve their own package.
License
MIT | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | ffi-flang-zig | kassane/ffi-flang-zig | 2024-06-18T15:16:52Z | FFI flang-new runtime with Zig | main | 2 | 0 | 0 | 0 | https://api.github.com/repos/kassane/ffi-flang-zig/tags | Apache-2.0 | [
"cross-compile",
"ffi",
"ffi-bindings",
"flang",
"fortran",
"llvm",
"zig",
"zig-package"
] | 3,002 | false | 2025-03-31T13:00:07Z | true | false | unknown | github | [] | ffi-flang-zig
FFI between Fortran runtime and Zig
<a>LLVM/flang v19.1.7</a> files are included in this repository.
Inspired by <a>sourceryinstitute/ISO_Fortran_binding</a>. However, for LLVM-based only!
Requires
<ul>
<li><a>Zig</a> v0.14.0 or master</li>
<li><a>Flang</a></li>
</ul>
How to use
Build docker and run image:
<code>bash
$ docker build -t flang-zig -f .devcontainer/Dockerfile
$ docker run -it --rm -v $(pwd):/app -w /app flang-zig bash</code>
Build help
<code>bash
Project-Specific Options:
-Doptimize=[enum] Prioritize performance, safety, or binary size
Supported Values:
Debug
ReleaseSafe
ReleaseFast
ReleaseSmall
-Dtarget=[string] The CPU architecture, OS, and ABI to build for
-Dcpu=[string] Target CPU features to add or subtract
-Ddynamic-linker=[string] Path to interpreter on the target system
-Dshared=[bool] Build as shared library [default: false]
-Damalgamation=[bool] Build as amalgamation [default: false]
-Denable-tests=[bool] Build tests [default: false]</code> | [] |
https://avatars.githubusercontent.com/u/1356248?v=4 | zargunaught | srjilarious/zargunaught | 2024-04-20T14:17:40Z | Zig argument parsing library, based on my C++ argunaught library | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/srjilarious/zargunaught/tags | MIT | [
"zig",
"zig-package"
] | 507 | false | 2025-03-12T22:10:21Z | true | true | 0.14.0 | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | dizzy | bcrist/dizzy | 2024-03-26T01:04:14Z | Zig Comptime Dependency Injection | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/bcrist/dizzy/tags | MIT | [
"dependency-injection",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 11 | false | 2025-02-14T02:38:15Z | true | true | 0.14.0-dev.3217+5b9b5e45c | github | [] | Dizzy
Function Parameter Dependency Injection for Zig
See test.zig for example usage. | [
"https://github.com/bcrist/shittip",
"https://github.com/neurocyte/flow"
] |
https://avatars.githubusercontent.com/u/2828351?v=4 | zkittle | bcrist/zkittle | 2024-05-10T23:40:05Z | A little Zig template engine | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/bcrist/zkittle/tags | MIT | [
"file-format",
"template",
"template-engine",
"templates",
"vscode-extension",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 192 | false | 2025-02-14T02:34:30Z | true | true | 0.14.0-dev.3217+5b9b5e45c | github | [
{
"commit": "e39301c1d36b3a2aa98a8c7c8e5fa2eaddfd1000",
"name": "console_helper",
"tar_url": "https://github.com/bcrist/zig-consolehelper/archive/e39301c1d36b3a2aa98a8c7c8e5fa2eaddfd1000.tar.gz",
"type": "remote",
"url": "https://github.com/bcrist/zig-consolehelper"
},
{
"commit": "5bb61... | Zkittle
A basic templating language for Zig programs.
The name is pronounced like "skittle," not "zee kittle".
Syntax
<code>A template always starts with "literal" text.
i.e. text that will just be included in the final document verbatim.
You can add data to your templates by surrounding a \\command block// with double slashes.
Whitespace inside command blocks is ignored, and it's legal to have an empty \\// command block.
\\ $ If a command block contains a $, then //
everything else in that command block is considered a comment.
\\$ If there is no // to close a block on the same line, it ends at the end of the line.
\\$ The final newline character is not included in the output document in this case.
\\$ Since comments end at the end of their containing command block, they are also at most one line.
Templates are evaluated using a "data context", which is usually a struct value.
The \\identifiers// in the command block reference fields of the data struct.
You can reference nested data structures the same way you would in Zig: \\ parent_field.child_field //
Individual elements of "collections" (arrays and slices) are accessed with '.': \\ some_array.0 //
Optionals are treated as a collection of size 0 or 1.
The length of a collection can be printed with: \\ some_array.# //
Accessing an out-of-bounds element is allowed; it becomes a void value (printing it is a no-op).
Tagged union fields can be accessed the same way as structs, but only the active field will resolve
to actual data; inactive fields will resolve to void.
Values of type void are considered a special 'nil' value. This includes accessing a struct field
that doesn't exist, an enum or union tag that isn't active (or doesn't exist), or a collection index
that's out of bounds, as well as data explicitly declared to have a type of `void` or
`@TypeOf(undefined)`. All values have a \\value.@exists// pseudo-field which converts the value to
a bool, where nil becomes false, and anything else becomes true.
The special \\*// syntax represents the whole data context (similar to the "this" or "self" pointer in
some programming languages). It can be useful when the current data context is not a struct, union,
or collection.
Identifiers that aren't qualified by '^' can reference a field in the current context, or the first
parent context that has a non-nil value for the field. This is useful because sometimes a template
is designed to be imported, but you don't know if it will be inside a "within" block. You can
explicitly search only the current context by using \\*.field// instead of \\field//.
You can "push" a new data context with the ':' operator (a.k.a "within").
This can be useful if you want to access multiple fields of a deeply nested struct.
For example, instead of:
First Name: \\phonebook.z.ziggleman.0.first//
Last Name: \\phonebook.z.ziggleman.0.last//
Phone Number: \\phonebook.z.ziggleman.0.phone//
we could instead write:
\\ phonebook.z.ziggleman.0:
First Name: \\first//
Last Name: \\last//
Phone Number: \\phone//
\\ ~
Note that the sequence does not end at the end of the command block, so that it can include
literal text easily. Instead, the ~ character ends the region.
When the data selected by a "within" block is a collection, the sequence will be evaluated once
for each item in the collection. You can print the current index with the \\@index// syntax. When
not inside a "within" region, nothing will be output. You can access the entire collection
instead of an individual item with \\ ^* //. You can access the "outer" data context with \\ ^^* //.
(note this also works when the within block isn't a collection)
If you have nested "within" blocks, the '^' prefixes can be chained as needed.
The conditional '?' operator only evaluates its subsequent region when its data value is "truthy,"
but it does not push a new data context:
\\ should_render_section? // whatever \\ ~
Boolean false, the number zero, and empty collections (including void-like values) are considered
falsey; all other values are truthy.
Both ':' and '?' regions may contain a ';' before the '~' to create an "otherwise" region.
This region will only be evaluated if the first region is not evaluated. e.g.
\\ has_full_name ? full_name ; first_name last_name ~ //
\\x / y// is mostly equivalent to \\x? x ; y ~// except that the former can be used as an
expression, while the latter always just prints x or y. Similarly \\x | y// is corresponds to
\\x.@exists? x ; y ~// in the same way.
Application-specific extensions can be added by adding functions to the data context. These
functions will be passed the writer, escape functions, and the root data context, as well as
a list of any parameters from the template. Calling a function from a template looks like
this: \\ :my_func param1 param2 param3 // Note that ":" is used for both function calls and
"within" blocks. In order to be treated as a function call, it must be followed immediately
by a non-whitespace character.
By default all strings will be printed with an HTML escape function.
This can be overridden or disabled in code when generating other types of documents.
You can also disable it for a specific expression with \\ @raw some_value //.
An alternative escaping function can be used for specific expressions with \\ @url some_value //.
By default, this will escape using percent encoding; suitable for embedding arbitrary data in URLs.
Within command blocks, you can use string literals, wrapped in double quotes, anywhere an
expression is expected. Note that no escape sequences are supported; the string literal simply
ends as soon as the next double quote is seen, so string literals can never contain a double
quote. Often string literals are functionally equivalent to closing the command block and
opening another immediately after:
\\ "Hellorld!" //Hellorld!\\
\\ $ but string literals also let you do things like:
\\ @raw "<table>" $ prevent escaping of HTML tags
\\ :func "asdf" $ pass literals to a function
String literals can also be used to access fields with names that aren't valid zkittle identifiers.
This only works when used after the "." or `^` operators:
\\ something."has weird fields"."and even recursive ones"
\\ *."I am in the current context"
\\ ^^"I'm in the parent context"
The \\ @include "path/to/template" // syntax can be used to pull the entire content of another
template into the current one.
Note that this happens at compile time, not at runtime (the template source is provided to the
template parser by a callback).
The \\ @resource "whatever" // syntax works similarly to @include, but instead of interpreting
the data returned by the callback as template source,
it treats it as a raw literal to be printed.
Sometimes you may want to render only a part of a template in some cases. To facilitate this,
you can define a \\ #fragment_name // to refer to part of the template, ending with the \\~//
operator. This doesn't affect how the overall template is rendered, but allows you to access
the sub-template by name from code. See https://htmx.org/essays/template-fragments/ for more
information about how this technique might be useful.
</code> | [
"https://github.com/bcrist/shittip"
] |
https://avatars.githubusercontent.com/u/52572989?v=4 | zig-time | Protonull/zig-time | 2024-05-13T23:27:57Z | zig-time but with Zig packaging | master | 0 | 0 | 1 | 0 | https://api.github.com/repos/Protonull/zig-time/tags | MIT | [
"zig",
"zig-library",
"zig-package"
] | 87 | true | 2025-01-18T09:42:16Z | true | true | 0.12.0 | github | [
{
"commit": "3dcc531937b58d787e183c25bad535c91bab1f7d",
"name": "zig_extras",
"tar_url": "https://github.com/nektro/zig-extras/archive/3dcc531937b58d787e183c25bad535c91bab1f7d.tar.gz",
"type": "remote",
"url": "https://github.com/nektro/zig-extras"
}
] | zig-time
This is a fork of <a>zig-time</a> that's uses Zig's native packaging instead of
<a>zigmod</a>.
Usage
Add this repository to your <code>build.zig.zon</code>, eg:
<code>zon
// build.zig.zon
.{
.name = "awesome-project",
.version = "0.1.0",
.minimum_zig_version = "0.12.0",
.paths = .{ "" },
.dependencies = .{
.zig_time = .{
.url = "git+https://github.com/Protonull/zig-time#<COMMIT HASH>",
.hash = "<HASH>" // Comment this out Zig will automatically tell you what has to use.
},
},
}</code>
After that, add the dependency to your build script, eg:
```zig
// build.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 = "awesome-project",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
// zig-time dependency goes here
exe.root_module.addImport("zig-time", b.dependency("zig_time", .{}).module("time"));
b.installArtifact(exe);
</code>
}
```
You may notice there's <code>zig-time</code>, <code>zig_time</code>, and <code>time</code>.
<ul>
<li><code>zig-time</code> is what you'd use as the import, like so: <code>const time = @import("zig-time")</code></li>
<li><code>zig_time</code> is the key to match in <code>build.zig.zon</code>, which doesn't like dashes.</li>
<li><code>time</code> is the name of the exported module from zig-time, the library itself.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | shittip | bcrist/shittip | 2024-03-30T23:44:17Z | Another shitty HTTP server | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/bcrist/shittip/tags | MIT | [
"http",
"http-server",
"server",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 167 | false | 2025-02-14T02:43:54Z | true | true | 0.14.0-dev.1694+3b465ebec | github | [
{
"commit": "058f6331d499e81df7b58858e7307543d5484404",
"name": "Temp_Allocator",
"tar_url": "https://github.com/bcrist/zig-tempallocator/archive/058f6331d499e81df7b58858e7307543d5484404.tar.gz",
"type": "remote",
"url": "https://github.com/bcrist/zig-tempallocator"
},
{
"commit": "3fcba... | SHITTIP
A shitty HTTP server | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | tlsf | kassane/tlsf | 2024-04-01T18:49:00Z | Two-Level Segregated Fit memory allocator implementation. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/kassane/tlsf/tags | - | [
"c",
"cmake",
"tlsf",
"zig-package"
] | 20 | true | 2024-04-01T19:07:13Z | true | true | unknown | github | [] | tlsf
Two-Level Segregated Fit memory allocator implementation.
Written by Matthew Conte (matt@baisoku.org).
Released under the BSD license.
Features
<ul>
<li>O(1) cost for malloc, free, realloc, memalign</li>
<li>Extremely low overhead per allocation (4 bytes)</li>
<li>Low overhead per TLSF management of pools (~3kB)</li>
<li>Low fragmentation</li>
<li>Compiles to only a few kB of code and data</li>
<li>Support for adding and removing memory pool regions on the fly</li>
</ul>
Caveats
<ul>
<li>Currently, assumes architecture can make 4-byte aligned accesses</li>
<li>Not designed to be thread safe; the user must provide this</li>
</ul>
Notes
This code was based on the TLSF 1.4 spec and documentation found at:
<code>http://www.gii.upv.es/tlsf/main/docs
</code>
It also leverages the TLSF 2.0 improvement to shrink the per-block overhead from 8 to 4 bytes.
History
2016/04/10 - v3.1
* Code moved to github
* tlsfbits.h rolled into tlsf.c
* License changed to BSD
2014/02/08 - v3.0
* This version is based on improvements from 3DInteractive GmbH
* Interface changed to allow more than one memory pool
* Separated pool handling from control structure (adding, removing, debugging)
* Control structure and pools can still be constructed in the same memory block
* Memory blocks for control structure and pools are checked for alignment
* Added functions to retrieve control structure size, alignment size, min and max block size, overhead of pool structure, and overhead of a single allocation
* Minimal Pool size is tlsf_block_size_min() + tlsf_pool_overhead()
* Pool must be empty when it is removed, in order to allow O(1) removal
2011/10/20 - v2.0
* 64-bit support
* More compiler intrinsics for ffs/fls
* ffs/fls verification during TLSF creation in debug builds
2008/04/04 - v1.9
* Add tlsf_heap_check, a heap integrity check
* Support a predefined tlsf_assert macro
* Fix realloc case where block should shrink; if adjacent block is in use, execution would go down the slow path
2007/02/08 - v1.8
* Fix for unnecessary reallocation in tlsf_realloc
2007/02/03 - v1.7
* tlsf_heap_walk takes a callback
* tlsf_realloc now returns NULL on failure
* tlsf_memalign optimization for 4-byte alignment
* Usage of size_t where appropriate
2006/11/21 - v1.6
* ffs/fls broken out into tlsfbits.h
* tlsf_overhead queries per-pool overhead
2006/11/07 - v1.5
* Smart realloc implementation
* Smart memalign implementation
2006/10/11 - v1.4
* Add some ffs/fls implementations
* Minor code footprint reduction
2006/09/14 - v1.3
* Profiling indicates heavy use of blocks of size 1-128, so implement small block handling
* Reduce pool overhead by about 1kb
* Reduce minimum block size from 32 to 12 bytes
* Realloc bug fix
2006/09/09 - v1.2
* Add tlsf_block_size
* Static assertion mechanism for invariants
* Minor bugfixes
2006/09/01 - v1.1
* Add tlsf_realloc
* Add tlsf_walk_heap
2006/08/25 - v1.0
* First release | [] |
https://avatars.githubusercontent.com/u/160516989?v=4 | lumi | Lumi-Engine/lumi | 2024-02-19T16:06:29Z | The main Lumi engine repo | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/Lumi-Engine/lumi/tags | BSD-3-Clause | [
"gamedev",
"gamedev-framework",
"gamedev-library",
"gamedevelopment",
"zig",
"zig-lang",
"zig-language",
"zig-lib",
"zig-library",
"zig-package",
"zig-programming-language",
"ziglang"
] | 68 | false | 2024-02-19T16:09:57Z | true | true | unknown | github | [
{
"commit": "63da35e57c3695a787b927e69e4140eb74ffc234",
"name": "mach_glfw",
"tar_url": "https://github.com/hexops/mach-glfw/archive/63da35e57c3695a787b927e69e4140eb74ffc234.tar.gz",
"type": "remote",
"url": "https://github.com/hexops/mach-glfw"
}
] |
Lumi Engine is a 2D game engine which aims to provide a performant, flexible and easy game development environment. | [] |
https://avatars.githubusercontent.com/u/36482619?v=4 | zig-time | jkoop/zig-time | 2024-07-29T01:18:30Z | zig-time but with Zig packaging | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/jkoop/zig-time/tags | MIT | [
"zig-package"
] | 94 | true | 2024-07-29T02:54:19Z | true | true | 0.13.0 | github | [
{
"commit": "8e59b16cf18473c7a307fd1441a716bc2b2b802a.zip",
"name": "zig_extras",
"tar_url": "https://github.com/jkoop/zig-extras/archive/8e59b16cf18473c7a307fd1441a716bc2b2b802a.zip.tar.gz",
"type": "remote",
"url": "https://github.com/jkoop/zig-extras"
}
] | zig-time
This is a fork of <a>zig-time</a> that's uses Zig's native packaging instead of
<a>zigmod</a>.
Usage
Add this repository to your <code>build.zig.zon</code>, eg:
<code>zon
// build.zig.zon
.{
.name = "awesome-project",
.version = "0.1.0",
.minimum_zig_version = "0.12.0",
.paths = .{ "" },
.dependencies = .{
.zig_time = .{
.url = "git+https://github.com/Protonull/zig-time#<COMMIT HASH>",
.hash = "<HASH>" // Comment this out Zig will automatically tell you what has to use.
},
},
}</code>
After that, add the dependency to your build script, eg:
```zig
// build.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 = "awesome-project",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
// zig-time dependency goes here
exe.root_module.addImport("zig-time", b.dependency("zig_time", .{}).module("time"));
b.installArtifact(exe);
</code>
}
```
You may notice there's <code>zig-time</code>, <code>zig_time</code>, and <code>time</code>.
<ul>
<li><code>zig-time</code> is what you'd use as the import, like so: <code>const time = @import("zig-time")</code></li>
<li><code>zig_time</code> is the key to match in <code>build.zig.zon</code>, which doesn't like dashes.</li>
<li><code>time</code> is the name of the exported module from zig-time, the library itself.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/170934839?v=4 | zig-utilities | Ang3lERR404/zig-utilities | 2024-06-03T17:01:27Z | Utilities for zig, in a smol, convenient file | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/Ang3lERR404/zig-utilities/tags | GPL-3.0 | [
"utilities",
"zig",
"zig-package",
"ziglang"
] | 14 | false | 2024-06-11T20:08:52Z | false | false | unknown | github | [] | Utils.zig
A smol utility library before skill issues were found :D
<strong><em>IN THE ENTIRE STANDARD LIBRARY FOR ZIG</em></strong>
=~=
<blockquote>
W h y\
a r e\
y o u\
l i k e\
t h i s
</blockquote> | [] |
https://avatars.githubusercontent.com/u/1562827?v=4 | combinato | travisstaloch/combinato | 2024-07-01T12:10:36Z | Parser combinators in zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/travisstaloch/combinato/tags | MIT | [
"parser-combinators",
"zig-package"
] | 30 | false | 2024-08-17T03:41:06Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/46655455?v=4 | zbencode | 4zv4l/zbencode | 2024-07-05T04:21:48Z | zig bencode library | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/4zv4l/zbencode/tags | GPL-3.0 | [
"zig-package"
] | 77 | false | 2025-02-02T14:49:24Z | true | true | unknown | github | [] | zbencode
zig bencode library
Example of usage
```zig
const std = @import("std");
const bencode = @import("bencode");
const sizeFmt = std.fmt.fmtIntSizeBin;
pub fn main() !void {
// setup + args
const allocator = std.heap.page_allocator;
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len != 2) {
print("usage: {s} [file.torrent]\n", .{args[0]});
return;
}
<code>// read file + decoding
const data = try std.fs.cwd().readFileAlloc(tally, "debian.torrent", 1 * 1024 * 1024);
defer tally.free(data);
var arena = std.heap.ArenaAllocator.init(tally);
var bencode = try parse(&arena, data);
defer bencode.deinit(&arena);
// pretty print
const root = bencode.dictionnary;
const info = root.get("info").?.dictionnary;
std.debug.print("name : {}\n", .{info.get("name").?});
std.debug.print("length : {}\n", .{sizeFmt(@intCast(info.get("length").?.integer))});
std.debug.print("tracker: {}\n", .{root.get("announce").?});
std.debug.print("creator: {}\n", .{root.get("created by").?});
std.debug.print("created: {}\n", .{root.get("creation date").?});
</code>
```
<code>$ btest debian.torrent
name : debian-12.9.0-amd64-netinst.iso
length : 632MiB
tracker: http://bttracker.debian.org:6969/announce
creator: mktorrent 1.1
created: 1736599700</code> | [] |
https://avatars.githubusercontent.com/u/48649707?v=4 | zig-quickphf | tensorush/zig-quickphf | 2024-03-25T20:41:27Z | Zig port of quickphf library for static hash map generation. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/tensorush/zig-quickphf/tags | MIT | [
"zig-package"
] | 24 | false | 2025-03-18T06:57:05Z | true | true | unknown | github | [] | zig-quickphf
Zig port of <a>quickphf library</a> for static hash map generation.
Usage
<ul>
<li>Add <code>quickphf</code> dependency to <code>build.zig.zon</code>.</li>
</ul>
<code>sh
zig fetch --save git+https://github.com/tensorush/zig-quickphf</code>
<ul>
<li>Use <code>quickphf</code> dependency in <code>build.zig</code>.</li>
</ul>
<code>zig
const quickphf_dep = b.dependency("quickphf", .{
.target = target,
.optimize = optimize,
});
const quickphf_mod = quickphf_dep.module("quickphf");
<compile>.root_module.addImport("quickphf", quickphf_mod);</code> | [] |
https://avatars.githubusercontent.com/u/4718156?v=4 | zoroutine-zig | laohanlinux/zoroutine-zig | 2024-05-11T10:21:20Z | null | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/laohanlinux/zoroutine-zig/tags | Apache-2.0 | [
"zig-package"
] | 115 | false | 2025-01-11T11:37:23Z | true | true | unknown | github | [] | zoroutine-zig | [] |
https://avatars.githubusercontent.com/u/6431196?v=4 | chess-engine-zig | oswalpalash/chess-engine-zig | 2024-04-16T04:40:08Z | Zig Based Chess Engine | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/oswalpalash/chess-engine-zig/tags | MIT | [
"chess",
"engine",
"uci",
"zig",
"zig-lang",
"zig-package"
] | 224 | false | 2025-04-19T14:28:37Z | true | false | unknown | github | [] | Zig based Chess Engine
Project Summary
A chess engine written in zig. Mostly written as a means to learn and improve at zig.
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> UCI Compliant
<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> Basic Evaluation
<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> FEN Parsing
<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> Board Design and Piece Information
<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> Move Generator
<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> Unit Tests for supported 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> CI Based Testing
<strong><em>NOTE:</em></strong> This is an evolving project. No backwards compatibility guaraenteed.
How to test
<code>bash
zig build test</code>
How to run
<code>bash
zig build run</code> | [] |
https://avatars.githubusercontent.com/u/2773256?v=4 | zig-meta-allyourcode | dasimmet/zig-meta-allyourcode | 2024-07-11T18:59:04Z | null | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/dasimmet/zig-meta-allyourcode/tags | - | [
"zig-package"
] | 196 | false | 2025-03-07T11:22:46Z | true | true | unknown | github | [
{
"commit": "master",
"name": "cmake",
"tar_url": "https://github.com/Kitware/CMake/releases/download/v3.30.3/cmake-3.30.3.tar.gz/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/Kitware/CMake/releases/download/v3.30.3/cmake-3.30.3.tar.gz"
},
{
"commit": "refs",
"... | meta-allyourcode
lazy dependencies for zig build.
This repository is for writing <code>build.zig</code> configurations for other c/c++ projects
CMake
using the zig build system, this repository bootstraps <code>cmake</code> <code>3.30.1</code> without any system cmake
or the usual shellscript method. it takes a while and is only tested on x64 linux,
but can be used to build your C/C++ dependency libraries.
the package also has a custom <code>CMakeStep</code> that will configure and build and install a cmake project,
and providdes a <code>.install(b, name)</code> function to get the artifacts:
<code>zig fetch --save https://github.com/dasimmet/zig-meta-allyourcode/archive/refs/heads/master.tar.gz</code>
build.zig (from <a>example</a>):
```
pub fn build() void {
const meta_import = b.lazyImport(@This(), "meta_allyourcode");
if (meta_import) |meta_allyourcode| {}
const cmakeStep = meta_allyourcode.addCMakeStep(b, .{
.target = b.standardTargetOptions(.{}),
.name = "cmake",
.source_dir = b.path(""),
.defines = &.{
.{ "CMAKE_BUILD_TYPE", if (optimize == .Debug) "Debug" else "Release" },
},
});
cmakeStep.addCmakeDefine();
const install_step = cmakeStep.install(b, "");
b.getInstallStep().dependOn(&install_step.step);
}
```
integrated builds
<ul>
<li>cmake (including custom build step?)</li>
<li>✅ stage1 linux</li>
<li>✅ running bootstrap <code>cmake</code> to reconfigure itself with <code>CC=zig cc</code></li>
<li>✅ use zig built <code>make</code> to rebuild <code>cmake</code></li>
<li>🏃♂️ stage1 windows</li>
<li>🏃♂️ stage1 macos</li>
<li>🏃♂️test building other cmake projects</li>
<li>try to link cmake fully static</li>
<li>test other architectures</li>
<li>libgit2 ✅</li>
<li>build for wasm32-wasi</li>
<li>wabt</li>
<li>✅ compile libwabt and wasm2wat</li>
<li>✅ add build.zig include code</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/163546630?v=4 | mime | zon-dev/mime | 2024-08-03T09:44:54Z | Support MIME (HTTP Media Types) types parse in Zig. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/zon-dev/mime/tags | MIT | [
"media-types",
"mime",
"mime-parser",
"mime-types",
"zig",
"zig-package",
"ziglang"
] | 16 | false | 2024-08-06T08:39:27Z | true | true | unknown | github | [] | mime
Support MIME (HTTP Media Types) types parse in Zig.
Usage:
```zig
var mime = Mime.parse(std.heap.page_allocator, "text/plain; charset=utf-8; foo=bar");
try std.testing.expect(mime != null);
try std.testing.expect(std.mem.eql(u8, mime.?.essence, "text/plain; charset=utf-8; foo=bar"));
try std.testing.expect(std.mem.eql(u8, mime.?.basetype, "text"));
try std.testing.expect(std.mem.eql(u8, mime.?.subtype, "plain"));
const charset = mime.?.getParam("charset");
try testing.expectEqualStrings("utf-8", charset.?);
const foo = mime.?.getParam("foo");
try testing.expectEqualStrings("bar", foo.?);
const bar = mime.?.getParam("bar");
try testing.expect(bar == null);
``` | [] |
https://avatars.githubusercontent.com/u/125233599?v=4 | zap | zigzap/zap | 2023-01-12T21:36:31Z | blazingly fast backends in zig | master | 22 | 2,877 | 97 | 2,877 | https://api.github.com/repos/zigzap/zap/tags | MIT | [
"api",
"blazingly",
"fast",
"http",
"rest",
"zig",
"zig-package"
] | 11,398 | false | 2025-05-22T06:15:05Z | true | true | unknown | github | [] | ⚡zap⚡ - blazingly fast backends in zig
<a></a>
Zap is the <a>zig</a> replacement for the REST APIs I used to
write in <a>python</a> with
<a>Flask</a> and
<a>mongodb</a>, etc. It can be considered to be a
microframework for web applications.
What I needed as a replacement was a blazingly fast and robust HTTP server that
I could use with Zig, and I chose to wrap the superb evented networking C
library <a>facil.io</a>. Zap wraps and patches <a>facil.io - the C
web application framework</a>.
<strong>⚡ZAP⚡ IS FAST, ROBUST, AND STABLE</strong>
After having used ZAP in production for years, I can confidently assert that it
proved to be:
<ul>
<li>⚡ <strong>blazingly fast</strong> ⚡</li>
<li>💪 <strong>extremely robust</strong> 💪</li>
</ul>
FAQ:
<ul>
<li>Q: <strong>What version of Zig does Zap support?</strong><ul>
<li>Zap uses the latest stable zig release (0.14.0), so you don't have to keep
up with frequent breaking changes. It's an "LTS feature".</li>
</ul>
</li>
<li>Q: <strong>Can Zap build with Zig's master branch?</strong><ul>
<li>See the <code>zig-master</code> branch. Please note that the zig-master branch is not
the official master branch of ZAP. Be aware that I don't provide tagged
releases for it. If you know what you are doing, that shouldn't stop you
from using it with zig master though.</li>
</ul>
</li>
<li>Q: <strong>Where is the API documentation?</strong><ul>
<li>Docs are a work in progress. You can check them out
<a>here</a>.</li>
<li>Run <code>zig build run-docserver</code> to serve them locally.</li>
</ul>
</li>
<li>Q: <strong>Does ZAP work on Windows?</strong><ul>
<li>No. This is due to the underlying facil.io C library. Future versions
of facil.io might support Windows but there is no timeline yet. Your best
options on Windows are <strong>WSL2 or a docker container</strong>.</li>
</ul>
</li>
<li>Q: <strong>Does ZAP support TLS / HTTPS?</strong><ul>
<li>Yes, ZAP supports using the system's openssl. See the
<a>https</a> example and make sure to build with
the <code>-Dopenssl</code> flag or the environment variable <code>ZAP_USE_OPENSSL=true</code>:</li>
<li><code>.openssl = true,</code> (in dependent projects' build.zig,
<code>b.dependency("zap" .{...})</code>)</li>
<li><code>ZAP_USE_OPENSSL=true zig build https</code></li>
<li><code>zig build -Dopenssl=true https</code></li>
</ul>
</li>
</ul>
Here's what works
I recommend checking out <strong>the new App-based</strong> or the Endpoint-based
examples, as they reflect how I intended Zap to be used.
Most of the examples are super stripped down to only include what's necessary to
show a feature.
<strong>To see API docs, run <code>zig build run-docserver</code>.</strong> To specify a custom
port and docs dir: <code>zig build docserver && zig-out/bin/docserver --port=8989
--docs=path/to/docs</code>.
New App-Based Examples
<ul>
<li><strong><a>app_basic</a></strong>: Shows how to use zap.App with a
simple Endpoint.</li>
<li><strong><a>app_auth</a></strong>: Shows how to use zap.App with an
Endpoint using an Authenticator.</li>
</ul>
See the other examples for specific uses of Zap.
Benefits of using <code>zap.App</code>:
<ul>
<li>Provides a global, user-defined "Application Context" to all endpoints.</li>
<li>Made to work with "Endpoints": an endpoint is a struct that covers a <code>/slug</code>
of the requested URL and provides a callback for each supported request method
(get, put, delete, options, post, head, patch).</li>
<li>Each request callback receives:</li>
<li>a per-thread arena allocator you can use for throwaway allocations without
worrying about freeing them.</li>
<li>the global "Application Context" of your app's choice</li>
<li>Endpoint request callbacks are allowed to return errors:</li>
<li>you can use <code>try</code>.</li>
<li>the endpoint's ErrorStrategy defines if runtime errors should be reported to
the console, to the response (=browser for debugging), or if the error
should be returned.</li>
</ul>
Legacy Endpoint-based examples
<ul>
<li><strong><a>endpoint</a></strong>: a simple JSON REST API example featuring a
<code>/users</code> endpoint for performing PUT/DELETE/GET/POST operations and listing
users, together with a simple frontend to play with. <strong>It also introduces a
<code>/stop</code> endpoint</strong> that shuts down Zap, so <strong>memory leak detection</strong> can be
performed in main().<ul>
<li>Check out how <a>main.zig</a> uses ZIG's awesome
<code>GeneralPurposeAllocator</code> to report memory leaks when ZAP is shut down.
The <a>StopEndpoint</a> just stops ZAP when
receiving a request on the <code>/stop</code> route.</li>
</ul>
</li>
<li><strong><a>endpoint authentication</a></strong>: a
simple authenticated endpoint. Read more about authentication
<a>here</a>.</li>
</ul>
Legacy Middleware-Style examples
<ul>
<li><strong><a>MIDDLEWARE support</a></strong>: chain together
request handlers in middleware style. Provide custom context structs, totally
type-safe. If you come from GO this might appeal to you.</li>
<li><strong><a>MIDDLEWARE with endpoint
support</a></strong>:
Same as the example above, but this time we use an endpoint at the end of the
chain, by wrapping it via <code>zap.Middleware.EndpointHandler</code>. Mixing endpoints
in your middleware chain allows for usage of Zap's authenticated endpoints and
your custom endpoints. Since Endpoints use a simpler API, you have to use
<code>r.setUserContext()</code> and <code>r.getUserContext()</code> with the request if you want to
access the middleware context from a wrapped endpoint. Since this mechanism
uses an <code>*anyopaque</code> pointer underneath (to not break the Endpoint API), it is
less type-safe than <code>zap.Middleware</code>'s use of contexts.</li>
<li><a><strong>Per Request Contexts</strong></a> : With the introduction of
<code>setUserContext()</code> and <code>getUserContext()</code>, you can, of course use those two in
projects that don't use <code>zap.Endpoint</code> or <code>zap.Middleware</code>, too, if you
really, really, absolutely don't find another way to solve your context
problem. <strong>We recommend using a <code>zap.Endpoint</code></strong> inside of a struct that
can provide all the context you need <strong>instead</strong>. You get access to your
struct in the callbacks via the <code>@fieldParentPtr()</code> trick that is used
extensively in Zap's examples, like the <a>endpoint
example</a>.</li>
</ul>
Specific and Very Basic Examples
<ul>
<li><strong><a>hello</a></strong>: welcomes you with some static HTML</li>
<li><strong><a>routes</a></strong>: a super easy example dispatching on
the HTTP path. <strong>NOTE</strong>: The dispatch in the example is a super-basic
DIY-style dispatch. See endpoint-based examples for more realistic use cases.</li>
<li><a><strong>simple_router</strong></a>: See how you
can use <code>zap.Router</code> to dispatch to handlers by HTTP path.</li>
<li><strong><a>serve</a></strong>: the traditional static web server with
optional dynamic request handling</li>
<li><strong><a>sendfile</a></strong>: simple example of how to send
a file, honoring compression headers, etc.</li>
<li><strong><a>bindataformpost</a></strong>: example
to receive binary files via form post.</li>
<li><strong><a>hello_json</a></strong>: serves you json
dependent on HTTP path</li>
<li><strong><a>mustache</a></strong>: a simple example using
<a>mustache</a> templating.</li>
<li><strong><a>http parameters</a></strong>: a simple example
sending itself query parameters of all supported types.</li>
<li><strong><a>cookies</a></strong>: a simple example sending itself a
cookie and responding with a session cookie.</li>
<li><strong><a>websockets</a></strong>: a simple websockets chat for the
browser.</li>
<li><strong><a>Username/Password Session
Authentication</a></strong>: A convenience
authenticator that redirects un-authenticated requests to a login page and
sends cookies containing session tokens based on username/password pairs
received via POST request.</li>
<li><a><strong>Error Trace Responses</strong></a>: You can now
call <code>r.sendError(err, status_code)</code> when you catch an error and a stack trace
will be returned to the client / browser.</li>
<li><a><strong>HTTPS</strong></a>: Shows how easy it is to use facil.io's
openssl support. Must be compiled with <code>-Dopenssl=true</code> or the environment
variable <code>ZAP_USE_OPENSSL</code> set to <code>true</code> and requires openssl dev dependencies
(headers, lib) to be installed on the system.</li>
<li>run it like this: <code>ZAP_USE_OPENSSL=true zig build run-https</code>
OR like this: <code>zig build -Dopenssl=true run-https</code></li>
<li>it will tell you how to generate certificates</li>
</ul>
⚡blazingly fast⚡
Claiming to be blazingly fast is the new black. At least, Zap doesn't slow you
down and if your server performs poorly, it's probably not exactly Zap's fault.
Zap relies on the <a>facil.io</a> framework and so it can't really
claim any performance fame for itself. In this initial implementation of Zap,
I didn't care about optimizations at all.
But, how fast is it? Being blazingly fast is relative. When compared with a
simple GO HTTP server, a simple Zig Zap HTTP server performed really well on my
machine (x86_64-linux):
<ul>
<li>Zig Zap was nearly 30% faster than GO</li>
<li>Zig Zap had over 50% more throughput than GO</li>
<li><strong>YMMV!!!</strong></li>
</ul>
So, being somewhere in the ballpark of basic GO performance, zig zap seems to be
... of reasonable performance 😎.
I can rest my case that developing ZAP was a good idea because it's faster than
both alternatives: a) staying with Python, and b) creating a GO + Zig hybrid.
On (now missing) Micro-Benchmarks
I used to have some micro-benchmarks in this repo, showing that Zap beat all the
other things I tried, and eventually got tired of the meaningless discussions
they provoked, the endless issues and PRs that followed, wanting me to add and
maintain even more contestants, do more justice to beloved other frameworks,
etc.
Case in point, even for me the micro-benchmarks became meaningless. They were
just some rough indicator to me confirming that I didn't do anything terribly
wrong to facil.io, and that facil.io proved to be a reasonable choice, also from
a performance perspective.
However, none of the projects I use Zap for, ever even remotely resembled
anything close to a static HTTP response micro-benchmark.
For my more CPU-heavy than IO-heavy use-cases, a thread-based microframework
that's super robust is still my preferred choice, to this day.
Having said that, I would <strong>still love</strong> for other, pure-zig HTTP frameworks to
eventually make Zap obsolete. Now, in 2025, the list of candidates is looking
really promising.
📣 Shout-Outs
<ul>
<li><a>http.zig</a> : Pure Zig! Close to Zap's
model. Performance = good!</li>
<li><a>jetzig</a> : Comfortably develop
modern web applications quickly, using http.zig under the hood</li>
<li><a>zzz</a> : Super promising, super-fast,
especially for IO-heavy tasks, io_uring support - need I say more?</li>
</ul>
💪 Robust
ZAP is <strong>very robust</strong>. In fact, it is so robust that I was confidently able to
only work with in-memory data (RAM) in all my ZAP projects so far: over 5 large
online research experiments. No database, no file persistence, until I hit
"save" at the end 😊.
So I was able to postpone my cunning data persistence strategy that's similar to
a mark-and-sweep garbage collector and would only persist "dirty" data when
traffic is low, in favor of getting stuff online more quickly. But even if
implemented, such a persistence strategy is risky because when traffic is not
low, it means the system is under (heavy) load. Would you confidently NOT save
data when load is high and the data changes most frequently -> the potential
data loss is maximized?
To answer that question, I just skipped it. I skipped saving any data until
receiving a "save" signal via API. And it worked. ZAP just kept on zapping. When
traffic calmed down or all experiment participants had finished, I hit "save"
and went on analyzing the data.
Handling all errors does pay off after all. No hidden control flow, no hidden
errors or exceptions is one of Zig's strengths.
To be honest: There are still pitfalls. E.g. if you request large stack sizes
for worker threads, Zig won't like that and panic. So make sure you don't have
local variables that require tens of megabytes of stack space.
🛡️ Memory-safe
See the <a>StopEndpoint</a> in the
<a>endpoint</a> example. The <code>StopEndpoint</code> just stops ZAP when
receiving a request on the <code>/stop</code> route. That example uses ZIG's awesome
<code>GeneralPurposeAllocator</code> in <a>main.zig</a> to report
memory leaks when ZAP is shut down.
You can use the same strategy in your debug builds and tests to check if your
code leaks memory.
Getting started
Make sure you have <strong>zig 0.14.0</strong> installed. Fetch it from
<a>here</a>.
<code>shell
$ git clone https://github.com/zigzap/zap.git
$ cd zap
$ zig build run-hello
$ # open http://localhost:3000 in your browser</code>
... and open <a>http://localhost:3000</a> in your browser.
Using ⚡zap⚡ in your own projects
Make sure you have <strong>the latest zig release (0.14.0)</strong> installed. Fetch it from
<a>here</a>.
If you don't have an existing zig project, create one like this:
<code>shell
$ mkdir zaptest && cd zaptest
$ zig init</code>
With an existing Zig project, adding Zap to it is easy:
<ol>
<li>Zig fetch zap</li>
<li>Add zap to your <code>build.zig</code></li>
</ol>
In your zig project folder (where <code>build.zig</code> is located), run:
<code>zig fetch --save "git+https://github.com/zigzap/zap#v0.10.1"</code>
Then, in your <code>build.zig</code>'s <code>build</code> function, add the following before
<code>b.installArtifact(exe)</code>:
```zig
const zap = b.dependency("zap", .{
.target = target,
.optimize = optimize,
.openssl = false, // set to true to enable TLS support
});
<code>exe.root_module.addImport("zap", zap.module("zap"));
</code>
```
From then on, you can use the Zap package in your project via <code>const zap =
@import("zap");</code>. Check out the examples to see how to use Zap.
Contribute to ⚡zap⚡ - blazingly fast
At the current time, I can only add to zap what I need for my personal and
professional projects. While this happens <strong>blazingly fast</strong>, some if not all
nice-to-have additions will have to wait. You are very welcome to help make the
world a blazingly fast place by providing patches or pull requests, add
documentation or examples, or interesting issues and bug reports - you'll know
what to do when you receive your calling 👼.
<strong>We have our own <a>ZAP discord</a> server!!!</strong>
Support ⚡zap⚡
Being blazingly fast requires a constant feed of caffeine. I usually manage to
provide that to myself for myself. However, to support keeping the juices
flowing and putting a smile on my face and that warm and cozy feeling into my
heart, you can always <a>buy me a coffee</a>
☕. All donations are welcomed 🙏 blazingly fast! That being said, just saying
"hi" also works wonders with the smiles, warmth, and coziness 😊.
Examples
You build and run the examples via:
<code>shell
$ zig build [EXAMPLE]
$ ./zig-out/bin/[EXAMPLE]</code>
... where <code>[EXAMPLE]</code> is one of <code>hello</code>, <code>routes</code>, <code>serve</code>, ... see the <a>list of
examples above</a>.
Example: building and running the hello example:
<code>shell
$ zig build hello
$ ./zig-out/bin/hello</code>
To just run an example, like <code>routes</code>, without generating an executable, run:
<code>shell
$ zig build run-[EXAMPLE]</code>
Example: building and running the routes example:
<code>shell
$ zig build run-routes</code>
<a>hello</a>
```zig
const std = @import("std");
const zap = @import("zap");
fn on_request(r: zap.Request) !void {
if (r.path) |the_path| {
std.debug.print("PATH: {s}\n", .{the_path});
}
<code>if (r.query) |the_query| {
std.debug.print("QUERY: {s}\n", .{the_query});
}
r.sendBody("<html><body><h1>Hello from ZAP!!!</h1></body></html>") catch return;
</code>
}
pub fn main() !void {
var listener = zap.HttpListener.init(.{
.port = 3000,
.on_request = on_request,
.log = true,
});
try listener.listen();
<code>std.debug.print("Listening on 0.0.0.0:3000\n", .{});
// start worker threads
zap.start(.{
.threads = 2,
.workers = 2,
});
</code>
}
``` | [
"https://github.com/0x4c756e61/ZDSM",
"https://github.com/Ashu11-A/zig-rest-api",
"https://github.com/BitlyTwiser/zlog",
"https://github.com/EloToJaa/zap",
"https://github.com/EngineersBox/Flow",
"https://github.com/Lajule/hsminer",
"https://github.com/OsakiTsukiko/nimrod",
"https://github.com/QubitSy... |
https://avatars.githubusercontent.com/u/109492796?v=4 | awesome-zig | zigcc/awesome-zig | 2022-12-17T03:52:10Z | A collection of some awesome public Zig programming language projects. | main | 0 | 1,415 | 75 | 1,415 | https://api.github.com/repos/zigcc/awesome-zig/tags | MIT | [
"andrew-kelley",
"awesome-list",
"bun",
"mach",
"zig",
"zig-lib",
"zig-library",
"zig-package",
"ziglang"
] | 291 | false | 2025-05-22T02:02:13Z | false | false | unknown | github | [] | Awesome Zig
This repository lists "awesome" projects written in Zig, maintained by <a>ZigCC community</a>.
<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>
The word "awesome" does not signify stability; instead, it might suggest something is somewhat old-fashioned or lacking novelty. Hence, exercise caution.
</blockquote>
Contributing
If you find a well-maintained library that is not yet included here, welcome to submit it via a pull request. Just be sure to execute <code>make all</code> before you open a PR.
Contents
<ul>
<li><a>Learning Resources</a></li>
<li><a>Tools</a></li>
<li><a>Text Editors</a></li>
<li><a>Linter</a></li>
<li><a>Documentation and Testing</a></li>
<li><a>Package and Version Manager</a></li>
<li><a>Utility</a></li>
<li><a>Linker</a></li>
<li><a>Data Structure and Algorithm</a></li>
<li><a>String Processing</a></li>
<li><a>File format processing</a></li>
<li><a>Logging Processing</a></li>
<li><a>Audio Processing</a></li>
<li><a>Image and Video Processing</a></li>
<li><a>Date, Time and Timezones</a></li>
<li><a>Command Line and Argument Parser</a></li>
<li><a>Memory Allocator and Management</a></li>
<li><a>Asynchronous Runtime</a></li>
<li><a>Multithreading</a></li>
<li><a>Embedded Development</a></li>
<li><a>General Operating System</a></li>
<li><a>Robot Operating System</a></li>
<li><a>Compilers and Interpreters</a></li>
<li><a>FFI Bindings</a></li>
<li><a>Zigged Project</a></li>
<li><a>GPU Computing</a></li>
<li><a>Scientific Computation</a></li>
<li><a>Linear Algebra</a></li>
<li><a>Machine Learning</a></li>
<li><a>Machine Learning Framework</a></li>
<li><a>Large Language Model</a></li>
<li><a>Database</a></li>
<li><a>Sensor and Communication Interface</a></li>
<li><a>Finite State Machine</a></li>
<li><a>Game Field</a></li>
<li><a>Emulators</a></li>
<li><a>Encryption</a></li>
<li><a>Network</a></li>
<li><a>Web Framework</a></li>
<li><a>Web3 Framework</a></li>
<li><a>WebAssembly</a></li>
<li><a>Performance Benchmark</a></li>
<li><a>Graphics Library</a></li>
<li><a>GUI</a></li>
<li><a>Misc</a></li>
</ul>
TOC is generated by <a>markdown-toc</a>.
Learning Resources
<ul>
<li><a>Zig Language Reference</a> : Zig Language Reference.</li>
<li><a>Zig In-depth Overview</a> : Zig In-depth Overview.</li>
<li><a>Zig Guide</a> : Get started with the Zig programming language.</li>
<li><a>Zig cookbook</a> : A collection of simple Zig programs that demonstrate good practices to accomplish common programming tasks.</li>
<li><a>Zig in 30 minutes</a> : A half-hour to learn Zig.</li>
<li><a>Ziglings</a> : Learn the Zig programming language by fixing tiny broken programs.</li>
<li><a>Awesome zig wiki</a>: Other interesting materials about Zig.</li>
<li><a>Learning Zig</a> : This guide aims to make you comfortable with Zig. It assumes prior programming experience, though not in any particular language.</li>
<li><a>Zig 圣经</a> : 简单、快速地学习 Zig.</li>
</ul>
Tools
Text Editors
<ul>
<li><a>FalsePattern/ZigBrains</a> : JetBrains IDEs (CLion, IntelliJ IDEA and others) plugin for Zig</li>
<li><a>isaachier/ztags</a> : ctags implementation for Zig written in Zig.</li>
<li><a>jinzhongjia/znvim</a> : neovim remote rpc client implementation with Zig.</li>
<li><a>Tetralux/sublime-zig</a> : My own, more lightweight, syntax highlighting for the Zig Programming Language.</li>
<li><a>ziglang/sublime-zig-language</a> : Zig language support for Sublime Text.</li>
<li><a>ziglang/vscode-zig</a> : Zig language support for VSCode.</li>
<li><a>ziglang/zig.vim</a> : Vim configuration for Zig.</li>
<li><a>ziglang/zig-mode</a> : Zig mode for Emacs.</li>
<li><a>zigtools/zls</a> : The @ziglang language server for all your Zig editor tooling needs, from autocomplete to goto-def! <a>install.zigtools.org/</a></li>
<li><a>jinzhongjia/zig-lamp</a> : Improve the Zig development experience in Neovim.</li>
<li><a>neurocyte/flow</a> : Flow Control - a programmer's text editor written in Zig.</li>
</ul>
Linter
<ul>
<li><a>nektro/ziglint</a> : linting suite for Zig</li>
</ul>
Documentation and Testing
<ul>
<li><a>kristoff-it/zig-doctest</a> : A tool for testing snippets of code, useful for websites and books that talk about Zig.</li>
</ul>
Package and Version Manager
<ul>
<li><a>zigcc/asdf-zig</a> : zig plugin for asdf version manager. <a>https://github.com/asdf-vm/asdf</a></li>
<li><a>marler8997/zigup</a> : Download and manage zig compilers.</li>
<li><a>zigtools/zpm</a> : Zig package manager helper.</li>
<li><a>goto-bus-stop/setup-zig</a> : Setup Zig for GitHub Action Workflows.</li>
<li><a>korandoru/setup-zig</a> : Set up your GitHub Actions workflow with a specific version of Zig.</li>
<li><a>jsomedon/night.zig</a> : Simple tool that just install & update zig nightly.</li>
<li><a>matklad/hello-getzig</a> : getzig is an idea for a zig version manager along the lines of gradle wrapper.</li>
<li><a>mitchellh/zig-overlay</a> : Nix flake for the Zig compiler.</li>
<li><a>Cloudef/zig2nix</a> : Flake for packaging, building and running Zig projects.</li>
<li><a>nix-community/zon2nix</a> : Convert dependencies in build.zig.zon files to Nix expressions.</li>
<li><a>Cloudef/nix-zig-stdenv</a> : Zig based cross-compiling toolchain.</li>
<li><a>joachimschmidt557/zigpkgs</a> : A collection of zig packages built with Nix.</li>
<li><a>nektro/zigmod</a> : 📦 A package manager for the Zig programming language.</li>
<li><a>mattnite/gyro</a> : A Zig package manager with an index, build runner, and build dependencies.</li>
<li><a>vezel-dev/zig-sdk</a> : An MSBuild SDK for building Zig, C, and C++ projects using the Zig compiler.</li>
<li><a>tristanisham/zvm</a> : lets you easily install/upgrade between different versions of Zig. ZLS install can be included.</li>
</ul>
Utility
<ul>
<li><a>BrookJeynes/jido</a> : Jido (formerly known as zte) is a small terminal file explorer, written in Zig.</li>
<li><a>fearedbliss/Honeydew</a> : A simple snapshot cleaner for OpenZFS written in Zig.</li>
<li><a>fearedbliss/Cantaloupe</a> : A simple backup replication tool for OpenZFS written in Zig.</li>
<li><a>Arnau478/hevi</a> : A minimalistic and modernized hex viewer, written in Zig.</li>
<li><a>gaskam/workspace</a> : A powerful Zig-based tool to manage all your GitHub repositories with ease.</li>
<li><a>rockorager.dev/lsr</a> : Efficient and fast <code>ls</code> alternative, written in Zig.</li>
</ul>
Linker
<ul>
<li><a>kubkon/bold</a> : <strong>bold</strong> is a drop-in replacement for Apple’s system linker <code>ld</code></li>
</ul>
Data Structure and Algorithm
<ul>
<li><a>hello-algo-zig</a> : <strong>Zig</strong> programming language codes for the famous public project <a>《Hello, Algorithm》|《 Hello,算法 》</a> about data structures and algorithms.</li>
<li><a>TheAlgorithms/Zig</a> : Collection of Algorithms implemented in Zig.</li>
<li><a>ramsyana/Zig-Math-Algorithms</a> : A collection of math algorithms in Zig—primes, Fibonacci, GCD, Euler's Totient, & more! Perfect for learning Zig & math.</li>
<li><a>alichraghi/zort</a> : Zort: Sorting algorithms in zig.</li>
<li><a>Srekel/zig-sparse-set</a> : 🎡 zig-sparse-set 🎡. Sparse sets for zig, supporting both SOA and AOS style.</li>
<li><a>mitchellh/zig-graph</a> : Directed graph data structure for Zig.</li>
<li><a>ok-ryoko/multiring.zig</a> : Singly linked, cyclic and hierarchical abstract data type in Zig.</li>
<li><a>jakubgiesler/VecZig</a> : Vector implementation in Zig.</li>
<li><a>JacobCrabill/btree.zig</a> : Behavior Tree library written in Zig.</li>
<li><a>DutchGhost/ArrayVec</a> : A library with an ArrayList-like API, except its a static array.</li>
<li><a>emekoi/deque.zig</a> : a lock free chase-lev deque for zig.</li>
<li><a>kristoff-it/zig-cuckoofilter</a> : Production-ready Cuckoo Filters for any C ABI compatible target.</li>
<li><a>BarabasGitHub/LZig4</a> : Implementing lz4 in zig.</li>
<li><a>marijnfs/zigtimsort</a> : TimSort implementation for Zig.</li>
<li><a>Sahnvour/zig-containers</a> : A set of containers for Zig.</li>
<li><a>booniepepper/zig-data-structures</a> : Home to some experiments in Zig data structures.</li>
<li><a>deckarep/ziglang-set</a> : A generic and general purpose Set implementation for the Zig language.</li>
<li><a>yamafaktory/hypergraphz</a> : HypergraphZ - A Hypergraph Implementation in Zig.</li>
<li><a>williamw520/toposort</a> : Topological sort library that produces topological ordered nodes and dependence-free subsets.</li>
<li><a>kobolds-io/stdx</a> : Helpful extensions to the zig standard library.</li>
</ul>
String Processing
<ul>
<li><a>JakubSzark/zig-string</a> : Zig String (A UTF-8 String Library). This library is a UTF-8 compatible string library for the Zig programming language.</li>
<li><a>jecolon/zigstr</a> : Zigstr is a UTF-8 string type for Zig programs.</li>
<li><a>ziglibs/string-searching</a> : String(not limited to []const u8)-searching algorithms in zig.</li>
<li><a>hwu1001/zig-string</a> : A String struct made for Zig.</li>
</ul>
File format processing
<ul>
<li><a>ziglibs/known-folders</a> Provides access to well-known folders across several operating systems.</li>
<li><a>tiehuis/zig-regex</a> : A regex implementation for the zig programming language.</li>
<li><a>getty-zig/getty</a> : Getty is a framework for building robust, optimal, and reusable (de)serializers in Zig. <a>getty.so</a></li>
<li><a>jecolon/ziglyph</a> : Unicode text processing for the Zig programming language.</li>
<li><a>kubkon/zig-yaml</a> : YAML parser for Zig.</li>
<li><a>nektro/zig-json</a> : A JSON library for inspecting arbitrary values.</li>
<li><a>getty-zig/json</a> : Getty JSON is a (de)serialization library for the JSON data format.</li>
<li><a>MahBestBro/regex</a> : A single file regex library written in and for Zig.</li>
<li><a>karlseguin/log.zig</a> : A structured logger for Zig.</li>
<li><a>mattyhall/tomlz</a> : A well-tested TOML parsing library for Zig.</li>
<li><a>mitchellh/zig-libxml2</a> : libxml2 built using Zig build system.</li>
<li><a>travisstaloch/protobuf-zig</a> : A protocol buffers implementation in zig.</li>
<li><a>sam701/zig-toml</a> : Zig TOML (v1.0.0) parser.</li>
<li><a>ziglibs/tres</a> : ValueTree-based JSON parser.</li>
<li><a>ziglibs/s2s</a> : A zig binary serialization format.</li>
<li><a>Arwalk/zig-protobuf</a> : a protobuf 3 implementation for zig.</li>
<li><a>aeronavery/zig-toml</a> : A TOML parser written in Zig.</li>
<li><a>goto-bus-stop/ziguid</a> : GUID parsing/stringifying with zig.</li>
<li><a>ducdetronquito/hppy</a> : The happy HTML parser ᕕ( ᐛ )ᕗ.</li>
<li><a>kivikakk/libpcre.zig</a> : Zig bindings to libpcre.</li>
<li><a>kivikakk/koino</a> : CommonMark + GFM compatible Markdown parser and renderer.</li>
<li><a>m-r-hunt/tjp</a> : Typed JSON Parser.</li>
<li><a>tiehuis/zig-ryu</a> : Zig port of <a>https://github.com/ulfjack/ryu</a>.</li>
<li><a>vi/zigmkv</a> : [wip] Matroska/webm (mkv) parser in Zig.</li>
<li><a>winksaville/zig-parse-number</a> : Implement ParseNumber which can parse any TypeId.Int or TypeId.Float.</li>
<li><a>demizer/markzig</a> : Pure Zig Markdown Parser.</li>
<li><a>thejoshwolfe/hexdump-zip</a> : produce an annotated hexdump of a zipfile.</li>
<li><a>javiorfo/prettizy</a> : Zig library to prettify JSON and XML strings.</li>
<li><a>javiorfo/zig-epub</a> : Minimal Zig library for creating EPUB files.</li>
</ul>
Logging Processing
<ul>
<li><a>emekoi/log.zig</a> : a thread-safe logging library for zig.</li>
<li><a>g41797/syslog</a> : <a>syslog</a> RFC5424 client library.</li>
<li><a>chrischtel/nexlog</a> : A modern, feature-rich logging library for Zig with thread-safety, file rotation, and colorized output.</li>
<li><a>sam701/slog</a> : a configurable, structured logging package for Zig with support for hierarchical loggers.</li>
</ul>
Audio Processing
<ul>
<li><a>orhun/linuxwave</a> : Generate music from the entropy of Linux 🐧🎵. <a>orhun.dev/linuxwave/</a></li>
<li><a>hexops/mach-sysaudio</a> : cross-platform low-level audio IO in Zig.</li>
<li><a>Hejsil/zig-midi</a> : zig-midi.</li>
</ul>
Image and Video Processing
<ul>
<li><a>zigimg/zigimg</a> : Zig library for reading and writing different image formats.</li>
<li><a>ryoppippi/zigcv</a> : opencv bindings for zig.</li>
<li><a>kassane/libvlc-zig</a> : Zig bindings for libVLC media framework.</li>
<li><a>marler8997/image-viewer</a> : An image-viewer experiment written in Zig.</li>
<li><a>bfactory-ai/zignal</a> : Image processing library in Zig, heavily inspired by dlib .</li>
</ul>
Date, Time and Timezones
<ul>
<li><a>scento/zig-date</a> : 🕒 time and date for Zig. zig-date is a date and time library for the Zig, inspired by the popular Rust library <a>chrono</a>.</li>
<li><a>frmdstryr/zig-datetime</a> : A datetime module for Zig with an api similar to python's Arrow.</li>
<li><a>nektro/zig-time</a> : A date and time parsing and formatting library for Zig.</li>
<li><a>travisstaloch/date-zig</a> : fast calendar algorithms ported to Zig (Cassio Neri's <a>EAF</a>).</li>
<li><a>leroycep/chrono-zig</a> : Zig port of the Rust chrono crate.</li>
<li><a>karlseguin/zul</a> : some date/time handling functionality among the other functionality.</li>
<li><a>clickingbuttons/datetime</a> : Generic Date, Time, and DateTime library.</li>
<li><a>leroycep/zig-tzif</a> : <a>TZif</a> parser that also handles POSIX timezone strings</li>
<li><a>FObersteiner/zdt</a> : Timezoned Datetime in Zig. For learning purposes.</li>
<li><a>rockorager/zeit</a> : Generic date/time library, including time zone loading and conversion.</li>
<li><a>deatil/zig-time</a> : A date and time parse and format library for Zig.</li>
</ul>
Command Line and Argument Parser
<ul>
<li><a>Hejsil/zig-clap</a> : A simple and easy to use command line argument parser library for Zig.</li>
<li><a>MasterQ32/zig-args</a> : Simple-to-use argument parser with struct-based config.</li>
<li><a>jiacai2050/zigcli</a> : A toolkit for building command lines programs in Zig.</li>
<li><a>PrajwalCH/yazap</a> : 🔧 The ultimate Zig library for seamless command line parsing. Effortlessly handles options, subcommands, and custom arguments with ease. <a>prajwalch.github.io/yazap</a></li>
<li><a>00JCIV00/cova</a> : Commands, Options, Values, Arguments. A simple yet robust cross-platform command line argument parsing library for Zig.</li>
<li><a>BanchouBoo/accord</a> : A simple argument parser for Zig.</li>
<li><a>judofyr/parg</a> : Lightweight argument parser for Zig.</li>
<li><a>sam701/zig-cli</a> : A simple package for building command line apps in Zig.</li>
<li><a>GabrieleInvernizzi/zig-prompter</a> : A flexible library for building interactive command line prompts.</li>
<li><a>kioz-wang/zargs</a> : Another Comptime-argparse for Zig.</li>
</ul>
Memory Allocator and Management
<ul>
<li><a>Aandreba/zigrc</a> : Zig reference-counted pointers inspired by Rust's Rc and Arc. <a>aandreba.github.io/zigrc/</a></li>
<li><a>DutchGhost/zorrow</a> : Borrowchecker in Zig. This is a userlevel implementation of borrowchk in Zig.</li>
<li><a>mdsteele/ziegfried</a> : A general-purpose memory allocator for Zig.</li>
<li><a>fengb/zee_alloc</a> : tiny Zig allocator primarily targeting WebAssembly.</li>
<li><a>suirad/Seal</a> : An allocator that wraps another allocator and detects if memory is leaked after usage.</li>
<li><a>rvcas/mpool</a> : A memory pool library written in Zig.</li>
<li><a>nsmryan/zig_sealed_and_compact</a> : Zig functions for memory management.</li>
<li><a>suirad/adma</a> : A general purpose, multithreaded capable slab allocator for Zig.</li>
<li><a>hmusgrave/zcirc</a> : A dynamic circular buffer allocator for zig.</li>
<li><a>dweiller/zig-composable-allocators</a> : Comptime-generic composable allocators.</li>
<li><a>bcrist/Zig-TempAllocator</a> : Arena allocator for interactive programs and simulations.</li>
<li><a>rdunnington/zig-stable-array</a> : Address-stable array with a max size that allocates directly from virtual memory.</li>
<li><a>dweiller/zimalloc</a> : zimalloc is general purpose allocator for Zig, inspired by <a>mimalloc</a>.</li>
<li><a>Hejsil/zig-gc</a> :A super simple mark-and-sweep garbage collector written in Zig.</li>
</ul>
Asynchronous Runtime
<ul>
<li><a>mitchellh/libxev</a> : libxev is a cross-platform, high-performance event loop that provides abstractions for non-blocking IO, timers, events, and more and works on Linux (io_uring or epoll), macOS (kqueue), and Wasm + WASI. Available as both a Zig and C API.</li>
<li><a>kprotty/zap</a> : An asynchronous runtime with a focus on performance and resource efficiency.</li>
<li><a>lithdew/pike</a> : Async I/O for Zig.</li>
</ul>
Multithreading
<ul>
<li><a>g41797/mailbox</a> : mailbox is convenient inter-thread communication mechanizm.</li>
</ul>
Embedded Development
<ul>
<li><a>ZigEmbeddedGroup/microzig</a> : Unified abstraction layer and HAL for several microcontrollers.</li>
<li><a>ZigEmbeddedGroup/stmicro-stm32</a> : HAL for stm32 (STMicro) devices.</li>
<li><a>ZigEmbeddedGroup/raspberrypi-rp2040</a> : MicroZig Hardware Support Package for Raspberry Pi RP2040.</li>
<li><a>ZigEmbeddedGroup/regz</a> : Generate zig code from ATDF or SVD files for microcontrollers.</li>
<li><a>nmeum/zig-riscv-embedded</a> : Experimental Zig-based CoAP node for the HiFive1 RISC-V board.</li>
<li><a>lupyuen/pinephone-nuttx</a> : Apache NuttX RTOS for PinePhone. Apache NuttX is a lightweight Real-Time Operating System (RTOS) that runs on PINE64 PinePhone. <a>lupyuen.github.io/articles/what</a></li>
<li><a>lupyuen/zig-bl602-nuttx</a> : Zig on RISC-V BL602 with Apache NuttX RTOS and LoRaWAN.</li>
<li><a>leecannon/zig-sbi</a> : Zig wrapper around the RISC-V SBI specification.</li>
<li><a>eastonman/zesty-core</a> : A RISC-V OS written in Zig.</li>
<li><a>kivikakk/daintree</a> : ARMv8-A/RISC-V kernel (with UEFI bootloader). An operating system plus a UEFI bootloader, all written in Zig.</li>
<li><a>markfirmware/zig-bare-metal-microbit</a> : Bare metal microbit program written in zig.</li>
<li><a>markfirmware/zig-bare-metal-raspberry-pi</a> : Bare metal raspberry pi program written in zig.</li>
<li><a>tralamazza/embedded_zig</a> : minimal Zig embedded ARM example (STM32F103 blue pill).</li>
<li><a>yvt/zig-armv8m-test</a> : Example Zig-based app for Armv8-M + TrustZone.</li>
<li><a>hspak/brightnessztl</a> : A CLI to control device backlight.</li>
<li><a>justinbalexander/svd2zig</a> : Convert System View Description (svd) files to Zig headers for baremetal development.</li>
<li><a>mqttiotstuff/iotmonitor</a> : PainLess, Monitor and State server for iot mqtt devices, and software agents. This daemon permit to maintain the execution of constellations of mqtt devices and associated agents.</li>
<li><a>Elara6331/zig-gpio</a>: A Zig library for controlling GPIO lines on Linux systems.</li>
<li><a>ringtailsoftware/zeptolibc</a> : Essential libc functions in Zig for freestanding targets</li>
</ul>
General Operating System
<ul>
<li><a>ZystemOS/Pluto</a> : An x86 kernel written in Zig.</li>
<li><a>davidgm94/birth</a> : Rise: an attempt to write a better operating system.</li>
<li><a>iguessthislldo/georgios</a> : Hobby Operating System.</li>
<li><a>rafaelbreno/zig-os</a> : A simple OS written in Zig following Philipp Oppermann's posts <a>Writing an OS in Rust</a>.</li>
<li><a>jzck/kernel-zig</a> : 💾 hobby x86 kernel zig.</li>
<li><a>andrewrk/HellOS</a> : "hello world" x86 kernel example.</li>
<li><a>marlersoft/zigwin32</a> : A complete autogenerated set of Zig bindings for the Win32 API.</li>
<li><a>a1393323447/zcore-os</a> : A RISC-V OS written in Zig. rCore-OS translated in Zig language.</li>
<li><a>b0bleet/zvisor</a> : Zvisor is an open-source hypervisor written in the Zig programming language, which provides a modern and efficient approach to systems programming.</li>
<li><a>TalonFloof/zorroOS</a> : Hobby operating system written in Zig.</li>
<li><a>CascadeOS/CascadeOS</a> : General purpose operating system targeting standard desktops and laptops.</li>
<li><a>AndreaOrru/zen</a> : Experimental operating system written in Zig.</li>
<li><a>DorianXGH/Lukarnel</a> : A microkernel in zig with rust microservices.</li>
<li><a>liampwll/zig-efi-os</a> : zig-efi-os.</li>
<li><a>nrdmn/uefi-examples</a> UEFI examples in Zig.</li>
<li><a>nrdmn/uefi-paint</a> : UEFI-bootable touch paint app.</li>
<li><a>sjdh02/trOS</a> : tiny aarch64 baremetal OS thingy.</li>
<li><a>ZeeBoppityZagZiggity/ZBZZ.OS</a> : An operating system built with RISCV and Zig.</li>
<li><a>pbui-project/pbui-main</a> : The PBUI (POSIX-compliant BSD/Linux Userland Implementation) project is a a free and open source project intended to implement some standard library toolsets in the Zig programming language.</li>
<li><a>momumi/x86-zig</a> : library for assembling x86 in zig (WIP).</li>
<li><a>javiorfo/zig-syslinfo</a> : Linux sysinfo Zig library.</li>
</ul>
Robot Operating System
<ul>
<li><a>jacobperron/rclzig</a> : ROS 2 client library in Zig.</li>
<li><a>luickk/MinimalRoboticsPlatform</a> : MRP is a minimal microkernel that supports the most fundamental robotic domains. It's thought for highly integrated robotics development.</li>
</ul>
Compilers and Interpreters
<ul>
<li><a>Aro</a> : Aro. A C compiler with the goal of providing fast compilation and low memory usage with good diagnostics.</li>
<li><a>buzz</a>: A small/lightweight statically typed scripting language.</li>
<li><a>fubark/cyber</a> : Fast and concurrent scripting.</li>
<li><a>squeek502/zua</a> : An implementation of Lua 5.1 in Zig, for learning purposes.</li>
<li><a>Vexu/bog</a> : Small, strongly typed, embeddable language.</li>
<li><a>fury</a> : Fury, a gradual, safe systems language.</li>
</ul>
FFI Bindings
<ul>
<li><a>natecraddock/ziglua</a> : Zig bindings for the Lua C API.</li>
<li><a>sackosoft/zig-luajit</a> : Zig bindings for the LuaJIT C API.</li>
<li><a>mitchellh/zig-objc</a> : Objective-C runtime bindings for Zig (Zig calling ObjC).</li>
<li><a>fulcrum-so/ziggy-pydust</a> : A toolkit for building Python extensions in Zig. <a>pydust.fulcrum.so/</a></li>
<li><a>katafrakt/zig-ruby</a> : This repo contains an experiment of building a Ruby extension with Zig programming language. It implements a slightly altered version of 100 doors from Rosetta Code.</li>
<li><a>ExpidusOS/zig-flutter</a> : Flutter w/ Zig.</li>
<li><a>lassade/c2z</a> : C++ to Zig bindings and transpiler.</li>
<li><a>floooh/sokol-zig</a> : Zig bindings for the sokol headers</li>
<li><a>jiacai2050/zig-curl</a> : Zig bindings for libcurl</li>
<li><a>jiacai2050/zig-rocksdb</a> : Zig bindings for RocksDB.</li>
<li><a>jiacai2050/zig-jemalloc</a> : Zig allocator baked by jemalloc</li>
<li><a>arshidkv12/zig-php</a> : Write PHP extension in Zig</li>
<li><a>OnlyF0uR/pqc-zig</a> : Zig bindings and abstractions for <a>PQClean</a>, post-quantum cryptography.</li>
</ul>
Zigged Project
<ul>
<li><a>libz</a>: zlib with the build system replaced by zig</li>
<li><a>libmp3lame</a>: libmp3lame with the build system replaced by zig</li>
<li><a>libvorbis</a>: libvorbis with the build system replaced by zig</li>
<li><a>libogg</a>: libogg with the build system replaced by zig</li>
<li><a>nasm</a>: nasm with the build system replaced by zig</li>
<li><a>ffmpeg</a>: ffmpeg with the build system replaced by zig</li>
<li><a>libebur128</a>: libebur128 with the build system replaced by zig</li>
<li><a>pulseaudio</a>: pulseaudio with the build system replaced by zig</li>
<li><a>libchromaprint</a>: chromaprint with the build system replaced by zig</li>
<li><a>raylib</a>: A simple and easy-to-use library to enjoy videogames programming</li>
<li><a>openssl</a>: TLS/SSL and crypto library (uses Zig Build)</li>
<li><a>wolfssl</a>: WolfSSL library - Using Zig Build</li>
<li><a>fmt</a>: A modern formatting library (uses zig build-system)</li>
<li><a>boost unordered</a>: Boost.org unordered module (uses zig build)</li>
<li><a>boost async</a>: Coroutines for C++20 & asio (uses zig build for testing)</li>
<li><a>json</a>: JSON for Modern C++ (uses zig build-system)</li>
<li><a>context</a>: <code>boost.context</code> library using zig build</li>
<li><a>fiber</a>: userland threads uses zig build</li>
<li><a>outcome</a>: Provides very lightweight outcome<T> and result<T> (non-Boost edition) (uses zig build-system)</li>
<li><a>Standalone</a>: Asio standalone C++ HTTP/S Server (uses zig build-system)</li>
<li><a>asio</a>: Asio C++ Library (uses zig build-system)</li>
<li><a>observable</a>: : Unique-ownership smart pointers with observable lifetime.</li>
<li><a>Catch2</a>: A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch) - uses zig build-system</li>
<li><a>cppfront</a>: Build Cppfront w/ zig build</li>
<li><a>hana</a>: Your standard library for metaprogramming</li>
<li><a>intrusive</a>: Boost.org intrusive module</li>
<li><a>range</a>: Range library for C++14/17/20, basis for C++20's std::ranges</li>
<li><a>zig-libxml2</a>: libxml2 built using Zig build system</li>
<li><a>benchmark</a>: A microbenchmark support library
First post at <a>here</a>.</li>
<li><a>libffi</a>: libffi with a Zig build script.</li>
</ul>
GPU Computing
<ul>
<li><a>gwenzek/cudaz</a> : Toy Cuda wrapper for Zig.</li>
<li><a>lennyerik/cutransform</a> : CUDA kernels in any language supported by LLVM.</li>
<li><a>Snektron/vulkan-zig</a> : Vulkan binding generator for Zig.</li>
<li><a>hexops/mach-gpu</a> : mach/gpu provides a truly cross-platform graphics API for Zig (desktop, mobile, and web) with unified low-level graphics & compute backed by Vulkan, Metal, D3D12, and OpenGL (as a best-effort fallback.)</li>
<li><a>hexops/mach-gpu-dawn</a> : Google's Dawn WebGPU implementation, cross-compiled with Zig into a single static library.</li>
<li><a>ckrowland/simulations</a> : GPU accelerated visual simulations.</li>
<li><a>Avokadoen/zig_vulkan</a> : Voxel ray tracing using Vulkan compute.</li>
<li><a>akhildevelops/cudaz</a> : Cuda wrapper for interacting with GPUs in zig.</li>
<li><a>e253/zig-ocl</a> : Static Zig Build of the OpenCL ICD Loader from Khronos Group.</li>
</ul>
Scientific Computation
<ul>
<li>
Linear Algebra
</li>
<li>
<a>kooparse/zalgebra</a> : Linear algebra library for games and real-time graphics.
</li>
<li><a>ziglibs/zlm</a> : Zig linear mathematics.</li>
<li><a>omaraaa/VecFns</a> : Automatic Vector Math Functions In Zig.</li>
<li><a>Laremere/alg</a> : Algebra for Zig.</li>
<li><a>BanchouBoo/algae</a> : Zig math library focused on game development.</li>
<li><a>JungerBoyo/zmath</a> : simple linear algebra library written in zig.</li>
<li><a>pblischak/zprob</a> : A Zig Library for Probability Distributions.</li>
</ul>
Machine Learning
<ul>
<li>
Machine Learning Framework
</li>
<li>
<a>ggml</a> : Tensor library for machine learning. Written in C.
</li>
<li><a>ggml-zig</a> : <a>ggml: Tensor library for machine learning</a> written in zig.</li>
<li><a>rockcarry/ffcnn</a> : ffcnn is a cnn neural network inference framework, written in 600 lines C language.</li>
<li><a>xboot/libonnx</a> : A lightweight, portable pure C99 onnx inference engine for embedded devices with hardware acceleration support.</li>
<li><a>kraiskil/onnx2c</a> : Open Neural Network Exchange to C compiler. Onnx2c is a <a>ONNX</a> to C compiler. It will read an ONNX file, and generate C code to be included in your project. Onnx2c's target is "Tiny ML", meaning running the inference on microcontrollers.</li>
<li><a>candrewlee14/zgml</a> : Tensor library for machine learning, inspired by ggml.</li>
<li><a>maihd/zten</a> : Tensor library for Zig, based on ggml.</li>
<li><a>andrewCodeDev/ZEIN</a> : Zig-based implementation of tensors.</li>
<li><a>recursiveGecko/onnxruntime.zig</a> : Experimental Zig wrapper for ONNX Runtime with examples (Silero VAD, NSNet2).</li>
<li><a>Gonzih/onnx-worker.zig</a> : onnx-worker.zig</li>
<li><a>zml</a> : zml is a machine learning framework</li>
<li><a>Zigrad</a> : A deep learning framework built on an autograd engine with high level abstractions and low level control. Trains neural networks 2.5x faster than Pytorch on Apple Silicon and 1.5x faster on CPU.</li>
<li>
<a>SilasMarvin/dnns from scratch in zig</a> : a very simple implementation of deep neural networks written in the Zig programming language. https://silasmarvin.dev/dnns-from-scratch-in-zig
</li>
<li>
Large Language Model
</li>
<li>
<a>ollama-zig</a> : Ollama Zig library.
</li>
<li><a>llama.cpp</a> : Inference of <a>LLaMA</a> model in pure C/C++.</li>
<li><a>cgbur/llama2.zig</a> : Inference Llama 2 in one file of pure Zig.</li>
<li><a>clebert/llama2.zig</a> : Inference Llama 2 in pure Zig.</li>
<li><a>renerocksai/gpt4all.zig</a> : ZIG build for a terminal-based chat client for an assistant-style large language model with ~800k GPT-3.5-Turbo Generations based on LLaMa.</li>
<li><a>EugenHotaj/zig_gpt2</a> : Neural Network Inference Engine in Zig. GPT2 inference engine written in Zig. The inference engine can run <a>NanoGPT</a>.</li>
</ul>
Database
<ul>
<li><a>tigerbeetle</a> : The distributed financial accounting database designed for mission critical safety and performance. <a>tigerbeetle.com</a></li>
<li><a>vrischmann/zig-sqlite</a> : zig-sqlite is a small wrapper around sqlite's C API, making it easier to use with Zig.</li>
<li><a>leroycep/sqlite-zig</a> : This repository has zig bindings for sqlite. It tries to make the sqlite c API more ziggish.</li>
<li><a>nDimensional/zig-sqlite</a> : Simple, low-level, explicitly-typed SQLite bindings for Zig.</li>
<li><a>mjoerussell/zdb</a> : A library for interacting with databases in Zig.</li>
<li><a>kristoff-it/redis-cuckoofilter</a> : Hashing-function agnostic Cuckoo filters for Redis.</li>
<li><a>kristoff-it/zig-okredis</a> : Zero-allocation Client for Redis 6+.</li>
<li><a>vrischmann/zig-cassandra</a> : Client for Cassandra 2.1+</li>
<li><a>speed2exe/myzql</a> : MySQL and MariaDB driver in native Zig</li>
<li><a>karlseguin/pg.zig</a> : Native PostgreSQL driver / client for Zig</li>
<li><a>karlseguin/zuckdb.zig</a> : A DuckDB driver for Zig</li>
</ul>
Sensor and Communication Interface
<ul>
<li><a>MasterQ32/zig-network</a> : A smallest-common-subset of socket functions for crossplatform networking, TCP & UDP.</li>
<li><a>ZigEmbeddedGroup/serial</a> : Serial port configuration library for Zig.</li>
<li><a>tetsu-koba/v4l2capture</a> : v4l2 video capturer written in Zig.</li>
<li><a>kdchambers/reel</a> : Screen capture software for Linux / Wayland.</li>
<li><a>ringtailsoftware/commy</a> : Serial terminal monitor for Linux, Mac and Windows</li>
</ul>
Finite State Machine
<ul>
<li><a>cryptocode/zigfsm</a> : zigfsm is a <a>finite state machine</a> library for Zig.</li>
</ul>
Game Field
<ul>
<li><a>Mach</a> : Mach is a game engine & graphics toolkit for the future. machengine.org.</li>
<li><a>zig-gamedev/zig-gamedev</a> : Building game development ecosystem for @ziglang!</li>
<li><a>ryupold/zecsi</a> : Small game framework made with Zig utilizing the awesome raylib.</li>
<li><a>wendigojaeger/ZigGBA</a> : Work in progress SDK for creating Game Boy Advance games using Zig programming language.</li>
<li><a>zPSP-Dev/Zig-PSP</a> : A project to bring the Zig Programming Language to the Sony PlayStation Portable!</li>
<li><a>prime31/zig-gamekit</a> : Companion repo for zig-renderkit for making 2D games.</li>
<li><a>Jack-Ji/jok</a> : A minimal 2d/3d game framework for zig.</li>
<li><a>star-tek-mb/Paradise</a> : Paradise is a wasm first game engine written in zig.</li>
<li><a>zkburke/quanta</a> : A game engine/framework written in and for zig.</li>
<li><a>andrewrk/tetris</a> : A simple tetris clone written in zig programming language. <a>www.youtube.com/watch?v=AiintPutWrE</a></li>
<li><a>DanB91/Zig-Playdate-Template</a> : Starter code for a Playdate program written in Zig.</li>
<li><a>foxnne/aftersun</a> : Top-down 2D RPG.</li>
<li><a>4imothy/termy48</a> : A 2048 game to run in terminal.</li>
<li><a>andrewrk/clashos</a> multiplayer arcade game for bare metal Raspberry Pi 3 B+.</li>
<li><a>MasterQ32/Ziguana-Game-System</a> A retro-style gaming console running on bare x86 metal written in Zig.</li>
<li><a>Srekel/zag</a> : Game dev project written in Zig and C.</li>
<li><a>TM35-Metronome/metronome</a> : A set of tools for modifying and randomizing Pokémon games. <a>tm35-metronome.github.io/</a></li>
<li><a>Akuli/curses-minesweeper</a> : Minesweeper game written in curses with zig.</li>
<li><a>thejoshwolfe/legend-of-swarkland</a> : Turn-based action fantasy puzzle game inspired by NetHack and Crypt of the Necrodancer. <a>wolfesoftware.com/legend-of-swarkland/</a></li>
<li><a>emekoi/ziglet</a> : a small zig game library.</li>
<li><a>kristianhasselknippe/zig-game-engine</a> : Learning zig through game engine</li>
<li><a>TM35-Metronome/tm35-nds</a> : A library for working with Nintendo DS roms.</li>
<li><a>fabioarnold/snake-zig</a> : A simple snake game written in the Zig programming language using OpenGL 2.</li>
<li><a>Stenodyon/blink</a> : A game about building logic with lasers.</li>
<li><a>tiehuis/zstack</a> : Line-race tetris mode in Zig.</li>
<li><a>godot-zig/godot-zig</a> : Zig bindings for Godot 4.</li>
<li><a>Avokadoen/ecez</a> : An archetype based ECS library written in pure zig.</li>
<li><a>nitanmarcel/ScriptHookVZig</a> : Library to write GTA V mods in Zig.</li>
<li><a>PixelGuys/Cubyz</a> : Voxel sandbox game with a large render distance, procedurally generated content and some cool graphical effects.</li>
<li><a>deckarep/dungeon-rush</a> : An SDL snake style game ported to Zig. Originally written in C.</li>
<li><a>ringtailsoftware/zigtris</a> : Zigtris, a terminal tetris</li>
<li><a>ringtailsoftware/zoridor</a> : Zoridor, a Quoridor game for terminal and web with a machine opponent</li>
<li><a>ringtailsoftware/zero-jetpack</a> : Zero-Jetpack a web game about Ziguanas carrying eggs</li>
<li><a>six519/YieArKUNGFUZig</a> : A Yie Ar Kung-Fu clone created in Zig with raylib</li>
</ul>
Emulators
<ul>
<li><a>Ronsor/riscv-zig</a> : A RISC-V emulator written in Zig.</li>
<li><a>leecannon/zriscv</a> : RISC-V emulator in Zig.</li>
<li><a>jtgoen/zig-chip-8</a> : Zig Implementation of a Chip-8 Emulator.</li>
<li><a>paoda/zba</a> : Game Boy Advance Emulator. Yes, I'm awful with project names.</li>
<li><a>fengb/fundude</a> Gameboy emulator: Zig -> wasm.</li>
<li><a>GrooveStomp/chip8-zig</a> : A CHIP-8 emulator written in Zig.</li>
<li><a>isaachier/gbemu</a> : Zig Game Boy emulator.</li>
<li><a>tiehuis/zig-gameboy</a> : A gameboy emulator in zig.</li>
<li><a>emekoi/c8</a> : chip 8 emulator in zig.</li>
<li><a>ringtailsoftware/zig-minirv32</a> : Zig RISC-V emulator with Linux and baremetal examples</li>
</ul>
Encryption
<ul>
<li><a>gernest/base32</a> : base32 encoding/decoding for ziglang</li>
<li><a>deatil/zpem</a> : A pem parse and encode library for Zig.</li>
<li><a>deatil/zig-md2</a> : A MD2 hash function library for Zig.</li>
<li><a>deatil/zig-md4</a> : A MD4 hash function library for Zig.</li>
<li><a>deatil/zig-sm3</a> : A SM3 hash function library for Zig.</li>
</ul>
Network
<ul>
<li><a>Vexu/routez</a> : Http server for Zig. <a>routez.vexu.eu</a></li>
<li><a>Vexu/zuri</a> : URI parser for Zig.</li>
<li><a>karlseguin/http.zig</a> : An HTTP/1.1 server for zig.</li>
<li><a>ducdetronquito/h11</a> : I/O-free HTTP/1.1 implementation inspired by hyper/h11.</li>
<li><a>lun-4/zigdig</a> : naive dns client library in zig.</li>
<li><a>connectFree/ZigZag</a> : Noise Framework implementation in Zig Language for use in EVER/IP and WireGuard.</li>
<li><a>euantorano/ip.zig</a> : A Zig library for working with IP Addresses.</li>
<li><a>lun-4/ziget</a> : simple wget in zig without libc.</li>
<li><a>marler8997/netpunch</a> : Punch Protocol.</li>
<li><a>mstroecker/zig-robotstxt</a> : Lightweight docker image for serving a disallow robots.txt file using the zig programming language.</li>
<li><a>remeh/statsd-zig</a> : Basic DogStatsD UDP/UDS server supporting gauges and counters and sending these metrics to Datadog.</li>
<li><a>gernest/url</a> : This is RFC 3986 compliant url parser for zig.</li>
<li><a>ringtailsoftware/misshod</a> : Experimental minimalist SSH client and server in zig</li>
<li><a>g41797/beanstalkz</a> : Thread-safe client library for <a>beanstalkd</a> - queue for background job processing.</li>
<li><a>vascocosta/zircon</a> : A simple IRC library written in Zig.</li>
<li><a>tardy-org/zzz</a> : A framework for writing performant and reliable networked services in Zig. Supports HTTP and HTTPS.</li>
</ul>
Web Framework
<ul>
<li><a>oven-sh/bun</a> : Incredibly fast JavaScript runtime, bundler, transpiler and package manager – all in one.</li>
<li><a>zigzap/zap</a> : ⚡zap⚡ - blazingly fast web backends in zig.</li>
<li><a>frmdstryr/zhp</a> : frmdstryr/zhp.</li>
<li><a>karlseguin/websocket.zig</a> : A websocket implementation for zig.</li>
<li><a>nikneym/ws</a> : WebSocket library for Zig ⚡</li>
<li><a>kivikakk/htmlentities.zig</a> : HTML entity data for Zig.</li>
<li><a>shritesh/zigfmt-web</a> : zig fmt on the web.</li>
<li><a>leroycep/zig-jwt</a> : JSON Web Tokens for Zig.</li>
<li><a>zon-dev/zinc</a> : Zinc is a web framework written in pure Zig with a focus on high performance, usability, security, and extensibility.</li>
<li><a>cztomsik/tokamak</a> : Web framework that leverages dependency injection for clean, modular application development.</li>
<li><a>jetzig-framework/jetzig</a> : Jetzig is a web framework written in Zig.</li>
<li><a>by-nir/aws-lambda-zig</a> : Super-fast AWS Lambda runtime for Zig.</li>
<li><a>deatil/zig-totp</a> : A TOTP(Time-based One-Time Password) library for zig.</li>
<li><a>deatil/zig-jwt</a> : A JWT(JSON Web Token) library for zig.</li>
<li><a>kristoff-it/zine</a> : Static Site Generator written in Zig.</li>
<li><a>uzyn/passcay</a> : Secure Passkey authentication (WebAuthn) library for Zig.</li>
</ul>
Web3 Framework
<ul>
<li><a>Syndica/sig</a> : a Solana Zig RPC Client implementation.</li>
<li><a>lithdew/rheia</a> : A blockchain written in Zig.</li>
<li><a>zen-eth/multiformats-zig</a> : This is the zig implementation of the multiformats <a>spec</a>.</li>
<li><a>zen-eth/zig-libp2p</a> : Zig implementation of <a>libp2p</a>, a modular network stack that allows you to build your own peer-to-peer applications.</li>
<li><a>EclesioMeloJunior/libp2p-zig</a> : A <a>libp2p</a> written in Zig.</li>
<li><a>Raiden1411/zabi</a> : Zabi aims to add support for interacting with ethereum or any compatible EVM based chain.</li>
<li><a>gballet/zevem/</a> : Ethereum Virtual Machine written in Zig.</li>
<li><a>blockblaz/ssz.zig</a> : A Zig implementation of the <a>SSZ serialization protocol</a>.</li>
<li><a>blockblaz/zeam</a> : A <a>Beam Chain</a> written in Zig.</li>
<li><a>jsign/verkle-crypto</a> : Cryptography for Ethereum Verkle Trees.</li>
<li><a>Ultra-Code/recblock</a> : Blockchain for a record management and money transfer system.</li>
<li><a>keep-starknet-strange/ziggy-starkdust</a> : A Zig implementation of Cairo VM for Cairo, the STARK powered provable language.</li>
<li><a>iskyd/walle</a> : A Bitcoin Wallet written in Zig.</li>
</ul>
WebAssembly
<ul>
<li><a>zig-wasi</a> : Minimal WASI Interpreter.</li>
<li><a>zware</a> : Zig WebAssembly Runtime Engine. zware is a library for executing WebAssembly embedded in <a>Zig</a> programs.</li>
<li><a>wazm</a> : wazm — Web Assembly Zig Machine.</li>
<li><a>zig-wasm-dom</a> : Zig + WebAssembly + JS + DOM.</li>
<li><a>mitchellh/zig-js</a> : Access the JS host environment from Zig compiled to WebAssembly.</li>
<li><a>zigwasm/wasm-zig</a> : Common Wasm runtime binding to C API.</li>
<li><a>zigwasm/wasmtime-zig</a> : Zig embedding of Wasmtime.</li>
<li><a>sleibrock/zigtoys</a> : All about Zig + WASM and seeing what we can do. <a>sleibrock.github.io/zigtoys/</a></li>
<li><a>andrewrk/lua-in-the-browser</a> : using zig to build lua for webassembly.</li>
<li><a>meheleventyone/zig-wasm-test</a> : A minimal Web Assembly example using Zig's build system.</li>
<li><a>thi.ng/wasm-api</a> : Modular, extensible API bridge and infrastructure for hybrid JS & WebAssembly projects.</li>
<li><a>oltdaniel/zig-js-interplay</a> : Seamless integration of Zig and JavaScript in WebAssembly.</li>
<li><a>ringtailsoftware/zig-wasm-audio-framebuffer</a> : Examples of integrating Zig and Wasm (and C) for audio and graphics on the web (including DOOM)</li>
</ul>
Performance Benchmark
<ul>
<li><a>zackradisic/rust-vs-zig</a> : This is an experiment to evaluate Rust vs. Zig by writing a bytecode interpreter with GC in both languages and comparing them.</li>
<li><a>lucascompython/zigXrustXc</a> : Performance of Zig vs Rust vs C.</li>
<li><a>CoalNova/BasicCompare</a> : A basic comparative analysis of C, C++, Rust, and Zig.</li>
<li><a>ziglang/gotta-go-fast</a> : Performance Tracking for Zig.</li>
<li><a>hendriknielaender/zBench</a> : Simple benchmarking library.</li>
<li><a>andrewrk/poop</a> : CLI Performance Observer written in Zig.</li>
</ul>
Graphics Library
<ul>
<li><a>hexops/mach-glfw</a> : Ziggified GLFW bindings with 100% API coverage, zero-fuss installation, cross compilation, and more.</li>
<li><a>ziglibs/zgl</a> : Zig OpenGL Wrapper.</li>
<li><a>MasterQ32/SDL.zig</a> : A shallow wrapper around SDL that provides object API and error handling.</li>
<li><a>andrewrk/SDL</a> : SDL with the build system replaced by Zig. <a>libsdl.org</a></li>
<li><a>MasterQ32/zig-opengl</a> : OpenGL binding generator based on the opengl registry.</li>
<li><a>MasterQ32/zero-graphics</a> : Application framework based on OpenGL ES 2.0. Runs on desktop machines, Android phones and the web.</li>
<li><a>JonSnowbd/ZT</a> : A zig based Imgui Application framework.</li>
<li><a>craftlinks/zig_learn_opengl</a> : Follow the Learn-OpenGL book using Zig.</li>
<li><a>ashpil/moonshine</a> : Moonshine: A general purpose ray traced renderer built with Zig + Vulkan.</li>
<li><a>fabioarnold/nanovg-zig</a> : <a>NanoVG</a> - Zig Version. A small anti-aliased hardware-accelerated vector graphics library. <a>fabioarnold.github.io/nanovg-zig/</a></li>
<li><a>fubark/cosmic</a> : A platform for computing and creating applications. <a>cosmic.ooo</a></li>
<li><a>renerocksai/slides</a> : This project is both a case study and also marks my first steps in the programming language Zig, towards creating a simple but powerful <a>imgui</a> based, OpenGL-rendered slideshow app in Zig.</li>
<li><a>TinyVG/sdk</a> : TinyVG software development kit. <a>tinyvg.tech/</a></li>
<li><a>andrewrk/zig-vulkan-triangle</a> : simple triangle displayed using vulkan, glfw, and zig.</li>
<li><a>cshenton/learnopengl</a> : Zig Learn OpenGL.</li>
<li><a>river</a> : A dynamic tiling Wayland compositor.</li>
<li><a>Nelarius/weekend-raytracer-zig</a> : A Zig implementation of the "Ray Tracing in One Weekend" book.</li>
<li><a>SpexGuy/Zig-Gltf-Display</a> : A program that displays glTF files using Vulkan, written in Zig.</li>
<li><a>tiehuis/zig-raytrace</a> : simple raytracer in zig.</li>
<li><a>tiehuis/zig-sdl2</a> : SDL2 bindings for Zig.</li>
<li><a>winksaville/zig-3d-soft-engine</a> : An attempt to create a 3D engine in software using zig.</li>
</ul>
GUI
<ul>
<li><a>Capy</a> : 💻Build one codebase and get native UI on Windows, Linux and Web. <a>capy-ui.org</a></li>
<li><a>david-vanderson/dvui</a> : Easy to Integrate Immediate Mode GUI for Zig.</li>
<li><a>kassane/qml_zig</a> : QML bindings for the Zig programming language.</li>
<li><a>MoAlyousef/zfltk</a> : Zig bindings for the FLTK gui library.</li>
<li><a>Aransentin/ZWL</a> : A Zig Windowing Library.</li>
<li><a>batiati/IUPforZig</a> : IUP (Portable User Interface Toolkit) bindings for the Zig language.</li>
<li><a>donpdonp/zootdeck</a> : Fediverse GTK Desktop Reader. <a>donpdonp.github.io/zootdeck/</a></li>
<li><a>lupyuen/zig-lvgl-nuttx</a> : Zig LVGL Touchscreen App on Apache NuttX RTOS.</li>
<li><a>lupyuen/pinephone-lvgl-zig</a> : LVGL for PinePhone (and WebAssembly) with Zig and Apache NuttX RTOS. <a>lupyuen.github.io/articles/lvgl2</a></li>
<li><a>ziglibs/positron</a> : A web renderer frontend for zig applications.</li>
<li><a>webui-dev/zig-webui</a> : Use any web browser or WebView as GUI, with your preferred language in the backend and HTML5 in the frontend, all in a lightweight portable lib.</li>
<li><a>star-tek-mb/zig-tray</a> : Create tray applications with zig.</li>
</ul>
Misc
<ul>
<li><a>BraedonWooding/Lazy-Zig</a> : Linq in Zig.</li>
<li><a>DutchGhost/maybeuninit</a> MaybeUninit in Zig.</li>
<li><a>hspak/geteltorito-zig</a> : geteltorito re-write in Zig.</li>
<li><a>NilsIrl/dockerc</a>: container image to single executable compiler.</li>
<li><a>nrdmn/ilo_license_key</a> : iLO license key library.</li>
<li><a>shepherdjerred/macos-cross-compiler</a> : Compile binaries for macOS on Linux.</li>
<li><a>tw4452852/zbpf</a> : Writing eBPF in Zig</li>
<li><a>rockorager/zzdoc</a> : scdoc-compatible manpage compiler for use in build.zig</li>
<li><a>rockorager/libvaxis</a> : Modern TUI library written in zig</li>
<li><a>Avokadoen/ecez_vulkan</a> : A scene editor built on <a>ecez</a> and Vulkan</li>
<li><a>attron/astroz</a> : Spacecraft and Astronomical Toolkit</li>
<li><a>Zigistry/Zigistry</a>: A place where you can find all the libraries that suit your Zig lang needs.</li>
<li><a>freref/fancy-cat</a>: PDF reader inside the terminal.</li>
<li><a>ghostty</a>: Modern terminal emulator written in zig.</li>
<li><a>zerotech-studio/zack</a> : Backtesting engine for trading strategies, written in Zig.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/206480?v=4 | websocket.zig | karlseguin/websocket.zig | 2022-05-28T14:35:01Z | A websocket implementation for zig | master | 5 | 407 | 38 | 407 | https://api.github.com/repos/karlseguin/websocket.zig/tags | MIT | [
"websocket",
"zig",
"zig-library",
"zig-package"
] | 561 | false | 2025-05-19T00:09:50Z | true | true | unknown | github | [] | A zig websocket server.
This project follows Zig master. See available branches if you're targeting a specific version.
Skip to the <a>client section</a>.
If you're upgrading from a previous version, check out the <a>Server Migration</a> and <a>Client Migration</a> wikis.
Server
```zig
const std = @import("std");
const ws = @import("websocket");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
<code>var server = try ws.Server(Handler).init(allocator, .{
.port = 9224,
.address = "127.0.0.1",
.handshake = .{
.timeout = 3,
.max_size = 1024,
// since we aren't using hanshake.headers
// we can set this to 0 to save a few bytes.
.max_headers = 0,
},
});
// Arbitrary (application-specific) data to pass into each handler
// Pass void ({}) into listen if you have none
var app = App{};
// this blocks
try server.listen(&app);
</code>
}
// This is your application-specific wrapper around a websocket connection
const Handler = struct {
app: <em>App,
conn: </em>ws.Conn,
<code>// You must define a public init function which takes
pub fn init(h: *ws.Handshake, conn: *ws.Conn, app: *App) !Handler {
// `h` contains the initial websocket "handshake" request
// It can be used to apply application-specific logic to verify / allow
// the connection (e.g. valid url, query string parameters, or headers)
_ = h; // we're not using this in our simple case
return .{
.app = app,
.conn = conn,
};
}
// You must defined a public clientMessage method
pub fn clientMessage(self: *Handler, data: []const u8) !void {
try self.conn.write(data); // echo the message back
}
</code>
};
// This is application-specific you want passed into your Handler's
// init function.
const App = struct {
// maybe a db pool
// maybe a list of rooms
};
```
Handler
When you create a <code>websocket.Server(Handler)</code>, the specified <code>Handler</code> is your structure which will receive messages. It must have a public <code>init</code> function and <code>clientMessage</code> method. Other methods, such as <code>close</code> can optionally be defined.
init
The <code>init</code> method is called with a <code>*websocket.Handshake</code>, a <code>*websocket.Conn</code> and whatever app-specific value was passed into <code>Server(H).init</code>.
When <code>init</code> is called, the handshake response has not yet been sent to the client (this allows your <code>init</code> method to return an error which will cause websocket.zig to send an error response and close the connection). As such, you should not use/write to the <code>*websocket.Conn</code> at this point. Instead, use the <code>afterInit</code> method, described next.
The websocket specification requires the initial "handshake" to contain certain headers and values. The library validates these headers. However applications may have additional requirements before allowing the connection to be "upgraded" to a websocket connection. For example, a one-time-use token could be required in the querystring. Applications should use the provided <code>websocket.Handshake</code> to apply any application-specific verification and optionally return an error to terminate the connection.
The <code>*websocket.Handshake</code> exposes the following fields:
<ul>
<li><code>url: []const u8</code> - URL of the request in its original casing</li>
<li><code>method: []const u8</code> - Method of the request in its original casing</li>
<li><code>raw_headers: []const u8</code> - The raw "key1: value1\r\nkey2: value2\r\n" headers. Keys are lowercase.</li>
</ul>
If you set the <code>max_headers</code> configuration value to > 0, then you can use <code>req.headers.get("HEADER_NAME")</code> to extract a header value from the given name:
If you set the <code>max_res_headers</code> configuration value to > 0, then you can set headers to be sent in the handshake response:
<code>zig
pub fn init(h: *ws.Handshake, conn: *ws.Conn, app: *App) !Handler {
h.res_headers.add("set-cookie", "delicious")
//...
}</code>
Note that, currently, the total length of the headers added to <code>res_headers</code> should not exceed 1024 characters, else you will exeperience an out of bounds segfault.
```zig
// the last parameter, an <em>App in this case, is an application-specific
// value that you passed into server.listen()
pub fn init(h: </em>websocket.Handshake, conn: websocket.Conn, app: *App) !Handler {
// get returns a ?[]const u8
// the name is lowercase
// the value is in its original case
const token = handshake.headers.get("authorization") orelse {
return error.NotAuthorized;
}
<code>return .{
.app = app,
.conn = conn,
};
</code>
}
```
You can iterate through all the headers:
<code>zig
var it = handshake.headers.iterator();
while (it.next) |kv| {
std.debug.print("{s} = {s}\n", .{kv.key, kv.value});
}</code>
Memory referenced by the <code>websocket.Handshake</code>, including headers from <code>handshake.headers</code> will be freed after the call to <code>init</code> completes. Application that need these values to exist beyond the call to <code>init</code> must make a copy.
afterInit
If your handler defines a <code>afterInit(handler: *Handler) !void</code> method, the method is called after the handshake response has been sent. This is the first time the connection can safely be used.
<code>afterInit</code> supports two overloads:
<code>zig
pub fn afterInit(handler: *Handler) !void
pub fn afterInit(handler: *Handler, ctx: anytype) !void</code>
The <code>ctx</code> is the same <code>ctx</code> passed into <code>init</code>. It is passed here for cases where the value is only needed once when the connection is established.
clientMessage
The <code>clientMessage</code> method is called whenever a text or binary message is received.
The <code>clientMessage</code> method can take one of four shapes. The simplest, shown in the first example, is:
<code>zig
// simple clientMessage
clientMessage(h: *Handler, data: []u8) !void</code>
The Websocket specific has a distinct message type for text and binary. Text messages must be valid UTF-8. Websocket.zig does not do this validation (it's expensive and most apps don't care). However, if you do care about the distinction, your <code>clientMessage</code> can take another parameter:
<code>zig
// clientMessage that accepts a tpe to differentiate between messages
// sent as `text` vs those sent as `binary`. Either way, Websocket.zig
// does not validate that text data is valid UTF-8.
clientMessage(h: *Handler, data: []u8, tpe: ws.MessageTextType) !void</code>
Finally, <code>clientMessage</code> can take an optional <code>std.mem.Allocator</code>. If you need to dynamically allocate memory within <code>clientMessage</code>, consider using this allocator. It is a fast thread-local buffer that fallsback to an arena allocator. Allocations made with this allocator are freed after <code>clientMessage</code> returns:
```zig
// clientMessage that takes an allocator
clientMessage(h: *Handler, allocator: Allocator, data: []u8) !void
// cilentMessage that takes an allocator AND a MessageTextType
clientMessage(h: *Handler, allocator: Allocator, data: []u8, tpe: ws.MessageTextType) !void`
```
If <code>clientMessage</code> returns an error, the connection is closed. You can also call <code>conn.close()</code> within the method.
close
If your handler defines a <code>close(handler: *Handler)</code> method, the method is called whenever the connection is being closed. Guaranteed to be called exactly once, so it is safe to deinitialize the <code>handler</code> at this point. This is called no mater the reason for the closure (on shutdown, if the client closed the connection, if your code close the connection, ...)
The socket may or may not still be alive.
clientClose
If your handler defines a <code>clientClose(handler: *Handler, data: []u8) !void</code> method, the function will be called whenever a <code>close</code> message is received from the client.
You almost certainly <em>do not</em> want to define this method and instead want to use <code>close()</code>. When not defined, websocket.zig follows the websocket specific and replies with its own matching close message.
clientPong
If your handler defines a <code>clientPong(handler: *Handler, data: []u8) !void</code> method, the function will be called whenever a <code>pong</code> message is received from the client. When not defined, no action is taken.
clientPing
If your handler defines a <code>clientPing(handler: *Handler, data: []u8) !void</code> method, the function will be called whenever <code>ping</code> message is received from the client. When not defined, websocket.zig will write a corresponding <code>pong</code> reply.
websocket.Conn
The call to <code>init</code> includes a <code>*websocket.Conn</code>. It is expected that handlers will keep a reference to it. The main purpose of the <code>*Conn</code> is to write data via <code>conn.write([]const u8)</code> and <code>conn.writeBin([]const u8)</code>. The websocket protocol differentiates between a "text" and "binary" message, with the only difference that "text" must be valid UTF-8. This library does not enforce this. Which you use really depends on what your client expects. For browsers, text messages appear as strings, and binary messages appear as a Blob or ArrayBuffer (depending on how the client is configured).
<code>conn.close(.{})</code> can also be called to close the connection. Calling <code>conn.close()</code> <strong>will</strong> result in the handler's <code>close</code> callback being called.
<code>close</code> takes an optional value where you can specify the <code>code</code> and/or <code>reason</code>: <code>conn.close(.{.code = 4000, .reason = "bye bye"})</code> Refer to <a>RFC6455</a> for valid codes. The <code>reason</code> must be <= 123 bytes.
Writer
It's possible to get a <code>std.io.Writer</code> from a <code>*Conn</code>. Because websocket messages are framed, the writter will buffer the message in memory and requires an explicit "flush". Buffering requires an allocator.
<code>zig
// .text or .binary
var wb = conn.writeBuffer(allocator, .text);
defer wb.deinit();
try std.fmt.format(wb.writer(), "it's over {d}!!!", .{9000});
try wb.flush();</code>
Consider using the <code>clientMessage</code> overload which accepts an allocator. Not only is this allocator fast (it's a thread-local buffer than fallsback to an arena), but it also eliminates the need to call <code>deinit</code>:
<code>``zig
pub fn clientMessage(h: *Handler, allocator: Allocator, data: []const u8) !void {
// Use the provided allocator.
// It's faster and doesn't require</code>deinit` to be called
<code>var wb = conn.writeBuffer(allocator, .text);
try std.fmt.format(wb.writer(), "it's over {d}!!!", .{9000});
try wb.flush();
</code>
}
```
Thread Safety
Websocket.zig ensures that only 1 message per connection/handler is processed at a time. Therefore, you will never have concurrent calls to <code>clientMessage</code>, <code>clientPing</code>, <code>clientPong</code> or <code>clientClose</code>. Conversely, concurrent calls to methods of <code>*websocket.Conn</code> are allowed (i.e. <code>conn.write</code> and <code>conn.close</code>).
Config
The 2nd parameter to <code>Server(H).init</code> is a configuration object.
```zig
pub const Config = struct {
port: u16 = 9882,
<code>// Ignored if unix_path is set
address: []const u8 = "127.0.0.1",
// Not valid on windows
unix_path: ?[]const u8 = null,
// In nonblocking mode (Linux/Mac/BSD), sets the number of
// listening threads. Defaults to 1.
// In blocking mode, this is ignored and always set to 1.
worker_count: ?u8 = null,
// The maximum number of connections, per worker.
// default: 16_384
max_conn: ?usize = null,
// The maximium allows message size.
// A websocket message can have up to 14 bytes of overhead/header
// Default: 65_536
max_message_size: ?usize = null,
handshake: Config.Handshake = .{},
thread_pool: ThreadPool = .{},
buffers: Config.Buffers = .{},
// compression is disabled by default
compression: ?Compression = null,
// In blocking mode the thread pool isn't used
pub const ThreadPool = struct {
// Number of threads to process messages.
// These threads are where your `clientXYZ` method will execute.
// Default: 4.
count: ?u16 = null,
// The maximum number of pending requests that the thread pool will accept
// This applies back pressure to worker and ensures that, under load
// pending requests get precedence over processing new requests.
// Default: 500.
backlog: ?u32 = null,
// Size of the static buffer to give each thread. Memory usage will be
// `count * buffer_size`.
// If clientMessage isn't defined with an Allocator, this defaults to 0.
// Else it default to 32768
buffer_size: ?usize = null,
};
const Handshake = struct {
// time, in seconds, to timeout the initial handshake request
timeout: u32 = 10,
// Max size, in bytes, allowed for the initial handshake request.
// If you're expected a large handshake (many headers, large cookies, etc)
// you'll need to set this larger.
// Default: 1024
max_size: ?u16 = null,
// Max number of headers to capture. These become available as
// handshake.headers.get(...).
// Default: 0
max_headers: ?u16 = null,
// Count of handshake objects to keep in a pool. More are created
// as needed.
// Default: 32
count: ?u16 = null,
};
const Buffers = struct {
// The number of "small" buffers to keep pooled.
//
// When `null`, the small buffer pool is disabled and each connection
// gets its own dedicated small buffer (of `size`). This is reasonable
// when you expect most clients to be sending a steady stream of data.
// When set > 0, a pool is created (of `size` buffers) and buffers are
// assigned as messages are received. This is reasonable when you expect
// sporadic and messages from clients.
//
// Default: `null`
small_pool: ?usize = null,
// The size of each "small" buffer. Depending on the value of `pool`
// this is either a per-connection buffer, or the size of pool buffers
// shared between all connections
// Default: 2048
small_size: ?usize = null,
// The number of large buffers to have in the pool.
// Messages larger than `buffers.small_size` but smaller than `max_message_size`
// will attempt to use a large buffer from the pool.
// If the pool is empty, a dynamic buffer is created.
// Default: 8
large_pool: ?u16 = null,
// The size of each large buffer.
// Default: min(2 * buffers.small_size, max_message_size)
large_size: ?usize = null,
};
// Compression is disabled by default, to enable it and accept the default
// values, set it to a defautl struct: .{}
const Compression = struct {
// The mimimum size of data before messages will be compressed
// null = message are never compressed when writing messages to the client
// If you want to enable compression, 512 is a reasonable default
write_threshold: ?usize = null,
// When compression is enable, and write_treshold != null, every connection
// gets an std.ArrayList(u8) to write the compressed message to. When this
// is true, the memory allocated to the ArrayList is kept for subsequent
// messages (i.e. it calls `clearRetainingCapacity`). When false, the memory
// is freed after each message.
// true = more memory, but fewer allocations
retain_write_buffer: bool = true,
// Advanced options that are part of the permessage-deflate specification.
// You can set these to true to try and save a bit of memory. But if you
// want to save memory, don't use compression at all.
client_no_context_takeover: bool = false,
server_no_context_takeover: bool = false,
};
</code>
}
```
Logging
websocket.zig uses Zig's built-in scope logging. You can control the log level by having an <code>std_options</code> decleration in your program's main file:
<code>zig
pub const std_options = std.Options{
.log_scope_levels = &[_]std.log.ScopeLevel{
.{ .scope = .websocket, .level = .err },
}
};</code>
Advanced
Pre-Framed Comptime Message
Websocket message have their own special framing. When you use <code>conn.write</code> or <code>conn.writeBin</code> the data you provide is "framed" into a correct websocket message. Framing is fast and cheap (e.g., it DOES NOT require an O(N) loop through the data). Nonetheless, there may be be cases where pre-framing messages at compile-time is desired. The <code>websocket.frameText</code> and <code>websocket.frameBin</code> can be used for this purpose:
```zig
const UNKNOWN_COMMAND = websocket.frameText("unknown command");
...
pub fn clientMessage(self: *Handler, data: []const u8) !void {
if (std.mem.startsWith(u8, data, "join: ")) {
self.handleJoin(data)
} else if (std.mem.startsWith(u8, data, "leave: ")) {
self.handleLead(data)
} else {
try self.conn.writeFramed(UNKNOWN_COMMAND);
}
}
```
Blocking Mode
kqueue (BSD, MacOS) or epoll (Linux) are used on supported platforms. On all other platforms (most notably Windows), a more naive thread-per-connection with blocking sockets is used.
The comptime-safe, <code>websocket.blockingMode() bool</code> function can be called to determine which mode websocket is running in (when it returns <code>true</code>, then you're running the simpler blocking mode).
Per-Connection Buffers
In non-blocking mode, the <code>buffers.small_pool</code> and <code>buffers.small_size</code> should be set for your particular use case. When <code>buffers.small_pool == null</code>, each connection gets its own buffer of <code>buffers.small_size</code> bytes. This is a good option if you expect most of your clients to be sending a steady stream of data. While it might take more memory (# of connections * buffers.small_size), its faster and minimizes multi-threading overhead.
However, if you expect clients to only send messages sporadically, such as a chat application, enabling the pool can reduce memory usage at the cost of a bit of overhead.
In blocking mode, these settings are ignored and each connection always gets its own buffer (though there is still a shared large buffer pool).
Stopping
<code>server.stop()</code> can be called to stop the webserver. It is safe to call this from a different thread (i.e. a <code>sigaction</code> handler).
Testing
The library comes with some helpers for testing.
```zig
const wt = @import("websocket").testing;
test "handler: echo" {
var wtt = wt.init();
defer wtt.deinit();
<code>// create an instance of your handler (however you want)
// and use &tww.conn as the *ws.Conn field
var handler = Handler{
.conn = &wtt.conn,
};
// execute the methods of your handler
try handler.clientMessage("hello world");
// assert what the client should have received
try wtt.expectMessage(.text, "hello world");
</code>
}
```
Besides <code>expectMessage</code> you can also call <code>expectClose()</code>.
Note that this testing is heavy-handed. It opens up a pair of sockets with one side listening on <code>127.0.0.1</code> and accepting a connection from the other. <code>wtt.conn</code> is the "server" side of the connection, and assertion happens on the client side.
Client
The <code>*websocket.Client</code> can be used in one of two ways. At its simplest, after creating a client and initiating a handshake, you simply use <code>write</code> to send messages and <code>read</code> to receive them. First, we create the client and initiate the handshake:
```zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
// create the client
var client = try websocket.Client.init(allocator, .{
.port = 9224,
.host = "localhost",
});
defer client.deinit();
// send the initial handshake request
const request_path = "/ws";
try client.handshake(request_path, .{
.timeout_ms = 1000,
// Raw headers to send, if any.
// A lot of servers require a Host header.
// Separate multiple headers using \r\n
.headers = "Host: localhost:9224",
});
}
```
We can then use <code>read</code> and <code>write</code>. By default, <code>read</code> blocks until a message is received (or an error occurs). We can make it return <code>null</code> by setting a timeout:
```zig
// optional, read will return null after 1 second
try client.readTimeout(std.time.ms_per_s * 1);
// echo messages back to the server until the connection is closed
while (true) {
// since we didn't set a timeout, client.read() will either
// return a message or an error (i.e. it won't return null)
const message = (try client.read()) orelse {
// no message after our 1 second
std.debug.print(".", .{});
continue;
};
<code>// must be called once you're done processing the request
defer client.done(message);
switch (message.type) {
.text, .binary => {
std.debug.print("received: {s}\n", .{message.data});
try client.write(message.data);
},
.ping => try client.writePong(message.data),
.pong => {},
.close => {
try client.close(.{});
break;
}
}
</code>
}
}
```
Config
When creating a Client, the 2nd parameter is a configuration object:
<ul>
<li><code>port</code> - The port to connect to. Required.</li>
<li><code>host</code> - The host/IP address to connect to. The Host:IP value IS NOT automatically put in the header of the handshake request. Required.</li>
<li><code>max_size</code> - Maximum incoming message size to allow. The library will dynamically allocate up to this much space per request. Default: <code>65536</code>.</li>
<li><code>buffer_size</code> - Size of the static buffer that's available for the client to process incoming messages. While there's other overhead, the minimal memory usage of the server will be <code># of active clients * buffer_size</code>. Default: <code>4096</code>.</li>
<li><code>tls</code> - Whether or not to connect over TLS. Only TLS 1.3 is supported. Default: <code>false</code>.</li>
<li><code>ca_bundle</code> - Provide a custom <code>std.crypto.Certificate.Bundle</code>. Only meaningful when <code>tls = true</code>. Default: <code>null</code>.</li>
</ul>
Setting <code>max_size == buffer_size</code> is valid and will ensure that no dynamic memory allocation occurs once the connection is established.
Zig only supports TLS 1.3, so this library can only connect to hosts using TLS 1.3. If no <code>ca_bundle</code> is provided, the library will create a default bundle per connection.
Handshake
<code>client.handshake()</code> takes two parameters. The first is the request path. The second is handshake configuration value:
<ul>
<li><code>timeout_ms</code> - Timeout, in milliseconds, for the handshake. Default: <code>10_000</code> (10 seconds).</li>
<li><code>headers</code> - Raw headers to include in the handshake. Multiple headers should be separated by by "\r\n". Many servers require a Host header. Example: <code>"Host: server\r\nAuthorization: Something"</code>. Defaul: <code>null</code></li>
</ul>
Custom Wrapper
In more advanced cases, you'll likely want to wrap a <code>*ws.Client</code> in your own type and use a background read loop with "callback" methods. Like in the above example, you'll first want to create a client and initialize a handshake:
```zig
const ws = @import("websocket");
const Handler = struct {
client: ws.Client,
fn init(allocator: std.mem.Allocator) !Handler {
var client = try ws.Client.init(allocator, .{
.port = 9224,
.host = "localhost",
});
defer client.deinit();
<code> // send the initial handshake request
const request_path = "/ws";
try client.handshake(request_path, .{
.timeout_ms = 1000,
.headers = "host: localhost:9224\r\n",
});
return .{
.client = client,
};
</code>
}
```
You can then call <code>client.readLoopInNewThread()</code> to start a background listener. Your handler must define a <code>serverMessage</code> method:
```zig
pub fn startLoop(self: *Handler) !void {
// use readLoop for a blocking version
const thread = try self.client.readLoopInNewThread(self);
thread.detach();
}
pub fn serverMessage(self: *Handler, data: []u8) !void {
// echo back to server
return self.client.write(data);
}
}
```
Websockets have a number of different message types. <code>serverMessage</code> only receives text and binary messages. If you care about the distinction, you can use an overload:
<code>zig
pub fn serverMessage(self: *Handler, data: []u8, tpe: ws.MessageTextType) !void</code>
where <code>tpe</code> will be either <code>.text</code> or <code>.binary</code>. Different callbacks are used for the other message types.
Optional Callbacks
In addition to the required <code>serverMessage</code>, you can define optional callbacks.
```zig
// Guaranteed to be called exactly once when the readLoop exits
pub fn close(self: *Handler) void
// If omitted, websocket.zig will automatically reply with a pong
pub fn serverPing(self: *Handler, data: []u8) !void
// If omitted, websocket.zig will ignore this message
pub fn serverPong(self: *Handler) !void
// If omitted, websocket.zig will automatically reply with a close message
pub fn serverClose(self: *Handler) !void
```
You almost certainly <strong>do not</strong> want to define a <code>serverClose</code> method, but instead what do define a <code>close</code> method. In your <code>close</code> callback, you should call <code>client.close(.{})</code> (and optionally pass a code and reason).
Client
Whether you're calling <code>client.read()</code> explicitly or using <code>client.readLoopInNewThread()</code> (or <code>client.readLoop()</code>), the <code>client</code> API is the same. In both cases, the various <code>write</code> methods, as well as <code>close()</code> are thread-safe.
Writing
It may come as a surprise, but every variation of <code>write</code> expects a <code>[]u8</code>, not a <code>[]const u8</code>. Websocket payloads sent from a client need to be masked, which the websocket.zig library handles. It is obviously more efficient to mutate the given payload versus creating a copy. By taking a <code>[]u8</code>, applications with mutable buffers benefit from avoiding the clone. Applications that have immutable buffers will need to create a mutable clone.
```zig
// write a text message
pub fn write(self: *Client, data: []u8) !void
// write a text message (same as client.write(data))
pub fn writeText(self: *Client, data: []u8) !void
// write a binary message
pub fn writeBin(self: *Client, data: []u8) !void
// write a ping message
pub fn writePing(self: *Client, data: []u8) !void
// write a pong message
// if you don't define a handlePong message, websocket.zig
// will automatically answer any ping with a pong
pub fn writePong(self: *Client, data: []u8) !void
// lower-level, use by all of the above
pub fn writeFrame(self: *Client, op_code: proto.OpCode, data: []u8) !void
```
Reading
As seen above, most applications will either chose to call <code>read()</code> explicitly or use a <code>readLoop</code>. It is *<em>not safe</em> to call <code>read</code> while the read loop is running.
<code>``zig
// Reads 1 message. Returns null on timeout
// Set a timeout using</code>client.readTimeout(ms)`
pub fn read(self: *Client) !?ws.Message
// Starts a readloop in the calling thread.
// <code>@TypeOf(handler)</code> must define the <code>serverMessage</code> callback
// (and may define other optional callbacks)
pub fn readLoop(self: *Client, handler: anytype) !void
// Same as <code>readLoop</code> but starts the readLoop in a new thread
pub fn readLoopInNewThread(self: *Client, h: anytype) !std.Thread
```
Closing
Use <code>try client.close(.{.code = 4000, .reason = "bye"})</code> to both send a close frame and close the connection. Noop if the connection is already known to be close. Thread safe.
Both <code>code</code> and <code>reason</code> are optional. Refer to <a>RFC6455</a> for valid codes. The <code>reason</code> must be <= 123 bytes.
Performance Optimization 1 - CA Bundle
For a high number of connections, it might be beneficial to manage our own CA bundle:
<code>zig
// some global data
var ca_bundle = std.crypto.Certificate.Bundle{}
try ca_bundle.rescan(allocator);
defer ca_bundle.deinit(allocator);</code>
And then assign this <code>ca_bundle</code> into the the configuration's <code>ca_bundle</code> field. This way the library does not have to create and scan the installed CA certificates for each client connection.
Performance Optimization 2 - Buffer Provider
For a high nummber of connections a large buffer pool can be created and provided to each client:
```zig
// Create a buffer pool of 10 buffers, each being 32K
const buffer_provider = try websocket.bufferProvider(allocator, 10, 32768);
defer buffer_provider.deinit();
// create your client(s) using the above created buffer_provider
var client = try websocket.connect(allocator, "localhost", 9001, .{
...
.buffer_provider = buffer_provider,
});
```
This allows each client to have a reasonable <code>buffer_size</code> that can accomodate most messages, while having an efficient fallback for the occasional large message. When <code>max_size</code> is greater than the large buffer pool size (32K in the above example) or when all pooled buffers are used, a dynamic buffer is created. | [] |
https://avatars.githubusercontent.com/u/7967463?v=4 | ziglua | natecraddock/ziglua | 2022-06-02T04:37:17Z | Zig bindings for the Lua C API | main | 24 | 360 | 52 | 360 | https://api.github.com/repos/natecraddock/ziglua/tags | MIT | [
"binding",
"library",
"lua",
"lua-bindings",
"package",
"zig",
"zig-package"
] | 1,517 | false | 2025-05-20T09:08:27Z | true | true | unknown | github | [
{
"commit": null,
"name": "lua51",
"tar_url": null,
"type": "remote",
"url": "https://www.lua.org/ftp/lua-5.1.5.tar.gz"
},
{
"commit": null,
"name": "lua52",
"tar_url": null,
"type": "remote",
"url": "https://www.lua.org/ftp/lua-5.2.4.tar.gz"
},
{
"commit": null,
... | Ziglua
<a></a>
<a></a>
Zig bindings for the <a>Lua C API</a>. Ziglua currently supports the latest releases of Lua 5.1, 5.2, 5.3, 5.4, and <a>Luau</a>.
Ziglua can be used in two ways, either
* <strong>embedded</strong> to statically embed the Lua VM in a Zig program,
* or as a shared <strong>module</strong> to create Lua libraries that can be loaded at runtime in other Lua-based software.
In both cases, Ziglua will compile Lua from source and link against your Zig code making it easy to create software that integrates with Lua without requiring any system Lua libraries.
Ziglua <code>main</code> is kept up to date with Zig <code>master</code>. See the <a><code>zig-0.13.0</code></a> branch for Zig 0.13.0 support.
Documentation
Docs are a work in progress and are automatically generated. Most functions and public declarations are documented:
* <a>Ziglua Docs</a>
See <a>docs.md</a> for more general information on Ziglua and how it differs from the C API.
Example code is included in the <a>examples</a> directory.
* Run an example with <code>zig build run-example-<name></code>
* Install an example with <code>zig build install-example-<name></code>
Why use Ziglua?
In a nutshell, Ziglua is a simple wrapper around the C API you would get by using Zig's <code>@cImport()</code>. Ziglua aims to mirror the <a>Lua C API</a> as closely as possible, while improving ergonomics using Zig's features. For example:
<ul>
<li>Zig error unions to require failure state handling</li>
<li>Null-terminated slices instead of C strings</li>
<li>Type-checked enums for parameters and return values</li>
<li>Compiler-enforced checking of optional pointers</li>
<li>Better types in many cases (e.g. <code>bool</code> instead of <code>int</code>)</li>
<li>Comptime convenience functions to make binding creation easier</li>
</ul>
Nearly every function in the C API is exposed in Ziglua. Additional convenience functions like <code>toAny</code> and <code>pushAny</code> use comptime reflection to make the API easier to use.
Integrating Ziglua in your project
Run <code>zig fetch --save git+https://github.com/natecraddock/ziglua</code> to add the most recent commit of ziglua to your <code>build.zig.zon</code> file.
Add a <code>#<tag></code> to the url to use a specific tagged release or commit like <code>zig fetch --save git+https://github.com/natecraddock/ziglua#0.3.0</code>
Then in your <code>build.zig</code> file you can use the dependency.
```zig
pub fn build(b: *std.Build) void {
// ... snip ...
<code>const lua_dep = b.dependency("zlua", .{
.target = target,
.optimize = optimize,
});
// ... snip ...
// add the zlua module and lua artifact
exe.root_module.addImport("zlua", lua_dep.module("zlua"));
</code>
}
```
This will compile the Lua C sources and link with your project.
There are currently three additional options that can be passed to <code>b.dependency()</code>:
<ul>
<li><code>.lang</code>: Set the Lua language to build and embed. Defaults to <code>.lua54</code>. Possible values are <code>.lua51</code>, <code>.lua52</code>, <code>.lua53</code>, <code>.lua54</code>, and <code>luau</code>.</li>
<li><code>.shared</code>: Defaults to <code>false</code> for embedding in a Zig program. Set to <code>true</code> to dynamically link the Lua source code (useful for creating shared modules).</li>
<li><code>luau_use_4_vector</code>: defaults to false. Set to true to use 4-vectors instead of the default 3-vector in Luau.</li>
</ul>
For example, here is a <code>b.dependency()</code> call that and links against a shared Lua 5.2 library:
```zig
const zlua = b.dependency("zlua", .{
.target = target,
.optimize = optimize,
.lang = .lua52,
.shared = true,
});
``````
The <code>zlua</code> module will now be available in your code. Here is a simple example that pushes and inspects an integer on the Lua stack:
```zig
const std = @import("std");
const zlua = @import("zlua");
const Lua = zlua.Lua;
pub fn main() anyerror!void {
// Create an allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
<code>// Initialize the Lua vm
var lua = try Lua.init(allocator);
defer lua.deinit();
// Add an integer to the Lua stack and retrieve it
lua.pushInteger(42);
std.debug.print("{}\n", .{try lua.toInteger(1)});
</code>
}
```
Contributing
Please make suggestions, report bugs, and create pull requests. Anyone is welcome to contribute!
I only use a subset of the Lua API through Ziglua, so if there are parts that aren't easy to use or understand, please fix it yourself or let me know!
Thank you to the <a>Lua</a> team for creating such a great language! | [
"https://github.com/JacobCrabill/zigdown"
] |
https://avatars.githubusercontent.com/u/7078566?v=4 | zig-cli | sam701/zig-cli | 2022-03-09T17:55:00Z | A simple package for building command line apps in Zig | main | 7 | 272 | 27 | 272 | https://api.github.com/repos/sam701/zig-cli/tags | MIT | [
"argument-parser",
"cli",
"command-line",
"zig-package",
"ziglang"
] | 165 | false | 2025-05-14T09:11:31Z | true | true | unknown | github | [] | ZIG-CLI
A simple package for building command line apps in Zig.
Inspired by <a>urfave/cli</a> Go package.
Features
<ul>
<li>command line arguments are parsed into zig values</li>
<li>long and short options: <code>--option1</code>, <code>-o</code></li>
<li>optional <code>=</code> sign: <code>--address=127.0.0.1</code> equals <code>--address 127.0.0.1</code></li>
<li>concatenated short options: <code>-a -b -c</code> equals <code>-abc</code></li>
<li>subcommands: <code>command1 -option1 subcommand2 -option2</code></li>
<li>multiple option values: <code>--opt val1 --opt val2 --opt val3</code></li>
<li>enums as option values: <code>--opt EnumValue1</code></li>
<li>options value can be read from environment variables with a configured prefix</li>
<li>positional arguments can be mixed with options: <code>--opt1 val1 arg1 -v</code></li>
<li>stops option parsing after <code>--</code>: <code>command -- --abc</code> will consider <code>--abc</code> as a positional argument to <code>command</code>.</li>
<li>errors on missing required options: <code>ERROR: option 'ip' is required</code></li>
<li>prints help with <code>--help</code></li>
<li>colored help messages when TTY is attached</li>
</ul>
Usage
```zig
const std = @import("std");
const cli = @import("zig-cli");
// Define a configuration structure with default values.
var config = struct {
host: []const u8 = "localhost",
port: u16 = undefined,
}{};
pub fn main() !void {
var r = try cli.AppRunner.init(std.heap.page_allocator);
<code>// Create an App with a command named "short" that takes host and port options.
const app = cli.App{
.command = cli.Command{
.name = "short",
.options = try r.allocOptions(&.{
// Define an Option for the "host" command-line argument.
.{
.long_name = "host",
.help = "host to listen on",
.value_ref = r.mkRef(&config.host),
},
// Define an Option for the "port" command-line argument.
.{
.long_name = "port",
.help = "port to bind to",
.required = true,
.value_ref = r.mkRef(&config.port),
},
}),
.target = cli.CommandTarget{
.action = cli.CommandAction{ .exec = run_server },
},
},
};
return r.run(&app);
</code>
}
// Action function to execute when the "short" command is invoked.
fn run_server() !void {
// Log a debug message indicating the server is listening on the specified host and port.
std.log.debug("server is listening on {s}:{d}", .{ config.host, config.port });
}
```
Using with the Zig package manager
Add <code>zig-cli</code> to your <code>build.zig.zon</code>
<code>zig fetch --save git+https://github.com/sam701/zig-cli</code>
See the <a><code>standalone</code></a> example in the <code>examples</code> folder.
Printing help
See <a><code>simple.zig</code></a>
```
$ ./zig-out/bin/simple sub1 --help
USAGE:
abc sub1 [OPTIONS]
another awesome command
this is my awesome multiline description.
This is already line 2.
And this is line 3.
COMMANDS:
sub2 sub2 help
OPTIONS:
-i, --ip this is the IP address
--int this is an int
--bool this is a bool
--float this is a float
-h, --help Prints help information
```
License
MIT | [
"https://github.com/GROOOOAAAARK/zig-commit-emojis",
"https://github.com/keep-starknet-strange/ziggy-starkdust",
"https://github.com/rupurt/zodbc",
"https://github.com/soheil-01/bittorrent-client",
"https://github.com/soheil-01/zpe"
] |
https://avatars.githubusercontent.com/u/146390816?v=4 | ffmpeg | allyourcodebase/ffmpeg | 2023-01-08T01:31:26Z | FFmpeg Zig package | main | 7 | 217 | 35 | 217 | https://api.github.com/repos/allyourcodebase/ffmpeg/tags | NOASSERTION | [
"ffmpeg",
"zig",
"zig-package"
] | 169,081 | false | 2025-05-17T16:27:17Z | true | true | 0.14.0 | github | [
{
"commit": "6c72830882690c1eb2567a537525c3f432c1da50.tar.gz",
"name": "libz",
"tar_url": "https://github.com/allyourcodebase/zlib/archive/6c72830882690c1eb2567a537525c3f432c1da50.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/allyourcodebase/zlib"
},
{
"commit": "7d862fe61... | FFmpeg Packaged for Zig
This is a fork of <a>ffmpeg</a>, packaged for Zig. Unnecessary
files have been deleted, and the build system has been replaced with
<code>build.zig</code>.
There are no system dependencies; the only thing required to build this package
is <a>Zig</a>.
Zig API bindings are also provided via the "av" module. See <code>doc/examples</code> for
API usage examples.
Differences from Upstream
<ul>
<li>Only a single static library is produced. There is no option to create a
dynamic library.</li>
<li>The ffmpeg command line tool is not provided. Perhaps this could be added if
desired.</li>
<li>Documentation, tests, and tools are not provided.</li>
<li>This package enables everything supported by the target; it does not expose
configuration options to choose the set of supported codecs and formats.</li>
<li>The set of external library integrations is fixed.</li>
</ul>
External Libraries Included
<ul>
<li>[x] libmp3lame</li>
<li>[x] libvorbis</li>
<li>[x] libogg</li>
</ul>
More can be added as desired.
Update Process
These are the instructions to update this package when a new FFmpeg version is
released upstream.
<ol>
<li>Merge the new tag into main and resolve all conflicts by replacing the
conflicting files with the files from upstream.</li>
<li><code>find libavcodec/ libavdevice/ libavfilter/ libavformat libavutil/ libswscale/ libswresample/ -type f -name "*.asm" -o -name "*.c" -o -name "*.S"</code></li>
<li>Edit to omit files ending in <code>_template.c</code> or <code>_tablegen.c</code></li>
<li>Sort the list</li>
<li>Update the <code>all_sources</code> list in <code>build.zig</code>.</li>
<li>Inspect the git diff to keep some of the source files commented out like
they were before. Some handy filtering rules apply:</li>
<li><code>/L</code> prefix means Linux-only</li>
<li><code>/W</code> prefix means Windows-only</li>
<li>Run <code>./configure --prefix=$HOME/local/ffmpeg --disable-doc --disable-htmlpages --disable-manpages --disable-podpages --disable-txtpages --disable-programs --enable-libmp3lame --enable-libvorbis --disable-shared --enable-static</code>
against upstream and diff the generated <code>config.h</code> file to the one generated
by this build script. Apply appropriate changes to <code>build.zig</code>.</li>
<li>Update these files which are generated by the upstream configure script:</li>
<li><code>config_components.h</code></li>
<li><code>libavfilter/filter_list.c</code></li>
<li><code>libavcodec/codec_list.c</code></li>
<li><code>libavcodec/parser_list.c</code></li>
<li><code>libavcodec/bsf_list.c</code></li>
<li><code>libavformat/demuxer_list.c</code></li>
<li><code>libavformat/muxer_list.c</code></li>
<li><code>libavdevice/indev_list.c</code></li>
<li><code>libavdevice/outdev_list.c</code></li>
<li><code>libavformat/protocol_list.c</code></li>
<li>Update the <code>headers</code> list in <code>build.zig</code> based on what files are present in
<code>$HOME/local/ffmpeg/include</code>.</li>
</ol> | [
"https://github.com/neurocyte/notcurses-zig"
] |
https://avatars.githubusercontent.com/u/473672?v=4 | nanovg-zig | fabioarnold/nanovg-zig | 2022-04-03T20:47:06Z | A small anti-aliased hardware-accelerated vector graphics library | main | 1 | 209 | 23 | 209 | https://api.github.com/repos/fabioarnold/nanovg-zig/tags | Zlib | [
"2d",
"gamedev",
"graphics",
"opengl",
"vector",
"vector-graphics",
"zig",
"zig-package"
] | 2,242 | false | 2025-05-18T07:36:09Z | true | true | 0.11.0 | github | [] | NanoVG - Zig Version
This is a rewrite of the original <a>NanoVG library</a> using the <a>Zig programming language</a>.
NanoVG is a small anti-aliased hardware-accelerated vector graphics library. It has a lean API modeled after the HTML5 canvas API. It is aimed to be a practical and fun toolset for building scalable user interfaces or any other real time visualizations.
Screenshot
Examples
There's a WebAssembly example using WebGL which you can immediately try here: https://fabioarnold.github.io/nanovg-zig. The source for this example can be found in <a>example_wasm.zig</a> and can be built by running <code>zig build -Dtarget=wasm32-freestanding</code>.
A native cross-platform example using <a>GLFW</a> can be found in <a>example_glfw.zig</a> and can be built and run with <code>zig build run</code>. It requires GLFW to be installed. On Windows <a>vcpkg</a> is an additional requirement.
For an example on how to use nanovg-zig in your project's <code>build.zig</code> you can take a look at https://github.com/fabioarnold/MiniPixel/blob/main/build.zig.
Features
<ul>
<li>Basic shapes: rect, rounded rect, ellipse, arc</li>
<li>Arbitrary paths of bezier curves with holes</li>
<li>Arbitrary stack-based 2D transforms</li>
<li>Strokes with different types of caps and joins</li>
<li>Fills with gradient support</li>
<li>Types of gradients: linear, box (useful for shadows), radial</li>
<li>Text with automatic linebreaks and blurring</li>
<li>Images as pattern for fills and strokes</li>
</ul>
Features exclusive to the Zig version
<ul>
<li>Clip paths</li>
<li>Image blurring</li>
</ul>
Usage
The NanoVG API is modeled loosely on the HTML5 canvas API. If you know canvas, you're up to speed with NanoVG in no time.
Creating a drawing context
The drawing context is created using a backend-specific initialization function. If you're using the OpenGL backend the context is created as follows:
<code>zig
const nvg = @import("nanovg");
...
var vg = try nvg.gl.init(allocator, .{
.debug = true,
});
defer vg.deinit();</code>
The second parameter defines options for creating the renderer.
<ul>
<li><code>antialias</code> means that the renderer adjusts the geometry to include anti-aliasing. If you're using MSAA, you can omit this option to be default initialized as false.</li>
<li><code>stencil_strokes</code> means that the render uses better quality rendering for (overlapping) strokes. The quality is mostly visible on wider strokes. If you want speed, you can omit this option to be default initialized as false.</li>
</ul>
Currently, there is an OpenGL backend for NanoVG: <a>nanovg_gl.zig</a> for OpenGL 2.0 and WebGL. WebGL is automatically chosen when targeting WebAssembly. There's an interface called <code>Params</code> defined in <a>internal.zig</a>, which can be implemented by additional backends.
<em>NOTE:</em> The render target you're rendering to must have a stencil buffer.
Drawing shapes with NanoVG
Drawing a simple shape using NanoVG consists of four steps:
1) begin a new shape,
2) define the path to draw,
3) set fill or stroke,
4) and finally fill or stroke the path.
<code>zig
vg.beginPath();
vg.rect(100,100, 120,30);
vg.fillColor(nvg.rgba(255,192,0,255));
vg.fill();</code>
Calling <code>beginPath()</code> will clear any existing paths and start drawing from a blank slate. There are a number of functions to define the path to draw, such as rectangle, rounded rectangle and ellipse, or you can use the common moveTo, lineTo, bezierTo and arcTo API to compose a path step-by-step.
Understanding Composite Paths
Because of the way the rendering backend is built in NanoVG, drawing a composite path - that is a path consisting of multiple paths defining holes and fills - is a bit more involved. NanoVG uses the even-odd filling rule and by default the paths are wound in counterclockwise order. Keep that in mind when drawing using the low-level drawing API. In order to wind one of the predefined shapes as a hole, you should call <code>pathWinding(nvg.Winding.solidity(.hole))</code>, or <code>pathWinding(.cw)</code> <strong><em>after</em></strong> defining the path.
<code>zig
vg.beginPath();
vg.rect(100,100, 120,30);
vg.circle(120,120, 5);
vg.pathWinding(.cw); // Mark circle as a hole.
vg.fillColor(nvg.rgba(255,192,0,255));
vg.fill();</code>
Building a Program with nanovg-zig
Here's how to integrate <code>nanovg-zig</code> into your Zig project:
<ol>
<li>
<strong>Add the library as a dependency:</strong>
Run the following command in your project directory to fetch and save <code>nanovg-zig</code> as a dependency:
<code>bash
zig fetch --save git+https://github.com/fabioarnold/nanovg-zig.git</code>
</li>
<li>
<strong>Import the library in your <code>build.zig</code> file:</strong>
Add the following code snippet to your <code>build.zig</code> file. This creates a dependency on <code>nanovg-zig</code> and imports the <code>nanovg</code> module into your executable:
<code>zig
const nanovg_zig = b.dependency("nanovg-zig", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("nanovg", nanovg_zig.module("nanovg"));</code>
Replace <code>exe</code> with your target executable.
</li>
<li>
<strong>Link against OpenGL:</strong>
<code>nanovg-zig</code> relies on OpenGL for rendering. <em>You must manually link against OpenGL in your <code>build.zig</code> file.</em> The <a>build.zig</a> file in the repository demonstrates how to do this.
</li>
<li>
<strong>Use NanoVG in your code:</strong>
You can now import and use the <code>nanovg</code> module in your Zig source files:
<code>zig
const nvg = @import("nanovg");</code>
Refer to the "Creating a drawing context" and "Drawing shapes with NanoVG" sections above for examples of how to use the NanoVG API.
</li>
</ol>
API Reference
See <a>nanovg.zig</a> for an API reference.
Projects using nanovg-zig
<ul>
<li><a>MiniPixel by fabioarnold</a></li>
<li><a>Snake by fabioarnold</a></li>
</ul>
License
The original library and this rewrite are licensed under the <a>zlib license</a>
Fonts used in the examples:
- Roboto licensed under <a>Apache license</a>
- Entypo licensed under CC BY-SA 4.0.
- Noto Emoji licensed under <a>SIL Open Font License, Version 1.1</a>
Links
Uses <a>stb_truetype</a> for font rendering. Uses <a>stb_image</a> for image loading. | [] |
https://avatars.githubusercontent.com/u/121257957?v=4 | mach-gpu-dawn | hexops-graveyard/mach-gpu-dawn | 2022-02-11T21:40:11Z | Google's Dawn WebGPU implementation, cross-compiled with Zig into a single static library | main | 0 | 151 | 14 | 151 | https://api.github.com/repos/hexops-graveyard/mach-gpu-dawn/tags | NOASSERTION | [
"zig-package"
] | 481 | false | 2025-04-24T16:02:28Z | true | true | unknown | github | [
{
"commit": null,
"name": "xcode_frameworks",
"tar_url": null,
"type": "remote",
"url": "https://pkg.machengine.org/xcode-frameworks/122b43323db27b2082a2d44ed2121de21c9ccf75.tar.gz"
},
{
"commit": null,
"name": "direct3d_headers",
"tar_url": null,
"type": "remote",
"url":... | Deprecated
This project has been deprecated and is no longer maintained.
Rationale: https://github.com/hexops/mach/issues/1166 | [] |
https://avatars.githubusercontent.com/u/65570835?v=4 | s2s | ziglibs/s2s | 2022-02-21T08:07:25Z | A zig binary serialization format. | master | 3 | 142 | 23 | 142 | https://api.github.com/repos/ziglibs/s2s/tags | MIT | [
"binary-data",
"serialization",
"serialization-library",
"zig",
"zig-package"
] | 3,787 | false | 2025-04-06T18:40:41Z | true | true | unknown | github | [] | struct to stream | stream to struct
A Zig binary serialization format and library.
Features
<ul>
<li>Convert (nearly) any Zig runtime datatype to binary data and back.</li>
<li>Computes a stream signature that prevents deserialization of invalid data.</li>
<li>No support for graph like structures. Everything is considered to be tree data.</li>
</ul>
<strong>Unsupported types</strong>:
<ul>
<li>All <code>comptime</code> only types</li>
<li>Unbound pointers (c pointers, pointer to many)</li>
<li><code>volatile</code> pointers</li>
<li>Untagged or <code>external</code> unions</li>
<li>Opaque types</li>
<li>Function pointers</li>
<li>Frames</li>
</ul>
API
The library itself provides only some APIs, as most of the serialization process is not configurable.
<code>``zig
/// Serializes the given</code>value: T<code>into the</code>stream<code>.
/// -</code>stream<code>is a instance of</code>std.io.Writer<code>/// -</code>T<code>is the type to serialize
/// -</code>value` is the instance to serialize.
fn serialize(stream: anytype, comptime T: type, value: T) StreamError!void;
/// Deserializes a value of type <code>T</code> from the <code>stream</code>.
/// - <code>stream</code> is a instance of <code>std.io.Reader</code>
/// - <code>T</code> is the type to deserialize
fn deserialize(stream: anytype, comptime T: type) (StreamError || error{UnexpectedData,EndOfStream})!T;
/// Deserializes a value of type <code>T</code> from the <code>stream</code>.
/// - <code>stream</code> is a instance of <code>std.io.Reader</code>
/// - <code>T</code> is the type to deserialize
/// - <code>allocator</code> is an allocator require to allocate slices and pointers.
/// Result must be freed by using <code>free()</code>.
fn deserializeAlloc(stream: anytype, comptime T: type, allocator: std.mem.Allocator) (StreamError || error{ UnexpectedData, OutOfMemory,EndOfStream })!T;
/// Releases all memory allocated by <code>deserializeAlloc</code>.
/// - <code>allocator</code> is the allocator passed to <code>deserializeAlloc</code>.
/// - <code>T</code> is the type that was passed to <code>deserializeAlloc</code>.
/// - <code>value</code> is the value that was returned by <code>deserializeAlloc</code>.
fn free(allocator: std.mem.Allocator, comptime T: type, value: T) void;
```
Usage and Development
Adding the library
Just add the <code>s2s.zig</code> as a package to your Zig project. It has no external dependencies.
Running the test suite
<code>sh-session
[user@host s2s]$ zig test s2s.zig
All 3 tests passed.
[user@host s2s]$</code>
Project Status
Most of the serialization/deserialization is implemented for the <em>trivial</em> case.
Pointers/slices with non-standard alignment aren't properly supported yet. | [] |
https://avatars.githubusercontent.com/u/5728002?v=4 | mustache-zig | batiati/mustache-zig | 2022-02-15T12:52:35Z | Logic-less templates for Zig | master | 11 | 140 | 24 | 140 | https://api.github.com/repos/batiati/mustache-zig/tags | MIT | [
"mustache",
"mustache-templating",
"zig-package",
"ziglang"
] | 1,129 | false | 2025-05-16T14:53:19Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/54114156?v=4 | zigglgen | castholm/zigglgen | 2023-01-15T23:09:41Z | Zig OpenGL binding generator | master | 0 | 111 | 14 | 111 | https://api.github.com/repos/castholm/zigglgen/tags | NOASSERTION | [
"bindings",
"opengl",
"zig",
"zig-package"
] | 1,560 | false | 2025-05-16T10:51:07Z | true | true | 0.14.0 | github | [] |
zigglgen
The only Zig OpenGL binding generator you need.
Installation and usage
zigglgen currently supports the following versions of the Zig compiler:
<ul>
<li><code>0.14.0</code></li>
<li><code>0.15.0-dev</code> (master)</li>
</ul>
Older or more recent versions of the compiler are not guaranteed to be compatible.
1. Run <code>zig fetch</code> to add the zigglgen package to your <code>build.zig.zon</code> manifest:
<code>sh
zig fetch --save git+https://github.com/castholm/zigglgen.git</code>
2. Generate a set of OpenGL bindings in your <code>build.zig</code> build script:
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe_mod = b.createModule(...);
<code>// Choose the OpenGL API, version, profile and extensions you want to generate bindings for.
const gl_bindings = @import("zigglgen").generateBindingsModule(b, .{
.api = .gl,
.version = .@"4.1",
.profile = .core,
.extensions = &.{ .ARB_clip_control, .NV_scissor_exclusive },
});
// Import the generated module.
exe_mod.addImport("gl", gl_bindings);
</code>
}
```
3. Initialize OpenGL and start issuing commands:
```zig
const windowing = @import(...);
const gl = @import("gl");
// Procedure table that will hold OpenGL functions loaded at runtime.
var procs: gl.ProcTable = undefined;
pub fn main() !void {
// Create an OpenGL context using a windowing system of your choice.
const context = windowing.createContext(...);
defer context.destroy();
<code>// Make the OpenGL context current on the calling thread.
windowing.makeContextCurrent(context);
defer windowing.makeContextCurrent(null);
// Initialize the procedure table.
if (!procs.init(windowing.getProcAddress)) return error.InitFailed;
// Make the procedure table current on the calling thread.
gl.makeProcTableCurrent(&procs);
defer gl.makeProcTableCurrent(null);
// Issue OpenGL commands to your heart's content!
const alpha: gl.float = 1;
gl.ClearColor(1, 1, 1, alpha);
gl.Clear(gl.COLOR_BUFFER_BIT);
</code>
}
```
See <a>castholm/zig-examples</a> for example projects.
API
See <a>this gist</a> for a preview of what the generated
code might look like.
OpenGL symbols
zigglgen generates declarations for OpenGL functions, constants, types and extensions using the original names as
defined in the various OpenGL specifications (as opposed to the prefixed names used in C).
| | C | Zig |
|-----------|:----------------------|:-------------------|
| Command | <code>glClearColor</code> | <code>ClearColor</code> |
| Constant | <code>GL_TRIANGLES</code> | <code>TRIANGLES</code> |
| Type | <code>GLfloat</code> | <code>float</code> |
| Extension | <code>GL_ARB_clip_control</code> | <code>ARB_clip_control</code> |
<code>info</code>
<code>zig
pub const info = struct {};</code>
Contains information about the generated set of OpenGL bindings, such as the OpenGL API, version and profile the
bindings were generated for.
<code>ProcTable</code>
<code>zig
pub const ProcTable = struct {};</code>
Holds pointers to OpenGL functions loaded at runtime.
This struct is very large, so you should avoid storing instances of it on the stack. Use global variables or allocate
them on the heap instead.
<code>ProcTable.init</code>
<code>zig
pub fn init(procs: *ProcTable, loader: anytype) bool {}</code>
Initializes the specified procedure table and returns <code>true</code> if successful, <code>false</code> otherwise.
A procedure table must be successfully initialized before passing it to <code>makeProcTableCurrent</code> or accessing any of
its fields.
<code>loader</code> is duck-typed. Given the prefixed name of an OpenGL command (e.g. <code>"glClear"</code>), it should return a pointer to
the corresponding function. It should be able to be used in one of the following two ways:
<ul>
<li><code>@as(?PROC, loader(@as([*:0]const u8, prefixed_name)))</code></li>
<li><code>@as(?PROC, loader.getProcAddress(@as([*:0]const u8, prefixed_name)))</code></li>
</ul>
If your windowing system has a "get procedure address" function, it is usually enough to simply pass that function as
the <code>loader</code> argument.
No references to <code>loader</code> are retained after this function returns.
There is no corresponding <code>deinit</code> function.
<code>makeProcTableCurrent</code>
<code>zig
pub fn makeProcTableCurrent(procs: ?*const ProcTable) void {}</code>
Makes the specified procedure table current on the calling thread.
A valid procedure table must be made current on a thread before issuing any OpenGL commands from that same thread.
<code>getCurrentProcTable</code>
<code>zig
pub fn getCurrentProcTable() ?*const ProcTable {}</code>
Returns the procedure table that is current on the calling thread.
<code>extensionSupported</code>
(Only generated if at least one extension is specified.)
<code>zig
pub fn extensionSupported(comptime extension: Extension) bool {}</code>
Returns <code>true</code> if the specified OpenGL extension is supported by the procedure table that is current on the calling
thread, <code>false</code> otherwise.
FAQ
Which OpenGL APIs are supported?
Any APIs, versions, profiles and extensions included in Khronos's <a>OpenGL XML API
Registry</a> are supported. These include:
<ul>
<li>OpenGL 1.0 through 3.1</li>
<li>OpenGL 3.2 through 4.6 (Compatibility/Core profile)</li>
<li>OpenGL ES 1.1 (Common/Common-Lite profile)</li>
<li>OpenGL ES 2.0 through 3.2</li>
<li>OpenGL SC 2.0</li>
</ul>
The <a><code>updateApiRegistry.ps1</code></a> PowerShell script is used to fetch the API registry and convert it
to a set of Zig source files that are committed to revision control and used by zigglgen.
Why is a thread-local procedure table required?
Per the OpenGL spec, OpenGL function pointers loaded when one OpenGL context is current are not guaranteed to remain
valid when a different context becomes current. This means that it would be incorrect to load a single set of function
pointers to global memory just once at application startup and then have them be shared by all current and future
OpenGL contexts.
In order to support portable multi-threaded multi-context OpenGL applications, it must be possible to load multiple sets
of function pointers. Because OpenGL contexts are already thread-local, it makes a lot of sense to handle function
pointers in a similar manner.
Why aren't OpenGL constants represented as Zig enums?
The short answer is that it's simply not possible to represent groups of OpenGL constants as Zig enums in a
satisfying manner:
<ul>
<li>The API registry currently specifies some of these groups, but far from all of them, and the groups are not guaranteed
to be complete. Groups can be extended by extensions, so Zig enums would need to be defined as non-exhaustive, and
using constants not specified as part of a group would require casting.</li>
<li>Some commands like <em>GetIntegerv</em> that can return constants will return them as plain integers. Comparing the returned
values against Zig enum fields would require casting.</li>
<li>Some constants in the same group are aliases for the same value, which makes them impossible to represent as
Zig enums.</li>
</ul>
Why did calling a supported extension function result in a null pointer dereference?
Certain OpenGL extension add features that are only conditionally available under certain OpenGL versions/profiles or
when certain other extensions are also supported; for example, the <em>VertexWeighthNV</em> command from the <em>NV_half_float</em>
extension is only available when the <em>EXT_vertex_weighting</em> extension is also supported. Unfortunately, the API registry
does not specify these interactions in a consistent manner, so it's not possible for zigglgen to generate code that
ensures that calls to supported extension functions are always safe.
If you use OpenGL extensions it is your responsibility to read the extension specifications carefully and understand
under which conditions their features are available.
Why can't I pass my windowing system's <code>getProcAddress</code> function to <code>ProcTable.init</code>?
It might have the wrong signature, such as taking a <code>[:0]const u8</code> (0-terminated slice) instead of a <code>[*:0]const u8</code>
(0-terminated many-pointer), or returning a pointer without an alignment qualifier. To fix this, define your own
function that wraps the windowing system's function and corrects the mismatch:
```zig
fn fixedGetProcAddress(prefixed_name: [*:0]const u8) ?gl.PROC {
return @alignCast(windowing.getProcAddress(std.mem.span(prefixed_name)));
}
// ...
if (!gl_procs.init(fixedGetProcAddress)) return error.InitFailed;
```
Contributing
If you have any issues or suggestions, please open an issue or a pull request.
Help us define overrides for function parameters and return types!
Due to the nature of the API Registry being designed for C, zigglgen currently generates most pointers types as <code>[*c]</code>
pointers, which is less than ideal. A long-term goal for zigglgen is for every single pointer type to be correctly
annotated. There are approximately 3300 commands defined in the API registry and if we work together, we can achieve
that goal sooner. Even fixing up just a few commands would mean a lot!
Overriding parameters/return types is very easy; all you need to do is add additional entries to the
<code>paramOverride</code>/<code>returnTypeOverride</code> functions in <a><code>zigglgen.zig</code></a>, then open a pull request with your
changes (bonus points if you also reference relevant OpenGL references page or specifications in the description of your
pull request).
License
This repository is <a>REUSE-compliant</a>. The effective SPDX license expression for the repository as a whole is:
<code>Apache-2.0 AND MIT</code>
Copyright notices and license texts have been reproduced in <a><code>LICENSE.txt</code></a>, for your convenience. | [
"https://github.com/PaNDa2code/zterm",
"https://github.com/anyputer/retro-zig",
"https://github.com/eddineimad0/widow",
"https://github.com/griush/CoreX",
"https://github.com/griush/zig-opengl-example",
"https://github.com/pierrekraemer/zgp",
"https://github.com/tiawl/cimgui.zig",
"https://github.com/... |
https://avatars.githubusercontent.com/u/3848910?v=4 | zigcli | jiacai2050/zigcli | 2022-09-20T14:39:58Z | A toolkit for building command lines programs in Zig. | main | 10 | 90 | 10 | 90 | https://api.github.com/repos/jiacai2050/zigcli/tags | MIT | [
"cli",
"lines-of-code",
"tree",
"zig",
"zig-package"
] | 255 | false | 2025-05-10T13:43:17Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "curl",
"tar_url": "https://github.com/jiacai2050/zig-curl/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/jiacai2050/zig-curl"
}
] | 404 | [
"https://github.com/zigcc/zig-cookbook"
] |
https://avatars.githubusercontent.com/u/499?v=4 | zini | judofyr/zini | 2022-08-04T17:05:58Z | Succinct data structures for Zig | main | 2 | 67 | 2 | 67 | https://api.github.com/repos/judofyr/zini/tags | 0BSD | [
"zig",
"zig-package"
] | 194 | false | 2025-04-25T06:09:52Z | true | true | 0.11.0 | github | [] | Zini
Zini (Zig + Mini) is a <a>Zig</a> library providing some succinct data structures:
<ul>
<li><code>zini.pthash</code>, a <a><strong>minimal perfect hash function</strong></a> construction algorithm, using less than 4 bits per element.</li>
<li><code>zini.ribbon</code>, a <strong>retrieval data structure</strong> (sometimes called a "static function") construction algorithm, having less than 1% overhead.</li>
<li><code>zini.CompactArray</code> stores n-bit numbers tightly packed, leaving no bits unused.
If the largest value in an array is <code>m</code> then you actually only need <code>n = log2(m) + 1</code> bits per element.
E.g. if the largest value is 270, you will get 7x compression using CompactArray over <code>[]u64</code> as it stores each element using only 9 bits (and 64 divided by 9 is roughly 7).</li>
<li><code>zini.DictArray</code> finds all distinct elements in the array, stores each once into a CompactArray (the dictionary), and creates a new CompactArray containing indexes into the dictionary.
This will give excellent compression if there's a lot of repetition in the original array.</li>
<li><code>zini.EliasFano</code> stores increasing 64-bit numbers in a compact manner.</li>
<li><code>zini.darray</code> provides constant-time support for the <code>select1(i)</code> operation which returns the <em>i</em>-th set bit in a <code>std.DynamicBitSetUnmanaged</code>.</li>
</ul>
Overview
PTHash, minimal perfect hash function
<code>zini.pthash</code> contains an implementation of <a>PTHash</a>, a <a>minimal perfect hash function</a> construction algorithm.
Given a set of <code>n</code> elements, with the only requirement being that you can hash them, it generates a hash function which maps each element to a distinct number between <code>0</code> and <code>n - 1</code>.
The generated hash function is extremely small, typically consuming less than <strong>4 <em>bits</em> per element</strong>, regardless of the size of the input type.
The algorithm provides multiple parameters to tune making it possible to optimize for (small) size, (short) construction time, or (short) lookup time.
To give a practical example:
In ~0.6 seconds Zini was able to create a hash function for /usr/share/dict/words containing 235886 words.
The resulting hash function required in total 865682 bits in memory.
This corresponds to 108.2 kB in total or 3.67 bits per word.
In comparison, the original file was 2.49 MB and compressing it with <code>gzip -9</code> only gets it down to 754 kB (which you can't use directly in memory without decompressing it).
It should of course be noted that they don't store the equivalent data as you can't use the generated hash function to determine if a word is present or not in the list.
The comparison is mainly useful to get a feeling of the magnitudes.
Bumped Ribbon Retrieval, a retrieval data structure
<code>zini.ribbon</code> contains an implementation of <a>Bumped Ribbon Retrieval</a> (<em>BuRR</em>), a retrieval data structure.
Given <code>n</code> keys (with the only requirement being that you can hash them) which each have an <code>r</code>-bit value, we'll build a data structure which will return the value for all of the <code>n</code> keys.
However, the keys are actually not stored (we're only using the hash) so if you ask for the value for an <em>unknown</em> key you will get a seemingly random answer; there's no way of knowing whether the key was present in the original dataset or not.
The theoretically minimal amount of space needed to store the <em>values</em> is <code>n * r</code> (we have <code>n</code> <code>r</code>-bit values after all).
We use the term "overhead" to refer to how much <em>extra</em> amount of data we need.
The Bumped Ribbon Retrieval will often have <strong>less than 1% overhead</strong>.
Usage
Zini is intended to be used as a library, but also ships the command-line tools <code>zini-pthash</code> and <code>zini-ribbon</code>.
As the documentation is a bit lacking it might be useful to look through <code>tools/zini-{pthash,ribbon}/main.zig</code> to understand how it's used.
```
USAGE
./zig-out/bin/zini-pthash [build | lookup]
COMMAND: build
Builds hash function for plain text file.
-i, --input
-o, --output
-c
-a, --alpha
-s, --seed
COMMAND: lookup
-i, --input
-k, --key
-b, --benchmark
```
And here's an example run of using <code>zini-pthash</code>.
```
Build zini-pthash:
$ zig build -Drelease-safe
Build a hash function:
$ ./zig-out/bin/zini-pthash build -i /usr/share/dict/words -o words.pth
Reading /usr/share/dict/words...
Building hash function...
Successfully built hash function:
seed: 12323441790160983030
bits: 865554
bits/n: 3.6693741892269993
Writing to words.pth
Look up an index in the hash function:
$ ./zig-out/bin/zini-pthash lookup -i words.pth --key hello
Reading words.pth...
Successfully loaded hash function:
seed: 12323441790160983030
bits: 865554
bits/n: 3.6693741892269993
Looking up key=hello:
112576
```
Acknowledgments
Zini is merely an implementation of existing algorithms and techniques already described in the literature:
<ul>
<li>The <a>PTHash</a> algorithm is described by Giulio Ermanno Pibiri and Roberto Trani in arXiv:2104.10402.</li>
<li>They also implemented PTHash as a C++ library in <a>https://github.com/jermp/pthash</a> under the MIT license.
Zini uses no code directly from that repository, but it has been an invaluable resource for understanding how to implement PTHash in practice.</li>
<li>The <a>BuRR</a> data structure is described by Peter C. Dillinger, Lorenz Hübschle-Schneider, Peter Sanders and Stefan Walzer in arXiv:2109.01892.</li>
</ul>
License
Zini is licensed under the <a>0BSD license</a>. | [
"https://github.com/LittleBigRefresh/FreshPresence"
] |
https://avatars.githubusercontent.com/u/175068426?v=4 | keylib | Zig-Sec/keylib | 2022-09-25T13:25:01Z | FIDO2/ PassKey compatible authentication library | master | 2 | 60 | 2 | 60 | https://api.github.com/repos/Zig-Sec/keylib/tags | MIT | [
"authentication",
"authenticator",
"ctap",
"ctap2",
"fido2",
"passkey",
"passkeys",
"webauthn",
"zig",
"zig-package",
"ziglang"
] | 1,050 | false | 2025-05-20T01:10:39Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "zbor",
"tar_url": "https://github.com/r4gus/zbor/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/r4gus/zbor"
},
{
"commit": "refs",
"name": "hidapi",
"tar_url": "https://github.com/r4gus/hidapi/archive/refs.tar.gz",
"type": "rem... | FIDO2 compatible authenticator and client library written in <a>Zig</a>. The authenticator part requires <strong>zero dynamic allocations</strong>.
<blockquote>
We track the latest stable release of Zig (<code>0.12.0</code>)
</blockquote>
If you want to see an example on how the library could be used, check out <a>PassKeeZ</a>.
| Zig version | keylib version |
|:-----------:|:--------------:|
| 0.13.0 | 0.5.0, 0.5.1, 0.5.2, 0.5.3 |
| 0.14.0 | 0.6.0 |
QA
What is FIDO2?
FIDO2 is a protocol designed for authentication purposes. It can be used as single factor (e.g., as a replacement for password based authentication) or as a second factor (e.g., instead of OTPs).
I've heard the term Passkey but what is that?
Passkey is a marketing term which is used to refer to a specific FIDO2 authenticator configuration. A authenticator can be configured to use so called discoverable credentials (also referred to as resident keys). Those credentials are stored somewhere on your device, e.g. in a encrypted database. Devices can also be protected by some form of user verification. This can be a PIN or a built in user verification method like a finger print scanner. Passkey refers to FIDO2 using discoverable credentials and some form of user verification.
Please note that this is only one interpretation of what PassKey means as the term itself is nowhere defined (see also [Passkeys's: A Shattered Dream](https://fy.blackhats.net.au/blog/2024-04-26-passkeys-a-shattered-dream/)).
How does it work?
FIDO2 uses asymmetric cryptography to ensure the authenticity of the user. A unique credential (key-pair) is created for each relying party (typically a web server) and bound to the relying party id (e.g., google.com). The private key stays on the authenticator and the public key is stored by the relying party. When a user wants to authenticate herself, the relying party sends a nonce (a random byte string meant to be only used once) and some other data, over the client (typically your web browser), to the authenticator. The authenticator looks up the required private key and signs the data with it. The generated signature can then be verified by the relying party using the corresponding public key.
What is the difference between FIDO2, PassKey and WebAuthn?
You might have noticed that FIDO2, PassKey and even WebAuthn are often used interchangeably by some articles and people which can be confusing, especially for people new to the protocol. Here is a short overview:
* `FIDO2` Protocol consisting of two sub-protocols: Client to Authenticator Protocol 2 (`CTAP2`) and Web Authentication (`WebAuthn`)
* `CTAP2` Specification that governs how a authenticator (e.g. YubiKey) should behave and how a authenticator and a client (e.g. web-browser) can communicate with each other.
* `WebAuthn` Specification that defines how web applications can use a authenticator for authentication. This includes the declaration of data structures and Java Script APIs.
* `PassKey`: A authenticator with a specific configuration (see above).
Why should I use FIDO2?
FIDO2 has a lot of advantages compared to passwords:
1. No secret information is shared, i.e. the private key stays on the authenticator or is protected, e.g. using key wrapping.
2. Each credential is bound to a relying party id (e.g. google.com), which makes social engineering attacks, like phishing websites, quite difficult (as long as the client verifies the relying party id properly).
3. Users don't have to be concerned with problems like password complexity.
4. If well implemented, FIDO2 provides a better user experience (e.g., faster logins).
5. A recent paper showed that with some adoptions, FIDO2 is ready for a post quantum world under certain conditions ([FIDO2, CTAP 2.1, and WebAuthn 2: Provable Security and Post-Quantum Instantiation, Cryptology ePrint Archive, Paper 2022/1029](https://eprint.iacr.org/2022/1029.pdf)).
Are there problems with FIDO2?
Yes, there are:
1. The two FIDO2 subprotocols (CTAP2 and WebAuthn) are way more difficult to implement, compared to password authentication.
2. There are more points of failure because you have three parties that are involved in the authentication process (authenticator, client, relying party).
3. Currently not all browsers support the CTAP2 protocol well (especially on Linux).
4. There is no way to verify that a client is trustworthy:
* Rogue clients may communicate with a authenticator without your consent
* Clients may display wrong information
5. The 4th layer introduced for Android, IOS, and Windows to connect authenticators and clients internally could be used as a man in the middle.
Does this library work with all browsers?
Answering this question isn't straightforward. The library, by its nature, is designed to be independent of any particular platform, meaning that you have the responsibility of supplying it with data for processing. To put it differently, you're in charge of creating a functional interface for communicating with a client, typically a web browser. On Linux, we offer a wrapper for the uhid interface, simplifying the process of presenting an application as a USB HID device with a Usage Page of F1D0 on the bus.
**There are known issues with older browsers (including Firefox)**. Newer browser versions should work fine. Tested with:
| Browser | Supported? | Tested version| Notes |
|:-------:|:----------:|:-------------:|:-----:|
| Cromium | ✅ | 119.0.6045.159 (Official Build) Arch Linux (64-bit) | |
| Brave | ✅ | Version 1.62.153 Chromium: 121.0.6167.85 (Official Build) (64-bit) | |
| Firefox | ✅ | 122.0 (64-bit) | |
| Opera | ✅ | version: 105.0.4970.16 chromium: 119.0.6045.159 | |
**Please let me know if you run into issues!**
Does this library implement the whole CTAP2 sepc?
No, we do not fully implement the entire [CTAP2](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#intro) specification. In the initial version of this library, which can be found on GitHub, our aim was to remain completely platform-agnostic and cover most of the CTAP2 specification. However, this approach introduced complexities for both users and developers. The current version of this library strikes a balance between usability and feature completeness.
We offer support for operations like __authenticatorMakeCredential__, __authenticatorGetAssertion__, __authenticatorGetInfo__, and __authenticatorClientPin__, with built-in support for __user verification__ and the __pinUvAuth protocol__ (versions 1 and 2). You are responsible for handling data management tasks (such as secure storage, updates, and deletions), verifying user presence, and conducting user verification. These responsibilities are fulfilled by implementing the necessary callbacks used to instantiate an authenticator (refer to the "Getting Started" section for details).
Zero dynamic allocations?
The authenticator part of this library doesn't allocate any memory dynamically. This has some draw backs like a fixed
size for strings (e.g., rpId, user name, etc.) but also reduces the complexity of the code.
The authenticator example uses `88655` bytes of stack space when compiled with `-Doptimize=ReleaseSmall` on Linux (x86\_64).
> The authenticator example has been profiled using valgrind.
> * `zig build auth-example -Doptimize=ReleaseSmall`
> * `valgrind --tool=drd --show-stack-usage=yes ./zig-out/bin/authenticator`
> * Test page: [webauthn.io](https://webauthn.io/) - Register + Authentication
> `thread 1 finished and used 88655 bytes out of 8388608 on its stack.`
> `ThinkPad-X1-Yoga-3rd 6.5.0-35-generic #35~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC x86_64 GNU/Linux`
Design
Getting Started
We maintain two examples on how to use the library:
<ul>
<li><code>authenticator</code> - <a>https://github.com/r4gus/keylib/blob/master/example/authenticator.zig</a><ul>
<li><strong>Please read the description at the top of the source code for instructions on how to setup uhid correctly</strong></li>
</ul>
</li>
<li><code>client</code> - <a>https://github.com/r4gus/keylib/blob/master/example/client.zig</a></li>
</ul>
Resources
<ul>
<li><a>CTAP2</a> - FIDO Alliance</li>
<li><a>WebAuthn</a> - W3C</li>
<li><a>CBOR RFC8949</a> - C. Bormann and P. Hoffman</li>
</ul>
<strong>FIDO2/Passkey test sites</strong>:
- <a>passkey.org</a>
- <a>webauthn.io</a>
Random Ideas
Protecting secrets using a PIN
Microcontrollers like the rp2040 allow the creation of cheap authenticators but they provide no means to somehow protect
secrets like master passwords, PINs, or credentials. One way one could securely store sensitive data is by making PIN
protection mandatory. Note that this is a tradeof and will render some counters (like the pin retry counter) useless if
an attacker has physical access to the chip, as one can not protect the counters from manipulation.
1. Your authenticator has PIN protection enabled by default, i.e. on first boot a default password is set. You should also
set the _force pin change_ flag to "encourge" the user to change his password.
2. Also on first boot, you create a master password which will encrypt all sensitive data using a AEAD cipher. The master
password itself is encrypted using a secret derived from the PIN.
3. Metadata like retry counters are not encrypted (make sure you __DONT__ store the PIN unencrypted!). This still allows
the blocking of a authenticator (in fact you should automatically reset the authenticator if the retry counter hits zero)
but an attack with physical access could potentially reset the counters giving him unlimited retries.
4. Make sure you disallow any operations on sensitive data without prior authentication (__alwaysUv__).
5. Make sure you only use PIN authentication.
6. During authentication you intercept the PIN hash (after decryption) and derive a deterministic secret from it
using a key derivation function of you choice (e.g. HKDF; but it must always be the same). This secret must have
the same lifetime as the pinUvAuthToken!
7. When the application requires a credential (or other sensitive data) you decrypt the master secret using the
derived secret and the decrypt the actual data with the master secret. If the application wants to overwrite data,
you decrypt the data, update it and the encrypt it using the master secret.
8. After you're done, make sure to overwrite any plain text information no longer required.
9. On pin change, just decrypt the master secret and then re-encrypt it using the secret derived
from the new PIN hash.
| [
"https://github.com/Zig-Sec/PassKeeZ"
] |
https://avatars.githubusercontent.com/u/3526922?v=4 | napigen | cztomsik/napigen | 2022-09-14T17:39:50Z | Automatic N-API (server-side javascript) bindings for your Zig project. | main | 3 | 59 | 7 | 59 | https://api.github.com/repos/cztomsik/napigen/tags | MIT | [
"javascript",
"napi",
"nodejs",
"zig",
"zig-package"
] | 84 | false | 2025-05-20T20:56:02Z | true | true | unknown | github | [
{
"commit": "master",
"name": "node_api",
"tar_url": "https://github.com/nodejs/node-api-headers/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/nodejs/node-api-headers"
}
] | zig-napigen
Comptime N-API bindings for Zig.
<blockquote>
You need to use latest Zig 0.14.0 to use this library.
See <a>ggml-js</a> for a complete, real-world
example.
</blockquote>
Features
<ul>
<li>Primitives, tuples, structs (value types), optionals</li>
<li>Strings (valid for the function scope)</li>
<li>Struct pointers (see below)</li>
<li>Functions (no classes, see below)</li>
<li>all the <code>napi_xxx</code> functions and types are re-exported as <code>napigen.napi_xxx</code>,\
so you can do pretty much anything if you don't mind going lower-level.</li>
</ul>
Limited scope
The library provides a simple and thin API, supporting only basic types. This
design choice is intentional, as it is often difficult to determine the ideal
mapping for more complex types. The library allows users to hook into the
mapping process or use the N-API directly for finer control.
Specifically, there is no support for classes.
Structs/tuples (value types)
When returning a struct/tuple by value, it is mapped to an anonymous JavaScript
object/array with all properties/elements mapped recursively. Similarly, when
accepting a struct/tuple by value, it is mapped back from JavaScript to the
respective native type.
In both cases, a copy is created, so changes to the JS object are not reflected
in the native part and vice versa.
Struct pointers (*T)
When returning a pointer to a struct, an empty JavaScript object will be created
with the pointer wrapped inside. If this JavaScript object is passed to a
function that accepts a pointer, the pointer is unwrapped back.
The same JavaScript object is obtained for the same pointer, unless it has
already been collected. This is useful for attaching state to the JavaScript
counterpart and accessing that data later.
Changes to JavaScript objects are not reflected in the native part, but
getters/setters can be provided in JavaScript and native functions can be called
as necessary.
Functions
JavaScript functions can be created with ctx.createFunction(zig_fn) and then
exported like any other value. Only comptime-known functions are supported. If
an error is returned from a function call, an exception is thrown in JavaScript.
```zig
fn add(a: i32, b: i32) i32 {
return a + b;
}
// Somewhere where the JsContext is available
const js_fun: napigen.napi_value = try js.createFunction(add);
// Make the function accessible to JavaScript
try js.setNamedProperty(exports, "add", js_fun);
```
Note that <strong>the number of arguments must match exactly</strong>. So if you need to
support optional arguments, you will have to provide a wrapper function in JS,
which calls the native function with the correct arguments.
Callbacks, *JsContext, napi_value
Functions can also accept the current <code>*JsContext</code>, which is useful for calling
the N-API directly or performing callbacks. To get a raw JavaScript value,
simply use <code>napi_value</code> as an argument type.
<code>zig
fn callMeBack(js: *napigen.JsContext, recv: napigen.napi_value, fun: napigen.napi_value) !void {
try js.callFunction(recv, fun, .{ "Hello from Zig" });
}</code>
And then
<code>javascript
native.callMeBack(console, console.log)</code>
If you need to store the callback for a longer period of time, you should create
a ref. For now, you have to do that directly, using <code>napi_create_reference()</code>.
defineModule(init_fn), exports
N-API modules need to export a function which will also init & return the
<code>exports</code> object. You could export <code>napi_register_module_v1</code> and call
<code>JsContext.init()</code> yourself but there's also a shorthand using <code>comptime</code> block
which will allow you to use <code>try</code> anywhere inside:
```zig
comptime { napigen.defineModule(initModule) }
fn initModule(js: *napigen.JsContext, exports: napigen.napi_value) anyerror!napigen.napi_value {
try js.setNamedProperty(exports, ...);
...
<code>return exports;
</code>
}
```
Hooks
Whenever a value is passed from Zig to JS or vice versa, the library will call a
hook function, if one is defined. This allows you to customize the mapping
process.
Hooks have to be defined in the root module, and they need to be named
<code>napigenRead</code> and <code>napigenWrite</code> respectively. They must have the following
signature:
```zig
fn napigenRead(js: *napigen.JsContext, comptime T: type, value: napigen.napi_value) !T {
return switch (T) {
// we can easily customize the mapping for specific types
// for example, we can allow passing regular JS strings anywhere where we expect an InternedString
InternedString => InternedString.from(try js.read([]const u8)),
<code> // otherwise, just use the default mapping, note that this time
// we call js.defaultRead() explicitly, to avoid infinite recursion
else => js.defaultRead(T, value),
}
</code>
}
pub fn napigenWrite(js: *napigen.JsContext, value: anytype) !napigen.napi_value {
return switch (@TypeOf(value) {
// convert InternedString to back to a JS string (hypothetically)
InternedString => try js.write(value.ptr),
<code> // same thing here
else => js.defaultWrite(value),
}
</code>
}
```
Complete example
The repository includes a complete example in the <code>example</code> directory. Here's a quick walkthrough:
<strong>1. Create a new library</strong>
<code>bash
mkdir example
cd example
zig init-lib</code>
<strong>2. Add napigen as zig module.</strong>
<code>zig fetch --save git+https://github.com/cztomsik/napigen#main</code>
<strong>3. Update build.zig</strong>
Then, change your <code>build.zig</code> to something like this:
```zig
const std = @import("std");
const napigen = @import("napigen");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const lib = b.addSharedLibrary(.{
.name = "example",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
// Add napigen
napigen.setup(lib);
// Build the lib
b.installArtifact(lib);
// Copy the result to a *.node file so we can require() it
const copy_node_step = b.addInstallLibFile(lib.getEmittedBin(), "example.node");
b.getInstallStep().dependOn(&copy_node_step.step);
</code>
}
```
<strong>4. Define & export something useful</strong>
Next, define some functions and the N-API module itself in <code>src/main.zig</code>
```zig
const std = @import("std");
const napigen = @import("napigen");
export fn add(a: i32, b: i32) i32 {
return a + b;
}
comptime {
napigen.defineModule(initModule);
}
fn initModule(js: *napigen.JsContext, exports: napigen.napi_value) anyerror!napigen.napi_value {
try js.setNamedProperty(exports, "add", try js.createFunction(add));
<code>return exports;
</code>
}
```
<strong>5. Use it from JS side</strong>
Finally, use it from JavaScript as expected:
```javascript
import { createRequire } from 'node:module'
const require = createRequire(import.meta.url)
const native = require('./zig-out/lib/example.node')
console.log('1 + 2 =', native.add(1, 2))
```
To build the library and run the script:
```
<blockquote>
zig build && node example.js
1 + 2 = 3
```
</blockquote>
License
MIT | [] |
https://avatars.githubusercontent.com/u/7078566?v=4 | zig-toml | sam701/zig-toml | 2022-12-20T21:06:03Z | Zig TOML (v1.0.0) parser | main | 1 | 52 | 21 | 52 | https://api.github.com/repos/sam701/zig-toml/tags | MIT | [
"parser",
"toml",
"zig-package",
"ziglang"
] | 136 | false | 2025-05-21T13:47:15Z | true | true | 0.14.0-dev.3197+1d8857bbe | github | [] | zig-toml
Zig <a>TOML v1.0.0</a> parser.
This is a top-down LL parser that parses directly into Zig structs.
Features
<ul>
<li>TOML Syntax</li>
<li>[x] Integers, hexadecimal, octal, and binary numbers</li>
<li>[x] Floats</li>
<li>[x] Booleans</li>
<li>[x] Comments</li>
<li>[x] Arrays</li>
<li>[x] Tables</li>
<li>[x] Array of Tables</li>
<li>[x] Inline Table</li>
<li>[x] Single-line strings</li>
<li>[x] String escapes (also unicode)</li>
<li>[x] Multi-line strings</li>
<li>[x] Multi-line string leading space trimming</li>
<li>[x] Trailing backslash in multi-line strings</li>
<li>[x] Date, time, date-time, time offset</li>
<li>Struct mapping</li>
<li>[x] Mapping to structs</li>
<li>[x] Mapping to enums</li>
<li>[x] Mapping to slices</li>
<li>[x] Mapping to arrays</li>
<li>[x] Mapping to pointers</li>
<li>[x] Mapping to integer and floats with lower bit number than defined by TOML, i.e. <code>i16</code>, <code>f32</code>.</li>
<li>[x] Mapping to optional fields</li>
<li>[x] Mapping to HashMaps</li>
<li>[ ] Serialization<ul>
<li>[x] Basic types like integers, floating points, strings, booleans etc.</li>
<li>[x] Arrays</li>
<li>[x] Top level tables</li>
<li>[x] Sub tables</li>
<li>[x] Pointers</li>
<li>[x] Date, time, DateTime, time offset</li>
<li>[x] Enums</li>
<li>[x] Unions</li>
</ul>
</li>
</ul>
Using with the Zig package manager
Add <code>zig-toml</code> to your <code>build.zig.zon</code>
```
For zig-master
zig fetch --save git+https://github.com/sam701/zig-toml
For zig 0.13
zig fetch --save git+https://github.com/sam701/zig-toml#last-zig-0.13
```
Example
See <a><code>example1.zig</code></a> for the complete code that parses <a><code>example.toml</code></a>
Run it with <code>zig build examples</code>
```zig
// ....
const Address = struct {
port: i64,
host: []const u8,
};
const Config = struct {
master: bool,
expires_at: toml.DateTime,
description: []const u8,
<code>local: *Address,
peers: []const Address,
</code>
};
pub fn main() anyerror!void {
var parser = toml.Parser(Config).init(allocator);
defer parser.deinit();
<code>var result = try parser.parseFile("./examples/example1.toml");
defer result.deinit();
const config = result.value;
std.debug.print("{s}\nlocal address: {s}:{}\n", .{ config.description, config.local.host, config.local.port });
std.debug.print("peer0: {s}:{}\n", .{ config.peers[0].host, config.peers[0].port });
</code>
}
```
Error Handling
TODO
License
MIT | [
"https://github.com/EngineersBox/Flow",
"https://github.com/darkyzhou/mcm"
] |
https://avatars.githubusercontent.com/u/3932972?v=4 | TextEditor | ikskuh/TextEditor | 2022-05-16T09:45:21Z | A backbone for text editors. No rendering, no input, but everything else. | main | 0 | 51 | 3 | 51 | https://api.github.com/repos/ikskuh/TextEditor/tags | MIT | [
"text",
"text-editor",
"unicode",
"zig",
"zig-package"
] | 29 | false | 2025-03-29T23:23:44Z | true | true | unknown | github | [
{
"commit": "b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz",
"name": "ziglyph",
"tar_url": "https://codeberg.org/dude_the_builder/ziglyph/archive/b89d43d1e3fb01b6074bc1f7fc980324b04d26a5.tar.gz.tar.gz",
"type": "remote",
"url": "https://codeberg.org/dude_the_builder/ziglyph"
}
] | TextEditor
A backend for text editors. It implements the common textbox editing options, but is both rendering and input agnostic.
Keyboard input must be translated into operations like <code>editor.delete(.right, .word)</code> to emulate what a typical text box implementation would do when <code>CTRL DELETE</code> is pressed.
For mouse input, the editor component needs to be made aware about the font that is used. For this, an abstract font interface is required.
API
```zig
const TextEditor = @import("src/TextEditor.zig");
fn init(TextEditor.Buffer, initial_text: []const u8) InsertError!TextEditor {
fn deinit(<em>TextEditor) void;
fn setText(</em>TextEditor, text: []const u8) InsertError!void;
fn getText(TextEditor) []const u8;
fn getSubString(editor: TextEditor, start: usize, length: ?usize) []const u8;
fn setCursor(<em>TextEditor, offset: usize) SetCursorError!void;
fn moveCursor(</em>TextEditor, direction: EditDirection, unit: EditUnit) void;
fn delete(<em>TextEditor, direction: EditDirection, unit: EditUnit) void;
fn insertText(</em>TextEditor, text: []const u8) InsertError!void;
fn graphemeCount(TextEditor) usize;
```
Common Key Mappings
| Keyboard Input | Editor Call |
| ---------------- | ------------------------------------ |
| <code>Left</code> | <code>editor.moveCursor(.left, .letter)</code> |
| <code>Right</code> | <code>editor.moveCursor(.right, .letter)</code> |
| <code>Ctrl+Left</code> | <code>editor.moveCursor(.left, .word)</code> |
| <code>Ctrl+Right</code> | <code>editor.moveCursor(.right, .word)</code> |
| <code>Home</code> | <code>editor.moveCursor(.left, .line)</code> |
| <code>End</code> | <code>editor.moveCursor(.right, .line)</code> |
| <code>Backspace</code> | <code>editor.delete(.left, .letter)</code> |
| <code>Delete</code> | <code>editor.delete(.right, .letter)</code> |
| <code>Ctrl+Backspace</code> | <code>editor.delete(.left, .word)</code> |
| <code>Ctrl+Delete</code> | <code>editor.delete(.right, .word)</code> |
| <em>text input</em> | <code>try editor.insert("string")</code> | | [] |
https://avatars.githubusercontent.com/u/499?v=4 | parg | judofyr/parg | 2022-03-05T10:45:26Z | Lightweight argument parser for Zig | main | 0 | 46 | 2 | 46 | https://api.github.com/repos/judofyr/parg/tags | 0BSD | [
"argument-parser",
"zig",
"zig-package"
] | 22 | false | 2025-04-14T07:01:30Z | true | true | unknown | github | [] | parg
<strong>parg</strong> is a lightweight argument parser for Zig which focuses on a single task:
Parsing command-line arguments into positional arguments and long/short flags.
It doesn't concern itself <em>anything</em> else.
You may find this useful as a quick way of parsing some arguments, or use it as a building block for a more elaborate CLI toolkit.
Features / non-features
<ul>
<li>Parses command-line arguments into <strong>positional arguments</strong>, <strong>long flags</strong> and <strong>short flags</strong>.</li>
<li>Provides an iterator interface (<code>while (parser.next()) |token| …</code>).</li>
<li>Supports boolean flags (<code>--force</code>, <code>-f</code>).</li>
<li>Supports multiple short flags (<code>-avz</code>).</li>
<li>Values can be provided as separate arguments (<code>--message Hello</code>), with a delimiter (<code>--message=Hello</code>) and also part of short flag (<code>-mHello</code>).</li>
<li>Automatically detects <code>--</code> and skips any further parsing.</li>
<li>Licensed under 0BSD.</li>
</ul>
Usage
The principles of <code>parg</code> are as follows:
<ul>
<li>Use <code>parseProcess</code>, <code>parseSlice</code> or <code>parse</code> to create a new parser.</li>
<li>Remember to call <code>deinit()</code> when you're done with the parser.</li>
<li>Call <code>next()</code> in a loop to parse arguments.</li>
<li>Call <code>nextValue()</code> whenever you need a plain value.</li>
<li>There's a few more knobs you can tweak with.</li>
</ul>
Let's go over these steps a bit more in detail.
Create a new parser instance
There's three ways of creating a parser instance.
All of these accept some <em>options</em> as the last argument.
```zig
const parg = @import("parg");
// (1) Parse arguments given to the current process:
var p = try parg.parseProcess(allocator, .{});
// (2) Parse arguments from a <code>[]const []const u8</code>:
var p = parg.parseSlice(slice, .{});
// (3) Parse arguments from an iterator (advanced usage):
var p = parg.parse(it, .{});
// Always remember to deinit:
defer p.deinit();
```
In addition, remember that the first parameter given to a process is the file name of the executable.
You typically want to call <code>nextValue()</code> to retrieve this value before you continue parsing any arguments.
<code>zig
const program_name = p.nextValue() orelse @panic("no executable name");</code>
Parsing boolean flags and positional arguments
Once you have a parser you want to call <code>next()</code> in a loop.
This returns a token which has three different possibilities:
<ul>
<li><code>.flag</code> when it encounters a flag (e.g. <code>--verbose</code> or <code>-v</code>).
This flag has a <code>.name</code> field which contains the name of the flag (without the dashes) and a <code>.kind</code> field if you need to distinguish between long and short flags.
There are also a helper functions <code>isLong</code> and <code>isShort</code> to easily check the name of the field.</li>
<li><code>.arg</code> when it encounters a positional argument.</li>
<li><code>.unexpected_value</code> when it encounters an unexpected value.
You should just quit the program with an error when this happens.
We'll come back to this in the next section.</li>
</ul>
Also note that this will automatically split up short flags as expected:
If you give the program <code>-fv</code> then <code>next()</code> will first return a flag with name <code>f</code>, and then a flag with name <code>v</code>.
```zig
// See examples/ex1.zig for full example.
var verbose = false;
var force = false;
var arg: ?[]const u8 = null;
while (p.next()) |token| {
switch (token) {
.flag => |flag| {
if (flag.isLong("force") or flag.isShort("f")) {
force = true;
} else if (flag.isLong("verbose") or flag.isShort("v")) {
verbose = true;
} else if (flag.isLong("version")) {
std.debug.print("v1\n", .{});
std.os.exit(0);
}
},
.arg => |val| {
if (arg != null) @panic("only one argument supported");
arg = val;
},
.unexpected_value => @panic("unexpected value"),
}
}
```
Parsing flags with values
When you find a flag which require a value you need to invoke <code>nextValue()</code>.
This returns an optional slice:
```zig
// See examples/ex2.zig for full example.
while (p.next()) |token| {
switch (token) {
.flag => |flag| {
if (flag.isLong("file") or flag.isShort("f")) {
file = p.nextValue() orelse @panic("--file requires value");
} else if (flag.isLong("verbose") or flag.isShort("v")) {
verbose = true;
} else if (flag.isLong("version")) {
std.debug.print("v1\n", .{});
std.os.exit(0);
}
},
.arg => @panic("unexpected argument"),
.unexpected_value => @panic("unexpected value"),
}
}
```
All of these will be treated the same way:
<ul>
<li><code>--file build.zig</code></li>
<li><code>--file=build.zig</code></li>
<li><code>-f build.zig</code></li>
<li><code>-f=build.zig</code></li>
<li><code>-fbuild.zig</code></li>
</ul>
Most notably, notice that when you call <code>nextValue()</code> it will "break out" of parsing short flags.
Without the call to <code>nextValue()</code> the code would parse <code>-fbuild.zig</code> as the short flags <code>-f</code>, <code>-b</code>, <code>-u</code>, and so on.
This also explains the need for <code>.unexpected_value</code> in <code>next()</code>:
If you pass <code>--force=yes</code> to the first example it will parse the <code>--force</code> as a long flag.
When you then <em>don't</em> invoke <code>nextValue()</code> (since it's a boolean flag) then we need to later bail out since we didn't expect a value.
Options and other functionality
There's currently only one option (which you configure when instantiate the parser):
<ul>
<li><code>auto_double_dash</code> (defaults to <code>true</code>).
When this is <code>true</code> it will look for <code>--</code> and then stop parsing anything as a flag.
Your program will <em>not</em> observe the <code>--</code> token at all, and all tokens after this point will be returned as <code>.arg</code> (even though they start with a dash).
When this is <code>false</code> it will return <code>--</code> as a regular argument (<code>.arg</code>) and argument parsing will continue as usual.</li>
</ul>
There's also one additional method:
<ul>
<li><code>p.skipFlagParsing()</code>.
This turns off any further argument parsing.
All tokens after this point will be returned as <code>.arg</code> (even though they start with a dash).</li>
</ul> | [
"https://github.com/judofyr/spice",
"https://github.com/nrdave/zmatrix"
] |
https://avatars.githubusercontent.com/u/25912761?v=4 | zbor | r4gus/zbor | 2022-07-06T23:29:57Z | CBOR parser written in Zig | master | 1 | 44 | 7 | 44 | https://api.github.com/repos/r4gus/zbor/tags | MIT | [
"cbor",
"encoder-decoder",
"parsing",
"rfc-8949",
"zig",
"zig-package",
"ziglang"
] | 4,619 | false | 2025-05-20T09:00:28Z | true | true | 0.14.0 | github | [] | zbor - Zig CBOR
The Concise Binary Object Representation (CBOR) is a data format whose design
goals include the possibility of extremely small code size, fairly small
message size, and extensibility without the need for version negotiation
(<a>RFC8949</a>). It is used
in different protocols like the Client to Authenticator Protocol
<a>CTAP2</a>
which is a essential part of FIDO2 authenticators/ Passkeys.
I have utilized this library in several projects throughout the previous year, primarily in conjunction with my <a>FIDO2 library</a>. I'd consider it stable.
With the introduction of <a>Zig version <code>0.11.0</code></a>, this library will remain aligned with the most recent stable release. If you have any problems or want
to share some ideas feel free to open an issue or write me a mail, but please be kind.
Getting started
Versions
| Zig version | zbor version |
|:-----------:|:------------:|
| 0.13.0 | 0.15.0, 0.15.1, 0.15.2 |
| 0.14.0 | 0.16.0, 0.17.0 |
First add this library as a dependency to your <code>build.zig.zon</code> file:
```bash
Replace with the version you want to use
zig fetch --save https://github.com/r4gus/zbor/archive/refs/tags/.tar.gz
```
then within you <code>build.zig</code> add the following code:
```zig
// First fetch the dependency...
const zbor_dep = b.dependency("zbor", .{
.target = target,
.optimize = optimize,
});
const zbor_module = zbor_dep.module("zbor");
// If you have a module that has zbor as a dependency...
const your_module = b.addModule("your-module", .{
.root_source_file = .{ .path = "src/main.zig" },
.imports = &.{
.{ .name = "zbor", .module = zbor_module },
},
});
// Or as a dependency for a executable...
exe.root_module.addImport("zbor", zbor_module);
```
Usage
This library lets you inspect and parse CBOR data without having to allocate
additional memory.
Inspect CBOR data
To inspect CBOR data you must first create a new <code>DataItem</code>.
```zig
const cbor = @import("zbor");
const di = DataItem.new("\x1b\xff\xff\xff\xff\xff\xff\xff\xff") catch {
// handle the case that the given data is malformed
};
```
<code>DataItem.new()</code> will check if the given data is well-formed before returning a <code>DataItem</code>. The data is well formed if it's syntactically correct.
To check the type of the given <code>DataItem</code> use the <code>getType()</code> function.
<code>zig
std.debug.assert(di.getType() == .Int);</code>
Possible types include <code>Int</code> (major type 0 and 1) <code>ByteString</code> (major type 2), <code>TextString</code> (major type 3), <code>Array</code> (major type 4), <code>Map</code> (major type 5), <code>Tagged</code> (major type 6) and <code>Float</code> (major type 7).
Based on the given type you can the access the underlying value.
<code>zig
std.debug.assert(di.int().? == 18446744073709551615);</code>
All getter functions return either a value or <code>null</code>. You can use a pattern like <code>if (di.int()) |v| v else return error.Oops;</code> to access the value in a safe way. If you've used <code>DataItem.new()</code> and know the type of the data item, you should be safe to just do <code>di.int().?</code>.
The following getter functions are supported:
* <code>int</code> - returns <code>?i65</code>
* <code>string</code> - returns <code>?[]const u8</code>
* <code>array</code> - returns <code>?ArrayIterator</code>
* <code>map</code> - returns <code>?MapIterator</code>
* <code>simple</code> - returns <code>?u8</code>
* <code>float</code> - returns <code>?f64</code>
* <code>tagged</code> - returns <code>?Tag</code>
* <code>boolean</code> - returns <code>?bool</code>
Iterators
The functions <code>array</code> and <code>map</code> will return an iterator. Every time you
call <code>next()</code> you will either get a <code>DataItem</code>/ <code>Pair</code> or <code>null</code>.
```zig
const di = DataItem.new("\x98\x19\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x18\x18\x19");
var iter = di.array().?;
while (iter.next()) |value| {
_ = value;
// doe something
}
```
Encoding and decoding
Serialization
You can serialize Zig objects into CBOR using the <code>stringify()</code> function.
```zig
const allocator = std.testing.allocator;
var str = std.ArrayList(u8).init(allocator);
defer str.deinit();
const Info = struct {
versions: []const []const u8,
};
const i = Info{
.versions = &.{"FIDO_2_0"},
};
try stringify(i, .{}, str.writer());
```
<blockquote>
Note: Compile time floats are always encoded as single precision floats (f32). Please use <code>@floatCast</code>
before passing a float to <code>stringify()</code>.
</blockquote>
The <code>stringify()</code> function is convenient but also adds extra overhead. If you want full control
over the serialization process you can use the following functions defined in <code>zbor.build</code>: <code>writeInt</code>,
<code>writeByteString</code>, <code>writeTextString</code>, <code>writeTag</code>, <code>writeSimple</code>, <code>writeArray</code>, <code>writeMap</code>. For more
details check out the <a>manual serialization example</a> and the
corresponding <a>source code</a>.
Stringify Options
You can pass options to the <code>stringify</code> function to influence its behavior. Without passing any
options, <code>stringify</code> will behave as follows:
<ul>
<li>Enums will be serialized to their textual representation</li>
<li><code>u8</code> slices will be serialized to byte strings</li>
<li>For structs and unions:<ul>
<li><code>null</code> fields are skipped by default</li>
<li>fields of type <code>std.mem.Allocator</code> are always skipped.</li>
<li>the names of fields are serialized to text strings</li>
</ul>
</li>
</ul>
You can modify that behavior by changing the default options, e.g.:
```zig
const EcdsaP256Key = struct {
/// kty:
kty: u8 = 2,
/// alg:
alg: i8 = -7,
/// crv:
crv: u8 = 1,
/// x-coordinate
x: [32]u8,
/// y-coordinate
y: [32]u8,
<code>pub fn new(k: EcdsaP256.PublicKey) @This() {
const xy = k.toUncompressedSec1();
return .{
.x = xy[1..33].*,
.y = xy[33..65].*,
};
}
</code>
};
//...
try stringify(k, .{ .field_settings = &.{
.{ .name = "kty", .field_options = .{ .alias = "1", .serialization_type = .Integer } },
.{ .name = "alg", .field_options = .{ .alias = "3", .serialization_type = .Integer } },
.{ .name = "crv", .field_options = .{ .alias = "-1", .serialization_type = .Integer } },
.{ .name = "x", .field_options = .{ .alias = "-2", .serialization_type = .Integer } },
.{ .name = "y", .field_options = .{ .alias = "-3", .serialization_type = .Integer } },
} }, str.writer());
```
Here we define a alias for every field of the struct and tell <code>serialize</code> that it should treat
those aliases as integers instead of text strings.
<strong>See <code>Options</code> and <code>FieldSettings</code> in <code>src/parse.zig</code> for all available options!</strong>
Deserialization
You can deserialize CBOR data into Zig objects using the <code>parse()</code> function.
```zig
const e = [5]u8{ 1, 2, 3, 4, 5 };
const di = DataItem.new("\x85\x01\x02\x03\x04\x05");
const x = try parse([5]u8, di, .{});
try std.testing.expectEqualSlices(u8, e[0..], x[0..]);
```
Parse Options
You can pass options to the <code>parse</code> function to influence its behaviour.
This includes:
<ul>
<li><code>allocator</code> - The allocator to be used. This is required if your data type has any pointers, slices, etc.</li>
<li><code>duplicate_field_behavior</code> - How to handle duplicate fields (<code>.UseFirst</code>, <code>.Error</code>).<ul>
<li><code>.UseFirst</code> - Use the first field.</li>
<li><code>.Error</code> - Return an error if there are multiple fields with the same name.</li>
</ul>
</li>
<li><code>ignore_unknown_fields</code> - Ignore unknown fields (default is <code>true</code>).</li>
<li><code>field_settings</code> - Lets you specify aliases for struct fields. Examples on how to use <code>field_settings</code> can be found in the <em>examples</em> directory and within defined tests.</li>
<li><code>ignore_override</code> - Flag to break infinity loops. This has to be set to <code>true</code> if you override the behavior using <code>cborParse</code> or <code>cborStringify</code>.</li>
</ul>
Builder
You can also dynamically create CBOR data using the <code>Builder</code>.
```zig
const allocator = std.testing.allocator;
var b = try Builder.withType(allocator, .Map);
try b.pushTextString("a");
try b.pushInt(1);
try b.pushTextString("b");
try b.enter(.Array);
try b.pushInt(2);
try b.pushInt(3);
//try b.leave(); <-- you can leave out the return at the end
const x = try b.finish();
defer allocator.free(x);
// { "a": 1, "b": [2, 3] }
try std.testing.expectEqualSlices(u8, "\xa2\x61\x61\x01\x61\x62\x82\x02\x03", x);
```
Commands
<ul>
<li>The <code>push*</code> functions append a data item</li>
<li>The <code>enter</code> function takes a container type and pushes it on the builder stack</li>
<li>The <code>leave</code> function leaves the current container. The container is appended to the wrapping container</li>
<li>The <code>finish</code> function returns the CBOR data as owned slice</li>
</ul>
Overriding stringify
You can override the <code>stringify</code> function for structs and tagged unions by implementing <code>cborStringify</code>.
```zig
const Foo = struct {
x: u32 = 1234,
y: struct {
a: []const u8 = "public-key",
b: u64 = 0x1122334455667788,
},
<code>pub fn cborStringify(self: *const @This(), options: Options, out: anytype) !void {
// First stringify the 'y' struct
const allocator = std.testing.allocator;
var o = std.ArrayList(u8).init(allocator);
defer o.deinit();
try stringify(self.y, options, o.writer());
// Then use the Builder to alter the CBOR output
var b = try build.Builder.withType(allocator, .Map);
try b.pushTextString("x");
try b.pushInt(self.x);
try b.pushTextString("y");
try b.pushByteString(o.items);
const x = try b.finish();
defer allocator.free(x);
try out.writeAll(x);
}
</code>
};
```
The <code>StringifyOptions</code> can be used to indirectly pass an <code>Allocator</code> to the function.
Please make sure to set <code>ignore_override</code> to <code>true</code> when calling recursively into <code>stringify(self)</code> to prevent infinite loops.
Overriding parse
You can override the <code>parse</code> function for structs and tagged unions by implementing <code>cborParse</code>. This is helpful if you have aliases for your struct members.
```zig
const EcdsaP256Key = struct {
/// kty:
kty: u8 = 2,
/// alg:
alg: i8 = -7,
/// crv:
crv: u8 = 1,
/// x-coordinate
x: [32]u8,
/// y-coordinate
y: [32]u8,
<code>pub fn cborParse(item: DataItem, options: Options) !@This() {
_ = options;
return try parse(@This(), item, .{
.ignore_override = true, // prevent infinite loops
.field_settings = &.{
.{ .name = "kty", .field_options = .{ .alias = "1" } },
.{ .name = "alg", .field_options = .{ .alias = "3" } },
.{ .name = "crv", .field_options = .{ .alias = "-1" } },
.{ .name = "x", .field_options = .{ .alias = "-2" } },
.{ .name = "y", .field_options = .{ .alias = "-3" } },
},
});
}
</code>
};
```
The <code>Options</code> can be used to indirectly pass an <code>Allocator</code> to the function.
Please make sure to set <code>ignore_override</code> to <code>true</code> when calling recursively into <code>parse(self)</code> to prevent infinite loops.
Structs with fields of type <code>std.mem.Allocator</code>
If you have a struct with a field of type <code>std.mem.Allocator</code> you have to override the <code>stringify</code>
funcation for that struct, e.g.:
```zig
pub fn cborStringify(self: *const @This(), options: cbor.StringifyOptions, out: anytype) !void {
_ = options;
<code>try cbor.stringify(self, .{
.ignore_override = true,
.field_settings = &.{
.{ .name = "allocator", .options = .{ .skip = true } },
},
}, out);
</code>
}
```
When using <code>parse</code> make sure you pass a allocator to the function. The passed allocator will be assigned
to the field of type <code>std.mem.Allocator</code>.
ArrayBackedSlice
This library offers a convenient function named ArrayBackedSlice, which enables you to create a wrapper for an array of any size and type. This wrapper implements the cborStringify and cborParse methods, allowing it to seamlessly replace slices (e.g., []const u8) with an array.
```zig
test "ArrayBackedSlice test" {
const allocator = std.testing.allocator;
<code>const S64B = ArrayBackedSlice(64, u8, .Byte);
var x = S64B{};
try x.set("\x01\x02\x03\x04");
var str = std.ArrayList(u8).init(allocator);
defer str.deinit();
try stringify(x, .{}, str.writer());
try std.testing.expectEqualSlices(u8, "\x44\x01\x02\x03\x04", str.items);
const di = try DataItem.new(str.items);
const y = try parse(S64B, di, .{});
try std.testing.expectEqualSlices(u8, "\x01\x02\x03\x04", y.get());
</code>
}
``` | [
"https://github.com/Zig-Sec/keylib",
"https://github.com/kj4tmp/gatorcat",
"https://github.com/r4gus/ccdb",
"https://github.com/uzyn/passcay"
] |
https://avatars.githubusercontent.com/u/65570835?v=4 | antiphony | ziglibs/antiphony | 2022-02-22T15:39:09Z | A zig remote procedure call solution | master | 0 | 41 | 1 | 41 | https://api.github.com/repos/ziglibs/antiphony/tags | MIT | [
"rpc",
"rpc-framework",
"zig",
"zig-package",
"ziglang"
] | 8,194 | false | 2025-05-17T14:09:17Z | true | true | unknown | github | [
{
"commit": "b30205d5e9204899fb6d0fdf28d00ed4d18fe9c9.tar.gz",
"name": "s2s",
"tar_url": "https://github.com/ziglibs/s2s/archive/b30205d5e9204899fb6d0fdf28d00ed4d18fe9c9.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ziglibs/s2s"
}
] | Antiphony
A simple Zig remote procedure call library.
Features
<ul>
<li>Transport layer agnostic</li>
<li>Support for nearly every non-generic function signature.</li>
<li>Nestable remote calls (peer calls host calls peer calls host calls ...)</li>
<li>Easy to use</li>
</ul>
API
```zig
// (comptime details left out for brevity)
pub fn CreateDefinition(spec: anytype) type {
return struct {
pub fn HostEndPoint(Reader: type, Writer: type, Implementation: type) type {
return CreateEndPoint(.host, Reader, Writer, Implementation);
}
pub fn ClientEndPoint(Reader: type, Writer: type, Implementation: type) type {
return CreateEndPoint(.client, Reader, Writer, Implementation);
}
pub fn CreateEndPoint(role: Role, ReaderType: type, WriterType: type, ImplementationType: type) type {
return struct {
const EndPoint = @This();
<code> pub const Reader = Reader;
pub const Writer = Writer;
pub const Implementation = Implementation;
pub const IoError = error{ ... };
pub const ProtocolError = error{ ... };
pub const InvokeError = error{ ... };
pub const ConnectError = error{ ... };
pub fn init(allocator: std.mem.Allocator, reader: Reader, writer: Writer) EndPoint;
pub fn destroy(self: *EndPoint) void;
pub fn connect(self: *EndPoint, impl: *Implementation) ConnectError!void;
pub fn shutdown(self: *EndPoint) IoError!void;
pub fn acceptCalls(self: *EndPoint) InvokeError!void;
pub fn invoke(self: *EndPoint, func_name: []const u8, args: anytype) InvokeError!Result(func_name);
};
}
};
</code>
}
// Example for CreateDefinition(spec):
const Definition = antiphony.CreateDefinition(.{
.host = .{
// add all functions the host implements:
.createCounter = fn () CreateError!u32,
.destroyCounter = fn (u32) void,
.increment = fn (u32, u32) UsageError!u32,
.getCount = fn (u32) UsageError!u32,
},
.client = .{
// add all functions the client implements:
.signalError = fn (msg: []const u8) void,
},
<code>// this is optional and can be left out:
.config = .{
// defines how to handle remote error sets:
.merge_error_sets = true,
},
</code>
});
```
Project Status
This project is currently in testing phase, all core features are already implemented and functional.
Contribution
Contributions are welcome as long as they don't change unnecessarily increase the complexity of the library. This library is meant to be the bare minimum RPC implementation that is well usable. Bug fixes and updates to new versions are always welcome.
Compile and run the examples
<code>sh-session
[user@host antiphony]$ zig build install
[user@host antiphony]$ ./zig-out/bin/socketpair-example
info: first increment: 0
info: second increment: 5
info: third increment: 8
info: final count: 15
error: remote error: This counter was already deleted!
info: error while calling getCount() with invalid handle: UnknownCounter
[user@host antiphony]$</code>
Run the test suite
<code>sh-session
[user@host antiphony]$ zig build test
Test [3/6] test "invoke function (emulated client, no self parameter)"... some(1334, 3.1415927410125732, "Hello, Host!");
Test [4/6] test "invoke function (emulated client, with self parameter)"... some(123, 1334, 3.1415927410125732, "Hello, Host!");
Test [5/6] test "invoke function with callback (emulated host, no self parameter)"... callback("Hello, World!");
Test [6/6] test "invoke function with callback (emulated host, with self parameter)"... callback(ClientImpl@7ffd33f6cdc0, "Hello, World!");
All 6 tests passed.
[user@host antiphony]$</code> | [] |
https://avatars.githubusercontent.com/u/33050391?v=4 | tree-fmt | speed2exe/tree-fmt | 2023-01-23T11:11:42Z | Tree-like pretty formatter for Zig | main | 0 | 40 | 0 | 40 | https://api.github.com/repos/speed2exe/tree-fmt/tags | Apache-2.0 | [
"zig-library",
"zig-package"
] | 1,287 | false | 2025-03-22T22:40:55Z | true | false | unknown | github | [] | Tree Formattar for Zig
<ul>
<li>Pretty prints out Zig Values for your debugging needs.</li>
<li>If you faces any issue with formatting, kindly open an issue.</li>
</ul>
Versioning
<ul>
<li>Current <code>main</code> branch tracks zig latest version</li>
<li>If you need a stable version, see release tags</li>
</ul>
Objective
<ul>
<li>Provide a colored tree-like visual representation of a Zig value to aid in debugging.</li>
</ul>
Features
<ul>
<li>Colored output to distinguish between types and values</li>
<li>Indentation to show the structure of the value</li>
<li>Special formatters for following types (Do file a PR or FR if you think there are more types that can require special formatting)</li>
<li><code>std.MultiArrayList</code></li>
<li><code>std.HashMapUnmanaged</code></li>
</ul>
Screenshot
Example
<ul>
<li>You can run on of the examples in the <code>examples</code> by executing the following command:
<code>bash
zig build test -Dtest-filter="anon struct 1"</code></li>
<li>You might need to require to remove <code>zig-cache</code> to run it again without changes.</li>
</ul>
Usage
<ul>
<li>Zig Package Manager Example: https://github.com/speed2exe/tree-fmt-example</li>
<li><code>zig.build.zon</code>
<code>zon
.{
.name = "your_package_name",
.version = "0.0.1",
.dependencies = .{
.tree_fmt = .{
// c6398b225f15cdbe35b3951920f634ffd1c65c12 is just commit hash
.url = "https://github.com/speed2exe/tree-fmt/archive/c6398b225f15cdbe35b3951920f634ffd1c65c12.tar.gz",
// just do `zig build`, get the error code and replace with expected hash
.hash = "12201dceb9a9c2c9a6fc83105a7f408132b9ab69173b266e7df2af2c1dd6f814cd51",
},
},
.paths = .{ "" },
}</code></li>
<li><code>build.zig</code>
<code>zig
pub fn build(b: *std.Build) void {
// ...
const dep = b.dependency("tree_fmt", .{});
const tree_fmt = dep.module("tree-fmt");
your_program.root_module.addImport("tree-fmt", tree_fmt);
}</code></li>
</ul>
Quick Setup
<ul>
<li>Fastest and easiest way to if you want to save time and effort.</li>
<li>This example is in <code>example_default_tree_formatter.zig</code></li>
</ul>
```zig
var tree_formatter = @import("tree-fmt").defaultFormatter();
pub fn main() !void {
const my_struct = .{ 1, 2.4, "hi" };
try tree_formatter.format(my_struct, .{
.name = "my_struct", // (optional) just an identifier to the root of the tree
});
}
<code>- Output:</code>
some_anon_struct: tuple{comptime comptime_int = 1, comptime comptime_float = 2.4, comptime <em>const [2:0]u8 = "hi"}
├─.0: comptime_int => 1
├─.1: comptime_float => 2.4e+00
└─.2: </em>const [2:0]u8 @21d169
└─.*: [2:0]u8 hi
├─[0]: u8 => 104
└─[1]: u8 => 105
```
Proper Setup
<ul>
<li>This is recommended, as it gives you more control over writer, allocator and settings.</li>
</ul>
```zig
const std = @import("std");
// add imports here
const treeFormatter = @import("tree-fmt").treeFormatter;
pub fn main() !void {
// initialize your allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer {
const leaked = gpa.deinit();
if (leaked) {
@panic("leaked memory!");
}
}
<code>// initialize a writer (std.io.Writer)
// tips if you print a lot: wrap with std.io.BufferedWriter to improve performance
var w = std.io.getStdOut().writer();
// initialize TreeFormatter with allocator and writer
var tree_formatter = treeFormatter(allocator, w);
// initialize your value
var sentinel_array: [*:0]const u8 = "hello world";
// call the method with writer and value
try tree_formatter.formatValueWithId(sentinel_array, .{
// .name = "sentinel_array", <-- example setting
// you can find settings at @import("./src/tree_fmt.zig").TreeFormatterSettings;
// you can also leave it blank to use default settings
});
</code>
}
```
<ul>
<li>
Output:
<code>sentinel_array: [*:0]const u8 @20a71e "hello world"
├─[0]: u8 => 104
├─[1]: u8 => 101
├─[2]: u8 => 108
├─[3]: u8 => 108
├─[4]: u8 => 111
├─[5]: u8 => 32
├─[6]: u8 => 119
├─[7]: u8 => 111
├─[8]: u8 => 114
├─[9]: u8 => 108
└─... (showed first 10 out of 11 items only)</code>
</li>
<li>
You can find other examples in the <code>examples</code> directory. To run specific example(s):
<code>bash
zig build test -Dtest-filter="name of test"
# e.g. zig build test -Dtest-filter="anon struct 1"</code>
</li>
</ul>
Example
<ul>
<li>
<code>std.ArrayList(u8)</code>
<code>.: array_list.ArrayListAligned(u8,null)
├─.items: []u8 @7efcc912f000
│ ├─[0]: u8 => 0
│ ├─[1]: u8 => 1
│ ├─[2]: u8 => 2
│ ├─[3]: u8 => 3
│ ├─[4]: u8 => 4
│ └─... (showed first 5 out of 100 items only)
├─.capacity: usize => 105
└─.allocator: mem.Allocator
├─.ptr: *anyopaque @7fffadc5b3d8
└─.vtable: *const mem.Allocator.VTable @202a38
└─.*: mem.Allocator.VTable
├─.alloc: *const fn(*anyopaque, usize, u8, usize) ?[*]u8 @238e00
├─.resize: *const fn(*anyopaque, []u8, u8, usize, usize) bool @2393c0
└─.free: *const fn(*anyopaque, []u8, u8, usize) void @23a2d0</code>
</li>
<li>
<code>std.AutoHashMap(u8, u8)</code>
<code>map: hash_map.HashMap(u8,u8,hash_map.AutoContext(u8),80)
├─.unmanaged: hash_map.HashMapUnmanaged(u8,u8,hash_map.AutoContext(u8),80)
│ ├─.iterator()
│ │ ├─.next(): hash_map.HashMapUnmanaged(u8,u8,hash_map.AutoContext(u8),80).Entry
│ │ │ ├─.key_ptr: *u8 @7fcad47f5021
│ │ │ │ └─.*: u8 => 1
│ │ │ └─.value_ptr: *u8 @7fcad47f5029
│ │ │ └─.*: u8 => 2
│ │ ├─.next(): hash_map.HashMapUnmanaged(u8,u8,hash_map.AutoContext(u8),80).Entry
│ │ │ ├─.key_ptr: *u8 @7fcad47f5022
│ │ │ │ └─.*: u8 => 0
│ │ │ └─.value_ptr: *u8 @7fcad47f502a
│ │ │ └─.*: u8 => 0
│ │ └─.next(): hash_map.HashMapUnmanaged(u8,u8,hash_map.AutoContext(u8),80).Entry
│ │ ├─.key_ptr: *u8 @7fcad47f5026
│ │ │ └─.*: u8 => 2
│ │ └─.value_ptr: *u8 @7fcad47f502e
│ │ └─.*: u8 => 4
│ ├─.metadata: ?[*]hash_map.HashMapUnmanaged(u8,u8,hash_map.AutoContext(u8),80).Metadata
│ │ └─.?: [*]hash_map.HashMapUnmanaged(u8,u8,hash_map.AutoContext(u8),80).Metadata @7fcad47f5018
│ ├─.size: u32 => 3
│ └─.available: u32 => 3
├─.allocator: mem.Allocator
│ ├─.ptr: *anyopaque @7ffc3b6baca0
│ └─.vtable: *const mem.Allocator.VTable @2045b8
│ └─.*: mem.Allocator.VTable
│ ├─.alloc: *const fn(*anyopaque, usize, u8, usize) ?[*]u8 @2433a0
│ ├─.resize: *const fn(*anyopaque, []u8, u8, usize, usize) bool @243960
│ └─.free: *const fn(*anyopaque, []u8, u8, usize) void @244870
└─.ctx: hash_map.AutoContext(u8) => .{}</code>
</li>
<li>
<code>std.MultiArrayList...</code> (see <code>example_multi_array_list.zig</code>)
<code>multi_array_list: multi_array_list.MultiArrayList(example_multi_array_list.Person)
├─.slice(): multi_array_list.MultiArrayList(example_multi_array_list.Person).Slice
│ └─.items
│ ├─(.id): []u64 @7f8cf20c3000
│ │ ├─[0]: u64 => 0
│ │ ├─[1]: u64 => 1
│ │ ├─[2]: u64 => 2
│ │ ├─[3]: u64 => 3
│ │ ├─[4]: u64 => 4
│ │ └─... (showed first 5 out of 7 items only)
│ ├─(.age): []u8 @7f8cf20c3080
│ │ ├─[0]: u8 => 0
│ │ ├─[1]: u8 => 1
│ │ ├─[2]: u8 => 2
│ │ ├─[3]: u8 => 3
│ │ ├─[4]: u8 => 4
│ │ └─... (showed first 5 out of 7 items only)
│ └─(.car): []example_multi_array_list.Car @7f8cf20c3040
│ ├─[0]: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─[1]: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─[2]: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─[3]: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─[4]: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ └─... (showed first 5 out of 7 items only)
├─.get
│ ├─(0): example_multi_array_list.Person
│ │ ├─.id: u64 => 0
│ │ ├─.age: u8 => 0
│ │ └─.car: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─(1): example_multi_array_list.Person
│ │ ├─.id: u64 => 1
│ │ ├─.age: u8 => 1
│ │ └─.car: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─(2): example_multi_array_list.Person
│ │ ├─.id: u64 => 2
│ │ ├─.age: u8 => 2
│ │ └─.car: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ ├─(3): example_multi_array_list.Person
│ │ ├─.id: u64 => 3
│ │ ├─.age: u8 => 3
│ │ └─.car: example_multi_array_list.Car
│ │ └─.license_plate_no: u64 => 555
│ └─... (showed first 4 out of 7 items only)
├─.bytes: [*]align(8) u8 @7f8cf20c3000
├─.len: usize => 7
└─.capacity: usize => 8</code>
</li>
<li>
<code>multi_array_list.MultiArrayList(zig.Ast.TokenList__struct_4206).Slice</code>
<code>ast: multi_array_list.MultiArrayList(zig.Ast.TokenList__struct_4200).Slice
├─.toMultiArrayList(): multi_array_list.MultiArrayList(zig.Ast.TokenList__struct_4200)
│ ├─.slice(): multi_array_list.MultiArrayList(zig.Ast.TokenList__struct_4200).Slice
│ │ └─.items
│ │ ├─(.tag): []zig.tokenizer.Token.Tag @7ff3c81f7098
│ │ │ ├─[0]: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.keyword_const (86)
│ │ │ ├─[1]: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.identifier (2)
│ │ │ ├─[2]: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.equal (12)
│ │ │ ├─[3]: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.builtin (7)
│ │ │ ├─[4]: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.l_paren (16)
│ │ │ └─... (showed first 5 out of 31 items only)
│ │ └─(.start): []u32 @7ff3c81f7000
│ │ ├─[0]: u32 => 1
│ │ ├─[1]: u32 => 7
│ │ ├─[2]: u32 => 11
│ │ ├─[3]: u32 => 13
│ │ ├─[4]: u32 => 20
│ │ └─... (showed first 5 out of 31 items only)
│ ├─.get
│ │ ├─(0): zig.Ast.TokenList__struct_4200
│ │ │ ├─.tag: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.keyword_const (86)
│ │ │ └─.start: u32 => 1
│ │ ├─(1): zig.Ast.TokenList__struct_4200
│ │ │ ├─.tag: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.identifier (2)
│ │ │ └─.start: u32 => 7
│ │ ├─(2): zig.Ast.TokenList__struct_4200
│ │ │ ├─.tag: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.equal (12)
│ │ │ └─.start: u32 => 11
│ │ ├─(3): zig.Ast.TokenList__struct_4200
│ │ │ ├─.tag: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.builtin (7)
│ │ │ └─.start: u32 => 13
│ │ ├─(4): zig.Ast.TokenList__struct_4200
│ │ │ ├─.tag: zig.tokenizer.Token.Tag => zig.tokenizer.Token.Tag.l_paren (16)
│ │ │ └─.start: u32 => 20
│ │ └─... (showed first 5 out of 31 items only)
│ ├─.bytes: [*]align(4) u8 @7ff3c81f7000
│ ├─.len: usize => 31
│ └─.capacity: usize => 38
├─.ptrs: [2][*]u8
│ ├─[0]: [*]u8 @7ff3c81f7098
│ └─[1]: [*]u8 @7ff3c81f7000
├─.len: usize => 31
└─.capacity: usize => 38</code>
</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/34946442?v=4 | marble | cryptocode/marble | 2022-03-20T12:47:11Z | A metamorphic testing library for Zig | main | 0 | 39 | 2 | 39 | https://api.github.com/repos/cryptocode/marble/tags | MIT | [
"metamorphic-testing",
"testing",
"testing-tool",
"testing-tools",
"zig",
"zig-library",
"zig-package"
] | 24 | false | 2025-03-25T01:37:34Z | true | true | unknown | github | [] |
Marble is a <a>metamorphic testing</a> library for Zig.
This library tracks Zig master and was last tested on <code>0.14.0-dev.3187+d4c85079c</code>
Metamorphic testing is a powerful technique that provides additional test coverage by applying a number of transformations to test input, and then checking if certain relations still hold between the outputs. Marble will automatically run through all possible combinations of these transformations.
Here's a <a>great introduction by</a> Cockroach Labs. I highly recommend reading before using this library.
The repository contains a few <a>test examples</a>
Resources
<ul>
<li><a>Hillel Wayne's blog post on Metamorphic Testing (highly recommended)</a></li>
<li><a>Test your Machine Learning Algorithm with Metamorphic Testing</a></li>
<li><a>Original paper by T.Y. Chen et al</a></li>
<li><a>Case study T.Y. Chen et al</a></li>
<li><a>Metamorphic Testing and Beyond T.Y. Chen et al</a></li>
<li><a>Survey on Metamorphic Testing</a></li>
<li><a>Performance Metamorphic Testing</a></li>
<li><a>Experiences from Three Fuzzer Tools</a></li>
<li><a>Monarch, a similar library for Rust</a></li>
</ul>
Building
To build and run test examples:
<code>bash
zig build
zig build test</code>
Importing the library
Add Marble as a Zig package in your build file, or simply import it directly after vendoring/adding a submodule:
<code>zig
const marble = @import("marble/main.zig");</code>
Writing tests
A metamorphic Zig test looks something like this:
```zig
const SinusTest = struct {
const tolerance = std.math.epsilon(f64) * 20;
<code>/// This test has a single value, but you could also design the test to take an
/// array as input. The transformations, check and execute functions would then
/// loop through them all. Alternatively, the test can be run multiple times
/// with different inputs.
value: f64,
/// The mathematical property "sin(x) = sin(π − x)" must hold
pub fn transformPi(self: *SinusTest) void {
self.value = std.math.pi - self.value;
}
/// Adding half the epsilon must still cause the relation to hold given the tolerance
pub fn transformEpsilon(self: *SinusTest) void {
self.value = self.value + std.math.epsilon(f64) / 2.0;
}
/// A metamorphic relation is a relation between outputs in different executions.
/// This relation must hold after every execution of transformation combinations.
pub fn check(_: *SinusTest, original_output: f64, transformed_output: f64) bool {
return std.math.approxEqAbs(f64, original_output, transformed_output, tolerance);
}
/// Called initially to compute the baseline output, and after every transformation combination
pub fn execute(self: *SinusTest) f64 {
return std.math.sin(self.value);
}
</code>
};
test "sinus" {
var i: f64 = 1;
while (i < 100) : (i += 1) {
var t = SinusTest{ .value = i };
try std.testing.expect(try marble.run(SinusTest, &t, .{}));
}
}
```
You will get compile time errors if the requirements for a metamorphic test are not met.
In short, you must provide a <code>value</code> field, a <code>check</code> function, an <code>execute</code> function and one or more <code>transform...</code> functions.
Writing transformations
Add one or more functions starting with <code>transform...</code>
Marble will execute all combinations of the transformation functions. After every
combination, <code>execute</code> is called followed by <code>check</code>.
Transformations should change the <code>value</code> property - Marble will remember what it was originally. The transformations must be such that <code>check</code>
succeeds. That is, the relations between the inital output and the transformed output must still hold.
Checking if relations still hold
You must provide a <code>check</code> function to see if one or more relations hold, and return true if so. If false is returned, the test fails with a print-out of the current transformation-combination.
Relation checks may be conditional; check out the tests for examples on how this works.
Executing
You must provide an <code>execute</code> function that computes a result based on the current value. The simplest form will simply return the current value, but you can
do any arbitrary operation here. This function is called before any transformations to form a baseline. This baseline is passed as the first argument to <code>check</code>
Optional before/after calls
Before and after the test, and every combination, <code>before(...)</code> and <code>after(...)</code> is called if present. This is useful to reset state, initialize test cases, and perform clean-up.
What happens during a test run?
Using the example above, the following pseudocode runs will be performed:
```
baseline = execute()
// First combination
transformPi()
out = execute()
check(baseline, out)
// Second combination
transformEpsilon()
out = execute()
check(baseline, out)
// Third combination
transformPi()
transformEpsilon()
out = execute()
check(baseline, out)
```
Configuring runs
The <code>run</code> function takes a <code>RunConfiguration</code>:
```zig
/// If set to true, only run each transformation once separately
skip_combinations: bool = false,
/// If true, print detailed information during the run
verbose: bool = false,
```
Error reporting
If a test fails, the current combination being executed is printed. For instance, the following tells us that the combination of <code>transformAdditionalTerm</code> and <code>transformCase</code> caused the metamorphic relation to fail:
```
Test [2/2] test "query"... Test case failed with transformation(s):
<blockquote>
<blockquote>
transformAdditionalTerm
transformCase
```
</blockquote>
</blockquote>
Terminology
<ul>
<li>Source test case output: The output produced by <code>execute()</code> on the initial input. This is also known as the baseline.</li>
<li>Derived test case output: The output produced by <code>execute()</code> after applying a specific combination of transformations.</li>
<li>Metamorphic relation: A property that must hold when considering a source test case and a derived test case.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/65322356?v=4 | zig-lsp-codegen | zigtools/zig-lsp-codegen | 2022-05-30T05:57:32Z | LSP codegen based on the MetaModel | main | 0 | 37 | 15 | 37 | https://api.github.com/repos/zigtools/zig-lsp-codegen/tags | MIT | [
"lsp",
"zig",
"zig-package"
] | 280 | false | 2025-04-30T17:33:10Z | true | true | 0.14.0 | github | [] | <a></a>
<a></a>
<a></a>
<a></a>
Zig LSP Codegen
Generates <code>std.json</code> compatible Zig code based on the official <a>LSP MetaModel</a>
Installation
<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>
The minimum supported Zig version is <code>0.14.0</code>.
</blockquote>
```bash
Initialize a <code>zig build</code> project if you haven't already
zig init
Add the <code>lsp_codegen</code> package to your <code>build.zig.zon</code>
zig fetch --save git+https://github.com/zigtools/zig-lsp-codegen.git
```
You can then import <code>lsp_codegen</code> in your <code>build.zig</code> with:
<code>zig
const lsp_codegen = b.dependency("lsp_codegen", .{});
const exe = b.addExecutable(...);
exe.root_module.addImport("lsp", lsp_codegen.module("lsp"));</code> | [] |
https://avatars.githubusercontent.com/u/15983269?v=4 | zig-nanoid | SasLuca/zig-nanoid | 2022-04-18T22:32:31Z | A tiny, secure, URL-friendly, unique string ID generator. Now available in pure Zig. | main | 1 | 30 | 3 | 30 | https://api.github.com/repos/SasLuca/zig-nanoid/tags | MIT | [
"id",
"nanoid",
"random",
"unique-id",
"unique-identifier",
"uniqueid",
"url",
"uuid",
"uuid-generator",
"zig",
"zig-package",
"ziglang"
] | 59 | false | 2025-03-27T18:32:48Z | true | false | unknown | github | [] | Nano ID in Zig
<a></a>
<a></a>
A battle-tested, tiny, secure, URL-friendly, unique string ID generator. Now available in pure Zig.
<ul>
<li><strong>Freestanding.</strong> zig-nanoid is entirely freestanding.</li>
<li><strong>Fast.</strong> The algorithm is very fast and relies just on basic math, speed will mostly depend on your choice of RNG.</li>
<li><strong>Safe.</strong> It can use any random generator you want and the library has no errors to handle.</li>
<li><strong>Short IDs.</strong> It uses a larger alphabet than UUID (<code>A-Za-z0-9_-</code>). So ID length was reduced from 36 to 21 symbols and it is URL friendly.</li>
<li><strong>Battle Tested.</strong> Original implementation has over 18 million weekly downloads on <a>npm</a>.</li>
<li><strong>Portable.</strong> Nano ID was ported to <a>20+ programming languages</a>.</li>
</ul>
Example
Basic usage with <code>std.crypto.random</code>:
```zig
const std = @import("std");
const nanoid = @import("nanoid");
pub fn main() !void
{
const result = nanoid.generate(std.crypto.random);
<code>std.log.info("Nanoid: {s}", .{result});
</code>
}
```
Comparison to UUID
Nano ID is quite comparable to UUID v4 (random-based).
It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability.
It also uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.
For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.
How to use
Generating an id with the default size
The simplest way to generate an id with the default alphabet and length is by using the function <code>generate</code> like so:
<code>zig
const result = nanoid.generate(std.crypto.random);</code>
If you want a custom alphabet you can use <code>generateWithAlphabet</code> and pass either a custom alphabet or one from <code>nanoid.alphabets</code>:
<code>zig
const result = nanoid.generateWithAlphabet(std.crypto.random, nanoid.alphabets.numbers); // This id will only contain numbers</code>
You can find a variety of other useful alphabets inside of <code>nanoid.alphabets</code>.
The result is an array of size <code>default_id_len</code> which happens to be 21 which is returned by value.
There are no errors to handle, assuming your rng object is valid everything will work.
The default alphabet includes the symbols "-_", numbers and English lowercase and uppercase letters.
Generating an id with a custom size
If you want a custom alphabet and length use <code>generateEx</code> or <code>generateExWithIterativeRng</code>.
The function <code>generateEx</code> takes an rng, an <code>alphabet</code>, a <code>result_buffer</code> that it will write the id to, and a <code>step_buffer</code>.
The <code>step_buffer</code> is used by the algorithm to store a random bytes so it has to do less calls to the rng and <code>step_buffer.len</code> must be at
least <code>computeRngStepBufferLength(computeMask(@truncate(u8, alphabet.len)), result_buffer.len, alphabet.len)</code>.
The function <code>generateExWithIterativeRng</code> is the same as <code>generateEx</code> except it doesn't need a <code>step_buffer</code>. It will use <code>Random.int(u8)</code>
instead of <code>Random.bytes()</code> to get a random byte at a time thus avoiding the need for a rng step buffer. Normally this will be slower but
depending on your rng algorithm or other requirements it might not be, so the option is there in case you need but normally it is
recommended you use <code>generateEx</code> which requires a temporary buffer that will be filled using <code>Random.bytes()</code> in order to get the best
performance.
Additionally you can precompute a sufficient length for the <code>step_buffer</code> and pre-allocate it as an optimization using
<code>computeSufficientRngStepBufferLengthFor</code> which simply asks for the largest possible id length you want to generate.
If you intend to use the <code>default_id_len</code>, you can use the constant <code>nanoid.rng_step_buffer_len_sufficient_for_default_length_ids</code>.
Regarding RNGs
You will need to provide an random number generator (rng) yourself. You can use the zig standard library ones, either <code>std.rand.DefaultPrng</code>
or if you have stricter security requirements use <code>std.rand.DefaultCsprng</code> or <code>std.crypto.random</code>.
When you initialize them you need to provide a seed, providing the same one every time will result in the same ids being generated every
time you run the program, except for <code>std.crypto.random</code>.
If you want a good secure seed you can generate one using <code>std.crypto.random.bytes</code>.
Here is an example of how you would initialize and seed <code>std.rand.DefaultCsprng</code> and use it:
```zig
// Generate seed
var seed: [std.rand.DefaultCsprng.secret_seed_length]u8 = undefined;
std.crypto.random.bytes(&seed);
// Initialize the rng and allocator
var rng = std.rand.DefaultCsprng.init(seed);
// Generate id
var id = nanoid.generate(rng.random());
```
Add zig-nanoid to your project
Manually
To add the library as a package to your zig project:
1. Download the repo and put it in a folder (eg: <code>thirdparty</code>) in your project.
2. Import the library's <code>build.zig</code> in your build script (eg: <code>const nanoid = @import("thirdparty/nanoid-zig/build.zig");</code>)
3. Add the library as a package to your steps (eg: <code>exe.addPackage(nanoid.getPackage("nanoid"));</code>)
Full example:
```zig
// build.zig
const std = @import("std");
const nanoid = @import("thirdparty/zig-nanoid/build.zig");
pub fn build(b: *std.build.Builder) void
{
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
<code>const exe = b.addExecutable("zig-nanoid-test", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.addPackage(nanoid.getPackage("nanoid"));
exe.install();
</code>
}
```
Using the gyro package manager
We support the zig <a>gyro package manager</a>.
Here is how to use it:
<ol>
<li>
From your terminal initialize a gyro project and add the package <code>SasLuca/nanoid</code>.
<code>gyro init
gyro add SasLuca/nanoid</code>
</li>
<li>
In your <code>build.zig</code> do an import like so <code>const pkgs = @import("deps.zig").pkgs;</code> and call <code>pkgs.addAllTo(exe);</code> to add all libraries to your executable (or some other target).
</li>
<li>
Import <code>const nanoid = @import("nanoid");</code> in your <code>main.zig</code> and use it.
</li>
<li>
Invoke <code>gyro build run</code> which will generate <code>deps.zig</code> and other files as well as building and running your project.
</li>
</ol>
Useful links
<ul>
<li>
Original implementation: https://github.com/ai/nanoid
</li>
<li>
Online Tool: https://zelark.github.io/nano-id-cc/
</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/3932972?v=4 | zig-mqtt | ikskuh/zig-mqtt | 2022-05-18T06:37:23Z | A build package for mqtt-c. | master | 0 | 23 | 5 | 23 | https://api.github.com/repos/ikskuh/zig-mqtt/tags | MIT | [
"iot",
"mqtt",
"protocol",
"zig",
"zig-package"
] | 5 | false | 2025-01-16T01:41:46Z | true | false | unknown | github | [] | zig-mqtt
A build package for the awesome <a>mqtt-c</a> project by <a>Liam Bindle</a>.
Right now only provides a build script API in <code>Sdk.zig</code>, but might contain a Zig frontend in the future.
Usage
```zig
const std = @import("std");
const Sdk = @import("Sdk.zig");
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
<code>const lib = Sdk.createLibrary(b);
lib.setBuildMode(mode);
lib.setTarget(target);
lib.install();
const exe = b.addExecutable(…);
exe.linkLibary(lib);
exe.addIncludePath(Sdk.include_path);
…
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/4075241?v=4 | zig-stable-array | rdunnington/zig-stable-array | 2022-08-26T14:17:35Z | Address-stable array with a max size that allocates directly from virtual memory. | main | 0 | 22 | 1 | 22 | https://api.github.com/repos/rdunnington/zig-stable-array/tags | NOASSERTION | [
"zig",
"zig-package"
] | 43 | false | 2025-04-21T06:21:55Z | true | true | unknown | github | [] | zig-stable-array
Address-stable array with a max size that allocates directly from virtual memory. Memory is only committed when actually used, and virtual page table mappings are relatively cheap, so you only pay for the memory that you're actually using. Additionally, since all memory remains inplace, and new memory is committed incrementally at the end of the array, there are no additional recopies of data made when the array is enlarged.
Ideal use cases are for large arrays that potentially grow over time. When reallocating a dynamic array with a high upper bound would be a waste of memory, and depending on dynamic resizing may incur high recopy costs due to the size of the array, consider using this array type. Another good use case is when stable pointers or slices to the array contents are desired; since the memory is never moved, pointers to the contents of the array will not be invalidated when growing. Not recommended for small arrays, since the minimum allocation size is the platform's minimum page size. Also not for use with platforms that don't support virtual memory, such as WASM.
Typical usage is to specify a large size up-front that the array should not encounter, such as 2GB+. Then use the array as usual. If freeing memory is desired, <code>shrinkAndFree()</code> will decommit memory at the end of the array. Total memory usage can be calculated with <code>calcTotalUsedBytes()</code>. The interface is very similar to ArrayList, except for the allocator semantics. Since typical heap semantics don't apply to this array, the memory is manually managed using mmap/munmap and VirtualAlloc/VirtualFree on nix and Windows platforms, respectively.
Usage:
<code>zig
var array = StableArray(u8).init(1024 * 1024 * 1024 * 128); // virtual address reservation of 128 GB
try array.appendSlice(&[_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
assert(array.calcTotalUsedBytes() == mem.page_size);
for (array.items) |v, i| {
assert(v == i);
}
array.shrinkAndFree(5);
assert(array.calcTotalUsedBytes() == mem.page_size);
array.deinit();</code> | [
"https://github.com/rdunnington/bytebox"
] |
https://avatars.githubusercontent.com/u/4678790?v=4 | zubench | dweiller/zubench | 2022-05-18T11:14:14Z | Micro benchmarking in zig | main | 1 | 21 | 4 | 21 | https://api.github.com/repos/dweiller/zubench/tags | MIT | [
"zig-package"
] | 55 | false | 2025-05-13T04:12:31Z | true | true | unknown | github | [] | zubench
A micro-benchmarking package for <a>Zig</a>.
goals
The primary goals of <strong>zubench</strong> are to:
<ul>
<li>be simple to use - there should be no need to wrap a function just to benchmark it</li>
<li>provide standard machine-readable output for archiving or post-processing</li>
<li>given the user the choice of which system clock(s) to use</li>
<li>provide statistically relevant and accurate results</li>
<li>integrate with the Zig build system</li>
</ul>
Not all these goals are currently met, and its always possible to debate how well they are met; feel free to open an issue (if one doesn't exist) or pull request if you would like to see improvement in one of these areas.
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> human-readable terminal-style output
<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> machine-readable JSON output
<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> wall, process, and thread time
<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> kernel/user mode times
<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> declarative <code>zig test</code> style benchmark runner
<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> option to define benchmarks as Zig tests
<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> adaptive sample sizes
<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> <a>MAD</a>-based outlier rejection
platforms
Some attempt has been made to work on the below platforms; those with a '️️️️️⚠️' in the table below haven't been tested, but <em>should</em> work for all implemented clocks. Windows currently only has the wall time clock implemented. If you find a non-Linux platform either works or has issues please raise an issue.
| Platform | Status |
| :------: | :----: |
| Linux | ✅ |
| Windows | ❗ |
| Darwin | ⚠️ |
| BSD | ⚠️ |
| WASI | ⚠️ |
usage
The <em>main</em> branch follows Zig's master branch, for Zig 0.12 use the <em>zig-0.12</em> branch.
The simplest way to create and run benchmarks is using one of the Zig build system integrations. There are currently two integrations, one utilising the Zig test system, and one utilising public declarations.
Both integrations will compile an executable that takes a collection of functions to benchmark, runs them repeatedly and reports timing statistics. The differences between the two integrations are how you define benchmarks in your source files, and how benchmarking options are determined.
test integration
The simplest way to define and run benchmarks is utilising the Zig test system. <strong>zubench</strong> will use a custom test runner to run the benchmarks. This means that benchmarks are simply Zig tests, i.e. <code>test { // code to benchmark }</code>. In order to avoid benchmarking regular tests when using this system, you should consider the way that Zig analyses test declarations and either give the names of benchmark tests a unique substring that can be used as a test filter or organise your tests so that when the compiller analyses the root file for benchmark tests, it will not analyse regular tests.
The following snippets show how you can use this integration.
```zig
const addTestBench = @import("zubench/build.zig").addTestBench;
pub fn build(b: *std.build.Builder) void {
// existing build function
// ...
<code>// benchmark all tests analysed by the compiler rooted in "src/file.zig", compiled in ReleaseSafe mode
const benchmark_exe = zubench.addTestBench(b, "src/file.zig", .ReleaseSafe);
// use a test filter to only benchmark tests whose name include the substring "bench"
// note that this is not required if the compiler will not analyse tests that you don't want to benchmark
benchmark_exe.setTestFilter("bench");
const bench_step = b.step("bench", "Run the benchmarks");
bench_step.dependOn(&benchmark_exe.run().step);
</code>
}
<code>This will make `zig build bench` benchmark tests the compiler analyses by starting at `src/file.zig`. `addTestBench()` returns a `*LibExeObjStep` for an executable that runs the benchmarks; you can integrate it into your `build.zig` however you wish. Benchmarks are `test` declarations the compiler analyses staring from `src/file.zig`:</code>zig
// src/file.zig
test "bench 1" {
// this will be benchmarked
// ...
}
test "also a benchmark" {
// this will be benchmarked
// ...
}
test {
// this will be benchmarked
// the test filter is ignored for unnamed tests
// ...
}
test "regular test" {
// this will not be benchmarked
return error.NotABenchmark;
}
```
public decl integration
This integration allows for fine-grained control over the execution of benchmarks, allowing you to specify various options as well as benchmark functions that take parameters.
The following snippets shows how you can use this integration.
```zig
// build.zig
const addBench = @import("zubench/build.zig").addBench;
pub fn build(b: *std.build.Builder) void {
// existing build function
// ...
<code>// benchmarks in "src/file.zig", compiled in ReleaseSafe mode
const benchmark_exe = addBench(b, "src/file.zig", .ReleaseSafe);
const bench_step = b.step("bench", "Run the benchmarks");
bench_step.dependOn(&benchmark_exe.run().step);
</code>
}
<code>This will make `zig build bench` run the benchmarks in `src/file.zig`, and print the results. `addBench()` returns a `*LibExeObjStep` for an executable that runs the benchmarks; you can integrate it into your `build.zig` however you wish. Benchmarks are specified in `src/file.zig` by creating a `pub const benchmarks` declaration:</code>zig
// add to src/file.zig
// the zubench package
const bench = @import("src/bench.zig");
pub const benchmarks = .{
.@"benchmark func1" = bench.Spec(func1){ .args = .{ arg1, arg2 }, .max_samples = 100 },
.@"benchmark func2" = bench.Spec(func2){
.args = .{ arg1, arg2, arg3 },
.max_samples = 1000,
.opts = .{ .outlier_detection = .none }}, // disable outlier detection
}
```
The above snippet would cause two benchmarks to be run called "benchmark func1" and "benchmark func2" for functions <code>func1</code> and <code>func2</code> respectively. The <code>.args</code> field of a <code>Spec</code> is a <code>std.meta.ArgsTuple</code> for the corresponding function, and <code>.max_samples</code> determines the maximum number of times the function is run during benchmarking. A complete example can be found in <code>examples/fib_build.zig</code>.
It is also relatively straightforward to write a standalone executable to perform benchmarks without using the build system integration. To create a benchmark for a function <code>func</code>, run it (measuring process and wall time) and obtain a report, all that is needed is
<code>zig
var progress = std.Progress.start(.{});
var bm = try Benchmark(func).init(allocator, "benchmark name", .{ func_arg_1, … }, .{}, max_samples, progress);
const report = bm.run();
bm.deinit();</code>
The <code>report</code> then holds a statistical summary of the benchmark and can used with <code>std.io.Writer.print</code> (for terminal-style readable output) or <code>std.json.stringify</code> (for JSON output). See <code>examples/</code> for complete examples.
Custom exectuable
It is also possible to write a custom benchmarking executable using <strong>zubench</strong> as a dependency. There is a simple example of this in <code>examples/fib2.zig</code> or, you can examine <code>src/bench_runner.zig</code>.
examples
Examples showing some ways of producing and running benchmarks can be found the <code>examples/</code> directory. Each of these files are built using the root <code>build.zig</code> file. All examples can be built using <code>zig build examples</code> and they can be run using <code>zig build run</code>.
status
<strong>zubench</strong> is in early development—the API is not stable at the moment and experiments with the API are planned, so feel free to make suggestions for the API or features you would find useful. | [
"https://github.com/dweiller/zig-wfc"
] |
https://avatars.githubusercontent.com/u/6756180?v=4 | libvlc-zig | kassane/libvlc-zig | 2022-12-08T17:13:15Z | Zig bindings for libVLC media framework. | main | 7 | 20 | 0 | 20 | https://api.github.com/repos/kassane/libvlc-zig/tags | BSD-2-Clause | [
"bindings",
"libvlc",
"libvlc-zig",
"zig",
"zig-library",
"zig-package"
] | 449 | false | 2025-03-06T14:00:03Z | true | true | unknown | github | [
{
"commit": "00424d823873612c795f59eb1fc9a29c7360782a.tar.gz",
"name": "libvlcpp",
"tar_url": "https://github.com/kassane/libvlcpp/archive/00424d823873612c795f59eb1fc9a29c7360782a.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/kassane/libvlcpp"
}
] |
<a>
</a>
<a>
</a>
<a>
</a>
<a>
</a>
<a>
</a>
libvlc-zig
Zig bindings for libVLC media framework. Some of the features provided by libVLC include the ability to play local files and network streams, as well as to transcode media content into different formats. It also provides support for a wide range of codecs, including popular formats like H.264, MPEG-4, and AAC.
Requirements
<ul>
<li><a>zig v0.11.0 or higher</a></li>
<li><a>vlc</a></li>
</ul>
How to use
Example
<code>bash
$> zig build run -Doptimize=ReleaseSafe # print-version (default)
$> zig build run -DExample="cliPlayer-{c,cpp,zig}" -Doptimize=ReleaseSafe -- -i /path/multimedia_file</code>
How to contribute to the libvlc-zig project?
Read <a>Contributing</a>.
FAQ
Q: Why isn't libvlc-zig licensed under <strong>LGPLv2.1</strong>?
A: The decision to license <code>libvlc-zig</code> under the <strong>BSD-2 clause</strong> was made by the author of the project. This license was chosen because it allows for more permissive use and distribution of the code, while still ensuring that the original author receives credit for their work.
<code>libvlc-zig</code> respects the original <strong>LGPLv2.1</strong> (Lesser General Public License) license of the VLC project.
Q: Are you connected to the developers of the original project?
A: No, the author of <code>libvlc-zig</code> is not part of the <strong>VideoLAN development team</strong>. They are simply interested in being part of the VLC community and contributing to its development.
Q: What is the main goal of this project?
A: The main goal of <code>libvlc-zig</code> is to provide a set of bindings for the <strong>VLC media player's</strong> libvlc library that are written in the <strong>Zig programming language</strong>. The project aims to provide a more modern and safe way to interface with the library, while maintaining compatibility with existing code written in <strong>C</strong> and <strong>C++</strong>.
Q: Does libvlc-zig aim to replace libvlc?
A: No, <code>libvlc-zig</code> does not aim to replace libvlc. Instead, it provides an alternative way to interface with the library that may be more suitable for Zig developers.
Q: Can I use libvlc-zig in my project?
A: Yes, you can use <code>libvlc-zig</code> in your project as long as you comply with the terms of the <strong>BSD-2 clause</strong> license. This includes giving credit to the original author of the code.
Q: Does libvlc-zig support all of the features of libvlc?
A: <code>libvlc-zig</code> aims to provide bindings for all of the features of libvlc, but it may not be complete or up-to-date with the latest version of the library. If you encounter any missing features or bugs, please report them to the project's GitHub issues page.
Q: What programming languages are compatible with libvlc-zig?
A: <code>libvlc-zig</code> provides bindings for the <strong>Zig programming language</strong>, but it can also be used with <strong>C</strong> and <strong>C++</strong> projects that use the libvlc library.
License
```
BSD 2-Clause License
Copyright (c) 2022, Matheus Catarino França
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
<ol>
<li>
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
</li>
<li>
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
```
</li>
</ol> | [] |
https://avatars.githubusercontent.com/u/106511?v=4 | pulseaudio | andrewrk/pulseaudio | 2023-01-17T06:46:23Z | pulseaudio with the build system replaced by zig | master | 0 | 16 | 2 | 16 | https://api.github.com/repos/andrewrk/pulseaudio/tags | NOASSERTION | [
"zig-package"
] | 15,876 | false | 2025-03-26T04:22:10Z | true | true | 0.14.0 | github | [] | PulseAudio Zig Package
This is a fork of
<a>PulseAudio</a>, packaged
for Zig. Unnecessary files have been deleted, and the build system has been
replaced with <code>build.zig</code>.
License
Original LICENSE file is unchanged. The Zig files that have been added to this
repository are MIT (Expat) licensed.
The MIT License (Expat)
Copyright (c) contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. | [] |
https://avatars.githubusercontent.com/u/2286349?v=4 | zig-sbi | leecannon/zig-sbi | 2022-03-03T23:01:23Z | Zig wrapper around the RISC-V SBI specification | master | 0 | 16 | 5 | 16 | https://api.github.com/repos/leecannon/zig-sbi/tags | MIT | [
"osdev",
"risc-v",
"riscv",
"riscv32",
"riscv64",
"sbi",
"zig",
"zig-package",
"ziglang"
] | 138 | false | 2025-04-28T05:31:08Z | true | true | 0.14.0-dev.3445+6c3cbb0c8 | github | [] | zig-sbi
Zig wrapper around the <a>RISC-V SBI specification</a>.
Compatible with SBI Specification v3.0-rc1.
Installation
Add the dependency to <code>build.zig.zon</code>:
<code>sh
zig fetch --save git+https://github.com/leecannon/zig-sbi</code>
Then add the following to <code>build.zig</code>:
<code>zig
const sbi = b.dependency("sbi", .{});
exe.root_module.addImport("sbi", sbi.module("sbi"));</code> | [] |
https://avatars.githubusercontent.com/u/20110944?v=4 | zig-embshell | ringtailsoftware/zig-embshell | 2023-01-31T00:09:50Z | Small embeddable command line shell in zig | main | 0 | 16 | 0 | 16 | https://api.github.com/repos/ringtailsoftware/zig-embshell/tags | MIT | [
"cli",
"embedded",
"shell",
"zig",
"zig-package",
"ziglang"
] | 40 | false | 2025-04-26T11:07:02Z | true | true | unknown | github | [] | EmbShell
A very small interactive command shell for (embedded) Zig programs.
EmbShell makes an ideal system monitor for debugging and interacting with a small embedded system. It interactively takes lines of text, parses commands and makes callbacks into handler functions.
Compared with Readline, Linenoise and Editline - EmbShell is tiny. It lacks most of their features, but it does have:
<ul>
<li>Tab completion for command names</li>
<li>Backspace for line editing</li>
<li>No reliance on libc and very little use of Zig's <code>std</code> (ie. no fancy print formatting)</li>
<li>Very little RAM use (just a configurable buffer for the incoming command line)</li>
</ul>
In EmbShell:
<ul>
<li>All commands and configuration are set at <code>comptime</code> to optimise footprint</li>
<li>All arguments are separated by whitespace, there is no support for quoted strings, multiline commands or escaped data</li>
<li>All handler arguments are strings, leaving it to the app to decide how to parse them</li>
<li>No runtime memory allocations</li>
</ul>
Using
Developed with <code>zig 0.14.0</code>
Run the sample
<code>cd example-posix
zig build run
</code>
<code>myshell> help
echo
led
myshell> echo hello world
You said: { echo, hello, world }
OK
myshell> led 1
If we had an LED it would be set to true
OK</code>
Using in your own project
First add the library as a dependency in your <code>build.zig.zon</code> file.
<code>zig fetch --save git+https://github.com/ringtailsoftware/zig-embshell.git</code>
And add it to <code>build.zig</code> file.
<code>zig
const embshell_dep = b.dependency("embshell", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("embshell", embshell_dep.module("embshell"));</code>
<code>@import</code> the module and provide a configuration.
<ul>
<li><code>.prompt</code> is the string shown to the user before each command is entered</li>
<li><code>.maxargs</code> is the maximum number of arguments EmbShell will process (e.g. "mycmd foo bar" is 3 arguments)</li>
<li><code>.maxlinelen</code> is the maximum length of a line to be handled, a buffer of this size will be created</li>
<li><code>.cmdtable</code> an array of names and handler function for commands</li>
</ul>
<code>zig
const UserdataT = u32;
const EmbShellT = @import("embshell").EmbShellFixedParams(UserdataT);
const EmbShell = @import("embshell").EmbShellFixed(.{
.prompt = "myshell> ",
.maxargs = 16,
.maxlinelen = 128,
.cmdtable = &.{
.{ .name = "echo", .handler = echoHandler },
.{ .name = "led", .handler = ledHandler },
},
.userdataT = UserdataT,
});</code>
Each handler function is in the following form. EmbShell prints "OK" after successfully executing each function and "Failed" if an error is returned.
<code>zig
fn myHandler(userdata: UserdataT, args:[][]const u8) anyerror!void {
// process args
// optionally return error
}</code>
Next, call <code>.init()</code> and provide a write callback to allow EmbShell to emit data
```zig
fn write(data:[]const u8) void {
// emit data to terminal
}
var shell = try EmbShell.init(write, userdata);
```
Finally, feed EmbShell with incoming data from the terminal to be processed
<code>zig
const buf = readFromMyTerminal();
shell.feed(buf)</code> | [] |
https://avatars.githubusercontent.com/u/80392719?v=4 | zfat | ZigEmbeddedGroup/zfat | 2022-05-07T08:35:40Z | Generic purpose platform-independent FAT driver for Zig | main | 0 | 13 | 5 | 13 | https://api.github.com/repos/ZigEmbeddedGroup/zfat/tags | MIT | [
"fat",
"fat32",
"filesystem",
"zig",
"zig-package"
] | 2,339 | false | 2025-05-02T16:00:06Z | true | true | unknown | github | [
{
"commit": null,
"name": "fatfs",
"tar_url": null,
"type": "remote",
"url": "http://elm-chan.org/fsw/ff/arc/ff15a.zip"
}
] | zfat
Bindings for the <a>FatFs</a> library | [] |
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-tls | nektro/zig-tls | 2022-10-28T21:49:40Z | [WIP] A pure-Zig TLS 1.3 client implementation. | master | 0 | 13 | 0 | 13 | https://api.github.com/repos/nektro/zig-tls/tags | MIT | [
"tls",
"tls13",
"zig",
"zig-package"
] | 40 | false | 2024-06-22T18:27:40Z | true | false | unknown | github | [] | zig-tls
A pure-Zig <a>RFC8446 TLS 1.3</a> client implementation.
Crypto is hard, please feel free to view the source and open issues for any improvements.
Indebted to https://tls13.xargs.org/ and multiple readings of the RFC.
License
MIT | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | nasm | allyourcodebase/nasm | 2023-02-05T19:40:24Z | nasm with the build system replaced by zig | master | 4 | 13 | 13 | 13 | https://api.github.com/repos/allyourcodebase/nasm/tags | NOASSERTION | [
"zig-package"
] | 7,700 | true | 2025-03-19T01:03:29Z | true | true | 0.14.0 | github | [] | This is a fork of <a>NASM</a>, packaged for Zig. Unnecessary files
have been deleted, and the build system has been replaced with <code>build.zig</code>.
Original README follows:
NASM, the Netwide Assembler
<a></a>
Many many developers all over the net respect NASM for what it is:
a widespread (thus netwide), portable (thus netwide!), very flexible
and mature assembler tool with support for many output formats (thus netwide!!).
Now we have good news for you: NASM is licensed under the "simplified"
<a>(2-clause) BSD license</a>.
This means its development is open to even wider society of programmers
wishing to improve their lovely assembler.
Visit our <a>nasm.us</a> website for more details.
With best regards, the NASM crew. | [
"https://github.com/allyourcodebase/ffmpeg"
] |
https://avatars.githubusercontent.com/u/107519028?v=4 | learn-zig | better-zig/learn-zig | 2022-06-15T00:09:56Z | zig quick learn | main | 0 | 12 | 1 | 12 | https://api.github.com/repos/better-zig/learn-zig/tags | Apache-2.0 | [
"ffi",
"ffi-bindings",
"zig",
"zig-package",
"ziglang"
] | 49 | false | 2025-01-01T02:47:27Z | false | false | unknown | github | [] | learn-zig
<ul>
<li>learning zig language</li>
</ul>
<blockquote>
related:
</blockquote>
<ul>
<li>✅ https://github.com/better-zig/ziglings-solutions<ul>
<li>zig 语法练习</li>
</ul>
</li>
</ul>
Features:
<ul>
<li><a>basic</a>: zig basic example</li>
<li><a>toolbox</a> : zig toolbox</li>
<li><a>zig-utils</a> : zig utils</li>
</ul>
<blockquote>
与 C 语言互操作性:
</blockquote>
<ul>
<li>✅ <a>c</a>: 使用 zig 作为 C 编译器, 直接编译 C 代码</li>
<li><code>cd packages/c; task run</code></li>
<li>or <code>task c:run</code></li>
<li>✅ <a>zig-use-c</a>: zig 调用 C 代码</li>
<li>✅ <a>zig-to-c</a>: zig 编译成 C Lib(C ABI), 基于 <code>FFI</code>, 被其他语言(如 dart)调用</li>
</ul>
QuickStart:
<blockquote>
requirements:
</blockquote>
<ul>
<li>zig: <code>0.10.0-dev.2617+47c4d4450</code></li>
<li>zigmod: <code>zigmod r80 macos aarch64 none</code></li>
</ul>
<blockquote>
install:
</blockquote>
```ruby
install zig:
task install:zig:dev
-> % zig version
0.10.0-dev.2617+47c4d4450
macos + m1 cpu:
task install:zigmod:m1
or macos + intel cpu
task install:zigmod:intel
```
<blockquote>
run:
</blockquote>
<code>ruby
task basic:run</code>
<blockquote>
test:
</blockquote>
<code>ruby
task basic:test</code>
Structure:
```ruby
-> % tree ./packages/ -L 2
./packages/
├── basic
│ ├── Taskfile.yml
│ ├── build.zig
│ ├── src
│ ├── zig-cache
│ ├── zig-out
│ └── zigmod.yml
├── toolbox
│ ├── Taskfile.yml
│ ├── build.zig
│ ├── src
│ └── zigmod.yml
└── zig-utils
├── Taskfile.yml
├── build.zig
├── src
├── zig-cache
└── zigmod.yml
``` | [] |
https://avatars.githubusercontent.com/u/121257957?v=4 | mach-system-sdk | hexops-graveyard/mach-system-sdk | 2022-03-04T23:33:51Z | DirectX 12 headers for MinGW/Zig, cross-compile DX12/Metal/etc with Zig, etc. | main | 0 | 9 | 2 | 9 | https://api.github.com/repos/hexops-graveyard/mach-system-sdk/tags | NOASSERTION | [
"zig-package"
] | 8 | false | 2023-09-30T11:30:35Z | false | false | unknown | github | [] | mach/system-sdk, more libraries for cross-compilation with Zig <a></a>
<ul>
<li>Updated DirectX 12 headers for use with MinGW/Zig</li>
<li>Cross-compile DirectX apps targetting Windows</li>
<li>Cross compile Metal apps targetting macOS/iOS Intel or Apple Silicon.</li>
<li>Cross compile OpenGL/Vulkan apps targetting Linux (not other OSs, sorry)</li>
</ul>
What is this?
One thing I care about extremely with <a>Mach engine</a> is that you're able to cross compile for any OS with nothing more than <code>zig</code> and <code>git</code>. And while we can build most things from source (GLFW, and even the DirectX Shader Compiler!) there are a few system headers / libraries where, really, we just need a copy of them.
<code>mach/system-sdk</code> is how Mach engine gets a copy of them via the Zig build system.
Although it was intended for Mach specifically, and I wouldn't be surprised if one day Zig provides better options out of the box, I realize others might benefit from this and so I've made it easy for anyone to use!
What does it provide?
Depending on the target OS, <code>system_sdk.zig</code> will automatically <code>git clone</code> the relevant system SDK for you and include it:
<ul>
<li><code>sdk-windows-x86_64</code> (~7MB):</li>
<li>Updated DirectX 12 headers (and prior versions) for use with Zig/MinGW when specifying a <code>-Dtarget=x86_64-windows-gnu</code> target.</li>
<li>DirectX libraries such as <code>dxgi.lib</code> and <code>dxguid.lib</code></li>
<li><code>sdk-linux-x86_64</code> (~40MB):</li>
<li>X11/xcb/Wayland libraries/headers (as static as possible)</li>
<li>OpenGL and Vulkan headers</li>
<li>Generated Wayland protocol sources</li>
<li><code>sdk-macos-11.3</code> (~198MB) and <code>sdk-macos-12.0</code> (~149MB)</li>
<li>A nearly full copy of the macOS 11.3 and 12.0 XCode SDKs, with just a few particularly large frameworks excluded.</li>
<li>Pretty much every framework, header, etc. that you need to develop macOS and iOS applications for Intel and Apple Silicon.</li>
<li>Symlinks mostly eliminated for ease of use on Windows</li>
</ul>
The build script will <code>git clone</code> these SDKs for you, pin them to a specific Git revision denoted in the <code>system_sdk.zig</code> file so they are versioned, and even prompt for XCode license agreement in the case of macOS SDKs.
into the appdata directory
<code>/Users/slimsag/Library/Application Support/hexops</code>
Single file & one-liner to use
Get <a>system_sdk.zig</a> into your codebase however you prefer. I suggest just copying it for now, it's a single file.
In your <code>build.zig</code>:
<code>const system_sdk = @import("system_sdk.zig");
...
system_sdk.include(b, step, .{});</code>
Where <code>step</code> is the exe / lib you're building.
Shared between Zig projects
The SDKs are cloned into your <code><appdata>/hexops</code> directory to ensure they are shared across projects and you don't end up with multiple copies. Prior to use the build script will <code>git reset</code> to the target revision.
Customization
If you don't like what is provided in the SDK repositories, I've tried to make it as easy as possible to switch to your own SDK repos. Just pass <code>Options</code>:
<code>zig
system_sdk.include(b, step, .{
.github_org = "myorg",
.linux_x86_64_revision = "ab7fa8f3a05b06e0b06f4277b484e27004bfb20f",
.windows_x86_64_revision = "5acba990efd112ea0ced364f0428e6ef6e7a5541",
});</code>
And set the revisions to the Git revisions of your forks of <a>the SDK repositories.</a>
Is this the right way to do this? Should I be using this?
To be clear, I don't think this is the perfect way or 100% ideal way to handle this. I am positive that the Zig community will eventually land on better solutions here.
For example, generating updated DirectX 12 headers for MinGW/Zig requires patching Microsoft's IDL files, running them through the Wine WIDL compiler, and then some. Storing even a few binaries in Git is not ideal, even if we do clone with <code>--depth 1</code>.
But, if you care about that developer experience as immensely as I do I hope you'll see a bit of reason behind the madness.
Use at your own peril!
Issues
Please file issues/complaints in the <a>main Mach repository</a>. | [] |
https://avatars.githubusercontent.com/u/379570?v=4 | iter-zig | eldesh/iter-zig | 2022-08-06T11:43:58Z | A basic iterator library written in Zig | master | 1 | 9 | 3 | 9 | https://api.github.com/repos/eldesh/iter-zig/tags | BSD-2-Clause | [
"zig-package"
] | 332 | false | 2025-05-14T08:05:51Z | true | false | unknown | github | [] | iter-zig
<strong>iter-zig</strong> is a lazy style generic iterator combinator library written in Zig.
Where the <em>iterator</em> means that the types enumrating all element of a set of values.
Support
This library is developped with:
<ul>
<li>Debian (x86_64) 10.4</li>
<li>Zig 0.10.0 and Zigmod r80</li>
<li>Zig 0.9.1 and Zigmod r79</li>
</ul>
Build
<code>sh
zig build</code>
Unit Test
To performs unit tests of iter-zig:
<code>sh
zig build test</code>
Example
An example program using iter-zig is provided.
The program can be performed with:
<code>sh
zig build example</code>
Source code of this program is <code>src/main.zig</code>.
Generate docs
To generate documentations:
<code>sh
zig build doc</code>
A html documents would be generated under the <code>./docs</code> directory.
Iterator Concept
<strong>Iterator</strong> is a generic concept that objects that enumrating a set of values.
Especially, in this library, Iterator is a value of a kind of types that satisfies follow constraints.
The constraints are:
- Have <code>Self</code> type
- Have <code>Item</code> type
- Have <code>next</code> method takes <code>*Self</code> and returns <code>?Item</code>.
Where the <code>Self</code> type specifies the type itself (equals to <code>@This()</code>), the <code>Item</code> type represents the type of elements returns from the iterator, and the <code>next</code> method returns a 'next' value of the container.
If the next value is not exists, 'null' must be returned.
The order of occurence of values are implementation defined.
However, all values must occur exactly once before 'null' is returned.
Features
Meta function
<a>The type constraints required as an Iterator</a> is able to be checked by <code>isIterator</code> function statically.
<code>zig
comptime assert(isIterator(SliceIter(u32)));
comptime assert(!isIterator(u32));</code>
When you implement a new type to be an iterator, it must ensure that <code>isIterator</code> returns <code>true</code>.
Container Iterators
<strong>iter-zig</strong> provides several basic iterators that wraps standard containers.
<ul>
<li>ArrayIter</li>
<li>SliceIter</li>
<li>ArrayListIter</li>
<li>SinglyLinkedListIter</li>
<li>BoundedArrayIter</li>
<li>TailQueueIter</li>
</ul>
For example, an iterator on a slice is able to be used as follows:
<code>zig
var arr = [_]u32{ 1, 2, 3 };
var iter = SliceIter(u32).new(arr[0..]);
try expectEqual(@as(u32, 1), iter.next().?.*);
try expectEqual(@as(u32, 2), iter.next().?.*);
try expectEqual(@as(u32, 3), iter.next().?.*);
try expectEqual(@as(?*u32, null), iter.next());</code>
Further, <code>Const</code> variations are defined for each containers.
These iterators behaves as same to non-const variations except for returns const pointers.
<ul>
<li>ArrayConstIter</li>
<li>SliceConstIter</li>
<li>ArrayListConstIter</li>
<li>SinglyLinkedListConstIter</li>
<li>BoundedArrayConstIter</li>
<li>TailQueueConstIter</li>
</ul>
<code>zig
var arr = [_]u32{ 1, 2, 3 };
var iter = SliceConstIter(u32).new(arr[0..]);
iter.next().?.* += 1; // error: cannot assign to constant</code>
Note that, these iterators not own container values into it.
The user must release the memory holding the container if necessary.
Iterators to Containers
Iterator to container converters are defined for some std containers.
<ul>
<li>slice_from_iter</li>
<li>array_list_from_iter</li>
<li>bounded_array_from_iter</li>
<li>singly_linked_list_from_iter</li>
</ul>
These converters consume the input iterator and build a container.
The constructed container contains all the elements of the iterator and no other elements.
Range Iterator
<code>range</code> creates a Range value such that it represents a range of numbers.
For example, <code>range(0, 10)</code> means that the numbers from <code>0</code> to <code>10</code>, which is mathematics is denoted as <code>[0,10)</code>.
In particular, Range instantiated with integral type to be iterator.
<code>zig
var rng = range(@as(u32, 0), 3);
try expectEqual(@as(u32, 0), rng.next().?);
try expectEqual(@as(u32, 1), rng.next().?);
try expectEqual(@as(u32, 2), rng.next().?);
try expectEqual(@as(?u32, null), rng.next());</code>
Similarly, <code>range_from</code> creates an instance of <code>RangeFrom</code> to represents an endless sequence of numbers.
e.g. <code>range_from(@as(u32, 0))</code> creates an endless sequence of natural numbers <code>0,1,2,...</code>.
<code>zig
var rng = range_from(@as(u32, 0));
try expectEqual(@as(u32, 0), rng.next().?);
try expectEqual(@as(u32, 1), rng.next().?);
try expectEqual(@as(u32, 2), rng.next().?);
..</code>
When <code>Range</code> or <code>RangeFrom</code> is instantiated with a type of floating numbers,
it would not be an Iterator. It is just a range of values.
<code>zig
comptime assert(!concept.isIterator(range.Range(f64)));
comptime assert(!concept.isIterator(range.RangeFrom(f64)));
comptime assert( range.range(@as(f64, 2.0), 3.0).contains(2.5))
comptime assert(!range.range(@as(f64, 2.0), 3.0).contains(1.5))</code>
Iterator Operators
All iterators defined in this library provide iterator functions below.
<ul>
<li>peekable</li>
<li>position</li>
<li>cycle</li>
<li>copied</li>
<li>cloned</li>
<li>nth</li>
<li>last</li>
<li>flat_map</li>
<li>flatten</li>
<li>partial_cmp</li>
<li>cmp</li>
<li>le</li>
<li>ge</li>
<li>lt</li>
<li>gt</li>
<li>sum</li>
<li>product</li>
<li>eq</li>
<li>ne</li>
<li>max</li>
<li>max_by</li>
<li>max_by_key</li>
<li>min</li>
<li>min_by</li>
<li>min_by_key</li>
<li>reduce</li>
<li>skip</li>
<li>scan</li>
<li>step_by</li>
<li>fold</li>
<li>try_fold</li>
<li>try_foreach</li>
<li>for_each</li>
<li>take_while</li>
<li>skip_while</li>
<li>map</li>
<li>map_while</li>
<li>filter</li>
<li>filter_map</li>
<li>chain</li>
<li>enumerate</li>
<li>all</li>
<li>any</li>
<li>take</li>
<li>count</li>
<li>find</li>
<li>find_map</li>
<li>inspect</li>
<li>fuse</li>
<li>zip</li>
</ul>
These functions are almost same to <a>functions on Iterator trait of Rust</a> except for experimental api.
Adaptor style iterator
Some functions above return an iterator from the iterator itself.
For that case, the functions are implemented in adaptor style.
For example, the <code>map</code> function returns a new iterator object <code>Map</code> rather than apply a function to each elements from the iterator.
```zig
var arr = [_]u32{ 1, 2, 3 };
var iter = SliceIter(u32).new(arr[0..]);
fn incr(x:u32) u32 { return x+1; }
// Calculations have not yet been performed.
var map: Map(SliceIter(u32), fn (u32) u32) = iter.map(incr);
try expectEqual(@as(u32, 2), map.next().?.<em>); // incr is performed
try expectEqual(@as(u32, 3), map.next().?.</em>); // incr is performed
try expectEqual(@as(u32, 4), map.next().?.<em>); // incr is performed
try expectEqual(@as(?</em>u32, null), map.next());
```
Implementing Iterator
<strong>iter-zig</strong> allows library users to implement a new iterator type by their self.
Further, it is easy to implement all functions showed in <a>Iterator Operators</a> to your new iterator type using <code>DeriveIterator</code>.
For example, let's make an iterator <code>Counter</code> which counts from <code>1</code> to <code>5</code>.
<code>zig
const Counter = struct {
pub const Self = @This();
pub const Item = u32;
count: u32,
pub fn new() Self { return .{ .count = 0 }; }
pub fn next(self: *Self) ?Item {
self.count += 1;
if (self.count < 6)
return self.count;
return null;
}
};</code>
Now we can use it as an iterator.
<code>zig
comptime assert(isIterator(Counter));
var counter = Counter.new();
try expectEqual(@as(u32, 1), counter.next().?);
try expectEqual(@as(u32, 2), counter.next().?);
try expectEqual(@as(u32, 3), counter.next().?);
try expectEqual(@as(u32, 4), counter.next().?);
try expectEqual(@as(u32, 5), counter.next().?);
try expectEqual(@as(?u32, null), counter.next());</code>
However, <code>Counter</code> not implement utility functions like <code>map</code> or <code>count</code> etc ...
To implement these functions, use <code>DeriveIterator</code> meta function like below.
```zig
const CounterExt = struct {
pub const Self = @This();
pub const Item = u32;
pub usingnamespace DeriveIterator(@This()); // Add
count: u32,
pub fn new() Self { return .{ .count = 0 }; }
pub fn next(self: *Self) ?Item {
self.count += 1;
if (self.count < 6)
return self.count;
return null;
}
};
```
In above code, <code>CounterExt</code> difference from <code>Counter</code> is only the <code>DeriveIterator(@This())</code> line.
Now, you can use all functions showed in <a>Iterator Operators</a>.
<code>zig
fn incr(x:u32) u32 { return x+1; }
fn even(x:u32) bool { return x % 2 == 0; }
fn sum(st:*u32, v:u32) ?u32 {
st.* += v;
return st.*;
}
var counter = CounterExt.new();
var iter = counter
.map(incr) // 2,3,4,5,6
.filter(even) // 2,4,6
.scan(@as(u32, 0), sum); // 2,6,12
try expectEqual(@as(u32, 2), iter.next().?);
try expectEqual(@as(u32, 6), iter.next().?);
try expectEqual(@as(u32, 12), iter.next().?);
try expectEqual(@as(?u32, null), iter.next());</code>
If you can implement some method efficiently rather than using <code>next</code> method, just implement that method (in <code>CounterExt</code> in the above).
<code>DeriveIterator</code> suppresses the generation of that function.
Convention
<strong>iter-zig</strong> adopts naming conventions for implementing iterators.
First, when defining a new iterator type, the type constructor must be named <code>MakeT</code> where type <code>T</code> is a name of the type.
And the constructor should take a <code>Derive</code> function like below.
<code>zig
pub fn MakeCounter(comptime Derive: fn (type) type) type {
return struct {
pub const Self = @This();
pub const Item = u32;
pub usingnamespace Derive(@This());
count: u32,
pub fn next(self: *Self) ?Item {
...
}
};
}</code>
This allows users to switch the function used for deriving.
Second, a type constructor should be named <code>T</code>.
And the constructor should forward <code>DeriveIterator</code> to <code>MakeT</code>.
<code>zig
pub fn Counter() type {
return MakeCounter(DeriveIterator);
}</code> | [] |
https://avatars.githubusercontent.com/u/63465728?v=4 | jigar | alichraghi/jigar | 2022-08-04T17:30:46Z | Case convertion library for ziguanas | master | 1 | 8 | 1 | 8 | https://api.github.com/repos/alichraghi/jigar/tags | MIT | [
"case-conversion",
"zig",
"zig-package"
] | 50 | false | 2023-09-30T11:26:03Z | true | false | unknown | github | [] | Jigar
case convertion library for ziguanas
supports: <code>lower case</code>, <code>UPPER CASE</code>, <code>MACRO_CASE</code>, <code>TRAIN-CASE</code>, <code>snake_case</code>, <code>snake_Camel</code>, <code>Snake_Pascal</code>, <code>kebab-case</code>, <code>Kebab-Pascal</code>, <code>camelCase</code> and <code>PascalCase</code>
Usage
```zig
const jigar = @import("jigar");
pub fn main() void {
var my_hello = "Hello World".*;
jigar.snakeCase(&my_hello); // results: hello_world
}
``` | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | libmp3lame | allyourcodebase/libmp3lame | 2023-01-08T01:38:56Z | libmp3lame with the build system replaced by zig | main | 3 | 7 | 5 | 7 | https://api.github.com/repos/allyourcodebase/libmp3lame/tags | NOASSERTION | [
"zig-package"
] | 1,501 | false | 2025-03-07T04:47:36Z | true | true | 0.14.0 | github | [] | This is a fork of <a>lame</a>, packaged for Zig.
Unnecessary files have been deleted, and the build system has been replaced
with <code>build.zig</code>.
Original README follows:
============================================================================
<code> LAME 3.xx
LAME Ain't an MP3 Encoder
http://lame.sf.net
May 2011
</code>
Originally developed by Mike Cheng (www.uq.net.au/~zzmcheng) and was
latter developed by Mark Taylor (www.mp3dev.org). Currently maintained
by The LAME Project.
This code is distributed under the GNU LIBRARY GENERAL PUBLIC LICENSE
(LGPL, see www.gnu.org), version 2.
As LAME may contain software for which some companies may claim software
patents, if you are in a location where software patents are recognized, it is
suggested that you seek legal advice before deploying and/or redistributing
LAME.
In particular, it is suggested to visit
<code>http://www.mp3licensing.com/
</code>
if it applies to your jurisdiction.
============================================================================
see the file "INSTALL" for installation (compiling) instructions.
see the file "USAGE" for the most up-to-date guide to the command line options.
see the file "LICENSE" for details on how to use LAME in non-GPL programs.
see the file "HACKING" if you are interested in working on LAME
see the file "API" for details of the LAME encoding library API
There is HTML documentation and a man page in the doc directory.
============================================================================
LAME uses the MPGLIB decoding engine, from the mpg123 package, written
by: Michael Hipp (www.mpg123.de) MPGLIB is released under the GPL.
Copyrights (c) 1999-2011 by The LAME Project
Copyrights (c) 1999,2000,2001 by Mark Taylor
Copyrights (c) 1998 by Michael Cheng
Copyrights (c) 1995,1996,1997 by Michael Hipp: mpglib
As well as additional copyrights as documented in the source code. | [
"https://github.com/allyourcodebase/ffmpeg"
] |
https://avatars.githubusercontent.com/u/4678790?v=4 | zig-wfc | dweiller/zig-wfc | 2022-07-01T02:42:47Z | An implementation of the wave function collapse algorithm in Zig | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/dweiller/zig-wfc/tags | MIT | [
"zig-package"
] | 81 | false | 2025-03-18T05:22:46Z | true | true | unknown | github | [
{
"commit": "53140a07a6ee27e28549c46209d900ba92f61ceb.tar.gz",
"name": "zubench",
"tar_url": "https://github.com/dweiller/zubench/archive/53140a07a6ee27e28549c46209d900ba92f61ceb.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/dweiller/zubench"
}
] | zig-wfc
An implementation of the wave function collapse algorithm in Zig
A generic library implementing the <em>wave function collapse</em> algorithm. This library exposes a generic core algorithm which produces tilings given a collection of tiles and associated adjacency constraints, as well a tile generator for implementing the <em>overlapping</em> mode. See the <a>original implementation</a> for an overview of the algorithm and links to other resources.
Using zig-wfc
You can use <code>zig-wfc</code> in a Zig project with the Zig build system. Include a dependency in your <code>build.zig.zon</code>, e.g.:
<code>.dependencies = .{
.zig_wfc = .{
.url = "https://github.com/dweiller/zig-wfc/archive/[[COMMIT_HASH]].tar.gz",
.hash = "[[ZIG_PACKAGE_HASH]]",
},
}</code>
Then retrieve the <code>wfc</code> module from the dependency in your <code>build.zig</code>:
```
pub fn build(b: *std.Build) !void {
<code>// -- snip --
const wfc = b.dependency("zig_wfc", .{}).module("wfc");
// assuming you have a `std.Build.Step.Compile` called 'exe' that wants to do WFC
exe.addModule("zig-wfc", wfc);
</code>
}
```
You can ascertain the correct value for <code>[[ZIG_PACKAGE_HASH]]</code> by leaving that field out initially; this make Zig report the correct hash value.
WFC Core
WFC is sometimes considered as having two different modes: overlapping and tiled. I think is description is a little misleading: I would rather say the WFC is a tiling generator (or maybe even more generally a graph colouring algorithm) and the overlapping mode merely one of several processing pipelines that can be used to achieve various effects. A good explanation how the core tiling algorithm relates to the overlapping mode can be found <a>here</a>. Another processing pipeline of particular interest I haven't yet seen talked about is what could be called the 'iterative mode' (if we want to keep the nomenclature of modes), which allows for generating <a>large-scale structure</a>, which are usually considered outside the scope of WFC.
The most common situation is generating a 2D or 3D cubic tiling and this library is currently restricted to 2-dimensional rectangular tilings.
Features (and todos)
<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> generic core algorithm you can use with any set of (2D) tiles/edge constraints forming a rectangular grid
<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> generate tiles from image (overlapping mode)
<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> seeded generation
- generation constraints
<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> maximum tile count (i.e. max number of times a tile can be used)
<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> minimum tile count (i.e. min number of times a tile can be used)
<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> connectivity constraints (i.e. forces tiles to be part of the same region/path)
<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> distance constraints (distance between particular tiles and of paths)
<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> tile symmetry groups
<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> iterative pipeline
<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> <em>n</em>-dimensional rectangular tilings
<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> hexagonal grid
Iterative pipeline
Helper utilities for the iterative pipeline is not yet implemented, but are planned for the future. This pipeline is a fairly general idea that produces intermediate tilings that are used to seed the next stage.
Large-scale structure
WFC does not generally produce large-scale structures as the constraints it considers are all local. However, the core tiling algorithm can be used to generate large-scale structure fairly easily using an iterative strategy. The basic idea is to first generate a low resolution tiling which is used to seed subsequent tile generation. The increase in resolution naturally leads to the initial tiling producing large-scale structure.
For example, say you wanted to generate a 2D tiling with some larger-scale structure that includes houses, roads and grass, including more specialised tiles for the boundary regions between the road and a front lawn (like a footpath). You could start by generating a 'seed' tiling at a lower resolution that has the tiles 'property' and 'road'. You then expand this tiling into a higher resolution one initially seeded with 'house', 'footpath' and 'grass' tiles in the regions associated to 'property' tiles and 'road' tiles seeded where the 'road' tiles were. The adjacency constraints for 'footpath' can then require that they border 'road' tiles and 'grass' tiles surround 'house' tiles. This guarantees a minimum size for each large-scale 'property' which are grassy regions (possibly) with house tiles inside them. More passes/sub-tile types could be added for improved internal structure of a 'property' (e.g. to make 'house' tiles form a connected region or to add a driveway).
Contributing
Contributions are welcome, as are issues requesting/suggesting better documentation or API and new features; feel free to open issues and send PRs. | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.