avatar_url stringlengths 47 116 ⌀ | name stringlengths 1 46 | full_name stringlengths 7 60 | created_at stringdate 2016-04-01 08:17:56 2025-05-20 11:38:17 | description stringlengths 0 387 ⌀ | default_branch stringclasses 44
values | open_issues int64 0 4.93k | stargazers_count int64 0 78.2k | forks_count int64 0 3.09k | watchers_count int64 0 78.2k | tags_url stringlengths 0 94 | license stringclasses 27
values | topics listlengths 1 20 | size int64 0 4.82M | fork bool 2
classes | updated_at stringdate 2018-11-13 14:41:18 2025-05-22 08:23:54 | has_build_zig bool 2
classes | has_build_zig_zon bool 2
classes | zig_minimum_version stringclasses 50
values | repo_from stringclasses 3
values | dependencies listlengths 0 38 | readme_content stringlengths 0 437k | dependents listlengths 0 21 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://avatars.githubusercontent.com/u/21127627?v=4 | wabt-zig | ytakhs/wabt-zig | 2023-04-25T13:30:40Z | WABT bindings for Zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/ytakhs/wabt-zig/tags | Apache-2.0 | [
"webassembly",
"zig"
] | 33 | false | 2023-04-25T13:40:01Z | true | false | unknown | github | [] | wabt-zig
WIP | [] |
https://avatars.githubusercontent.com/u/19827734?v=4 | aoc-2023 | ezradiniz/aoc-2023 | 2023-11-27T02:51:39Z | Advent of Code 2023 in Zig | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/ezradiniz/aoc-2023/tags | - | [
"aoc",
"aoc-2023",
"zig"
] | 145 | false | 2024-03-24T13:14:02Z | false | false | unknown | github | [] | Advent of Code 2023
My solutions for Advent of Code 2023 to learn <a>zig</a>.
https://adventofcode.com/2023/
Create Day
<code>console
$ ./create.sh <day></code> | [] |
https://avatars.githubusercontent.com/u/17427091?v=4 | zig-toxcore-c | TokTok/zig-toxcore-c | 2023-12-31T16:38:04Z | Zig wrapper for c-toxcore library. | master | 0 | 2 | 3 | 2 | https://api.github.com/repos/TokTok/zig-toxcore-c/tags | GPL-3.0 | [
"c",
"ffi",
"networking",
"tox",
"zig"
] | 70 | true | 2025-01-12T23:35:24Z | true | true | unknown | github | [
{
"commit": "56bef8abc59b6db7ce5a94ebce5d0843313d3ce2.tar.gz",
"name": "libsodium",
"tar_url": "https://github.com/jedisct1/libsodium/archive/56bef8abc59b6db7ce5a94ebce5d0843313d3ce2.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/jedisct1/libsodium"
},
{
"commit": "9f5eb260... | zig-toxcore-c
Zig wrapper for c-toxcore library.
build
<code>zig build run-local-test</code> | [] |
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-cookies | nektro/zig-cookies | 2023-02-28T04:19:10Z | null | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/nektro/zig-cookies/tags | MIT | [
"zig",
"zig-package"
] | 7 | false | 2025-05-21T20:33:28Z | false | false | unknown | github | [] | zig-cookies
<a></a>
<a></a>
<a></a>
<a></a>
A pure-Zig library for CRUDing HTTP Cookies. | [] |
https://avatars.githubusercontent.com/u/145422627?v=4 | string.zig | crispy-strawberry/string.zig | 2023-11-14T12:08:36Z | A Rust like String type for Zig | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/crispy-strawberry/string.zig/tags | Apache-2.0 | [
"string",
"zig",
"zig-package",
"ziglang"
] | 61 | false | 2023-12-24T09:56:37Z | true | true | unknown | github | [] | An allocated string type
Inspired by Rust's <code>String</code> type.
Implementation mostly ported from Rust.
Provides helper functions that make working with
strings easier.
I try to keep names consistent with <code>std.ArrayList</code>
Using with package manager
<ol>
<li>Create <code>build.zig.zon</code> in the project root if you don't already have one.</li>
<li>Add the barebones skeleton. (<a>this</a> if you don't know what it looks like)</li>
<li>Inside the dependencies section add -
<code>.string = .{
.url = "git+https://github.com/crispy-strawberry/string.zig#main",
}</code></li>
<li>Run <code>zig build</code> and wait for zig to complain about the hash</li>
<li>Copy the provided hash and add it besides the url like -
<code>.string = .{
.url = "<repo url>",
.hash = "<the provided hash>"
}</code></li>
<li>In your <code>build.zig</code>, add -
<code>zig
const string = b.dependency("string", .{ .optimize = optimize, .target = target });
// Replace exe with whatever you are using.
exe.addModule("string", string.module("string"));</code></li>
<li>Now, in your source files, you can use <code>String</code> by-
<code>zig
const String = @import("string").String;</code></li>
<li>Enjoy :)</li>
</ol>
Examples
```zig
const hello_world = try String.fromStr(allocator, "Hello World!");
std.debug.print("{}\n", .{hello_world.isAscii()});
``` | [] |
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-signal | nektro/zig-signal | 2023-02-28T04:14:49Z | null | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/nektro/zig-signal/tags | MIT | [
"linux",
"zig",
"zig-package"
] | 5 | false | 2025-05-21T20:33:35Z | true | false | unknown | github | [] | zig-signal
<a></a>
<a></a>
<a></a>
<a></a>
Zig API for defining signal handlers. | [] |
https://avatars.githubusercontent.com/u/33480665?v=4 | arm-kernel | lowczarc/arm-kernel | 2023-09-20T21:21:44Z | 💾 An ARM kernel in Zig. | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/lowczarc/arm-kernel/tags | NOASSERTION | [
"arm",
"armv7-a",
"bare-metal",
"bcm2837",
"kernel",
"low-level",
"osdev",
"raspberry-pi",
"zig"
] | 118 | false | 2024-09-15T21:17:18Z | false | false | unknown | github | [] | ===============================================================================
LancelOS arm-kernel
===============================================================================
Description:
The goal is to write a simple ARM kernel for Raspberry (only Pi 2 for now but
it won't be too hard to port) in Zig.
I want to understand how my computer work and I like learning by doing.
This is not and will never be intended for any kind of production environment.
Features:
[x] Boot
[x] UART Read/Write
[x] Kernel/Userspace memory separation
[x] "device file" model
[x] open, read, write, close syscalls (on char devices only)
[x] brk syscall, malloc/free in userspace
[x] Framebuffer Read/Write
[x] Virtual TTY with a home-made font :)
[ ] Keyboard
[ ] File system
[x] Multiple processes running at the same time, context switching
[ ] Non system-blocking syscalls
[ ] Pipe
[ ] Userspace shell
... Maybe more, don't know yet
Usage:
You need to have the bare-metal ARM cross-assembly/link tools install
On Archlinux it's extra/arm-none-eabi-binutils
As well as the zig compiler and qemu if you want to test it on your machine.
You can build the kernel with:
make
This will build the kernel to an ./init.bin file
To launch it in qemu:
make qemu-screen
License:
This project is licensed under the "THE GAME LICENSE"
Resources:
https://wiki.osdev.org
https://developer.arm.com/documentation/ddi0595/2021-12/AArch32-Registers
@AsahiLina's explanation of CVE-2022-32947 is a very entertaining way to
understand page tables https://www.youtube.com/watch?v=hDek2cp0dmI
BROADCOM BCM2837 ARM Peripherals datasheet
https://linux-kernel-labs.github.io/refs/heads/master/index.html
https://www.kernel.org/doc/html/latest/index.html | [] |
https://avatars.githubusercontent.com/u/16236219?v=4 | Scale | dylanlangston/Scale | 2023-11-02T23:33:30Z | Game Off 2023 - Theme "Scale" | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/dylanlangston/Scale/tags | MIT | [
"2023",
"game-off",
"gamejam",
"raylib",
"raylib-zig",
"zig"
] | 1,538 | false | 2024-06-07T02:00:34Z | true | true | unknown | github | [
{
"commit": "6094869e3e845e90e1e8ae41b98e889fb3e13e78.tar.gz",
"name": "raylib",
"tar_url": "https://github.com/raysan5/raylib/archive/6094869e3e845e90e1e8ae41b98e889fb3e13e78.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/raysan5/raylib"
}
] | <a></a>
<a></a>
<a></a>
<a></a>
<a>
</a>
This <a>Progressive Web App</a> is a submission to the 2023 <em>Game Off</em> event hosted by <a>GitHub</a> on <a>itch.io</a>, It was created by <a>@dylanlangston</a> using the following:
- <a>Zig</a>
- <a>Raylib</a> via <a>Raylib-Zig</a>
- <a>Raygui</a> via <a>Raygui.zig</a>
- <a>Emscripten</a>
- <a>Binaryen</a>
- <a>Svelte</a>
- <a>Typescript</a>
- <a>TailwindCSS</a>
This was my first attempt[^1] coding using Zig as well as my first app to target <a>web assembly</a>.
What's Game Off? [^2]
<blockquote>
<a>Game Off</a> is GitHub's annual game jam challenging individuals and teams to build a game during the month of November. Use whatever programming languages, game engines, or libraries you like. You're also welcome to use AI tools to help generate code, assets, or anything in between!
The theme for this year's jam is <strong>SCALE</strong>!
</blockquote>
My interpretion of the theme is a vertical platformer ~~that is procedurally generated~~[^3].
<a></a>
Getting Started
<em>This repository includes a <a>devcontainer.json</a> and prebuilt <a>Codespace</a> images to get up and running quickly with a full-featured development environment in the cloud!</em>[^4]
Clone
<ol>
<li>Clone this repository: <code>git clone https://github.com/dylanlangston/Scale.git</code></li>
<li>Change directories into the newly created <code>./Scale</code> folder. Then initialize the submodules: <code>git submodule update --init --recursive</code></li>
</ol>
Debug Locally:
<ol>
<li>If you haven't already, install Zig version 0.11.0 using the <a>instructions here</a>.</li>
<li>Configure you build environment for Raylib using the appropriate <a>instructions</a> for you platform.</li>
<li>Finally, to start the game run the command <code>zig build run</code>. Alternatively run the <strong><em>Debug</em></strong> task in VSCode.</li>
</ol>
Build for Web:
<ol>
<li>Complete steps to <strong>Clone</strong> and <strong>Debug Locally</strong> above first.</li>
<li>Change directories into the <code>./Scale</code> folder. Build the zig portion of the game using command <code>zig build -Dtarget=wasm32-emscripten</code>. Alternatively run the <strong><em>Build Web</em></strong> task in VSCode.</li>
<li>If you haven't already, install NodeJS LTS from <a>here</a> (or your preferred source).</li>
<li>Change directories into the <code>./Scale/src/scale-website</code> folder. Then install the required node packages using <code>npm install</code>.</li>
<li>Build the web version by running the command <code>npm run build</code>. You can find the generated static site in the <code>./Scale/src/scale-website/build</code> folder.</li>
</ol>
Credits
| Font | Source | License |
|:---- |:------:| -------:|
| <em>Eight Bit Dragon</em> | https://www.fontspace.com/eight-bit-dragon-font-f30428 | Freeware, Non-Commercial |
| <em>Two Lines</em> | https://www.fontspace.com/2-lines-font-f14541 | Freeware, Non-Commercial |
| <em>Ec Bricks Regular</em> | https://www.fontspace.com/ec-bricks-font-f30951 | Creative Commons (by-nc-nd) Attribution Non-commercial No Derivatives |
| Palette | Source |
|:-------:|:------:|
| <em>Miyazaki 16</em> | https://lospec.com/palette-list/miyazaki-16 |
| Sound | Creator | Tool | License |
|:-------:|:------:|:---:|:-------:|
| <em><a>jump</a></em> | <a>miajohnson99</a> | <a>Chiptone</a> | Creative Commons (by) Attribution |
| <em><a>Game Over</a></em> | <a>miajohnson99</a> | <a>BeepBox</a> | Creative Commons (by) Attribution |
| Music | Creator | Tool | License |
|:-------:|:------:|:---:|:-------:|
| <em><a>Theme</a></em> | <a>miajohnson99</a> | <a>BeepBox</a> | Creative Commons (by) Attribution |
All the included textures were created using <a>Piskel</a> and are licensed as Creative Commons (by) Attribution.
[^1]: As this is my first attempt, it's likely that this code isn't idiomatic or following best practices.
[^2]: Game Off 2023 on <a>Itch.io</a>
[^3]: The platforms are pre-generated and randomly placed due to time constraints.
[^4]: For local development check out <a>Dev Containers</a> and <a>DevPod</a>. | [] |
https://avatars.githubusercontent.com/u/1374?v=4 | zig-bgfx-example | Interrupt/zig-bgfx-example | 2023-08-27T21:46:49Z | A simple example of using BGFX with Zig | main | 1 | 2 | 1 | 2 | https://api.github.com/repos/Interrupt/zig-bgfx-example/tags | - | [
"bgfx",
"gamedev",
"shaders",
"zig"
] | 18,984 | true | 2024-09-19T08:00:13Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "zigstr",
"tar_url": "https://github.com/jecolon/zigstr/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/jecolon/zigstr"
}
] | Zig + BGFX Example Project
A small example project that shows how to use BGFX from Zig, based on Ziggy (https://github.com/heretique/ziggy)
Running
<ul>
<li>Compile shaders first with <code>zig build shaders</code></li>
<li>Then <code>zig build run</code></li>
</ul>
Notes
<ul>
<li>Building will build BGFX's shader compiler called <code>shaderc</code> alongside the app.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/65205079?v=4 | zignr | ivansantiagojr/zignr | 2024-02-07T04:24:04Z | Generate .gitgnore files from command line with zignr | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/ivansantiagojr/zignr/tags | GPL-3.0 | [
"cli",
"git-ignore",
"zig"
] | 39 | false | 2025-03-18T21:48:20Z | true | true | 0.14.0 | github | [] | zignr
This is a CLI tool to generate <code>.gitgnore</code> files written in zig.
Installation
For now, you can install from our pre-built binary (Linux only):
<code>sh
curl -sSL https://raw.githubusercontent.com/ivansantiagojr/zignr/main/install.sh | bash -</code>
<blockquote>
To make <code>zignr</code> available globally you should have <code>~/.local/bin</code> on you <code>PATH</code>
</blockquote>
Usage
To create a .gitgnore file you can simply use <code>zignr <language> > .gitnore</code>. This command will overwrite your .gitignore file. Example:
<code>bash
zignr zig > .gitgnore</code>
Multi language example:
<code>bash
zignr zig,python,lua > .gitgnore</code>
To see the list of all .gitignore templates you can call <code>zignr</code> with, just use:
<code>bash
zignr list</code>
References
This project started as a Zig learning experience (and still is), so I will link my references below:
First of all, zignr is heavily inspired by <a>ignr.py</a>, which uses the <a>gitignore.io</a> API.
Zig references I used:
<ul>
<li><a>Zig Cookbook</a> </li>
<li><a>Zig documentation</a> </li>
<li><a>Zig Common Tasks</a> </li>
<li><a>Ziglings</a></li>
<li><a>Zig Guides</a></li>
<li><a>Introduction to Zig</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/9091958?v=4 | tircli | avestura/tircli | 2024-01-04T15:45:45Z | ⏰ A HTTP CLI client for Time.ir, written in ⚡Zig | master | 0 | 2 | 2 | 2 | https://api.github.com/repos/avestura/tircli/tags | - | [
"hijri-calendar",
"iran",
"timeir",
"zig"
] | 4 | false | 2024-04-07T07:06:56Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/135145066?v=4 | donuts | dying-will-bullet/donuts | 2023-06-09T14:46:18Z | Beautiful spinners for terminal. | master | 1 | 2 | 2 | 2 | https://api.github.com/repos/dying-will-bullet/donuts/tags | MIT | [
"spinner",
"terminal-utilities",
"tui",
"zig",
"ziglang"
] | 29 | false | 2024-06-10T01:52:08Z | true | true | unknown | github | [] | donuts 🍩
<a></a>
Beautiful spinners for terminal.
Features
<ul>
<li>75 built-in spinners.</li>
<li>Supports ANSI Color.</li>
</ul>
Tutorial
Create a spinner with a text message.
```zig
const std = @import("std");
const Donuts = @import("donuts").Donuts;
pub fn main() !void {
// Create a spinner
var sp = Donuts(std.io.getStdOut()).init(
// message
"Scanning files...",
// spinner style
.{ .style = .dots },
// options
.{},
);
<code>// Start a thread to render spinner
try sp.start();
std.time.sleep(1 * std.time.ns_per_s);
// Write text to same stream
try sp.echoLine("1) build.zig", .{});
std.time.sleep(1 * std.time.ns_per_s);
try sp.echoLine("2) build.zig.zon", .{});
std.time.sleep(1 * std.time.ns_per_s);
try sp.echoLine("3) README.md", .{});
// Stop the spinner thread and render exit text.
try sp.stop(.{ .symbol = "✅", .message = "Done" });
</code>
}
```
Colorful spinner and message.
```zig
pub fn main() !void {
var sp = Donuts(std.io.getStdOut()).init(
"Scanning files...",
.{ .style = .dots },
.{
.spinner_style = .{
.bg = .MAGENTA,
},
.message_style = .{ .fg = .blue, .bold = true },
},
);
try sp.start();
<code>std.time.sleep(1 * std.time.ns_per_s);
try sp.echoLine(
"1) build.zig",
.{ .fg = .WHITE, .bold = true },
);
std.time.sleep(1 * std.time.ns_per_s);
try sp.echoLine(
"2) build.zig.zon",
.{ .fg = .yellow, .bold = true },
);
std.time.sleep(1 * std.time.ns_per_s);
try sp.echoLine(
"3) README.md",
.{ .fg = .CYAN, .bold = true },
);
try sp.stop(
.{
.symbol = "✓",
.symbol_style = .{ .fg = .GREEN, .bold = true },
.message = "Done",
.message_style = .{ .fg = .GREEN, .bold = true },
},
);
</code>
}
```
Simple download progress bar
```zig
pub fn main() !void {
var sp = Donuts(std.io.getStdOut()).init(
"Downloading ...",
.{ .style = .dots },
.{},
);
<code>try sp.start();
std.time.sleep(200 * std.time.ns_per_ms);
var text: [128]u8 = undefined;
for (0..100) |i| {
const len = (try std.fmt.bufPrint(&text, "Progress {d:>02}% ", .{i})).len;
@memset(text[len .. len + i / 2], '#');
@memset(text[len + i / 2 ..], '-');
sp.setMessage(text[0 .. len + 50]);
std.time.sleep(50 * std.time.ns_per_ms);
}
try sp.stop(.{ .symbol = "✅", .message = "Finsihed." });
</code>
}
```
Installation
Zig 0.11
Add <code>donuts</code> as dependency in <code>build.zig.zon</code>:
<code>.{
.name = "my-project",
.version = "0.1.0",
.dependencies = .{
.donuts = .{
.url = "https://github.com/dying-will-bullet/donuts/archive/refs/tags/v0.2.0.tar.gz",
.hash = "1220c47de7b9878c2aeb26ab20383482b0319f8ead60682dc1e47d0be2feef5588b6"
},
},
}</code>
Add <code>donuts</code> as a module in <code>build.zig</code>:
```diff
diff --git a/build.zig b/build.zig
index 957f625..d1a906c 100644
--- a/build.zig
+++ b/build.zig
@@ -15,6 +15,9 @@ pub fn build(b: *std.Build) void {
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
<ul>
<li>const opts = .{ .target = target, .optimize = optimize };</li>
<li>const donuts_module = b.dependency("donuts", opts).module("donuts");
+
const exe = b.addExecutable(.{
.name = "tmp",
// In this case the main source file is merely a path, however, in more
@@ -23,6 +26,7 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = optimize,
});</li>
<li>
exe.addModule("donuts", donuts_module);
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
```
</li>
</ul>
Zig 0.12 / nightly
Please use the master branch.
LICENSE
MIT License Copyright (c) 2023, Hanaasagi | [] |
https://avatars.githubusercontent.com/u/22280250?v=4 | export_ppm | Durobot/export_ppm | 2023-12-13T14:11:24Z | A couple of functions to export data as a PPM/PGM image file from your Zig code | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/Durobot/export_ppm/tags | MIT | [
"pgm",
"pgm-format",
"pgm-image",
"pgm-writer",
"ppm",
"ppm-format",
"ppm-image",
"zig",
"zig-package",
"ziglang"
] | 19 | false | 2025-01-07T23:48:10Z | true | true | 0.12.0-dev.3097+5c0766b6c | github | [] | export_ppm
Just a couple of functions in Zig that export image data, RGB/RGBA/grayscale/grayscale+alpha (but alpha channel is ignored), 8 or 16 bits per channel, as PPM/PGM files. Not enough code to be called a library.
PPM and PGM are very simple graphic file formats, but they are widespread enough for popular editors, like <a>Gimp</a>, <a>Krita</a> or <a>Adobe Photoshop</a> to be able to open them. Meaning you can quickly dump whatever you want from your Zig programs as a PPM/PGM file and open it in an editor.
See https://en.wikipedia.org/wiki/Netpbm?useskin=vector, https://netpbm.sourceforge.net/doc/ppm.html.
Check out the tests in <code>export_ppm.zig</code> for examples of use.
<strong>test_data_src</strong> folder contains PNG images I used as test data, ignore them or use them however you want. I release them in public domain.
<strong>export_ppm.zig</strong> is licensed under <a>the MIT License</a>.
Just drop <code>export_ppm.zig</code> into your project and add <code>const eppm = @import("export_ppm.zig");</code>, or use the Zig package manager:
<ol>
<li>In your project's <code>build.zig.zon</code>, in <code>.dependencies</code>, add</li>
</ol>
<code>zig
.export_ppm =
.{
.url = "https://github.com/Durobot/export_ppm/archive/<GIT 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 your project's <code>build.zig</code>, in <code>pub fn build</code>, before <code>b.installArtifact(exe);</code>, add</li>
</ol>
<code>zig
const eppm = b.dependency("export_ppm",
.{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("export_ppm", eppm.module("export_ppm"));</code>
<ol>
<li>
Add <code>const eppm = @import("export_ppm");</code>in your source file(s).
</li>
<li>
Build your project with <code>zig build</code>, as you normally do.
</li>
</ol> | [] |
https://avatars.githubusercontent.com/u/480330?v=4 | zig-fsm-compiler | Cloudef/zig-fsm-compiler | 2024-01-01T11:24:02Z | Ragel compatible FSM compiler for Zig | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/Cloudef/zig-fsm-compiler/tags | MIT | [
"compiler",
"fsm",
"lexer",
"logic",
"parser",
"parsing",
"state",
"state-machine",
"state-management",
"tokenizer",
"zig"
] | 110 | false | 2025-03-01T18:03:15Z | true | true | unknown | github | [] | zig-fsm-compiler
Ragel compatible FSM compiler for Zig
<blockquote>
<span class="bg-red-100 text-red-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-red-900 dark:text-red-300">CAUTION</span>
This project is still in WIP stage.
You won't be able to use it yet.
Once the ragel language scanner itself can be compiled, it should be usable.
</blockquote>
<a></a>
Project is tested on zig version 0.12.0-dev.1861+412999621
How to use
zig-fsm-compiler can be used either as a standalone compiler or directly from your zig program as a module.
Standalone usage
<code>usage: zig-fsm-compiler [options] [file]
general:
-h, -H, -?, --help Print this usage and exit
-v, --version Print version information and exit
-o <file> Write output to <file>
-s Print some statistics on stderr
-I <dir> Add <dir> to the list of directories to search
for included an imported files
error reporting format:
--error-format=gnu file:line:column: message (default)
--error-format=msvc file(line,column): message
fsm minimization:
-n Do not perform minimization
visualization:
-V Generate a dot file for Graphviz
-p Display printable characters on labels
-S <spec> FSM specification to output (for graphviz output)
-M <machine> Machine definition/instantiation to output (for graphviz output)</code>
Module usage
First add zig-fsm-compiler to your project
<code>build.zig.zon</code>
<code>zig
.fsm_compiler = .{
.url = "https://github.com/Cloudef/zig-fsm-compiler/archive/{COMMIT}.tar.gz",
.hash = "{HASH}",
},</code>
<code>build.zig</code>
<code>zig
const fsm_compiler = b.dependency("fsm_compiler", .{}).module("fsm-compiler");
exe.addModule("fsm-compiler", fsm_compiler);</code>
<code>main.zig</code>
```zig
const fsm_compiler = @import("fsm-compiler");
fn main() !void {
// TODO
}
```
Comptime usage
It is not possible to run the compiler itself comptime, but it is possible to use the generated output comptime.
zig-fsm-compiler provides "run artifact" that can be used to generate machines from your <code>build.zig</code>.
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
Running compiler comptime may be possible once https://github.com/ziglang/zig/issues/14931 is fixed.
</blockquote>
<code>build.zig</code>
```zig
const std = @import("std");
const fsm_compiler = @import("fsm-compiler");
pub fn build(b: *std.Build) void {
// TODO
}
```
Ragel
<a>Ragel</a> is a state machine compiler by Adrian Thurston.
It is highly recommended to read this <a>PDF</a> to learn the
Ragel language.
zig-fsm-compiler is written by studying the above PDF, it contains no code from the actual Ragel project aside from
the modified <code>rlscan.rl</code> to bootstrap the initial version of the Ragel language parser.
Differences from Ragel
While zig-fsm-compiler aims to be compatible with the Ragel language there are still differences.
<ul>
<li>Only zig target is supported for code generation.</li>
<li><em>Other languages may be supported in future, but it is not a priority.</em></li>
<li>Actions with code only works if using code generation.</li>
<li><em>It is possible to bind functions to actions to get past this limitation.</em></li>
<li>getkey, access, variable, write statements are ignored and hidden variables do not exist.</li>
<li><em>Instead the compiler generates a optimized machine and runner with an entrypoint for executing the machine.</em></li>
<li><em>This means zig-fsm-compiler is not compatible with the output of Ragel.</em></li>
<li>alphtype statement is ignored.</li>
<li><em>Instead the compiler always uses the smallest types possible for the optimized machine.</em></li>
</ul>
Examples
<blockquote>
</blockquote> | [] |
https://avatars.githubusercontent.com/u/7967463?v=4 | zf-wasm-playground | natecraddock/zf-wasm-playground | 2024-02-08T16:40:35Z | a simple web playground to demo zf | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/natecraddock/zf-wasm-playground/tags | - | [
"fuzzy-search",
"wasm",
"zig"
] | 97 | false | 2024-03-10T18:20:52Z | true | true | 0.12.0 | github | [
{
"commit": "fa11243c405ee2124c8f42bb0f6c3e7244bb39d1.tar.gz",
"name": "zf",
"tar_url": "https://github.com/natecraddock/zf/archive/fa11243c405ee2124c8f42bb0f6c3e7244bb39d1.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/natecraddock/zf"
}
] | zf wasm playground
See it live: https://nathancraddock.com/zf-playground/
Build
<code>$ zig build
$ mv zig-out/bin/zf.wasm .</code>
Run
Use a simple webserver like the one bundled with python
<code>$ python -m http.server</code> | [] |
https://avatars.githubusercontent.com/u/135145066?v=4 | deunicode | dying-will-bullet/deunicode | 2023-06-05T05:55:24Z | ASCII transliterations of Unicode text. | master | 1 | 2 | 1 | 2 | https://api.github.com/repos/dying-will-bullet/deunicode/tags | NOASSERTION | [
"ascii",
"deunicode",
"slugify",
"transliteration",
"unicode",
"unidecode",
"zig",
"ziglang"
] | 192 | false | 2025-01-08T13:03:58Z | true | true | unknown | github | [] | deunicode 🪚
<a></a>
The <code>deunicode</code> library(aka. <code>unidecode</code>) transliterates Unicode strings such as "Æneid" into pure
ASCII ones such as "AEneid."
This is an implementation of Rust's <a>deunicode</a> crate in Zig, using its own Unicode mapping data. Therefore, it is distributed under the same license.
Examples
```zig
const std = @import("std");
const deunicode = @import("deunicode").deunicode;
const deunicodeAlloc = @import("deunicode").deunicodeAlloc;
pub fn main() !void {
const allocator = std.heap.page_allocator;
<code>// Using allocator, caller should free the memory
const res = try deunicodeAlloc(allocator, "世界和平");
defer allocator.free(res);
std.debug.print("{s}\n", .{res}); // Shi Jie He Ping
// Using the buffer
var buffer: [1024]u8 = undefined;
const res2 = try deunicode(&buffer, "おはよう");
std.debug.print("{s}\n", .{res2}); // ohayou
</code>
}
```
API Doc
<ul>
<li><code>fn deunicodeAlloc(allocator: Allocator, s: []const u8) ![]const u8</code>:
Return new string, caller should free memory.</li>
<li><code>fn deunicode(out: []u8, s: []const u8) ![]const u8</code>:
Use buffer instead of allocator. Retrun a string slice.</li>
</ul>
When an ASCII replacement cannot be found, the default placeholder <code>[?]</code> is used.
If you want to customize the placeholder, you can use the following API.
<ul>
<li><code>fn deunicodeCustomAlloc(allocator: Allocator, s: []const u8, custom_placeholder: []const u8) ![]const u8</code></li>
<li><code>fn deunicodeCustom(out: []u8, s: []const u8, custom_placeholder: []const u8) ![]const u8</code></li>
</ul>
Installation
Add <code>deunicode</code> as dependency in <code>build.zig.zon</code>:
<code>.{
.name = "my-project",
.version = "0.1.0",
.dependencies = .{
.deunicode = .{
.url = "https://github.com/dying-will-bullet/deunicode/archive/refs/tags/v0.1.1.tar.gz",
.hash = "1220fef06e2fab740b409eaec28fee459526c86f297e6c43fdaee471084cc569f397",
},
},
}</code>
Expose <code>deunicode</code> as a module in <code>build.zig</code>:
```diff
diff --git a/build.zig b/build.zig
index 60fb4c2..0255ef3 100644
--- a/build.zig
+++ b/build.zig
@@ -15,6 +15,9 @@ pub fn build(b: *std.Build) void {
// set a preferred release mode, allowing the user to decide how to optimize.
const optimize = b.standardOptimizeOption(.{});
<ul>
<li>const opts = .{ .target = target, .optimize = optimize };</li>
<li>const deunicode_module = b.dependency("deunicode", opts).module("deunicode");
+
const exe = b.addExecutable(.{
.name = "m",
// In this case the main source file is merely a path, however, in more
@@ -23,6 +26,7 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = optimize,
});</li>
<li>
exe.addModule("deunicode", deunicode_module);
// This declares intent for the executable to be installed into the
// standard location when the user invokes the "install" step (the default
</li>
</ul>
```
Guarantees and Warnings
Here are some guarantees you have when calling <code>deunicode()</code>:
<ul>
<li>The <code>String</code> returned will be valid ASCII; the decimal representation of
every <code>char</code> in the string will be between 0 and 127, inclusive.</li>
<li>Every ASCII character (0x00 - 0x7F) is mapped to itself.</li>
<li>All Unicode characters will translate to printable ASCII characters
(<code>\n</code> or characters in the range 0x20 - 0x7E).</li>
</ul>
There are, however, some things you should keep in mind:
<ul>
<li>Some transliterations do produce <code>\n</code> characters.</li>
<li>Some Unicode characters transliterate to an empty string, either on purpose
or because <code>deunicode</code> does not know about the character.</li>
<li>Some Unicode characters are unknown and transliterate to <code>"[?]"</code>
(or a custom placeholder, or <code>None</code> if you use a chars iterator).</li>
<li>Many Unicode characters transliterate to multi-character strings. For
example, "世" is transliterated as "Shi".</li>
<li>Transliteration is context-free and not sophisticated enough to produce proper Chinese or Japanese.
Han characters used in multiple languages are mapped to a single Mandarin pronounciation,
and will be mostly illegible to Japanese readers. Transliteration can't
handle cases where a single character has multiple possible pronounciations.</li>
</ul>
Unicode data
<ul>
<li><a><code>Text::Unidecode</code></a> by Sean M. Burke</li>
<li><a>Unicodey</a> by Cal Henderson</li>
<li><a>gh emoji</a></li>
<li><a>any_ascii</a></li>
</ul>
For a detailed explanation on the rationale behind the original
dataset, refer to <a>this article</a> written
by Burke in 2001.
LICENSE
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
<ul>
<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>
<li>The names of this software's contributors may not be used to endorse or
promote products derived from this software without specific prior written
permission.</li>
</ul>
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | [] |
https://avatars.githubusercontent.com/u/55436060?v=4 | zuffy | arats-io/zuffy | 2023-10-14T14:19:42Z | null | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/arats-io/zuffy/tags | MIT | [
"logger",
"time",
"zig",
"zig-package",
"zoneinfo"
] | 540 | false | 2024-12-01T12:00:34Z | true | true | 0.13.0 | github | [] | Zig UFFY library
Current Zig UFFY library do offer bunch of extra functionality!
Work in progress...; If somewthing is not working, feel free to contribute or open a issue.
Require zig version: <strong>0.14.0-dev.850+ddcb7b1c1</strong>
Usage
Include the zuffy into the <code>build.zig.zon</code> file.
```
zig fetch --save https://github.com/arats-io/zuffy/archive/refs/tags/v.tar.gz
.dependencies = .{
.zuffy = .{
.url = "https://github.com/arats-io/zuffy/archive/refs/tags/v0.1.14.tar.gz",
.hash = "12201fd38f467e6c64ee7bca53da95863b6c05da77fc51daf0ab22079ede57cbd4e2",
},
},
```
List of modules
Pools
<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 Pool
Using allocator and the locker
<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 Pool Lock & Memory Free
Based on on implementation of @kprotty's from https://github.com/kprotty/zap
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Thread Pool
Copied from @kprotty's from https://github.com/kprotty/zap
Bytes
<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> Buffer
<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> Utf8Buffer (StringBuilder)
Time and Time Zoneinfo
<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> Time
<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> Time Zoneinfo
Usage
Environment variable <code>TZ</code> can be used to calculate a time for a different timezone.
```
export TZ='Europe/Tiraspol';
2023 Nov 5th Sun 22:33:05.477603 UTC+03:00
```
In case if machine is not having a way to fetch desired zoninfo, the library is considering embeded zip(and gziped) archive with all zone information.
```
export TZ='Europe/Tiraspol.zip';
2023 Nov 5th Sun 22:33:05.477603 UTC+03:00
```
<strong>NOTE</strong>
<a>time zones info</a> data are embeded (zip and gziped, having 92kb) into the 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> *nix systems
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> windows systems
Archives
<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> Zip
<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> archive extraction
<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> archive creation
<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> More archive formats to be added ...
Lists
<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> CircularList (FIFO & LIFO)
<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> SkipList
Eazy Logger
<a>zlog</a>
Contributing
Contributions of all kinds is welcome! | [] |
https://avatars.githubusercontent.com/u/72992574?v=4 | ziggy | UDogg/ziggy | 2023-08-10T19:39:51Z | Learning Zig by writing simple but optimized programs | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/UDogg/ziggy/tags | - | [
"calculator",
"prime-numbers",
"zig"
] | 4,347 | false | 2024-03-11T01:22:03Z | false | false | unknown | github | [] |
(A) calc.zig
Program Overview
The <a><code>calc.zig</code></a> program is a simple calculator application written in the Zig programming language. It allows you to perform basic arithmetic operations such as addition, subtraction, multiplication, division, and quotient(integer) division all in one. The program takes two user-provided integer inputs and then displays the results of these operations.
Prerequisites
<ul>
<li>Zig programming language installed on your system. You can download and install Zig for your OS from the official website: <a><code>Zig Downloads</code></a></li>
</ul>
Running the Program
Follow these steps to run the <a><code>calc.zig</code></a> program:
<ol>
<li>
<strong>Open a Terminal</strong>: Open a terminal window that you are comfortable with on your computer.
</li>
<li>
<strong>Navigate to Program Directory</strong>: Use the <code>cd</code> command to navigate to the directory where the <code>calc.zig</code> file is located.
</li>
<li>
<strong>Compile the Program</strong>: In the terminal, enter the following command to compile the program:
```sh
zig build-exe calc.zig
</li>
<li><strong>Run the Program</strong>: After successful compilation, run the compiled executable by typing:
<code>sh
./calc</code></li>
<li><strong>Follow Instructions</strong>: The program will prompt you to enter two numbers. Enter the first number and press Enter. Then, enter the second number and press Enter again.</li>
<li><strong>View Results</strong>: The program will display the results of various arithmetic operations performed on the provided numbers, including addition, subtraction, multiplication, quotient, and division. It will also show the execution time in milliseconds.</li>
<li><strong>Exit the Program</strong>: After viewing the results, the program will exit automatically.</li>
</ol>
Sample interaction
<code>sh
$ zig build-exe calc.zig
$ ./calc
Enter a number: 10
Enter another number: 5
The sum of 10 and 5 is 15
The difference of 10 and 5 is 5
The product of 10 and 5 is 50
The quotient of 10 and 5 is 2
The division of 10 and 5 produces 2.000000
Execution time(depends on your typing speed and time you took to enter numbers): 600 ms</code>
Notes
<ul>
<li>The program utilizes Zig's standard library modules for various functionalities like input/output, string manipulation, and arithmetic operations.</li>
<li>The program expects float/int inputs for arithmetic operations, and it handles invalid input scenarios by displaying appropriate error messages.</li>
<li>Results are displayed in scientific notation example 29 = 2.9e+01
3948573 = 3.948573e+06</li>
<li>The execution time displayed depends on the time you take to enter the numbers and your typing speed.</li>
</ul>
(B) prime.zig
Program Overview
The <a><code>prime.zig</code></a> program is designed to work with prime numbers. It offers functionalities to check if a given number is prime, find the nth prime number, print the first N prime numbers, and find the position of a specific prime number in the sequence of all prime numbers. The program uses a variety of functions and logic to achieve these tasks.
Prerequisites
<ul>
<li>Zig programming language installed on your system. You can download and install Zig for your OS from the official website: <a><code>Zig Downloads</code></a></li>
</ul>
Running the Program
Follow these steps to run the <a><code>prime.zig</code></a> program:
<ol>
<li>
<strong>Open a Terminal</strong>: Open a terminal window that you are comfortable with on your computer.
</li>
<li>
<strong>Navigate to Program Directory</strong>: Use the <code>cd</code> command to navigate to the directory where the <a><code>prime.zig</code></a> file is located.
</li>
<li>
<strong>Compile the Program</strong>: In the terminal, enter the following command to compile the program:
<code>sh
zig build-exe prime.zig</code>
</li>
<li><strong>Run the Program</strong>: After successful compilation, run the compiled executable by typing:
<code>sh
./prime</code></li>
<li><strong>Follow Instructions</strong>: The program will prompt you to enter the number of prime numbers you want to print (n), the value of N (the nth prime number you wish to find), and a prime number to find its position.</li>
<li><strong>View Results</strong>: The program will provide various outputs based on your inputs, including the first N prime numbers, the nth prime number, and the position of a specific prime number.</li>
<li><strong>Exit the Program</strong>: After viewing the results, the program will exit automatically.</li>
</ol>
Sample interaction
<code>sh
$ zig build-exe prime.zig
$ ./prime
Enter the number of prime numbers you want to print: 5
Enter the value of N (Nth prime number you wish to print): 3
Enter a prime number to find its position: 7
The first 5 prime numbers are: 2, 3, 5, 7, 11
The 3rd prime number is: 5
The position of 7 in the set of all prime numbers is 4
Total execution time: 0 milliseconds</code>
Notes
<ul>
<li>The program efficiently determines whether a given number is prime using the <strong>isPrime</strong> function, which employs various conditions and checks.</li>
<li>It calculates the nth prime number using the <strong>nthPrime</strong> function, which iterates through numbers and uses the <strong>isPrime</strong> function to find the nth prime.</li>
<li>The program displays the prime numbers using the primes function, which prints the requested number of prime numbers.</li>
<li>The <strong>findPrimePosition</strong> function determines the position of a specific prime number within the set of all prime numbers.</li>
<li>The execution time displayed may vary depending on your system's performance and user input.</li>
</ul>
Feel free to experiment with different input values and explore the program's functionalities!
(C) game.zig
<strong>In development</strong> freecodecamp guy
(D) net.zig
<strong>In development</strong>
Written with ❤️ and Ziglang
Written by
<a>Utkarsh "UC" Choudhary</a>
<a>
</a>
| [
"https://github.com/Arnau478/hevi",
"https://github.com/kristoff-it/zine"
] |
https://avatars.githubusercontent.com/u/7057784?v=4 | wasm2wasm2wasm | xonoxitron/wasm2wasm2wasm | 2023-05-30T09:24:00Z | 🤙 A bridge among Go, Rust and Zig WebAssembly runtimes 🦫 <-> 🦀 <-> ⚡ via JavaScript 🚀 | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/xonoxitron/wasm2wasm2wasm/tags | MIT | [
"golang",
"javascript",
"runtime",
"rust",
"wasm",
"web-assembly",
"zig"
] | 9 | false | 2024-12-23T20:24:58Z | false | false | unknown | github | [] | wasm2wasm2wasm: Go + Rust + Zig WASM Interop
wasm2wasm2wasm is a project that demonstrates WebAssembly (WASM) interoperation among Go, Rust and Zig modules using JavaScript as the intermediary. The project provides a web-based interface where users can perform addition, subtraction and multiplication operations using Go, Rust and Zig WASM modules.
Project Structure
The project consists of the following directories and files:
<ul>
<li><strong>go/</strong>: Contains the Go module source code.</li>
<li><strong>go.mod</strong>: Go module configuration file.</li>
<li>
<strong>main.go</strong>: Go module source code file.
</li>
<li>
<strong>rust/</strong>: Contains the Rust module source code.
</li>
<li><strong>main.rs</strong>: Rust module source code file.</li>
<li><strong>Cargo.toml</strong>: Cargo manifest file.</li>
</ul>
<strong>zig/</strong>: Contains the Zig module source code.
<ul>
<li>
<strong>main.zig</strong>: Zig module source code file.
</li>
<li>
<strong>bridge/</strong>: Contains the JavaScript and HTML files for the web interface.
</li>
<li><strong>wasm_exec.js</strong>: JavaScript file necessary for running Go WASM modules.</li>
<li><strong>wasm2wasm2wasm.js</strong>: JavaScript file that handles loading and interoperation among Go, Rust and Zig WASM modules.</li>
<li><strong>wasm2wasm2wasm.html</strong>: HTML file providing the web interface for performing operations.</li>
</ul>
Building the Project
To build the project and generate the WASM modules, follow these steps:
<ol>
<li>Compile the Rust module to WASM:</li>
</ol>
<code>bash
rustc --target wasm32-unknown-unknown --crate-type cdylib ./rust/main.rs -o ./bridge/rust_main.wasm</code>
<ol>
<li>Compile the Go module to WASM:</li>
</ol>
<code>bash
GOOS=js GOARCH=wasm go build -o ./bridge/go_main.wasm ./go/main.go</code>
<ol>
<li>Compile the Zig module to WASM:</li>
</ol>
<code>bash
zig build-lib -target wasm32-freestanding -dynamic -OReleaseSmall ./zig/main.zig</code>
Running the Project
To run the project, you need to serve the files over a web server. You can use any static file server of your choice. Here's an example using the <code>http-server</code> package:
<ol>
<li>Install <code>http-server</code> globally (if not already installed):</li>
</ol>
<code>bash
npm install -g http-server</code>
<ol>
<li>Serve the project files:</li>
</ol>
<code>bash
cd bridge
http-server</code>
<ol>
<li>Open your browser and navigate to the provided URL (usually <code>http://localhost:8080</code>).</li>
</ol>
Interacting with the Web Interface
Once the project is running in your browser, you'll see the web interface with two input fields (a and b) and three buttons for performing addition and subtraction operations.
<ul>
<li>
<strong>Add with Go WASM</strong>: Calculates the sum of values entered in the 'a' and 'b' fields using the Go WASM module.
</li>
<li>
<strong>Sub with Rust WASM</strong>: Calculates the subtraction of values entered in the 'a' and 'b' fields using the Rust WASM module.
</li>
<li>
<strong>Mul with Rust WASM</strong>: Calculates the multiplication of values entered in the 'a' and 'b' fields using the Zig WASM module.
</li>
</ul>
The result of the operation will be displayed in the 'r' field.
Understanding the Code
The project consists of three main components: the Go WASM module, the Rust WASM module and the Zig WASM module, which are loaded and interacted with using JavaScript as the intermediary. Here's a brief explanation of each component:
<ul>
<li><strong>Go WASM Module (main.go)</strong>:</li>
<li>The <code>main.go</code> file contains the Go code for the WASM module.</li>
<li>The <code>add</code> function performs addition of two numbers and is registered as an exported function using <code>js.Global().Set</code>.</li>
<li>The <code>registerCallback</code> function registers the <code>add</code> function as a callback for JavaScript to invoke.</li>
<li>
The <code>main</code> function initializes the Go WASM module, registers the callback, and waits indefinitely for JavaScript calls.
</li>
<li>
<strong>Rust WASM Module (main.rs)</strong>:
</li>
<li>The <code>main.rs</code> file contains the Rust code for the WASM module.</li>
<li>The <code>subtract</code> function performs subtraction of two numbers.</li>
<li>The <code>initialize</code> function logs a message indicating the initialization of the Rust WASM module.</li>
<li>
The <code>extern</code> block defines the <code>console_log</code> function, which allows Rust to log messages to the JavaScript console.
</li>
<li>
<strong>Zig WASM Module (main.zig)</strong>:
</li>
<li>The <code>main.zig</code> file contains the Rust code for the WASM module.</li>
<li>
The <code>multiply</code> function performs subtraction of two numbers.
</li>
<li>
<strong>JavaScript Interoperability (wasm2wasm2wasm.js)</strong>:
</li>
<li>The <code>loadGoWasm</code> function loads and runs the Go WASM module using the <code>Go</code> class and WebAssembly APIs.</li>
<li>The <code>loadRustWasm</code> function loads and instantiates the Rust WASM module, defining the <code>console_log</code> function as an import.</li>
<li>The <code>loadZigWasm</code> function loads and instantiates the Zig WASM module.</li>
<li>The <code>addWithGo</code> function is called when the "Add with Go WASM" button is clicked, invoking the Go WASM module's <code>add</code> function and updating the result field.</li>
<li>The <code>subtractWithRust</code> function is called when the "Sub with Rust WASM" button is clicked, invoking the Rust WASM module's <code>subtract</code> function and updating the</li>
<li>The <code>multiplyWithZig</code> function is called when the "Mul with Rust WASM" button is clicked, invoking the Zig WASM module's <code>multiply</code> function and updating the result field.</li>
</ul>
Conclusion
wasm2wasm2wasm demonstrates how to achieve WASM interoperation among Go, Rust and Zig modules using JavaScript as the bridge. The project provides a clear example of how to load, initialize, and interact with WASM modules from different languages. You can use this project as a starting point for more complex interoperations or as a reference for understanding WASM interop concepts. Feel free to explore and modify the project to suit your needs! | [] |
https://avatars.githubusercontent.com/u/116491743?v=4 | Cellulator | efjimm/Cellulator | 2023-04-11T01:06:57Z | Spreadsheet program written in Zig | master | 4 | 2 | 0 | 2 | https://api.github.com/repos/efjimm/Cellulator/tags | GPL-3.0 | [
"spreadsheets",
"zig"
] | 3,140 | false | 2025-05-14T18:25:20Z | true | true | unknown | github | [
{
"commit": "master",
"name": "wcwidth",
"tar_url": "https://github.com/efjimm/zig-wcwidth/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/efjimm/zig-wcwidth"
},
{
"commit": "master",
"name": "shovel",
"tar_url": "https://github.com/efjimm/shovel/archive/mast... | Cellulator
Cellulator is a TUI spreadsheet calculator written in <a>Zig</a>.
Portability
Cellulator works on Linux and MacOS. Zig's standard library is currently missing some constants and
types for other POSIX compliant OS's that are required by Cellulator, and may or may not build for
them.
Terminal Compatibility
Cellulator should be compatible with most modern software terminals. Cellulator does not use
curses, instead using a <a>fork</a> of
<a>zig-spoon</a>. spoon uses vt-100 escape sequences to draw
to the screen, which should be supported by any modern terminal.
Installation
Requirements:
<ul>
<li>Zig master</li>
</ul>
Clone the repo and run <code>zig build -Doptimize=ReleaseSafe</code> to build the project. The resulting
binary will be in zig-out/bin by default.
Run <code>zig build test -fsummary</code> to run the tests.
Usage
Cellulator is currently in early development. Expect missing features. If you actually intend on
using Cellulator, build it in ReleaseSafe mode to catch any latent bugs.
The maximum sheet size is 4,294,967,296 rows by 4,294,967,296 columns.
Modes
Cellulator used mode-based input, like in vim. There are multiple modes in Cellulator:
<ul>
<li>normal</li>
<li>visual</li>
<li>visual select</li>
<li>command normal</li>
<li>command insert</li>
<li>command operator pending</li>
</ul>
Normal mode allows you to move around the sheet using vim-like motions and perform various
operations. Visual mode is used for performing operations on a range of cells interactively.
Command normal and command insert mode allow for editing the command buffer and submitting
commands. Command operator pending modes perform a specific action on a range of text delimited by
an inputted motion.
Statements / Commands
Cellulator differentiates between <strong>statements</strong> and <strong>commands</strong>. They can both be entered via the
command line. The main difference is that statements can be read from a file - this is how
Cellulator saves sheet state to disk.
There is currently only one type of statement in cellulator:
<ul>
<li><code>let {cell address} = {expression}</code></li>
<li>{cell address} is the text address of a cell, e.g. <code>A0</code>, <code>GL3600</code></li>
<li>{expression} is any <a>expression</a></li>
</ul>
Commands can be entered via placing a colon character as the first character of a command.
Pressing ':' in normal mode will do this automatically. What follows is a list of currently
implemented commands. Values surrounded in {} are optional.
<ul>
<li><code>w {filepath}</code> Save to the given filepath, or to the sheet's filepath if not specified.</li>
<li><code>e{!} filepath</code> Try to load from the given file. Will not continue if there are unsaved changes.
This can be overridden by specifying a ! after 'e'.</li>
<li><code>q{!}</code> Quit the program. Will not continue if there are unsaved changes, unless ! is specified.</li>
<li><code>fill (range) (value) {increment}</code></li>
<li>Fills the given range with value, incrementing by increment each cell. Increment is applied
left to right, top to bottom. Example: ":fill b1:d12 30 0.2"</li>
<li><code>bw {filepath}</code> Save to the given filepath in a binary format. This format is significantly
faster to save/load. Filepath must be specified.</li>
<li><code>be {filepath}</code> Load from the given filepath in a binary format.</li>
<li><code>text-align [cell address] left|right|center</code> Set the alignment of the text in the specified cell.
If the cell address is not given, the cell under the cursor is affected.</li>
</ul>
Expressions
Expressions consist of number/string literals, cell references, cell ranges, builtin functions,
and operators. They can be used on the right-hand side of the <code>=</code> in a <code>let</code> statement.
Number literals
Number literals consist of a string of ASCII digit characters (0-9) and underscores, with at most
one decimal point. Underscores are ignored and are only used for visual separation of digits.
Underscores are not preserved when assigned to cells.
Examples:
<ul>
<li><code>1000000</code></li>
<li><code>1_000_000</code></li>
<li><code>1_234_567.000_089</code></li>
</ul>
String Literals
String literals consist of arbitrary text surrounded by single or double quotes. There is
currently no way to escape quotes inside of quotes.
Examples:
<ul>
<li>'This is a string'</li>
<li>'Double "quotes" inside of single quotes'</li>
<li>"Single 'quotes' inside of double quotes"</li>
</ul>
Cell References
Cell references evaluate to the value of another cell. The value returned by a cell reference will be
updated if the expression contained by that cell changes.
Examples:
<ul>
<li><code>A0</code></li>
<li><code>GP359</code></li>
<li><code>crxp65535</code> (Last cell in a sheet)</li>
</ul>
Cell Ranges
Cell ranges represent all cells in the inclusive square area between two positions. Cell ranges can
only be used in builtin functions. They are defined as two cell references separated with a colon
<code>:</code> character.
Examples:
<ul>
<li><code>A0:B0</code> (Contains 2 cells)</li>
<li><code>A0:A0</code> (Contains 1 cell)</li>
<li><code>D6:E3</code> (Contains 8 cells)</li>
</ul>
Numeric Operators
The following is a list of all operators that return number values. They try to convert non-number
operands (e.g. strings) to numbers. Strings that cannot be converted to numbers will return an
InvalidCoercion error.
<ul>
<li>unary <code>+</code> Positive numeric literal</li>
<li>unary <code>-</code> Negative numeric literal</li>
<li>binary <code>+</code> Addition</li>
<li>binary <code>-</code> Subtraction</li>
<li><code>*</code> Multiplication</li>
<li><code>/</code> Division</li>
<li><code>%</code> Modulo division (remainder)</li>
<li><code>(</code> and <code>)</code> Grouping operators</li>
</ul>
String Operators
The following is a list of operators that return string values. They try to convert non-string
operands to strings. Converting a number to a string never fails outside of OOM situations.
<ul>
<li><code>#</code> Concatenates the strings on the left and right</li>
<li>Examples:<ul>
<li><code>'This is a string' # ' that has been concatenated'</code></li>
<li><code>'1: ' # A0</code></li>
<li><code>A0 # B0</code></li>
</ul>
</li>
</ul>
Builtin Functions
Builtin functions perform specific operations on a number of arguments. Builtins are used in the
format <code>@builtin_name(argument_1, argument_2, argument_3, ...)</code>. Different builtins take and
return different types and numbers of arguments.
The following builtins take an arbitrary number of arguments and coerce them to numbers. They may
also take ranges as arguments.
<ul>
<li><code>@sum</code> Returns the sum of its arguments</li>
<li><code>@prod</code> Returns the product of its arguments</li>
<li><code>@avg</code> Returns the average of its arguments.</li>
<li><code>@min</code> Returns the smallest argument.</li>
<li><code>@max</code> Returns the largest argument.</li>
</ul>
The following builtins take one argument and coerce it to a string. They may <em>not</em> take a range
as an argument.
<ul>
<li><code>@upper</code> Returns the ASCII uppercase version of its argument as a string.</li>
<li><code>@lower</code> Returns the ASCII lowercase version of its argument as a string.</li>
</ul>
Keybinds
Motions in command normal and command operator pending modes can be prefixed by a number, which
will repeat the following motion that many times. This does not currently work for any of the
<em>inside</em> or <em>around</em> motions.
Normal Mode
<ul>
<li><code>1-9</code> Set count</li>
<li><code>0</code> Set count if count is not zero, otherwise move cursor to the first populated cell on the
current row</li>
<li><code>j</code>, <code>Down</code> Move cursor down</li>
<li><code>k</code>, <code>Up</code> Move cursor up</li>
<li><code>h</code>, <code>Left</code> Move cursor left</li>
<li><code>l</code>, <code>Right</code> Move cursor right</li>
<li><code>:</code> Enter command insert mode</li>
<li><code>=</code> Enter command insert mode, with text set to <code>let cellname =</code>, where cellname is the cell
under the cursor</li>
<li><code>e</code> Edit the expression of the current cell</li>
<li><code>dd</code>, <code>x</code> Delete the cell under the cursor</li>
<li><code>Esc</code> Dismiss status message</li>
<li><code>$</code> Move cursor to the last populated cell on the current row</li>
<li><code>gc</code> Move cursor to the count column</li>
<li><code>gr</code> Move cursor to the count row</li>
<li><code>gg</code> Move cursor to the first cell in the current column</li>
<li><code>G</code> Move cursor to the last cell in the current column</li>
<li><code>w</code> Move cursor to the next populated cell</li>
<li><code>b</code> Move cursor to the previous populated cell</li>
<li><code>f</code> Increase decimal precision of the current column</li>
<li><code>F</code> Decrease decimal precision of the current column</li>
<li><code>+</code> Increase width of current column if non-empty</li>
<li><code>-</code> Decrease width of current column if non-empty</li>
<li><code>aa</code> Fit column width to contents</li>
<li><code>u</code> Undo</li>
<li><code>U</code> Redo</li>
<li><code><</code> Align text under cursor to the left</li>
<li><code>></code> Align text under cursor to the right</li>
<li><code>|</code> Align text undor cursor to the center</li>
</ul>
Visual Mode
<ul>
<li>All normal mode motions</li>
<li><code>Esc</code>, <code>C-[</code> Enter normal mode</li>
<li><code>d</code>, <code>x</code> Delete the cells in the given range</li>
<li><code>o</code> Swap cursor and anchor</li>
<li><code>Alt-j</code> Move selection down count times</li>
<li><code>Alt-k</code> Move selection up count times</li>
<li><code>Alt-h</code> Move selection left count times</li>
<li><code>Alt-l</code> Move selection right count times</li>
</ul>
Visual Select Mode
<ul>
<li>All visual mode motions</li>
<li><code>Return</code> Write the selected range to the command buffer</li>
<li><code>Esc</code> Cancel select mode</li>
</ul>
Command Insert Mode
<ul>
<li><code>Esc</code> Enter command normal mode</li>
<li><code>Return</code>, <code>C-m</code>, <code>C-j</code> Submit the current text as a command</li>
<li><code>Backspace</code>, <code>Del</code> Delete the character before the cursor and move backwards one</li>
<li><code>C-p</code>, <code>Up</code> Previous command</li>
<li><code>C-n</code>, <code>Down</code> Next command</li>
<li><code>C-a</code>, <code>Home</code> Move cursor to the beginning of the line</li>
<li><code>C-e</code>, <code>End</code> Move cursor to the end of the line</li>
<li><code>C-f</code>, <code>Right</code> Move cursor forward one character</li>
<li><code>C-b</code>, <code>Left</code> Move cursor backward one character</li>
<li><code>C-w</code> Delete the word before the cursor</li>
<li><code>C-u</code> Delete all text in the command buffer</li>
<li><code>C-v</code> Enter visual select mode</li>
<li><code>C-p</code>, <code><Up></code> History prev</li>
<li><code>C-n</code>, <code><Down></code> History next</li>
</ul>
Command Normal Mode
<ul>
<li><code>Esc</code> Leaves command mode without submitting command</li>
<li><code>1-9</code> Set count</li>
<li><code>0</code> Set count if count is not zero, otherwise move cursor to the first populated cell on the
current row</li>
<li><code>h</code>, <code>Left</code> Move cursor left count times</li>
<li><code>l</code>, <code>Right</code> Move cursor right count times</li>
<li><code>k</code>, <code>Up</code> Previous command count times</li>
<li><code>j</code>, <code>Down</code> Next command count times</li>
<li><code>i</code> Enter command insert mode</li>
<li><code>I</code> Enter command insert mode and move to the beginning of the line</li>
<li><code>a</code> Enter command insert mode and move one character to the right</li>
<li><code>A</code> Enter command insert mode and move to the end of the line</li>
<li><code>s</code> Delete the character under the cursor and enters command insert mode</li>
<li><code>S</code> Deletes all text and enters command insert mode</li>
<li><code>x</code> Delete the character under the cursor</li>
<li><code>d</code> Enter operator pending mode, with deletion as the operator action</li>
<li><code>c</code> Enter operator pending mode, with change (delete and enter insert mode) as the operator action</li>
<li><code>D</code> Deletes all text at and after the cursor</li>
<li><code>C</code> Deletes all text at and after the cursor, and enters command insert mode</li>
<li><code>w</code> Moves cursor to the start of the next word count times</li>
<li><code>W</code> Moves cursor to the start of the next WORD count times</li>
<li><code>b</code> Moves cursor to the start of the previous word count times</li>
<li><code>B</code> Moves cursor to the start of the previous WORD count times</li>
<li><code>e</code> Moves cursor to the end of the next word count times</li>
<li><code>E</code> Moves cursor to the end of the next WORD count times</li>
<li><code>M-e</code> Moves cursor to the end of the previous word count times</li>
<li><code>M-E</code> Moves cursor to the end of the previous WORD count times</li>
<li><code>$</code>, <code>End</code> Move cursor to the end of the line</li>
<li><code>k</code>, <code><Up></code> History prev</li>
<li><code>j</code>, <code><Down></code> History next</li>
</ul>
Command Operator Pending Mode
Performs the given operation on the text delimited by the next motion
<ul>
<li>All motions in command normal mode</li>
<li><code>iw</code> Inside word</li>
<li><code>aw</code> Around word</li>
<li><code>iW</code> Inside WORD</li>
<li><code>aW</code> Around WORD</li>
<li><code>i(</code>, <code>i)</code> Inside parentheses</li>
<li><code>a(</code>, <code>a)</code> Around parentheses</li>
<li><code>i[</code>, <code>i]</code> Inside brackets</li>
<li><code>a[</code>, <code>a]</code> Around brackets</li>
<li><code>i{</code>, <code>i}</code> Inside braces</li>
<li><code>a{</code>, <code>a}</code> Around braces</li>
<li><code>i<</code>, <code>i></code> Inside angle brackets</li>
<li><code>a<</code>, <code>a></code> Around angle brackets</li>
<li><code>i"</code> Inside double quotes</li>
<li><code>a"</code> Around double quotes</li>
<li><code>i'</code> Inside single quotes</li>
<li><code>a'</code> Around single quotes</li>
<li><code>i`</code> Inside backticks</li>
<li><code>a`</code> Around backticks</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/54369961?v=4 | fpaper.zig | ferhatgec/fpaper.zig | 2023-06-05T22:59:34Z | zig implementation of fpaper file format | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/ferhatgec/fpaper.zig/tags | MIT | [
"file-format",
"fpaper",
"zig"
] | 5 | false | 2023-06-05T23:04:06Z | false | false | unknown | github | [] | <a>fpaper</a>.zig
zig implementation of <a>fpaper</a> file format
see other implementations:
<ul>
<li><a>c++</a></li>
<li><a>rust</a></li>
<li><a>python</a></li>
<li><a>c++ (renderer)</a></li>
</ul>
fpaper.zig licensed under the terms of MIT License. | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | tracy-zig | kassane/tracy-zig | 2023-08-01T12:35:42Z | Tracy binding for Zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/kassane/tracy-zig/tags | - | [
"bindings",
"tracy",
"zig",
"ziglang"
] | 12 | false | 2023-08-01T17:07:44Z | true | false | unknown | github | [] | tracy-zig
Tracy binding for Zig (WiP)
Requirement
<ul>
<li>zig <a>v0.11</a> or higher</li>
<li>git (download <a>tracy</a>)</li>
</ul>
Reference
<ul>
<li><a>zls</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/54369961?v=4 | ffetch.zig | ferhatgec/ffetch.zig | 2023-06-04T20:25:36Z | ffetch in zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/ferhatgec/ffetch.zig/tags | MIT | [
"fetch",
"libcurl",
"request",
"zig"
] | 4 | false | 2023-06-04T20:33:53Z | false | false | unknown | github | [] | <a>fetch fetch</a>
simple web fetching in zig via curl
ffetch.zig licensed under the terms of MIT License. | [] |
https://avatars.githubusercontent.com/u/21037233?v=4 | zigget | zekexiao/zigget | 2023-05-30T09:47:11Z | zig clone and zig build | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/zekexiao/zigget/tags | - | [
"zig"
] | 7 | false | 2023-06-05T03:24:56Z | true | false | unknown | github | [] | zigget
a simple tool for clone and build zig sources,
do <code>zigget install zigtools/zls</code> command list:
<ol>
<li>git clone https://github.com/zigtools/zls $HOME/.zigget/source/zigtools/zls</li>
<li>zig build -Doptimize=ReleaseFast</li>
<li>ln -s $HOME/.zigget/source/zigtools/zls/zig-out/bin/zls $HOME/.zigget/bin/zls</li>
</ol>
usage
<code>zigget command options</code>
<code>install, git clone repo, build, and create symlink
update, git pull repo and build
remove, remove installed repo
list, for list all install repo</code> | [] |
https://avatars.githubusercontent.com/u/43040593?v=4 | zig_appimage | dantecatalfamo/zig_appimage | 2023-08-01T00:21:46Z | Tiny script that creates a single self-contained AppImage for zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/dantecatalfamo/zig_appimage/tags | - | [
"appimage",
"zig"
] | 2 | false | 2023-09-22T13:22:31Z | false | false | unknown | github | [] | zig_appimage
Tiny script that creates a single self-contained AppImage for zig.
The entire compiler and all of its files are merged into a single file.
Usage
<code>./create_all.sh</code> - Creates AppImages for x86-64 and arm64 | [] |
https://avatars.githubusercontent.com/u/10529756?v=4 | zig-weact-ch582f-bare | mejobloggs/zig-weact-ch582f-bare | 2023-06-08T10:39:08Z | Barebones led blink | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/mejobloggs/zig-weact-ch582f-bare/tags | - | [
"ch582",
"wch",
"weact",
"zig",
"ziglang"
] | 11 | false | 2023-11-01T17:11:27Z | true | false | unknown | github | [] | Board: https://github.com/WeActStudio/WeActStudio.WCH-BLE-Core
MCU: WCH CH582F
Barebones led blinkage without using a timer
build just with plain <code>zig build</code> command, build.zig has everything setup
flash with <code>wchisp flash ./zig-out/bin/weact-ch582f</code>
wchisp found here: https://ch32-rs.github.io/wchisp/ | [] |
https://avatars.githubusercontent.com/u/59750184?v=4 | sqlp.zig | fremantle-industries/sqlp.zig | 2023-03-25T02:22:54Z | A generic SQL parser aiming to support all major dialects | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/fremantle-industries/sqlp.zig/tags | MIT | [
"sql",
"sql-parser",
"zig"
] | 2 | false | 2023-03-29T10:06:42Z | true | false | unknown | github | [] | sqlp.zig
A generic SQL parser aiming to support all major dialects
Development
<code>sh
make</code>
Test
<code>sh
make test</code>
Authors
<ul>
<li>Alex Kwiatkowski - alex+git@fremantle.io</li>
</ul>
License
<code>sqlp.zig</code> is released under the <a>MIT license</a> | [] |
https://avatars.githubusercontent.com/u/5215793?v=4 | aprender-zig | panda-coder/aprender-zig | 2023-02-10T16:56:32Z | Repositório para aprendizagem da linguagem zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/panda-coder/aprender-zig/tags | MIT | [
"programming",
"zig"
] | 5 | false | 2023-03-04T23:57:04Z | false | false | unknown | github | [] | Aprender zig
First steps
<ul>
<li>Check the <a>Getting start</a> official</li>
</ul>
<em>obs: I am currently using the snap installation for ubuntu</em>
Hello World
<ol>
<li><a>Exemplo de Hello World</a></li>
</ol>
Types and declaring variables
<ol>
<li><a>Declaring variables</a> ( <a>How to Run</a> )</li>
</ol>
License
<a>MIT</a> | [] |
https://avatars.githubusercontent.com/u/74733047?v=4 | traitor | greytdepression/traitor | 2023-08-24T17:02:36Z | A small public-domain trait framework for zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/greytdepression/traitor/tags | 0BSD | [
"traits",
"zig"
] | 35 | false | 2023-11-01T17:24:32Z | true | false | unknown | github | [] | traitor
A small public-domain trait framework for zig
This software is in the public domain for jursidictions in which the public
domain exists. Alternatively, it is available under the Zero-Clause BSD
license.
Quick Start
Zig's standard library already has trait helpers in the form of std.meta.trait that
let you query a type for declarations and fields by name.
Traitor works in a more Rust inspired way. You define a trait by building a struct
that contains all the desired fields, declarations, and functions.
```zig
const GraphTrait = struct {
pub const Directed = false;
<code>num_vertices: usize,
// This is just a dummy implementation used to obtain the function signature.
// Traits are only meant to be a compile time construct and not used at runtime.
pub fn hasEdge(i: usize, j: usize) bool {
_ = j; _ = i; unreachable;
}
</code>
};
<code>*Note that (function) declarations must be marked `pub` in order for traitor to see them.*
Now if you want to check another type against those trait bounds, you can call
`traitor.checkTrait(GraphTrait, MyOtherType)`. Traitor will then check that `MyOtherType` also
has a declaration `Directed` of type `bool`, a field `num_vertices` of type `usize`, and a function
`hasEdge` taking two `usize` and returning a `bool`.
This is intended to be used in generic functions, e.g.</code>zig
fn dijkstra(graph: anytype, start: usize, end: usize) -> Path {
comptime traitor.checkTrait(GraphTrait, @TypeOf(graph));
<code>// code here
</code>
}
<code>``
Make sure to call</code>checkTrait<code>with the</code>comptime` keyword to ensure that the zig compiler does not
print additional compile errors that arise from your code trying to access missing declarations or
fields if the trait bounds are not met.
Additionally, traitor allows you to add some meta data to your traits. Any declaration whose identifier
starts with <code>__traitor</code> will be skipped when checking trait bounds. Currently, the only meta data traitor
recognizes is <code>__traitor_trait_name</code> which can be set to a string (literal) and overrides the name
traitor will call the trait in error messages.
<code>zig
const GraphTrait2 = struct {
pub const __traitor_trait_name = "Graph II";
// ...
};</code>
<strong>Warning: the prefix <code>__traitor_internal</code> is reserved for internal meta data. Using it yourself may
result in unforseen errors.</strong>
Optional Fields and Declarations
Sometimes you might want to allow an implementation of a trait to choose to not implement a certain
field or declaration. For this case traitor allows you to hint to it that a certain field/declaration
is optional. It will not throw a compile error if the type implementing your trait does not have said
field/declaration, however, if a field/declaration of said name exists it will be type checked.
To mark a field/declaration as optional you simply wrap its type in <code>traitor.Optional</code>.
```zig
const Trait = struct {
foo: traitor.Optional(usize),
<code>pub const Bar: traitor.Optional(type) = .{};
pub const foobar: traitor.Optional(fn (usize, usize) bool) = .{};
</code>
};
<code>This trait above is then e.g. implemented by the empty struct `struct {}` or by</code>zig
const Type = struct {
foo: usize,
<code>pub const Bar: type = void;
pub fn foobar(i: usize, j: usize) bool {
// code
}
</code>
};
```
Associated Types
One limitation that might become obvious pretty quickly is that defining methods is not possible
with the tools laid out above. Specifically, if we had a trait
<code>zig
const GraphTrait = struct {
pub fn numEdges(self: GraphTrait) usize {
// code
}
};</code>
then any type implementing <code>GraphTrait</code> would have to add a function <code>numEdges</code> that takes as input
parameter an instance of <code>GraphTrait</code> -- not of the type that implements it.
```zig
const MyGraph = struct {
num_edges: usize,
<code>pub fn numEdges(self: GraphTrait) usize {
// no access to the field `num_edges` :(
}
</code>
};
```
To allow for this, traitor can handle 'associated types' that get substituted at comptime to the
relevant actual types.
<code>GenericSelf</code>
The type <code>traitor.GenericSelf</code> will be substituted to whatever type that is being checked against trait
bounds. So in the above example, we could actually implement methods using <code>traitor.GenericSelf</code>:
```zig
const GraphTrait = struct {
pub fn numEdges(self: traitor.GenericSelf) usize {
return 0;
}
};
const MyGraph = struct {
num_edges: usize,
<code>pub fn numEdges(self: MyGraph) usize {
return self.num_edges; // :)
}
</code>
};
<code>Since type substitution works recursively, this also works with compound types and we can thus even take pointers
to `self` and modify the struct.</code>zig
const GraphTrait = struct {
pub fn addEdge(self: *traitor.GenericSelf, i: usize, j: usize) void {
// ...
}
};
const MyGraph = struct {
pub fn addEdge(self: *MyGraph, i: usize, j: usize) void {
// code
}
};
```
<code>AssociatedType("AssociatedTypeName")</code>
We can use the same type substitution as in <code>traitor.GenericSelf</code> with arbitrary other associated types.
To add an associated type, first the trait needs to have a declaration of type <code>type</code> and whose name is
the name of the associated type.
<code>zig
const GraphTrait = struct {
pub const Payload = usize;
};</code>
Note that the types implementing your trait will be able to override the value
of the declaration (i.e. what type the payload will be in this example), but they will still need to supply
a <code>type</code> (e.g. they might use <code>Payload = []const u8</code> to store strings instead of integers).
After that, you can reference this associated type throughout your trait using <code>traitor.AssociatedType("<name of AT>")</code>.
```zig
const GraphTrait = struct {
pub const Payload = usize;
pub const DefaultPayload: traitor.AssociatedType("Payload") = undefined;
<code>some_node_payload: traitor.AssociatedType("Payload"),
pub fn getPayload(self: traitor.GenericSelf, i: usize) traitor.AssociatedType("Payload") {
// ...
}
</code>
};
const MyGraph = struct {
pub const Payload = []const u8;
pub const DefaultPayload: []const u8 = "foobar";
<code>some_node_payload: []const u8,
pub fn getPayload(self: MyGraph, i: usize) []const u8 {
return self.some_node_payload;
}
</code>
};
```
Error Codes
Traitor prints a two digit error code (e.g. <code>[E01]</code>) at the start of each error message. These can be
cross referenced here for a more detailed explanation of the kind of error traitor encountered.
<code>[E00] Unknown</code>
This is the default error value and should never be encountered. If you see an <code>[E00]</code> error message,
traitor itself has a bug. Please file an issue about it :)
<code>[E01] TraitNotAStruct</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. Traits are
defined using structs (see above in the Quick Start guide). You or the library that you are using supplied
something different from a trait.
As an example, the following code will produce this error as <code>u32</code> is not a struct:
<code>zig
// [E01] The trait must be a struct but 'u32' is not.
traitor.checkTrait(u32, TypeToCheck);</code>
<code>[E02] TypeNotAStruct</code>
This is an error with the type you supplied. Similarly to the trait itself, the type that you check must
also be a struct. The following code will produce this error:
<code>zig
// [E02] The type implementing the trait must be a struct but 'u32' is not.
traitor.checkTrait(GraphTrait, u32);</code>
<code>[E03] DeclarationIncompatibleType</code>
This is an error with the type you supplied. The type you supplied contains a declaration that has the same
name as one of the required declarations of your trait, but it has the wrong type. With the graph example
above, the following implementation would cause this error:
```zig
const MyGraph = struct {
<code>// [E03] Declaration 'Directed' has the wrong type. Expected 'bool', found '*const [5:0]u8'.
pub const Directed = "maybe";
// ...
</code>
};
```
<code>[E04] FunctionIncompatibleSignature</code>
This is an error with the type you supplied. The type you supplied contains a function declaration that has the
same name as one of the required function declarations of your trait, but it has the wrong signature. With the
graph example above, the following implementation would cause this error:
```zig
const MyGraph = struct {
<code>// [E04] Function 'hasEdge' has the wrong signature. Expected 'fn(usize, usize) bool', found 'fn(bool) void'.
pub fn hasEdge(foo: bool) void {}
// ...
</code>
};
```
<code>[E05] FieldIncompatibleType</code>
This is an error with the type you supplied. The type you supplied contains a field that has the same
name as one of the required fields of your trait, but it has the wrong type. With the graph example
above, the following implementation would cause this error:
```zig
const MyGraph = struct {
<code>// [E05] Field 'num_vertices' has the wrong type. Expected 'usize', found 'bool'.
num_vertices: bool,
// ...
</code>
};
```
<code>[E06] MissingDeclaration</code>
<code>[E07] MissingFunction</code>
<code>[E08] MissingField</code>
This is an error with the type you supplied. The type is missing a declaration/function declaration/field.
With the graph example above, the following implementation would cause this error:
<code>zig
// [E06] Missing declaration 'pub Directed: bool'.
// [E07] Missing function declaration 'pub fn hasEdge(usize, usize) bool {}'.
// [E08] Missing field 'num_vertices: usize'.
const MyGraph = struct {};</code>
<code>[E09] TraitMetaDataHasIncorrectType</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. One of the
meta data declarations of the trait has the wrong type. You or the library that you are using supplied
added incompatible meta data.
As an example, the following code will produce this error as <code>__traitor_trait_name</code> must be a string.
<code>zig
const GraphTrait = struct {
// [E09] The type of the trait's '__traitor_trait_name' declaration must be compatible with
// '[]const u8', found 'bool' instead.
pub const __traitor_trait_name = false;
};</code>
<code>[E10] TraitIllegalUseOfTraitorInternalDecl</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. The trait has
a declaration whose name starts with <code>__traitor_internal</code>. This prefix is reserved for internal mechanisms
and thus this declaration caused an error in the internal logic.
As an example, the following code will produce this error as <code>__traitor_internal_associated_type_decl_name</code>
is used internally.
<code>zig
const GraphTrait = struct {
// [E10] Illegal use of `__traitor_internal_associated_type_decl_name` declaration in trait.
pub const Foobar: struct {
pub const __traitor_internal_associated_type_decl_name = 9;
} = .{};
};</code>
<code>[E11] TraitMissingAssociatedTypeDeclaration</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. The trait references
an associated type, but never declares it.
As an example, the following code will produce this error as <code>Payload</code> is never declared.
```zig
const GraphTrait = struct {
// [E11] Expected declaration of associated type 'Payload' in trait.
pub fn defaultPayload() traitor.AssociatedType("Payload") {
// code
}
<code>// To fix this, uncomment type following line and add a type
// pub const Payload: type = ...;
</code>
};
```
<code>[E12] TraitAssociatedTypeNotAType</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. The trait references
an associated type, but the declaration is not of type <code>type</code>.
As an example, the following code will produce this error as <code>Payload</code> is an <code>i32</code> and not a <code>type</code>. It would
be correct to define <code>Payload = i32</code>.
```zig
const GraphTrait = struct {
// [E12] Expected declaration of associated type 'Payload' to be of type 'type', got 'i32' instead.
pub fn defaultPayload() traitor.AssociatedType("Payload") {
// code
}
<code>pub const Payload: i32 = 0;
</code>
};
```
<code>[E13] TraitGenericTypeLayoutNotAuto</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. The trait has a field
or declaration that has a type that makes use of an associated type internally while also having non-auto layout.
As an example, the following code will produce this error as <code>GenericAssociatedFoo</code> has type that is an
<code>extern struct</code> (thus layout <code>extern</code> and not <code>auto</code>) but also contains a field whose type is defined by the
associated type <code>Payload</code>. If you remove <code>extern</code>, the below code would compile.
```zig
const GraphTrait = struct {
// [E13] Structs making use of associated types must have automatic layout. Found issue in
// 'example.GraphTrait.GenericAssociatedFoo'.
pub const GenericAssociatedFoo: extern struct {
bar: traitor.AssociatedType("Payload"),
} = undefined;
<code>pub const Payload = void;
</code>
};
```
<code>[E14] TraitGenericTypeHasDecls</code>
This is an error with the trait you supplied, not the type that is supposed to be checked. The trait has a field
or declaration that has a type that makes use of an associated type internally while also having a declaration.
This is currently not possible due to a limitation of how <code>@Type</code> works in zig
(https://github.com/ziglang/zig/issues/6709).
As an example, the following code will produce this error as <code>GenericAssociatedFoo</code> has type that contains a field
whose type is defined by the associated type <code>Payload</code> while also containing a declaration <code>SomeDeclaration</code>.
```zig
const GraphTrait = struct {
// [E14] Structs making use of associated types must not have declarations.
// Found issue in 'example.GraphTrait.GenericAssociatedFoo'.
pub const GenericAssociatedFoo: struct {
const SomeDeclaration: i32 = 5;
<code> bar: traitor.AssociatedType("Payload"),
} = undefined;
pub const Payload = void;
</code>
};
``` | [] |
https://avatars.githubusercontent.com/u/109755957?v=4 | JamLang | IsaacMcCracken/JamLang | 2023-02-12T21:34:29Z | The Jam Programing Language | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/IsaacMcCracken/JamLang/tags | - | [
"compiler",
"language",
"zig",
"ziglang"
] | 420 | false | 2023-02-13T05:10:21Z | true | false | unknown | github | [] | JamLang
Description:
The Jam Programing language is a language I created for the fun of learning.
Syntactically resembling go and zig. I have no current ambition to take over
in the language war. If you want a good new language to use I suggest zig.
I may or may not finish this project.
Progress:
Currently I have the AST able to emit bytecode for mathematical expressions
and it can run that on a <strong>extremely</strong> simple 8-bit virtual machine.
Ambitions
<ul>
<li>run it on a virtual machine that can support 32 and 64 bit types (like wasm)</li>
<li>have simple code generation for x86_64 architecture.</li>
<li>have a simple standard library written in the language</li>
<li>maybe make some educational programing games that use the language</li>
</ul>
sample <code>hello_world.jam</code> program that will be compilable in the future.
<code>func main() i32 {
@print("Hello, Mom.\n")
}
</code> | [] |
https://avatars.githubusercontent.com/u/110837479?v=4 | 12in2024 | jD2R/12in2024 | 2023-12-21T15:19:45Z | Coding growth project for 2024. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/jD2R/12in2024/tags | - | [
"bash",
"c",
"cpp",
"csharp",
"golang",
"kotlin",
"lua",
"python",
"ruby",
"rust",
"typescript",
"wasm",
"zig"
] | 12 | false | 2024-01-25T19:03:09Z | false | false | unknown | github | [] | 12 Languages in 2024
As part of my developer goals, there have been quite a few languages I've been meaning to learn thoroughly for a while now (I work way too much with plain, vanilla JS). Plus, I've always wanted to move beyond the borders of web development and gain a more general respect for programming overall - and the onset of 2024 is the perfect opportunity to accomplish this.
Starting in January, I'll be spinning a random wheel of 12 languages that I've handpicked (not any definitive list, just a bunch that I've been meaning to explore for a while) to learn for the coming year; each month, I'll add a new one to my toolkit.
The best way to learn a language quickly isn't to watch a bunch of tutorials, it's to get in there and start building something immediately. Hence, each month's folder will be updated regularly with small example programs and larger checkpoint programs to make sure that I get as much bang into my month as possible. I'll also be making a final project to "prove" my newfound skills. If you're interested in the exact day-by-day playthrough, I've included it under <code>schedule.txt</code>.
Enough of me talking, let's get into the calendar.
Calendar
<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> January: Lua
<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> February: TBD
<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> March: TBD
<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> April: TBD
<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> May: TBD
<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> June: TBD
<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> July: TBD
<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> August: TBD
<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> September: TBD
<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> October: TBD
<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> November: TBD
<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> December: TBD
Remaining
<ul>
<li>Python</li>
<li>TypeScript</li>
<li>C#</li>
<li>C/C++</li>
<li>Go</li>
<li>Rust</li>
<li>Kotlin</li>
<li>WASM</li>
<li>Zig</li>
<li>Ruby</li>
<li>Bash</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/61627919?v=4 | nvim | nuIIpointerexception/nvim | 2023-07-23T18:42:52Z | ❄️ fast and minimal neovim config. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/nuIIpointerexception/nvim/tags | - | [
"neovim-config",
"nvim",
"ocaml",
"rust",
"typescript",
"zig"
] | 18 | false | 2023-08-01T16:10:51Z | false | false | unknown | github | [] | nvim | [] |
https://avatars.githubusercontent.com/u/50797868?v=4 | rc | maolonglong/rc | 2024-01-02T15:20:38Z | Reference counting in Zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/maolonglong/rc/tags | MIT | [
"atomic",
"memory-management",
"zig"
] | 5 | false | 2024-12-07T07:47:02Z | true | false | unknown | github | [] | Reference Counting
<a></a>
<a></a> | [] |
https://avatars.githubusercontent.com/u/67585967?v=4 | kiss-ng | git-bruh/kiss-ng | 2023-02-21T10:48:44Z | Next generation of the KISS Package manager | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/git-bruh/kiss-ng/tags | - | [
"kiss",
"landlock",
"package-manager",
"sandboxing",
"zig"
] | 78 | false | 2025-05-20T14:45:40Z | true | true | 0.14.0 | github | [
{
"commit": "1e1148f41afe2bc330cc2bbe6db7735f06ff68c8",
"name": "dag_zig",
"tar_url": "https://github.com/git-bruh/dag.zig/archive/1e1148f41afe2bc330cc2bbe6db7735f06ff68c8.tar.gz",
"type": "remote",
"url": "https://github.com/git-bruh/dag.zig"
}
] | kiss-ng
Next generation of the <a>KISS</a> package manager, aiming to be more robust and powerful (sandboxed builds, provides system, etc)
TODO
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> alternatives & provides system
<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> build
<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> run as unprivileged user
<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> sandboxed builds using <a><code>landlock</code></a>
<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> checksum
<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> download
<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> parallel downloads
<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> install
<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> dynamic dependency detector
<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> binary stripping
<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> conflicts
<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> list
<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> remove
<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> 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> update
<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> upgrade
<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> hooks (package-specified only, no user hooks)
<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> pre-remove
<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> post-install
- ~~[ ] user hooks~~ not planned
<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> global lock for installation/removal
<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> environment variables
<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> <code>KISS_ROOT</code>
- ~~[ ] <code>KISS_COMPRESS</code>~~ <code>zstd</code> compression by default
<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> <code>KISS_PATH</code>
- ~~[ ] <code>KISS_COLOR</code>~~ not planned
<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> <code>KISS_DEBUG</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> <code>KISS_FORCE</code>
- ~~[ ] <code>KISS_HOOK</code>~~ not planned
<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> <code>KISS_KEEPLOG</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> <code>KISS_PROMPT</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> <code>KISS_TMPDIR</code> | [] |
https://avatars.githubusercontent.com/u/133017480?v=4 | ziglings-solutions | Leenuus/ziglings-solutions | 2023-12-04T14:20:23Z | Clone from Ziglings | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/Leenuus/ziglings-solutions/tags | MIT | [
"awesome",
"zig",
"ziglings"
] | 1,245 | false | 2024-12-20T16:41:55Z | true | false | unknown | github | [] | Ziglings Solution
<a>For the Origin Repo, here</a>
Some Learning Notes
Characteristic of Zig lang
<ol>
<li>A very extensive syntax, full of features from other languages.</li>
<li><code>defer</code> and <code>errdefer</code> keyword makes life easier</li>
<li>treat errors as return value in the form of <code>enum</code>, btw, <em>Zig</em>'s <code>enum</code> is much more understandable and writable than the <em>Rust</em> one</li>
<li>A much more powerful <code>switch</code> statement</li>
<li><code>unreachable</code> keyword optimization hints to the compiler, also as placeholder for programmer</li>
<li>A much more understandable type system, <strong>without annoying nested type</strong> visually. A <em>Rust</em> programmer will thank it for <strong>no crazy type annotation</strong>. Think about a <code>Result</code> with <code>Option</code> inside adding generic annotation.</li>
<li>As for function, it follows a convetional way same as <em>C</em> function, but the <strong>parameter is not rebindable</strong>, like <em>Rust</em> function parameter without a <code>mut</code> in front of it.</li>
<li>Following point 7, we can have multiple name to the same thing in memory, however, <em>Zig</em> forces <strong>all declared variable should be used</strong>, helping us get rid of confusion, without the bothering to persuade the <em>borrow checker</em></li>
<li>No macro system, so there won't be extra annotations everywhere and also symbols which you can't know whether it is a macro. Maybe <code>comptime</code> code generation is a better idea.</li>
</ol>
Assignment Semantic
This is important to figure out <strong>how assignment works</strong> when learning a new programming language.
In Zig, assignment works this way:
<ol>
<li>When assigning primitive type to a new variable, Zig allocates memory for this variable, and copies the primitive type value into this memory slot. This works like any other languages.</li>
<li>When assigning complex type like a struct, Zig still copies this value to the new variable.</li>
<li>Function Parameter works the same way, the default semantic is copy semantic. It is not the same as those dynammic languages like Python and Javascript(And a non-dynamic one, Java). When these languages receive a reference to complex type, this reference binds to the variable, you can use this <strong>reference</strong> to <strong>access and modify its fields</strong>. But when you modify the structure or class itself, (btw, the only way to do so is to rebind it)you <strong>lost the reference to the passed in value</strong>.</li>
<li>In Rust, semantic gets more complicated. You can use <code>mut var: type</code>, <code>mut var: &type</code>, <code>mut var: &mut type</code>, <code>var: &type</code>, <code>var: &mut type</code>, <code>var: type</code> to specify the incoming parameter. The <code>mut</code> comes in front of the variable name <code>var</code> indicates whether <code>var</code> is rebindable. And the following annotions indicate the type of the parameter. <code>&mut type</code> means mutable reference; you use this type to modify the value outside of the function, invoking side effects. <code>&type</code> means immutable reference; you can only read the variable, not allowed to change it. <code>type</code> is a way to consume the value passed in, which indicates you don't need this value anymore after executing the function, so Rust compiler could safely release the memory it takes.</li>
<li>Implicit assignment. Code like <code>var a = struct A{}; var b = [a, a];</code> <strong>works differently</strong> in different languages too. But in fact, it is just assignment. So for languages like C, Zig and Cpp, the array <code>b</code> just gets two copy of <code>a</code>, consuming it own space.</li>
</ol>
Pointers
Are all of these pointer types starting to get confusing?
```
FREE ZIG POINTER CHEATSHEET! (Using u8 as the example type.)
+---------------+----------------------------------------------+
| u8 | one u8 |
| <em>u8 | pointer to one u8 |
| [2]u8 | two u8s |
| [</em>]u8 | pointer to unknown number of u8s |
| [<em>]const u8 | pointer to unknown number of immutable u8s |
| </em>[2]u8 | pointer to an array of 2 u8s |
| *const [2]u8 | pointer to an immutable array of 2 u8s |
| []u8 | slice of u8s |
| []const u8 | slice of immutable u8s |
+---------------+----------------------------------------------+
```
Enum and Union
Enum with wrapped value is somehow union in fact.
```Rust
enum Fruit{
Apple(Apple),
Grape(Grape),
}
struct Apple;
struct Grape;
```
I mean, union is a way to save memory in machine level, but <strong>in a programmer perspctive</strong>, it gives a way to express these things are things in the same group. And what about enum? It is a way to express that there are A, B, C, D, total 4 options in this circumstances. So when you combine two concepts, you get a way to indicate a group, also a way to specify the certain thing belonged to this group. To be short, <strong>union creates a namespace holding the options, and enum indicates one option, a fancy name, variant, in this namespace.</strong>
So in Zig, there is something like
```Zig
const Insect = union(enum) {
flowers_visited: u16,
still_alive: bool,
};
// The same as the following
const InsectStat = enum { flowers_visited, still_alive };
const Insect = union(InsectStat) {
flowers_visited: u16,
still_alive: bool,
};
``` | [] |
https://avatars.githubusercontent.com/u/11492844?v=4 | lineprofiles | fjebaker/lineprofiles | 2023-04-07T17:53:27Z | A Cunningham transfer-function integrator for building relativistic lineprofile models. | main | 4 | 1 | 1 | 1 | https://api.github.com/repos/fjebaker/lineprofiles/tags | MIT | [
"astrophysics",
"black-holes",
"general-relativity",
"lineprofiles",
"xspec",
"xspec-model",
"zig"
] | 183 | false | 2024-05-29T09:08:01Z | true | true | unknown | github | [
{
"commit": "main.tar.gz",
"name": "zfitsio",
"tar_url": "https://github.com/fjebaker/zigFITSIO/archive/main.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/fjebaker/zigFITSIO"
}
] |
klineprofiles
A Cunningham transfer function integrator written in the <a>Zig programming language</a>. Constructs relativistic lineprofile spectra for use with <a>SpectralFitting.jl</a>, HEASoft's <a>XSPEC</a>, and beyond. This code integrates pre-computed Green's function / Cunningham transfer functions with an interpolated emissivity function, solving
$$
F(E, \delta E) = \int_{r_0}^{R} \text{d} r \int_{E}^{E+\delta E} \text{d}g I_{\text{obs}}(r, g) \varepsilon(r),
$$
on energy grids $E$ with bin width $\delta E$.
The pre-computed transfer functions in $I_\text{obs}$ can be obtained using general relativistic ray-tracing software, such as <a>Gradus.jl</a>. With every <a>release</a>, an example table is provided for the Kerr spacetime, which interpolates over black hole spin $a$ and observer inclination $\theta$.
Usage
To install into XSPEC, follow the guide in the <a>release</a> description. The latest pre-computed table model is currently v0.1.0, and can be downloaded directly from <a>here</a>.
<ul>
<li><strong>Note</strong>: this model is compatible with XSPEC v12.13 onwards, and will not compile for older versions due to breaking changes in the generated model wrappers.</li>
</ul>
Building from source
Note that building from source is not reqiured in order to use this model. See the <a>Usage</a> section above.
To build the static library from source, compile with Zig 0.12.0-dev.1647+325e0f5f0:
<code>bash
git clone https://github.com/fjebaker/lineprofiles \
&& cd lineprofiles \
&& zig build -Doptimize=ReleaseFast xspec</code>
Model descriptions
A number of different models are included in the source code, and additional models can be tailored to meet specific needs. <em>A la carte</em>:
Additive
<ul>
<li><code>kline</code>: lineprofiles with power-law emissivities of the form $\varepsilon(r) = r^{-\alpha}$.</li>
</ul>
| Parameter | Description |
| --------- | -------------------------------------------------- |
| <code>a</code> | Unitless black hole spin |
| <code>incl</code> | Observer inclination $\theta$ (degrees) |
| <code>eline</code> | Energy of central line (e.g. Fe K$\alpha$ 6.4 keV) |
| <code>alpha</code> | Emissivity powerlaw index |
| <code>rmin</code> | Inner radius of the accretion disc |
| <code>rout</code> | Outer radius of the accretion disc |
<ul>
<li><code>kline5</code>: lineprofiles with emissivity given as an interpolated power-law between 5 knots.</li>
</ul>
| Parameter | Description |
| ------------ | ------------------------------------------------------------------------------------------ |
| <code>a</code> | Unitless black hole spin |
| <code>incl</code> | Observer inclination $\theta$ (degrees) |
| <code>eline</code> | Energy of central line (e.g. Fe K$\alpha$ 6.4 keV) |
| <code>alpha</code> | Emissivity powerlaw index beyond <code>e5</code> |
| <code>rmin</code> | Inner radius of the accretion disc |
| <code>rout</code> | Outer radius of the accretion disc |
| <code>e1</code> to <code>e5</code> | Emissivity interpolation knots (see <a>Emissivity interpolation</a>) |
Convolutional
<ul>
<li><code>kconv</code>: convolutional analog of <code>kline</code>.</li>
</ul>
| Parameter | Description |
| --------- | --------------------------------------- |
| <code>a</code> | Unitless black hole spin |
| <code>incl</code> | Observer inclination $\theta$ (degrees) |
| <code>alpha</code> | Emissivity powerlaw index |
| <code>rmin</code> | Inner radius of the accretion disc |
| <code>rout</code> | Outer radius of the accretion disc |
<ul>
<li><code>kconv5</code>: convolutional analog of <code>kline5</code>.</li>
</ul>
| Parameter | Description |
| ------------ | ------------------------------------------------------------------------------------------ |
| <code>a</code> | Unitless black hole spin |
| <code>incl</code> | Observer inclination $\theta$ (degrees) |
| <code>alpha</code> | Emissivity powerlaw index beyond <code>e5</code> |
| <code>rmin</code> | Inner radius of the accretion disc |
| <code>rout</code> | Outer radius of the accretion disc |
| <code>e1</code> to <code>e5</code> | Emissivity interpolation knots (see <a>Emissivity interpolation</a>) |
Emissivity interpolation
The emissivity function in <code>klineN</code> and <code>kconvN</code> is calculated with a linear interpolation in $\log \varepsilon$, $\log r$ space; that is to say, the power law index is piecewise constant between $N$ knots $\vec{k} = (r_1, r_2, \ldots, r_N)$:
$$
\varepsilon(r, \vec{k}) = \left{ \begin{matrix}
\varepsilon_1, & r \leq r_1 \
\varepsilon_2, & r_1 < r \leq r_2 \
\vdots & \
\varepsilon_N, & r_N < r \leq r_\text{cut} \
r^{-\alpha} & \text{otherwise}
\end{matrix}\right. ,
$$
where the different $r_i$ are calculated as $N$ log linear intervals between the inner and some cutoff radius of the disc.
The cutoff radius $r_\text{cut}$ is under half of the outer radius of the disc in log space (see figure below). This is to fit the inner regions of the disc, where the majority of the variation in emissivity is expected.
This interpolation regime is in order to mimic the different emissivity functions of a disc irradiated by some arbitrary, axis-symmetric ionizing flux. The ionizing flux may itself be a consequence of different coronal models for the black hole. Fitting the emissivity functions should thereby allow the model to infer general properties about e.g. the morphology or position of the corona.
For example, the ionizing flux of a lamp post corona around a maximally spinning black hole at height $h = 10 r_\text{g}$ may be approximated with this emissivity interpolation:
| [] |
https://avatars.githubusercontent.com/u/74559859?v=4 | life | Jabolol/life | 2023-12-30T18:08:48Z | A Game of Life implementation that runs on the browser | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/Jabolol/life/tags | MIT | [
"deno",
"webassembly",
"zig"
] | 154 | false | 2023-12-30T21:51:33Z | true | false | unknown | github | [] | life
A <a>Game of Life</a>
implementation in <code>Zig</code> and <code>WebAssembly</code>.
installation
Make sure you have both <a><code>Zig</code></a> and
<a><code>Deno</code></a> installed and on your <code>$PATH</code>.
<ol>
<li>Clone the repository</li>
</ol>
<code>bash
git clone https://github.com/Jabolol/life.git .</code>
<ol>
<li>Build the <code>WebAssembly</code> file and
<a><code>patterns.json</code></a> file using <code>zig</code>.</li>
</ol>
<code>bash
zig build</code>
<ol>
<li>Navigate to the <a><code>www/</code></a> directory and start the website.</li>
</ol>
<code>bash
cd www && deno task start</code>
custom patterns
Custom patterns consist of files in the <a><code>assets/</code></a> directory. The
format of these files is as follows:
<code>txt
0 0 0 0 0 0
0 0 1 1 0 0
0 1 0 0 1 0
0 0 1 1 0 0
0 0 0 0 0 0</code>
Where <code>0</code> is a dead cell and <code>1</code> is a live cell. There is a space between each
cell and a newline between each row.
Every time you change a file in the <a><code>assets/</code></a> directory, you need
to rebuild the <a><code>patterns.json</code></a> file using <code>zig</code>.
The pattern is automatically centered on the canvas.
<code>bash
zig build</code>
contributing
Contributions are welcome. Please open an issue or a pull request. Please run
the following commands before opening a pull request, and ensure that they all
pass.
```bash
zig specific commands
zig fmt src
zig fmt www/static/patterns.json
zig test src/main.zig
zig test src/pattern.zig
zig build
deno specific commands
deno fmt www
deno lint www
```
license
This project is licensed under the <a>MIT License</a>. | [] |
https://avatars.githubusercontent.com/u/48321566?v=4 | aoc-2023 | twoneis/aoc-2023 | 2023-11-25T20:55:03Z | AdventOfCode 2023 in Zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/twoneis/aoc-2023/tags | - | [
"advent-of-code",
"advent-of-code-2023",
"zig"
] | 152,050 | false | 2024-04-04T20:01:24Z | false | false | unknown | github | [] | Advent of Code 2023
My attempt at advent of code 2023 in zig.
Goal
Get more familiar with zig and have some fun.
.. and not give up.
Notes
<ul>
<li>I added a template that provides more than the bare minimum and does it in a decently good way (as far as I can tell) after day 8.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/47727831?v=4 | httpz | darrensemusemu/httpz | 2023-02-16T20:50:08Z | A simple Go like http server implementation | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/darrensemusemu/httpz/tags | MIT | [
"http",
"http-server",
"zig"
] | 21 | false | 2023-10-29T21:45:29Z | true | false | unknown | github | [] | httpz
A simple Go like http server implementation. Note: WIP.
Example
Simple Server
```zig
// ....
const addr = try net.Address.parseIp("0.0.0.0", 8080);
var http_server = httpz.Server.init(allocator, addr);
defer http_server.close();
const t = struct {
fn handleHome(res: <em>httpz.Response, _: </em>httpz.Request) anyerror!void {
res.status = .ok;
try res.setHeader("Content-Type", "text/plain");
try res.body.appendSlice("Hello World");
}
};
var mux = httpz.Mux.init(allocator);
try mux.handle("/", t.handleHome);
std.log.info("running on port: 8080", .{});
try http_server.listenAndServe(&mux);
``` | [] |
https://avatars.githubusercontent.com/u/12962448?v=4 | mbedtls | star-tek-mb/mbedtls | 2023-02-27T19:13:48Z | mbedtls zig build | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/star-tek-mb/mbedtls/tags | - | [
"https",
"mbedtls",
"tls",
"zig"
] | 1,277 | false | 2023-03-03T22:10:44Z | true | false | unknown | github | [] | Overview
mbedtls v3.3.0 with zig build system | [
"https://github.com/FranciscoLlobet/miso",
"https://github.com/allyourcodebase/curl",
"https://github.com/allyourcodebase/ffmpeg",
"https://github.com/jiacai2050/zig-curl",
"https://github.com/lishaduck/zig-curl",
"https://github.com/thomashn/libssh"
] |
https://avatars.githubusercontent.com/u/71920313?v=4 | webidl.zig | MidstallSoftware/webidl.zig | 2024-02-01T21:04:50Z | Webidl for Zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/MidstallSoftware/webidl.zig/tags | GPL-3.0 | [
"webidl",
"zig"
] | 64 | false | 2024-05-29T09:05:45Z | true | true | unknown | github | [
{
"commit": "358a028beb32ebb193dadb6f7a954965745892a7.tar.gz",
"name": "parser-toolkit",
"tar_url": "https://github.com/MasterQ32/parser-toolkit/archive/358a028beb32ebb193dadb6f7a954965745892a7.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/MasterQ32/parser-toolkit"
}
] | webidl.zig
Webidl for Zig | [] |
https://avatars.githubusercontent.com/u/565124?v=4 | w4-zig-bingosylt | peterhellberg/w4-zig-bingosylt | 2023-10-25T12:06:46Z | null | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/peterhellberg/w4-zig-bingosylt/tags | - | [
"gamedev",
"gamejam",
"wasm",
"wasm4",
"zig"
] | 283 | false | 2024-08-19T09:01:35Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "w4",
"tar_url": "https://github.com/peterhellberg/w4/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/peterhellberg/w4"
}
] | w4-zig-bingosylt :zap:
A game written in Zig for the <a>WASM-4</a> fantasy console.
Building
Build the cart by running:
<code>shell
make</code>
Then run it with:
<code>shell
make run</code>
Bundle for html, linux and windows using:
<code>shell
make bundle</code>
Sprites
I generate sprites from PNG files like this <code>w4 png2src -t sprite.tpl image.png</code>
Where the custom template for <code>w4 png2src</code> looks like this:
<code>zig
{{#sprites}}
pub const {{name}} = Sprite{
.sprite = ([{{length}}]u8{ {{bytes}} })[0..],
.width = {{width}},
.height = {{height}},
.flags = w4.{{flagsHumanReadable}},
};
{{/sprites}}</code>
Links
<ul>
<li>:art: <a>Lospec Pixel Art Scaler</a>: This tools helps you scale pixel art to bigger sizes without filtering</li>
<li>:tangerine: <a>Lospec Tangerine Noir Palette</a>: Three shades with a sharp tangerine accent</li>
<li>:video_game: <a>WASM-4 Documentation</a>: Learn more about WASM-4</li>
<li>:octocat: <a>WASM-4 GitHub</a>: Submit an issue or PR. Contributions are welcome!</li>
<li>:sparkles: <a>Jok</a>: A minimal 2d/3d game framework for Zig</li>
<li>:fire: <a>Zig Crash Course</a></li>
</ul>
Jam
Kodsnacks Tvåveckorssylt - #9
<a>https://itch.io/jam/spelsylt9</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>
Submissions open to November 6th 2023 at 12:00 AM
</blockquote>
Theme: BINGO!
Skapa din egen bingorad från bingobrickan nedanför. Du måste välja minst 2 rutor och de måste sitta ihop enligt klassiska bingoregler (horisontellt, vertikalt eller diagonalt).
Skriva gärna på ditt spel vilka brickor du valde!
| [] |
https://avatars.githubusercontent.com/u/52547?v=4 | flymake-zig | juergenhoetzel/flymake-zig | 2023-08-15T19:55:50Z | A zig backend for Flymake | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/juergenhoetzel/flymake-zig/tags | GPL-3.0 | [
"emacs",
"emacs-package",
"zig",
"ziglang"
] | 19 | false | 2023-08-17T15:36:24Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/3470288?v=4 | wws-zig-kit | kwlum/wws-zig-kit | 2023-02-19T07:57:22Z | A Zig wasm workers server kit. | main | 0 | 1 | 1 | 1 | https://api.github.com/repos/kwlum/wws-zig-kit/tags | MIT | [
"wasm",
"webassembly",
"zig"
] | 39 | false | 2024-10-14T16:41:58Z | true | false | unknown | github | [] | WWS kit in Zig
An experimental <a>WWS</a> kit written in zig.
Usage Examples
Hello World
```zig
const std = @import("std");
const kit = @import("wws-zig-kit");
fn handle(request: kit.Request, response: <em>kit.Response, _: </em>kit.Cache) !void {
try response.headers.put("content-type", "text/plain");
try response.body.writeAll("Hello World!");
response.status = std.http.Status.ok;
}
pub fn main() !void {
const routes = [_]kit.Route{kit.Route.get(handle)};
try kit.run(std.heap.c_allocator, 65535, null, &routes);
}
```
Cache (Key/Value Store)
ex: <a>counter</a>
```zig
fn handle(_: <em>void, request: kit.Request, response: </em>kit.Response, cache: *kit.Cache) !void {
const counter_str = cache.get("counter") orelse "0";
const counter = std.fmt.parseInt(u32, counter_str, 10) catch 0;
<code>var buf: [16]u8 = undefined;
const counter_buf = try std.fmt.bufPrint(&buf, "{d}", .{counter + 1});
try cache.put("counter", counter_buf);
try response.body.print("Counter: {d}", .{counter});
response.status = std.http.Status.ok;
</code>
}
```
Dynamic routes
ex: <a>dynamic-routes</a>
```zig
fn handle(<em>: <em>void, request: kit.Request, response: </em>kit.Response, </em>: *kit.Cache) !void {
if (request.params.get("id")) |id| {
try response.body.print("Product Id: {s}", .{id});
} else {
try response.body.writeAll("Product not found.");
}
<code>try response.headers.put("content-type", "text/plain");
response.status = http.Status.ok;
</code>
}
```
Environment variables
```zig
fn handle(_: kit.Request, response: <em>kit.Response, _: </em>kit.Cache) !void {
response.status = std.http.Status.ok;
<code>const msg = std.os.getenv("message") orelse "";
try response.body.writeAll(msg);
</code>
}
```
Build and Run
Build the echo example, require zig-0.10.1 installed:
<code>zig build
</code>
Run WWS inside workers directory, require WWS installed.
<code>wws www
</code>
Call the http endpoint with:
<code>curl -d "Hello World!" http://localhost:8080/echo
</code> | [] |
https://avatars.githubusercontent.com/u/52031254?v=4 | zig-learning-material | WeebNetsu/zig-learning-material | 2023-02-13T07:29:27Z | The learning material used for my Zig course | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/WeebNetsu/zig-learning-material/tags | MIT | [
"learn-zig",
"learntocode",
"zig"
] | 3 | false | 2023-11-01T17:12:20Z | false | false | unknown | github | [] | Zig Learning Material
These are all the lessons I created when learning Zig, they became my Zig course.
If you want to support the work I do, please consider donating to me on one of these platforms:
<a></a>
<a></a>
<a></a>
<a></a> | [] |
https://avatars.githubusercontent.com/u/12368711?v=4 | zig-animate | mjakeman/zig-animate | 2024-02-02T18:07:34Z | Animation, interpolation, and sequencing library for zig. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/mjakeman/zig-animate/tags | MIT | [
"animation",
"animation-library",
"interpolation",
"zig",
"zig-library"
] | 25 | false | 2024-09-21T23:35:28Z | true | true | unknown | github | [] | zig-animate
A property animation library in Zig.
Demo 1: Property Interpolation
Full demo code in <a><code>animator.zig</code></a>.
```zig
const start = Vec2{ .x = 0, .y = 0 };
const end = Vec2{ .x = 1, .y = 1 };
const anim = Animator(Vec2).init(start, end, EaseInCubicVec2);
// 2D Cubic Easing
try std.testing.expectEqual(Vec2{ .x = 0.015625, .y = 0.015625 }, anim.eval(0.25));
try std.testing.expectEqual(Vec2{ .x = 0.125, .y = 0.125 }, anim.eval(0.5));
try std.testing.expectEqual(Vec2{ .x = 0.421875, .y = 0.421875 }, anim.eval(0.75));
try std.testing.expectEqual(Vec2{ .x = 1, .y = 1 }, anim.eval(1));
```
Demo 2: Sequencing
Full demo code in <a><code>sequencer.zig</code></a>.
We can animate a complex object:
```zig
const TestObject = struct {
value: f32,
other_value: Vec2,
<code>const Self = @This();
fn update(self: *Self, value: f32) void { ... }
fn update_other(self: *Self, other_value: Vec2) void { ... }
</code>
}
```
Sequencing multiple property animations:
```zig
var testObj: TestObject = undefined;
testObj.value = 30;
testObj.other_value = Vec2{ .x = 10, .y = 10 };
// Go from 30 to 50 over 80 frames
const valueAnim = animator.Animator(f32).init(30, 50, curves.EaseInCubic);
const valueEvent = Event.create_transition(TestObject, f32, &testObj, &valueAnim, 80, TestObject.update);
// Go from (10, 10) to (6, 4) over 65 frames
const otherValueAnim = animator.Animator(Vec2).init(Vec2{ .x = 10, .y = 10 }, Vec2{ .x = 6, .y = 4 }, EaseInCubicVec2);
const otherValueEvent = Event.create_transition(TestObject, Vec2, &testObj, &otherValueAnim, 65, TestObject.update_other);
// Create a sequencer
var sequencer = Sequencer.init(TestAllocator);
sequencer.add_event(0, valueEvent);
sequencer.add_event(0, otherValueEvent);
// Move the sequencer forward
sequencer.tick(10);
// Check the values
const expectedVal = curves.EaseInCubic(30, 50, 10.0 / 80.0);
try std.testing.expectEqual(expectedVal, testObj.value);
const expectedVector = EaseInCubicVec2(Vec2{ .x = 10, .y = 10 }, Vec2{ .x = 6, .y = 4 }, 10.0 / 65.0);
try std.testing.expectEqual(expectedVector, testObj.other_value);
```
Key Concepts
The three files in this library are:
* <code>animator.zig</code>: Contains Animators, which are objects that animate over a given property. You have one animator per property, so a location/rotation/scale animation might have <code>locationAnim: Animator(Vec3)</code>, <code>rotationAnim: Animator(Quat)</code>, <code>scaleAnim: Animator(Vec3)</code> (respectively).
* <code>sequencer.zig</code>: Allows for Actions (one-off event) and Transitions (ongoing event) to be scheduled and run. You have one sequencer per project/module/grouping of animations.
* <code>curves.zig</code>: A collection of interpolation functions for f32. See the <code>animator.zig</code> class for an easy example of how to create higher dimension interpolation functions (e.g. for Vector2/3/4/etc).
Examples
In each source file, there are fully-commented tests demonstrating some key patterns.
For example, see <a>sequencer.zig</a>.
Building
Standard Zig library:
<code>zig build
zig build test --summary all</code>
About
This repo is a mirror of the in-tree animation library from my personal game engine project. As such, this library is actively (albeit infrequently) maintained.
Contributions
Contributions are welcome, although keep in mind the library scope is intentionally small.
Licence
MIT Licensed - do what you want! | [] |
https://avatars.githubusercontent.com/u/3594035?v=4 | game-boy | tsunaminoai/game-boy | 2023-08-09T01:02:31Z | An attempt to learn zig by emulating the LR35902 | main | 4 | 1 | 0 | 1 | https://api.github.com/repos/tsunaminoai/game-boy/tags | MIT | [
"8080",
"emulation",
"lr35902",
"zig",
"ziglang",
"ziglearn"
] | 637 | false | 2025-04-19T19:00:41Z | true | true | 0.11.0 | github | [] | game-boy
An attempt to learn zig while writing an emulator for a "simple" chip.
This is built and tested with Zig 0.11.0.
Developing
Clone the repo and run <code>zig build test</code> to build and test the emulator.
Credits
<ul>
<li><a>Zig</a></li>
<li><a>Gameboy CPU Manual</a></li>
<li>Inspiration from <a>Wuelle</a></li>
<li><a>Gameboy CPU (LR35902) instruction set</a></li>
</ul>
License
MIT | [] |
https://avatars.githubusercontent.com/u/87582318?v=4 | zig-webp | koenigskraut/zig-webp | 2023-11-02T05:26:16Z | Zig binding for libwebp | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/koenigskraut/zig-webp/tags | - | [
"libwebp",
"webp",
"zig"
] | 26 | false | 2024-03-04T13:44:23Z | true | true | unknown | github | [
{
"commit": "81c90e3b5d6278ab564de3e81dd46588d83a88b3.tar.gz",
"name": "libwebp",
"tar_url": "https://github.com/koenigskraut/libwebp/archive/81c90e3b5d6278ab564de3e81dd46588d83a88b3.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/koenigskraut/libwebp"
}
] | zig-webp
Zig binding for libwebp, libwebp used is a fork with added Zig build system. It is added as a dependency and will be downloaded and built from source.
Quick start
<ol>
<li>
Add zig-webp as a dependency in your build.zig.zon as follows:
<code>diff
.{
.name = "your-project",
.version = "1.0.0",
.paths = .{
"src/",
"build.zig",
"build.zig.zon",
},
.dependencies = .{
+ .zig_webp = .{
+ .url = "https://github.com/koenigskraut/zig-webp/archive/1358da0b9f486e5ea04c149fed4f57f70a395363.tar.gz",
+ .hash = "122072edc915633a032c53bacd9b1035d44649242b323d97a7d93dd540c607a2d7d3",
+ },
},
}</code>
</li>
<li>
In your build.zig add zig-webp as a dependency and attach its modules to your project:
```diff
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<ul>
<li>const opts = .{ .target = target, .optimize = optimize };</li>
<li>const dep = b.dependency("zig_webp", opts);
+</li>
<li>const webp_module = dep.module("zig-webp");</li>
<li>
const webp_lib = dep.artifact("webp");
const exe = b.addExecutable(.{
.name = "test",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
+ exe.addModule("webp", webp_module);
+ exe.linkLibrary(webp_lib);
exe.install();
...
}
```
</li>
</ul>
</li>
<li>
Import and use it in your project! Note that currently zig-webp keeps the structure of original header files like <code>webp/encode.h</code> and <code>webp/decode.h</code>:
```zig
const std = @import("std");
const webp = struct {
const decode = @import("webp").decode;
const encode = @import("webp").encode;
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();
<code>var in_file = try std.fs.openFileAbsolute("path_to_file.webp", .{});
defer in_file.close();
var data = try in_file.readToEndAlloc(alloc, 1<<24);
const rgb = try webp.decode.decodeRGB(data);
defer rgb.deinit();
var out_file = try std.fs.cwd().createFile("out.ppm", .{});
defer out_file.close();
const writer = out_file.writer();
try writer.print("P6\n{} {}\n255\n", .{ rgb.width, rgb.height });
for (0..rgb.height) |h| {
try writer.writeAll(rgb.data[rgb.width * 3 * h ..][0 .. rgb.width * 3]);
}
</code>
}
```
</li>
</ol> | [] |
https://avatars.githubusercontent.com/u/139293750?v=4 | pieQ | bogwi/pieQ | 2023-08-05T00:34:03Z | Priority Queue for Zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/bogwi/pieQ/tags | MIT | [
"algorithms",
"data-structures",
"priority-queue",
"zig",
"zig-lang",
"zig-package"
] | 37 | false | 2024-11-17T16:57:53Z | true | true | unknown | github | [] | Priority Queue in ZIG
Foreword
How fast is PieQ? On the Apple M1 CPU, inserting in random order and removing 100,000,000 unsigned 32-bit integer pairs in ReleaseFast mode takes <code>1.5</code> seconds for insert and about <code>20</code> seconds for remove. The cumulative time stayed within <code>22</code> seconds for many attempts, which pushes PieQ a bit into HashMap territory. And PieQ does not warp under heavy load because there are no recursive calls. Add+remove time compared to ZIG's standard PriorityQueue library shows that PieQ is twice as fast.
The API is designed to be as literal and self-explanatory as possible. PieQ uses an implicit data structure, so there is no memory allocation routine. The possible error interface is reduced to a bare minimum, like warning you if the queue is empty and you still want to pull something from it; that must be an error. Every public method has a comprehensive doc string where needed, and the full API is used in the test section. Interesting uncommon features like changing the root or locking the root are also implemented.
PieQ has two modes of operation, min-oriented and max-oriented, which are turned on by passing <code>.min</code> or <code>.max</code> parameters during initiation. This is along with the general idea of a priority queue. However, keys can also be complex types. PieQ gives you the ability to define what is min and what is max, and is designed to handle any key, anything you know how to compare; if not, invent how. For example, PieQ can be easily used as a data filter, sorting multi-valued elements together, such as enum's literals. Or you can filter items with certain keys you are interested in and put them strictly in front of the queue to pop them earlier than the rest. Maybe you want to queue vectors as keys, or functions that call other functions, you can do that.
There could be many dozens of possible use cases, I can't mention them all, but the testing section is a good place to start.
Applications that come to mind are heavy load balancers, stock market or large financial tasks - schedulers, medical solutions; then graphs, Dijkstra, of course, statistics, and anywhere you need scheduled event processing.
Benchmark
If you are interested in how well PieQ runs on your system, try <code>bench</code> step. Run this:
<code>zig
zig build bench -- 12345678</code>
and you will get stats for your machine
<code>PieQ: 12_345_678 items
|action |push |pop |sum |
|time:sec|0.1563 |2.0006 |2.1569 |
|ns:item |12.6578 |162.0510|174.7088|</code>
Running <code>zig build bench</code> without arguments tests on the default 1Mil. With modern CPUs, it makes sense to test harder, at least above 10Mils. Or if you know in advance the amount of data you intend to run, it is great to do such a test; or against other priority queue implementations to find the best option for your code.
Usage
<ol>
<li>
Add <code>PieQ</code> as a dependency in your <code>build.zig.zon</code>.
<code>zig
.{
.name = "name_of_your_package",
.version = "version_of_your_package",
.dependencies = .{
.PieQ = .{
.url = "https://github.com/bogwi/pieQ/archive/master.tar.gz",
.hash = "1220dbe03c05ad89578e9522d3f2ff1fa611495f770773c711979ac00e48fd2825e9",
},
},
}</code>
If the hash has changed, you will get a gentle <code>error: hash mismatch</code> where in the field <code>found:</code> ZIG brings you the correct value.
</li>
<li>
Add <code>PieQ</code> as a module in your <code>build.zig</code>.
<code>zig
const pieQ = b.dependency("PieQ", .{});
exe.addModule("PieQ", pieQ.module("PieQ"));</code>
Using the module in test scopes, requires one more declaration with the same constant (if you need the module in tests, of course).
```zig
unit_tests.addModule("PieQ", pieQ.module("PieQ"));
```
</li>
<li>
Import the module.
<code>zig
const PieQ = @import("PieQ").PieQ;</code>
</li>
<li>This is your comparison function if you want numbers.
<code>zig
fn compareU32(isMin: bool, a: u32, b: u32) bool {
while (isMin)
return a <= b;
return a >= b;
}</code></li>
<li>And this this how you initiate the Queue.
<code>zig
var minQueue = PieQ(u32, u32, .min, compareU32).init(your_allocator);
defer minQueue.deinit();</code></li>
</ol>
To find out more, see the testing section, file <code>pieq.zig</code>. Tests and code are placed together so you can explore the implementation better, hovering over the functions and all. Thanks. | [] |
https://avatars.githubusercontent.com/u/252122?v=4 | zotp | shavit/zotp | 2023-04-25T18:07:18Z | Time-based one-time password generator | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/shavit/zotp/tags | - | [
"cli",
"totp-generator",
"zig"
] | 10 | false | 2025-03-04T11:21:36Z | true | false | unknown | github | [] | TOTP
<blockquote>
Generate TOTP codes RFC-6238
</blockquote>
CLI Quick Start
Add a provider and generate code:
```
$ zotp a
$ zotp g
123456
```
List all providers:
<code>$ zotp l
$ zotp list</code>
Delete a provider:
<code>$ zotp delete <server>
$ zotp d <server></code>
Uninstall:
<code>$ zotp uninstall</code>
This will delete <code>.config/zotp</code> | [] |
https://avatars.githubusercontent.com/u/43842467?v=4 | zig-wadder | nonk123/zig-wadder | 2023-12-12T20:13:27Z | A map viewer for DOOM WADs | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/nonk123/zig-wadder/tags | MIT | [
"doom",
"map",
"raylib",
"viewer",
"wad",
"zig"
] | 25 | false | 2025-03-18T09:13:40Z | true | false | unknown | github | [] | zig-wadder
A WAD map-viewing experiment made with Zig. | [] |
https://avatars.githubusercontent.com/u/565124?v=4 | w4-shadows | peterhellberg/w4-shadows | 2023-11-29T07:43:10Z | null | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/peterhellberg/w4-shadows/tags | - | [
"gamedev",
"wasm",
"wasm4",
"zig"
] | 11 | false | 2025-04-28T09:21:55Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "w4",
"tar_url": "https://github.com/peterhellberg/w4/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/peterhellberg/w4"
}
] | w4-shadows :zap:
Using <a>Zig</a> to compile a <code>.wasm</code> cart
for use in <a>WASM-4</a>
Development
File watcher can be started by calling:
<code>sh
zig build spy</code>
Running the cart in WASM-4:
<code>sh
zig build run</code>
Deploy:
<code>make Deploy</code> | [] |
https://avatars.githubusercontent.com/u/22245086?v=4 | zig-gl-learning | kyle-marshall/zig-gl-learning | 2023-06-04T19:59:37Z | Diving into https://learnopengl.com with zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/kyle-marshall/zig-gl-learning/tags | - | [
"examples",
"glfw",
"learning",
"opengl",
"zig"
] | 43,327 | false | 2023-06-12T02:23:50Z | false | false | unknown | github | [] | zig-gl-learning
So far, these examples just extend https://github.com/hexops/mach-glfw-opengl-example by following the "Getting started" chapters at https://learnopengl.com/.
In order to run the examples as they are, you will need to clone the repos <a>zigimg</a> and <a>mach-glfw</a> into "ref" so that symbolic links resolve correctly. | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | zbox | bcrist/zbox | 2023-10-31T02:01:39Z | SVG Block Diagram Generator | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/bcrist/zbox/tags | MIT | [
"block-diagram",
"blockdiagram",
"svg",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 109 | false | 2024-06-22T14:41:00Z | true | true | 0.12.0-dev.1849+bb0f7d55e | github | [
{
"commit": "7f5cc0cc3d36545a6f9bcf34c1b5cc4f06a3cd56.tar.gz",
"name": "Zig-DeepHashMap",
"tar_url": "https://github.com/bcrist/Zig-DeepHashMap/archive/7f5cc0cc3d36545a6f9bcf34c1b5cc4f06a3cd56.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/bcrist/Zig-DeepHashMap"
}
] | ZBox
ZBox is a tool for programmatically creating SVG block diagrams in Zig. | [] |
https://avatars.githubusercontent.com/u/13811862?v=4 | libmocha | thechampagne/libmocha | 2023-09-26T10:50:35Z | A C library to parse mocha an elegant configuration language for both humans and machines. | main | 0 | 1 | 1 | 1 | https://api.github.com/repos/thechampagne/libmocha/tags | BSD-3-Clause-Clear | [
"c",
"library",
"mocha",
"parser",
"zig",
"ziglang"
] | 18 | false | 2024-02-18T04:54:13Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "mocha",
"tar_url": "https://github.com/hqnna/mocha/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/hqnna/mocha"
}
] | libmocha
<a></a> <a></a>
A C library to parse <strong>mocha</strong> an elegant configuration language for both humans and machines.
Example
This program output all tokens in text.
```c
include
include
int main(void) {
const char* text =
"defaults: { \
user_id: 0 \
start_id: user_id \
} \
hanna: { \
name: 'hanna rose' \
id: @:defaults:user_id \
inventory: ['banana' 12.32] \
}";
mocha_object_t obj;
if (mocha_parse(&obj, text) != MOCHA_ERROR_NONE) {
return 1;
}
for (size_t i = 0; i < obj.fields_len; i++) {
mocha_field_t field = mocha_field(&obj, i);
printf("%s: {\n", field.name);
<code>for (size_t j = 0; j < field.value.object.fields_len; j++) {
mocha_field_t field0 = mocha_field(&field.value.object, j);
printf("%s: ", field0.name);
switch (field0.type) {
case MOCHA_VALUE_TYPE_INTEGER64:
printf("%ld\n", field0.value.integer64);
break;
case MOCHA_VALUE_TYPE_FLOAT64:
printf("%f\n", field0.value.float64);
break;
case MOCHA_VALUE_TYPE_STRING:
printf("'%s'\n", field0.value.string);
break;
case MOCHA_VALUE_TYPE_ARRAY:
printf("[");
for (size_t idx = 0; idx < field0.value.array.items_len; idx++) {
mocha_value_t value;
mocha_value_type_t value_type = mocha_array(&field0.value.array, &value, idx);
if (value_type == MOCHA_VALUE_TYPE_STRING) {
printf("'%s' ", value.string);
} else if (value_type == MOCHA_VALUE_TYPE_FLOAT64) {
printf("%f", value.float64);
}
}
printf("]\n");
break;
case MOCHA_VALUE_TYPE_REFERENCE:
fwrite(field0.value.reference.name, field0.value.reference.name_len, 1, stdout);
if (field0.value.reference.child != NULL) printf(":");
mocha_reference_t reference;
reference.child = field0.value.reference.child;
while (mocha_reference_next(&reference) == 0) {
fwrite(reference.name, reference.name_len, 1, stdout);
if (reference.child != NULL) printf(":");
}
printf("\n");
break;
default:
break;
}
}
printf("}\n");
</code>
}
mocha_deinit(&obj);
}
```
References
<ul>
<li><a>mocha</a></li>
</ul>
License
This repo is released under the <a>BSD-3-Clause-Clear License</a>. | [] |
https://avatars.githubusercontent.com/u/128398851?v=4 | scrolllockd | ry-diffusion/scrolllockd | 2023-05-27T01:05:52Z | The Scrolllockd led daemon for Linux | zig | 0 | 1 | 0 | 1 | https://api.github.com/repos/ry-diffusion/scrolllockd/tags | - | [
"daemon",
"evdev",
"linux",
"zig"
] | 32 | false | 2024-08-18T12:03:39Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/25558240?v=4 | protest | ibokuri/protest | 2023-11-19T05:11:52Z | A set of modules for easy testing in Zig | main | 0 | 1 | 3 | 1 | https://api.github.com/repos/ibokuri/protest/tags | MIT | [
"assert",
"assertions",
"require",
"testing",
"zig",
"ziglang"
] | 25,547 | false | 2024-06-12T14:04:41Z | true | true | unknown | github | [] | Protest
<a></a>
<a></a>
<a></a>
<a></a>
Protest is a set of modules for testing and validating Zig code. A
<a>testify</a> for Zig, if you will, cause testify's awesome!
<a><code>require</code></a> Module
The <code>require</code> module some provides helpful functions to help you write tests.
<ul>
<li>Descriptive and easy to read failure descriptions.</li>
<li>Simplified testing code.</li>
<li>Requirements can be annotated with a custom message.</li>
</ul>
```zig
const require = @import("protest").require;
test {
// Require equality.
try require.equalf(123, 123, "They should be {s}", .{"equal"});
<code>// Require inequality.
try require.notEqualf(123, 456, "They should not be {s}", .{"equal"});
// Require that `value` is not null.
try require.notNull(value);
// Since `value` cannot be null, safely unwrap it and check its payload.
try require.equal("Foobar", value.?);
</code>
}
```
```
run test: error: 'test_0' failed:
<code> Error: Not equal:
expected: "Foobar"
actual: "Barfoo"
Error Trace:
</code>
/tmp/example/src/main.zig:14:5: 0x1048a5027 in test_0 (test)
try require.equal("Foobar", value.?);
^
```
Installation
<ol>
<li>
Declare Protest as a dependency in <code>build.zig.zon</code>:
<code>diff
.{
.name = "my-project",
.version = "1.0.0",
.paths = .{""},
.dependencies = .{
+ .protest = .{
+ .url = "https://github.com/ibokuri/protest/archive/<COMMIT>.tar.gz",
+ },
},
}</code>
</li>
<li>
Add Protest as a module in <code>build.zig</code>:
```diff
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<ul>
<li>const opts = .{ .target = target, .optimize = optimize };</li>
<li>
const protest_mod = b.dependency("protest", opts).module("protest");
const tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
</li>
<li>
tests.addModule("protest", protest_mod);
...
}
```
</li>
</ul>
</li>
<li>
Obtain Protest's package hash:
<code>$ zig build --fetch
my-project/build.zig.zon:7:20: error: url field is missing corresponding hash field
.url = "https://github.com/ibokuri/protest/archive/<COMMIT>.tar.gz",
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
note: expected .hash = "<HASH>",</code>
</li>
<li>
Update <code>build.zig.zon</code> with Protest's package hash:
<code>diff
.{
.name = "my-project",
.version = "1.0.0",
.paths = .{""},
.dependencies = .{
.protest = .{
.url = "https://github.com/ibokuri/protest/archive/<COMMIT>.tar.gz",
+ .hash = "<HASH>",
},
},
}</code>
</li>
</ol> | [
"https://github.com/getty-zig/getty",
"https://github.com/getty-zig/json"
] |
https://avatars.githubusercontent.com/u/69832658?v=4 | ZEngine | bluesillybeard/ZEngine | 2024-02-03T17:54:34Z | A basic game engine written in Zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/bluesillybeard/ZEngine/tags | MIT | [
"engine",
"game-development",
"game-engine",
"zig",
"ziglang"
] | 49 | false | 2024-05-24T05:03:19Z | true | false | unknown | github | [] | ZEngine
A basic game engine written in Zig. It's more of a basic foundation than anything.
Important notice
ZEngine is early in development. It may <em>seem</em> like an insanely tiny library, therefore it's impossible to get wrong. However, since this is a critical part of a game, despite its simplicity there is still so much it can improve. As such, expect breaking changes!
Also, ZEngine is specifically created for my own projects. It's MIT licensed for a reason - I have little care about what other people do with it, since I created it for my own use.
Features
<ul>
<li>ECS using zig-ecs</li>
<li>Separated state and behavior<ul>
<li>Components define state, Systems define behavior</li>
</ul>
</li>
<li>multiple entity registries per application<ul>
<li>This means, you can have multiple instances of your application, but still have a single rendering system.</li>
</ul>
</li>
<li>Fully modular - ZEngine is merely the framework for a more advanced custom solution to be built. Official modules are in separate repositories, so they are 100% optional.<ul>
<li>This means you can use the official system, use someone elses, or just write your own!</li>
</ul>
</li>
</ul>
Official systems
<ul>
<li>None at the moment - you'll have to do mostly everything yourself</li>
</ul>
Examples
see <a>ZEngineExamples</a> for examples on how to use ZEngine
TODO:
<ul>
<li>built-in serialization<ul>
<li>automatic and explicit version forwarding</li>
<li>components can be excluded from serialization</li>
</ul>
</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/28833727?v=4 | aes-my-file | zzk13180/aes-my-file | 2023-05-14T04:08:58Z | ⚡Encrypt/decrypt files using the AES-256-GCM algorithm | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/zzk13180/aes-my-file/tags | MIT | [
"aes-256-gcm",
"encrypt",
"encryption-decryption",
"zig"
] | 7 | false | 2025-02-10T00:45:57Z | true | false | unknown | github | [] | Encrypt and decrypt your files using AES algorithm
Getting Started
<ul>
<li>Install <a>Zig</a>. zig_version 0.11.0</li>
</ul>
<code>bash
git submodule update --init</code>
<code>bash
zig build run</code>
Download
<ul>
<li><a>Windows</a></li>
</ul>
you can open system dialog to select file
| [] |
https://avatars.githubusercontent.com/u/141338245?v=4 | zig_fmt | wasm-fmt/zig_fmt | 2023-09-01T05:08:08Z | A WASM Based Zig Formatter | main | 2 | 1 | 0 | 1 | https://api.github.com/repos/wasm-fmt/zig_fmt/tags | MIT | [
"formatter",
"formatting",
"wasm",
"webassembly",
"zig"
] | 49 | false | 2025-03-15T18:48:37Z | true | false | unknown | github | [] | <a></a>
<a></a>
Install
<code>bash
npm install @wasm-fmt/zig_fmt</code>
Usage
```javascript
import init, { format } from "@wasm-fmt/zig_fmt";
await init();
const input = `
const std = @import("std");
pub fn main() !void
{
const stdout = std.io.getStdOut().writer();
var i: usize = 1;
while (i <= 16) : (i += 1)
{
if (i % 15 == 0)
{
try stdout.writeAll("ZiggZagg\n");
} else
if (i % 3 == 0)
{
try stdout.writeAll("Zigg\n");
} else
if (i % 5 == 0)
{
try stdout.writeAll("Zagg\n");
}
else
{
try stdout.print("{d}\n", .{i});
}
}
}
`;
const formatted = format(input);
console.log(formatted);
```
For Vite users:
```JavaScript
import init, { format } from "@wasm-fmt/zig_fmt/vite";
// ...
``` | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | Zig-BitHelper | bcrist/Zig-BitHelper | 2023-10-28T05:50:38Z | Zig utilities for low-level bit manipulation | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/bcrist/Zig-BitHelper/tags | MIT | [
"util",
"utilities",
"utility-library",
"utils",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 4 | false | 2024-07-27T18:06:17Z | true | true | 0.12.0-dev.2063+804cee3b9 | github | [] | Zig-BitHelper
Provides some helper functions for dealing with integers as bit fields:
<ul>
<li>bits.as: Similar to @bitCast, but works with enums as well</li>
<li>bits.zx: Casts as unsigned and zero-extends to the requested size</li>
<li>bits._1x: Casts as unsigned and one-extends to the requested size</li>
<li>bits.sx: Casts as signed and then extends to the requested size</li>
<li>bits.concat: Concatenates unsigned integers (little endian)</li>
<li>bits.swapHalves: Swaps the high and low halves of an integer with event bit count</li>
</ul> | [
"https://github.com/bcrist/Zig-ROM-Compress"
] |
https://avatars.githubusercontent.com/u/7742806?v=4 | aoc-2023 | moutansos/aoc-2023 | 2023-12-03T08:39:12Z | Advent of Code 2023 | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/moutansos/aoc-2023/tags | - | [
"advent-of-code",
"advent-of-code-2023",
"advent-of-code-2023-zig",
"zig"
] | 35 | false | 2024-10-07T19:40:58Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/93522910?v=4 | zigist | 42LM/zigist | 2023-07-27T21:09:23Z | Update a gist with a random dev joke. Pure Zig⚡ | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/42LM/zigist/tags | MIT | [
"actions",
"continuous-integration",
"cron",
"cronjob",
"githubci",
"zig",
"ziglang"
] | 99 | false | 2025-05-08T12:02:45Z | true | false | unknown | github | [] | Zigist - Update a gist with a random dev joke
<a></a> <a></a>
Nothing fancy here. This is just a simple github action to update a gist with a random dev joke using <a>Zig ⚡️</a>.
Quick start
<code>yaml
uses: 42LM/zigist@v1
with:
gh-token: ${{ secrets.GH_TOKEN }}
gist-id: e35b7dfc8ec2c958a7f8f0c9938ffd60</code>
<blockquote>
[!TIP]
Pin the gist in your profile:
<a>See it in ~action~ the wild</a>
</blockquote>
Inputs
|Input Name|Description|Required|
| --- | --- | :---: |
|<code>gh-token</code>|The GitHub <a>Personal Access Token</a> with <em>gist</em> access|☑️|
|<code>gist-id</code>|The GitHub public gist id|☑️|
<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>
<code>gh-token</code>: The GitHub Token needs to be created as a repository secret in the repository that uses this action.[^1]
<code>gist-id</code>: The GitHub gist needs to be created with the file name <code>NEWS.md</code>.[^2]
</blockquote>
Example usage
https://github.com/42LM/zigist/blob/772cf37d3bf22d435f5aa8459b65a6a150d69e7f/.github/workflows/cron.yaml#L1-L16
Local environment setup
The following two environment variables need to be set up:
1. <code>GH_TOKEN</code>: Create a github token that has access to gists.
2. <code>GIST_ID</code>: Create a gist.
Copy <code>.envrc.example</code> to <code>.envrc</code> and edit values. Load this environment into your shell, for example with <a>direnv</a>.
<code>sh
cp .envrc.example .envrc</code>
Zig
<code>sh
zig build run</code>
<code>sh
zig build test --summary all</code>
Docker
<code>sh
docker build -t zig0.14.0 .</code>
<code>sh
docker run --name zigist zig0.14.0 $GH_TOKEN $GIST_ID</code>
[^1]: Place repository secret:
[^2]: Create github gist with filename <code>NEWS.md</code>: | [] |
https://avatars.githubusercontent.com/u/2529002?v=4 | comptime | robinvandernoord/comptime | 2023-08-10T12:45:47Z | "Zig into Python's speed lane with Comptime – it's not a sprint; it's a compile!" | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/robinvandernoord/comptime/tags | MIT | [
"ast",
"compiler",
"comptime",
"python",
"zig"
] | 43 | false | 2024-08-28T22:45:26Z | false | false | unknown | github | [] | comptime
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
"Comptime" accelerates Python code by precomputing complex calculations, turning them into simple lookups for faster
execution.
<strong>Table of Contents</strong>
<ul>
<li><a>Installation</a></li>
<li><a>Usage</a></li>
<li><a>License</a></li>
</ul>
Comptime is inspired by the concept of compile-time computation found in languages
like <a>Zig</a>, and it brings this powerful
feature into the world of Python, an interpreted language. By utilizing special decorators, you can mark functions whose
return values should be precomputed. This enables you to separate computationally expensive parts of your code,
performing those calculations once, and embedding the results directly into your source code. The result is Python code
that executes faster by turning complex calculations into simple lookups. Whether you're optimizing critical performance
bottlenecks or exploring new ways to structure your code, Comptime offers a novel approach to accelerate your Python
development.
<strong>"Zig into Python's speed lane with Comptime – it's not a sprint; it's a compile!"</strong>
:warning: Warning: this is only a proof-of-concept
This code was only created to test the concept. It should NOT be used in a production environment, as I can not
guarantee at this time that the semantics of the outputted code are correct.
Furthermore, initial performance tests show that for relatively simple calculations, this does NOT actually improve
performance:
```bash
python examples/perf.py # pre-comptime:
Function executed in: 2.0992 seconds total; avg of 209.92 ns. per execution.
python examples/perf_match.py # comptime with match-case strategy:
Function executed in: 21.5824 seconds total; avg of 2158.24 ns. per execution.
python examples/perf_dict.py # comptime with dict lookup strategy:
Function executed in: 152.4098 seconds total; avg of 15240.98 ns. per execution.
```
While this package could be useful in cases where the calculation is actually heavy, it could also negatively impact
your performance!
Installation
<code>console
pip install comptime</code>
Usage
```python
src_raw/main.py: before comptime
from comptime import comptime
@comptime.skip
def nonpure_method():
# this method has side effects so should only be used at runtime
print("e.g. sending an email")
@comptime
def my_method():
...
# some expensive calculations
nonpure_method() # not executed due to @comptime.skip
return 41 + 1
@comptime("users", "posts")
def call_api(endpoint):
# api get value for endpoint
...
return value
call_api("other") # possible comptime warning due to unsupported argument?
```
<code>bash
comptime --input src_raw --output src_compiled</code>
```python
src_compiled/main.py: after comptime
import typing
def nonpure_method():
# this method has side effects so should only be used at runtime
print("e.g. sending an email")
def my_method():
# computed by comptime
return 42
def call_api(endpoint: typing.Literal["users", "posts"]):
# computed by comptime
match endpoint:
case "users":
return ['user1']
case "posts":
return ['post1']
case _:
raise ValueError("Uncompiled variant {endpoint}")
return value
```
Acknowledgments
This project owes its inspiration and certain elements of its design to various sources:
<ul>
<li>
<strong>Zig Programming Language:</strong> The concept of compile-time computation in Comptime is inspired
by <a>Zig</a>, a language that emphasizes safety, performance, and readability. A special
thank you to Zig's creators and community for their innovative approach to programming.
</li>
<li>
<strong>GPT-4 by OpenAI:</strong> Assistance with the project boilerplate, creative brainstorming, and crafting the memorable
slogan "Zig into Python's speed lane with Comptime – it's not a sprint; it's a compile!" was provided by GPT-4. It
also wrote this section.
</li>
</ul>
Please note that the author of comptime is not affiliated with Zig, OpenAI, or any other entities mentioned
above. The acknowledgments are expressions of gratitude and inspiration and do not imply any formal association or
endorsement by these parties.
License
<code>comptime</code> is distributed under the terms of the <a>MIT</a> license. | [] |
https://avatars.githubusercontent.com/u/5161200?v=4 | monkey-lang | viddrobnic/monkey-lang | 2023-09-06T10:43:44Z | Interpreter for monkey language based on interpreterbook.com. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/viddrobnic/monkey-lang/tags | MIT | [
"rust",
"zig"
] | 279 | false | 2024-05-13T20:43:35Z | false | false | unknown | github | [] | Monkey Language
Interpreter for Monkey Language based on the <a>Writing An Interpreter In Go</a> book. This repository contains two implementations - one in Rust and one in Zig.
Project Structure
This repository contains two implementations of the interpreter. The primary implementation is the one in Rust, which implements more features of the language.
The implementation in Zig was done for learning purposes as my first non-hello world project in Zig. It implements only the basic language features.
Performance
During the implementation of the interpreter in Zig, I started wondering how the original Go implementation from the book's author compares to the Rust and Zig implementations.
Rust and Zig are not garbage collected, which makes the implementation of the AST evaluation different from the Go implementation since you have to also implement your own garbage collector.
I tested the performance of all three interpreters on a simple program that calculates Fibonacci numbers. It was tested on an M1 MacBook Pro. Here are the results:
| Language | Average Time [ms] | Relative Performance |
| -------- | ----------------- | -------------------- |
| Go | 4.303 | 1.0 |
| Rust | 5.730 | 1.33 |
| Zig | 6.397 | 1.49 |
<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 benchmark is not very detailed and was done just to satisfy my curiosity, so it should be taken with a grain of salt.
</blockquote>
License
Project is licensed under the <a>MIT License</a>. | [] |
https://avatars.githubusercontent.com/u/8881507?v=4 | zentropy | aalbacetef/zentropy | 2024-02-01T16:37:09Z | A tool to measure a file's Shannon entropy. Available on Linux, Mac, and Windows. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/aalbacetef/zentropy/tags | BSD-3-Clause | [
"shannon-entropy",
"zig"
] | 177 | false | 2024-10-06T20:40:01Z | true | true | unknown | github | [] | Introduction
<code>zentropy</code> is a tool to measure a file's Shannon entropy, which gives useful information such as theoretical minimum size, but also helpful in identifying specific kinds of files.
Note, various compression algorithms can reach sizes smaller than the one given by calculating Shannon entropy, as Shannon entropy assumes a statistical model where the bytes are uncorrelated (i.e: 0 order).
Usage
Fairly straightforward, point it at a file!
<code>bash
$ zentropy /path/to/file</code>
Here's the output of running it against the project's build.zig:
```bash
$ zentropy ./build.zig
| zentropy |
entropy => 0.55 nats
entropy (bits) => 4.36 bits
file size => 1.59 Kib
possible file size => 887.35 bytes
compression => 45.49 %
```
Installation
Get a precompiled binary from the <a>release page</a> or build your own with zig!
Special steps
On both Linux and Mac, don't forget to <code>chmod +x /path/to/binary</code>.
Mac might yell at you for trying to run the binary, in which case, just run:
<code>bash
$ xattr -d com.apple.quarantine /path/to/binary</code>
Supported platforms
So far, it's only been tested on:
| arch | os |
|---------|---------|
| x86_64 | windows |
| x86_64 | linux |
| x86_64 | mac os |
Roadmap
Some things on the roadmap / to-do list when I have some 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> support wasm
<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> JSON output
<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> wrap in a Docker container
<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> allow setting chunk size via env var or cli flag | [] |
https://avatars.githubusercontent.com/u/1713384?v=4 | bug-free-enigma | exilesprx/bug-free-enigma | 2023-11-19T22:40:37Z | Ziglings | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/exilesprx/bug-free-enigma/tags | MIT | [
"zig",
"ziglings"
] | 1,413 | false | 2025-04-29T02:54:55Z | true | false | unknown | github | [] | Cheatsheet
Namespaces
<code>// methods declared in namespaces is also known as "decls"</code>
Pointers
<code>// FREE ZIG POINTER CHEATSHEET! (Using u8 as the example type.)
// +---------------+----------------------------------------------+
// | u8 | one u8 |
// | *u8 | pointer to one u8 |
// | [2]u8 | two u8s |
// | [*]u8 | pointer to unknown number of u8s |
// | [*]const u8 | pointer to unknown number of immutable u8s |
// | *[2]u8 | pointer to an array of 2 u8s |
// | *const [2]u8 | pointer to an immutable array of 2 u8s |
// | []u8 | slice of u8s |
// | []const u8 | slice of immutable u8s |
// +---------------+----------------------------------------------+</code>
Tagged unions - exercise 057
<code>// If you don't have a need for a separate enum, you can define
// an inferred enum with your union all in one place. Just use
// the 'enum' keyword in place of the tag type:
//
// const Foo = union(enum) {
// small: u8,
// medium: u32,
// large: u64,
// };</code>
Error unions
```
// If canFail() fails, foo will equal 6.
// One way to deal with error unions is to "catch" any error and
// replace it with a default value.
//
// foo = canFail() catch 6;
// Zig lets us make what's called an "error union" which is a value
// which could either be a regular value OR an error from a set:
//
// var text: MyErrorSet!Text = getText("foo.txt");
// Catch lets us capture the error value and perform additional
// actions with this form:
//
// canFail() catch |err| {
// if (err == FishError.TunaMalfunction) {
// ...
// }
// };
//
// Zig has a handy "try" shortcut for this common error handling pattern:
//
// canFail() catch |err| return err;
//
// which can be more compactly written as:
//
// try canFail();
//
// Let's revisit the very first error exercise. This time, we're going to
// look at an error-handling variation of the "if" statement.
//
// if (foo) |value| {
//
// // foo was NOT an error; value is the non-error value of foo
//
// } else |err| {
//
// // foo WAS an error; err is the error value of foo
//
// }
//
// We'll take it even further and use a switch statement to handle
// the error types.
//
// if (foo) |value| {
// ...
// } else |err| switch(err) {
// ...
// }
```
Optionals
```
// Sometimes you know that a variable might hold a value or
// it might not. Zig has a neat way of expressing this idea
// called Optionals. An optional type just has a '?' like this:
//
// var foo: ?u32 = 10;
//
// Now foo can store a u32 integer OR null (a value storing
// the cosmic horror of a value NOT EXISTING!)
// The handy ".?" shortcut:
//
// const foo = bar.?;
//
// is the same as
//
// const foo = bar orelse unreachable;
//
// Before we can use the optional value as the non-null type
// (a u32 integer in this case), we need to guarantee that it
// isn't null. One way to do this is to THREATEN IT with the
// "orelse" statement.
//
// var bar = foo orelse 2;
//
// Optionals are a lot like error union types which can either
// hold a value or an error. Likewise, the orelse statement is
// like the catch statement used to "unwrap" a value or supply
// a default value:
//
// var maybe_bad: Error!u32 = Error.Evil;
// var number: u32 = maybe_bad catch 0;
```
Floating point numbers
<code>// As an example, Zig's f16 is a IEEE 754 "half-precision" binary
// floating-point format ("binary16"), which is stored in memory
// like so:
//
// 0 1 0 0 0 0 1 0 0 1 0 0 1 0 0 0
// | |-------| |-----------------|
// | exponent significand
// |
// sign</code>
Coerce
<code>//
// 1. Types can always be made _more_ restrictive.
//
// var foo: u8 = 5;
// var p1: *u8 = &foo;
// var p2: *const u8 = p1; // mutable to immutable
//
// 2. Numeric types can coerce to _larger_ types.
//
// var n1: u8 = 5;
// var n2: u16 = n1; // integer "widening"
//
// var n3: f16 = 42.0;
// var n4: f32 = n3; // float "widening"
//
// 3. Single-item pointers to arrays coerce to slices and
// many-item pointers.
//
// const arr: [3]u8 = [3]u8{5, 6, 7};
// const s: []const u8 = &arr; // to slice
// const p: [*]const u8 = &arr; // to many-item pointer
//
// 4. Single-item mutable pointers can coerce to single-item
// pointers pointing to an array of length 1. (Interesting!)
//
// var five: u8 = 5;
// var a_five: *[1]u8 = &five;
//
// 5. Payload types and null coerce to optionals.
//
// var num: u8 = 5;
// var maybe_num: ?u8 = num; // payload type
// maybe_num = null; // null
//
// 6. Payload types and errors coerce to error unions.
//
// const MyError = error{Argh};
// var char: u8 = 'x';
// var char_or_die: MyError!u8 = char; // payload type
// char_or_die = MyError.Argh; // error
//
// 7. 'undefined' coerces to any type (or it wouldn't work!)
//
// 8. Compile-time numbers coerce to compatible types.
//
// Just about every single exercise program has had an example
// of this, but a full and proper explanation is coming your
// way soon in the third-eye-opening subject of comptime.
//
// 9. Tagged unions coerce to the current tagged enum.
//
// 10. Enums coerce to a tagged union when that tagged field is a
// zero-length type that has only one value (like void).
//
// 11. Zero-bit types (like void) can be coerced into single-item
// pointers.
//</code>
Loop expressions
```
// But what value is returned from a loop if a break statement is
// never reached? We need a default expression. Thankfully, Zig
// loops also have 'else' clauses! As you might have guessed, the
// 'else' clause is evaluated when: 1) a 'while' condition becomes
// false or 2) a 'for' loop runs out of items.
//
// const two: u8 = while (true) break 2 else 0; // 2
// const three: u8 = for ([1]u8{1}) |f| break 3 else 0; // 3
// Until version 0.11, Zig's 'for' loops did not directly
// replicate the functionality of the C-style: "for(a;b;c)"
// which are so well suited for iterating over a numeric
// sequence.
//
// Instead, 'while' loops with counters clumsily stood in their
// place:
//
// var i: usize = 0;
// while (i < 10) : (i += 1) {
// // Here variable 'i' will have each value 0 to 9.
// }
//
// But here we are in the glorious future and Zig's 'for' loops
// can now take this form:
//
// for (0..10) |i| {
// // Here variable 'i' will have each value 0 to 9.
// }
//
// The key to understanding this example is to know that '0..9'
// uses the new range syntax:
//
// 0..10 is a range from 0 to 9
// 1..4 is a range from 1 to 3
//
// At the moment, ranges are only supported in 'for' loops.
//
// The general form of a 'for' loop with two lists is:
//
// for (list_a, list_b) |a, b| {
// // Here we have the first item from list_a and list_b,
// // then the second item from each, then the third and
// // so forth...
// }
//
// What's really beautiful about this is that we don't have to
// keep track of an index or advancing a memory pointer for
// <em>either</em> of these lists. That error-prone stuff is all taken
// care of for us by the compiler.
//
//
// The 'for' loop is not just limited to looping over one or two
// items. Let's try an example with a whole bunch!
//
// But first, there's one last thing we've avoided mentioning
// until now: The special range that leaves off the last value:
//
// for ( things, 0.. ) |t, i| { ... }
//
// That's how we tell Zig that we want to get a numeric value for
// every item in "things", starting with 0.
//
// A nice feature of these index ranges is that you can have them
// start with any number you choose. The first value of "i" in
// this example will be 500, then 501, 502, etc.:
//
// for ( things, 500.. ) |t, i| { ... }
//
```
Labels
```
// As we've just learned, you can return a value using a break
// statement. Does that mean you can return a value from any
// labeled block? Yes it does!
//
// const foo = make_five: {
// const five = 1 + 1 + 1 + 1 + 1;
// break :make_five five;
// };
// Being able to return a value from an
// inner loop is sometimes so handy, it almost feels like cheating
// (and can help you avoid creating a lot of temporary variables).
//
// const bar: u8 = two_loop: while (true) {
// while (true) {
// break :two_loop 2;
// }
// } else 0;
// Finally, you can also use block labels with the 'continue'
// statement:
//
// my_while: while (true) {
// continue :my_while;
// }
```
Comptime
```
// ALL numeric literals in Zig are of type comptime_int or
// comptime_float. They are of arbitrary size (as big or
// little as you need).
//
// Notice how we don't have to specify a size like "u8",
// "i32", or "f64" when we assign identifiers immutably with
// "const".
//
// When we use these identifiers in our program, the VALUES
// are inserted at compile time into the executable code. The
// IDENTIFIERS "const_int" and "const_float" don't exist in
// our compiled application!
//
// const const_int = 12345;
// const const_float = 987.654;
//
// But something changes when we assign the exact same values
// to identifiers mutably with "var".
// When placed before a variable declaration, 'comptime'
// guarantees that every usage of that variable will be performed
// at compile time.
//
// As a simple example, compare these two statements:
//
// var bar1 = 5; // ERROR!
// comptime var bar2 = 5; // OKAY!
//
// The first one gives us an error because Zig assumes mutable
// identifiers (declared with 'var') will be used at runtime and
// we have not assigned a runtime type (like u8 or f32). Trying
// to use a comptime_int of undetermined size at runtime is
// a MEMORY CRIME and you are UNDER ARREST.
//
// You can also put 'comptime' before a function parameter to
// enforce that the argument passed to the function must be known
// at compile time. We've actually been using a function like
// this the entire time, std.debug.print():
//
// fn print(comptime fmt: []const u8, args: anytype) void
//
//
// One of the more common uses of 'comptime' function parameters is
// passing a type to a function:
//
// fn foo(comptime MyType: type) void { ... }
//
// In fact, types are ONLY available at compile time, so the
// 'comptime' keyword is required here.
//
//
// Being able to pass types to functions at compile time lets us
// generate code that works with multiple types. But it doesn't
// help us pass VALUES of different types to a function.
//
// For that, we have the 'anytype' placeholder, which tells Zig
// to infer the actual type of a parameter at compile time.
//
// fn foo(thing: anytype) void { ... }
//
// Then we can use builtins such as @TypeOf(), @typeInfo(),
// @typeName(), @hasDecl(), and @hasField() to determine more
// about the type that has been passed in. All of this logic will
// be performed entirely at compile time.
//
// An 'inline for' is performed at compile time, allowing you to
// programatically loop through a series of items in situations
// like those mentioned above where a regular runtime 'for' loop
// wouldn't be allowed:
//
// inline for (.{ u8, u16, u32, u64 }) |T| {
// print("{} ", .{@typeInfo(T).Int.bits});
// }
//
// In the above example, we're looping over a list of types,
// which are available only at compile time.
//
// There is also an 'inline while'. Just like 'inline for', it
// loops at compile time, allowing you to do all sorts of
// interesting things not possible at runtime.
//
// As a matter of fact, you can put 'comptime' in front of any
// expression to force it to be run at compile time.
//
// Execute a function:
//
// comptime llama();
//
// Get a value:
//
// bar = comptime baz();
//
// Execute a whole block:
//
// comptime {
// bar = baz + biff();
// llama(bar);
// }
//
// Get a value from a block:
//
// var llama = comptime bar: {
// const baz = biff() + bonk();
// break :bar baz;
// }
// In addition to knowing when to use the 'comptime' keyword,
// it's also good to know when you DON'T need it.
//
// The following contexts are already IMPLICITLY evaluated at
// compile time, and adding the 'comptime' keyword would be
// superfluous, redundant, and smelly:
//
// * The container-level scope (outside of any function in a source file)
// * Type declarations of:
// * Variables
// * Functions (types of parameters and return values)
// * Structs
// * Unions
// * Enums
// * The test expressions in inline for and while loops
// * An expression passed to the @cImport() builtin
//
// Work with Zig for a while, and you'll start to develop an
// intuition for these contexts. Let's work on that now.
```
Sentinels
```
// A sentinel value indicates the end of data. Let's imagine a
// sequence of lowercase letters where uppercase 'S' is the
// sentinel, indicating the end of the sequence:
//
// abcdefS
//
// If our sequence also allows for uppercase letters, 'S' would
// make a terrible sentinel since it could no longer be a regular
// value in the sequence:
//
// abcdQRST
// ^-- Oops! The last letter in the sequence is R!
//
// Zig supports sentinel-terminated arrays, slices, and pointers:
//
// const a: [4:0]u32 = [4:0]u32{1, 2, 3, 4};
// const b: [:0]const u32 = &[4:0]u32{1, 2, 3, 4};
// const c: [*:0]const u32 = &[4:0]u32{1, 2, 3, 4};
//
// Array 'a' stores 5 u32 values, the last of which is 0.
// However the compiler takes care of this housekeeping detail
// for you. You can treat 'a' as a normal array with just 4
// items.
//
// Slice 'b' is only allowed to point to zero-terminated arrays
// but otherwise works just like a normal slice.
//
// Pointer 'c' is exactly like the many-item pointers we learned
// about in exercise 054, but it is guaranteed to end in 0.
// Because of this guarantee, we can safely find the end of this
// many-item pointer without knowing its length. (We CAN'T do
//
// Are you ready for the THE TRUTH about Zig string literals?
//
// Here it is:
//
// @TypeOf("foo") == *const [3:0]u8
//
// Which means a string literal is a "constant pointer to a
// zero-terminated (null-terminated) fixed-size array of u8".
//
// Now you know. You've earned it. Welcome to the secret club!
//
// Why do we bother using a zero/null sentinel to terminate
// strings in Zig when we already have a known length?
//
// Versatility! Zig strings are compatible with C strings (which
// are null-terminated) AND can be coerced to a variety of other
// Zig types:
//
// const a: [5]u8 = "array".<em>;
// const b: </em>const [16]u8 = "pointer to array";
// const c: []const u8 = "slice";
// const d: [:0]const u8 = "slice with sentinel";
// const e: [<em>:0]const u8 = "many-item pointer with sentinel";
// const f: [</em>]const u8 = "many-item pointer";
//
// All but 'f' may be printed. (A many-item pointer without a
// sentinel is not safe to print because we don't know where it
// ends!)
//
// We were able to get a printable string out of a many-item
// pointer by using a slice to assert a specific length.
//
// But can we ever GO BACK to a sentinel-terminated pointer
// after we've "lost" the sentinel in a coercion?
//
// Yes, we can. Zig's @ptrCast() builtin can do this. Check out
// the signature:
//
// @ptrCast(value: anytype) anytype
```
Quoted identifiers
<code>//
// Sometimes you need to create an identifier that will not, for
// whatever reason, play by the naming rules:
//
// const 55_cows: i32 = 55; // ILLEGAL: starts with a number
// const isn't true: bool = false; // ILLEGAL: what even?!
//
// If you try to create either of these under normal
// circumstances, a special Program Identifier Syntax Security
// Team (PISST) will come to your house and take you away.
//
// Thankfully, Zig has a way to sneak these wacky identifiers
// past the authorities: the @"" identifier quoting syntax.
//
// @"foo"
//
// Please help us safely smuggle these fugitive identifiers into
// our program:</code>
Structs
```
//
// Struct types are always "anonymous" until we give them a name:
//
// struct {};
//
// So far, we've been giving struct types a name like so:
//
// const Foo = struct {};
//
// * The value of @typeName(Foo) is ".Foo".
//
// A struct is also given a name when you return it from a
// function:
//
// fn Bar() type {
// return struct {};
// }
//
// const MyBar = Bar(); // store the struct type
// const bar = Bar() {}; // create instance of the struct
//
// * The value of @typeName(Bar()) is "Bar()".
// * The value of @typeName(MyBar) is "Bar()".
// * The value of @typeName(@TypeOf(bar)) is "Bar()".
//
// You can also have completely anonymous structs. The value
// of @typeName(struct {}) is "struct:".
//
//
// An anonymous struct value LITERAL (not to be confused with a
// struct TYPE) uses '.{}' syntax:
//
// .{
// .center_x = 15,
// .center_y = 12,
// .radius = 6,
// }
//
// These literals are always evaluated entirely at compile-time.
//
// You can even create anonymous struct literals without field
// names:
//
// .{
// false,
// @as(u32, 15),
// @as(f64, 67.12)
// }
//
// We call these "tuples", which is a term used by many
// programming languages for a data type with fields referenced
// by index order rather than name. To make this possible, the Zig
// compiler automatically assigns numeric field names 0, 1, 2,
// etc. to the struct.
//
// Since bare numbers are not legal identifiers (foo.0 is a
// syntax error), we have to quote them with the @"" syntax.
// Example:
//
// const foo = .{ true, false };
//
// print("{} {}\n", .{foo.@"0", foo.@"1"});
//
// Anonymous struct literal syntax can also be used to compose an
// "anonymous list" with an array type destination:
//
// const foo: [3]u32 = .{10, 20, 30};
//
// Otherwise it's a "tuple":
//
// const bar = .{10, 20, 30};
//
// The only difference is the destination type.
//
```
Async - regressed and not present in the current version as of writing this
```
//
// Six Facts:
//
// 1. The memory space allocated to your program for the
// invocation of a function and all of its data is called a
// "stack frame".
//
// 2. The 'return' keyword "pops" the current function
// invocation's frame off of the stack (it is no longer needed)
// and returns control to the place where the function was
// called.
//
// fn foo() void {
// return; // Pop the frame and return control
// }
//
// 3. Like 'return', the 'suspend' keyword returns control to the
// place where the function was called BUT the function
// invocation's frame remains so that it can regain control again
// at a later time. Functions which do this are "async"
// functions.
//
// fn fooThatSuspends() void {
// suspend {} // return control, but leave the frame alone
// }
//
// 4. To call any function in async context and get a reference
// to its frame for later use, use the 'async' keyword:
//
// var foo_frame = async fooThatSuspends();
//
// 5. If you call an async function without the 'async' keyword,
// the function FROM WHICH you called the async function itself
// becomes async! In this example, the bar() function is now
// async because it calls fooThatSuspends(), which is async.
//
// fn bar() void {
// fooThatSuspends();
// }
//
// 6. The main() function cannot be async!
//
// Given facts 3 and 4, how do we fix this program (broken by facts
// 5 and 6)?
//
//
// So, 'suspend' returns control to the place from which it was
// called (the "call site"). How do we give control back to the
// suspended function?
//
// For that, we have a new keyword called 'resume' which takes an
// async function invocation's frame and returns control to it.
//
// fn fooThatSuspends() void {
// suspend {}
// }
//
// var foo_frame = async fooThatSuspends();
// resume foo_frame;
//
//
// Because they can suspend and resume, async Zig functions are
// an example of a more general programming concept called
// "coroutines". One of the neat things about Zig async functions
// is that they retain their state as they are suspended and
// resumed.
//
//
// The 'await' keyword waits for an async function to complete
// and then captures its return value.
//
// fn foo() u32 {
// return 5;
// }
//
// var foo_frame = async foo(); // invoke and get frame
// var value = await foo_frame; // await result using frame
//
//
// Remember how a function with 'suspend' is async and calling an
// async function without the 'async' keyword makes the CALLING
// function async?
//
// fn fooThatMightSuspend(maybe: bool) void {
// if (maybe) suspend {}
// }
//
// fn bar() void {
// fooThatMightSuspend(true); // Now bar() is async!
// }
//
// But if you KNOW the function won't suspend, you can make a
// promise to the compiler with the 'nosuspend' keyword:
//
// fn bar() void {
// nosuspend fooThatMightSuspend(false);
// }
//
// If the function does suspend and YOUR PROMISE TO THE COMPILER
// IS BROKEN, the program will panic at runtime, which is
// probably better than you deserve, you oathbreaker! >:-(
//
//
// You have doubtless noticed that 'suspend' requires a block
// expression like so:
//
// suspend {}
//
// The suspend block executes when a function suspends. To get
// sense for when this happens, please make the following
// program print the string
//
// "ABCDEF"
//
```
Interfaces
<code>//
// Remember our ant and bee simulator constructed with unions
// back in exercises 55 and 56? There, we demonstrated that
// unions allow us to treat different data types in a uniform
// manner.
//
// One neat feature was using tagged unions to create a single
// function to print a status for ants *or* bees by switching:
//
// switch (insect) {
// .still_alive => ... // (print ant stuff)
// .flowers_visited => ... // (print bee stuff)
// }
//
// Well, that simulation was running just fine until a new insect
// arrived in the virtual garden, a grasshopper!
//
// Doctor Zoraptera started to add grasshopper code to the
// program, but then she backed away from her keyboard with an
// angry hissing sound. She had realized that having code for
// each insect in one place and code to print each insect in
// another place was going to become unpleasant to maintain when
// the simulation expanded to hundreds of different insects.
//
// Thankfully, Zig has another comptime feature we can use
// to get out of this dilemma called the 'inline else'.
//
// We can replace this redundant code:
//
// switch (thing) {
// .a => |a| special(a),
// .b => |b| normal(b),
// .c => |c| normal(c),
// .d => |d| normal(d),
// .e => |e| normal(e),
// ...
// }
//
// With:
//
// switch (thing) {
// .a => |a| special(a),
// inline else => |t| normal(t),
// }
//
// We can have special handling of some cases and then Zig
// handles the rest of the matches for us.
//</code>
C integration
```
//
// When Andrew Kelley announced the idea of a new programming language
// - namely Zig - in his blog on February 8, 2016, he also immediately
// stated his ambitious goal: to replace the C language!
//
// In order to be able to achieve this goal at all, Zig should be
// as compatible as possible with its "predecessor".
// Only if it is possible to exchange individual modules in existing
// C programs without having to use complicated wrappers,
// the undertaking has a chance of success.
//
// So it is not surprising that calling C functions and vice versa
// is extremely "smooth".
//
// To call C functions in Zig, you only need to specify the library
// that contains said function. For this purpose there is a built-in
// function corresponding to the well-known @import():
//
// @cImport()
//
// All required libraries can now be included in the usual Zig notation:
//
// const c = @cImport({
// @cInclude("stdio.h");
// @cInclude("...");
// });
//
// Now a function can be called via the (in this example) constant 'c':
//
// c.puts("Hello world!");
//
//
// Something must be considered when compiling with C functions.
// Namely that the Zig compiler knows that it should include
// corresponding libraries. For this purpose we call the compiler
// with the parameter "lc" for such a program,
// e.g. "zig run -lc hello_c.zig".
//
```
Memory allocation
```
//
// Zig provides several different allocators. In the Zig
// documentation, it recommends the Arena allocator for simple
// programs which allocate once and then exit:
//
// const std = @import("std");
//
// // memory allocation can fail, so the return type is !void
// pub fn main() !void {
//
// var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
// defer arena.deinit();
//
// const allocator = arena.allocator();
//
// const ptr = try allocator.create(i32);
// std.debug.print("ptr={<em>}\n", .{ptr});
//
// const slice_ptr = try allocator.alloc(f64, 5);
// std.debug.print("slice_ptr={</em>}\n", .{slice_ptr});
// }
//
// For more details on memory allocation and the different types of
// memory allocators, see https://www.youtube.com/watch?v=vHWiDx_l4V0
//
// // In order to be able to process the input values,
// // memory is required. An allocator is defined here for
// // this purpose.
// const ally = std.testing.allocator;
//
// // The allocator is used to initialize an array into which
// // the numbers are stored.
// var list = std.ArrayList(u32).init(ally);
//
```
Formatting
```
//
// C set string formatting standards over the years, and Zig is
// following suit and growing daily. Due to this growth, there is
// no official documentation for standard library features such
// as string formatting.
//
// Therefore, the comments for the format() function are the only
// way to definitively learn how to format strings in Zig:
//
// https://github.com/ziglang/zig/blob/master/lib/std/fmt.zig#L29
//
//
// And this is where it gets exciting, because format() accepts a
// variety of formatting instructions. It's basically a tiny
// language of its own. Here's a numeric example:
//
// print("Catch-{x:0>4}.", .{twenty_two});
//
// This formatting instruction outputs a hexadecimal number with
// leading zeros:
//
// Catch-0x0016.
//
// Or you can center-align a string like so:
//
// print("{s:<em>^20}\n", .{"Hello!"});
//
// Output:
//
// </em><strong><em>*</em>*Hello!</strong><strong>*</strong>
//
```
Data-oriented design
```
//
// In the Zig community, you may see the difference in groupings
// presented with the terms "Array of Structs" (AoS) versus
// "Struct of Arrays" (SoA).
//
// To envision these two designs in action, imagine an array of
// RPG character structs, each containing three different data
// types (AoS) versus a single RPG character struct containing
// three arrays of one data type each, like those in the exercise
// above (SoA).
//
//
// For a more practical application of "data-oriented design"
// watch the following talk from Andrew Kelley, the creator of Zig:
// https://vimeo.com/649009599
//
```
Testing
```
//
// A big advantage of Zig is the integration of its own test system.
// This allows the philosophy of Test Driven Development (TDD) to be
// implemented perfectly. Zig even goes one step further than other
// languages, the tests can be included directly in the source file.
//
// This has several advantages. On the one hand it is much clearer to
// have everything in one file, both the source code and the associated
// test code. On the other hand, it is much easier for third parties
// to understand what exactly a function is supposed to do if they can
// simply look at the test inside the source and compare both.
//
// Especially if you want to understand how e.g. the standard library
// of Zig works, this approach is very helpful. Furthermore it is very
// practical, if you want to report a bug to the Zig community, to
// illustrate it with a small example including a test.
//
// Tests can be run via Zig build system or applied directly to
// individual modules using "zig test xyz.zig".
//
```
Tokenization
<code>//
// // In order to be able to process the input values,
// // memory is required. An allocator is defined here for
// // this purpose.
// const ally = std.testing.allocator;
//
// // The allocator is used to initialize an array into which
// // the numbers are stored.
// var list = std.ArrayList(u32).init(ally);
//
//
// // This way you can never forget what is urgently needed
// // and the compiler doesn't grumble either.
// defer list.deinit();
//
// // Now it gets exciting:
// // A standard tokenizer is called (Zig has several) and
// // used to locate the positions of the respective separators
// // (we remember, space and comma) and pass them to an iterator.
// var it = std.mem.tokenizeAny(u8, input, " ,");
//
// // The iterator can now be processed in a loop and the
// // individual numbers can be transferred.
// while (it.next()) |num| {
// // But be careful: The numbers are still only available
// // as strings. This is where the integer parser comes
// // into play, converting them into real integer values.
// const n = try parseInt(u32, num, 10);
//
// // Finally the individual values are stored in the array.
// try list.append(n);
// }
//</code>
Threading
<code>// These curly brackets are very important, they are necessary
// to enclose the area where the threads are called.
// Without these brackets, the program would not wait for the
// end of the threads and they would continue to run beyond the
// end of the program.
// pub fn main() void {
// {
// Now we start the first thread, with the number as parameter
// const handle = try std.Thread.spawn(.{}, thread_function, .{1});
//
// Waits for the thread to complete,
// then deallocates any resources created on `spawn()`.
// defer handle.join();
// }
// }
//</code> | [] |
https://avatars.githubusercontent.com/u/61315998?v=4 | widow | eddineimad0/widow | 2023-06-10T20:59:18Z | A Simple zig library for creating windows and getting inputs. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/eddineimad0/widow/tags | MIT | [
"input",
"window",
"windows",
"zig"
] | 9,126 | false | 2025-05-13T09:18:55Z | true | true | 0.14.0 | github | [
{
"commit": "d5f381759825ee0bac29bc294d47aa05be4ab7b5",
"name": "zigglgen",
"tar_url": "https://github.com/castholm/zigglgen/archive/d5f381759825ee0bac29bc294d47aa05be4ab7b5.tar.gz",
"type": "remote",
"url": "https://github.com/castholm/zigglgen"
}
] | Introduction
Widow is a simple windowing library written in zig.
Supported Platforms
Currently Widow supports windows Os.
Support for Linux isn't complete yet and still in work,
and there is no current plan to support any other platforms.
Examples
All API functions are well documented and you can check out the examples
for more details on how to use.
The following sample creates a window.
```zig
const std = @import("std");
const widow = @import("widow");
const EventType = widow.event.EventType;
const EventQueue = widow.event.EventQueue;
const KeyCode = widow.input.keyboard.KeyCode;
var gpa_allocator: std.heap.DebugAllocator(.{}) = .init;
pub fn main() !void {
defer std.debug.assert(gpa_allocator.deinit() == .ok);
const allocator = gpa_allocator.allocator();
<code>// first we need to preform some platform specific initialization.
// and build a context for the current platform.
// the context also keep a copy of the allocator you pass it
// to use it for all allocations done by the library.
const ctx = try widow.createWidowContext(allocator);
defer widow.destroyWidowContext(allocator, ctx);
// the window will require an event queue to
// send events.
var ev_queue = try EventQueue.init(allocator, 256);
defer ev_queue.deinit();
// create a WindowBuilder.
var builder = widow.WindowBuilder.init();
// customize the window.
var mywindow = builder.withTitle("Simple Window")
.withSize(800, 600)
.withResize(true)
.withDPIAware(true)
.withPosition(200, 200)
.withDecoration(true)
.build(ctx, null) catch |err| {
std.debug.print("Failed to build the window,{}\n", .{err});
return;
};
// closes the window when done.
defer mywindow.deinit();
_ = mywindow.setEventQueue(&ev_queue);
event_loop: while (true) {
// wait until an event is posted.
try mywindow.waitEvent();
var event: widow.event.Event = undefined;
while (ev_queue.popEvent(&event)) {
switch (event) {
EventType.WindowClose => |window_id| {
std.debug.print("closing Window #{}\n", .{window_id});
break :event_loop;
},
EventType.Keyboard => |*key| {
if (key.state.isPressed()) {
if (key.keycode == KeyCode.Q) {
// let's request closing the window on
// pressing Q key
mywindow.queueCloseEvent();
}
}
},
else => continue,
}
}
}
</code>
}
```
Minimum Zig Version
✅ <a>0.14.0</a>
The main branch will stick to stable zig releases.
Dependecies
<ul>
<li><a>zigglgen</a>: OpenGL binding used in the <code>gl_triangle.zig</code> example</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/1596350?v=4 | advent-of-code-zig | russmatney/advent-of-code-zig | 2023-11-24T23:40:13Z | null | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/russmatney/advent-of-code-zig/tags | - | [
"advent-of-code",
"adventofcode",
"zig"
] | 41 | false | 2025-02-19T17:50:51Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/139293750?v=4 | SortedMap | bogwi/SortedMap | 2023-11-29T04:12:49Z | Map for fast storing key-value pairs sorted by key | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/bogwi/SortedMap/tags | MIT | [
"map",
"skiplist",
"sorted-data",
"sorted-map",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 128 | false | 2024-10-25T08:43:07Z | true | true | unknown | github | [] | SortedMap in ZIG
Description
Sorted Map is a fast key-value table, an advance version of <a>skiplist ADT</a> as proposed by W.Pugh in 1989 for ordered mapping of keys to values.
Features
<ul>
<li>Takes any numeric key except the maximum possible value for the given type. </li>
<li>Takes any literal key of type <code>[]const u8</code> and of any length, but lexicographically smaller than <code>"ÿ"</code> ASCII 255. </li>
<li>Values are arbitrary values.</li>
<li>Works in <code>.set</code> or <code>.list</code> mode. The latter allows duplicate keys.</li>
<li>Has forward and backward iteration.</li>
<li>Has <code>min</code>, <code>max</code>, <code>median</code> key query.</li>
<li>Supports queries by key or index, similar to Python's list class, including reverse indexing.</li>
<li>Basic operations like <code>get</code>, <code>remove</code> work on a range as well.</li>
<li>Updating the values by giving the <code>start_idx</code> - <code>stop_idx</code> range is O(1) each update. Yes, the whole map can be updated in O(n).</li>
<li>Updating the values by giving the <code>start_key</code> - <code>stop_key</code> range is O(1) each update.</li>
</ul>
Performance
The benchmark is a set of standard stress routines to measure the throughput for the given task. The machine is an Apple M1 with 32GB RAM, optimization flag <code>ReleaseFast</code>.
There are five tests in total, all of which are run on the random data with intermediate shuffling during the test stages:
<strong>READ HEAVY</strong>\
[read 98, insert 1, remove 1, update 0 ]\
Models caching of data in places such as web servers and disk page caches.
<strong>EXCHANGE</strong>\
[read 10, insert 40, remove 40, update 10]\
Replicates a scenario where the map is used to exchange data.
<strong>EXCHANGE HEAVY</strong>\
[read 1, insert 98, remove 98, update 1]\
This test is an inverse of <em>RH</em> test. Hard for any map.
<strong>RAPID GROW</strong>\
[read 5, insert 80, remove 5, update 10]\
A scenario where the map is used to collect large amounts of data in a short burst.
<strong>CLONE</strong>\
Clone the Map. That is, rebuild the map anew yet from the sorted data.
<code>u64</code>, arbitrary feed
```
SortedMap u64 BENCHMARK|
10_000_000 ops:each test|
|name |Tp Mops:sec| Rt :sec|
=====================================
|RH | 51.47| 0.194274|
arena size: 13804, cache len: 131
|EX | 23.25| 0.430069|
arena size: 13804, cache len: 121
|EXH | 20.20| 0.494928|
arena size: 13804, cache len: 135
|RG | 0.53| 18.996072|
arena size: 595966060, cache len: 5
|CLONE | 5.86| 1.279128|
```
<code>[8]const u8</code>, arbitrary literal, arbitrary feed
```
SortedMap STR BENCHMARK|
10_000_000 ops:each test|
|name |Tp Mops:sec| Rt :sec|
=====================================
|RH | 25.49| 0.392336|
arena size: 13564, cache len: 133
|EX | 17.02| 0.587408|
arena size: 13564, cache len: 123
|EXH | 14.49| 0.690115|
arena size: 13564, cache len: 137
|RG | 0.37| 26.855707|
arena size: 894236804, cache len: 5
|CLONE | 3.12| 2.400613|
```
How to run the benchmark
<code>zig build bench</code>
By default it runs 100_000 rounds each test on the <code>u64</code> type.
Give it a larger number to stress the map more.
<code>zig build bench -- 1_000_000</code>
Prepend with <code>-str</code> to test on the arbitrary <code>[8]u8</code> word.
<code>zig build bench -- 1_000_000 -str</code>
How to use it
Copy <code>sorted_map.zig</code> and <code>cache.zig</code> into your project, or make a fork and work from there. Or you can import it as a dependency.
Declare in your file:
<code>zig
const SortedMap = @import("sorted_map.zig").SortedMap;</code>
Initiate for numeric keys:
```zig
const map = SortedMap(u64, your_value_type, .list).init(your_allocator);
defer map.deinit();
```
Initiate for string literal keys:
<code>zig
const map = SortedMap([]const u8, your_value_type, .set).init(your_allocator);
defer map.deinit();</code>
zig version
<code>0.12.0-dev.1830+779b8e259</code> | [] |
https://avatars.githubusercontent.com/u/968130?v=4 | zlox | iam-afk/zlox | 2023-04-19T14:10:43Z | The Lox language implementation in Zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/iam-afk/zlox/tags | MIT | [
"crafting-interpreters",
"zig"
] | 9 | false | 2023-04-19T19:51:20Z | true | false | unknown | github | [] | zlox
The Lox language implementation in Zig | [] |
https://avatars.githubusercontent.com/u/44898501?v=4 | zig-install | MinecraftPublisher/zig-install | 2023-09-09T13:48:28Z | Unofficial installer and downloader for zig. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/MinecraftPublisher/zig-install/tags | - | [
"installer",
"installer-script",
"zig",
"ziglang"
] | 3 | false | 2024-01-13T10:36:22Z | false | false | unknown | github | [] | zig-build
An installer script for zig, Written in Bun Javascript.
This script:
<ol>
<li>Fetches the release data from the official zig website</li>
<li>Obtains the build target for the current machine</li>
<li>Checks for an existing clone of the latest download ->
If yes, Jumps directly to Step 5.</li>
<li>Downloads and extracts the latest release</li>
<li>Copies the latest release to the current user's home directory.</li>
<li>Quits; If there are no errors, A <code>zig/</code> directory should be created on your
home directory.</li>
</ol>
Adding to PATH
To add zig to path after running this script, You have to add this line to your rc file:
<code>bash
export PATH=$PATH:~/zig</code>
Or, To ease your work, Run this:
<code>bash
curl https://raw.githubusercontent.com/MinecraftPublisher/zig-build/master/path.sh | $0</code>
(This will download and run the script below)
Or, Run this script to add it directly to your rc file:
```bash
Detect shell
echo Detecting current shell...
SHELL=""
for i in $(echo $0 | tr "/" "\n"); do
SHELL=$i
done
RC="$HOME/.${SHELL}rc"
echo RC Path: $RC
echo 'export PATH=$PATH:~/zig' >> $RC
echo Done!
``` | [] |
https://avatars.githubusercontent.com/u/36560490?v=4 | zig-ws | thegeeko/zig-ws | 2023-10-25T19:15:39Z | websocket server implementation based on https://datatracker.ietf.org/doc/html/rfc6455 | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/thegeeko/zig-ws/tags | - | [
"websocket",
"websocket-server",
"zig"
] | 418 | false | 2024-03-12T23:43:39Z | true | false | unknown | github | [] | ZIG-WS:
a server implementaion of <a>RFC6455</a> in Zig it passes the whole <a>autobahn</a> test suite you can see the report inside the support folder
Test localy:
to start a simple echo server:
```bash
clone repo
git clone https://github.com/thegeeko/zig-ws && cd zig-ws
start the server
zig build run_example
```
you can run tests by :
```bash
clone repo
git clone https://github.com/thegeeko/zig-ws && cd zig-ws
start the server
zig build run_example
on another term run tests using autobahn docker image
docker run -it --rm \
-v "$PWD/autobahn/:/config" \
-v "$PWD/autobahn/reports:/reports" \
--net="host" \
--name fuzzingclient \
crossbario/autobahn-testsuite wstest -m fuzzingclient -s /config/fuzzingclient.json
```
How it works:
it doesn't create http server or handle that for you .. it only takes an allocator and std server Response object eg:
```zig
const std = @import("std");
const Response = std.http.Server.Response;
// ZIG_WS
const WsEvents = @import("ws").WsEvents;
const WebSocket = @import("ws").WebSocket;
const CloseStatus = @import("ws").CloseStatus;
pub fn main() !void {
var ga = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = ga.allocator();
defer {
const check = ga.deinit();
if (check == .leak) {
@panic("Memory Leak");
}
}
<code>var server = std.http.Server.init(allocator, .{ .reuse_address = true });
defer server.deinit();
const addr = try std.net.Address.parseIp("127.0.0.1", 3000);
try server.listen(addr);
std.log.info("server started in port: {}", .{3000});
const ws_events = WsEvents{
.on_msg = on_msg,
.on_binary = on_binary,
};
while (true) {
var res = try server.accept(.{ .allocator = allocator });
res.wait() catch |err| switch (err) {
error.HttpHeadersInvalid => continue,
error.ConnectionResetByPeer => continue,
error.EndOfStream => continue,
else => return err,
};
// will take the ownership of the response
var ws = try WebSocket.init(allocator, &res);
defer ws.deinit();
try ws.handle(ws_events);
}
</code>
}
fn on_msg(msg: []const u8, ws: *WebSocket) void {
std.log.debug("msg: ({}) {s}", .{ msg.len, msg });
ws.send(msg) catch unreachable;
}
fn on_binary(msg: []const u8, ws: *WebSocket) void {
std.log.debug("msg - bin: ({}) {}", .{ msg.len, std.fmt.fmtSliceHexLower(msg) });
ws.send_binary(msg) catch unreachable;
}
``` | [] |
https://avatars.githubusercontent.com/u/76531574?v=4 | zig_c_mixture | malespiaut/zig_c_mixture | 2023-06-30T07:05:06Z | Minimal working example of mixing Zig with C code. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/malespiaut/zig_c_mixture/tags | Unlicense | [
"c",
"c-interop",
"zig",
"zig-interop"
] | 5 | false | 2025-03-03T15:10:55Z | true | false | unknown | github | [] | Zig and C mixture
This repo contains a minimal working example, of a Zig program that also contains C files.
This is meant to show and teach you how can Zig code can call C code, and vice versa. | [] |
https://avatars.githubusercontent.com/u/30945458?v=4 | zig-glfw | FalsePattern/zig-glfw | 2023-06-17T17:10:45Z | Ziggified GLFW bindings with 100% API coverage, zero-fuss installation, cross compilation, and more. | main | 1 | 1 | 0 | 1 | https://api.github.com/repos/FalsePattern/zig-glfw/tags | NOASSERTION | [
"gamedev",
"glfw",
"zig",
"zig-package",
"ziglang"
] | 3,773 | true | 2025-05-20T07:35:29Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "glfw_c",
"tar_url": "https://github.com/falsepattern/glfw//archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/falsepattern/glfw/"
}
] | zig-glfw
Perfected GLFW bindings for Zig, with 100% API coverage, zero-fuss installation, cross compilation, and more.
Features
<ul>
<li>Zero-fuss installation, cross-compilation at the flip of a switch, and broad platform support.</li>
<li>100% API coverage. Every function, type, constant, etc. has been exposed in a ziggified API.</li>
</ul>
Community maintained
The <a>Mach engine</a> project no longer uses GLFW, and so this project is now community-maintained. Pull requests are welcome and will be reviewed.
Some old documentation is available <a>here</a> (most of which is replicated below).
What does a ziggified GLFW API offer?
<ul>
<li><strong>Enums</strong>, always know what value a GLFW function can accept as everything is strictly typed. And use the nice Zig syntax to access enums, like <code>window.getKey(.escape)</code> instead of <code>c.glfwGetKey(window, c.GLFW_KEY_ESCAPE)</code></li>
<li>Slices instead of C pointers and lengths.</li>
<li>Generics, so you can just use window.hint instead of glfwWindowHint, glfwWindowHintString, etc.</li>
<li><a>packed structs</a> represent bit masks, so you can use <code>if (joystick.down and joystick.right)</code> instead of <code>if (joystick & c.GLFW_HAT_DOWN and joystick & c.GLFW_HAT_RIGHT)</code>, etc.</li>
<li>Methods, e.g. <code>my_window.hint(...)</code> instead of <code>glfwWindowHint(my_window, ...)</code>.</li>
<li><code>true</code> and <code>false</code> instead of <code>c.GLFW_TRUE</code> and <code>c.GLFW_FALSE</code> constants.</li>
</ul>
How do I use OpenGL, Vulkan, etc. with this?
You’ll need to bring your own library, e.g.:
<ul>
<li>OpenGL: <a>castholm/zigglgen</a> (<a>example</a>)</li>
<li>Vulkan: <a>Snektron/vulkan-zig</a> (<a>example</a>)</li>
</ul>
Getting started
First <code>zig init</code> to create a Zig project. Then you will need to add mach-glfw to your <code>build.zig.zon</code>, and update your <code>build.zig</code> and <code>src/main.zig</code> files:
<code>build.zig.zon</code>
mach-glfw uses the Zig package manager. To add it as a dependency, run the following command:
<code>sh
zig fetch --save git+https://github.com/falsepattern/zig-glfw</code>
This will add an entry for zig-glfw to your <code>build.zig.zon</code>.
<code>build.zig</code>
Add the following to your <code>build.zig</code> below your <code>const exe = b.addExecutable(...)</code> line:
<code>zig
// Use zig-glfw
const glfw_dep = b.dependency("zig_glfw", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("glfw", glfw_dep.module("zig-glfw"));</code>
<code>src/main.zig</code>
Here’s an example program to get you started:
```zig
const std = @import("std");
const glfw = @import("glfw");
/// Default GLFW error handling callback
fn errorCallback(error_code: glfw.ErrorCode, description: [:0]const u8) void {
std.log.err("glfw: {}: {s}\n", .{ error_code, description });
}
pub fn main() !void {
glfw.setErrorCallback(errorCallback);
if (!glfw.init(.{})) {
std.log.err("failed to initialize GLFW: {?s}", .{glfw.getErrorString()});
return error.GlfwInitFailed;
}
defer glfw.terminate();
<code>// Create our window
const window = glfw.Window.create(640, 480, "Hello, zig-glfw!", null, null, .{}) orelse {
std.log.err("failed to create GLFW window: {?s}", .{glfw.getErrorString()});
return error.WindowCreationFailed;
};
defer window.destroy();
// Wait for the user to close the window.
while (!window.shouldClose()) {
window.swapBuffers();
// Render your graphics here
glfw.pollEvents();
}
</code>
}
```
A warning about error handling
<strong>Unless the action you’re performing is truly critical to your application continuing further, you should avoid terminating on GLFW errors and log them instead.</strong>
Unfortunately, GLFW must return errors for a <em>large portion</em> of its functionality on some platforms, but especially for Wayland in particular.
If you want your application to run well for most Linux users, you should e.g. merely log errors that are not critical.
Here is a rough list of functionality Wayland does not support:
<ul>
<li><code>Window.setIcon</code></li>
<li><code>Window.setPos</code>, <code>Window.getPos</code></li>
<li><code>Window.iconify</code>, <code>Window.focus</code></li>
<li><code>Monitor.setGamma</code></li>
<li><code>Monitor.getGammaRamp</code>, <code>Monitor.setGammaRamp</code></li>
</ul>
For example, <code>window.getPos()</code> will always return x=0, y=0 on Wayland due to lack of platform support. Ignoring this error is a reasonable choice for most applications.
However, errors like this can still be caught and handled:
```zig
const pos = window.getPos();
// Option 1: convert a GLFW error into a Zig error.
// Heed our warning about Wayland above, though!
glfw.getErrorCode() catch |err| {
std.log.err("failed to get window position: error={!}", .{err});
return err; // Or fall back to an alternative implementation.
};
// Option 2: log a human-readable description of the error.
if (glfw.getErrorString()) |description| {
std.log.err("failed to get window position: {s}", .{description});
// ...
}
// Option 3: use a combination of the above approaches.
if (glfw.getError()) |err| {
const error_code = err.error_code; // Zig error
const description = err.description; // Human-readable description
std.log.err("failed to get window position: error={!}: {s}", .{error_code, description});
// ...
}
```
Note that the above example relies on GLFW’s saved error being empty; otherwise, previously emitted errors may be mistaken for an error caused by <code>window.getPos()</code>.
If your application frequently ignores errors, it may be necessary to call <code>glfw.clearError()</code> or <code>defer glfw.clearError()</code> to ensure a clean slate for future error handling.
GLFW version
We generally follow the latest master version of GLFW, as recorded <a>here</a>, as this allows us to work with the GLFW author to fix e.g. undefined behavior that Zig catches, and benefit from the latest & greatest changes - such as runtime X11/Wayland switching recently. | [] |
https://avatars.githubusercontent.com/u/12397073?v=4 | yacli | IridescentRose/yacli | 2023-09-13T17:59:04Z | Yet Another CLI! | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/IridescentRose/yacli/tags | MIT | [
"cli",
"zig"
] | 9 | false | 2023-11-01T17:25:19Z | false | false | unknown | github | [] | yacli
Yet Another CLI Library (in Zig)
How do I use it?
Import the <code>yacli.zig</code> file:
<code>zig
const yacli = @import("yacli.zig");</code>
Now define your subroutines:
```zig
fn version_subroutine(arg_it: anytype) !void {
_ = arg_it;
std.debug.print("Version 1\n", .{});
}
pub fn main() {
// ...
<code>const help_string =
\\version Prints version
\\
;
try yacli.parse_subroutines(allocator, help_string, .{
version_subroutine,
});
</code>
}
```
Great but how do I get arguments?
Let's modify the previous program:
```zig
fn hello_subroutine(arg_it: anytype) !void {
const help_string =
\name= Name to print
\
;
var args = yacli.parse_args(help_string, arg_it) catch return;
<code>std.debug.print("Hello, {s}!", .{args.name});
</code>
}
fn version_subroutine(arg_it: anytype) !void {
_ = arg_it;
std.debug.print("Version 1\n", .{});
}
pub fn main() {
// ...
<code>const help_string =
\\add Add two numbers
\\version Prints version
\\
;
try yacli.parse_subroutines(allocator, help_string, .{
hello_subroutine,
version_subroutine,
});
</code>
}
```
Limitations
Currently the annotated type in the help string is not parsed yet -- everything is just a string. | [] |
https://avatars.githubusercontent.com/u/81834798?v=4 | zilo | TheMetalStorm/zilo | 2023-08-13T18:48:38Z | kilo editor in zig, following along with https://viewsourcecode.org/snaptoken/kilo/index.html | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/TheMetalStorm/zilo/tags | - | [
"kilo",
"linux",
"programming",
"terminal",
"terminal-based",
"termios",
"text-editor",
"texteditor",
"ubuntu",
"zig",
"ziglang",
"zilo"
] | 66 | false | 2024-10-07T01:09:29Z | true | false | unknown | github | [] | zilo
kilo editor, ported from C to Zig!
Why?
I wanted to work on a project in my free time. A while back I watched a few parts of a Video Series in which someone was porting the Kilo Text Editor to Rust. I though that it would be a nice way to learn a new programming language and I also was interested in learning how a simple text editor works. So I decided to do something similiar, and while I didn't want to dive deeper into Rust (yet?), another langauge had caught my eye. I liked Zigs Syntax and its promises of being a "modern" C alternative, so I got started.
Build
This program was built with Zig 0.11. Compile it with the command:
<code>zig build -Doptimize=ReleaseSafe</code>
Usage
<code>./zilo [filepath]</code> | [] |
https://avatars.githubusercontent.com/u/138609742?v=4 | zig-pipeline | fluent-ci-templates/zig-pipeline | 2023-07-04T17:09:11Z | A ready-to-use CI/CD Pipeline for Zig projects. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/fluent-ci-templates/zig-pipeline/tags | MIT | [
"cicd",
"dagger",
"deno",
"deno-module",
"devops",
"pipeline",
"typescript",
"zig"
] | 158 | false | 2024-11-27T06:43:19Z | false | false | unknown | github | [] | Zig Pipeline
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
A ready-to-use CI/CD Pipeline for your <a>Zig</a> projects.
🚀 Usage
Run the following command in your project:
<code>bash
fluentci run zig_pipeline</code>
Or, if you want to use it as a template:
<code>bash
fluentci init -t zig</code>
This will create a <code>.fluentci</code> folder in your project.
Now you can run the pipeline with:
<code>bash
fluentci run .</code>
🧩 Dagger Module
Use as a <a>Dagger</a> module:
<code>bash
dagger install github.com/fluent-ci-templates/zig-pipeline@main</code>
Call a function from the module:
```bash
dagger -m github.com/fluent-ci-templates/zig-pipeline call \
test --src .
dagger -m github.com/fluent-ci-templates/zig-pipeline call \
build --src .
```
🛠️ Environment variables
| Variable | Description |
| --------------- | ---------------------------------------------- |
| <code>ZIG_VERSION</code> | The version of Zig to use. Defaults to <code>0.10.1</code> |
✨ Jobs
| Job | Description |
| --------- | ------------- |
| test | Run tests |
| build | Build project |
```typescript
test(
src: Directory | string = ".",
version?: string
): Promise
build(
src: Directory | string = ".",
version?: string
): Promise
```
👨💻 Programmatic usage
You can also use this pipeline programmatically:
```ts
import { test, build } from "jsr:@fluentci/zig";
await test();
await build();
``` | [] |
https://avatars.githubusercontent.com/u/24578855?v=4 | zig-totp | deatil/zig-totp | 2023-10-22T06:24:40Z | A TOTP and HOTP library for zig. | main | 0 | 1 | 1 | 1 | https://api.github.com/repos/deatil/zig-totp/tags | Apache-2.0 | [
"hotp",
"otp",
"otp-generator",
"otp-verification",
"otpauth",
"totp",
"zig",
"zig-hotp",
"zig-otp",
"zig-totp"
] | 285 | false | 2025-05-21T03:55:19Z | true | true | 0.14.0-dev.3451+d8d2aa9af | github | [] | Zig-totp
A TOTP and HOTP library for zig.
Why One Time Passwords?
One Time Passwords (OTPs) are an mechanism to improve security over passwords alone. When a Time-based OTP (TOTP) is stored on a user's phone, and combined with something the user knows (Password), you have an easy on-ramp to <a>Multi-factor authentication</a> without adding a dependency on a SMS provider. This Password and TOTP combination is used by many popular websites including Google, GitHub, Facebook, Salesforce and many others.
The <code>zig-totp</code> library enables you to easily add TOTPs to your own application, increasing your user's security against mass-password breaches and malware.
Because TOTP is standardized and widely deployed, there are many <a>mobile clients and software implementations</a>.
Env
<ul>
<li>Zig >= 0.14.0-dev.3451+d8d2aa9af</li>
</ul>
Adding zig-totp as a dependency
Add the dependency to your project:
<code>sh
zig fetch --save=zig-totp git+https://github.com/deatil/zig-totp#main</code>
or use local path to add dependency at <code>build.zig.zon</code> file
<code>zig
.{
.dependencies = .{
.@"zig-totp" = .{
.path = "./lib/zig-totp",
},
...
}
}</code>
And the following to your <code>build.zig</code> file:
<code>zig
const zig_totp_dep = b.dependency("zig-totp", .{});
exe.root_module.addImport("zig-totp", zig_totp_dep.module("zig-totp"));</code>
The <code>zig-totp</code> structure can be imported in your application with:
<code>zig
const zig_totp = @import("zig-totp");</code>
Get Starting
~~~zig
const std = @import("std");
const totp = @import("zig-totp");
pub fn main() !void {
const alloc = std.heap.page_allocator;
<code>const secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
const n = totp.time.now().utc();
const passcode = try totp.generateCode(alloc, secret, n);
// output:
// generateCode: 906939
std.debug.print("generateCode: {s} \n", .{passcode});
const valid = totp.validate(alloc, passcode, secret);
// output:
// validate: true
std.debug.print("validate: {} \n", .{valid});
</code>
}
~~~
Generate keyurl
~~~zig
const std = @import("std");
const totp = @import("zig-totp");
pub fn main() !void {
const alloc = std.heap.page_allocator;
<code>const secret = "test-data";
var key = try totp.generate(alloc, .{
.issuer = "Example",
.account_name = "accountName",
.period = 30,
// .secret_size = 20,
// use secret if secret not empty, or use secret_size to generate secret
.secret = secret,
.digits = .Six,
.algorithm = .SHA1,
});
const keyurl = key.urlString();
// output:
// keyurl: otpauth://totp/Example:accountName?issuer=Example&period=30&digits=6&secret=ORSXG5BNMRQXIYI&algorithm=SHA1
std.debug.print("keyurl: {} \n", .{keyurl});
</code>
}
~~~
LICENSE
<ul>
<li>The library LICENSE is <code>Apache2</code>, using the library need keep the LICENSE.</li>
</ul>
Copyright
<ul>
<li>Copyright deatil(https://github.com/deatil).</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/16594625?v=4 | cake.zig | purrie/cake.zig | 2023-10-06T11:45:18Z | UI toolkit written in Zig | master | 0 | 1 | 1 | 1 | https://api.github.com/repos/purrie/cake.zig/tags | MIT | [
"raylib",
"ui",
"zig"
] | 134 | false | 2024-09-01T15:39:55Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/8009085?v=4 | llama2.c | aahmed-se/llama2.c | 2023-11-25T03:39:02Z | Inference Llama 2 in one file of pure C | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/aahmed-se/llama2.c/tags | MIT | [
"zig",
"ziglang"
] | 1,189 | true | 2023-12-22T12:00:17Z | true | false | unknown | github | [] | llama2.c
Zig Build Support
This is fork of the original project with support for build.zig
Here are the instructions to use it
<code>cd llama2.c
zig build
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories15M.bin
mv ./zig-out/bin/run
./run stories15M.bin</code>
Tested with zig 0.11.0
Introduction
Have you ever wanted to inference a baby <a>Llama 2</a> model in pure C? No? Well, now you can!
Train the Llama 2 LLM architecture in PyTorch then inference it with one simple 700-line C file (<a>run.c</a>). You might think that you need many billion parameter LLMs to do anything useful, but in fact very small LLMs can have surprisingly strong performance if you make the domain narrow enough (ref: <a>TinyStories</a> paper). This repo is a "fullstack" train + inference solution for Llama 2 LLM, with focus on minimalism and simplicity.
As the architecture is identical, you can also load and inference Meta's Llama 2 models. However, the current code only inferences models in fp32, so you will most likely not be able to productively load models larger than 7B. Work on model quantization is currently ongoing.
Please note that this repo started recently as a fun weekend project: I took my earlier <a>nanoGPT</a>, tuned it to implement the Llama-2 architecture instead of GPT-2, and the meat of it was writing the C inference engine in <a>run.c</a>. So the project is young and moving quickly. Hat tip to the awesome <a>llama.cpp</a> for inspiring this project. Compared to llama.cpp, I wanted something super simple, minimal, and educational so I chose to hard-code the Llama 2 architecture and just roll one inference file of pure C with no dependencies.
feel the magic
<a></a>
First, navigate to the folder where you keep your projects and clone this repository to this folder:
<code>bash
git clone https://github.com/karpathy/llama2.c.git</code>
Then, open the repository folder:
<code>bash
cd llama2.c</code>
Now, let's just run a baby Llama 2 model in C. You need a model checkpoint. Download this 15M parameter model I trained on the <a>TinyStories</a> dataset (~60MB download):
<code>bash
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories15M.bin</code>
Compile and run the C code:
<code>bash
make run
./run stories15M.bin</code>
You'll see the text stream a sample. On my M1 MacBook Air this runs at ~110 tokens/s. See <a>performance</a> or the Makefile for compile flags that can significantly speed this up. We can also try a bit bigger 42M parameter model:
<code>bash
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories42M.bin
./run stories42M.bin</code>
This still runs at interactive rates and samples more coherent and diverse stories:
<blockquote>
Once upon a time, there was a little girl named Lily. She loved playing with her toys on top of her bed. One day, she decided to have a tea party with her stuffed animals. She poured some tea into a tiny teapot and put it on top of the teapot. Suddenly, her little brother Max came into the room and wanted to join the tea party too. Lily didn't want to share her tea and she told Max to go away. Max started to cry and Lily felt bad. She decided to yield her tea party to Max and they both shared the teapot. But then, something unexpected happened. The teapot started to shake and wiggle. Lily and Max were scared and didn't know what to do. Suddenly, the teapot started to fly towards the ceiling and landed on the top of the bed. Lily and Max were amazed and they hugged each other. They realized that sharing was much more fun than being selfish. From that day on, they always shared their tea parties and toys.
</blockquote>
You can also prompt the model with a prefix or a number of additional command line arguments, e.g. to sample at temperature 0.8 for 256 steps and with a prompt:
<code>bash
./run stories42M.bin -t 0.8 -n 256 -i "One day, Lily met a Shoggoth"</code>
<blockquote>
One day, Lily met a Shoggoth. He was very shy, but was also very generous. Lily said “Hello Shoggy! Can I be your friend?” Shoggy was happy to have a friend and said “Yes, let’s explore the universe together!” So they set off on a journey to explore the universe. As they travelled, Shoggy was happy to explain to Lily about all the wonderful things in the universe. At the end of the day, Lily and Shoggy had gathered lots of wonderful things from the universe, and they both felt very proud. They promised to explore the universe as one big pair and to never stop being generous to each other.
</blockquote>
There is also an even better 110M param model available, see <a>models</a>.
Quick note on sampling, the recommendation for ~best results is to sample with <code>-t 1.0 -p 0.9</code>, i.e. temperature 1.0 (default) but also top-p sampling at 0.9 (default). Intuitively, top-p ensures that tokens with tiny probabilities do not get sampled, so we can't get "unlucky" during sampling, and we are less likely to go "off the rails" afterwards. More generally, to control the diversity of samples use either the temperature (i.e. vary <code>-t</code> between 0 and 1 and keep top-p off with <code>-p 0</code>) or the top-p value (i.e. vary <code>-p</code> between 0 and 1 and keep <code>-t 1</code>), but not both. Nice explainers on LLM sampling strategies include <a>this</a>, <a>this</a> or <a>this</a>.
Meta's Llama 2 models
As the neural net architecture is identical, we can also inference the Llama 2 models released by Meta. Sadly there is a bit of friction here due to licensing (I can't directly upload the checkpoints, I think). So Step 1, get the Llama 2 checkpoints by following the <a>Meta instructions</a>. Once we have those checkpoints, we have to convert them into the llama2.c format.
For this we need to install the python dependencies (<code>pip install -r requirements.txt</code>) and then use the <code>export.py</code> file, e.g. for 7B model:
<code>bash
python export.py llama2_7b.bin --meta-llama path/to/llama/model/7B</code>
The export will take ~10 minutes or so and generate a 26GB file (the weights of the 7B model in float32) called <code>llama2_7b.bin</code> in the current directory. It has been <a>reported</a> that despite efforts. I would not attempt to run anything above 7B right now for two reasons: first, 13B+ currently doesn't work because of integer flow in pointer arithmetic, which is yet to be fixed, and second, even if it were fixed, this repo is doing float32 inference right now, so it would be fairly unusably slow. Once the export is done, we can run it:
<code>bash
./run llama2_7b.bin</code>
This ran at about 4 tokens/s compiled with <a>OpenMP</a> on 96 threads on my CPU Linux box in the cloud. (On my MacBook Air M1, currently it's closer to 30 seconds per token if you just build with <code>make runfast</code>.) Example output:
<blockquote>
The purpose of this document is to highlight the state-of-the-art of CoO generation technologies, both recent developments and those in commercial use. The focus is on the technologies with the highest merit to become the dominating processes of the future and therefore to be technologies of interest to S&T ... R&D. As such, CoO generation technologies developed in Russia, Japan and Europe are described in some depth. The document starts with an introduction to cobalt oxides as complex products and a short view on cobalt as an essential material. The document continues with the discussion of the available CoO generation processes with respect to energy and capital consumption as well as to environmental damage.
</blockquote>
base models... ¯\<em>(ツ)</em>/¯. Since we can inference the base model, it should be possible to also inference the chat model quite easily, and have a conversation with it. And if we can find a way to run 7B more efficiently, we can start adding LoRA to our training script, and going wild with finetunes all within the repo!
You can also chat with the Llama Chat models. Export the chat model exactly as above:
<code>bash
python export.py llama2_7b_chat.bin --meta-llama /path/to/7B-chat</code>
Then chat with it by specifying the chat mode using the <code>-m</code> flag, e.g.:
<code>bash
./run llama2_7b_chat.bin -m chat</code>
You can also try Meta's Code Llama models even if support for them is incomplete. In particular, some hyperparameters changed (e.g. the constant in RoPE layer), so the inference is not exactly correct and a bit buggy right now. Looking into fixes. Make sure to build the tokenizer for the plain and instruct variants and pass it when doing inference.
<code>bash
python export.py codellama2_7b.bin --meta-llama /path/to/CodeLlama-7b
python tokenizer.py --tokenizer-model=/path/to/CodeLlama-7b/tokenizer.model
./run codellama2_7b.bin -z /path/to/CodeLlama-7b/tokenizer.bin</code>
Chat with Code Llama Instruct:
<code>bash
python export.py codellama2_7b_instruct.bin --meta-llama /path/to/CodeLlama-7b-Instruct
python tokenizer.py --tokenizer-model=/path/to/CodeLlama-7b-Instruct/tokenizer.model
./run codellama2_7b_instruct.bin -m chat -z /path/to/CodeLlama-7b-Instruct/tokenizer.bin</code>
int8 quantization
The (default) script <a>run.c</a>, above, uses a float32 forward pass, where the entire calculation of the forward pass is kept in fp32. This is very easy to understand as far as reference code goes, but it has the following downsides: the model checkpoint files are very large (it takes 4 bytes per every individual weight), and the forward pass is relatively slow. The (very) common inference optimization employed in practice is to quantize the model parameters to lower precision, giving up a little bit of correctness in return for smaller checkpoint sizes and faster forward passes (as most of the inference uses integer arithmetic). Empirically, LLMs can tolerate precisions as low as 4-bit (or even lower), but we use int8 here because it is a "safe" setting that gets us the benefits but doesn't sacrifice too much of the model accuracy. Only the weights that participate in matmuls are quantized. All the other parameters (e.g. especially the scale and bias in RMSNorm) are kept in float32, because these layers are very sensitive. Now, if all you're after is reduction in checkpoint sizes, you could quantize the weights, save the checkpoint, and then dequantize them in run.c, and do float32 inference as normal and call it a day. This is totally fine. But here, we go one step further (as is standard practice) and additionally quantize the activations in the forward pass. This requires us to dynamically quantize and dequantize between float32 and int8 at runtime, which adds overhead. But the benefit is that now the majority of the calculations (the matmuls especially!) are using pure integer arithmetic, where both weights and activations enter as int8. This is where the speedups can fundamentally come from. The version we use is the "Q8_0" quantization (llama.cpp terminology), where the 0 means that the weight quantization is symmetric around 0, quantizing to the range [-127, 127].
The quantized forward pass is implemented in <a>runq.c</a>. To use it, we have to export the model in the quantized format. For example, the float32 version of Llama 2 7B was exported as:
<code>python export.py llama2_7b.bin --meta-llama path/to/llama/model/7B</code>
This creates a 26GB file, because each one of 7B parameters is 4 bytes (fp32). To export it quantized, we instead use version 2 export:
<code>python export.py llama2_7b_q80.bin --version 2 --meta-llama path/to/llama/model/7B</code>
This runs for a few minutes, but now creates only a 6.7GB file. For exporting non-meta checkpoints you would use the --checkpoint arg instead of --meta-llama arg (more docs on this later, below). Now let's inference them. I like to use OMP here because these are big models, so e.g. on my Linux box:
<code>make runomp
OMP_NUM_THREADS=64 ./run llama2_7b.bin -n 40
OMP_NUM_THREADS=64 ./runq llama2_7b_q80.bin -n 40</code>
This runs 40 steps just to get a timing. The float32 version for me runs at 4.6 tok/s, and the int8 version at 14 tok/s. So we achieved a 3X speedup while reducing the checkpoint size by 4X. However, the forward pass is quantized to int8, and therefore silently very slightly lower quality.
huggingface models
We can load any huggingface models that use the Llama 2 architecture. See the script <a>export.py</a> and the <code>--hf</code> flag to export the model .bin file.
models
For the sake of examples of smaller, from-scratch models, I trained a small model series on TinyStories. All of these trained in a few hours on my training setup (4X A100 40GB GPUs). The 110M took around 24 hours. I am hosting them on huggingface hub <a>tinyllamas</a>, both in the original PyTorch .pt, and also in the llama2.c format .bin:
| model | dim | n_layers | n_heads | n_kv_heads | max context length | parameters | val loss | download
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 260K | 64 | 5 | 8 | 4 | 512 | 260K | 1.297 | <a>stories260K</a>
| OG | 288 | 6 | 6 | 6 | 256 | 15M | 1.072 | <a>stories15M.bin</a> |
| 42M| 512 | 8 | 8 | 8 | 1024 | 42M | 0.847 | <a>stories42M.bin</a> |
| 110M| 768 | 12 | 12 | 12 | 1024 | 110M | 0.760 | <a>stories110M.bin</a> |
You'll notice that the 110M model is equivalent to GPT-1 in size. Alternatively, this is also the smallest model in the GPT-2 series (<code>GPT-2 small</code>), except the max context length is only 1024 instead of 2048. The only notable changes from GPT-1/2 architecture is that Llama uses RoPE relatively positional embeddings instead of absolute/learned positional embeddings, a bit more fancy SwiGLU non-linearity in the MLP, RMSNorm instead of LayerNorm, bias=False on all Linear layers, and is optionally multiquery (but this is not yet supported in llama2.c).
training
Let's see how we can train a baby Llama 2 from scratch using the code in this repo. First let's download and pretokenize some source dataset, e.g. I like <a>TinyStories</a> so this is the only example currently available in this repo. But it should be very easy to add datasets, see the code.
<code>bash
python tinystories.py download
python tinystories.py pretokenize</code>
Then train our model:
<code>bash
python train.py</code>
<strong>brief training guide</strong>. See the train.py script for more exotic launches and hyperparameter overrides. Here is a brief guide to how to set the parameters. Look at the table at the very end of the <a>Chinchilla paper</a> to get a sense of how the Transformer parameters (dim, n_layers, n_heads) grow or shrink together. Extrapolate/interpolate this pattern to get bigger or smaller transformers. Set the max context length however you wish, depending on the problem: this should be the max number of tokens that matter to predict the next token. E.g. Llama 2 uses 2048. Next, you want the <em>total</em> batch size per update (printed by the script as "tokens per iteration will be:") to be somewhere around 100K tokens for medium-sized applications. For tiny applications it could be lower, for large training (e.g. GPTs/LLamas) it is usually ~0.5M, or even more. You get there by first maxing out the batch_size to whatever your system allows (e.g. mine was 16 in a recent run because after that my GPU runs out of memory), and then you want to increase gradient_accumulation_steps to be as high as necessary to reach the total batch size of ~100K. Finally, you want to tune your learning_rate (LR). You want this to be as high as your training allows. Very small networks can get away with a large LR (e.g. 1e-3 or even higher). Large networks need lower LRs. 3e-4 is a safe choice in most medium-sized applications, but can be too low for small networks, so try to increase it! Finally, max_iters is the length of training. Play with different settings. I mostly only ever tune these parameters and leave most of the others unchanged. Here is an example of how I trained the 110M model, which I don't think is anywhere near optimal, but looked sensible to me: dim 768, n_layers 12, n_heads 12 (so size of each head is 768 / 12 = 64 channels), seq len of 1024, batch size 16 (this is the most that fit my A100 40GB GPU), gradient_accumulation_steps = 8 was needed to get total tokens batch size to be 16 batch size * 1024 tokens in sequence * 8 grad_accum = 131,072 tokens per update. Good. Learning rate 4e-4 (probably a little too low). max_iters 200K (probably a bit too high). Dropout 0.1, as that usually helps a bit at medium size. That was it. I ran using Distributed Data Parallel (DDP) on 4 GPUs on my cloud machine, training took ~day or so.
Totally understand if you want to skip model training, for simple demo just download one of the pretrained models (see <a>models</a> section), e.g.:
<code>bash
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories15M.bin</code>
Once we have the model.bin file, we can inference in C. Compile the C code first:
<code>bash
make run</code>
You can now run it simply as
<code>bash
./run stories15M.bin</code>
Watch the tokens stream by, fun! We can also run the PyTorch inference script for a comparison. Download one of the models again from huggingface hub and point the <code>sample.py</code> script at it:
<code>bash
wget https://huggingface.co/karpathy/tinyllamas/resolve/main/stories15M.pt -P out15M
python sample.py --checkpoint=out15M/stories15M.pt</code>
Which gives the same results.
custom tokenizers
In everything above, we've assumed the custom Lllama 2 tokenizer with 32,000 tokens. However, in many boutique LLMs, using vocabulary this big might be an overkill. If you have a small application you have in mind, you might be much better off training your own tokenizers. This can make everything nicer - with smaller vocabs your model has fewer parameters (because the token embedding table is a lot smaller), the inference is faster (because there are fewer tokens to predict), and your average sequence length per example could also get smaller (because the compression is a lot more efficient on your data). So let's see how we train a custom tokenizer.
By default, to pretokenize the tinystories dataset we had to run, in order:
<code>python tinystories.py download
python tinystories.py pretokenize</code>
The <code>pretokenize</code> stage here loads the Llama 2 tokenizer (vocab size 32,000) and uses it to convert the downloaded text into integers, and saves that to file. We now change this as follows, to train an example 4096-token tokenizer:
<code>python tinystories.py download
python tinystories.py train_vocab --vocab_size=4096
python tinystories.py pretokenize --vocab_size=4096</code>
The <code>train_vocab</code> stage will call the <code>sentencepiece</code> library to train the tokenizer, storing it in a new file <code>data/tok4096.model</code>. I tried to reproduce as well as I could the settings that (I think) Meta used to train their vocabulary. This uses the Byte Pair Encoding algorithm that starts out with raw utf8 byte sequences of the text data and then iteratively merges the most common consecutive pairs of tokens to form the vocabulary. Inspect the <code>tinystories.py</code> file - the custom tokenizers are stored in a special directory structure indexed by the vocab size.
A quick note of interest is that vocab size of 4096 trained specifically on tinystories creates integer sequences with about the same sequence length per example as the default Llama 2 tokenizer of 32000 tokens! This means that our custom, tailored tokenizer is a lot better adapted to our specific text, and can compress it very effectively. So our trained models are smaller and faster.
Now that we have pretokenized the dataset with our custom tokenizer, we can train the model. The training script <code>train.py</code> doesn't care about the exact tokens, it only cares about the vocabulary size so it can correctly initialize the model. So when training your model, make sure to pass in
<code>python train.py --vocab_source=custom --vocab_size=4096</code>
(The defaults are <code>llama2</code> and <code>32000</code> respectively, which indicates the default Llama 2 tokenizer). This trains the model. Finally we are ready to run inference with our <code>run.c</code> script. For that we need two things. Number one, we have to export our tokenizer in the <code>.bin</code> format, do that with:
<code>python tokenizer.py --tokenizer-model=data/tok4096.model</code>
This writes the tokenizer to <code>data/tok4096.bin</code>. Now we can run inference, pointing it to this tokenizer using the <code>-z</code> flag:
<code>./run out/model.bin -z data/tok4096.bin</code>
This should print the samples. If you leave out the <code>-z</code> flag, it will use the default Llama 2 tokenizer, which would generate a good sequence of integers, but they would get translated using a different vocabulary to text, so it would look like gibberish.
performance
There are many ways to potentially speed up this code depending on your system. Have a look at the <a>Makefile</a>, which contains a lot of notes. The <code>make run</code> command currently uses the <code>-O3</code> optimization by default, i.e.:
<code>bash
gcc -O3 -o run run.c -lm</code>
-O3 includes optimizations that are expensive in terms of compile time and memory usage. Including vectorization, loop unrolling, and predicting branches.
To get a much better performance, try to compile with <code>make runfast</code>. This turns on the <code>-Ofast</code> flag, which includes additional optimizations that may break compliance with the C/IEEE specifications, in addition to <code>-O3</code>. See <a>the GCC docs</a> for more information.
Try <code>-march=native</code> to compile the program to use the architecture of the machine you're compiling on rather than a more generic CPU. This may enable additional optimizations and hardware-specific tuning such as improved vector instructions/width.
The fastest throughput I saw so far on my MacBook Air (M1) so far is with <code>make runfast</code>.
You can also experiment with replacing <code>gcc</code> with <code>clang</code>.
If compiling with gcc, try experimenting with <code>-funroll-all-loops</code>, see PR <a>#183</a>
<strong>OpenMP</strong>. Big improvements can also be achieved by compiling with OpenMP, which "activates" the <code>#pragma omp parallel for</code> inside the matmul and attention, allowing the work in the loops to be split up over multiple processors.
You'll need to install the OpenMP library and the clang compiler first (e.g. <code>apt install clang libomp-dev</code> on ubuntu). Then you can compile with <code>make runomp</code>, which does:
<code>bash
clang -Ofast -fopenmp -march=native run.c -lm -o run</code>
When you run inference make sure to use OpenMP flags to set the number of threads, e.g.:
<code>bash
OMP_NUM_THREADS=4 ./run out/model.bin</code>
Depending on your system resources you may want to tweak these hyperparameters and use more threads. But more is not always better, usually this is a bit U shaped. In particular, if your CPU has SMT (multithreading), try setting the number of threads to the number of physical cores rather than logical cores. The performance difference can be large due to cache thrashing and communication overhead. The PyTorch documentation <a>CPU specific optimizations
</a> has some good information that applies here too.
platforms
On <strong>Windows</strong>, use <code>build_msvc.bat</code> in a Visual Studio Command Prompt to build with msvc, or you can use <code>make win64</code> to use mingw compiler toolchain from linux or windows to build the windows target. MSVC build will automatically use openmp and max threads appropriate for your CPU unless you set <code>OMP_NUM_THREADS</code> env.
On <strong>Centos 7</strong>, <strong>Amazon Linux 2018</strong> use <code>rungnu</code> Makefile target: <code>make rungnu</code> or <code>make runompgnu</code> to use openmp.
On <strong>Mac</strong>, use clang from brew for openmp build. Install clang as <code>brew install llvm</code> and use the installed clang binary to compile with openmp: <code>make runomp CC=/opt/homebrew/opt/llvm/bin/clang</code>
tests
You can run tests simply with pytest:
<code>bash
$ pip install pytest
$ pytest</code>
This will currently invoke two tests inside <code>test_all.py</code>, which forward the model in both C and Python for 200 steps and check the output against a known good expected output. The tests currently run in only a few seconds, but will have to download and cache the stories260K models in a temporary <code>test</code> directory (only ~2MB download).
There are also some tests in C, in the file <a>test.c</a>. You can run these with <code>make testcc</code>, or to see more stuff printed:
<code>make testcc VERBOSITY=1</code>
Call for help: help add more tests.
ack
I trained the llama2.c storyteller models on a 4X A100 40GB box graciously provided by the excellent <a>Lambda labs</a>, thank you.
discord
Figured it's possible to reuse my existing discord channel (that I use for my <a>zero to hero youtube series</a>), see #llama2c channel on <a>discord</a>, for any quick questions, related discussions, etc.
contributing
A few words on this repo and the kinds of PRs that are likely to be accepted. What is the goal of this repo? Basically I think there will be a lot of interest in training or finetuning custom micro-LLMs (think ~100M - ~1B params, but let's say up to ~10B params) across a large diversity of applications, and deploying them in edge-adjacent environments (think MCUs, phones, web browsers, laptops, etc.). I'd like this repo to be the simplest, smallest, most hackable repo to support this workflow, both training and inference. In particular, this repo is not a complex framework with a 1000 knobs controlling inscrutible code across a nested directory structure of hundreds of files. Instead, I expect most applications will wish to create a fork of this repo and hack it to their specific needs and deployment platforms.
People who care about deployment efficiency above all else should look at <a>llama.cpp</a>. This repo still cares about efficiency, but not at the cost of simplicity, readability or portability. Basically, I expect that a lot of people come to this repo because the training code is 2 readable .py files and the inference code is 500 lines of C. So I'd like this to continue to be a kind of simplest "reference implementation" that can be easily hacked in a separate fork into whatever downstream application people are excited about. It shouldn't be full-featured. It shouldn't take 100 different options or settings. It shouldn't be the most efficient. A few examples:
<ul>
<li>someone re-ordered two loops to improve data locality for a small efficieny win => instant merge.</li>
<li>someone added the one line "pragma omp parallel for", which allows you to compile with OpenMP and dramatically speed up the code, or acts as just a comment if you don't compile it that way => instant merge.</li>
<li>bug fixes and touchups etc. => happy to merge</li>
</ul>
A few examples of PRs are that are not an excellent fit:
<ul>
<li>adding more than several #ifdefs all over the place in code. If they are localized / few, might be okay.</li>
<li>adding a lot of code that is very specific to some specific platform (e.g. MCUs, or some special version of linux or processor). These may be a better fit for forks of the project, and I am very happy to maintain a list of these forks in section below.</li>
<li>adding hundreds of lines of code to run.c that are only active in specific scenarios or platforms.</li>
</ul>
If your candidate PRs have elements of these it doesn't mean they won't get merged, it just means they will make it into the gray territory. TLDR: I am eager to merge any mostly small, mostly localized, broadly applicable, clean changes that improve the efficiency and portability of the repo, while keep its hackability and readability. I appreciate all PRs seeking to help me improve the project, thank you! <3.
notable forks
<ul>
<li>Rust</li>
<li><a>llama2.rs</a> by @<a>gaxler</a>: a Rust port of this project</li>
<li><a>llama2.rs</a> by @<a>leo-du</a>: A Rust port of this project</li>
<li><a>llama2-rs</a> by @<a>danielgrittner</a>: a Rust port of this project</li>
<li><a>llama2.rs</a> by @<a>lintian06</a>: A Rust port of this project</li>
<li><a>pecca.rs</a> by @<a>rahoua</a>: A Rust port leveraging <a>ndarray</a>, supports BLAS.</li>
<li><a>llama2.rs</a> by @<a>flaneur2020</a>: A Rust port of this project.</li>
<li>Go</li>
<li><a>go-llama2</a> by @<a>tmc</a>: a Go port of this project</li>
<li><a>llama2.go</a> by @<a>nikolaydubina</a>: a Go port of this project</li>
<li><a>llama2.go</a> by @<a>haormj</a>: a Go port of this project</li>
<li><a>llama2.go</a> by @<a>saracen</a>: a Go port of this project</li>
<li>Android</li>
<li><a>llama2.c-android</a>: by @<a>Manuel030</a>: adds Android binaries of this project</li>
<li><a>llama2.c-android-wrapper</a>: by @<a>celikin</a>: added JNI wrapper, PoC</li>
<li>C++</li>
<li><a>llama2.cpp</a> by @<a>leloykun</a>: a C++ port of this project</li>
<li>JavaScript</li>
<li><a>llama2.js</a> by @<a>epicure</a>: a JavaScript port of this project</li>
<li><a>llamajs</a> by @<a>agershun</a>: a JavaScript port of this project</li>
<li><a>llama2.ts</a> by @<a>oleksandr_now</a>: a TypeScript port of this project. Full Llama2-7B capable.</li>
<li><a>llama2.c-emscripten</a> by @<a>gohai</a>: Emscripten (JavaScript) port, based on @ggerganov's initial prototype</li>
<li>Zig</li>
<li><a>llama2.zig</a> by @<a>cgbur</a>: A Zig port of this project</li>
<li><a>llama2.zig</a> by @<a>vodkaslime</a>: a Zig port of this project</li>
<li><a>llama2.zig</a> by @<a>clebert</a>: a Zig port of this project</li>
<li>Julia</li>
<li><a>llama2.jl</a> by @<a>juvi21</a>: a Julia port of this project</li>
<li>Scala</li>
<li><a>llama2.scala</a> by @<a>jrudolph</a>: a Scala port of this project</li>
<li>Java</li>
<li><a>llama2.java</a> by @<a>mukel</a>: a Java port of this project</li>
<li>Kotlin</li>
<li><a>llama2.kt</a> by @<a>madroidmaq</a>: a Kotlin port of this project</li>
<li>Python</li>
<li><a>llama2.py</a> by @<a>tairov</a>: a simple one file pure Python port of this project with zero dependencies</li>
<li>C#</li>
<li><a>llama2.cs</a> by @<a>trrahul</a>: a C# port of this project</li>
<li>Dart</li>
<li><a>llama2.dart</a> by @<a>yiminghan</a>: one-file dart port of this project, works with Flutter!</li>
<li>Web</li>
<li><a>llama2c-web</a> by @<a>dmarcos</a>: Super simple way to build unmodified llama2.c to WASM and run it in the browser. <a>Demo</a></li>
<li>WebAssembly</li>
<li><a>icpp-llm</a>: LLMs for the Internet Computer</li>
<li>Fortran</li>
<li><a>llama2.f90</a>: a Fortran port of this project</li>
<li>Mojo</li>
<li><a>llama2.🔥</a> by @<a>tairov</a>: pure Mojo port of this project</li>
<li>OCaml</li>
<li><a>llama2.ml</a> by @<a>jackpeck</a>: an OCaml port of this project</li>
<li><a>llama2.c - Llama 2 Everywhere</a> by @<a>trholding</a>: Standalone, Bootable & Portable Binary Llama 2</li>
<li><a>llama2.c-zh - Bilingual Chinese and English</a> by @<a>chenyangMl</a>: Expand tokenizer to support training and inference in both Chinese and English</li>
</ul>
unsorted todos
<ul>
<li>add support in run.c of reading version 1+ files from export, later deprecate "version 0"</li>
<li>run.cu (CUDA) investigate and merge</li>
<li>add more tests inside <a>test.c</a></li>
<li>add Engine class for use in sample.py that does efficient inference in PyTorch, e.g. KV cache keeping</li>
<li>make it easier to add a new dataset with not too much pain</li>
<li>(LoRA) finetuning and export of Llama 2 models</li>
</ul>
License
MIT | [] |
https://avatars.githubusercontent.com/u/11492844?v=4 | wasmFITSIO | fjebaker/wasmFITSIO | 2023-04-18T15:52:19Z | Compiling CFITSIO for the browser. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/fjebaker/wasmFITSIO/tags | MIT | [
"astronomy",
"astrophysics",
"cfitsio",
"fits",
"wasm",
"zig"
] | 1,703 | false | 2024-01-12T11:49:06Z | true | false | unknown | github | [] | wasmFITSIO
Compiling <a>CFITSIO</a> for WASM with Zig.
Check out the up-to-date demo <a>here</a>. | [] |
https://avatars.githubusercontent.com/u/41441643?v=4 | codecrafters-bittorrent-zig | ImBIOS/codecrafters-bittorrent-zig | 2023-11-12T10:47:02Z | "Build Your Own BitTorrent" Challenge. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/ImBIOS/codecrafters-bittorrent-zig/tags | - | [
"bittorrent",
"zig",
"ziglang"
] | 6 | false | 2025-05-03T07:04:26Z | false | false | unknown | github | [] | <a></a>
This is a starting point for Zig solutions to the
<a>"Build Your Own BitTorrent" Challenge</a>.
In this challenge, you’ll build a BitTorrent client that's capable of parsing a
.torrent file and downloading a file from a peer. Along the way, we’ll learn
about how torrent files are structured, HTTP trackers, BitTorrent’s Peer
Protocol, pipelining and more.
<strong>Note</strong>: If you're viewing this repo on GitHub, head over to
<a>codecrafters.io</a> to try the challenge.
Passing the first stage
The entry point for your BitTorrent implementation is in <code>app/main.zig</code>. Study
and uncomment the relevant code, and push your changes to pass the first stage:
<code>sh
git add .
git commit -m "pass 1st stage" # any msg
git push origin master</code>
Time to move on to the next stage!
Stage 2 & beyond
Note: This section is for stages 2 and beyond.
<ol>
<li>Ensure you have <code>zig (0.11)</code> installed locally</li>
<li>Run <code>./your_bittorrent.sh</code> to run your program, which is implemented in
<code>app/main.zig</code>.</li>
<li>Commit your changes and run <code>git push origin master</code> to submit your solution
to CodeCrafters. Test output will be streamed to your terminal.</li>
</ol> | [] |
https://avatars.githubusercontent.com/u/70819762?v=4 | zurl | MidasVanVeen/zurl | 2023-04-21T14:40:08Z | like curl, but zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/MidasVanVeen/zurl/tags | - | [
"httpclient",
"networking",
"socket",
"zig"
] | 10 | false | 2023-08-27T06:30:59Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/463136?v=4 | advent-of-code | guidoschmidt/advent-of-code | 2023-12-08T08:50:10Z | 🎄🖤🦎 Advent of Code 2023/2024 using zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/guidoschmidt/advent-of-code/tags | - | [
"advent-of-code",
"advent-of-code-2023",
"advent-of-code-2023-zig",
"advent-of-code-2024",
"advent-of-code-2024-zig",
"zig"
] | 405 | false | 2025-03-30T01:01:30Z | true | true | unknown | github | [] | Advent Of Code 🎄 <a>zig</a> solutions
<ol>
<li>Install <a>zig</a> (<a>.zigversion</a>), preferably using <a>zvm</a></li>
<li>Run <code>zig build run</code> to select a specific day</li>
<li>Run <code>zig build run -- DAY</code>, e.g. <code>zig build run -- 9</code> to run a specific day </li>
</ol>
AOC_COOKIE
To obtain the puzzle inputs, you need to set the environment variable
<code>ACO_COOKIE</code> to the session cookie value from adventofcode.com:
fish shell:
<code>fish
set -Ux AOC_COOKIE session=XXX...</code>
Powershell:
```pwsh
```
@TODO
<ul>
<li>Use <a>terminal grahpics
protocol</a> via
<a>libvaxis</a></li>
<li>Implement common re-usable data structures (e.g. 2D map, graph, etc.) and
algorithms (e.g. depth-first search, dijkstra/A* shortest-path like algorithms
etc.)</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/2445604?v=4 | learn-zig | daggerok/learn-zig | 2024-02-07T02:59:44Z | Zig | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/daggerok/learn-zig/tags | MIT | [
"zig",
"zig-github-actions"
] | 27 | false | 2025-01-23T11:04:56Z | false | false | unknown | github | [] | learn-zig <a></a>
Learn zig programming language
getting started
install <a>zig-macos-aarch64-0.14.0-dev.2851+b074fb7dd</a> version
<code>bash
test ! -d ~/.dev/zig || mv -fv ~/.dev/zig ~/.dev/zig-$(date +%Y-%m-%d-%H-%M-%S)
mkdir -pv ~/.dev/zig
export ZIG_URL="https://ziglang.org/builds/zig-macos-aarch64-0.14.0-dev.2851+b074fb7dd.tar.xz"
curl -LSs "$ZIG_URL" | tar -xJ -C ~/.dev/zig --strip-components=1</code>
init project:
<code>bash
mkdir my-zig-project
cd my-zig-project
zig init</code>
testing:
```bash
zig test src/main.zig
zig test src/root.zig
or simply
zig build test
```
build and run:
<code>bash
zig build # or: zig build --summary all
❯ ./zig-out/bin/*</code> | [] |
https://avatars.githubusercontent.com/u/50797868?v=4 | evio-lite.zig | maolonglong/evio-lite.zig | 2023-11-02T04:55:00Z | Zig port of evio-lite (fast event-loop networking for Zig) | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/maolonglong/evio-lite.zig/tags | MIT | [
"epoll",
"kqueue",
"networking",
"zig"
] | 4 | false | 2023-11-03T02:01:26Z | true | false | unknown | github | [] | evio-lite
<code>evio-lite</code> is an event loop networking framework that is extra small and fast. It's the lite version of the <a>evio</a> package. | [] |
https://avatars.githubusercontent.com/u/145401770?v=4 | litha | wintermarstice-labratory/litha | 2023-06-19T06:21:42Z | [WIP] A library for machine learning, neural networks, artificial intelligence and deep learning – in Zig. | main | 41 | 1 | 0 | 1 | https://api.github.com/repos/wintermarstice-labratory/litha/tags | MIT | [
"artificial-intelligence",
"deep-learning",
"machine-learning",
"neural-network",
"open-source",
"zig"
] | 19 | false | 2024-04-14T20:46:09Z | true | false | unknown | github | [] |
Litha
<blockquote>
<em>Important!</em> This library is still under construction, so it might not be suitable for production use cases just yet. However, your contributions and feedback can help us expedite its readiness for broader usage. This README describes what Litha will become when it is ready. As of now, <strong>features are not implemented yet</strong>.
</blockquote>
Litha is a powerful library designed to cater to machine learning, neural networks, artificial intelligence, and deep learning operations in the Zig programming language.
Why Litha?
It's true that there are many mature and well-supported AI/ML/DL libraries in the programming world. Litha, however, comes with its unique benefits that make it worth considering for your machine learning projects:
1. Self Contained
Litha aims to be a fully self-contained library for machine learning in Zig. This means it brings everything you need to build, train, and deploy machine learning models without requiring numerous dependencies or additional libraries. With Litha, you get all the tools you need in a single, unified package, making your machine learning projects easier to manage and maintain.
2. Compile Time Abilities
One of the unique features of Litha, empowered by the capabilities of Zig, is its extensive use of compile-time abilities. These abilities can be leveraged to optimize machine learning models, tune performance critical parameters, and perform sophisticated type-level computations, all at compile-time.
This can lead to highly efficient code execution and performance improvements, as a lot of decisions are made at compile-time rather than at run-time. This also contributes to the predictability and robustness of the models built with Litha, as potential issues can be caught at compile-time, reducing the likelihood of run-time errors.
3. Value Through Convenience
Litha is not just a general machine learning library, it is also a toolbox for training and deploying models. With Zig's build system, Litha can do a slew of neat tricks:
- Embed an already existing model into executable (or a library), ready to be used at run-time, just like a dependency.
- Generate code for the model for training and inference. Train a model with a single build step (<code>zig build train</code>)
4. API Inclusivity and Flexibility
In contrast to many machine learning libraries that heavily depend on CUDA and therefore NVIDIA hardware, Litha embraces an inclusive and flexible approach to APIs. While Litha does support CUDA when it's available, it also provides compatibility with a wide variety of open APIs such as Vulkan and OpenCL, as well as proprietary APIs like DirectX and Metal. This means you can run Litha on almost any hardware, whether it's a GPU or just a CPU.
This inclusive approach eliminates the limitations and vendor lock-ins associated with being tied to a specific hardware or API. With Litha, you have the freedom to use the resources that are available to you, and the flexibility to switch between different APIs as needed.
By choosing Litha, you are opting for a machine learning library that values flexibility, inclusivity, and your freedom to choose. Whether you're developing on a high-end machine with the latest GPU or on a less powerful device with CPU-only, Litha has you covered.
Why Zig?
Zig is an emerging language that is designed to be simple, reliable, and efficient, filling a unique niche in the programming world. Here's why we chose Zig for the Litha library:
1. Simplicity and Readability
Zig aims to be simple and straightforward. There are no hidden behaviors or complex abstractions. This means the code you write is the code that gets executed, leading to highly predictable and easy-to-debug programs.
2. Performance
Zig enables low-level programming without losing high-level convenience. It provides manual memory management and other low-level features, making it possible to write extremely efficient code.
3. Control
Zig offers robust control over system resources, allowing direct management of memory allocation and hardware. It also supports compiling to C, enabling interoperability with a vast number of existing libraries.
4. Safety
While Zig gives you a lot of power, it also encourages writing safe code. It has built-in features to handle errors explicitly and avoid undefined behavior.
5. Community
The Zig community is vibrant and growing. This provides a pool of shared knowledge and resources for developers working in Zig.
In summary, Zig’s blend of simplicity, efficiency, control, safety, and community makes it a great fit for Litha. We believe that Zig's philosophy aligns with our goals to provide a simple, efficient, and powerful library for machine learning and AI.
The "official" IRC channel is #litha on Libera.Chat.
License
The primary mission of Litha, like the Zig project, is to serve users. This doesn't only mean the developers who use Litha to build machine learning and AI models, but more importantly, the end-users who benefit from the applications created using this library.
Our aim is for Litha to be a tool that empowers end-users, not to exploit them financially or restrict their freedom to interact with hardware or software in any way.
We firmly believe in fostering a culture of open-source collaboration and sharing. However, setting up social norms around these values tends to be a more effective way to ensure their adherence than complicating software licenses. As such, complicating the software license of Litha could potentially jeopardize the value it brings to its users.
Therefore, Litha is released under the MIT (Expat) License, coupled with a simple request: use it to improve how software caters to the needs of end-users. | [] |
https://avatars.githubusercontent.com/u/139293750?v=4 | eruzero | bogwi/eruzero | 2023-08-05T00:27:38Z | Bullet-Train fast hashmap for Zig | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/bogwi/eruzero/tags | MIT | [
"benchmark",
"data-structures",
"hashmap",
"hashtable",
"zig",
"zig-package",
"ziglang"
] | 41 | false | 2024-06-20T09:31:10Z | true | true | unknown | github | [] | eruZero
Bullet-Train fast hashmap for Zig.
eruZero aims to be a replacement for Zig's standard HashMap.
The motivation was to create a simple and fast map based on an implicit data structure that works well with any key out of the box, without providing context or a custom hasher. The only exceptions are .Float and untagged .Union types. <em>(Floats can be hashed, though. A convenient and fast key wrapper that breaks the float on integer and memo parts with controlled precision is present in the tests part of the code.)</em>
eruZero supports the main std/HashMap API. New features are dedicated update to an existing value, scaling down the underlying memory when no longer needed, basic operations on sets, and automatic tombstone cleanup, making the map very resistant to the problem.
Include in your project
for <code>build.zig.zon</code>
```zig
.{
.name = "name_of_your_package",
.version = "version_of_your_package",
.dependencies = .{
.eruZero = .{
.url = "https://github.com/bogwi/eruzero/archive/master.tar.gz",
.hash = "1220dbe03c05ad89578e952Ed3f2ff1fa611495f770773c711979ac00e48fd2825e9",
},
},
}
<code>``
If the hash has changed, you will get a gentle</code>error: hash mismatch<code>where in the field</code>found:` ZIG brings you the correct value.
for <code>build.zig</code>
<code>zig
const eruZero = b.dependency("eruZero", .{});
exe.addModule("eruZero", eruZero.module("eruZero"));</code>
Bench
Benchmark is inspired by https://github.com/xacrimon/dashmap, which has its benchmark ported of the libcuckoo benchmark.
There are four tests in total:
<strong>RH: READ HEAVY</strong>\
[read 98, insert 1, remove 1, update 0 ]\
Models caching of data in places such as web servers and disk page caches.
<strong>EX: EXCHANGE</strong>\
[read 10, insert 40, remove 40, update 10]\
Replicates a scenario where the map is used to exchange data.
<strong>EXH: EXCHANGE HEAVY</strong>\
[read 1, insert 98, remove 98, update 1]\
This test is an inverse of <em>RH</em> test. Hard for any map.
<strong>RG: RAPID GROW</strong>\
[read 5, insert 80, remove 5, update 10]\
A scenario where the map is used to collect large amounts of data in a short burst.
All tests except <em>RG</em> are designed to keep the map small. The keys are rotated, so the tests are tombstone-heavy. Especially the <em>EXH</em> test. At the end of the test, on the default 1M ops, the map has wrenched with 980k tombstones under the size of only 1!
Benchmark against ZIG's both HashMap and ArrayHashMap can be called in the command line via
<code>zig build bench</code>
The default test runs on one million ops. You can run it with any number of operations; append the number as <code>zig build bench -- 12345678</code>. It is okay to format the number as 12_345_678 with an underscore. Unintentionally, we can make the number too large, which may not be what we want.
Performance and stats
For each card, the tests are run as four independent loops of 100 ops each until the specified cap is reached. The results are interesting. Sure, a map like eruZero, which does not let deleted items accumulate, will have a huge advantage over the one without such a heuristic. Also, it seems that building a hashmap backed by an underlying ArrayList is much more effective than talking directly to the allocator, at least in Zig's universe. Further discussion is needed.
We did this on u64 keys, wyhash for both maps, gpa allocator, ReleaseFast mode, and Apple M1 laptop. If you have built a hashmap that supports Zig's std:HashMap API and would like to see it included in the benchmark, drop us a line. You are very welcome.
<em>Tp</em>: Throughput: millions of operations per second.\
<em>Rt</em>: Runtime : time spent on the test, in seconds.\
<em>aggregate</em>: This is an absolute measurement of an individual hashmap's <em>throughput</em> (total number of ops the map has engaged through the four tests in a row divided by the combined <em>runtime</em>) contrary to single tests measuring relative performances.
```
HASHMAP BENCHMARK|
1_000_000 ops:each test|
|name |Tp Mops:sec| Rt :sec|
=====================================
|eruZero |
|RH | 251.46| 0.003977|
|EX | 63.16| 0.015832|
|EXH | 64.25| 0.015563|
|RG | 47.46| 0.021070|
|aggregate | 70.87| 0.056442|
|ArrayHashMap |
|RH | 139.60| 0.007163|
|EX | 81.52| 0.012268|
|EXH | 81.63| 0.012250|
|RG | 24.66| 0.040544|
|aggregate | 55.38| 0.072225|
|HashMap |
|RH | 62.65| 0.015961|
|EX | 13.04| 0.076673|
|EXH | 8.28| 0.120821|
|RG | 57.06| 0.017524|
|aggregate | 17.32| 0.230980|
<code> HASHMAP BENCHMARK|
10_000_000 ops:each test|
</code>
|name |Tp Mops:sec| Rt :sec|
=====================================
|eruZero |
|RH | 256.21| 0.039030|
|EX | 62.19| 0.160800|
|EXH | 59.97| 0.166756|
|RG | 36.06| 0.277308|
|aggregate | 62.12| 0.643895|
|ArrayHashMap |
|RH | 141.78| 0.070530|
|EX | 84.29| 0.118637|
|EXH | 83.80| 0.119330|
|RG | 17.61| 0.567956|
|aggregate | 45.64| 0.876454|
|HashMap |
|RH | 64.22| 0.155703|
|EX | 13.20| 0.757729|
|EXH | 8.34| 1.199348|
|RG | 36.86| 0.271328|
|aggregate | 16.78| 2.384107|
<code> HASHMAP BENCHMARK|
100_000_000 ops:each test|
</code>
|name |Tp Mops:sec| Rt :sec|
=====================================
|eruZero |
|RH | 258.13| 0.387407|
|EX | 65.79| 1.520057|
|EXH | 62.78| 1.592761|
|RG | 26.91| 3.715796|
|aggregate | 55.43| 7.216020|
|ArrayHashMap |
|RH | 144.43| 0.692390|
|EX | 86.05| 1.162134|
|EXH | 84.47| 1.183876|
|RG | 17.79| 5.621304|
|aggregate | 46.19| 8.659705|
|HashMap |
|RH | 64.08| 1.560445|
|EX | 13.21| 7.567642|
|EXH | 8.34| 11.988912|
|RG | 25.86| 3.867002|
|aggregate | 16.01| 24.984001|
```
Conclusions
Based on the above data, if you are building an application that is <em>READ HEAVY</em>, consider using the eruZero map, which is specifically designed for static reading with occasional removals. If you are building an application similar to the <em>EXCHANGE</em> test, consider using ArrayHashMap, which has excellent removal performance and almost instant iteration over the entire map (not tested here). Zig's HashMap is great for growing and reading small volumes under 1M entries. In general, eruZero completed four tests in the least amount of time.
If you do not want external dependencies, you should still consider using Zig's excellent ArrayHashMap in your projects, which is an overall better alternative to Zig's HashMap. ArrayHashMap is somewhat underestimated in Zig's community (as it seems, scavenging the GitHub data) because it grows slower than std:HashMap and because of popular synthetic tests, usually consisting of <em>grow-clear-put_again-get-iterate-remove</em> sequence or similar, used to benchmark hashmaps. And somehow it got into people's heads that the map that runs the sequence faster is better. In fact, the ArrayHashMap will not come out on top in such synthetic tests. However, tests that do not measure the hashmap's performance by the number of deleted entries it holds at runtime cannot tell the whole truth. | [] |
https://avatars.githubusercontent.com/u/43012445?v=4 | pixel-edit | cowboy8625/pixel-edit | 2024-01-09T02:24:49Z | a simple pixel editor | master | 6 | 1 | 0 | 1 | https://api.github.com/repos/cowboy8625/pixel-edit/tags | MIT | [
"pixel-editor",
"zig"
] | 276 | false | 2024-12-19T19:45:05Z | true | true | unknown | github | [
{
"commit": "2176d37bcc83af8acdabf4f8ce51fd93060f15b2.tar.gz",
"name": "raylib-zig",
"tar_url": "https://github.com/Not-Nik/raylib-zig/archive/2176d37bcc83af8acdabf4f8ce51fd93060f15b2.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/Not-Nik/raylib-zig"
}
] | Pixel Edit
Building
<ul>
<li>built with version <code>0.13.0</code></li>
</ul>
<code>shell
git clone https://github.com/cowboy8625/pixel-edit &&
cd pixel-edit &&
zig build run</code>
TODO
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Animations - display each frame as the exported image would be displayed
UI
<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> World UI scaling with camera
<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> Ui implementation for buttons on a grid.
<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> some how highlight the selected tool in use
File Manager
<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> Back button to move up a folder <code>../</code> at the top of the list
<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> sort list to have folders at the top and files at the bottom
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Create Folder button
<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> If file name is to long chop it and add ...
Text Input
<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> TextInput add cursor movement with arrow keys
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> move left and right in text input with cursor
TOOLS
<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> Brush size
<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> custom brushs
<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> custom and saveable color palette (save to a json file)
WIDNOWS
file manager doesnt work | [] |
https://avatars.githubusercontent.com/u/337093?v=4 | convert2i420 | tetsu-koba/convert2i420 | 2023-04-26T06:08:47Z | Utilities written in Zig to convert camera output to i420 video format | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/tetsu-koba/convert2i420/tags | - | [
"v4l2",
"video-streaming",
"zig"
] | 27 | false | 2024-05-18T05:48:57Z | true | false | unknown | github | [] | Video format converter to I420
Utilities written in Zig to convert camera output to I420 video format.
I420 is Planar YUV 4:2:0.
Supported input video format
<ul>
<li>YUYV (YUYV 4:2:2)</li>
<li>NV12 (Y/CbCr 4:2:0)</li>
<li>I422 (Planar YUV 4:2:2)</li>
</ul>
Caveat
This is optimized for a video stream from a video camera.
Video width and height must be an even number. Each line has no padding.
How to use
See test files.
Example
```
!/bin/sh -eux
WIDTH=320
HEIGHT=240
FRAMERATE=15
v4l2capture /dev/video0 /dev/stdout $WIDTH $HEIGHT $FRAMERATE YUYV | \
convert2i420 /dev/stdin /dev/stdout $WIDTH $HEIGHT YUYV | \
ffplay -f rawvideo -pixel_format yuv420p -video_size ${WIDTH}x${HEIGHT} /dev/stdin
```
ToDo
Make this into a package when the official zig package manager is released. | [] |
https://avatars.githubusercontent.com/u/435029?v=4 | zig-js | footearth/zig-js | 2023-08-28T19:09:12Z | Access the JS host environment from Zig compiled to WebAssembly. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/footearth/zig-js/tags | MIT | [
"zig",
"zig-library",
"zig-package"
] | 223 | true | 2023-08-28T20:10:05Z | true | false | unknown | github | [] | zig-js
zig-js is a Zig library (and accompanying JS glue) that enables Zig
running in a WebAssembly environment to interact with a JavaScript-based
host.
Note this makes it particularly easy for Zig to call into JS. This
doesn't help for JS calling into Zig. This is more akin to Go's
<code>syscall/js</code> package and not like Rust's <code>wasm-bindgen</code>.
Note: the main branch of this repository attempts to remain compatible
with the latest nightly release of Zig, and therefore may not be compatible
with official Zig releases.
Example
```zig
// Get and set objects and properties
const document = try js.global.get(js.Object, "document");
defer document.deinit();
const title = try document.getAlloc(js.String, alloc, "title");
defer alloc.free(title);
std.log.info("the title is: {s}", .{str});
try document.set("title", js.string("A new title."));
// Call functions
js.global.call(void, "alert", .{js.string("Hello from Zig!")});
```
The code is a bit verbose with the error handling but since JS is a
dynamic language there are potential invalid types at every step of the
way. Additionally, <code>deinit</code> calls are necessary to dereference garbage-collected
values on the host side.
Under the covers, this is hiding a lot of complexity since the JS/WASM
ABI only allows passing numeric types and sharing memory.
Usage
To use this library, you must integrate a component in both the Zig
and JS environment. For Zig, vendor this repository and add the package.
For example in your build.zig:
```zig
const js = @import("zig-js");
pub fn build(b: *std.build.Builder) !void {
// ... other stuff
exe.addPackage(js.pkg);
}
```
From JS, install and import the package in the <code>js/</code> directory (in the future
this will be published to npm). A TypeScript example is shown below but
JS could just as easily be used:
```typescript
import { ZigJS } from 'zig-js-glue';
// Initialize the stateful zigjs class. You should use one per wasm instance.
const zigjs = new ZigJS();
fetch('my-wasm-file.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
// When creating your Wasm instance, pass along the zigjs import
// object. You can merge this import object with your own since zigjs
// uses its own namespace.
WebAssembly.instantiate(bytes, zigjs.importObject())
).then(results => {
const { memory, my_func } = results.instance.exports;
// Set the memory since zigjs interfaces with memory.
zigjs.memory = memory;
// Run any of your exported functions!
my_func();
});
```
<strong>WARNING:</strong> The zig-js version used in your Zig code and JS code must match.
I'm not promising any protocol stability right now so pin your versions
appropriately. To determine what version is compatible, look up the tagged
version in this repository and the corresponding commits.
Internals
The fundamental idea in this is based on the Go
<a>syscall/js</a> package. The implementation
is relatively diverged since Zig doesn't have a runtime or garbage collection,
but the fundamental idea of sharing "refs" and the format of those refs is
based on Go's implementation.
The main idea is that Zig communicates to JS what values it would like
to request, such as the "global" object. JS generates a "ref" for this
object (a unique 64-bit numeric value) and sends that to Zig. This ref now
uniquely identifies the value for future calls such as "give me the
'document' property on this ref."
The ref itself is a 64-bit value. For numeric types, the ref <em>is</em> the
value. We take advantage of the fact that all numbers in JavaScript are
IEEE 754 encoded 64-bit floats and use NaN as a way to send non-numeric values
to Zig (NaN-boxing).
NaN in IEEE 754 encoding is <code>0111_1111_1111_<anything but all 0s></code> in binary.
We use a common NaN value of <code>0111_1111_1111_1000_0000...</code> so that we can use
the bottom (least-significant) 49 bits to store type information and
a 32-bit ID.
The 32-bit ID is just an index into an array on the JS side. A simple scheme
is used to reuse IDs after they're dereferenced.
Performance
Usage of this package causes the WASM/JS boundary to be crossed a LOT
and this is generally not very fast and not an optimal way to use wasm.
The optimal way to use WASM is more like a GPU: have the host (or wasm
module) preload a bunch of work into a byte buffer and send it over
in one single call. However, this approach is pretty painful.
This packge makes interfacing with JS very, very easy. Consider the
tradeoffs and choose what is best for you. | [] |
https://avatars.githubusercontent.com/u/3904240?v=4 | melo | almmiko/melo | 2023-09-27T10:17:36Z | Experimental JavaScript runtime | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/almmiko/melo/tags | - | [
"javascript",
"melo",
"zig"
] | 10 | false | 2023-11-01T19:07:36Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/98668553?v=4 | ZigThreeFingerDrag | EsportToys/ZigThreeFingerDrag | 2023-10-26T12:07:11Z | Enable three-finger drag for Precision Touchapds on Windows. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/EsportToys/ZigThreeFingerDrag/tags | GPL-3.0 | [
"precision-touchpad",
"rawinput",
"sendinput",
"three-finger-drag",
"windows",
"zig"
] | 32 | false | 2024-08-17T17:21:00Z | true | false | unknown | github | [] | ZigThreeFingerDrag
A rewrite of my <a>PrecisionThreeFingerDrag</a> AutoIt script in Zig. | [] |
https://avatars.githubusercontent.com/u/3759175?v=4 | fmtbuf | Hejsil/fmtbuf | 2023-02-28T15:15:55Z | Buffered formatting that figures out the buffer size for you | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/Hejsil/fmtbuf/tags | MIT | [
"buffer",
"formatting",
"zig",
"zig-lib",
"zig-library",
"zig-package"
] | 8 | false | 2024-09-13T12:23:30Z | true | false | unknown | github | [] |
fmtbuf
An alternative to <code>std.fmt.bufPrintZ</code> which can:
<ul>
<li>Automatically figure out the buffer size at compile time</li>
<li>Can be partially formatted, allowing for a prefix to be formatted and reused.</li>
</ul>
```zig
const FmtBuf = @import("fmtbuf").FmtBuf;
const std = @import("std");
test {
var buf = FmtBuf("[{}] = {}", std.meta.Tuple(&.{ usize, u8 })){};
try std.testing.expectEqualStrings("[0] = 0", buf.format(.{ 0, 0 }));
try std.testing.expectEqualStrings("[12] = 3", buf.format(.{ 12, 3 }));
<code>var partial = buf.partialFormat(1, .{500});
try std.testing.expectEqualStrings("[500] = 0", partial.format(.{0}));
try std.testing.expectEqualStrings("[500] = 1", partial.format(.{1}));
try std.testing.expectEqualStrings("[500] = 2", partial.format(.{2}));
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/1563110?v=4 | zig-simple-router | gabstv/zig-simple-router | 2023-08-24T22:06:06Z | A simple generic router for Zig | main | 0 | 1 | 1 | 1 | https://api.github.com/repos/gabstv/zig-simple-router/tags | MIT | [
"http",
"router",
"zap",
"zig"
] | 34 | false | 2024-11-25T14:48:03Z | true | true | unknown | github | [] | Simple Router
Grug wants simple router that works well with <a>Zap</a>.
Grug will probably deprecate this once Zap gets an official router implementation.
```zig
const std = @import("std");
const zap = @import("zap");
const router = @import("router");
fn dispatch_routes(r: zap.SimpleRequest) void {
// dispatch
if (r.path) |the_path| {
var p = routes.get(the_path) catch unreachable;
if (p) |*match| {
defer match.deinit();
if (match.item != null) {
std.debug.print("route {s}\n", .{match.path() catch unreachable});
match.item.?(r);
return;
}
std.debug.print("route '{s}' has nil handler", .{match.path() catch unreachable});
}
}
// or default: present menu
r.sendBody(
\
\
\
<a>static</a>
\
<a>dynamic</a>
\
<a>very dynamic</a>
\
<a>very dynamic</a>
\
\
) catch return;
}
fn static_site(r: zap.SimpleRequest) void {
r.sendBody("
Hello from STATIC ZAP!") catch return;
}
var dynamic_counter: i32 = 0;
fn dynamic_site(r: zap.SimpleRequest) void {
dynamic_counter += 1;
var buf: [128]u8 = undefined;
const filled_buf = std.fmt.bufPrintZ(
&buf,
"
Hello # {d} from DYNAMIC ZAP!!!",
.{dynamic_counter},
) catch "ERROR";
r.sendBody(filled_buf) catch return;
}
fn setup_routes(a: std.mem.Allocator) !void {
routes = router.Router(zap.SimpleHttpRequestFn).init(a);
try routes.put("/static", static_site);
try routes.put("/dynamic", dynamic_site);
try routes.put("/dynamic/:very_dynamic", dynamic_site);
}
var routes: router.Router(zap.SimpleHttpRequestFn) = undefined;
pub fn main() !void {
try setup_routes(std.heap.page_allocator);
var listener = zap.SimpleHttpListener.init(.{
.port = 3000,
.on_request = dispatch_routes,
.log = true,
});
try listener.listen();
<code>std.debug.print("Listening on 0.0.0.0:3000\n", .{});
zap.start(.{
.threads = 2,
.workers = 2,
});
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/17755880?v=4 | rp2040.zig | rjsberry/rp2040.zig | 2023-10-12T17:39:54Z | Startup and basic peripheral access for the RP2040 MCU in Zig. | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/rjsberry/rp2040.zig/tags | 0BSD | [
"embedded",
"example",
"quickstart",
"raspberry-pi-pico",
"rp2040",
"zig"
] | 6 | false | 2024-06-25T20:16:00Z | true | true | unknown | github | [
{
"commit": "db538e12b6dea9f22a6f711543a8a1eb765d1870.tar.gz",
"name": "cortex_m",
"tar_url": "https://github.com/rjsberry/cortex_m.zig/archive/db538e12b6dea9f22a6f711543a8a1eb765d1870.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/rjsberry/cortex_m.zig"
}
] | <em>rp2040.zig</em>
Startup and basic peripheral access for the RP2040 MCU in Zig.
License
If you use the <code>rp2040_startup</code> module a pre-compiled second stage bootloader
is embedded into your firmware. This is licensed under the 3BSD license. For
more info see <a>startup/bin</a>.
All other files are dual licensed under the 0BSD and MIT licenses. | [] |
https://avatars.githubusercontent.com/u/135145066?v=4 | bktree | dying-will-bullet/bktree | 2023-07-19T13:46:10Z | BK-Tree for Zig. | master | 1 | 1 | 2 | 1 | https://api.github.com/repos/dying-will-bullet/bktree/tags | - | [
"bktree",
"close-matches",
"hamming-distance",
"levenshtein-distance",
"spellcheck",
"zig",
"ziglang"
] | 13 | false | 2024-10-25T08:40:31Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "deque",
"tar_url": "https://github.com/Hanaasagi/zig-deque/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/Hanaasagi/zig-deque"
}
] | BK-tree
<a></a>
Implementing a Brukhard Keller tree data structure that allows for querying of "close" matches on discrete distances.
Feature
<ul>
<li><code>HammingDistance</code>: int type and unicode bytes.</li>
<li><code>LevenshteinDistance</code>: unicode bytes.</li>
</ul>
Example
```zig
const std = @import("std");
const bktree = @import("bktree");
pub fn main() !void {
const allocator = std.heap.page_allocator;
<code>var tree = bktree.BkTree([]const u8, bktree.LevenshteinDistance([]const u8)).init(allocator);
defer tree.deinit();
// word list
const words = &[_][]const u8{
"isValid",
"isInvalid",
"valid",
"invalid",
"validated",
};
// insert to the BK-Tree
try tree.insertSlice(words);
// A list of words with two edit distances from "inInvald".
var it = try tree.find("inInvald", 2);
std.debug.print("Found misspell word '{s}'.\n", .{"inInvald"});
// iterate results
while (try it.next()) |match| {
// match[0] is the pointer of value.
// match[1] is the edit distances
std.debug.print("Did you mean '{s}'?\n", .{match[0].*});
}
</code>
}
```
LICENSE
MIT | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | Zig-DeepHashMap | bcrist/Zig-DeepHashMap | 2023-10-28T04:43:58Z | Zig std.HashMaps with deep keys | main | 0 | 1 | 0 | 1 | https://api.github.com/repos/bcrist/Zig-DeepHashMap/tags | MIT | [
"hashmap",
"utilities",
"utility-library",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 6 | false | 2025-02-14T02:02:27Z | true | true | 0.14.0-dev.3217+5b9b5e45c | github | [] | Zig-DeepHashMap
Provides versions of <code>AutoHashMap</code>, etc. that follow pointers when hashing and comparing. | [
"https://github.com/bcrist/zbox"
] |
https://avatars.githubusercontent.com/u/8464038?v=4 | zig-raylib-template | ezekielbaniaga/zig-raylib-template | 2023-09-05T11:35:05Z | This represents a straightforward application of the raylib library in Zig version 0.11.0. | master | 0 | 1 | 0 | 1 | https://api.github.com/repos/ezekielbaniaga/zig-raylib-template/tags | NOASSERTION | [
"zig",
"ziglang"
] | 611 | false | 2024-09-27T16:21:10Z | true | false | unknown | github | [] |
A simple <a>zig</a> + <a>raylib</a> template
This represents a straightforward application of the raylib library in Zig version 0.11.0.
Quick GIT Note: The libraries included here are cloned using git submodule, which means that when you clone this project, you won't receive the latest version of raylib. This is due to submodules being linked to specific commit IDs.
What about raygui?
Absolutely! raygui has also been included as a submodule. With any luck, I'll find the time to implement it in this template as well.
Thanks to <a>Codotaku</a>'s YouTube Channel for showing how it's done.
| [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.