avatar_url
stringlengths 46
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 45
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 0
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 60
values | repo_from
stringclasses 3
values | dependencies
listlengths 0
121
| readme_content
stringlengths 0
437k
| dependents
listlengths 0
21
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://avatars.githubusercontent.com/u/15308111?v=4 | arocc | Vexu/arocc | 2021-02-25T10:26:10Z | A modern fully featured C compiler. | master | 45 | 1,351 | 59 | 1,351 | https://api.github.com/repos/Vexu/arocc/tags | MIT | [
"c",
"compiler",
"zig"
]
| 5,685 | false | 2025-05-22T07:04:27Z | true | true | 0.15.0-dev.460+f4e9846bc | github | []
|
Aro
A C compiler with the goal of providing fast compilation and low memory usage with good diagnostics.
The project intends to support standard C and all common extensions:
| Version | status |
| ---------------- | ---------------------------------------------------------------------------------------------------------- |
| C23 | Complete excluding <a>Add IEEE 754 interchange and extended types</a> |
| C17 | Complete excluding warnings <a>Ensure C1/ compatibility</a> |
| C11 | Complete excluding warnings <a>Ensure C11 compatibility</a> |
| C99 | Complete excluding warnings <a>Ensure C99 compatibility</a> |
| C95 | Complete |
| C89 | Complete |
| GNU extensions | <a>Ensure GNU C extension compatibility</a> |
| Clang extensions | <a> Ensure Clang C extension compatibility</a> |
Aro will be used as the C frontend for <a>C to Zig translation</a> in the Zig toolchain.
Codegen
Earlier there was a proof of concept backend capable of producing a valid hello world binary
but it was removed to make way for a new more capable backend which is still under construction.
The new backend will reuse parts of the self-hosted Zig compiler.
<a>#542</a>
Using aro as a module
The following assumes that your package has a <code>build.zig.zon</code> file.
<code>sh-session
zig fetch --save git+https://github.com/Vexu/arocc.git</code>
Add the following to your <code>build.zig</code>:
```zig
const aro = b.dependency("aro", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("aro", aro.module("aro"));
// Optional; this will make aro's builtin includes (the <code>include</code> directory of this repo) available to <code>Toolchain</code>
b.installDirectory(.{
.source_dir = aro.path("include"),
.install_dir = .prefix,
.install_subdir = "include",
});
```
Now you can do
<code>zig
const aro = @import("aro");</code>
in your Zig code. | []
|
https://avatars.githubusercontent.com/u/23202?v=4 | wasm4 | aduros/wasm4 | 2021-08-05T23:48:23Z | Build retro games using WebAssembly for a fantasy console. | main | 117 | 1,327 | 182 | 1,327 | https://api.github.com/repos/aduros/wasm4/tags | ISC | [
"2d-game-engine",
"assemblyscript",
"d",
"dlang",
"emscripten",
"fantasy-computer",
"fantasy-console",
"game-development",
"gamedev",
"go",
"golang",
"nelua",
"nim",
"odin",
"retrogaming",
"rust",
"typescript",
"wasm",
"webassembly",
"zig"
]
| 5,746 | false | 2025-05-21T08:22:29Z | false | false | unknown | github | []
|
<a></a>
WASM-4
Build retro games using WebAssembly for a fantasy console
<a>Website</a> •
<a>Showcase</a> •
<a>Docs</a> •
<a>Discussions</a>
About
<strong>WASM-4</strong> is a low-level fantasy game console for building small games with WebAssembly. Game
cartridges (ROMs) are small, self-contained <code>.wasm</code> files that can be built with any programming
language that compiles to WebAssembly.
Key Features
<ul>
<li>
<strong>No Glue Code</strong>: If you've ever tried to write even a simple "Hello World"
with WebAssembly before, you'll know it usually involves writing a bunch of
JS and HTML glue. WASM-4 removes all of that, games interface directly with
the system through a small API.
</li>
<li>
<strong>Minimalist</strong>: Fantasy consoles force developers to work with limited resources.
This makes them simple to learn, and easier to focus on finishing your game.
</li>
<li>
<strong>Language Agnostic</strong>: Use any programming language, as long as it can compile to WebAssembly. Out
of the box we currently support: AssemblyScript, C/C++, D, Go, Nelua, Nim, Odin, Rust, WAT, and
Zig.
</li>
<li>
<strong>Portable</strong>: WASM-4 is designed to run on any device that can execute WebAssembly, even outside
of the web! It includes a lightweight runtime written in C that runs even <a>low-powered microcontrollers</a>
and <a>obsolete hardware</a>.
</li>
<li>
<strong>Netplay</strong>: Instant online multiplayer, featuring rollback netcode. All games that support local
multiplayer automatically support netplay. WASM-4 handles syncing controller inputs over the
Internet.
</li>
</ul>
🚀 60 Second Quickstart
```shell
Install the w4 command
npm install -g wasm4
Create a project
w4 new --assemblyscript hello-world
Setup toolchain
cd hello-world
npm install
Build and run your game!
npm run build
w4 run build/cart.wasm
```
For more info and guides, check the <a>full documentation</a>.
🎮 Hardware Specs
<ul>
<li>Display: 160x160 pixels, 4 customizable colors, updated at 60 Hz.</li>
<li>Memory: 64 KB linear RAM, memory-mapped I/O, save states.</li>
<li>Cartridge Size Limit: 64 KB.</li>
<li>Input: Keyboard, mouse, touchscreen, up to 4 gamepads.</li>
<li>Audio: 2 pulse wave channels, 1 triangle wave channel, 1 noise channel.</li>
<li>Disk Storage: 1024 bytes.</li>
</ul>
🙏 Contributing
Contributions are welcome! Here are just a few ways to help:
<ul>
<li><strong>Build a game or experiment, we'll feature it on wasm4.org!</strong></li>
<li>Improve our documentation or write a tutorial.</li>
<li>Submit a bug report or feature request on Github.</li>
<li>Answer questions on the discussions forum.</li>
<li>Implement support for a new tool or language.</li>
<li>Give the project a star on Github for visibility.</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/49629865?v=4 | pixi | foxnne/pixi | 2021-06-17T17:43:39Z | Pixel art editor made with Zig. | main | 16 | 966 | 26 | 966 | https://api.github.com/repos/foxnne/pixi/tags | MIT | [
"2d",
"animation",
"cross-platform",
"editor",
"gamedev",
"imgui",
"mit-license",
"pixelart",
"zig",
"ziglang"
]
| 13,624 | false | 2025-05-22T07:14:35Z | true | true | unknown | github | [
{
"commit": "24e6db38d0e4274367ff2595aa8199e0f0157875.tar.gz",
"name": "mach",
"tar_url": "https://github.com/foxnne/mach/archive/24e6db38d0e4274367ff2595aa8199e0f0157875.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/foxnne/mach"
},
{
"commit": "5aa9281b29a61db91f4db29cdaf158321a91beb4.tar.gz",
"name": "zig_imgui",
"tar_url": "https://github.com/foxnne/zig-imgui/archive/5aa9281b29a61db91f4db29cdaf158321a91beb4.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/foxnne/zig-imgui"
},
{
"commit": "d9a0947365b1ee8131fcf518feac8dfe896cfcfa.tar.gz",
"name": "zstbi",
"tar_url": "https://github.com/foxnne/zstbi/archive/d9a0947365b1ee8131fcf518feac8dfe896cfcfa.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/foxnne/zstbi"
},
{
"commit": "9620a611a8c039711dc780bf296d8dc100d16d3a.tar.gz",
"name": "zmath",
"tar_url": "https://github.com/foxnne/zmath/archive/9620a611a8c039711dc780bf296d8dc100d16d3a.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/foxnne/zmath"
}
]
|
<strong>Pixi</strong> is an cross-platform open-source pixel art editor and animation editor written in <a>Zig</a>.
Check out the <a>user guide</a>!
<a></a>
Currently supported features
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Typical pixel art operations. (draw, erase, dropper, bucket, selection, transformation, etc)
<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> Create animations and preview easily, edit directly on the preview.
<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> View previous and next frames of the animation.
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Set sprite origins for drawing sprites easily in game frameworks.
<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> Import and slice existing .png spritesheets.
<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> Intuitive and customizeable user interface.
<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> Sprite packing
<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> Theming
<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> Automatic packing and export on file save
<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> Also a zig library offering modules for handling assets
<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> NEW: Export animations as .gifs
User Interface
<ul>
<li>The user interface is driven by <a>Dear Imgui</a> which should be familiar to many.</li>
<li>The general layout takes many ideas from VSCode, as well as general project setup using folders.</li>
</ul>
Compilation
<ul>
<li>[Linux] Ensure <code>gtk+3-devel</code> or similar is installed (for native file dialogs).</li>
<li>Install zig using <a>zigup</a> <code>zigup 0.14.0-dev.2577+271452d22</code> or manually and add to PATH.</li>
<li>Zig version required is latest mach nominated version, find [here.]https://machengine.org/docs/nominated-zig/#2024110-mach(https://machengine.org/docs/nominated-zig/#2024110-mach)</li>
<li>Clone pixi.</li>
<li>Build.<ul>
<li><code>git clone https://github.com/foxnne/pixi.git</code></li>
<li><code>cd pixi</code></li>
<li><code>zig build run</code></li>
</ul>
</li>
</ul>
Credits
<ul>
<li>The wonderful <a>Dear Imgui</a> used for almost all of the user interface.</li>
<li><a>emidoots</a> for all the help and <a>mach</a>.</li>
<li><a>michal-z</a> for all the help and <a>zig-gamedev</a>.</li>
<li><a>prime31</a> for all the help.</li>
<li>Any and all contributors</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/7967463?v=4 | zf | natecraddock/zf | 2021-08-23T23:02:10Z | a commandline fuzzy finder and zig module designed for filtering filepaths | main | 8 | 536 | 22 | 536 | https://api.github.com/repos/natecraddock/zf/tags | MIT | [
"cli",
"fuzzy",
"fuzzy-search",
"library",
"unix",
"zig",
"zig-library",
"zig-package"
]
| 317 | false | 2025-05-19T13:03:43Z | true | true | unknown | github | [
{
"commit": "1201bf393a9c8ae4e1564d01e4e4d9377e2c89de.tar.gz",
"name": "ziglyph",
"tar_url": "https://github.com/jecolon/ziglyph/archive/1201bf393a9c8ae4e1564d01e4e4d9377e2c89de.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/jecolon/ziglyph"
}
]
| zf
<a></a> <a></a>
zf is an interactive commandline fuzzy finder that prioritizes matches on filenames. zf accepts newline separated strings on <code>stdin</code> and outputs the selected line on <code>stdout</code>. Use with a pipe, or io redirection. See the <a>documentation</a> for more details. zf is also packaged as an allocation-free library for fuzzy filtering.
https://user-images.githubusercontent.com/7967463/225198950-a6ab568f-644f-40a1-b202-c12a35aeaed8.mp4
Features
<ul>
<li>designed for fuzzy matching file paths (but also works as a general purpose fuzzy finder)</li>
<li>refine search results with whitespace separated query terms</li>
<li>case insensitive unless the query contains uppercase letters (smartcase)</li>
<li>multiselect to output multiple selected lines</li>
<li>Zig and C libraries for the zf ranking algorithm</li>
</ul>
zf aims to be simple:
* no full-window interface
* minimal config and options
* sensible defaults
Docs
<ul>
<li><a>Usage Documentation</a></li>
<li><a>Library Documentation</a></li>
</ul>
Why use zf?
zf was designed knowing that a frequent use case for fuzzy finders is filtering filepaths. It also works great for any arbitrary string, but it is especially good at filtering filepaths with precision.
Specifically,
<ul>
<li>Matches on filenames are prioritized over filepath matches</li>
<li>Matches on the beginning of a word are prioritized over matches in the middle of a word</li>
<li>Non-sequential character matches are penalized</li>
<li>Strict path matching offers even more precision</li>
</ul>
Here are some concrete examples.
Filename priority
The query is matched first on the filename and then on the path if the filename doesn't match. This example comes from Blender's source code, and was my original inspiration for designing zf.
```text
<blockquote>
make
./GNUmakefile
./source/blender/makesdna/DNA_genfile.h
./source/blender/makesdna/intern/dna_genfile.c
./source/blender/makesrna/intern/rna_cachefile.c
./source/blender/makesdna/DNA_curveprofile_types.h
```
</blockquote>
Fzf and fzy both rank <code>source/blender/makesdna/DNA_genfile.h</code> first in the results, with <code>GNUmakefile</code> 10 items down the list.
Space-separated tokens
But not every filename is unique. Sometimes there are codebases where there are many files with the same or similar names, like an <code>__init__.py</code> in Python, or <code>.c</code> and <code>.h</code> file pairs in C. In zf each space separated query term is used to narrow down the results. Imagine searching for an <code>__init__.py</code> file in a Python project.
```text
<blockquote>
init
./<strong>init</strong>.py
./ui/<strong>init</strong>.py
./data/<strong>init</strong>.py
./config/<strong>init</strong>.py
```
</blockquote>
At this point you can either move the selection down with Down or <code>c-n</code> to find
<code>./config/__init__.py</code>, or you can add a new token to the query string.
```text
<blockquote>
init c
./config/<strong>init</strong>.py
```
</blockquote>
Treating the query string as a sequence of tokens makes filtering more
efficient.
Strict path matching
This feature is a "do what I mean" feature, more easily used than explained. When the query looks like a path (contains at least one path separator) strict path matching is enabled.
Path segments are the portions of a path delimited by path separators. <code>foo/bar</code> has segments <code>foo</code> and <code>bar</code>. With strict path matching the path segments of the query token must not span across path segments in the candidate. As an example, the query <code>foo/</code> would match <code>foo/bar/</code> but not <code>fo/obar/</code> because the characters <code>"foo"</code> must appear in a single path segment.
This is useful for narrowing down results when you know the exact path structure of your files. With the following paths
<code>./app/models/foo/bar/baz.rb
./app/models/foo/bar-baz.rb
./app/models/foo-bar-baz.rb
./app/monsters/dungeon/foo/bar/baz.rb</code>
Strict path matching ensures that the intended path structure is found.
```
<blockquote>
a/m/f/b/baz
./app/models/foo/bar/baz.rb
```
</blockquote>
In other fuzzy finders the string <code>app/monsters/dungeon/foo/bar/baz.rb</code> is also included in the results. Strict path matching prevents this because there is a slash between <code>onsters/dungeon</code> and nothing in the query matches the <code>dungeon</code> segment.
To end strict path matching, just add a space to start a new query token.
Installation
Arch Linux
An <a>AUR package</a> is available.
macOS
Install with Homebrew
<code>brew install zf</code>
Nix
<code>nix-env --install zf</code>
Binaries
Each <a>release</a> has binaries attached for macOS and Linux.
Building from source
For compatibility with system package managers, zf targets the latest stable release of Zig. The <a><code>unstable</code></a> branch is kept up to date with Zig master.
<code>git clone https://github.com/natecraddock/zf
cd zf
zig build -Doptimize=ReleaseSafe --summary all</code>
The executable will be created in <code>./zig-out/bin/zf</code>. For debug builds omit <code>-Doptimize=ReleaseSafe</code>.
Integrations
Would you like to use zf in an editor? Try one of the following plugins
<ul>
<li><a>zf.vim</a>: zf integrated with vim for
fuzzy file finding. Similar to fzf.vim.</li>
<li><a>telescope-zf-native.nvim</a>
a neovim <a>telescope</a>
extension to override the default Lua sorter with zf.</li>
</ul>
Contributing
I am open to contributions of all kinds, but be aware that I want to keep zf small and easy to maintain. | [
"https://github.com/cyberegoorg/cetech1",
"https://github.com/natecraddock/zf-wasm-playground",
"https://github.com/reykjalin/project-picker"
]
|
https://avatars.githubusercontent.com/u/86896666?v=4 | awesome-zig | catdevnull/awesome-zig | 2021-08-18T01:28:48Z | A list of awesome projects related to Zig | main | 0 | 463 | 34 | 463 | https://api.github.com/repos/catdevnull/awesome-zig/tags | CC0-1.0 | [
"awesome",
"awesome-list",
"zig",
"ziglang"
]
| 220 | true | 2025-05-21T14:15:59Z | false | false | unknown | github | []
| Awesome Zig <a></a>
<a></a>
A general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.
Contents
<ul>
<li><a>Algorithms and data structures</a></li>
<li><a>Allocators and memory</a></li>
<li><a>Audio</a></li>
<li><a>Bootables</a></li>
<li><a>Compilers and interpreters</a></li>
<li><a>Concurrency</a></li>
<li><a>Database</a></li>
<li><a>Editor plugins</a></li>
<li><a>Emulators</a></li>
<li><a>Game tools and libraries</a></li>
<li><a>Games</a></li>
<li><a>GUI</a></li>
<li><a>Misc libraries</a></li>
<li><a>Network</a></li>
<li><a>HTTP</a></li>
<li><a>Web</a></li>
<li><a>System tools</a></li>
<li><a>Zig development tools</a></li>
<li><a>Package managers</a></li>
<li><a>Parser</a></li>
<li><a>Learning resources</a></li>
<li><a>C/C++ libraries packaged for Zig</a></li>
<li><a>Other</a></li>
</ul>
Algorithms and data structures
<ul>
<li><a>ziglibs/s2s</a> - Binary serialization format and library.</li>
<li><a>BarabasGitHub/LZig4</a> - LZ4 implementation.</li>
<li><a>DutchGhost/ArrayVec</a> - An array with a vector feeling.</li>
<li><a>emekoi/deque.zig</a> - A lock free chase-lev deque.</li>
<li><a>kristoff-it/zig-cuckoofilter</a> - Production-ready Cuckoo Filters for any C ABI compatible target.</li>
<li><a>marijnfs/zigtimsort</a> - TimSort implementation.</li>
<li><a>Sahnvour/zig-containers</a> - A container library.</li>
<li><a>Srekel/zig-sparse-set</a> - Sparse sets, supporting both SOA and AOS style.</li>
<li><a>hexops/xorfilter</a> - Xor Filters for checking if a key is part of a set.</li>
<li><a>JakubSzark/zig-string</a> - UTF-8 string data structure.</li>
<li><a>karlseguin/cache.zig</a> - Thread-safe, expiration-aware, LRU cache.</li>
</ul>
Allocators and memory
<ul>
<li><a>fengb/zee_alloc</a> - Tiny allocator primarily targeting WebAssembly.</li>
<li><a>mdsteele/ziegfried</a> - A general-purpose memory allocator.</li>
<li><a>suirad/Seal</a> - An allocator that wraps another allocator and detects if memory is leaked after usage.</li>
<li><a>Hejsil/zig-gc</a> - A super simple mark-and-sweep garbage collector.</li>
<li><a>dbandstra/zig-hunk</a> - Basic "Hunk" memory allocator, based on the hunk system from id Software's Quake engine.</li>
</ul>
Audio
<ul>
<li><a>Hejsil/zig-midi</a></li>
<li><a>hazeycode/zig-alsa</a> - Bindings for ALSA (libasound).</li>
<li><a>dantecatalfamo/sndio-zig</a> - Bindings for <a>sndio</a>.</li>
<li><a>orhun/linuxwave</a> - Generate music from the entropy of Linux.</li>
<li><a>dbandstra/zig-wav</a> - Simple WAV file parser and writer.</li>
</ul>
Bootables
<ul>
<li><a>AndreaOrru/zen</a> - Experimental operating system.</li>
<li><a>andrewrk/clashos</a> - Multiplayer arcade game for bare metal Raspberry Pi 3 B+.</li>
<li><a>andrewrk/HellOS</a> - "hello world" x86 kernel example.</li>
<li><a>chivay/vmt</a> - Toy OS.</li>
<li><a>DorianXGH/Lukarnel</a> - A microkernel with Rust microservices.</li>
<li><a>iguessthislldo/georgios</a> - Hobby Operating System.</li>
<li><a>jzck/kernel-zig</a> - Hobby x86 kernel.</li>
<li><a>markfirmware/zig-bare-metal-microbit</a> - Bare metal microbit program.</li>
<li><a>markfirmware/zig-bare-metal-raspberry-pi</a> - Bare metal raspberry pi program.</li>
<li><a>MasterQ32/RetrOS</a> - A retro-style gaming console running on bare x86 metal.</li>
<li><a>nrdmn/uefi-examples</a> - UEFI examples.</li>
<li><a>nrdmn/uefi-paint</a> - UEFI-bootable touch paint app.</li>
<li><a>rafaelbreno/zig-os</a> - A simple OS following Philipp Oppermann's posts "Writing an OS in Rust".</li>
<li><a>SamTebbs33/pluto</a> - An x86 kernel.</li>
<li><a>sjdh02/trOS</a> - Tiny aarch64 baremetal OS thingy.</li>
<li><a>tralamazza/embedded_zig</a> - Minimal embedded ARM example (STM32F103 blue pill).</li>
<li><a>yvt/zig-armv8m-test</a> - Example app for Armv8-M + TrustZone.</li>
<li><a>ZeeBoppityZagZiggity/ZBZZ.OS</a> - An operating system built for RISCV.</li>
</ul>
Compilers and interpreters
<ul>
<li><a>oven-sh/bun</a> - Incredibly fast JavaScript runtime, bundler, transpiler and package manager – all in one.</li>
<li><a>Vexu/bog</a> - Small, strongly typed, embeddable language.</li>
<li><a>LoLa Programming Language</a> - (<a>GitHub</a>) An embeddable programming language for game scripting.</li>
<li><a>squeek502/zua</a> - An implementation of Lua 5.1 for learning purposes.</li>
<li><a>CurtisFenner/zsmol</a> - The new Smol compiler and reference.</li>
<li><a>dantecatalfamo/brainfuck-zig</a> - Brainfuck interpreter.</li>
<li><a>dantecatalfamo/mruby-zig</a> - <a>mruby</a> bindings.</li>
<li><a>dantecatalfamo/wren-zig</a> - <a>wren</a> bindings.</li>
<li><a>fulcrum-so/ziggy-pydust</a> - <a>Python</a> bindings.</li>
<li><a>fubark/cyber</a> - Fast and concurrent scripting.</li>
</ul>
Concurrency
<ul>
<li><a>mitchellh/libxev</a> - Cross-platform event-loop.</li>
<li><a>kprotty/zefi</a> - Fiber library.</li>
<li><a>rsepassi/zigcoro</a> - coroutine-friendly, based on libxev.</li>
<li><a>iacore/minicoro-zig</a> - Bindings for minicoro - Stackful Stack-Switching Coroutine.</li>
</ul>
Database
<ul>
<li><a>coilhq/tigerbeetle</a> - A distributed financial accounting database designed for mission critical safety and performance.</li>
<li><a>kristoff-it/redis-cuckoofilter</a> - Hashing-function agnostic Cuckoo filters for Redis.</li>
<li><a>kristoff-it/zig-okredis</a> - Zero-allocation Client for Redis 6+.</li>
<li><a>leroycep/sqlite-zig</a> - SQLite bindings.</li>
<li><a>vrischmann/zig-cassandra</a> - Client for Cassandra 2.1+.</li>
<li><a>vrischmann/zig-sqlite</a> - SQLite wrapper.</li>
<li><a>karlseguin/zuckdb.zig</a> - DuckDB wrapper.</li>
<li><a>karlseguin/pg.zig</a> - Native PostgreSQL client.</li>
</ul>
Editor plugins
<ul>
<li><a>MarioAriasC/zig-support</a> - Language support for JetBrains IDEs (IntelliJ, CLion and others)</li>
<li><a>isaachier/ztags</a> - Ctags implementation for Zig.</li>
<li><a>Tetralux/sublime-zig</a> - My own, more lightweight, syntax highlighting for Zig.</li>
<li><a>ziglang/sublime-zig-language</a> - Zig language support for Sublime Text.</li>
<li><a>ziglang/vscode-zig</a> - Zig language support for VSCode.</li>
<li><a>ziglang/zig-mode</a> - Zig mode for Emacs.</li>
<li><a>ziglang/zig.vim</a> - Vim configuration for Zig.</li>
<li><a>zigtools/zls</a> - Zig LSP implementation + Zig Language Server.</li>
</ul>
Emulators
<ul>
<li><a>fengb/fundude</a> - Gameboy emulator for WASM.</li>
<li><a>GrooveStomp/chip8-zig</a> - CHIP-8 emulator.</li>
<li><a>sourgrasses/ichigo</a> - Virtual Boy emulator.</li>
<li><a>floooh/kc85.zig</a> - A KC85 emulator.</li>
<li><a>Arwalk/ChipZ</a> A simple Chip8 emulator (library and executable).</li>
</ul>
Game tools and libraries
<ul>
<li><a>hexops/mach</a> - Game engine and graphics toolkit.</li>
<li><a>michal-z/zig-gamedev</a> - DirectX 12 game development ecosystem.</li>
<li><a>floooh/sokol-zig</a> - <a>Sokol</a> bindings.</li>
<li><a>TM35-Metronome/metronome</a> - A set of tools for modifying and randomizing Pokémon games.</li>
<li><a>TM35-Metronome/tm35-nds</a> - A library for working with Nintendo DS roms.</li>
<li><a>user00e00/sudokuinzig</a> - Simple and robust sudoku solver.</li>
<li><a>wendigojaeger/ZigGBA</a> - SDK for creating Game Boy Advance games using Zig.</li>
<li><a>hazeycode/brucelib</a> - Monorepo of modules for programming cross-platforms games, simulations, engines & editors.</li>
<li><a>andy5995/zigdeck</a> - A library that creates and shuffles a deck of cards from which you can draw.</li>
</ul>
Games
<ul>
<li><a>Akuli/curses-minesweeper</a> - Minesweeper game written in curses.</li>
<li><a>andrewrk/tetris</a> - A simple tetris clone.</li>
<li><a>fabioarnold/snake-zig</a> - A simple snake clone.</li>
<li><a>Stenodyon/blink</a> - A game about building logic with lasers.</li>
<li><a>thejoshwolfe/legend-of-swarkland</a> - Hack-n-slash roguelike inspired by NetHack.</li>
<li><a>tiehuis/zstack</a> - Line-race tetris mode.</li>
<li><a>kooparse/zalgebra</a> - Linear algebra library for games and real-time computer graphics.</li>
<li><a>floooh/pacman.zig</a> - A Pacman clone.</li>
<li><a>dantecatalfamo/OpenCSE</a> - Free implementation of the Can't Stop Express dice game.</li>
<li><a>dbandstra/oxid</a> - Arcade-style game where you fight waves of monsters in a fixed-screen maze.</li>
<li><a>six519/YieArKUNGFUZig</a> - Yie Ar Kung-Fu clone with raylib.</li>
</ul>
GUI
<ul>
<li><a>capy-ui/capy</a> - Cross-platform library for making true native GUIs.</li>
<li><a>david-vanderson/gui</a> - Immediate mode GUI for Zig.</li>
<li><a>Aransentin/ZWL</a> - Zig Windowing Library.</li>
<li><a>prime31/zig-upaya</a> - GUI toolkit.</li>
<li><a>fubark/cosmic</a> - GUI toolkit.</li>
<li><a>batiati/IUPforZig</a> - Zig idiomatic and type-checked bindings for IUP Portable User Interface Toolkit.</li>
<li><a>andrewrk/zig-sdl</a> - Self-contained SDL2 package for Zig.</li>
<li><a>Snektron/vulkan-zig</a> - Vulkan binding generator.</li>
<li><a>Avokadoen/zig_vulkan</a> - Toy renderer using Vulkan and GLFW.</li>
<li><a>andrewrk/zig-vulkan-triangle</a> - Simple triangle displayed using Vulkan, GLFW, and Zig.</li>
<li><a>kassane/QML-zig</a> - QML bindings.</li>
<li><a>cshenton/learnopengl</a> - <a>Learn OpenGL</a> tutorials ported to Zig.</li>
<li><a>ifreund/river</a> - Dynamic wayland compositor that takes inspiration from dwm and bspwm.</li>
<li><a>Nelarius/weekend-raytracer-zig</a> - An implementation of the "Ray Tracing in One Weekend" book.</li>
<li><a>SpexGuy/Zig-Gltf-Display</a> - A program that displays glTF files using Vulkan.</li>
<li><a>tiehuis/zig-raytrace</a> - Simple raytracer.</li>
<li><a>donpdonp/zootdeck</a> - Fediverse GTK Desktop Reader.</li>
<li><a>MasterQ32/ZigPaint</a> - A simple paint application. Used to create an OpenGL loader/wrapper and a minimal UI system.</li>
<li><a>olexij-christian/zgtk3</a> - GTK3 bindings.</li>
</ul>
Misc libraries
<ul>
<li><a>natecraddock/ziglua</a> - Bindings for the Lua C API.</li>
<li><a>ryoppippi/zigcv</a> - Bindings for OpenCV4.</li>
<li><a>BraedonWooding/Lazy-Zig</a> - Linq.</li>
<li><a>DutchGhost/maybeuninit</a> - MaybeUninit.</li>
<li><a>emekoi/log.zig</a> - A thread-safe logging library.</li>
<li><a>kprotty/zap</a> - A collection of libraries which provide interfaces over the system for writing high performance applications.</li>
<li><a>vbrusca/ZigMatrixUtils</a> - Matrix manipulation and utility library.</li>
<li><a>mlarouche/zigimg</a> - Library for reading and writing different image formats.</li>
<li><a>bfactory-ai/zignal</a> - Image processing library inspired by <a>dlib</a>.</li>
<li><a>dbandstra/zig-pcx</a> - PCX image format decoder and encoder.</li>
<li><a>ziglibs/known-folders</a> - Provides access to well-known folders across several operating systems.</li>
<li><a>SasLuca/zig-nanoid</a> - Battle-tested, tiny, secure, URL-friendly, unique string ID generator. Now available in pure Zig.</li>
<li><a>kassane/libvlc-zig</a> - Bindings for libVLC media framework.</li>
<li><a>karlseguin/log.zig</a> - Structured logging library.</li>
<li><a>dantecatalfamo/9p-zig</a> - 9P2000 client/server library.</li>
<li><a>karlseguin/singleflight.zig</a> - Duplicate function call suppression.</li>
<li><a>kassane/lean4-zig</a> - Bindings for Lean 4 (theorem prover).</li>
<li><a>attron/astroz</a> - Astronomical and Spacecraft Toolkit.</li>
<li><a>pblischak/zprob</a> - Module for Random Number Distributions.</li>
</ul>
Network
<ul>
<li><a>MasterQ32/zig-network</a> - Small network abstraction layer around TCP & UDP.</li>
<li><a>dantecatalfamo/zig-dns</a> - Experimental DNS library implemented in zig.</li>
<li><a>euantorano/ip.zig</a> - Library for working with IP Addresses.</li>
<li><a>lun-4/zigdig</a> - Naive DNS client library.</li>
<li><a>marler8997/netpunch</a> - Outbound proxy protocol.</li>
<li><a>remeh/statsd-zig</a> - Basic DogStatsD UDP server.</li>
</ul>
HTTP
<ul>
<li><a>Luukdegram/apple_pie</a> - HTTP 1.0/1.1 Server implementation.</li>
<li><a>truemedian/zfetch</a> - HTTP(S) client based on iguanaTLS.</li>
<li><a>ducdetronquito/requestz</a> - HTTP client based on h11.</li>
<li><a>ducdetronquito/h11</a> - I/O-free HTTP/1.1 implementation inspired by hyper/h11.</li>
<li><a>lun-4/ziget</a> - Simple wget without libc.</li>
<li>~~<a>Vexu/routez</a> - HTTP server.~~</li>
<li><a>frmdstryr/zhp</a> - Featureful HTTP server.</li>
<li><a>axgdev/telegram_echobot_zig</a> - Telegram echo bot.</li>
<li><a>karlseguin/http.zig</a> - HTTP/1.1 server.</li>
<li><a>zigzap/zap</a> - blazingly fast, robust HTTP server.</li>
</ul>
Messaging
<ul>
<li><a>skunkwerks/zamqp</a> - AMQP client, based on rabbitmq-c.</li>
<li><a>nine-lives-later/zzmq</a> - ZeroMQ library, based on CZMQ.</li>
</ul>
Web
<ul>
<li><a>andrewrk/lua-in-the-browser</a> - Using Zig to build Lua for WebAssembly.</li>
<li><a>karlseguin/websocket.zig</a> - A WebSocket implementation.</li>
<li><a>kivikakk/htmlentities.zig</a> - HTML5 entity data.</li>
<li><a>meheleventyone/zig-wasm-test</a> - A minimal WebAssembly example using Zig's build system.</li>
<li><a>shritesh/zig-wasm-dom</a> - Zig + WebAssembly + JS + DOM.</li>
<li><a>shritesh/zigfmt-web</a> - Zig fmt on the web.</li>
<li><a>zigwasm/wasm-zig</a> - Common WASM runtime binding to C API.</li>
<li><a>zigwasm/wasmer-zig</a> - Bindings for the Wasmer WebAssembly runtime.</li>
<li><a>zigwasm/wasmtime-zig</a> - Bindings of Wasmtime.</li>
<li><a>batiati/mustache-zig</a> - Mustache implementation.</li>
<li><a>floscodes/zerve</a> - Simple framework for writing web services and web apps.</li>
<li><a>zon-dev/zinc</a> - Zinc is a framework focusing on high performance, usability, security, and extensibility.</li>
<li><a>by-nir/aws-lambda-zig</a> - Super-fast AWS Lambda runtime for Zig.</li>
</ul>
System tools
<ul>
<li><a>pbui-project/pbui-main</a> - BSD/Linux core utilities written in Zig.</li>
<li><a>hspak/brightnessztl</a> - A CLI to control device backlight.</li>
<li><a>thejoshwolfe/hexdump-zip</a> - Produce an annotated hexdump of a zipfile.</li>
<li><a>kubkon/zacho</a> - Zig's Mach-O parser.</li>
<li><a>weskoerber/mac_address</a> - A cross-platform library to retrieve the MAC address from your network interfaces without libc.</li>
</ul>
Zig development tools
<ul>
<li><a>marler8997/zigup</a> - Download and manage zig compilers.</li>
<li><a>korandoru/setup-zig</a> - Set up a specific version of Zig environment on GitHub Actions.</li>
<li><a>weskoerber/zvm</a> - POSIX-compliant bash script to manage multiple active Zig versions.</li>
<li><a>vezel-dev/zig-sdk</a> - MSBuild SDK for building Zig, C, and C++ projects using the Zig compiler.</li>
<li><a>aherrmann/rules_zig</a> - Bazel build rules for Zig.</li>
</ul>
Package managers
<ul>
<li><a>zigtools/zpm</a> - Unofficial Zig package manager.</li>
<li><a>mattnite/gyro</a> - Package manager with an index, build runner, and build dependencies.</li>
<li><a>nektro/zigmod</a> - Zig package manager.</li>
<li><a>cheetah/asdf-zig</a> - Zig plugin for the ASDF package manager.</li>
<li><a>mattnite/ezpkg</a> - Zig Package Manager Expansion Pack.</li>
<li><a>nix-community/zon2nix</a> - Convert the dependencies in <code>build.zig.zon</code> to a Nix expression.</li>
</ul>
Parser
<ul>
<li><a>darithorn/zig-toml</a> - A TOML parser.</li>
<li><a>Himujjal/zig-json5</a> - JSON5 parser resembling the <code>std.json</code> APIs.</li>
<li><a>EzequielRamis/zimdjson</a> - Parsing gigabytes of JSON per second. Zig port of simdjson with fundamental features.</li>
<li><a>chwayne/rem</a> - An HTML parsing library.</li>
<li><a>goto-bus-stop/ziguid</a> - GUID parsing/stringifying.</li>
<li><a>00JCIV00/cova</a> - Commands, Options, Values, Arguments. A simple yet robust cross-platform command line argument parsing library.</li>
<li><a>Hejsil/zig-clap</a> - Simple command line argument parsing library.</li>
<li><a>sam701/zig-cli</a> - Package for building command line apps.</li>
<li><a>kivikakk/libpcre.zig</a> - Bindings to libpcre for Perl-compatible regular expressions.</li>
<li><a>kivikakk/koino</a> - CommonMark/GitHub Flavored Markdown parser and HTML renderer.</li>
<li><a>kubkon/zig-yaml</a> - YAML parser.</li>
<li><a>loo-re/zini</a> - Consistent .ini parser.</li>
<li><a>sreehax/zig-ini</a> - .ini parser.</li>
<li><a>Nulo/ini-parser</a> - .ini parser.</li>
<li><a>tiehuis/zig-regex</a> - A regex implementation.</li>
<li><a>tiehuis/zig-ryu</a> - Port of <a>ryu</a>.</li>
<li><a>Vexu/zuri</a> - URI parser.</li>
<li><a>vi/zigmkv</a> - Matroska/webm (mkv) parser.</li>
<li><a>winksaville/zig-parse-args</a> - Parse command line arguments.</li>
<li><a>winksaville/zig-parse-number</a> - Implement ParseNumber which can parse any TypeId.Int or TypeId.Float.</li>
<li><a>gernest/base32</a> - Base32 encoding/decoding.</li>
<li><a>caolan/zig-netstring</a> - Netstring parser.</li>
<li><a>Arwalk/zig-protobuf</a> - Implementation of Protocol Buffers v3 leveraging Zig's comptime.</li>
<li><a>iddev5/inon</a> - Data configuration file format.</li>
<li><a>naneros/ztoml</a> - TOMLv1.0.0 parser and convert TOML to JSON.</li>
<li><a>InKryption/comath</a> - Calculate math expressions in comptime.</li>
<li><a>weskoerber/kewpie</a> - A simple query string parser.</li>
</ul>
Learning resources
<ul>
<li><a>belse-de/zig-tut</a> - A collection of small projects and tutorials to learn Zig.</li>
<li><a>Sobeston/ziglearn</a> - Zig learning resources.</li>
<li><a>zighelp/zighelp</a> - Get up to speed with Zig quickly (ziglearn fork).</li>
<li><a>ziglings/exercises</a> - Learn Zig by fixing tiny example programs.</li>
</ul>
C/C++ libraries packaged for Zig
These C/C++ libraries were packaged to be used with the Zig build and packaging system (<code>build.zig</code>).
C
<ul>
<li><a>andrewrk/SDL</a> - Simple Directmedia Layer.</li>
<li><a>andrewrk/libz</a> - Zlib data compression.</li>
<li><a>andrewrk/ffmpeg</a> - library only.</li>
<li><a>andrewrk/libgroove</a> - streaming audio processing library.</li>
<li><a>andrewrk/libsoundio</a> - library for real-time audio input and output.</li>
<li><a>kassane/openssl-zig</a> - crypto, providers & ssl libraries only.</li>
<li><a>kassane/wolfssl</a> - wolfssl library.</li>
<li><a>kassane/libbpf</a> - BPF CO-RE (Compile Once – Run Everywhere).</li>
<li><a>kassane/winpthreads</a> - PThread library for MinGW.</li>
<li><a>raysan5/raylib</a> - A simple and easy-to-use library to enjoy videogames programming.</li>
<li><a>jmcnamara/libxlsxwriter</a> - Creating Excel XLSX files.</li>
<li><a>alexrp/libffi</a> - libffi with a Zig build script.</li>
</ul>
C++
<ul>
<li><a>andrewrk/libchromaprint</a> - library for generating audio fingerprints used by AcoustID.</li>
<li><a>kassane/asio</a> - (non-boost) Networking I/O library (w/ event-loop, C++14/17/20).</li>
<li><a>kassane/fmt</a> - Modern formatting library.</li>
<li><a>kassane/context</a> - (boost-context) fiber library (C++14/17/20).</li>
<li><a>kassane/fiber</a> - (boost-fiber) userland threads (C++14/17/20).</li>
<li><a>kassane/beast</a> - (boost-beast) HTTP and WebSocket (C++14/17/20).</li>
<li><a>kassane/hana</a> - (boost-hana) Meta-programming library (header-only, C++14/17/20).</li>
<li><a>kassane/intrusive</a> - (boost-intrusive) intrusive containers (header-only, C++03/11/14).</li>
<li><a>kassane/unordered</a> - (boost-unordered) hashmap and set concurrency containers (C++03/11/14).</li>
<li><a>kassane/catch2</a> - Unit testing library (C++14/17/20).</li>
<li><a>kassane/outcome</a> - (non-boost) Error handler (C++14/17/20).</li>
<li><a>kassane/json</a> - jsoncpp ported to Zig packaging.</li>
<li><a>kassane/Standalone-Server</a> - Asio standalone C++ HTTP/S Server.</li>
<li><a>kassane/range-v3</a> - modern range library (C++14/17/20).</li>
<li><a>kassane/libzmq</a> - ZeroMQ core engine in C++ library.</li>
<li><a>kassane/libsigcplusplus</a> - Typesafe callback system for standard C++.</li>
<li><a>ggerganov/llama.cpp</a> - Port of Facebook's LLaMA model in C/C++.</li>
</ul>
Other
<ul>
<li><a>All Your Codebase</a> - Development status of Zig and its' ecosystem.</li>
<li><a>zig.pm</a> - A community-maintained repository of Zig packages.</li>
<li><a>hspak/geteltorito-zig</a> - Geteltorito re-write in Zig.</li>
<li><a>momumi/x86-zig</a> - Library for assembling x86.</li>
<li><a>nrdmn/ilo_license_key</a> - ILO license key library.</li>
<li><a>vegecode/svd2zig</a> - Convert System View Description (svd) files to Zig headers for baremetal development.</li>
<li><a>mqttiotstuff/iotmonitor</a> - MQTT IotMonitor tools, save time to monitor mqtt agents or devices.</li>
<li><a>ve-nt/outfieldr</a> - <a>TLDR</a> client.</li>
<li><a>kubkon/zig-ios-example</a> - Minimal <code>build.zig</code> for targeting iOS.</li>
<li><a>ynuwenhof/zigbraten</a> - Proof of concept internal cheat for Cube 2: Sauerbraten.</li>
<li><a>vbrusca/ZigSdlGameTemplate</a> - SDL game project template.</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/94020660?v=4 | cosmic | fubark/cosmic | 2021-11-09T22:41:16Z | A platform for computing and creating applications. | master | 17 | 355 | 16 | 355 | https://api.github.com/repos/fubark/cosmic/tags | MIT | [
"3d",
"graphics",
"opengl",
"ui",
"vulkan",
"wasm",
"zig"
]
| 16,740 | false | 2025-05-18T05:32:24Z | true | false | unknown | github | []
| <a></a>
<a></a>
Cosmic
The goals for Cosmic is changing and the project description will be updated soon. In the meantime, check out the <a>graphics</a> and <a>ui</a> zig libraries with examples.
Progress
<ul>
<li>Cosmic Web (<em>In progress.</em>)</li>
<li>Cosmic Desktop (<em>In progress.</em>)</li>
</ul>
The following components were created during the development of Cosmic.
- 2D/3D Graphics (<a>Source</a>)
- UI and animation framework (<a>Source</a>)
- Cyber language and compiler (<a>Source</a>)
- JavaScript runtime (<a>Source</a>.
- V8 bindings (<a>Source</a>)
- Incremental AST parser and tokenizer. (<a>Source</a>)
Scripting
<a>Cyber</a> will be the primary scripting language used in Cosmic.
The engine will be language agnostic, allowing interop with other languages.
Contributing
We will be building the app primarily in Zig.
<a>Why Zig When There is Already C++, D, and Rust?</a>
Zig's toolchain is ideal for this project. Even though it has yet to reach 1.0, it's LLVM backend is stable and stage2 is just around the corner.
There is a lot to be done! If you find the project interesting, consider submitting a PR. A good way to start is to submit or repond to an existing Github Issue. Please star the repo and let's do this!
If you have questions or suggestions, submit an issue or join the discord for more direct discourse.
License
Cosmic is free and open source under the MIT License. | []
|
https://avatars.githubusercontent.com/u/4776412?v=4 | zig-protobuf | Arwalk/zig-protobuf | 2021-04-30T16:11:03Z | a protobuf 3 implementation for zig. | master | 20 | 299 | 39 | 299 | https://api.github.com/repos/Arwalk/zig-protobuf/tags | MIT | [
"protobuf",
"zig",
"zig-package"
]
| 791 | false | 2025-05-17T13:49:31Z | true | true | 0.14.0 | github | []
| zig-protobuf
Welcome!
This is an implementation of google Protocol Buffers version 3 in Zig.
Protocol Buffers is a serialization protocol so systems, from any programming language or platform, can exchange data reliably.
Protobuf's strength lies in a generic codec paired with user-defined "messages" that will define the true nature of the data encoded.
Messages are usually mapped to a native language's structure/class definition thanks to a language-specific generator associated with an implementation.
Zig's compile-time evaluation becomes extremely strong and useful in this context: because the structure (a message) has to be known beforehand, the generic codec can leverage informations, at compile time, of the message and it's nature. This allows optimizations that are hard to get as easily in any other language, as Zig can mix compile-time informations with runtime-only data to optimize the encoding and decoding code paths.
State of the implementation
This repository, so far, only aims at implementing <a>protocol buffers version 3</a>.
The latest version of the zig compiler used for this project is 0.14.0.
This project is currently able to handle all scalar types for encoding, decoding, and generation through the plugin.
Branches
There are 2 branches you can use for your development.
<ul>
<li><code>master</code> is the branch with current developments, working with the latest stable release of zig.</li>
<li><code>zig-master</code> is a branch that merges the developments in master, but works with the latest-ish master version of zig. </li>
</ul>
How to use
<ol>
<li>Add <code>protobuf</code> to your <code>build.zig.zon</code>.
<code>sh
zig fetch --save "git+https://github.com/Arwalk/zig-protobuf#v2.0.0"</code></li>
<li>Use the <code>protobuf</code> module. In your <code>build.zig</code>'s build function, add the dependency as module before
<code>b.installArtifact(exe)</code>.
```zig
pub fn build(b: *std.Build) !void {
// first create a build for the dependency
const protobuf_dep = b.dependency("protobuf", .{
.target = target,
.optimize = optimize,
});
<code>// and lastly use the dependency as a module
exe.root_module.addImport("protobuf", protobuf_dep.module("protobuf"));
</code>
}
```
</li>
</ol>
Generating .zig files out of .proto definitions
You can do this programatically as a compilation step for your application. The following snippet shows how to create a <code>zig build gen-proto</code> command for your project.
```zig
const protobuf = @import("protobuf");
pub fn build(b: *std.Build) !void {
// first create a build for the dependency
const protobuf_dep = b.dependency("protobuf", .{
.target = target,
.optimize = optimize,
});
<code>...
const gen_proto = b.step("gen-proto", "generates zig files from protocol buffer definitions");
const protoc_step = protobuf.RunProtocStep.create(b, protobuf_dep.builder, target, .{
// out directory for the generated zig files
.destination_directory = b.path("src/proto"),
.source_files = &.{
"protocol/all.proto",
},
.include_directories = &.{},
});
gen_proto.dependOn(&protoc_step.step);
</code>
}
```
If you're really bored, you can buy me a coffe here.
<a></a> | []
|
https://avatars.githubusercontent.com/u/96174566?v=4 | sdk | TinyVG/sdk | 2021-12-18T16:43:10Z | TinyVG software development kit | main | 16 | 281 | 16 | 281 | https://api.github.com/repos/TinyVG/sdk/tags | MIT | [
"sdk",
"tinyvg",
"vector-graphics",
"zig",
"zig-package"
]
| 107 | false | 2025-05-08T22:29:59Z | true | true | unknown | github | [
{
"commit": "03af1b6c5bfda9646a562c861055024daed5b238.tar.gz",
"name": "args",
"tar_url": "https://github.com/ikskuh/zig-args/archive/03af1b6c5bfda9646a562c861055024daed5b238.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ikskuh/zig-args"
},
{
"commit": "9349d087a3216ebea27cc99b5b4bd8affe234816.tar.gz",
"name": "ptk",
"tar_url": "https://github.com/ikskuh/parser-toolkit/archive/9349d087a3216ebea27cc99b5b4bd8affe234816.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ikskuh/parser-toolkit"
}
]
| TinyVG Software Development Kit
This SDK enables you to work with the <a>TinyVG</a> vector graphics format.
Contents
<ul>
<li>Native Library (C ABI)</li>
<li>Zig Package</li>
<li>Command Line Tooling</li>
<li>Offline Rendering (TVG -> TGA)</li>
<li>Format Conversion (SVG <-> TVG <-> TVGT)</li>
</ul>
Building
The SDK is implemented with <a>Zig</a> 0.11.0 and <a>dotnet 6</a>.
To build the SDK (except <code>svg2tvgt</code>), do this:
<code>sh-session
[user@host sdk]$ zig build
[user@host sdk]$</code>
This will then produce the folders <code>zig-cache</code> (for temporary files) and <code>zig-out</code>, which contains the SDK files for your current platform.
To build <code>svg2tvgt</code>, go into the folder <code>src/tools/svg2tvgt</code> and do this:
```sh-session
[user@host sdk]$ cd src/tools/svg2tvgt/
[user@host svg2tvgt]$ dotnet build
MSBuild version 17.3.2+561848881 for .NET
Determining projects to restore...
All projects are up-to-date for restore.
svg2tvgt -> /mnt/src/tools/svg2tvgt/bin/Debug/net6.0/svg2tvgt.dll
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:00.69
[user@host svg2tvgt]$
```
This will then produce <code>src/tools/svg2tvgt/bin/Debug/net5.0/svg2tvgt</code> (or <code>.exe</code> if you are on windows). | []
|
https://avatars.githubusercontent.com/u/1519747?v=4 | zig-yaml | kubkon/zig-yaml | 2021-05-31T20:06:47Z | YAML parser for Zig | main | 18 | 230 | 51 | 230 | https://api.github.com/repos/kubkon/zig-yaml/tags | MIT | [
"yaml",
"zig",
"zig-library"
]
| 307 | false | 2025-05-19T20:35:17Z | true | true | unknown | github | []
| zig-yaml
YAML parser for Zig
What is it?
This lib is meant to serve as a basic (or maybe not?) YAML parser for Zig. It will strive to be YAML 1.2 compatible
but one step at a time.
This is very much a work-in-progress, so expect things to break on a regular basis. Oh, I'd love to get the
community involved in helping out with this btw! Feel free to fork and submit patches, enhancements, and of course
issues.
Basic installation
The library can be installed using the Zig tools. First, you need to fetch the required release of the library into your project.
<code>zig fetch --save https://github.com/kubkon/zig-yaml/archive/refs/tags/[RELEASE_VERSION].tar.gz</code>
It's more convenient to save the library with a desired name, for example, like this (assuming you are targeting latest release of Zig):
<code>zig fetch --save=yaml https://github.com/kubkon/zig-yaml/archive/refs/tags/0.1.1.tar.gz</code>
And then add those lines to your project's <code>build.zig</code> file:
<code>// add that code after "b.installArtifact(exe)" line
const yaml = b.dependency("yaml", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("yaml", yaml.module("yaml"));</code>
After that, you can simply import the zig-yaml library in your project's code by using <code>const yaml = @import("yaml");</code>.
For zig-0.14, please use any release after <code>0.1.0</code>. For pre-zig-0.14 (e.g., zig-0.13), use <code>0.0.1</code>.
Basic usage
The parser currently understands a few YAML primitives such as:
* explicit documents (<code>---</code>, <code>...</code>)
* mappings (<code>:</code>)
* sequences (<code>-</code>, <code>[</code>, <code>]</code>)
In fact, if you head over to <code>examples/</code> dir, you will find YAML examples that have been tested against this
parser. You can also have a look at end-to-end test inputs in <code>test/</code> directory.
If you want to use the parser as a library, add it as a package the usual way, and then:
```zig
const std = @import("std");
const Yaml = @import("yaml").Yaml;
const gpa = std.testing.allocator;
const source =
\names: [ John Doe, MacIntosh, Jane Austin ]
\numbers:
\ - 10
\ - -8
\ - 6
\nested:
\ some: one
\ wick: john doe
\finally: [ 8.17,
\ 19.78 , 17 ,
\ 21 ]
;
var yaml: Yaml = .{ .source = source };
defer yaml.deinit(gpa);
```
<ol>
<li>For untyped, raw representation of YAML, use <code>Yaml.load</code>:</li>
</ol>
```zig
try yaml.load(gpa, source);
try std.testing.expectEqual(untyped.docs.items.len, 1);
const map = untyped.docs.items[0].map;
try std.testing.expect(map.contains("names"));
try std.testing.expectEqual(map.get("names").?.list.len, 3);
```
<ol>
<li>For typed representation of YAML, use <code>Yaml.parse</code>:</li>
</ol>
```zig
const Simple = struct {
names: []const []const u8,
numbers: []const i16,
nested: struct {
some: []const u8,
wick: []const u8,
},
finally: [4]f16,
};
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit();
const simple = try yaml.parse(arena.allocator(), Simple);
try std.testing.expectEqual(simple.names.len, 3);
```
<ol>
<li>To convert <code>Yaml</code> structure back into text representation, use <code>Yaml.stringify</code>:</li>
</ol>
<code>zig
try yaml.stringify(std.io.getStdOut().writer());</code>
which should write the following output to standard output when run:
<code>sh
names: [ John Doe, MacIntosh, Jane Austin ]
numbers: [ 10, -8, 6 ]
nested:
some: one
wick: john doe
finally: [ 8.17, 19.78, 17, 21 ]</code>
Error handling
The library currently reports user-friendly, more informative parsing errors only which are stored out-of-band.
They can be accessed via <code>Yaml.parse_errors: std.zig.ErrorBundle</code>, but typically you would only hook them up to
your error reporting setup.
For example, <code>example/yaml.zig</code> binary does it like so:
```zig
var yaml: Yaml = .{ .source = source };
defer yaml.deinit(allocator);
yaml.load(allocator) catch |err| switch (err) {
error.ParseFailure => {
assert(yaml.parse_errors.errorMessageCount() > 0);
yaml.parse_errors.renderToStdErr(.{ .ttyconf = std.io.tty.detectConfig(std.io.getStdErr()) });
return error.ParseFailure;
},
else => return err,
};
```
Running YAML spec test suite
Remember to clone the repo with submodules first
<code>sh
git clone --recurse-submodules</code>
Then, you can run the test suite as follows
<code>sh
zig build test -Denable-spec-tests</code>
See also <a>issue #48</a> for a meta issue tracking failing spec tests.
Any test that you think of working on and would like to include in the spec tests (that was previously skipped), can be removed from the skipped tests lists in https://github.com/kubkon/zig-yaml/blob/b3cc3a3319ab40fa466a4d5e9c8483267e6ffbee/test/spec.zig#L239-L562 | []
|
https://avatars.githubusercontent.com/u/82044447?v=4 | getty | getty-zig/getty | 2021-04-06T14:54:07Z | A (de)serialization framework for Zig | main | 13 | 221 | 13 | 221 | https://api.github.com/repos/getty-zig/getty/tags | MIT | [
"getty",
"serialization",
"zig",
"ziglang"
]
| 158,506 | false | 2025-05-12T09:25:43Z | true | true | unknown | github | [
{
"commit": "e7a9bc39c213985814a904b38e4506a6fbd537b2.tar.gz",
"name": "protest",
"tar_url": "https://github.com/ibokuri/protest/archive/e7a9bc39c213985814a904b38e4506a6fbd537b2.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ibokuri/protest"
}
]
| Getty
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
Getty is a framework for building <strong>robust</strong>, <strong>optimal</strong>, and <strong>reusable</strong> (de)serializers in Zig.
<ul>
<li>Compile-time (de)serialization.</li>
<li>Out-of-the-box support for a variety of <code>std</code> types.</li>
<li>Granular customization for existing and remote types.</li>
<li>Data models that serve as simple and generic baselines for (de)serializers.</li>
</ul>
Quick Start
<code>build.zig</code>
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const opts = .{ .target = target, .optimize = optimize };
const json_mod = b.dependency("json", opts).module("json");
const exe = b.addExecutable(.{
.name = "quick-start",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
exe.addModule("json", json_mod);
const run_cmd = b.addRunArtifact(exe);
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
```
<code>build.zig.zon</code>
```zig
.{
.name = "quick-start",
.version = "0.1.0",
.paths = .{""},
.dependencies = .{
.json = .{
.url = "https://github.com/getty-zig/json/archive/3e3cf7b.tar.gz",
.hash = "122017ccb426b5f5690fdda438134852e940796b0ac619eb2648782a7879146f4fcd",
},
},
}
```
<code>src/main.zig</code>
```zig
const std = @import("std");
const json = @import("json");
const ally = std.heap.page_allocator;
const Point = struct {
x: i32,
y: i32,
};
pub fn main() !void {
const value = Point{ .x = 1, .y = 2 };
// Serialize a Point value into JSON.
const serialized = try json.toSlice(ally, value);
defer ally.free(serialized);
// Deserialize JSON data into a Point value.
const deserialized = try json.fromSlice(ally, Point, serialized);
// Print results.
std.debug.print("{s}\n", .{serialized}); // {"x":1,"y":2}
std.debug.print("{}\n", .{deserialized}); // main.Point{ .x = 1, .y = 2 }
}
```
Installation
<ol>
<li>
Declare Getty as a project dependency with <code>zig fetch</code>:
<code>sh
zig fetch --save git+https://github.com/getty-zig/getty.git#<COMMIT></code>
</li>
<li>
Expose Getty as a module in your project's <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const opts = .{ .target = target, .optimize = optimize }; // 👈
const getty_mod = b.dependency("getty", opts).module("getty"); // 👈
const exe = b.addExecutable(.{
.name = "my-project",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("getty", getty_mod); // 👈
// ...
</code>
}
```
</li>
<li>
Import Getty into your code:
<code>zig
const getty = @import("getty");</code>
</li>
</ol>
Resources
<ul>
<li><a>Website</a></li>
<li><a>Tutorial</a></li>
<li><a>Examples</a></li>
<li><a>API Reference</a></li>
<li><a>Contributing</a></li>
</ul> | [
"https://github.com/Cloudef/zig-router",
"https://github.com/getty-zig/json"
]
|
https://avatars.githubusercontent.com/u/919553?v=4 | ziglyph | jecolon/ziglyph | 2021-03-11T23:46:13Z | Unicode text processing for the Zig programming language. | main | 0 | 211 | 7 | 211 | https://api.github.com/repos/jecolon/ziglyph/tags | - | [
"characters",
"collation",
"display-width",
"grapheme-cl",
"normalization",
"segmentation",
"strings",
"unicode",
"utf-8",
"word-wrap",
"zig"
]
| 34,328 | false | 2025-04-28T11:42:11Z | false | false | unknown | github | []
| ziglyph
ziglyph is now at: https://codeberg.org/dude_the_builder/ziglyph | [
"https://github.com/dgv/play.zig",
"https://github.com/ikskuh/TextEditor",
"https://github.com/natecraddock/zf"
]
|
https://avatars.githubusercontent.com/u/76228776?v=4 | DOOM-fire-zig | const-void/DOOM-fire-zig | 2022-01-15T22:56:25Z | DOOM's fire algo, in zig, for 256 color terminals w/no dependencies | master | 1 | 194 | 21 | 194 | https://api.github.com/repos/const-void/DOOM-fire-zig/tags | GPL-3.0 | [
"256-color",
"doom",
"xterm",
"zig"
]
| 87 | false | 2025-05-14T17:00:31Z | true | true | 0.14.0 | github | []
| DOOMFIRE
Test your TTY's might!
https://user-images.githubusercontent.com/76228776/149635702-a331f892-7799-4f7f-a4a6-7048d3529dcf.mp4
The doom-fire algo can push upwards of 180k a frame - results may vary! It is, to my surprise, a nice TTY stress test.
As a comparison, this is the younger sibling of a node variant ( https://github.com/const-void/DOOM-fire-node ).
INSTALL
<code>$ git clone https://github.com/const-void/DOOM-fire-zig/
$ cd DOOM-fire-zig
$ zig build run
...</code>
Build Requirements:
* all platforms - libc
* all platforms - x64 (for now)
* windows - kernel32
Merge Request (MR) Validation:
* Each MR tested on MacOS Sequia 15.3 / M1 w/zig 0.14 on MacOS Kitty, VS Code, Alacritty.
* Many MR tested on Windows 10 / Intel, with Microsoft Terminal, CMD.EXE, PowerShell.
* Linux tests are c/o the wonderful community who help identify...and repair...cross platform issues!
Results
Start your favorite terminal, maximize it, then launch DOOM-fire-zig! Test your terminal's might.
| Terminal | Linux | MacOS | Windows |
| ------------------ | ------ | ------------ | ---------------- |
| Alacritty | great? | great | very poor (4pfs) |
| Apple Terminal.app | - | poor (? fps) | - |
| CMD.EXE | - | - | poor (20fps) |
| iterm.app | - | ok | - |
| kitty.app | - | great | - |
| Microsoft Terminal | - | - | great |
| Powershell | - | - | poor (20fps) |
| VS Code | great | great | poor (20fps) |
| Warp | great? | great | - |
| WezTerm | ? | ? | ok |
Definitions
```
<= 5 avg fps = very poor
<= 24 avg fps = poor
... avg fps = ok
<blockquote>
= 100 avg fps = great
```
</blockquote>
Microsoft Note
It appears Windows terminal performance is a function of the underlying console; when a terminal is using the default Microsoft console, such as used by CMD.EXE, Windows fps appears to be gated.
MacOS / Apple Note
The default MacOS / Apple terminal reports an avg 30-40 fps, however visually, it appears to be drop frames, resulting in a very choppy effect.
Results are for fun
As our approach is unscientific, we only indicate avg fps for underpeformers, to set expectations; results will vary based on - os+platform, GPU, terminal size (function of font size, monitor resolution, zoom %, etc), specific terminal configuration, terminal version -- even zig itself is a factor.
We don't test every terminal with each merge request; the majority come from the community. One report is enough! This is for fun, to encourage terminals to be great out-of-the-box, and us to learn - to explore what our terminals can do, and share configuration that gives fps a boost (at potential cost elsewhere...).
180kb a frame at 100+fps is...great!!! Amazing.
Inspiration / Credits
<ul>
<li>
Thanks to contributors for your support!
</li>
<li>
doom fire - https://github.com/filipedeschamps/doom-fire-algorithm, https://github.com/fabiensanglard/DoomFirePSX/blob/master/flames.html
</li>
<li>color layout - https://en.wikipedia.org/wiki/ANSI_escape_code</li>
<li>ansi codes - http://xfree86.org/current/ctlseqs.html</li>
<li>str, zig - https://www.huy.rocks/everyday/01-04-2022-zig-strings-in-5-minutes</li>
<li>emit - https://zig.news/kristoff/where-is-print-in-zig-57e9</li>
<li>term sz, zig - https://github.com/jessrud/zbox/blob/master/src/prim.zig</li>
<li>osx term sz - https://github.com/sindresorhus/macos-term-size/blob/main/term-size.c</li>
<li>px char - https://github.com/cronvel/terminal-kit</li>
</ul>
Repo Guidance
Find the list of releases here: https://github.com/const-void/DOOM-fire-zig/releases
* YYYY.<#> Zig #.##
Find the list of branches here: https://github.com/const-void/DOOM-fire-zig/branches
* master -- the most recent 'working' code base; tries to be compatible with latest released stable zig version.
* zig-#.## -- compatible with specific zig release (two active - current and future)...historical zig versions will be stale.
* -zig-#.##- -- branches associated with resolving a reported issue.
Branch and Merge Request Detail
Repository guidance is a bit like the Pirate's Code. More akin to a set of guidelines, really.
This repo has been around since 2022, and as zig has changed, so has repository philosophy, from YOLO/anything goes, to a bit more discipline, primarily for clarity for contributions; over the years we have learned that the precise version of zig version is <em>everything</em>.
From build, to std, to language feature.
Later zig versions tend to break compatibility vs prior zig versions; as a result, the precise zig version becomes very important, as the most recent zig version often requires code that simply won't build in prior versions
IMPACT: Repository branching is to tied to zig version.
Repository intention is for compatibility with two zig versions - one branch for current "stable" zig version, as well as a branch for future development version of zig.
Back porting updates from DOOM-fire-zig / zig.current to zig.prior is too time consuming, the juice isn't worth the squeeze. However, starting with zig-0.13, repository philosophy will enable adventurers into this domain!
Branches are as follows:
* zig-0.13: historical
* zig-0.14: zig current version
* zig-0.15: zig dev version
Ultimately, the time and attention of a contributor is most important.
Always, submit a merge request and the particulars can be sorted out at the point of merge. This whole repository is for fun, so the intention is to keep guidance light-weight and easy.
How to submit a merge request
Each zig version has it's own branch; the stable version of zig will be merged with main aka master; once a given merge with main has proven it's stability, it will get released to mark the commits as a point in time.
To fix an issue or add enhancement, in github, please fork the home repository into your own github identity. From there, checkout the relevant zig branch from your fork, make your updates, commit back to your repo. When you are happy, please submit your merge request back to this repository, requesting a merge with the relevant zig version.
<code>zsh
$ git clone https://github.com/<your-github-id>/DOOM-fire-zig/
$ cd DOOM-fire-zig
$ zig build run
$ git checkout zig-0.##
$ ... code ...
$ git commit -m "<semantic commit>"</code>
zig.current to zig.future
After a merge to zig.current branch, after some testing, I will periodically merge with main and zig.future. At some point in the next ten+ years, main and zig.future will be more similar than not!
Github Releases Detail
Releases are used to identify a 'moment in time' snapshot. Release tags are tied to the year so you can compare your local workstation file timestamps to the release tag and have a general picture of how long it has been since you have cloned/fetched/pulled etc.
Releases are created for the current version of zig, for clarity.
<ul>
<li>DOOM-Fire-zig endeavors to be updated at least annually, usually around a holiday when I have time.</li>
<li>Releases and tags are "snapshots" in time of the code base/repo, a way to plumb the history and depths of time, as DOOM-Fire-zig iterates and evolves across zig updates. </li>
<li>Each annual update will have a tag of YYYY.1, with subsequent tags incrementing the "minor" indicator -> YYYY.2, YYYY.3. </li>
<li>Each tag will have a release associated with it. The release name will be YYYY.x Zig #.## - Major Feature</li>
</ul>
License
Copyright 2022-2025, const-void, released under GPL3.
DOOM-fire-zig is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/. | []
|
https://avatars.githubusercontent.com/u/34946442?v=4 | bio | cryptocode/bio | 2021-04-08T17:25:25Z | A Lisp dialect written in Zig | main | 1 | 191 | 1 | 191 | https://api.github.com/repos/cryptocode/bio/tags | MIT | [
"lisp",
"scheme",
"zig"
]
| 1,339 | false | 2025-05-16T00:30:21Z | true | false | unknown | github | []
|
<em>The project is in the early stages of development. To discuss all things Bio and get help with issues, feel free to join the <a>Discord</a></em>
Bio is a Lisp dialect similar to Scheme, with some novel features like environment expressions which enable capabilities like modules and composite types.
Features include macros, garbage collection, error handling, a module facility, destructuring, and a standard library.
Example:
```scheme
(filter
(quicksort '(5 40 1 -3 2) <)
(lambda (x) (>= x 0)))
(1 2 5 40)
```
The core of Bio is lambda expressions, from which the standard library builds syntax like <code>type</code> and <code>fun</code>:
<code>``scheme
; Create a composite type. This is sugar for</code>(var Point (lambda (x y) ... (self)))`
(type Point (x y)
(fun area () (* x y)))
; Make an instance of Point
(var pt (Point 5 7))
; Call a member function. All this is just syntax sugar based on a lambda
; returning its own environment.
(print "Area:" (pt (area)) '\n)
Area: 35
```
<em>The language and its documentation is work in progress. For up-to-date examples, I recommend studying <code>std.lisp</code>, <code>test.lisp</code> and the files in the <code>examples</code> directory.</em>
Table of Contents
<ul>
<li><a>Building and running</a><ul>
<li><a>Running tests</a></li>
</ul>
</li>
<li><a>Language Reference</a><ul>
<li><a>Naming conventions</a></li>
<li><a>Intrinsics</a><ul>
<li><a>nil</a></li>
<li><a>#t and #f</a></li>
<li><a>#! and #value</a></li>
<li><a>typename</a></li>
<li><a>number? symbol? list? bool? callable? error?</a></li>
<li><a>var and define</a></li>
<li><a>vars</a></li>
<li><a>set! and unset!</a></li>
<li><a>arithmetic functions</a></li>
<li><a>equality</a></li>
<li><a>order</a></li>
<li><a>env and gc</a></li>
<li><a>fun, lambda and λ</a></li>
<li><a>type</a></li>
<li><a>macro</a></li>
<li><a>macroexpand</a></li>
<li><a>self and environment lookups</a></li>
<li><a>&rest</a></li>
<li><a>quote</a></li>
<li><a>quasiquote</a></li>
<li><a>unquote</a></li>
<li><a>unquote-splicing</a></li>
<li><a>eval</a></li>
<li><a>apply</a></li>
<li><a>gensym</a></li>
<li><a>if</a></li>
<li><a>cond</a></li>
<li><a>loop</a></li>
<li><a>begin</a></li>
<li><a>try</a></li>
<li><a>error</a></li>
<li><a>print</a></li>
<li><a>as</a></li>
<li><a>list</a></li>
<li><a>append</a></li>
<li><a>range</a></li>
<li><a>len</a></li>
<li><a>string</a></li>
<li><a>import</a></li>
<li><a>assert</a></li>
<li><a>exit</a></li>
<li><a>debug-verbose</a></li>
<li><a>math.pi and math.e</a></li>
<li><a>math.floor</a></li>
<li><a>string.split</a></li>
</ul>
</li>
<li><a>Standard library</a><ul>
<li><a>car, cdr, caar, cadr, cddr, caddr, last, nth</a></li>
<li><a>cons</a></li>
<li><a>nil?</a></li>
<li><a>atom?</a></li>
<li><a>bool?</a></li>
<li><a>relational functions</a></li>
<li><a>logical functions</a></li>
<li><a>let macro</a></li>
<li><a>filter</a></li>
<li><a>map</a></li>
<li><a>quicksort</a></li>
<li><a>while macro</a></li>
<li><a>list.iterate and each</a></li>
<li><a>reduce-with</a></li>
<li><a>each-pair</a></li>
<li><a>matrix functions</a></li>
<li><a>hashmap</a></li>
<li><a>io.read-number</a></li>
<li><a>typename</a></li>
<li><a>time.now</a></li>
<li><a>double-quote</a></li>
<li><a>inc! and dec!</a></li>
<li><a>file i/o and stdin/stdout</a></li>
<li><a>math.odd? math.even? odd-items and even-items</a></li>
<li><a>math.abs</a></li>
<li><a>math.pow</a></li>
<li><a>math.average</a></li>
<li><a>math.sqrt</a></li>
<li><a>math.safe-div</a></li>
<li><a>math.make-random-generator and math.random-list</a></li>
<li><a>math.fib and math.fact</a></li>
<li><a>Y</a></li>
</ul>
</li>
<li><a>Modules</a><ul>
<li><a>Module example</a></li>
</ul>
</li>
</ul>
</li>
</ul>
Building and running
Clone the repository and cd to the root directory.
Bio currently targets Zig v13.0
<strong>Build</strong>
<code>bash
zig build</code>
<strong>Run the REPL:</strong>
<code>bash
zig-out/bin/bio</code>
<strong>Run a Bio source file:</strong>
<code>bash
zig-out/bin run examples/triangles.lisp</code>
You can also use <code>import</code> to evaluate files from the REPL, e.g. <code>(import "examples/albums.lisp")</code>
Running tests
The test suite in <code>test.lisp</code> can be evaluated with <code>zig test src/main.zig</code> or <code>./bio run test.lisp</code>
Language Reference
A Bio program consists of one or more s-expressions. An s-expression is recursively defined as being either
<ol>
<li>an atom</li>
<li>a list, which may contain lists and atoms</li>
</ol>
An atom is either a 64-bit floating point number, or a symbol. A symbol is any sequence of utf8 code points that is not a valid number. Symbols serve as strings when the symbol is enclosed in double-quotes, such as <code>"This is a symbol"</code>. Bio does not have a separate string type; the term string is simply used to denote a symbol serving as a string.
Naming conventions
<ul>
<li>Predicates have a question mark suffix, such as <code>atom?</code></li>
<li>Destructive actions have an exclamation point suffix, such as <code>set!</code></li>
<li>Sentinels are prefixed with an ampersand, such as <code>&rest</code></li>
<li>Symbols with special meaning are prefixed <code>#</code>, such as <code>#t</code></li>
<li>Identifiers are kebab-case, while composite types such as modules are PascalCase</li>
</ul>
Intrinsics
Intrinsics are built-in functions, macros, and symbols implemented by the interpreter. They are building blocks for the standard library and user programs.
nil
A symbol representing the absence of a value. Note that <code>nil</code> and <code>'()</code> are considered equal.
#t and #f
Symbols representing true and false, respectively. Note that <code>nil</code> coerces to <code>#f</code>.
#?
A symbol representing the last top-level expression evaluation.
Example:
<code>scheme
(+ 2 3)
(* 2 #?)
10</code>
#! and #value
The <code>#value</code> symbol contains the value returned by a <em>tried</em> expression. This usually removes the need to use a temporary variable when you need to both check for errors <em>and</em> use the result.
The <code>#!</code> symbol contains the error after a <code>try</code> expression. If no error occurs, this is set to <code>nil</code>.
<code>(try (math.safe-div (io.read-number) (io.read-number))
(print "The doubled result is: " (* 2 #value))
(print "Failed: " #!))</code>
typename
The 'typename' functions returns a string representation of the type. The most specific classification is returned, so <code>(typename #t)</code> is "bool", even though #t is also a symbol.
```scheme
(typename 'a)
"symbol"
(typename math.pi)
"number"
(typename #t)
"bool"
(typename '(a b c))
"list"
(typename +)
"function"
```
number? symbol? list? bool? callable? error?
Predicates to determine expression types. There's also an <code>atom?</code> predicate in the standard library.
These all return #t
<code>scheme
(number? -5.7)
(number? x)
(symbol? 'x)
(symbol? #t)
(bool? #t)
(bool? #f)
(list? '(abc))
(callable? +)
(error? (math.safe-div 4 0))</code>
var and define
'var' creates a variable binding in the <em>current</em> environment. The binding will fail if it already exists in the current environment. The <code>define</code> function is just an alias to <code>var</code>
Variable names can be any utf8 sequence that doesn't start with a number, " and '. Variable names are case-sensitive.
<code>scheme
(var x 5)
(define y 5)
(var name (io.read-line))
(var double (lambda (val) (* 2 val)))
(var 😀 "Smiley")
(print 😀)
"Smiley"</code>
Local variables:
```scheme
(var x 2)
(var y 2)
(var z 2)
(var some-function (lambda (x)
<code>; Allowed, y is not in the local scope
(var y 10)
; Not allowed, x is a formal in the same scope
; (var x 10)
(print x y z)
</code>
))
<blockquote>
(some-function 3)
3 10 2
```
</blockquote>
vars
A list can be destructured into variables using <code>vars</code>
<code>scheme
(var stuff '(1 2 3))
(vars a b c stuff)
(assert (= a 1))
(assert (= b 2))
(assert (= c 3))</code>
set! and unset!
Changes the value of an existing binding (values themselves are immutable). The binding is searched from current to root scope.
```scheme
; Define x, then update it
(var x 5)
(set! x 10)
; Be evil and redefine + to mean -
(set! + -)
(+ 10 2)
8
; Remove binding, allowing it to be defined again
(unset! x)
(var x 'hey)
```
You can optionally pass a specific environment for the binding being set as the first argument:
```scheme
(type Point (x y)
(fun area () (* x y)))
(var pt (Point 5 7))
(print "Area:" (pt (area)) '\n)
Area: 35
; Change x by passing the pt environment to set!
(set! pt x 6)
(print "Area:" (pt (area)) '\n)
Area: 42
```
arithmetic functions
The arithmetic functions work on floating-point numbers. Unlike infix notation, any number of arguments can be given.
```scheme
(+ -3 5)
2
(/ 2 (* 10 (+ math.pi 2 3 (- 2 3))))
0.028004957675577865
; pi symbol is same as math.pi (tip: this is available with Option+P if you're on a mac)
(define circumference (λ (x) (* 2 π x)))
```
Additional math functions are available in the standard library.
equality
The <code>=</code> and <code>~=</code> functions check for exact and approximate equality. The approximate case is only for numeric operands and accepts a third argument to override the tolerance (epsilon is by default 1e-7)
<code>scheme
(= x 5)
(= '(1 2 3 4) nums)
(= '(1 3) (odd-items nums))
(~= a b 0.0005)</code>
Exact equality is implemented in terms of the <code>order</code> function, allowing nested lists to be compared.
order
The <code>order</code> function returns 0, -1, 1 do indicate if the first argument is equal, less than or greater than the second argument. All expression types are supported.
Lists are recursively compared. If list lengths differ, the shorter one is considered smaller. Empty lists and <code>nil</code> are considered equal, otherwise <code>nil</code> is always considered smaller.
```scheme
(order 100 200)
-1
(order 'def 'abc)
1
(order '(1 2 3) '(0 1 2))
1
(order '(1 2) '(0 1 2))
-1
(order 6 (* 2 3))
0
```
Standard library functions such as <code><</code> are implemented in terms of <code>order</code>.
env and gc
<code>env</code> prints the content of the current environment.
```
<blockquote>
(env)
Environment for global: Env@10db4b000
import = , env <em>Env@0
exit = , env </em>Env@0
gc = , env <em>Env@0
#f = #f, env </em>Env@0
#t = #t, env <em>Env@0
#? = #t, env </em>Env@0
nil = nil, env *Env@0
...
```
</blockquote>
The garbage collector runs periodically, though the criteria and extent are intentionally left undefined by this language reference.
fun, lambda and λ
Creating functions in Bio can be done either with <code>fun</code> or <code>lambda</code>. The <code>fun</code> function is just a convenience macro that expands to a lambda definition.
```scheme
<blockquote>
(fun square (x) (* x x))
(square 5)
25
```
</blockquote>
Below is the equivalent lambda definition:
```scheme
<blockquote>
(var square (lambda (x) (* x x)))
(square 5)
25
```
</blockquote>
Direct application without binding to a variable:
```scheme
<blockquote>
((lambda (x) (* x x)) 5)
25
```
</blockquote>
The lambda symbol can be used in place of the lambda identifier
<code>scheme
(var doubler (λ (x) (* 2 x)))</code>
A lambda invocation has its own environment, and the parent environment is the one that existed when the lambda was defined. In other words, Bio is lexically scoped.
type
A type expression is syntax sugar for functions returning their own environment. This is useful when making composite types.
```scheme
(type Point (x y)
(fun area () (* x y))
)
(var pt (Point 5 7))
(print "Area:" (pt (area)) '\n)
; Change x by passing the pt environment to set!
(set! pt x 6)
(print "Area:" (pt (area)) '\n)
```
Composite types can contain local variables and other functions, just like regular lambda expression.
macro
This function creates a macro.
Unlike lambdas, arguments are not evaluated when the macro is invoked. Instead, they're evaluated if and when the body does so. Note
that eager evaluation of macro arguments can be forced by placed <code>&eval</code> in front of the formal parameter.
When the macro is invoked, the body is evaluated. The returned expression (which represents Bio code) is then evaluated as the final result.
<code>``scheme
(var print-with-label (macro (label &rest values)</code>(print label ": " ,@values)
))
(print-with-label Primes 2 3 5 7)
Primes: 2 3 5 7
```
A macro invocation has its own environment, and the parent environment is the current one. This is different from lambdas whose parent environment is the one in which the lambda was defined.
macroexpand
You can stop the evaluation of the code returned from a macro by wrapping it in <code>macroexpand</code>
Consider a typical swap macro:
<code>scheme
(var swap (macro (a b)
`(let ((temp ,a))
(set! ,a ,b)
(set! ,b temp))))</code>
Here's a typical usage example:
```scheme
(let ((x 3) (y 7))
(swap x y)
(print "Swapped:" x y "\n")
)
Swapped: 7 3
```
But now we wanna see how the macro is expanded as code instead:
```scheme
(let ((x 5) (y 8))
(print "Macro expansion:" (macroexpand (swap x y)) "\n")
)
Macro expansion: (let ((temp x)) (set! x y) (set! y temp))
```
Of course, you can store away the expansion for later invocation, or just evaluate the expansion directly:
```scheme
(let ((x 5) (y 8))
(eval (macroexpand (swap x y)))
(print "Swapped:" x y "\n")
)
Swapped: 8 5
```
self and environment lookups
The <code>self</code> function returns the current environment as an expression. This can then be used as a function to perform lookups in that environment. This enables composite data types with their own functions, as well as modules. The distinction is purely conceptual.
A top-level <code>(self)</code> call will return the root environment as an expression:
```scheme
<blockquote>
(self)
((self) +)
((self) (+ 1 2))
3
(((self) +) 1 2)
3
```
</blockquote>
As you can see, when an environment is placed in the first position of a list, it changes which environment the following argument is looked up in.
The argument can either be a symbol, or a list which will be interpreted in the context of the new environment.
Use cases of <code>self</code> include modules, composite data types, polymorphic behavior, and enabling duck-typed interfaces/protocols.
See <a>Modules</a> for more information and an example.
&rest
A sentinel symbol causing the rest of the arguments to be delivered as a single list argument. This enables variadic functions and macros.
quote
The <code>quote</code> function and the <code>'</code> shorthand returns the argument unevaluated.
```scheme
<blockquote>
(quote a)
a
'a
a
'(a b 1 2)
(a b 1 2)
</blockquote>
```
quasiquote
The <code>quasiquote</code> function and the ` shorthand returns the argument unevaluated. Unlike <code>quote</code>, however, it allows arguments to be selectively evaluated using <code>unquote</code> and <code>unquote-splicing</code>
```scheme
; Evaluate one of the list items
<blockquote>
(quasiquote (1 2 (unquote (+ 1 2)) 4))
(1 2 3 4)
</blockquote>
; Same thing using shorthand notation
<blockquote>
`(1 2 ,(+ 1 2) 4)
(1 2 3 4)
</blockquote>
; Use unquote-splicing to make a larger list of primes:
<blockquote>
(var primes '(2 3 5 7 11 13))
`(,@primes 17 19 23)
(2 3 5 7 11 13 17 19 23)
```
</blockquote>
Quasi quotation is commonly used to make templates in macros, but it has uses in regular functions as well.
unquote
In the context of a quasiquote, evaluate the argument. The shorthand version is <code>,</code>
unquote-splicing
In the context of a quasiquote, evaluate the elements of the list and place the result in the enclosing list. The shorthand version is <code>,@</code>
eval
Evaluates all arguments, leaving the last evaluation as the result. If quote and quasiquote expressions are encountered, these are unquoted before evaluation.
```scheme
(eval '(+ 1 2))
3
(var expr '(* 2 3))
```
apply
Evaluates the given function with the given argument list. The last argument must be a list argument. Any preceding arguments are prepended to that list. This means that <code>(apply + 1 '(2 3))</code> is equivalent to <code>(apply + '(1 2 3))</code>.
```scheme
<blockquote>
(apply + 5 2 1 '(10 20))
38
(var list-of-numbers '(1 2 3 4))
(apply * list-of-numbers)
24
+
(apply #? '(5 2))
7
```
</blockquote>
Using <code>apply</code> is mostly useful when arguments are given as a list and the function at hand expects arguments to be passed individually.
gensym
Generates a unique symbol.
```scheme
<blockquote>
(gensym)
gensym_1
(gensym)
gensym_2
```
</blockquote>
if
The <code>if</code> expression evaluates the first argument. If true, then the second argument is evaluated, otherwise the third (optional) argument is evaluated. Each branch can have multiple expressions using constructs such as <code>begin</code> or <code>let</code>.
```scheme
(if (< x 10) 'Yes 'No)
(var res (if (math.odd? x) 'Odd 'Even))
```
Here's a list of if expressions from <code>examples/fizzbuzz-if.lisp</code>, none of which have an else branch:
<code>scheme
(if (= 0 x) (print "Fizz"))
(if (= 0 y) (print "Buzz"))
(if (and (!= 0 x) (!= 0 y)) (print i))</code>
cond
The <code>cond</code> expression is useful when if/else conditions lead to deep nesting. It takes a variable number of predicate/body pairs, and ends with an else clause. The else clause is <em>required</em> and consists only of the body. It must be the last entry in the cond expression.
Here's the cond expression from <code>examples/fizzbuzz-cond.lisp</code>:
<code>scheme
(cond
((and (= 0 x) (= 0 y)) (print "FizzBuzz" "\n"))
((= 0 x) (print "Fizz" "\n"))
((= 0 y) (print "Buzz" "\n"))
((print i "\n"))
)</code>
loop
The <code>loop</code> function loops from n to m, or until &break is encountered
The current iteration is optionally available in the given induction variable.
```scheme
; loops 10 times
(loop '(0 10) (print 'Hi\n))
; loops 10 times counting down
(loop '(10 0) (print 'Hi\n))
; loops 10 times, current iteration count goes into the idx variable
; the current iteration is available in the idx variable (you can call it anything)
(loop 'idx '(0 10) (print "Hi #" idx "\n"))
; loops forever until &break is encountered
(loop 'idx '() (print "Hi #" idx "\n") (if (= idx 4) &break))
```
begin
Evaluates a list of expressions and returns the last one as the result. This is useful when more than one expression needs to be evaluated, like in the branches of the <code>if</code> function:
```scheme
(if (< i 10)
(begin
(var x 5)
(set! x (+ x 1))
(print (* x 2))
)
)
12
```
try
The <code>try</code> function evaluates the first argument. If the result is not an error expression, then the second argument is evaluated (the success branch), otherwise the third argument is evaluated (the error branch). The error branch is optional (in which case <code>nil</code> will be returned; add an error branch if you want to propagate the error.)
It's often necessary to know the value of the tried expression if it succeeds. This can be done using an intermediary variable, or by looking up the <code>#value</code> symbol:
<code>scheme
(try (math.safe-div 6 2)
(if (= #value 3)
(print "As expected!\n")
)
)</code>
The error expression is available through the <code>#!</code> symbol, used here by the error branch:
<code>scheme
(try (math.safe-div 6 2)
(if (= #value 3)
(print "As expected!\n")
)
(print "Could not divide: " #!)
)</code>
A function that may fail does not have to be used in a try function:
```scheme
<blockquote>
(var res (math.safe-div x y))
3.5
(math.safe-div x 0)
Division by zero
```
</blockquote>
You can also use <code>try</code> after the fact:
```scheme
<blockquote>
(var res (math.safe-div x 0))
(try (math.safe-div 1 0) #t `(string "Not good: " ,#!))
Not good: Division by zero
```
</blockquote>
error
The <code>error</code> function creates a new error expression.
```scheme
(var fail-if-ten (lambda (x)
(if (= x 10)
(error "10 is not allowed")
#t
)
))
(try (fail-if-ten 10)
"All good"
(begin
(print "Something went terribly wrong!\n")
#!
)
)
Something went terribly wrong!
10 is not allowed
```
Notice how the <code>try</code> expression propagates the error by putting <code>#!</code> as the last expression in the error case.
Errors don't have to be symbols, any expression will do.
print
<code>print</code> prints one or more expressions separated by a space. Combine <code>print</code> with <code>string</code> if you need to print verbatim (without spaces between expressions)
```scheme
(print "What's your name?")
(var name (io.read-line))
(print "What's your age?")
(var age (as number (io.read-line)))
(print "Hi" name (if (> age 80) "... you're quite old" ""))
```
IO examples work best if you put them in a file and then use <code>(import "thename.lisp")</code> or <code>bio run thename.lisp</code>
See also the <code>io.</code> functions in the standard library.
as
The <code>as</code> function converts an expression from one type to another. If a conversion is not supported, <code>nil</code> is returned.
The target conversion is either <code>number</code>, <code>symbol</code>, or <code>list</code>.
<code>scheme
(var age (as number (io.read-line)))
(assert (= '(5) (as list 5)))
(as symbol mynumber)
(set! age (as symbol age))</code>
list
Creates a new list from its arguments. Quoting can be used to create lists without evaluating the expressions.
```scheme
<blockquote>
(var x 3)
(list 1 2 x)
(1 2 3)
'(1 2 x)
(1 2 x)
```
</blockquote>
append
Creates a new list from its arguments. List arguments are spliced into the new list.
```scheme
<blockquote>
(append '(a b c) '(d e f (g h)))
(a b c d e f (g h))
(append 'a 'b 1 2 (+ 1 2))
(a b 1 2 3)
```
</blockquote>
range
The <code>range</code> function is the building block for querying lists, and is used to build standard library functions such as <code>car</code> and <code>cdr</code>.
<ul>
<li>If called with no arguments, the first expression in a list is returned.</li>
<li>If called with one argument, a list containing the sublist from <code>start</code> to end-of-list is returned.</li>
<li>If called with two arguments, a list containing the sublist from <code>start</code> to <code>end</code> (exclusive) is returned.</li>
</ul>
Negative indices are end-of-list relative. <code>nil</code> is returned if any indices are out of range.
```scheme
<blockquote>
(var letters '(a b c d e))
(a b c d e)
(range letters)
a
(range letters -1)
(e)
(range (range letters -1))
e
(range letters 2)
(c d e)
(range letters 2 4)
(c d)
(range letters -4 -2)
(c d)
</blockquote>
```
len
The length of a list (in item count) or symbol (in bytes)
```scheme
<blockquote>
(len '(1 2 3))
3
```
</blockquote>
string
Creates a symbol by concatenating the <em>rendering</em> of its arguments.
```scheme
<blockquote>
(var message (string "The value is " x))
The value is 5
(string "An error occurred : " #!)
An error occurred : Division by zero
```
</blockquote>
import
Reads and evaluates the given file. The path can be relative or absolute.
<code>scheme
(import "examples/albums.lisp")</code>
assert
Checks if the expression evaluates to #t. If not, an error is printed and the process is terminated. Evaluates to #t if successful.
<code>scheme
(assert (= '(a b c 1 2 3) mylist))</code>
exit
Exits the process with an optional exit code (default is 0)
<code>scheme
(exit 1)</code>
debug-verbose
Toggles the verbosity flag. When on, some details are printed during evaluation, such as <code>nil</code> results and quasiquote expansions.
Math pi and e
The values of π and Euler's number respectively. The symbol <code>π</code> is an alias to <code>pi</code> in the Math module.
Math floor
Returns the largest integer less than or equal to the argument.
<code>scheme
(var math (Math))
(math (floor (math pi)))
3</code>
string.split
Given one or more delimiters, tokenizes the input symbol and produces a list of symbols.
<code>scheme
(assert (= (string.split "" ",") '()))
(assert (= (string.split "a" ",") '(a)))
(assert (= (string.split "a,b,c" ",") '(a b c)))
(assert (= (string.split "a,b,c," ",") '(a b c)))
(assert (= (string.split "a,b;c," ",;") '(a b c)))
(assert (= (string.split " " ",") (list " ")))</code>
Standard library
The standard library is a file called <code>std.lisp</code> that's loaded and evaluated when the interpreter starts.
car, cdr, caar, cadr, cddr, caddr, last, nth
These functions treat a list as pairs in the classical Lisp sense. <code>car</code> returns the first list item, while <code>cdr</code> returns the rest of the list. <code>last</code> returns the last list item.
```scheme
(var nums '(1 2 3 4))
(assert (= 1 (car nums)))
(assert (= 2 (cadr nums)))
(assert (= 3 (caddr nums)))
(assert (= 4 (last nums)))
(assert (= 3 (nth 2 nums)))
(assert (nil? (nth 100 nums)))
```
cons
Prepends an item to a list:
```scheme
<blockquote>
(cons 'a '(b c))
(a b c)
</blockquote>
```
nil?
True if the argument is <code>nil</code> or an empty list.
atom?
True if the argument is a number or a symbol (in other words, not a list)
bool?
True if the argument is <code>#t</code> or <code>#f</code>
relational functions
The relation functions are <code><=</code>, <code><</code>, <code>></code>, <code>>=</code>, <code>!=</code> in addition to the intrinsic <code>=</code>
logical functions
The <code>and</code> and <code>or</code> macros perform the usual shortcut evaluation. The <code>not</code> function checks if the argument is false. If so, the result is then <code>#t</code>, otherwise it's <code>#f</code>
let macro
Local bindings can be created with a <code>lambda</code> expression. If the only reason to create a lambda is to have local variables, then the <code>let</code> macro is more convenient.
```scheme
(var x 10)
(var y 20)
(let ((x 5) (y 6))
(+ x y)
)
11
```
filter
Filters a list.
```scheme
<blockquote>
(filter (lambda (x) (< x 5)) '(3 9 5 8 2 4 7))
(3 2 4)
```
</blockquote>
map
Applies a function over one or more lists.
```scheme
; Create a list of sums taking operands from three lists
<blockquote>
(map + '(0 2 5) '(1 2 3) '(1 2 3))
(2 6 11)
</blockquote>
; Double every element in a list
<blockquote>
(map (λ (x) (* 2 x)) '(1 2 3))
(2 4 6)
</blockquote>
; A list of pairs with the order reversed
<blockquote>
(map (λ (x y) (list y x)) '(a b c) '(1 2 3))
((1 a) (2 b) (3 c))
```
</blockquote>
quicksort
Sorts a list using the supplied comparator function. The following example sorts the same list in ascending and descending order by passing <code><</code> and <code>></code> as the comparator functions. In the ascending example, we also filter out negative numbers:
```scheme
<blockquote>
(filter
(quicksort '(5 40 1 -3 2) <)
(λ (x) (>= x 0)))
(1 2 5 40)
(quicksort '(5 40 1 -3 2) >)
(40 5 2 1 -3)
</blockquote>
```
You can also pass a lambda to do your own ordering. See the <strong>albums</strong> example file for an example of doing this to sort albums.
while macro
Expands to a tail-recursive function running a body while the predicate holds:
<code>scheme
(while (< c 10000000)
(print "Value is now " c "\n")
(inc! c)
)</code>
list.iterate and each
The <code>list.iterate</code> function allows for convenient iteration of lists. The first argument is a list. The second argument is a function that's called for every item in the list, with the item as an argument. <code>each</code> is an alias to this function.
```scheme
; Print all numbers
(each lots-of-numbers print)
; Create a new list of numbers, with double the values
(var result '())
(each nums (lambda (item)
(set! result (append result (* 2 item)))
))
(2 4 6 8 10 12)
```
reduce-with
Signature: <code>(reduce-with initial fn op list)</code>
Calls <code>op</code> on every item in <code>list</code>, but only after applying the function <code>fn</code> to the item.
```scheme
(reduce-with 0 (lambda (x) (+ x 1)) + '(1 2 3))
9
```
This works like this:
<ul>
<li>start with the list <code>'(1 2 3)</code></li>
<li>apply the lambda which adds 1 to each element, leaving <code>'(2 3 4)</code></li>
<li>reduce to a single number <code>9</code> using <code>+</code> with the initial number <code>0</code></li>
</ul>
each-pair
Calls a supplied lambda with each consecutive pair in a list.
<code>scheme
; Pair iteration where each pair 1 5, 3 3 and 4 2 all sum to 6
(each-pair '(1 5 3 3 4 2)
(λ (a b)
(assert (= 6 (+ a b)))))</code>
matrix functions
```scheme
; Multidimensional list (matrix) access
(var M '(((10 11 12) (13 14 15)) ((16 17 18) (19 20 21))))
(assert (= 20 (matrix-at M 1 1 1)))
(assert (= nil (matrix-at M 1 1 100)))
(assert (= '(10 11 12) (matrix-at M 0 0)))
(var M2 '( (1 2 3 4) (a b c d)))
(assert (= 'c (matrix-at M2 1 2)))
; Update matrix; the old value is returned
(assert (= 'c (matrix-set! M2 'x 1 2)))
(assert (= 'x (matrix-at M2 1 2)))
; Trying to set a value outside the matrix returns an error
(assert (error? (try (matrix-set! M2 0 200 2) #t #!)))
```
hashmap
The are numerous hashmap related functions available:
```scheme
(var mymap (hashmap.new ("1" 2) (3 4)))
(assert (hashmap? mymap))
(assert (= (len mymap) 2))
(hashmap.put mymap 5 6)
(hashmap.put mymap 7 "Initial entry")
(var initial-entry (hashmap.put mymap 7 "Another entry"))
(assert (= initial-entry "Initial entry"))
(assert (= (len mymap) 4))
(assert (= (hashmap.get mymap 7) "Another entry"))
(hashmap.remove mymap 7)
(assert (= (hashmap.get mymap 7) nil))
(assert (= (len mymap) 3))
(var keys '())
(var vals '())
(hashmap.iterate mymap (λ (k v)
(item-append! keys k)
(item-append! vals v)
))
(assert (= '(1 3 5) keys))
(assert (= '(2 4 6) vals))
(var count-removed (hashmap.clear mymap))
(assert (= count-removed 3))
(assert (= (len mymap) 0))
; k -> '()
(var hmlist (hashmap.new))
(hashmap.append! hmlist 'a 1)
(hashmap.append! hmlist 'a 2)
(assert (= (hashmap.get hmlist 'a) '(1 2)))
; The 'a entry exists, so the lambda is called, which updates the list
(hashmap.put-or-apply hmlist 'a 3 (λ (list)
(assert (= list '(1 2)))
(item-append! list 3)
))
(assert (= (hashmap.get hmlist 'a) '(1 2 3)))
(assert (= (hashmap.maybe-put hmlist 'a '(5 5 5)) '(1 2 3)))
(assert (= (hashmap.maybe-put hmlist 'b '(5 5 5)) '(5 5 5)))
(assert (contains? hmlist 'a))
(assert (not (contains? hmlist 'not-there)))
```
io.read-number
Read a number from stdin.
If input is not a number, an <code>error</code> expression is returned.
typename
Returns the type name of its argument
```scheme
<blockquote>
(define x 5)
(typename x)
number
(typename 'x)
symbol
```
</blockquote>
time.now
Returns the current time in milliseconds since unix epoch:
```scheme
<blockquote>
(time.now)
1618413357184
```
</blockquote>
double-quote
Renders the argument and wraps the result in double-quotes.
```scheme
<blockquote>
(double-quote name)
"Joanna"
(double-quote 5)
"5"
(double-quote (+ 2 3))
"5"
```
</blockquote>
inc! and dec!
Increments and decrements
file i/o and stdin/stdout
A file is opened with <code>io.open-file</code>, which takes a relative or absolute path name as an argument. The file is then closed with <code>io.close-file</code>. Currently, line oriented reading and writing is supported.
<code>scheme
(var report (io.open-file "report.csv"))
(io.read-line report)
(io.write-line report "a new line is appended")
(io.close-file report)</code>
<code>io.read-line</code> returns the <em>error</em> expression "EOF" if end of the file is reached.
<code>io.read-line</code> and <code>io.write-line</code> without a file argument reads and writes to stdin and stdout respectively.
<code>io.read-byte</code> reads one byte at a time from a file.
math.odd? math.even? odd-items and even-items
<code>math.odd?</code> and <code>math.even?</code> determine if a number is odd or even, respectively.
<code>odd-items</code> and <code>even-items</code> create a list with odd- and even indexed items respectively. These functions are 1 based.
```scheme
<blockquote>
(math.odd? 5)
</blockquote>
t
<blockquote>
(odd-items '(a b c d e f g))
(a c e g)
```
</blockquote>
math.abs
Returns the absolute value of the argument.
<code>scheme
(math.abs -17)
17</code>
math.pow
Calculates <code>x^y</code>:
```scheme
<blockquote>
(math.pow 2 32)
4294967296
```
</blockquote>
math.average
The average of a list of numbers
math.sqrt
Calculate the square root using Newton's method
```scheme
<blockquote>
(math.sqrt 986)
31.40063693621559
```
</blockquote>
math.safe-div
Divides the first argument by the second. If the divisor is zero, the result is an error.
<code>scheme
(try (safe-div 6 2)
(if (= #value 3)
(print "As expected!\n")
)
)</code>
math.make-random-generator and math.random-list
Given a seed, <code>math.make-random-generator</code> creates a linear congruent random number generator.
Example using current Unix epoch as seed:
```scheme
<blockquote>
(var rng (math.make-random-generator 0))
(rng)
362807296
(rng)
1965043776
```
</blockquote>
Given a random number generator, <code>math.random-list</code> generates a list of <code>n</code> random numbers:
```scheme
<blockquote>
(var rng (math.make-random-generator 0))
(math.random-list rng 10)
(1055406848 752570112 91411200 3016512 1968096889 765038592 339902464 1666232384 1888402176 197119744)
```
</blockquote>
math.fib and math.fact
Recursive Fibonacci and factorial functions (note: as Bio doesn't support arbitrary precision numbers yet, it can only handle relatively small inputs)
Y
The Y fixpoint combinator (technically, the Z combinator as Bio is applicative)
```scheme
<blockquote>
(var ! (Y (lambda (r) (lambda (x) (if (< x 2) 1 (* x (r (- x 1))))))))
(! 5)
</blockquote>
120
```
Modules
A Bio module is a module <em>by convention</em>, somewhat similar to classical Javascript modules:
<ol>
<li>A <code>mod-<modulename>.lisp</code> file with the contents wrapped in a lambda call</li>
<li>The last expression is <code>(self)</code>, making the environment available to the importer</li>
<li>The following definitions are available:<ul>
<li>module-name, a string describing the module</li>
<li>module-version, a list of numbers signifying major, major, and patch</li>
<li>module-description, an <em>optional</em> description of the module</li>
</ul>
</li>
</ol>
Modules
A Bio module is a module <em>by convention</em>, somewhat similar to classical Javascript modules:
<ol>
<li>A <code>mod-<modulename>.lisp</code> file with the contents wrapped in a lambda call</li>
<li>The last expression is <code>(self)</code>, making the environment available to the importer</li>
<li>The following definitions are available:<ul>
<li>module-name, a string describing the module</li>
<li>module-version, a list of numbers signifying major, major, and patch</li>
<li>module-description, an <em>optional</em> description of the module</li>
</ul>
</li>
</ol>
Module example
The examples directory contains a sample module called <code>mod-pos.lisp</code>
To use the module in a REPL:
```scheme
bio> (var Point (import "examples/mod-pos.lisp"))
bio> (var pt (Point (new-point 2 5.4)))
bio> (pt x)
2
bio> (pt y)
5.4
bio> (pt (as-string))
2 5.4
bio> (var loc (Point (new-location 100.5 200.5)))
bio> (loc x)
100.5
bio> (loc y)
200.5
bio> (loc (as-string))
100.5° N 200.5° E
``` | []
|
https://avatars.githubusercontent.com/u/473672?v=4 | MiniPixel | fabioarnold/MiniPixel | 2021-12-02T18:23:41Z | A tiny pixel art editor | main | 9 | 187 | 11 | 187 | https://api.github.com/repos/fabioarnold/MiniPixel/tags | MIT | [
"pixel-art",
"pixel-editor",
"sprites",
"zig",
"ziglang"
]
| 12,072 | false | 2025-05-09T10:30:46Z | true | true | unknown | github | [
{
"commit": "91b199d3cbb314c52c630b7bf6050c4d665c0628.tar.gz",
"name": "nfd",
"tar_url": "https://github.com/fabioarnold/nfd-zig/archive/91b199d3cbb314c52c630b7bf6050c4d665c0628.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/fabioarnold/nfd-zig"
},
{
"commit": "db4a162db2f6f59f737d03f441455dc9524d5793.tar.gz",
"name": "sdl",
"tar_url": "https://github.com/andrewrk/SDL/archive/db4a162db2f6f59f737d03f441455dc9524d5793.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/andrewrk/SDL"
},
{
"commit": "6777f1db221d0cb50322842f558f03e3c3a4099f.tar.gz",
"name": "zigwin32",
"tar_url": "https://github.com/marlersoft/zigwin32/archive/6777f1db221d0cb50322842f558f03e3c3a4099f.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/marlersoft/zigwin32"
},
{
"commit": "b3396d4e65da5862c6ff088f64b3301aa50f3a9f.tar.gz",
"name": "nanovg",
"tar_url": "https://github.com/fabioarnold/nanovg-zig/archive/b3396d4e65da5862c6ff088f64b3301aa50f3a9f.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/fabioarnold/nanovg-zig"
}
]
| Mini Pixel
A tiny pixel art editor.
Website and download
https://fabioarnold.itch.io/mini-pixel
Building from source
See <a>INSTALL.md</a>.
Credits
<ul>
<li><a>nanovg library</a> by Mikko Mononen</li>
<li><a>zigwin32</a> by Jonathan Marler</li>
<li><a>s2s</a> by Felix Queißner</li>
</ul>
License
Mini Pixel is licensed under the MIT License, see <a>LICENSE</a> for more information. | []
|
https://avatars.githubusercontent.com/u/27973237?v=4 | zig-pypi | ziglang/zig-pypi | 2021-07-12T16:16:50Z | The Zig programming language, packaged for PyPI | main | 2 | 173 | 18 | 173 | https://api.github.com/repos/ziglang/zig-pypi/tags | MIT | [
"pypi",
"python",
"zig"
]
| 32 | false | 2025-05-13T19:28:00Z | false | false | unknown | github | []
| Zig PyPI distribution
This repository contains the script used to repackage the <a>releases</a> of the <a>Zig programming language</a> as <a>Python binary wheels</a>. This document is intended for maintainers; see the <a>package README</a> for rationale and usage instructions.
The repackaged artifacts are published as the <a>ziglang PyPI package</a>.
Preparation
The script requires Python 3.9 and later and a <a>PEP 723</a> compatible script
runner, such as <a><code>pipx</code></a>, <a><code>pdm</code></a>, <a><code>hatch</code></a>, <a><code>uv</code></a>, or
similar. Please refer to their documentation for installation instructions.
Building wheels
Run the repackaging script. Here's an example invocation with <a><code>pdm</code></a>:
```shell
$ pdm run make_wheels.py --help
usage: make_wheels.py [-h] [--version VERSION] [--suffix SUFFIX] [--outdir OUTDIR]
[--platform {x86_64-windows,x86_64-macos,aarch64-macos,i386-linux,x86-linux,x86_64-linux,aarch64-linux,armv7a-linux}]
Repackage official Zig downloads as Python wheels
options:
-h, --help show this help message and exit
--version VERSION version to package, use <code>latest</code> for latest release, <code>master</code> for nightly build
--suffix SUFFIX wheel version suffix
--outdir OUTDIR target directory
--platform {x86_64-windows,x86_64-macos,aarch64-macos,i386-linux,x86-linux,x86_64-linux,aarch64-linux,armv7a-linux}
platform to build for, can be repeated
```
This command will download the Zig release archives for every supported platform and convert them to binary wheels, which are placed under <code>dist/</code>. The Zig version and platforms can be passed as arguments.
The process of converting release archives to binary wheels is deterministic, and the output of the script should be bit-for-bit identical regardless of the environment and platform it runs under. To this end, it prints the SHA256 hashes of inputs and outputs; the hashes of the inputs will match the ones on the <a>Zig downloads page</a>, and the hashes of the outputs will match the ones on the <a>PyPI downloads page</a>.
Uploading wheels
Run the publishing utility:
<code>shell
pdm run twine dist/*</code>
This command will upload the binary wheels built in the previous step to PyPI.
License
This script is distributed under the terms of the <a>MIT (Expat) license</a>.
Please refer to the <a>Zig license</a> for the terms
of use of the Zig programming language itself, or look in the <code>.dist-info/licenses/</code>
directory of the built wheels for individual licenses of the bundled components. | []
|
https://avatars.githubusercontent.com/u/3932972?v=4 | zero-graphics | ikskuh/zero-graphics | 2021-05-17T22:27:59Z | Application framework based on OpenGL ES 2.0. Runs on desktop machines, Android phones and the web | master | 2 | 166 | 19 | 166 | https://api.github.com/repos/ikskuh/zero-graphics/tags | MIT | [
"android",
"android-sdk",
"desktop-linux",
"game-development",
"graphics",
"sdl",
"sdl2",
"wasm",
"zig",
"zig-package",
"ziglang"
]
| 16,818 | false | 2025-04-29T17:17:13Z | true | false | unknown | github | []
| Zero Graphics
A very minimal OpenGL ES 2.0 library for Zig. Opens you a window and let's you draw things.
Comes with a pixel-perfect 2D renderer and maybe some day even with a bit of a 3D api.
Features
<ul>
<li>Multi-platform support</li>
<li>Desktop (Linux, MacOS, Windows, ...)</li>
<li>WebAssembly</li>
<li>Android</li>
<li>Pixel perfect 2D rendering</li>
<li>Primitives (line, rectangle, triangle, ...)</li>
<li>Text / TTF fonts</li>
<li>Textures</li>
<li>Basic 3D rendering</li>
<li>Multi-mesh models with flat textures</li>
<li>Zig-style immediate-mode user interface</li>
<li>Proper DPI scaling support in renderer</li>
</ul>
Project status
CI
The CI coverage currently looks like this:
| · | Windows | macOS | Linux |
| -------------- | ------- | ----- | ----- |
| Desktop | ✅ | ✅ | ✅ |
| WebAssembly | ✅ | ✅ | ✅ |
| Android | ✅ | ✅ | ✅ |
| <code>zero-init</code> | ✅ | ✅ | ✅ |
| <code>zero-convert</code> | ✅ | ✅ | ✅ |
Status: <a></a>
Previews
Work-in-progress, but works quite well already. There is one <a>big project</a> depending on it and is used as a <em>real-world application</em> driver behind <em>Zero Graphics</em>.
Project Goals
Basic Framework
<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 the following platforms
<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> Wasm
<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> Create OpenGL ES 2.0 context
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Input Mouse
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Input Keyboard
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Linux Desktop
<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> Create OpenGL ES 2.0 context
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Input Mouse
<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> Input Keyboard
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Windows Desktop (not tested, but should work via SDL2)
<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> Android
<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> Create OpenGL ES 2.0 context
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Input Mouse
<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> Input Keyboard
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Create an OpenGL ES 2.0 context
<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> Provide input events
<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> Single pointer motion (finger or mouse)
<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> Single click event (finger, mouse)
<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> Text input for keyboard (utf-8 encoded)
<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> Provide window events
<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> Resize
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Close
<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> Provide access to the underlying backend
<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 creation of single-file applications
<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> Single executable for easy distribution
<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> Embedded resources
2D Rendering library
<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> Pixel perfect drawing of
<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> Lines
<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> Rectangles
<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> Images
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Basic "copy full texture to rectangle"
<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> Copy portion of texture ("atlas rendering")
<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> TTF font rendering via <a><code>stb_ttf</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> Image loading via <a><code>zigimg</code></a>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Stack based/nested scissoring
3D Rendering library
<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> Tool based on Assimp to convert models into loadable format
<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> static geometry
<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/animated geometry
<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> Blender export script
<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> Draw static geometry
<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> Draw animated geometry
<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> Skinning based on skeletons
<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> Axis- and camera aligned billboards
<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> Basic particles
<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> Tiny built-in pipeline with
<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> shadow mapping
<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> planar reflections
<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> water reflections
Dependencies
Desktop
<ul>
<li><a>SDL2</a></li>
</ul>
Web
<ul>
<li><a>js glue code</a></li>
<li><a>root page</a></li>
</ul>
Android
<ul>
<li>Android SDK</li>
<li>Android NDK</li>
<li>Android Build Tools</li>
<li>OpenJDK</li>
<li>some other tools</li>
</ul>
Building / Running
This project uses <a>submodules</a>, so to get started, clone the repo with submodules recursively:
<code>sh-session
[user@computer work]$ git clone https://github.com/MasterQ32/zero-graphics --recurse-submodules</code>
or, if you already cloned the repository:
<code>sh-session
[user@computer work]$ git clone https://github.com/MasterQ32/zero-graphics
[user@computer work]$ cd zero-graphics/
[user@computer zero-graphics]$ git submodule update --init --recursive</code>
Desktop PC
Requires <code>SDL2</code> to be installed.
<code>sh-session
[user@computer zero-graphics]$ zig build run</code>
A window should open with the application in fullscreen.
The following environment variables can control how zero-graphics behaves:
<ul>
<li><code>ZEROG_FULLSCREEN</code> is <code>y</code> for forced fullscreen or <code>n</code> for forced window mode.</li>
<li><code>ZEROG_RESIZEABLE</code> is <code>y</code> for forced resizable window.</li>
<li><code>ZEROG_DPI</code> is a number specifying the pixel density.</li>
</ul>
Web/Wasm version
Includes a teeny tiny web server for debugging.
<code>sh-session
[user@computer zero-graphics]$ zig build install run-wasm</code>
Now visit http://127.0.0.1:8000/demo_application.htm to see the demo.
Android
Connect your phone first and install both a JDK as well as the Android SDK with NDK included. The ZeroGraphics build system will tell you if
it couldn't auto-detect the SDK paths.
<code>sh-session
[user@computer zero-graphics]$ zig build -Denable-android run-app</code>
The app should now be installed and started on your phone.
Documentation
Getting started
To create a new project, build this repository with <code>zig build</code> first. Then use the tool <code>zero-init</code> from <code>zig-out/bin</code> to initialize a new project:
<code>sh-session
[felix@denkplatte-v2 ~]$ mkdir game
[felix@denkplatte-v2 ~]$ cd game
[felix@denkplatte-v2 game]$ /path/to/zero-graphics/zig-out/bin/zero-init symlink # initialize via symlink, quickest option. use zero-init -h to see all options
[felix@denkplatte-v2 game]$ ls
src vendor build.zig
[felix@denkplatte-v2 game]$ zig build
[felix@denkplatte-v2 game]$ zig build run
info(sdl): SDL Video Driver: x11
info(sdl): Render resolution: 1280×720
info(sdl): Virtual resolution: 1280×720
info(demo): OpenGL Version: OpenGL ES 3.2 Mesa 21.2.3
info(demo): OpenGL Vendor: AMD
info(demo): OpenGL Renderer: AMD Radeon(TM) Vega 10 Graphics (RAVEN, DRM 3.41.0, 5.13.19_1, LLVM 12.0.1)
info(demo): OpenGL GLSL: OpenGL ES GLSL ES 3.20
info(zero_graphics): [shader compiler] [other] Shader Stats: SGPRS: 16 VGPRS: 8 Code Size: 212 LDS: 0 Scratch: 0 Max Waves: 10 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0
info(zero_graphics): [shader compiler] [other] Shader Stats: SGPRS: 16 VGPRS: 8 Code Size: 40 LDS: 0 Scratch: 0 Max Waves: 10 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0
info(zero_graphics): [shader compiler] [other] Shader Stats: SGPRS: 8 VGPRS: 24 Code Size: 52 LDS: 0 Scratch: 0 Max Waves: 10 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0
info(zero_graphics): [shader compiler] [other] Shader Stats: SGPRS: 8 VGPRS: 24 Code Size: 24 LDS: 0 Scratch: 0 Max Waves: 10 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0
info(zero_graphics): [shader compiler] [other] Shader Stats: SGPRS: 8 VGPRS: 8 Code Size: 60 LDS: 0 Scratch: 0 Max Waves: 10 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0
info(zero_graphics): [shader compiler] [other] Shader Stats: SGPRS: 16 VGPRS: 20 Code Size: 392 LDS: 0 Scratch: 0 Max Waves: 10 Spilled SGPRs: 0 Spilled VGPRs: 0 PrivMem VGPRs: 0</code>
Check out the file <a><code>src/main.zig</code></a> to see your app skeleton. You can also adjust the <a><code>build.zig</code></a> to set your project name.
The functions are roughly called in this order:
The separation between <em>application init</em> and <em>graphics init</em> is relevant for Android apps which will destroy their window when you send it into the background and will recreate it when it is selected again. This means that all GPU content will be lost then and must be restored.
Your application state will not be destroyed, so the rendering can render the same data as before.
Architecture
<code>zero-graphics</code> follows a somewhat unusual architecture for Zig applications.
Your applications is a <em>package</em> that will be consumed by a <code>zero-graphics</code> host. This host is implementing the "main loop" and will invoke both <code>update</code> and <code>render</code> periodically. It will also initialize and open the window and pump events.
This design allows <code>zero-graphics</code> to run on several different platforms, including most desktop PCs, Android and even web browsers via WebAssembly.
You can check out the <a>Sdk.zig</a> file to find out how a application is built. | []
|
https://avatars.githubusercontent.com/u/7967463?v=4 | telescope-zf-native.nvim | natecraddock/telescope-zf-native.nvim | 2022-01-19T22:20:00Z | native telescope bindings to zf for sorting results | master | 4 | 158 | 7 | 158 | https://api.github.com/repos/natecraddock/telescope-zf-native.nvim/tags | MIT | [
"neovim",
"sorter",
"telescope",
"zf",
"zig"
]
| 1,030 | false | 2025-05-01T23:39:21Z | false | false | unknown | github | []
| telescope-zf-native.nvim
native <a>telescope</a> bindings to
<a>zf</a> for sorting results.
<a>Try it online!</a>
In short, zf is a filepath fuzzy finder. It is designed for better matching on filepaths than fzf or fzy. Matches on filenames are prioritized, and the strict path matching feature helps narrow down directory trees with precision. See the <a>zf</a> repo for full details. Some highlights:
<ul>
<li>a match on the filename is prioritized over a match on the full path</li>
<li>a search including path separators enables "strict path matching"</li>
<li>this means each path segment in the query must be found in a path segment of the file</li>
<li><code>src/</code> would match <code>src/index.js</code> but not <code>tests/routes/client/index.js</code></li>
<li>the search query is space-separated to make narrowing down results easier</li>
<li>searching for <code>init.py</code> would find several <code>__init__.py</code> files in a Python project</li>
<li>but a search for <code>init.py c</code> would match <code>./config/__init__.py</code> (or any other paths also containing <code>c</code>)</li>
</ul>
Why
By default, <a>telescope</a> uses a
sorter implemented in Lua. This is fine, but performance can suffer on larger
lists of data.
telescope-zf-native.nvim is a telescope extension that provides a more
performant natively-compiled sorter written in <a>Zig</a> with
more accurate filename matching using the
<a>zf</a> algorithm. Pre-compiled libzf binaries
are included. See below for the current list of supported platforms and
architectures.
The zf algorithm
See the <a>zf repo</a> for more information on
the algorithm and standalone executable (a replacement for <code>fzf</code> or <code>fzy</code>). But
here's a short summary:
After analyzing filenames from over 50 git repositories selected randomly from
GitHub, I concluded that the majority of filenames are unique in a project. I
used this in designing the zf algorithm to make a fuzzy-finder that is optimized
for filtering filepaths.
<ul>
<li>Matches on filenames are highly favored over filepath matches</li>
<li>Matches on the beginning of a word are prioritized over matches in
the middle of a word</li>
<li>Non-sequential character matches are penalized</li>
</ul>
With these heuristics, zf does a really good job sorting the desired file to the
top of the results list. But there are plenty of files that share the same or
similar names like <code>init.lua</code> or <code>__init__.py</code> for example. zf parses the query
string as a list of space-delimited tokens to easily refine the search results
when the first match isn't the wanted file. Simply append further terms to the
query to narrow down the results.
Installation
Install in neovim with a package manager like
<a>packer.nvim</a> or
<a>vim-plug</a>.
<code>lua
--- packer
use "natecraddock/telescope-zf-native.nvim"</code>
If you are using <a>lazy.nvim</a> and experience troubles installing the plugin, try something like the following (see <a>this issue</a> for more details):
<code>lua
require('lazy').setup('my_plugins', { rocks = { enabled = false } })</code>
Then load the extension in telescope with default settings.
<code>lua
require("telescope").load_extension("zf-native")</code>
The default config replaces the default telescope sorters with zf for all
sorting. To confirm that the extension loaded properly, and to view the current
settings, run <code>:checkhealth zf-native</code>.
For additional configuration, use the following:
```lua
require("telescope").setup({
extensions = {
["zf-native"] = {
-- options for sorting file-like items
file = {
-- override default telescope file sorter
enable = true,
<code> -- highlight matching text in results
highlight_results = true,
-- enable zf filename match priority
match_filename = true,
-- optional function to define a sort order when the query is empty
initial_sort = nil,
-- set to false to enable case sensitive matching
smart_case = true,
},
-- options for sorting all other items
generic = {
-- override default telescope generic item sorter
enable = true,
-- highlight matching text in results
highlight_results = true,
-- disable zf filename match priority
match_filename = false,
-- optional function to define a sort order when the query is empty
initial_sort = nil,
-- set to false to enable case sensitive matching
smart_case = true,
},
}
},
</code>
})
require("telescope").load_extension("zf-native")
```
The above settings are the default, so if you are satisfied with the defaults
there is no need to change anything.
Example initial_sort function
The <code>initial_sort</code> function is used when the query is empty.
Here is an example that prioritizes <code>.lua</code> files
<code>lua
['zf-native'] = {
file = {
initial_sort = function (line)
if line:match('%.lua$') then
return 0
end
return 1
end
}
}</code>
The function accepts a line to rank and should return a number between 0 and 1,
with numbers closer to 0 giving the line a higher priority.
Supported Platforms
The <code>lib/</code> directory contains libzf pre-compiled libraries for:
* linux (x86 and arm)
* macos (x86 and arm)
* windows (x86)
If your OS is not supported, or there are issues loading the libraries please
submit an issue. For requests of support of new platforms or any other issue,
please include the output of <code>:checkhealth zf-native</code> in the issue.
Related
<ul>
<li><a>telescope-fzf-native.nvim</a></li>
<li><a>telescope-fzy-native.nvim</a></li>
</ul>
I also thank the developers who worked on these projects as my reference for
using the LuaJIT FFI. | []
|
https://avatars.githubusercontent.com/u/94020660?v=4 | zig-v8 | fubark/zig-v8 | 2021-12-06T23:22:27Z | Simple V8 builds with C and Zig bindings. | master | 6 | 153 | 18 | 153 | https://api.github.com/repos/fubark/zig-v8/tags | MIT | [
"js",
"v8",
"wasm",
"zig"
]
| 685 | false | 2025-05-02T18:31:34Z | true | false | unknown | github | []
| zig-v8
Builds V8 from official source and provides C bindings and a Zig API. This would be used for embedding the V8 runtime into your Zig or C ABI compatible projects.
V8 is the JS/WASM runtime that powers Google Chrome and Microsoft Edge.
Project Status
Static libs are built and released with <a>Github Actions</a>.
| Native | Cross Compile | Target | Demo Binary (<a>shell.zig</a>)* |
| ------ | ------ | -------- | -------- |
| ✅ | | Linux x64 | shell - 19 M |
| ✅ | ✅ | Windows x64 | shell.exe - 14 M |
| ✅ | | macOS x64 | shell - 24 M |
| ✅ | ✅ | macOS arm64 | shell - 21 M |
* shell.zig is a JS repl and statically linked with v8. Compiled with -Doptimize=ReleaseSafe. The V8 dependency can be further reduced in size if you don't need all the features (eg. disable WASM runtime).
| Toolchain | Fresh Build<em> | Cached Build</em> |
| ------ | ------ | ------ |
| gclient, full feature + v8 toolchain | 1.5-2 hrs | with sccache: 10-20min |
| minimal feature + v8 toolchain | 40-50 min | with sccache: 5-10min |
| minimal feature + zig c++ toolchain | | with zig caching: |
* Time is measured on standard Github instances.
System Requirements
<ul>
<li>Zig compiler (0.11.0). You can get that <a>here</a>.</li>
<li>Python 3 (2.7 seems to work as well)</li>
<li>For native macOS builds:</li>
<li>XCode (You won't need this when using zig's c++ toolchain!)
if you come across this error:
<code>xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance</code>
run <code>sudo xcode-select -s /Applications/Xcode.app/Contents/Developer</code></li>
</ul>
Build
By default UseGclient=false in build.zig. This will pull the minimum sources and deps needed to build v8 and reduce build times.
If you want to include everything, set UseGclient=true. Build times can be quite long using gclient but afterwards rerunning "zig build" should be incremental. You can also use sccache for better incremental build times.
```sh
Clone the repo.
git clone https://github.com/fubark/zig-v8.git
cd zig-v8
Pull prebuilt GN/Ninja. If UseGclient=true, it also pulls depot_tools.
zig build get-tools
Pull v8 source
zig build get-v8
Build, resulting static library should be at:
v8-build/{target}/{debug/release}/ninja/obj/zig/libc_v8.a
On windows, use msvc: zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-windows-msvc
zig build -Doptimize=ReleaseSafe
```
Demo
```sh
shell.zig is a simple JS repl.
Assumes you've already built v8.
zig build run -Dpath="src/shell.zig" -Doptimize=ReleaseSafe
If you built v8 using the zig toolchain, you'll need to add the flag here as well.
zig build run -Dpath="src/shell.zig" -Doptimize=ReleaseSafe -Dzig-toolchain
```
Cross Compiling
With Zig's toolchain, we can build V8 from libstdc++ that's bundled with zig and cross compile to foreign targets/cpus! Simply amazing. Eventually, this will also replace the default V8 toolchain for native builds after further testing.
Linux x64 (Host) to MacOS arm64 (Target)
```sh
Assumes you've fetched tools and v8 sources. See above build steps.
Resulting static lib will be at:
v8-build/aarch64-macos/release/ninja/obj/zig/libc_v8.a
zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-macos-gnu -Dzig-toolchain
```
Cross compile to Windows with gnu (mingw64)
Zig comes with mingw64 source and headers so you'll be able to target Windows without MSVC.
<code>sh
zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-windows-gnu -Dzig-toolchain</code>
Usage
See src/shell.zig or test/test.zig on how to use the library with the Zig API as well as build.zig (fn linkV8) on how to link with the built V8 static library.
Contributing
The C bindings is incomplete but it should be relatively easy to add more as we need them.
C API naming convention should closely follow the V8 C++ API.
Troubleshooting
If you get an error saying that it can't find any of the following:
```
pkg-config
glib-2.0
gmodule-2.0
gobject-2.0
gthread-2.0
```
You'll need to run the following command before continuing:
<code>sudo apt install -y pkg-config libglib2.0-dev</code>
Or your distro's equivalent | []
|
https://avatars.githubusercontent.com/u/34946442?v=4 | zigfsm | cryptocode/zigfsm | 2022-01-18T22:29:31Z | A finite state machine library for Zig | main | 0 | 152 | 6 | 152 | https://api.github.com/repos/cryptocode/zigfsm/tags | MIT | [
"finite-state-machine",
"fsm",
"fsm-library",
"graphviz",
"state-machine",
"zig",
"zig-library",
"zig-package"
]
| 84 | false | 2025-05-19T21:19:18Z | true | true | unknown | github | []
| zig<strong>fsm</strong> is a <a>finite state machine</a> library for Zig.
This library supports Zig 0.12.x, 0.13, 0.14, as well as Zig master. Last test was on Zig version <code>0.15.0-dev.11+5c57e90ff</code>
Use the zigfsm main branch to compile with Zig master. Use the appropriate zig-<em>version</em> tag to target a Zig version not compatible with the main branch.
Tested on Linux, macOS, FreeBSD and Windows.
Table of Contents
<ul>
<li><a>Features</a></li>
<li><a>Motivation</a></li>
<li><a>Using zigfsm</a></li>
<li><a>Building</a></li>
<li><a>Importing the library</a></li>
<li><a>Learning from the tests</a></li>
<li><a>Creating a state machine type</a></li>
<li><a>Making an instance</a></li>
<li><a>Adding state transitions</a></li>
<li><a>Optionally defining events</a></li>
<li><a>Defining transitions and events at the same time</a></li>
<li><a>Defining transitions and events as a table</a></li>
<li><a>Changing state</a></li>
<li><a>Probing the current state</a></li>
<li><a>Inspecting what transition happened</a></li>
<li><a>Valid states iterator</a></li>
<li><a>Importing state machines</a></li>
<li><a>Transition handlers</a><ul>
<li><a>Canceling transitions</a></li>
</ul>
</li>
</ul>
Features
<ul>
<li>Never allocates</li>
<li>Works at both comptime and runtime</li>
<li>Fast transition validation</li>
<li>Compact memory representation</li>
<li>State machines can export themselves to the Graphviz DOT format</li>
<li>Defined programmatically or by importing Graphviz or libfsm text (even at compile time)</li>
<li>Imported state machines can autogenerate state- and event enums</li>
<li>Optional event listeners can add functionality and cancel transitions</li>
<li>Push-down automaton wrappers are easy to write (see GameState example in tests.zig)</li>
<li>Comprehensive test coverage which also serves as examples</li>
</ul>
Motivation
Using an FSM library may have some benefits over hand-written state machines:
* Many real-world processes, algorithms, and protocols have rigorously defined state machines available. These can be imported directly or programmatically into zigfsm.
* Can lead to significant simplification of code, as transition rules are explicitly stated in one place. Contrast this with the brittleness of manually checking and documenting which states can follow a certain state when a certain event happens.
* An invalid state transition is an immediate error with useful contextual information.
* You get visualization for free, which is helpful during development, debugging and as documentation.
Using zigfsm
Before diving into code, it's worth repeating that zigfsm state machines can generate their own diagram, as well as import them. This can be immensely helpful when working on your state machines,
as you get a simple visualization of all transitions and events. Obviously, the diagrams can be used as part of your documentation as well.
Here's the diagram from the CSV parser test, as generated by the library:
Diagrams can be exported to any writer using <code>exportGraphviz(...)</code>, which accepts <code>StateMachine.ExportOptions</code> to change style and layout.
A png can be produced using the following command: <code>dot -Tpng csv.gv -o csv.png</code>
Building
To build, test and benchmark:
<code>zig build -Doptimize=ReleaseFast
zig build test
zig build benchmark</code>
The benchmark always runs under ReleaseFast.
Importing the library
Add zigfsm as a Zig package to your <code>zon</code> file, or simply import <code>main.zig</code> directly if vendoring.
Here's how to update your zon file using the latest commit of zigfsm:
<code>bash
zig fetch --save git+https://github.com/cryptocode/zigfsm</code>
Next, update your <code>build.zig</code> to add zigfsm as an import. For example:
<code>zig
exe.root_module.addImport("zigfsm", b.dependency("zigfsm", .{}).module("zigfsm"));</code>
Now you can import zigfsm from any Zig file:
```zig
// This example implements a simple Moore machine: a three-level intensity lightswitch
const std = @import("std");
const zigfsm = @import("zigfsm");
pub fn main() !void {
// A state machine type is defined using state enums and, optionally, event enums.
// An event takes the state machine from one state to another, but you can also switch to
// other states without using events.
//
// State and event enums can be explicit enum types, comptime generated enums, or
// anonymous enums like in this example.
//
// If you don't want to use events, simply pass null to the second argument.
// We also define what state is the initial one, in this case .off
var fsm = zigfsm.StateMachine(enum { off, dim, medium, bright }, enum { click }, .off).init();
<code>// There are many ways to define transitions (and optionally events), including importing
// from Graphviz. In this example we use a simple API to add events and transitions.
try fsm.addEventAndTransition(.click, .off, .dim);
try fsm.addEventAndTransition(.click, .dim, .medium);
try fsm.addEventAndTransition(.click, .medium, .bright);
try fsm.addEventAndTransition(.click, .bright, .off);
std.debug.assert(fsm.isCurrently(.off));
// Do a full cycle: off -> dim -> medium -> bright -> off
_ = try fsm.do(.click);
_ = try fsm.do(.click);
_ = try fsm.do(.click);
_ = try fsm.do(.click);
// Make sure we're in the expected state
std.debug.assert(fsm.isCurrently(.off));
std.debug.assert(fsm.canTransitionTo(.dim));
</code>
}
```
Learning from the tests
A good way to learn zigfsm is to study the <a>tests</a> file.
This file contains a number of self-contained tests that also demonstrates various aspects of the library.
Creating a state machine type
A state machine type is defined using state enums and, optionally, event enums.
Here we create an FSM for a button that can be clicked to flip between on and off states. The initial state is <code>.off</code>:
<code>zig
const State = enum { on, off };
const Event = enum { click };
const FSM = zigfsm.StateMachine(State, Event, .off);</code>
If you don't need events, simply pass null:
<code>zig
const FSM = zigfsm.StateMachine(State, null, .off);</code>
Making an instance
Now that we have a state machine <em>type</em>, let's create an instance with an initial state :
<code>zig
var fsm = FSM.init();</code>
If you don't need to reference the state machine type, you can define the type and get an instance like this:
<code>zig
var fsm = zigfsm.StateMachine(State, Event, .off).init();</code>
You can also pass anonymous state/event enums:
<code>zig
var fsm = zigfsm.StateMachine(enum { on, off }, enum { click }, .off).init();</code>
Adding state transitions
<code>zig
try fsm.addTransition(.on, .off);
try fsm.addTransition(.off, .on);</code>
Optionally defining events
While <code>transitionTo</code> can now be used to change state, it's also common to invoke state transitions
using events. This can vastly simplify using and reasoning about your state machine.
The same event can cause different transitions to happen, depending on the current state.
Let's define what <code>.click</code> means for the on and off states:
<code>zig
try fsm.addEvent(.click, .on, .off);
try fsm.addEvent(.click, .off, .on);</code>
This expresses that if <code>.click</code> happens in the <code>.on</code> state, then transition to the <code>.off</code> state, and vice versa.
Defining transitions and events at the same time
A helper function is available to define events and state transitions at the same time:
<code>zig
try fsm.addEventAndTransition(.click, .on, .off);
try fsm.addEventAndTransition(.click, .off, .on);</code>
Which approach to use depends on the application.
Defining transitions and events as a table
Rather than calling addTransition and addEvent, <code>StateMachineFromTable</code> can be used to pass a table of event- and state transitions.
<code>zig
const State = enum { on, off };
const Event = enum { click };
const definition = [_]Transition(State, Event){
.{ .event = .click, .from = .on, .to = .off },
.{ .event = .click, .from = .off, .to = .on },
};
var fsm = zigfsm.StateMachineFromTable(State, Event, &definition, .off, &.{}).init();</code>
Note that the <code>.event</code> field is optional, in which case only transition validation is added.
Changing state
Let's flip the lights on by directly transitioning to the on state:
<code>zig
try fsm.transitionTo(.on);</code>
This will fail with <code>StateError.Invalid</code> if the transition is not valid.
Next, let's change state using the click event. In fact, let's do it several times, flipping the switch off and on and off again:
<code>zig
try fsm.do(.click);
try fsm.do(.click);
try fsm.do(.click);</code>
Again, this will fail with <code>StateError.Invalid</code> if a transition is not valid.
Finally, it's possible to change state through the more generic <code>apply</code> function, which takes either a new state or an event.
<code>zig
try fsm.apply(.{ .state = .on });
try fsm.apply(.{ .event = .click });</code>
Probing the current state
The current state is available through <code>currentState()</code>. To check if the current state is a specific state, call <code>isCurrently(...)</code>
If final states have been added through <code>addFinalState(...)</code>, you can check if the current state is in a final state by calling <code>isInFinalState()</code>
To check if the current state is in the start state, call <code>isInStartState()</code>
See the API docstring for more information about these are related functions.
Inspecting what transition happened
```zig
const transition = try fsm.do(.identifier);
if (transition.to == .jumping and transition.from == .running) {
...
}
```
... where <code>transition</code> contains the fields <code>from</code>, <code>to</code> and <code>event</code>.
Followed by an if/else chain that checks relevant combinations of from- and to states. This could, as an example, be used in a parser loop.
See the tests for examples.
Valid states iterator
It's occasionally useful to know which states are possible to reach from the current state. This is done using an iterator:
<code>zig
while (fsm.validNextStatesIterator()) |valid_next_state| {
...
}</code>
Importing state machines
It's possible, even at compile time, to parse a <code>Graphviz</code> or <code>libfsm</code> text file and create a state machine from this.
<ul>
<li>
<code>importText</code> is used when you already have state- and event enums defined in Zig. <code>importText</code> can also be called at runtime to define state transitions.
</li>
<li>
<code>generateStateMachineFromText</code> is used when you want the compiler to generate these enums for you. While this saves you from writing enums manually, a downside is that editors and language servers are unlikely to support autocomplete on generated types.
</li>
</ul>
The source input can be a string literal, or brought in by <code>@embedFile</code>.
See the test cases for examples on how to use the import features.
Transition handlers
A previous section explained how to inspect the source and target state. There's another way to do this, using callbacks.
This gets called when a transition happens. The main benefit is that it allows you to cancel a transition.
Handlers also makes it easy to keep additional state, such as source locations when writing a parser.
Let's keep track of the number of times a light switch transition happens:
<code>zig
var countingHandler = CountingHandler.init();
try fsm.addTransitionHandler(&countingHandler.handler);</code>
Whenever a transition happens, the handler's public <code>onTransition</code> function will be called. See tests for complete
examples of usage.
Canceling transitions
The transition handler can conditionally stop a transition from happening by returning <code>HandlerResult.Cancel</code>. The callsite of <code>transitionTo</code> or <code>do</code> will then fail with <code>StateError.Invalid</code>
Alternatively,<code>HandlerResult.CancelNoError</code> can be used to cancel without failure (in other words, the current state remains but the callsite succeeds) | []
|
https://avatars.githubusercontent.com/u/3932972?v=4 | zig-qoi | ikskuh/zig-qoi | 2021-11-25T23:08:00Z | Quite OK Image format encoder/decoder written in Zig | master | 4 | 144 | 7 | 144 | https://api.github.com/repos/ikskuh/zig-qoi/tags | MIT | [
"image-decoder",
"image-encoder",
"image-format",
"qoi",
"zig",
"zig-package",
"ziglang"
]
| 2,618 | false | 2025-05-09T11:15:06Z | true | true | 0.14.0 | github | [
{
"commit": "9425b94c103a031777fdd272c555ce93a7dea581",
"name": "args",
"tar_url": "https://github.com/ikskuh/zig-args/archive/9425b94c103a031777fdd272c555ce93a7dea581.tar.gz",
"type": "remote",
"url": "https://github.com/ikskuh/zig-args"
},
{
"commit": "0ce4eca3560d5553b13263d6b6bb72e146dd43d0",
"name": "img",
"tar_url": "https://github.com/zigimg/zigimg/archive/0ce4eca3560d5553b13263d6b6bb72e146dd43d0.tar.gz",
"type": "remote",
"url": "https://github.com/zigimg/zigimg"
}
]
| zig-qoi
A implementation of the <a><em>Quite OK Image Format</em></a> for Zig. This implementation conforms to the <a>Qoi specification</a>.
API
Add <code>src/qoi.zig</code> to your Zig project as a package.
```zig
pub const DecodeError = error{ OutOfMemory, InvalidData, EndOfStream };
pub const EncodeError = error{ OutOfMemory };
// Simple API:
pub fn isQOI(bytes: []const u8) bool;
pub fn decodeBuffer(allocator: std.mem.Allocator, buffer: []const u8) DecodeError!Image;
pub fn decodeStream(allocator: std.mem.Allocator, reader: anytype) !Image;
pub fn encodeBuffer(allocator: std.mem.Allocator, image: ConstImage) EncodeError![]u8;
pub fn encodeStream(image: ConstImage, writer: anytype) !void;
// Streaming API:
pub fn encoder(writer: anytype) Encoder(@TypeOf(writer));
pub fn Encoder(comptime Writer: type) type {
return struct {
writer: Writer,
pub fn reset(self: <em>Self) void;
pub fn flush(self: </em>Self) (EncodeError || Writer.Error)!void;
pub fn push(self: *Self, pixel: Color) (EncodeError || Writer.Error)!void;
};
}
pub const ColorRun = struct {
color: Color,
length: usize,
};
pub fn decoder(reader: anytype) Decoder(@TypeOf(reader));
pub fn Decoder(comptime Reader: type) type {
return struct {
reader: Reader,
pub fn fetch(self: *Self) Reader.Error!ColorRun;
};
}
```
Implementation Status
Everything specified in https://github.com/phoboslab/qoi/issues/37 is implemented and accessible via the API.
Performance
On my machine (AMD Ryzen 7 3700U), i did a small benchmark with decoding <code>bench.zig</code>, which will decode <code>zero.qoi</code>:
| Build Mode | QOI Bytes | Raw Bytes | Encoding Time | Decoding Time |
| ------------ | ----------- | -------------- | ------------- | ------------- |
| Debug | 75.024 byte | 1.048.576 byte | 14.439ms | 7.061ms |
| ReleaseSmall | 75.024 byte | 1.048.576 byte | 1.888ms | 1.499ms |
| ReleaseSafe | 75.024 byte | 1.048.576 byte | 1.392ms | 512.706us |
| ReleaseFast | 75.024 byte | 1.048.576 byte | 1.186ms | 456.762us |
This means that this implementation is roughly able to decode ~2.1 GB/s raw texture data and is considered "fast enough" for now. If you find some performance improvements, feel free to PR it!
Running perf on the benchmark compiled with ReleaseFast showed that the implementation is quite optimal for the CPU, utilizing it to 100% and executing up to 3 instructions per cycle on my machine.
```sh-console
[felix@denkplatte-v2 zig-qoi]$ perf stat ./zig-out/bin/qoi-bench
Benchmark [4067/4096] Encoding time for 1048576 => 75024 bytes: 1.019ms
Benchmark [4067/4096] Decoding time for 75024 => 1048576 bytes: 419.223us
Performance counter stats for './zig-out/bin/qoi-bench':
<code> 9.665,11 msec task-clock:u # 0,997 CPUs utilized
0 context-switches:u # 0,000 K/sec
0 cpu-migrations:u # 0,000 K/sec
21.066 page-faults:u # 0,002 M/sec
29.757.225.002 cycles:u # 3,079 GHz (83,33%)
317.453.390 stalled-cycles-frontend:u # 1,07% frontend cycles idle (83,33%)
515.819.113 stalled-cycles-backend:u # 1,73% backend cycles idle (83,32%)
83.377.885.642 instructions:u # 2,80 insn per cycle
# 0,01 stalled cycles per insn (83,36%)
18.947.655.057 branches:u # 1960,417 M/sec (83,31%)
193.594.708 branch-misses:u # 1,02% of all branches (83,35%)
9,693303129 seconds time elapsed
9,553127000 seconds user
0,112001000 seconds sys
</code>
```
Also, running the <a>benchmark dataset</a> of the original author, it yielded the <a>following data</a>:
<code>Number of total images: 1351
Average PNG Compression: 18.57%
Average QOI Compression: 22.70%
Average Compression Rate (MB/s): 438.31 MB/s
Minimal Compression Rate (MB/s): 27.06 MB/s
Maximum Compression Rate (MB/s): 1390.15 MB/s
Average Decompression Rate (MB/s): 1128.46 MB/s
Maximum Decompression Rate (MB/s): 39.77 MB/s
Maximum Deompression Rate (MB/s): 13307.20 MB/s</code>
<a>See also the original analysis on Google Docs</a>
Contribution
Run the test suite like this:
<code>sh-console
[user@host zig-qoi]$ zig build test
All 5 tests passed.</code>
Run the benchmark like this:
<code>sh-console
[user@host zig-qoi]$ zig build benchmark
Benchmark [4096/4096] Encoding time for 1048576 => 67076 bytes: 16.649ms
Benchmark [4095/4096] Decoding time for 67076 => 1048576 bytes: 5.681ms</code>
To run the benchmark for batch files, run this:
<code>sh-console
[user@host zig-qoi]$ zig build install && ./zig-out/bin/qoi-bench-files $(folder_a) $(folder_b) ...
File Name Width Height Total Raw Bytes Total PNG Bytes PNG Compression Total QOI Bytes QOI Compression QOI to PNG Decode Time (ns) Encode Time (ns)
data/zero.png 512 512 1048576 80591 0.08 67076 0.06 0.8323013782501221 5628360 14499346
total sum 0 0 1048576 80591 0.08 67076 0.06 0.8323013782501221 5628360 14499346</code>
Pass as many folders you like to the benchmarking tool. It will render a CSV file on the <code>stderr</code>. | []
|
https://avatars.githubusercontent.com/u/175892156?v=4 | Zag-Smalltalk | Zag-Research/Zag-Smalltalk | 2021-02-25T07:40:57Z | Smalltalk VM Written in Zig with methods stored as type-annotated ASTs | main | 4 | 135 | 8 | 135 | https://api.github.com/repos/Zag-Research/Zag-Smalltalk/tags | MIT | [
"compiler",
"interpreter",
"smalltalk",
"zig"
]
| 115,091 | false | 2025-05-21T03:10:11Z | false | false | unknown | github | []
| Zag-Smalltalk
Smalltalk VM Written in Zig with methods stored as type-annotated ASTs
Methods are re-constituted from the AST for edit windows.
No Interpreter; uses Threaded and CPS execution models interchangeably
Memory structure and some of execution principles loosely modelled on OpenSmalltalk VM
Eventually it wiil include a JIT compiler
More information in the <a>Documentation</a>
Papers and Talks can be found <a>here</a>
(Previously called AST-Smalltalk, but since the implementation is in Zig, a rename seemed obvious.)
Loading into Pharo (known to load with Pharo 13)
<em>very much work-in-progress at the moment</em>
<code>smalltalk
Metacello new
baseline: 'ZagSmalltalk';
repository: 'github://Zag-Research/Zag-Smalltalk:main';
load</code> | []
|
https://avatars.githubusercontent.com/u/9152478?v=4 | moonshine | ashpil/moonshine | 2021-06-21T02:48:39Z | A spectral path tracer built with Zig + Vulkan | trunk | 0 | 123 | 5 | 123 | https://api.github.com/repos/ashpil/moonshine/tags | AGPL-3.0 | [
"raytracing",
"vulkan",
"zig"
]
| 26,605 | false | 2025-05-18T23:00:20Z | true | true | 0.14.0 | github | [
{
"commit": "fdbe6d60d1a937ee64f4e37c2acd0c76a7588f24.tar.gz",
"name": "vulkan_zig",
"tar_url": "https://github.com/Snektron/vulkan-zig/archive/fdbe6d60d1a937ee64f4e37c2acd0c76a7588f24.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/Snektron/vulkan-zig"
},
{
"commit": "9c77de5c3dd216f28e407eec65ed9c0a296c1f74.tar.gz",
"name": "vulkan_headers",
"tar_url": "https://github.com/KhronosGroup/Vulkan-Headers/archive/9c77de5c3dd216f28e407eec65ed9c0a296c1f74.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/KhronosGroup/Vulkan-Headers"
},
{
"commit": "master",
"name": "dcimgui",
"tar_url": "https://github.com/dearimgui/dear_bindings/releases/download/master_nogeneratedefaultargfunctions_2025-05-18T04-48-54/AllBindingFiles.zip/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/dearimgui/dear_bindings/releases/download/master_nogeneratedefaultargfunctions_2025-05-18T04-48-54/AllBindingFiles.zip"
},
{
"commit": "cdb5cbe6f8786ced227624a71bc8a677618e5327.tar.gz",
"name": "imgui",
"tar_url": "https://github.com/ocornut/imgui/archive/cdb5cbe6f8786ced227624a71bc8a677618e5327.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ocornut/imgui"
},
{
"commit": "e7ea71be039836da3a98cea55ae5569cb5eb885c.tar.gz",
"name": "glfw",
"tar_url": "https://github.com/glfw/glfw/archive/e7ea71be039836da3a98cea55ae5569cb5eb885c.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/glfw/glfw"
},
{
"commit": "735ff73ce5959cf005eb99ce517c9bcecab89dfb.tar.gz",
"name": "tinyexr",
"tar_url": "https://github.com/syoyo/tinyexr/archive/735ff73ce5959cf005eb99ce517c9bcecab89dfb.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/syoyo/tinyexr"
},
{
"commit": "b6579c3887c7ab0eef5f1eda09abbbc1f04d76ce.tar.gz",
"name": "zgltf",
"tar_url": "https://github.com/kooparse/zgltf/archive/b6579c3887c7ab0eef5f1eda09abbbc1f04d76ce.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/kooparse/zgltf"
},
{
"commit": "a29749ebe0be57d2b19d8406475bd2326d0f1a85.tar.gz",
"name": "wuffs",
"tar_url": "https://github.com/google/wuffs-mirror-release-c/archive/a29749ebe0be57d2b19d8406475bd2326d0f1a85.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/google/wuffs-mirror-release-c"
}
]
|
# Moonshine
**A spectral path tracer built with Zig + Vulkan**
<a></a>
<em>Salle de bain by nacimus, rendered with Moonshine</em>
Features
<ul>
<li>Binaries<ul>
<li>offline -- a headless offline renderer</li>
<li>online -- a real-time windowed renderer</li>
<li>hydra -- a hydra render delegate</li>
</ul>
</li>
<li>Light Transport<ul>
<li>Full spectral path tracing</li>
<li>Direct light sampling with multiple importance sampling for all lights and materials</li>
</ul>
</li>
<li>Lights<ul>
<li>360° environment maps</li>
<li>Sampled via <a>hierarchical warping</a></li>
<li>Emissive meshes</li>
<li>Sampled according to power via 1D <a>hierarchical warping</a></li>
</ul>
</li>
<li>Materials<ul>
<li>Standard PBR with metallic + roughness</li>
<li>Mirror</li>
<li>Glass with dispersion</li>
</ul>
</li>
<li>Homogeneous volumes</li>
</ul>
Dependencies
Build
<ul>
<li>zig (see version <a>in CI</a>)</li>
<li>DirectXShaderCompiler</li>
<li>For the online (real-time) renderer:</li>
<li>For Linux (Ubuntu, similar on others):<ul>
<li>For Wayland: <code>wayland-protocols</code> <code>libwayland-dev</code> <code>libxkbcommon-dev</code></li>
<li>For X11: <code>libxcursor-dev</code> <code>libxrandr-dev</code> <code>libxinerama-dev</code> <code>libxi-dev</code></li>
</ul>
</li>
</ul>
Run
<ul>
<li>A GPU supporting Vulkan ray tracing</li>
</ul>
License
This project is licensed under the AGPL. | []
|
https://avatars.githubusercontent.com/u/3291217?v=4 | async_io_uring | saltzm/async_io_uring | 2021-04-16T00:06:39Z | An event loop in Zig using io_uring and coroutines | main | 0 | 121 | 1 | 121 | https://api.github.com/repos/saltzm/async_io_uring/tags | MIT | [
"event-loop",
"io-uring",
"zig",
"zig-package"
]
| 157 | false | 2025-05-14T01:40:36Z | false | false | unknown | github | []
| Overview
<code>AsyncIOUring</code> is an event loop that wraps the <code>IO_Uring</code> library with coroutines
support. It supports all <code>IO_Uring</code> operations (with the intentional exception
of <code>poll_update</code>*).
In addition, it allows:
* Adding timeouts to operations
* Manual cancellation of operations
* Writing custom operations for advanced use cases
It is currently functionally complete, though there are a few <code>TODO</code>s marked in
the source related to polishing the API. It's not used in production anywhere currently.
See <code>src/async_io_uring.zig</code> for full API documentation.
See the <code>examples</code> directory for an echo client and server that use the event loop.
* If you need this for some reason, please create an issue.
<blockquote>
:warning: <strong>The <code>main</code> branch of <code>async_io_uring</code> will follow changes to zig's <code>master</code> branch to stay up-to-date with changes to the <code>IO_Uring</code> API (among others).</strong> See the tagged releases of <code>async_io_uring</code> that are marked to work with specific stable versions of zig. (E.g., release v0.1.0 works with zig 0.9.1)
</blockquote>
Table of contents
<ul>
<li><a>Background</a></li>
<li><a>Goals</a></li>
<li><a>Installation</a></li>
<li><a>Example usage</a><ul>
<li><a>Echo client</a></li>
<li><a>Operation timeouts</a></li>
<li><a>Operation cancellation</a></li>
</ul>
</li>
</ul>
Background
As an overview for the unfamiliar, <code>io_uring</code> is a new-ish Linux kernel feature
that allows users to enqueue requests to perform syscalls into a submission
queue (e.g. a request to read from a socket) and then submit the submission
queue to the kernel for processing.
When requests from the submission queue have been satisfied, the result is
placed onto completion queue by the kernel. The user is able to either poll
the kernel for completion queue results or block until results are
available.
Zig's <code>IO_Uring</code> library provides a convenient interface to the kernel's
<code>io_uring</code> functionality. The user of <code>IO_Uring</code>, however, still has to manually
deal with submitting requests to the kernel and retrieving events from the
completion queue, which can be tedious.
This library wraps the <code>IO_Uring</code> library by adding an event loop that handles
request submission and completion, and provides an interface for each syscall
that uses zig's <code>async</code> functionality to suspend execution of the calling code
until the syscall has been completed. This lets the user write code that looks
like blocking code, while still allowing for concurrency even within a single
thread.
Goals
<ul>
<li><strong>Minimal</strong>: Wraps the <code>IO_Uring</code> library in the most lightweight way
possible. This means it still uses the <code>IO_Uring</code> data structures in many
places, like for completion queue entries. There are no additional internal
data structures other than the submission queue and completion queue used by
the <code>IO_Uring</code> library. This means there's no heap allocation. It also relies
entirely on kernel functionality for timeouts and cancellation.</li>
<li><strong>Complete</strong>: You should be able to do anything with this that you could do
with <code>IO_Uring</code>.</li>
<li><strong>Easy to use</strong>: Because of the use of coroutines, code written with this
library looks almost identical to blocking code. In addition, operation
timeouts and cancellation support is integrated into the API for all operations.</li>
<li><strong>Performant</strong>: The library does no heap allocation and there's minimal
additional logic on top of <code>suspend</code>/<code>resume</code>. </li>
</ul>
Installation
This library integrates with the <a>zigmod</a>
package manager. If you've installed <code>zigmod</code>, you can add a line like the
following to your <code>root_dependencies</code> in the <code>zig.mod</code> file of your project
and run <code>zigmod fetch</code>:
<code>yml
root_dependencies:
- ...
- src: git https://github.com/saltzm/async_io_uring.git</code>
You'll then be able to include <code>async_io_uring.zig</code> by doing something like:
<code>zig
const io = @import("async_io_uring");</code>
The examples directory is structured roughly as you might structure a project
that uses <code>async_io_uring</code>, with a working <code>zig.mod</code> file and <code>build.zig</code> that
can serve as examples.
You'll also need a Linux kernel version that supports all of the <code>io_uring</code>
features you'd like to use. (All testing was done on version 5.13.0.)
Example usage
Echo client
Jumping right into a realistic example, the following is a snippet of code from
the echo client in the <code>examples</code> directory:
```zig
const io = @import("async_io_uring");
pub fn run_client(ring: *AsyncIOUring) !void {
// Make a data structure that lets us do async file I/O with the same
// syntax as <code>std.debug.print</code>.
var writer = try AsyncWriter.init(ring, std.io.getStdErr().handle);
<code>// Address of the echo server.
const address = try net.Address.parseIp4("127.0.0.1", 3131);
// Open a socket for connecting to the server.
const server = try os.socket(address.any.family, os.SOCK.STREAM | os.SOCK.CLOEXEC, 0);
defer {
_ = ring.close(server, null, null) catch {
std.os.exit(1);
};
}
// Connect to the server.
_ = try ring.connect(server, &address.any, address.getOsSockLen(), null, null);
const stdin_file = std.io.getStdIn();
const stdin_fd = stdin_file.handle;
var input_buffer: [256]u8 = undefined;
while (true) {
// Prompt the user for input.
try writer.print("Input: ", .{});
const read_timeout = os.linux.kernel_timespec{ .tv_sec = 10, .tv_nsec = 0 };
// Read a line from stdin with a 10 second timeout.
// This is the more verbose API - you can also do `ring.read`.
const read_cqe = ring.do(
io.Read{ .fd = stdin_fd, .buffer = input_buffer[0..], .offset = input_buffer.len },
io.Timeout{ .ts = &read_timeout, .flags = 0 },
null,
) catch |err| {
if (err == error.Cancelled) {
try writer.print("\nTimed out waiting for input, exiting...\n", .{});
return;
} else return err;
};
const num_bytes_read = @intCast(usize, read_cqe.res);
// Send it to the server.
_ = try ring.send(server, input_buffer[0..num_bytes_read], 0, null, null);
// Receive response.
const recv_cqe = try ring.recv(server, input_buffer[0..], 0, null, null);
const num_bytes_received = @intCast(usize, recv_cqe.res);
try writer.print("Received: {s}\n", .{input_buffer[0..num_bytes_received]});
}
</code>
}
```
Operation timeouts
<code>AsyncIOUring</code> supports adding timeouts to all operations. Adding a timeout to
an operation causes it to be cancelled after the specified timeout, returning
an error code <code>error.Cancelled</code> if cancellation was successful.
An example from the unit tests:
```zig
fn testReadThatTimesOut(ring: *AsyncIOUring) !void {
var read_buffer = [_]u8{0} ** 20;
<code>const ts = os.linux.kernel_timespec{ .tv_sec = 0, .tv_nsec = 10000 };
// Try to read from stdin - there won't be any input so this should
// reliably time out.
const read_cqe = ring.do(
Read{ .fd = std.io.getStdIn().handle, .buffer = read_buffer[0..], .offset = 0 },
Timeout{ .ts = &ts, .flags = 0 },
null,
);
try std.testing.expectEqual(read_cqe, error.Cancelled);
</code>
}
```
Operation cancellation
<code>AsyncIOUring</code> supports cancellation for all operations. Each operation is
identified by an <code>id</code> that is set via a <code>maybe_id</code> "output parameter" in all
operation submission functions (e.g. <code>read</code>, <code>send</code>, etc.). This <code>id</code> can then
be passed to <code>AsyncIOUring.cancel</code> to cancel that operation.
An example from the unit tests:
```zig
fn testReadThatIsCancelled(ring: *AsyncIOUring) !void {
var read_buffer = [_]u8{0} ** 20;
<code>var op_id: u64 = undefined;
// Try to read from stdin - there won't be any input so this operation should
// reliably hang until cancellation.
var read_frame = async ring.do(
Read{ .fd = std.io.getStdIn().handle, .buffer = read_buffer[0..], .offset = 0 },
null,
&op_id,
);
const cancel_cqe = try ring.cancel(op_id, 0, null, null);
// Expect that cancellation succeeded.
try std.testing.expectEqual(cancel_cqe.res, 0);
const read_cqe = await read_frame;
try std.testing.expectEqual(read_cqe, error.Cancelled);
</code>
}
``` | []
|
https://avatars.githubusercontent.com/u/5728002?v=4 | IUPforZig | batiati/IUPforZig | 2021-06-19T23:19:14Z | IUP (Portable User Interface Toolkit) bindings for the Zig language. | master | 2 | 120 | 4 | 120 | https://api.github.com/repos/batiati/IUPforZig/tags | Unlicense | [
"gui",
"iup",
"iup-gui-library",
"iup-toolkit",
"multiplatform",
"zig",
"zig-package",
"ziglang"
]
| 3,719 | false | 2025-03-25T23:27:17Z | true | false | unknown | github | []
| 404 | []
|
https://avatars.githubusercontent.com/u/90459844?v=4 | zigbyexample.github.io | zigbyexample/zigbyexample.github.io | 2021-09-10T13:15:58Z | Learn How to use Zig's Standard Library, by simple and small examples. | main | 1 | 116 | 12 | 116 | https://api.github.com/repos/zigbyexample/zigbyexample.github.io/tags | MIT | [
"example",
"learn",
"tutorial",
"zig",
"zig-by-example",
"zigbyexample"
]
| 964 | false | 2025-01-13T06:39:58Z | false | false | unknown | github | []
| Zig by Example [DEPRECATED]
Please see <a>ziglearn.org</a> for a more complete guide | []
|
https://avatars.githubusercontent.com/u/39384757?v=4 | rem | chadwain/rem | 2021-08-23T05:47:27Z | An HTML parsing library, written in Zig. | master | 1 | 115 | 12 | 115 | https://api.github.com/repos/chadwain/rem/tags | GPL-3.0 | [
"dom",
"html",
"parser",
"zig"
]
| 1,085 | false | 2025-04-25T15:48:18Z | true | true | unknown | github | []
| rem
rem is an HTML5 parser written in <a>Zig</a>.
About
Features
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> An HTML5 parser consisting of a tokenizer (complete) and a tree constructor (works "well enough")
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> A minimal DOM implementation
<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> HTML fragment parsing
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Tested by <a>html5lib-tests</a>
Things to be improved
<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> Better DOM functionality
<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 for more character encodings
<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 for Javascript
Why create this?
<ul>
<li>To understand what it takes "implement" HTML, even if just a small portion of it. As I discovered, even just trying to parse an HTML file <em>correctly</em> can be quite challenging.</li>
<li>To learn more about web standards in general. Reading the HTML spec naturally causes (or rather, forces) one to learn about DOM (especially), SVG, CSS, and many others.</li>
<li>For use in other projects, and to be useful to others.</li>
</ul>
Lastly...
rem is still a work in progress. Not all the features of a fully-capable HTML5 parser are implemented.
Get the code
Clone the repository like this:
<code>git clone --recursive --config core.autocrlf=false https://github.com/chadwain/rem.git</code>
There are no dependencies other than a Zig compiler. Note that this library is only compatible with Zig version 0.11.0 or newer.
Use the code
Here's an example of using the parser. You can see the output of this program by running <code>zig build example</code>.
```zig
const std = @import("std");
const rem = @import("rem");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == .ok);
const allocator = gpa.allocator();
<code>// This is the text that will be read by the parser.
// Since the parser accepts Unicode codepoints, the text must be decoded before it can be used.
const input = "<!doctype html><html><h1 style=bold>Your text goes here!</h1>";
const decoded_input = &rem.util.utf8DecodeStringComptime(input);
// Create the DOM in which the parsed Document will be created.
var dom = rem.dom.Dom{ .allocator = allocator };
defer dom.deinit();
// Create the HTML parser.
var parser = try rem.Parser.init(&dom, decoded_input, allocator, .report, false);
defer parser.deinit();
// This causes the parser to read the input and produce a Document.
try parser.run();
// `errors` returns the list of parse errors that were encountered while parsing.
// Since we know that our input was well-formed HTML, we expect there to be 0 parse errors.
const errors = parser.errors();
std.debug.assert(errors.len == 0);
// We can now print the resulting Document to the console.
const stdout = std.io.getStdOut().writer();
const document = parser.getDocument();
try rem.util.printDocument(stdout, document, &dom, allocator);
</code>
}
```
Test the code
rem uses <a>html5lib-tests</a> as a test suite. Specifically, it tests against the 'tokenizer' and 'tree-construction' tests from that suite.
<code>zig build test-tokenizer</code> will run the 'tokenizer' tests.
<code>zig build test-tree-construction</code> will run the 'tree-construction' tests in 2 ways: with scripting disabled, then with scripting enabled.
The expected results are as follows:
- tokenizer: All tests pass.
- tree-construction (scripting disabled): Some tests are skipped because they rely on HTML features that aren't yet implemented in this library (specifically, templates). All other tests pass.
- tree-construction (scripting enabled): Similar to testing with scripting off, but in addition, some entire test files are skipped because they would cause panics.
License
GPL-3.0-only
Copyright (C) 2021-2023 Chadwain Holness
rem is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this library. If not, see <a>https://www.gnu.org/licenses/</a>.
References
<a>HTML Parsing Specification</a>
<a>DOM Specification</a> | []
|
https://avatars.githubusercontent.com/u/919553?v=4 | zigstr | jecolon/zigstr | 2021-06-29T14:59:45Z | Zigstr is a UTF-8 string type for Zig programs. | main | 0 | 111 | 4 | 111 | https://api.github.com/repos/jecolon/zigstr/tags | - | [
"string",
"unicode",
"utf-8",
"zig"
]
| 1,949 | false | 2025-02-10T21:35:45Z | false | false | unknown | github | []
| zigstr
zigstr is now at: https://codeberg.org/dude_the_builder/zigstr | [
"https://github.com/Interrupt/zig-bgfx-example"
]
|
https://avatars.githubusercontent.com/u/4075241?v=4 | bytebox | rdunnington/bytebox | 2021-10-23T02:23:07Z | Standalone WebAssembly VM. | main | 14 | 101 | 5 | 101 | https://api.github.com/repos/rdunnington/bytebox/tags | MIT | [
"wasi",
"wasm",
"wasm-interpreter",
"zig",
"zig-package"
]
| 2,192 | false | 2025-05-13T18:41:13Z | true | true | 0.13.0 | github | [
{
"commit": "bbb120cd0e4a8a83a21217e67ab6d7697a809756.tar.gz",
"name": "zig-stable-array",
"tar_url": "https://github.com/rdunnington/zig-stable-array/archive/bbb120cd0e4a8a83a21217e67ab6d7697a809756.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/rdunnington/zig-stable-array"
}
]
| Bytebox
<a></a>
Bytebox is a WebAssembly VM.
Getting started
Requirements
Bytebox currently builds with <a>Zig 0.13.x</a> to avoid churn on zig master.
To run the tests:
* <code>wasm-tools</code> is required to run the wasm testsuite. You can install it via the rust toolchain <code>cargo install wasm-tools</code> or directly from the <a>release page</a>.
* <code>python3</code> is required to run the wasi testsuite. You may need to run <code>python3 -m pip install -r test/wasi/wasi-testsuite/test-runner/requirements.txt</code> to ensure the wasi test runner has all the necessary dependencies installed.
Run Tests
<code>sh
git clone --recurse-submodules https://github.com/rdunnington/bytebox.git
cd bytebox
zig build test-unit # run builtin zig unit tests
zig build test-wasm # run official wasm spec testsuite
zig build test-wasi # run official wasi spec testsuite
zig build test-mem64 # run memory64 compat test
zig build test # run all of the above in parallel (output will not be pretty!)</code>
Usage
You can use the standalone runtime to load and execute WebAssembly programs:
<code>sh
zig build run -- <file> [function] [function args]...</code>
Or embed Bytebox in your own programs:
```zig
// build.zig
const std = @import("std");
pub fn build(b: *std.build.Builder) void {
const exe = b.addExecutable("my_program", "src/main.zig");
exe.addPackage(std.build.Pkg{
.name = "bytebox",
.source = .{ .path = "bytebox/src/core.zig" }, // submodule in the root dir
});
exe.setTarget(b.standardTargetOptions(.{}));
exe.setBuildMode(b.standardReleaseOptions());
exe.install();
const run = exe.run();
const step = b.step("run", "runs my_program");
step.dependOn(&run.step);
}
// main.zig
const std = @import("std");
const bytebox = @import("bytebox");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator: std.mem.Allocator = gpa.allocator();
<code>const wasm_data: []u8 = try std.fs.cwd().readFileAlloc(allocator, "example.wasm", 1024 * 128);
defer allocator.free(wasm_data);
const module_def = try bytebox.createModuleDefinition(allocator, .{});
defer module_def.destroy();
try module_def.decode(wasm_data);
const module_instance = try bytebox.createModuleInstance(.Stack, module_def, allocator);
defer module_instance.destroy();
try module_instance.instantiate(.{});
</code>
}
```
Inter-language FFI is also supported. See <code>src/bytebox.h</code> for an overview in C. To use bytebox as a static library, link with the built library in <code>zig-out/lib/</code>. Note that Zig assumes a default stack size of 8MB, so you'll need to ensure the same in your program.
Status
This project is still in the alpha stage.
| Legend | Meaning |
| --- | --- |
|✅|Implemented|
|❌|TODO|
|💀|Not planned/Removed from spec|
<a>WebAssembly</a> support:
| Status | Feature |
| --- | --- |
|✅|WebAssembly 1.0|
|✅|Sign extension instructions|
|✅|Non-trapping float-to-int conversion|
|✅|Multiple values|
|✅|Reference types|
|✅|Table instructions|
|✅|Multiple tables|
|✅|Bulk memory and table instructions|
|✅|Vector instructions|
<a>WASI Preview 1</a> support:
| Status | Feature |
| --- | --- |
|✅|args_get|
|✅|args_sizes_get|
|✅|environ_get|
|✅|environ_sizes_get|
|✅|clock_res_get|
|✅|clock_time_get|
|✅|fd_advise|
|✅|fd_allocate|
|✅|fd_close|
|✅|fd_datasync|
|✅|fd_fdstat_get|
|✅|fd_fdstat_set_flags|
|💀|fd_fdstat_set_rights|
|✅|fd_filestat_get|
|✅|fd_filestat_set_size|
|✅|fd_filestat_set_times|
|✅|fd_pread|
|✅|fd_prestat_get|
|✅|fd_prestat_dir_name|
|✅|fd_pwrite|
|✅|fd_read|
|✅|fd_readdir|
|✅|fd_renumber|
|✅|fd_seek|
|❌|fd_sync|
|✅|fd_tell|
|✅|fd_write|
|✅|path_create_directory|
|✅|path_filestat_get|
|✅|path_filestat_set_times|
|❌|path_link|
|✅|path_open|
|❌|path_readlink|
|✅|path_remove_directory|
|❌|path_rename|
|✅|path_symlink|
|✅|path_unlink_file|
|❌|poll_oneoff|
|✅|proc_exit|
|💀|proc_raise|
|❌|sched_yield|
|✅|random_get|
|❌|sock_accept|
|❌|sock_recv|
|❌|sock_send|
|❌|sock_shutdown|
Roadmap
These tasks must be completed to enter alpha:
* API ergonomics pass
* Documentation
* General TODO/code cleanup
* Crash hardening/fuzzing
To enter beta:
* No breaking API changes after this point
* Performance competitive with other well-known interpreters (e.g. <a>micro-wasm-runtime</a>, <a>wasm3</a>)
To have a 1.0 release:
* Tested with a wide variety of wasm programs
* Successfully used in other beta-quality projects | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | ziglint | nektro/ziglint | 2021-08-23T02:16:09Z | A linting suite for Zig | master | 21 | 100 | 3 | 100 | https://api.github.com/repos/nektro/ziglint/tags | MIT | [
"lint",
"linter",
"zig"
]
| 92 | false | 2025-05-04T11:15:43Z | true | false | unknown | github | []
| ziglint
<a></a>
A linting suite for Zig.
Usage
<code>$ ./ziglint</code>
This will search the current directory for <code>.zig</code> files and lint them against the various tests in the suite. See the <a>bad/</a> folder for examples of the caught lints.
Installation
This requires having <a>Zig</a> and <a>Zigmod</a> installed.
<ul>
<li>https://ziglang.org/download/</li>
<li>https://github.com/nektro/zigmod/releases</li>
</ul>
<code>sh
$ zigmod aq install 1/nektro/ziglint</code>
Built With
<ul>
<li>Zig master <code>0.11.0</code></li>
<li><a>Zigmod</a> package manager</li>
<li>See <a><code>zig.mod</code></a></li>
</ul>
Available Rules
<ul>
<li><code>dupe_import</code>: warn against duplicate <code>@import</code> calls with the same value</li>
<li><code>todo</code>: list all <code>// TODO</code> comments</li>
<li><code>file_as_struct</code>: checks for file name capitalization in the presence of top level fields</li>
<li><code>unused_decl</code>: checks for unused container level <code>const</code>/<code>var</code>s</li>
</ul>
Want to propose more? Open an issue here on Github.
Using in Github Actions
```yml
jobs:
lint:
runs-on: ubuntu-latest
<code>steps:
- uses: actions/checkout@v2
- name: Setup Zig
uses: goto-bus-stop/setup-zig@v1
with:
version: "0.11.0"
- uses: nektro/actions-setup-zigmod@v1
- run: zigmod aq install 1/nektro/ziglint
- run: ~/.zigmod/bin/ziglint -skip todo
</code>
```
License
MIT | []
|
https://avatars.githubusercontent.com/u/39014565?v=4 | zoltan | ranciere/zoltan | 2021-11-26T09:33:05Z | A Sol-inspired minimalist Lua binding for Zig. | main | 7 | 98 | 9 | 98 | https://api.github.com/repos/ranciere/zoltan/tags | MIT | [
"lua",
"metaprogramming",
"zig"
]
| 445 | false | 2025-05-03T15:14:45Z | true | false | unknown | github | []
|
zoltan
A Sol-inspired minimalist Lua binding for Zig.
Features
<ul>
<li>Supports Zig 0.9.0</li>
<li>Lua tables</li>
<li>table creation from Zig</li>
<li>get/set/create methods</li>
<li>possible key types: numerical, string</li>
<li>Scalars</li>
<li>int, float, bool</li>
<li>Lua string (equals <code>[] const u8</code>)</li>
<li>Functions</li>
<li>calling Zig function from Lua and vice-versa</li>
<li>Zig functions can accept<ul>
<li>scalars, Lua types (table, functions, custom types)</li>
</ul>
</li>
<li>Custom types</li>
<li>registered types could be instantiated from Lua</li>
<li>public functions are registered in Lua</li>
<li>supports <code>self</code></li>
<li>Scalar array support (equals Lua tables without metatables + numeric keys)</li>
<li>All of the supported use-cases are intensively tested & leak-free</li>
</ul>
Tutorial
Installing
In addition to the binding facilities, <code>zoltan</code> contains the vanilla Lua source (v5.4.3) and the necessary code to compile it. If <code>zoltan</code> is installed in the <code>third_party</code> library in your application's root, then you have to add to your <code>build.zig</code> the following:
```zig
// At the beginning of the file
const addLuaLib = @import("third_party/zoltan/build.zig").addLuaLibrary;
pub fn build(b: *std.build.Builder) void {
...
// Exe part
exe.addPackage(.{ .name = "lua", .path = .{ .path="third_party/zoltan/src/lua.zig" }});
addLuaLib(exe, "third_party/zoltan/");
...
// Test part
const lua_tests = b.addTest("third_party/zoltan/src/tests.zig");
addLuaLib(lua_tests, "third_party/zoltan/");
lua_tests.setBuildMode(mode);
```
You can found an example integration <a>here</a>.
Instantiating and destroying Lua engine
```zig
const Lua = @import("lua").Lua;
...
pub fn main() anyerror!void {
...
var lua = try Lua.init(std.testing.allocator);
defer lua.destroy();
lua.openLibs(); // Open common standard libraries
```
Running Lua code
<code>zig
_ = lua.run("print('Hello World!')");</code>
Getting/setting Lua global varibles
```zig
lua.set("int32", 42);
var int = lua.get(i32, "int32");
std.log.info("Int: {}", .{int}); // 42
lua.set("string", "I'm a string");
const str = lua.get([] const u8, "string");
std.log.info("String: {s}", .{str}); // I'm a string
```
Resource handling
The following functions acquire some kind of resource (heap, Lua reference):
<ul>
<li><code>getResource</code></li>
<li><code>createTable</code></li>
<li><code>createUserType</code></li>
</ul>
You have to release the acquired resources by calling the <code>release</code> method:
<code>zig
var tbl = try lua.createTable();
....
lua.release(tbl); // You have to release</code>
Lua tables
```zig
var tbl = try lua.createTable();
defer lua.release(tbl);
lua.set("tbl", tbl);
var inTbl = try lua.createTable();
// Set, integer key
inTbl.set(1, "string");
inTbl.set(2, 3.1415);
inTbl.set(3, 42);
var tst1 = inTbl.get([]const u8, 1);
var tst2 = inTbl.get(f32, 2);
var tst3 = inTbl.get(i32, 3);
try std.testing.expect(std.mem.eql(u8, test1, "string"));
try std.testing.expect(tst2 == 3.1415);
try std.testing.expect(tst3 == 42);
// Set, string key
inTbl.set("bool", true);
var tst4 = inTbl.get(bool, "bool");
try std.testing.expect(tst4 == true);
// Set table in parent
tbl.set("inner", inTbl);
// Now we can release the inTbl directly (tbl refers it)
lua.release(inTbl);
```
Calling Lua function from Zig
```zig
_ = lua.run("function double_me(a) return 2*a; end");
var doubleMe = lua.get(Lua.Function(fn(a: i32) i32), "double_me");
// As Zig doesn't handle variable args, one should pass the arguments as anonymous struct
var res = doubleMe.call(.{42});
std.log.info("Result: {}", .{res}); // 84
```
Calling Zig function from Lua
```zig
var testResult: i32 = 0;
fn test_fun(a: i32, b: i32) void {
std.log.info("I'm a test: {}", .{a<em>b});
testResult = a</em>b;
}
...
lua.set("test_fun", test_fun);
lua.run("test_fun(3,15)");
try std.testing.expect(testResult == 45);
```
Passing Lua function to Zig function
<code>zig
fn testLuaInnerFun(fun: Lua.Function(fn(a: i32) i32)) i32 {
var res = fun.call(.{42}) catch unreachable;
std.log.warn("Result: {}", .{res});
return res;
}
...</code>
Mechanism on Zig side
```zig
lua.run("function getInt(a) print(a); return a+1; end");
var luafun = try lua.getResource(Lua.Function(fn(a: i32) i32), "getInt");
defer lua.release(luafun);
var result = testLuaInnerFun(luafun);
std.log.info("Zig Result: {}", .{result});
```
Mechanism on Lua side
```zig
lua.set("zigFunction", testLuaInnerFun);
const lua_command =
\function getInt(a) print(a); return a+1; end
\print("Preppare");
\zigFunction(getInt);
\print("Oppare");
;
lua.run(lua_command);
```
Custom types
Registering Zig structs in Lua
```zig
const TestCustomType = struct {
a: i32,
b: f32,
c: []const u8,
d: bool,
<code>pub fn init(_a: i32, _b: f32, _c: []const u8, _d: bool) TestCustomType {
return TestCustomType{ ... };
}
pub fn destroy(_: *TestCustomType) void {}
pub fn getA(self: *TestCustomType) i32 { return self.a; }
pub fn getB(self: *TestCustomType) f32 { return self.b; }
pub fn getC(self: *TestCustomType) []const u8 { return self.c; }
pub fn getD(self: *TestCustomType) bool { return self.d; }
pub fn reset(self: *TestCustomType) void {
self.a = 0;
self.b = 0;
self.c = "";
self.d = false;
}
pub fn store(self: *TestCustomType, _a: i32, _b: f32, _c: []const u8, _d: bool) void {
self.a = _a;
self.b = _b;
self.c = _c;
self.d = _d;
}
</code>
};
...
// <strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong>
try lua.newUserType(TestCustomType);
// <strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong>
```
Instantiating custom type in Zig
```zig
var obj = try lua.createUserType(TestCustomType, .{42, 42.0, "life", true});
defer lua.release(obj);
// One can access the inner struct via the ptr field
std.testing.expect(obj.ptr.getA() == 42);
// One can set as global
lua.set("zigObj", obj);
// And then use it
lua.run("zigObj:reset()");
std.testing.expect(obj.ptr.getA() == 0);
```
Instantiating custom type in Lua
```zig
lua.run("obj = TestCustomType.new(42, 42.0, 'life', true)");
// Get as a reference (it doesn't hold reference to the inner object,
// therefore the lifetime is managed totally by the Lua engine
// => storing is dangerous)
var ptr = try lua.get(*TestCustomType, "obj");
std.testing.expect(ptr.getA() == 42);
```
TODO
In order of importance:
- The current error handling is a little bit rustic, sometimes rough :) A proper error handling strategy would be better.
- Run Lua code from file
- zigmod support
- LuaJIT support
- <code>Lua.Table</code> should deep-copy between table and user structs
- Lua Coroutine support
- <code>Lua.Table</code> should support JSON
- Option for building without libc (if possible)
- Performance benchmarks | []
|
https://avatars.githubusercontent.com/u/86482337?v=4 | jaz | zig-java/jaz | 2021-05-29T18:29:27Z | A JVM implementation in Zig! | main | 1 | 91 | 5 | 91 | https://api.github.com/repos/zig-java/jaz/tags | - | [
"java",
"jaz",
"jvm",
"zig"
]
| 186 | false | 2025-04-16T05:45:26Z | true | false | unknown | github | []
| jaz
<strong>Ja</strong>va in <strong>Z</strong>ig.
Parses Java class files and bytecode.
Taking it for a spin
To try out jaz for yourself, install jvm 16, then run the following commands:
```bash
Compiles Java source
javac test/src/jaztest/*.java
Adds user path to javastd
echo "pub const conf = .{.javastd_path = \"/path/to/javastd\"};" > src/conf.zig
Runs demo
zig build run
``` | []
|
https://avatars.githubusercontent.com/u/13558411?v=4 | Cpp-Go-Zig-Odin | phillvancejr/Cpp-Go-Zig-Odin | 2022-02-07T04:53:38Z | A series of small programs/tasks to compare C++, Go, Zig, Odin, D, Janet, Swift, Nim and C# to see which I like the most | main | 1 | 90 | 4 | 90 | https://api.github.com/repos/phillvancejr/Cpp-Go-Zig-Odin/tags | - | [
"cpp",
"csharp",
"dlang",
"go",
"golang",
"janet",
"janet-lang",
"nim",
"nim-lang",
"odin",
"swift",
"zig",
"ziglang"
]
| 22,388 | false | 2025-04-19T07:48:29Z | false | false | unknown | github | []
| C++ vs Go vs Zig vs Odin vs D vs Janet vs Swift vs Nim
A series of small test programs to figure out which of the languages I like best. I don't plan on dropping C++ but I'd be willing to replace Go with Zig or Odin if I like them.
UPDATE 08/28/23
Go vs C
I think C# has earned its place for me as a primary tool. I still love Go due to its simplicity so I'll still find use for it, especially for Wasm graphics demos since .NET wasm is too large currently, though if a future version of .NET wasm (or a js compiler) can produce small enough code I'll reconsider C# for browser graphic demos. Here are the pros and cons for me of Go vs C#:
Go
<ul>
<li><code>+</code> Simple</li>
<li><code>+</code> super easy C/ffi interop</li>
<li><code>+</code> Easy and small distributable executables</li>
<li><code>+</code> Feels like C plus</li>
<li><code>+</code> Wails for UI is cool</li>
<li><code>+</code> Fyne for UI is simple</li>
<li><code>-</code> Wails for UI uses 4 langauges, html, css, javascript & Go</li>
<li><code>-</code> Wails (and most webview based uis) on mac has startup flash/flicker</li>
<li><code>-</code> Fyne doesn't support topmost/always on top windows</li>
</ul>
C
<ul>
<li><code>+</code> flexible distribution with .NET reliant programs which are very light and also self contained executables</li>
<li><code>+</code> LINQ is cool</li>
<li><code>+</code> Blazor is cool</li>
<li><code>+</code> MAUI is cool</li>
<li><code>+</code> Avalonia is for me, the best cross platform gui framework in any language</li>
<li><code>+</code> Unity</li>
<li><code>+</code> Godot</li>
<li><code>+</code> ASP.NET </li>
<li><code>-</code> Non Native self contained .NET exe's are about 5 times the size of go</li>
<li><code>-</code> wasm is currently very large at around 4 Mb</li>
<li><code>?</code> always adding new often useful features, maybe the most rapidly developing language and platform. This could be good or bad but so far I like the direction its headed so mostly positive for me, but it does make the language/platform harder and harder to learn.</li>
</ul>
I have use cases for both languages. If C# is too slow/large as in the case of wasm I'd probably use Go and if that is even larger/slower than I want I can always use C++. I think between Go, C#, C++ and Javascript, I've got most of my interests covered
C
C# enters the competition. I've been keeping an eye on .NET and C# for a while and the last few versions of .NET have been focusing on some very cool features that I've been waiting to test, namely: Wasm, Top Level Statements (C# 9) and new Native Aot with .NET 8.
The Native AOT is very cool allowing C# to be compiled into small self contained executables and brings C# closer to Go in terms of distribution. The coolest feature for me personally is that Native AOT exes can not only call into foreign libraries but actually statically link native libraries as well. This makes C# a compelling choice especially for me, due to the .NET MAUI and Avalonia libraries for GUI programming.
C++
I love C++. Despite its ugly bits, its still my favorite. And programming successfully in it makes me feel like a superhero even with trivial programs
Go
Even though it was eliminated early on, I will probably still use it for small tools using Webview because its networking support is just too good.
UPATE 04/27/22
Go is un-eliminated after rewriting the opengl example directly against C myself and I think that after using it for a few projects out side of this where in one case it actually replaced a previously C++ version, it might be dethroning C++ as my favorite.
Zig
Zig is super interesting and I definitely want to explore it further. There is an imporant note on the compile times I recorded. Zig was consistently significantly slower than the others, however I actuallys poke with Andrew Kelly the creator of Zig on discord about this and He mentioned that the compile times will dramatically improve when the self hosted incremental compiler is finished which is about 66% of the way there (as of 02/13/2022). Despite its verbosity I really love the language's approach to memory management (via allocators) and error handling. Also Zig can be used as a cross compiling C and C++ (and I think also Objective C ) compiler. I've even read a couple Go articles in which Zig is used to cross compile Go applications using Cgo. It has a cool build system using the language itself as the build language. I will absolutely be playing with it more in the future.
Odin
Odin is also awesome. It feels like the most high level out of these due to its syntax. It isn't as far along with some things like networking but it has great bindings for many game and media libraries out of the box (though on mac I had to do some manual building). Its pretty cool and I would even consider replacing Go with it since superficially they are similar. In fact once Odin gets standard networking I will revisit and consider replacing Go with it. Also I complained a lot about Odin's strong typing and strict casting, however of course this was greatly exaggerated by my misunderstanding. You can mitigate the casting by precasting things that you will use a lot, and also by using constants wherever possible as these are "untyped" and coerce to other types easily
D
I added D during the platformer task and found it is interesting. In many ways it does improve on C++. But its kind of a pain to use in wasm which is important for me, so I won't be using it further.
Janet
see upate below
I added a weird language called <a>Janet</a> recently. Janet is a lisp like language which can be embedded in and extended with C, similar to <a>Mruby</a>. I had come acrossed it many times before but just wrote it off as another weird Lisp, but recently (Late Feb 2022) I've been revisiting Lisps thanks to <a>Bagger's awesome video</a> of recompiling a 3d demo as it runs. I began learning Common Lisp with SBCL and had intended to use Emacs and Slime/Swank for development but... I detest Emacs. Ha ha, the bindings are just too unnatural for me coming from Vim. I know there is the Spacemacs plugin to make it more like vim but I couldn't get it to work on Mac Catalina. And so I decided to give up on Lisps for good as my thinking was that Emacs it the best Lisp environment and if I can't use the best environment I'm just not going to use it at all. Well I came to <a>Alive</a> in VSCode and a project called <a>Conjure</a> for <a>Neovim</a> and these worked well and were easy to set up.
Janet is much simpler and smaller than Common Lisp and this was attractive to me. And so I decided that if I could get live reloading for Janet working like Baggers showed in his Lisp video then I'd use it. Well Janet has a package called <a>spork</a> which contains, among other things, a SWANK like server for Janet. And so spork along with Conjure and Neovim allowed me to have my live reloading development, and so I decided to learn Janet.
Janet is awesome. Once you get passed the strange S expression syntax is it very fun. Of course complex expressions are still hard to read but to me its other merits are worth it. It comes with networking, coroutines/fibers (green threads) and real native (OS)threading, with (to my knowledge) no GIL. To me the final feature that made Janet really worth using is the fact that using its easy to install package manager <a>jpm</a> you can compile your project to standalone binaries. And the size is quite reasonable for a non systems language: the Pong example using Raylib is about 2.4MB on Mac OS Catalina. Additionally it has a great set of bindings to Raylib called <a>Jaylib</a> which map very closely to the C api, much closer than the Commmon Lisp bindings I found. Since Janet is a small virtual machine that can be embedded in C, it should be trivial to compile it for the browser via Wasm and Emscripten, and the official documentation even mentions this. Also in the <a>gitter channel</a> a user mentioned that he has successfully used the Jaylib bindings with emscripten. It has std library socket wrappers and an "official" community <a>http server</a>. It even has Webview <a>bindings</a>, however I may write my own since these are very old and because I maintain my own fork of <a>Webview</a>.
Overall I really liked Janet and I think it will be dethroning Go as my secondary language.
UPATE 04/27/22
I learned more about and worked with Janet last month. Toward the end I ended up writing OpenGl bindings which were quite capable though not complete. However I found compiling to wasm much more difficult than I originally thought. Compiling Janet to wasm via emscripten is quite easy, however my OpenGL bindings are a large project with many submodules and the Janet C embedding api doesn't have support for preserving this module structure when exposing bindings, that is to say that all my gl functions would be exposed in the global scope, meaning my module imports wouldn't work. The workaround is to create a dummy project structure that imports all the functions from the global scope in the proper modules, however this was much more than I wanted to do. I really liked Janet, but this event led me to abandon the gl bindings and go back to Go which I'm quite happy with now.
Swift
Added swift on 6/1/22. I forgot about swift during the project. Swift has made a lot of progress towards cross compatibility and as of 2022, Swift runs on Mac, Linux, Windows and Wasm. On Windows a lot of effort has been invested to allow Swift to interop with the win32 api and so completely native applications can be written in pure swift for both Mac and Windows using their native bindings. Swift is not garbage collected, although technically it is since reference counting is a form of garbage collection, but it wont' suffer from GC pauses. It is a proven language, it is obviously used extensively (almost exclusively) on Mac OS for everything from Applications to games. I imagine that these days virtually all games are written in Swift for IOS and so it is a proven games programming language even though I've never seen it mentioned in discussions about games languages. I assume that Swift can't run on any consoles currently and this might be the reason it is not mentioned in game language discussions, but then again Python is quite popular amongs hobbyist and no one is even thinking of running Python on consoles. It can't cross compile like Go or Zig unfortunately. It is really nice and looks and feels like a GC'd scripting language but compiles natively. It feels a lot like Rust without the borrow checker, and it predates Rust as far as I know.
Swift is fun and it was really nice to use. However I think the thing that might hold it back for me is that even though it is supported on Windows and Linux, I don't know of any cross platform networking api that would allow for tcp or udp servers. Though its great C interop does mean that something like SDL_Net, Enet or Mongoose could be used
Nim
Nim is pretty cool. Its similar to Go in that it has a lot of libraries included. I'd say that interop with C is easier in Nim because the types map more closely to C. In Nim an array is the same as a C array so there is no funny business with wrapping unsafe slices like in Go. I'd say that Nim is in general better than Go for graphics, however nothing I've tested so far can beat Go's easy concurrency. So for everything except highly concurrent networking I'd say that I actaully prefer Nim over Go. Also Nim's module system is in my opinion better than Go's. Go's system requires specific file layouts and when testing a repo on github and pushing and pulling I found that I had to make sure Go wasn't caching the changes and used the latest commits which I forget how to do often, however with Nim its like Python, you just import the file and its the file that is in the import path. Nim is more complex language than Go in terms of what you can do, but in practice I found that the complexity of say macros don't really seem to show. If you're learning macros they are quite complex but they exist in many places and can be used without necessarily knowing how they are implemented. Back to Nim's C interop, you do have to write bindings, however the c2nim tool which can be installed via the nimble package manager is excellent. I was able to generate nim bindings to the emoon's <a>minifb </a> library very easily and the only thing I needed to do manually was insert importing code for a single struct, and then embed the linking flags. I'd say this is better than Go because even though Go can just include C with cgo, interacting with that C from Go often involves trickery due to Go's view of C as unsafe and because Go has strict rules about passing memory back and forth with C code.
First class compilation to Javascript is cool.
The funny thing is, I'd say that overall Nim is a better language than Go when it comes to interop with C, maybe syntax aesthetics if you care about that (I don't really), and definitely its module system, however Nim also feels really generic. It is definitely a general purpose language and doesn't really shine in any area. Go shines in networking, concurrency, compile times and simplicity and even though it brings some irritations and annoyances with things like its C interop, at least it has a reason for being. Nim is a cool language dont get me wrong, but it doesn't really feel like it has a reason to exist. Nim makes most everything easier (at least easier than C and C++) but it doesn't necessarily make anything awesome. I'd say that Nim is good for people who want a compiled language and are very concerned about how code looks. I mean I have to say I do think Nim is the best looking language of the lot.
My rankings
Graphics
Place
Language
Notes
1
Odin
Odin has built in libraries for Opengl, Metal, DirectX 11 & 12, Vulkan and WebgL 1 & 2. The Language also has builtin in array component wise operations which can be used for basic vector math as builtin in Matrix and Quaternion types and libraries containing all the game math you'd have to install as a separate library in every other language. It has builtin bindings to SDL net and Enet for networking. I don't think wasm with Odin and OpenGL isn't too difficult, you should just need to use the WebGL libraries instead of the OpenGL ones which should just be a matter of conditional imports. I haven't tried this specifically but I'm confident it would work for the most part
2
C++
Obviously pretty much all the libraries are written in C or C++. The only reason it isn't number 1 is because with Odin link flags are embedded in the libraries so you don't have to worry about build flags like in C++ and because Odin has built in support for Vectors, Matrices and Quaternions. But if you don't mind writing simple makefiles, and either writing or getting libraries for things like vectors and matrices C++ is of course still great. Also C++'s wasm support works with OpenGL and SDL with pretty much just a change of compilers, using emscripten instead of the normal compiler. Emscripten's downside for me personally is that you get a large bundle. When I say the bundle is large, its not so much about size but complexity, emscripten does things a specific way. Its still very easy to use and in fact is the best for cross platform graphics from desktop and web
3
Nim
Not a whole lot ot say except that Nim's C interop is very good so working with graphics apis is also simple. It does have a very comprehensive library <a>NimGL</a> which provides not only OpenGL bindings but also: GLFW, Vulkan and <a>ImGui</a>. For the web, Nim works with Emscripten since it compiles to C but Nim also has first class compilation to JavaScript and the front page of the Nim site actually has a snake game written in JS by the language creator
4
Go
Go is pretty good once you get past some of the setup for its C interop. Also you can make talking to C easier by using C types instead of Go types. For example if you want to pass some floats to openGL its super easy if you use C.float instead of Go's float. Go also works well with Wasm and even its concurrency works with both <a>GopherJS</a> and <a>TinyGo</a>
5
D
D could arguably be #2 either tied with or displacing C++ if we're just talking about Desktop without web support. D's dstep tool and importc language feature make interop with C pretty easy. It has componet wise array operations similar to Odin which is nice. For me the big problem with D is that its wasm support is terrible. You can really only use it with betterC which is D's limited mode that restricts it to an enhanced C subset. When I was asking questions about using D's betterC with wasm one discord user kept refering to it as worse D, which might sound negative but is 100% accurate. Many of the things that make D good don't work in better C. Overall using D on desktop is great, but its terrible for the web and wasm
6
Zig
Zig's C interop is great, actually for the most part its almost as easy as C++ and it also works very well with wasm. I think the main draw back for Zig with graphics is that its syntax for casting is very verbose and it becomes a bit of a chore
Networking
Place
Language
Notes
1
Go
No surprise here. Go's networking is the best, not just because it has so many built in libraries specifically built for networking, but also because its concurrency is so simple and efficient
2
Nim
Nim's async and multithreading are not as polished as Go's coroutine concurrency but they are simple and work. Its networking is also pretty simple. It doesn't really stand out as being particularly interesting but it is straightforward and straightforward is good
3
D
D has built in sockets and the higher level vibe D library for http servers is well documented. D also has decent parallelism constructs. Not a lot to say as I haven't actually used D for networking, I just looked at some of the documentation and tutorials. Though I haven't actually done any D networkign myself, just from the examples on the Dlang site and Rosetta code I can see that it is very simple to use
4
Odin
Despite not having standard networking, Odin has built in support for <a>SDL_Net</a> and <a>Enet</a>. I haven't used Enet but I did use SDL net to write Odin's echo server example
5
C++
Of course you could use Unix or Windows sockets if you don't care about cross platform support, but Asio is really cool. Its more verbose than the options above, but it does give C++ cross platform networking. It also serves as a general purpose async runtime for C++. It was pretty simple to use and the rewrite of the echo server with Asio was easy to put together
6
Zig
Zig's networking is actually very nice, but its not documented and will probably change until 1.0. Andrew Kelley, Zig's creator says that proper documentation will come at 1.0, which is a reasonable plan. I think once Zig's networking is documented it will easily move up this list. Zig's async stuff is very cool but not complete and more complex than Go so I don't think I could place it higher than #2
Overall
lower score is better. No scores for the trival programs like Battle and Guess Number
lang
ppm & png
http & json
opengl
echo server
build system
platformer
pong
total
c++
1
2
2
1
3
1
1
11
go
1
1
4
1
2
todo
todo
9
zig
2
3
3
2
1
4
n/a
15
odin
1
6
1
2
2
3
1
16
d
n/a
n/a
n/a
1
n/a
n/a
1
tbd
janet
n/a
n/a
n/a
1
n/a
n/a
1
tbd
nim
n/a
1
n/a
1
n/a
n/a
n/a
n/a
c#
n/a
4
n/a
n/a
n/a
n/a
n/a
n/a
<ul>
<li>[X] Guess Number</li>
<li>[X] Http and Json</li>
<li>[X] Langton's Ant</li>
<li>[X] PPM and PNG</li>
<li>[X] Text Battle Simulation</li>
<li>[X] Build System</li>
<li>[X] Echo Server</li>
<li>[X] OpenGL Triangle</li>
<li>[X] Mini Platformer - One Lone Coder port</li>
<li>[X] Pong</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/32078353?v=4 | mibu | xyaman/mibu | 2021-10-03T17:08:47Z | Pure Zig library for low-level terminal manipulation. | main | 2 | 89 | 10 | 89 | https://api.github.com/repos/xyaman/mibu/tags | MIT | [
"ansi",
"color",
"console",
"cursor",
"terminal",
"zig",
"zig-package"
]
| 86 | false | 2025-05-18T00:21:59Z | true | true | unknown | github | []
| <blockquote>
<span class="bg-yellow-100 text-yellow-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300">WARNING</span>
This library is a WIP and may have breaking changes and bugs.
</blockquote>
mibu
<strong>mibu</strong> is pure Zig library for low-level terminal manipulation.
<blockquote>
Tested with zig version <code>2024.11.0-mach</code> (0.14.0-dev.2577+271452d22)
</blockquote>
Features
<ul>
<li>Allocation free.</li>
<li>UTF-8 support.</li>
<li>Style (bold, italic, underline, etc).</li>
<li>Termios / Raw mode.</li>
<li>8-16 colors.</li>
<li>True Color (24-bit RGB).</li>
<li>Cursor controls.</li>
<li>Clear(Erase) functions.</li>
<li>Key events.</li>
<li>Partial Mouse events. (Click, Scroll, Release)</li>
</ul>
How to use
First we add the library as a dependency in our <code>build.zig.zon</code> file with the
following command.
<code>bash
zig fetch --save git+https://github.com/xyaman/mibu</code>
And we add it to <code>build.zig</code> file.
```zig
const mibu_dep = b.dependency("mibu", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("mibu", mibu_dep.module("mibu"));
```
Now we can use the library in our code.
```zig
const std = @import("std");
const mibu = @import("mibu");
const color = mibu.color;
pub fn main() void {
std.debug.print("{s}Hello World in purple!\n", .{color.print.bgRGB(97, 37, 160)});
}
```
Getting Started
See the <a>examples directory</a>
You can run the examples with the following command:
```bash
Prints text with different colors
zig build color
Prints what key you pressed, until you press <code>q</code> or <code>ctrl+c</code>
zig build event
zig build alternate_screen
```
TODO
<ul>
<li>Mouse events
<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> Left, middle, right click
<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> Scroll up, down
<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> Release
<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> Modifiers (shift, ctrl, alt)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Move
<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> Click and move (drag)</li>
<li>Support all keys events</li>
</ul>
Projects that use <code>mibu</code>
<ul>
<li><a>zigtris</a></li>
<li><a>chip8 (wip)</a></li>
</ul> | [
"https://github.com/GabrieleInvernizzi/zig-prompter",
"https://github.com/darkyzhou/mcm",
"https://github.com/ringtailsoftware/zig-wasm-audio-framebuffer",
"https://github.com/ringtailsoftware/zigtris",
"https://github.com/ringtailsoftware/zoridor",
"https://github.com/xyaman/chip8",
"https://github.com/xyaman/ytplayer"
]
|
https://avatars.githubusercontent.com/u/87844133?v=4 | zig-sdk | vezel-dev/zig-sdk | 2021-06-13T05:19:25Z | An MSBuild SDK for building Zig, C, and C++ projects using the Zig compiler. | master | 18 | 88 | 2 | 88 | https://api.github.com/repos/vezel-dev/zig-sdk/tags | 0BSD | [
"build",
"c",
"cpp",
"dotnet",
"msbuild",
"zig"
]
| 652 | false | 2025-05-15T13:34:26Z | false | false | unknown | github | []
| Zig SDK
<strong>
An MSBuild SDK for building Zig, C, and C++ projects using the Zig
compiler.
</strong>
[](LICENSE-0BSD)
[](https://github.com/vezel-dev/zig-sdk/commits/master)
[](https://github.com/vezel-dev/zig-sdk/actions/workflows/build.yml)
[](https://github.com/vezel-dev/zig-sdk/discussions)
[](https://discord.gg/wtzCfaX2Nj)
[](https://vezel.zulipchat.com)
The <strong>Zig SDK</strong> is an
<a>MSBuild SDK</a>
that augments the .NET SDK with the ability to build Zig, C, and C++ projects.
With support for multiple programming languages, cross-compilation, NuGet
packaging, and more, the <strong>Zig SDK</strong> makes it trivial to author native
components as part of your .NET solution - without all the hassle that is
usually part and parcel of building and packaging native code. These features
are powered by the <a>Zig</a> toolchain.
Usage
This project offers the following packages:
| Package | Description | Downloads |
| -: | - | :- |
| <a></a> | Provides the MSBuild SDK and associated tasks. | |
To install an SDK package in a project, add it to your <code>global.json</code> under the
<code>msbuild-sdks</code> property.
For more information, please visit the
<a>project home page</a>.
Building
You will need the .NET SDK installed. Simply run <code>./cake</code>
(a <a>Bash</a> script) to build artifacts. You can
also use <code>./cake pack</code> if you do not want to build the documentation (which
requires Node.js).
License
This project is licensed under the terms found in
<a><code>LICENSE-0BSD</code></a>.
The Zig logo is licensed under the terms found in
<a><code>LICENSE-CC-BY-SA-4.0</code></a>. | []
|
https://avatars.githubusercontent.com/u/66022611?v=4 | Avalanche | SnowballSH/Avalanche | 2022-01-16T23:19:33Z | UCI Chess Engine written in Zig. | master | 2 | 85 | 4 | 85 | https://api.github.com/repos/SnowballSH/Avalanche/tags | MIT | [
"ai",
"chess",
"minimax",
"neural-network",
"nnue",
"zig"
]
| 32,675 | false | 2025-05-13T03:18:23Z | true | false | unknown | github | []
| Avalanche
Avalanche is the first and strongest UCI Chess Engine written in <a>Zig</a>
Strength
<strong>Official <a>40/15 CCRL ELO (v2.1.0)</a>: 3346</strong>
<strong>Official <a>Blitz CCRL ELO (v2.1.0)</a>: 3400</strong>
Version 2.1.0 participated in TCEC Swiss 6.
About
Avalanche is the <strong>first and strongest chess engine</strong> written in the <a>Zig programming language</a>, proving Zig's ability to succeed in real-world, competitive applications.
Avalanche v1.4.0 was the <strong>sole winner</strong> of the 102nd CCRL Amateur Series Tournament (Division 5), having a score of <strong>29.5/44</strong>. See <a>Tournament Page</a>.
Avalanche uses the new <strong>NNUE</strong> (Efficiently Updatable Neural Network) technology for its evaluation.
This project isn't possible without the help of the Zig community, since this is the first and only Zig code I've ever written. Thank you!
License
Good Old MIT License. In short, feel free to use this program anywhere, but please credit this repository somewhere in your project :)
Compile
<code>zig build -Drelease-fast</code>
Avalanche is only guaranteed to compile using Zig v0.10.x. Newer versions will not work as Avalanche still uses Stage1.
Avalanche also has a lichess account (though not often played): https://lichess.org/@/IceBurnEngine
Usage
Avalanche follows the UCI protocol and is not a full chess application. You should use Avalanche with a UCI-compatible GUI interface. If you need to use the CLI, make sure to send \n at the end of your input (^\n on windows command prompt).
Past Versions
Credits
<ul>
<li><a>Dan Ellis Echavarria</a> for writing the github action CI and helping me with Zig questions</li>
<li><a>Ciekce</a> for guiding me with migrating to the new Marlinflow and answering my stupid questions related to NNUE</li>
<li>
Many other developers in the computer chess community for guiding me through new things like SPRT testing.
</li>
<li>
https://www.chessprogramming.org/ for explanation on everything I need, including search, tt, pruning, reductions... everything.
</li>
<li>https://github.com/nkarve/surge for movegen inspiration.</li>
<li>Maksim Korzh, https://www.youtube.com/channel/UCB9-prLkPwgvlKKqDgXhsMQ for getting me started on chess programming.</li>
<li>https://github.com/dsekercioglu/blackmarlin for NNUE structure and trainer skeleton (1.5.0 and older)</li>
<li>https://github.com/Disservin/Smallbrain and https://github.com/cosmobobak/viridithas for search ideas</li>
<li>https://openai.com/dall-e-2/ for generating the beautiful logo image</li>
</ul>
Originality Status
<ul>
<li>General</li>
<li>This is the first released chess engine written in the <strong>Zig Programming Language</strong>. Although there are Zig libraries for chess, Avalanche is completely stand-alone and does not use any external libraries.</li>
<li>Move Generator</li>
<li>Algorithm is inspired by Surge, but code is 100% hand-written in Zig.</li>
<li>Search</li>
<li>Avalanche has a simple Search written 100% by myself, but is probably a subset of many other engines. Some ideas are borrowed from other chess engines as in comments. However many ideas and parameters are tuned manually and automatically using my own scripts.</li>
<li>Evaluation</li>
<li>The Hand-Crafted Evaluation is based on https://www.chessprogramming.org/PeSTO%27s_Evaluation_Function with adaptation to endgames. The HCE is only activated at late endgames when finding checkmate against a lone king is needed.</li>
<li>NNUE since 2.0.0 is trained with https://github.com/jw1912/bullet</li>
<li>The NNUE data since 2.0.0 is purely generated from self-play games. Currently, the latest dev network is trained on 600 million self-play positions at depth 8.</li>
<li>UCI Interface/Communication code</li>
<li>100% original</li>
</ul>
Alternative Square Logos
| []
|
https://avatars.githubusercontent.com/u/2665334?v=4 | zig-play | gsquire/zig-play | 2021-04-10T23:51:54Z | An online Zig compiler inspired by Go and Rust | main | 2 | 83 | 9 | 83 | https://api.github.com/repos/gsquire/zig-play/tags | MIT | [
"zig"
]
| 41 | false | 2025-03-05T20:20:15Z | false | false | unknown | github | []
| Zig Playground
This is a rudimentary online compiler for the <a>Zig</a> programming language. It
is inspired by the <a>Go</a> playground.
It's currently served from this <a>page</a>.
Setup
The main server is a Go binary that serves up a single HTML page that allows you to enter your Zig
code and then run it. To run it yourself, you will need a Go tool chain which can be installed via
<code>brew</code> on a Mac. If you wish to run it locally, you must compile it for your <code>GOOS</code> and <code>GOARCH</code>
but I have included a small shell script to make a Linux binary that Docker can use as well. You
should also have Zig installed and accessible from within your <code>$PATH</code> on the host.
Hosting
In theory this could be run anywhere that a Docker container can execute. Google's Cloud Run may be
a cheap option considering their generous free tier.
FAQ
<blockquote>
What can this playground do?
</blockquote>
It is currently set up to simply run and format a single Zig source file. (i.e. <code>zig run source.zig</code> & <code>zig fmt source.zig</code>)
<blockquote>
Are there any timeouts?
</blockquote>
If your code doesn't build within 10 seconds, the server will quit your request.
<blockquote>
Why am I getting rate-limited?
</blockquote>
You're allowed five compilations per minute which I think is fairly generous.
<blockquote>
Is it secure?
</blockquote>
Go read the source. I do not collect logs of any kind and am not interested in your data. Unless it
is causing issues to the service.
<blockquote>
Will this always be available?
</blockquote>
To the best of my ability, I will try and keep this online.
Contact
Feel free to write to [email protected] with any questions or comments.
License
MIT | []
|
https://avatars.githubusercontent.com/u/4005377?v=4 | zig-support | MarioAriasC/zig-support | 2021-10-03T00:12:42Z | Zig language support for JetBrains IDEs | main | 6 | 79 | 8 | 79 | https://api.github.com/repos/MarioAriasC/zig-support/tags | GPL-3.0 | [
"idea-plugin",
"intellij",
"intellij-plugin",
"kotlin",
"zig"
]
| 1,499 | false | 2024-11-14T16:46:10Z | false | false | unknown | github | []
| zig-support
<a></a>
<a></a>
Support for the <a>Zig Programming Language</a>
<em>Warning</em>
This project is discontinued. Any developement of bug fixing stopped around August 2023.
I reccomend you to migrate <a>ZigBrains</a> (<a>GitHub</a>).
ZigBrains has more features and integrates ZLS.
I'm contributing sporadically to ZigBrains development.
Features
<ul>
<li>Basic language syntax rendering
</li>
<li>Comment/Uncomment Zig code</li>
<li>Live templates
</li>
<li>Formatting using <code>zig fmt</code> (Ctrl|Cmd + Alt + l)</li>
</ul>
Installation
<ul>
<li>Using IDE built-in plugin system:</li>
</ul>
Settings/Preferences > Plugins > Marketplace > Search for "zig-support" >
Install Plugin
<ul>
<li>Manually:</li>
</ul>
Download the <a>latest release</a> and install it manually using
Settings/Preferences > Plugins > ⚙️ > Install plugin from disk...
Acknowledgments
This plugin is based on two previous plugins:
- <a>ZigLang</a> by <a>Edison Su</a>
- <a>Zig</a> by <a>Tesla Zhang</a>
Plugin based on the <a>IntelliJ Platform Plugin Template</a>. | []
|
https://avatars.githubusercontent.com/u/82044447?v=4 | json | getty-zig/json | 2021-07-11T12:59:09Z | A (de)serialization library for JSON | main | 3 | 78 | 10 | 78 | https://api.github.com/repos/getty-zig/json/tags | MIT | [
"json",
"serialization",
"zig"
]
| 23,244 | false | 2025-04-05T13:45:52Z | true | true | unknown | github | [
{
"commit": "78738b665a53db4be85696635b9c832fbca8d273.tar.gz",
"name": "getty",
"tar_url": "https://github.com/getty-zig/getty/archive/78738b665a53db4be85696635b9c832fbca8d273.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/getty-zig/getty"
},
{
"commit": "e7a9bc39c213985814a904b38e4506a6fbd537b2.tar.gz",
"name": "protest",
"tar_url": "https://github.com/ibokuri/protest/archive/e7a9bc39c213985814a904b38e4506a6fbd537b2.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ibokuri/protest"
}
]
|
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
Overview
<em>Getty JSON</em> is a (de)serialization library for the JSON data format.
Installation
<ol>
<li>
Declare Getty JSON as a project dependency with <code>zig fetch</code>:
<code>sh
zig fetch --save git+https://github.com/getty-zig/json.git#<COMMIT></code>
</li>
<li>
Expose Getty JSON as a module in your project's <code>build.zig</code>:
```zig
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const opts = .{ .target = target, .optimize = optimize }; // 👈
const json_mod = b.dependency("json", opts).module("json"); // 👈
const exe = b.addExecutable(.{
.name = "my-project",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("json", json_mod); // 👈
// ...
</code>
}
```
</li>
<li>
Import Getty JSON into your code:
<code>zig
const json = @import("json");</code>
</li>
</ol> | [
"https://github.com/Scythe-Technology/Zune",
"https://github.com/allyourcodebase/boost-libraries-zig",
"https://github.com/kassane/beast",
"https://github.com/lfcm64/z-tree-sitter",
"https://github.com/soheil-01/bitzig"
]
|
https://avatars.githubusercontent.com/u/20167110?v=4 | kisa | greenfork/kisa | 2021-06-23T10:57:40Z | Text editor of the new world | master | 0 | 77 | 0 | 77 | https://api.github.com/repos/greenfork/kisa/tags | MIT | [
"console-application",
"editor",
"kisa",
"modal-editing",
"tui",
"zig"
]
| 1,149 | false | 2025-04-11T05:11:04Z | true | false | unknown | github | []
| Kisa
Kisa is a hackable and batteries-included text editor of the new world.
Home repository is on <a>sourcehut</a> but there's also a mirror on <a>GitHub</a>.
Kisa is in its early stage and it is not usable at the moment. See <a>roadmap</a>
for the current progress.
There's a growing set of <a>design documents</a>, beware most
of it is not implemented.
Purpose
I, greenfork, the one who started this project, would like to have a
supreme code editor. I want to edit code with pleasure, I want to know
that whenever I feel something is not right - I have enough power to fix it,
but with great power comes great responsibility. I shall wield this power
with caution and I shall encourage my peers and empower them to follow
my steps and eventually let them lead me instead of simply being led.
Zen
<ul>
<li>Programmer must be able to perfect their tool.</li>
<li>Choice is burden.</li>
<li>Choice is freedom.</li>
</ul>
Goals
<ul>
<li>Provide a powerful and flexible code editor - obvious but worth saying,
we should not provide anything less than that.</li>
<li>Identify common workflows and set them in stone - text editing has become
quite sophisticated in this day and age, we have already discovered a lot
of editing capabilities. Now is the time to make them easy to use and fully
integrated with the rest of the features of the editor, not rely on
third-party plugins to emulate the necessary features.</li>
<li>Adhere to hybrid Unix/Apple philosophy - programs must be able to communicate
with each other, the editor must make integrations with other tools possible,
this is from Unix philosophy. At the same time the editor must be built from
ground-up and have full control of all its core features to provide a
single and uniform way of doing things, this is from Apple philosophy.</li>
<li>Make it infinitely extensible by design, no hard assumptions - the only types of
unimplementable features are those which were not accounted for from the
very beginning and got hardblocked by design decisions which are interleaved
with the rest of the editor, so changing it is not feasible. The solution
is simple - layers and layers of abstractions, assumptions are strictly
kept to minimum by careful thinking about the public API design of each layer.</li>
<li>Make it hackable - I believe there are several key points to make an editor
hackable: interesting design, clean code, extensive development documentation,
friendly attitude to anyone trying.</li>
</ul>
Communication
<ul>
<li><a>~greenfork/kisa-announce@lists.sr.ht</a> - readonly mailing list for rare
announcements regarding this project, <a>web archive</a>. Subscribe
to this list by sending any email to
<a>~greenfork/kisa-announce+subscribe@lists.sr.ht</a>.</li>
<li><a>~greenfork/kisa-devel@lists.sr.ht</a> - mailing list for discussions and
sending patches, <a>web archive</a></li>
<li><a>hello@greenfork.me</a> - my personal email address</li>
<li><a>Discord</a> - real-time chatting experience</li>
<li><a>Twitch</a> - occasional streams including editor development</li>
<li><a>YouTube</a> - recordings of past streams and other related videos</li>
</ul>
Please be kind and understanding to everyone.
Are you new to mailing lists? Please check out <a>this tutorial</a>.
There's also the <a>in-detail comparison video</a> of pull requests
versus patches.
Contributing
Ideas are very welcome. At this stage of the project the main task is to
shape its design and provide proof-of-concept implementations of these ideas.
Code contributions without previous discussions are unlikely to be accepted
so please discuss the design first. Ideas should be in-line with the current
goals and values of this editor. Many ideas will likely be rejected since not
all goals and values are identified, but nevertheless they will help us to
shape the editor.
For structured discussions please use <a>~greenfork/kisa-devel@lists.sr.ht</a> mailing list.
How to build
Currently it is only relevant for the development, there's no usable
text editor (just yet).
Requirements:
- Zig master, currently <a>https://ziglang.org/builds/zig-linux-x86_64-0.10.0-dev.3685+dae7aeb33.tar.xz</a>
- git
<code>$ git clone --recurse-submodules https://github.com/greenfork/kisa
$ cd kisa
$ zig build test
$ zig build run</code>
Is this a task for a mere mortal?
Code editor is a big project. I have a habit of abandoning projects, I moderately
lose interest to them. I am not religious but God give me strength.
In the interview on <a>Zig Showtime</a> Andreas Kling, the author of <a>SerenityOS</a>,
talks about how important it is to lay just one brick at a time. Let's try that. | []
|
https://avatars.githubusercontent.com/u/34946442?v=4 | bithacks | cryptocode/bithacks | 2021-11-19T23:45:50Z | Zig bithacks | main | 0 | 76 | 4 | 76 | https://api.github.com/repos/cryptocode/bithacks/tags | - | [
"zig"
]
| 47 | false | 2025-05-11T14:37:41Z | false | false | unknown | github | []
| Zig Bit Twiddling Hacks
This Zig library reimplements and improves upon the <a>Bit Twiddling Hacks</a> snippets originally authored by Sean Eron Anderson and contributors.
Most recently tested with Zig master version <code>0.14.0-dev.1694+3b465ebec</code>.
Use the zig-0.13 tag to target Zig 0.13/0.12
Run tests with <code>zig test bithacks.zig</code>
Improvements include:
<ul>
<li>Comptime args are used to prune branches in certain cases where the caller can provide extra information about the input.</li>
<li>Removed some undefined behavior related to type punning, as noted in ISO C99 6.5/7.</li>
<li>Inscrutable preprocessor tricks are replaced with comptime code.</li>
<li>Variations of the same bithack tend to have more consistent ranges for the same domain. For instance, the original log2 variations behave differently for 0-input.</li>
<li>Improved type safety, and several solutions have been made generic.</li>
<li>All bithacks have tests.</li>
<li>Asserts are added to properly restrict the function domain.</li>
</ul>
Snapshot of original bithacks document used when making this library: https://web.archive.org/web/20211116092214/https:graphics.stanford.edu/~seander/bithacks.html
Every bithack has a corresponding test, whose names are verbatim copies of the headings in the documentation. Like the originial, some solutions trade portability for higher
performance. Patented variations have not been ported.
Note that std functions are never used even if they offer a solution. The point of this is to show how the bithacks can be implemented in Zig, including how to turn clever preprocessor tricks into readable and typesafe comptime alternatives.
If you find bugs or want to suggest improvements, please consider submitting an issue or pull request.
Public domain
Like the original version, this library is released under public domain with the same warranty disclaimer.
Documentation
This following is a copy of https://graphics.stanford.edu/~seander/bithacks.html. It serves to provide a stable documentation link target for the Zig implementation of the solutions.
The copy is verbatim, with the exception of a few fixes to the table of contents links.
Bit Twiddling Hacks
By Sean Eron Anderson
[email protected]
Individually, the <strong>code snippets here are in the public domain</strong> (unless otherwise noted) — feel free to use them however you please. The aggregate collection and descriptions are © 1997-2005 Sean Eron Anderson. The code and descriptions are distributed in the hope that they will be useful, but <strong>WITHOUT ANY WARRANTY</strong> and without even the implied warranty of merchantability or fitness for a particular purpose. As of May 5, 2005, all the code has been tested thoroughly. Thousands of people have read it. Moreover, <a>Professor Randal Bryant</a>, the Dean of Computer Science at Carnegie Mellon University, has personally tested almost everything with his <a>Uclid code verification system</a>. What he hasn't tested, I have checked against all possible inputs on a 32-bit machine. <strong>To the first person to inform me of a legitimate bug in the code, I'll pay a bounty of US$10 (by check or Paypal)</strong>. If directed to a charity, I'll pay US$20.
Contents
<ul>
<li><a>About the operation counting methodology</a></li>
<li><a>Compute the sign of an integer</a></li>
<li><a>Detect if two integers have opposite signs</a>
<a></a></li>
<li><a></a><a>Compute the integer absolute value (abs) without branching</a></li>
<li><a>Compute the minimum (min) or maximum (max) of two integers without branching</a></li>
<li><a>Determining if an integer is a power of 2</a></li>
<li>Sign extending<ul>
<li><a>Sign extending from a constant bit-width</a></li>
<li><a>Sign extending from a variable bit-width</a></li>
<li><a>Sign extending from a variable bit-width in 3 operations</a></li>
</ul>
</li>
<li><a>Conditionally set or clear bits without branching</a></li>
<li><a>Conditionally negate a value without branching</a></li>
<li><a>Merge bits from two values according to a mask</a></li>
<li>Counting bits set<ul>
<li><a>Counting bits set, naive way</a></li>
<li><a>Counting bits set by lookup table</a></li>
<li><a>Counting bits set, Brian Kernighan's way</a></li>
<li><a>Counting bits set in 14, 24, or 32-bit words using 64-bit instructions</a></li>
<li><a>Counting bits set, in parallel</a></li>
<li><a>Count bits set (rank) from the most-significant bit upto a given position</a></li>
<li><a>Select the bit position (from the most-significant bit) with the given count (rank)</a></li>
</ul>
</li>
<li>Computing parity (1 if an odd number of bits set, 0 otherwise)<ul>
<li><a>Compute parity of a word the naive way</a></li>
<li><a>Compute parity by lookup table</a></li>
<li><a>Compute parity of a byte using 64-bit multiply and modulus division</a></li>
<li><a>Compute parity of word with a multiply</a></li>
<li><a>Compute parity in parallel</a></li>
</ul>
</li>
<li>Swapping Values<ul>
<li><a>Swapping values with subtraction and addition</a></li>
<li><a>Swapping values with XOR</a></li>
<li><a>Swapping individual bits with XOR</a></li>
</ul>
</li>
<li>Reversing bit sequences<ul>
<li><a>Reverse bits the obvious way</a></li>
<li><a>Reverse bits in word by lookup table</a></li>
<li><a>Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division)</a></li>
<li><a>Reverse the bits in a byte with 4 operations (64-bit multiply, no division)</a></li>
<li><a>Reverse the bits in a byte with 7 operations (no 64-bit, only 32)</a></li>
<li><a>Reverse an N-bit quantity in parallel with 5 * lg(N) operations</a></li>
</ul>
</li>
<li>Modulus division (aka computing <em>remainders</em>)<ul>
<li><a>Computing modulus division by 1 << s without a division operation (obvious)</a></li>
<li><a>Computing modulus division by (1 << s) - 1 without a division operation</a></li>
<li><a>Computing modulus division by (1 << s) - 1 in parallel without a division operation</a></li>
</ul>
</li>
<li>Finding integer log base 2 of an integer (aka the position of the highest bit set)<ul>
<li><a>Find the log base 2 of an integer with the MSB N set in O(N) operations (the obvious way)</a></li>
<li><a>Find the integer log base 2 of an integer with an 64-bit IEEE float</a></li>
<li><a>Find the log base 2 of an integer with a lookup table</a></li>
<li><a>Find the log base 2 of an N-bit integer in O(lg(N)) operations</a></li>
<li><a>Find the log base 2 of an N-bit integer in O(lg(N)) operations with multiply and lookup</a></li>
</ul>
</li>
<li><a>Find integer log base 10 of an integer</a></li>
<li><a>Find integer log base 10 of an integer the obvious way</a></li>
<li><a>Find integer log base 2 of a 32-bit IEEE float</a></li>
<li><a>Find integer log base 2 of the pow(2, r)-root of a 32-bit IEEE float (for unsigned integer r)</a></li>
<li>Counting consecutive trailing zero bits (or finding bit indices)<ul>
<li><a>Count the consecutive zero bits (trailing) on the right linearly</a></li>
<li><a>Count the consecutive zero bits (trailing) on the right in parallel</a></li>
<li><a>Count the consecutive zero bits (trailing) on the right by binary search</a></li>
<li><a>Count the consecutive zero bits (trailing) on the right by casting to a float</a></li>
<li><a>Count the consecutive zero bits (trailing) on the right with modulus division and lookup</a></li>
<li><a>Count the consecutive zero bits (trailing) on the right with multiply and lookup</a></li>
</ul>
</li>
<li><a>Round up to the next highest power of 2 by float casting</a></li>
<li><a>Round up to the next highest power of 2</a></li>
<li>Interleaving bits (aka computing <em>Morton Numbers</em>)<ul>
<li><a>Interleave bits the obvious way</a></li>
<li><a>Interleave bits by table lookup</a></li>
<li><a>Interleave bits with 64-bit multiply</a></li>
<li><a>Interleave bits by Binary Magic Numbers</a></li>
</ul>
</li>
<li>Testing for ranges of bytes in a word (and counting occurances found)<ul>
<li><a>Determine if a word has a zero byte</a></li>
<li><a>Determine if a word has a byte equal to n</a></li>
<li><a>Determine if a word has byte less than n</a></li>
<li><a>Determine if a word has a byte greater than n</a></li>
<li><a>Determine if a word has a byte between m and n</a></li>
</ul>
</li>
<li><a>Compute the lexicographically next bit permutation</a></li>
</ul>
<a name="OperationCounting">About the operation counting methodology</a>
When totaling the number of operations for algorithms here, any C operator is counted as one operation. Intermediate assignments, which need not be written to RAM, are not counted. Of course, this operation counting approach only serves as an approximation of the actual number of machine instructions and CPU time. All operations are assumed to take the same amount of time, which is not true in reality, but CPUs have been heading increasingly in this direction over time. There are many nuances that determine how fast a system will run a given sample of code, such as cache sizes, memory bandwidths, instruction sets, etc. In the end, benchmarking is the best way to determine whether one method is really faster than another, so consider the techniques below as possibilities to test on your target architecture.
<a name="CopyIntegerSign">Compute the sign of an integer</a>
int v; // we want to find the sign of v
int sign; // the result goes here
// CHAR_BIT is the number of bits per byte (normally 8).
sign = -(v < 0); // if v < 0 then -1, else 0\.
// or, to avoid branching on CPUs with flag registers (IA32):
sign = -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
// or, for one less instruction (but not portable):
sign = v >> (sizeof(int) * CHAR_BIT - 1);
The last expression above evaluates to sign = v >> 31 for 32-bit integers. This is one operation faster than the obvious way, sign = -(v < 0). This trick works because when signed integers are shifted right, the value of the far left bit is copied to the other bits. The far left bit is 1 when the value is negative and 0 otherwise; all 1 bits gives -1. Unfortunately, this behavior is architecture-specific.
Alternatively, if you prefer the result be either -1 or +1, then use:
sign = +1 | (v >> (sizeof(int) * CHAR_BIT - 1)); // if v < 0 then -1, else +1
On the other hand, if you prefer the result be either -1, 0, or +1, then use:
sign = (v != 0) | -(int)((unsigned int)((int)v) >> (sizeof(int) * CHAR_BIT - 1));
// Or, for more speed but less portability:
sign = (v != 0) | (v >> (sizeof(int) * CHAR_BIT - 1)); // -1, 0, or +1
// Or, for portability, brevity, and (perhaps) speed:
sign = (v > 0) - (v < 0); // -1, 0, or +1
If instead you want to know if something is non-negative, resulting in +1 or else 0, then use:
sign = 1 ^ ((unsigned int)v >> (sizeof(int) * CHAR_BIT - 1)); // if v < 0 then 0, else 1
Caveat: On March 7, 2003, Angus Duggan pointed out that the 1989 ANSI C specification leaves the result of signed right-shift implementation-defined, so on some systems this hack might not work. For greater portability, Toby Speight suggested on September 28, 2005 that CHAR_BIT be used here and throughout rather than assuming bytes were 8 bits long. Angus recommended the more portable versions above, involving casting on March 4, 2006. <a>Rohit Garg</a> suggested the version for non-negative integers on September 12, 2009.
<a name="DetectOppositeSigns">Detect if two integers have opposite signs</a>
int x, y; // input values to compare signs
bool f = ((x ^ y) < 0); // true iff x and y have opposite signs
Manfred Weis suggested I add this entry on November 26, 2009.
<a name="IntegerAbs">Compute the integer absolute value (abs) without branching</a>
int v; // we want to find the absolute value of v
unsigned int r; // the result goes here
int const mask = v >> sizeof(int) * CHAR_BIT - 1;
r = (v + mask) ^ mask;
Patented variation:
r = (v ^ mask) - mask;
Some CPUs don't have an integer absolute value instruction (or the compiler fails to use them). On machines where branching is expensive, the above expression can be faster than the obvious approach, r = (v < 0) ? -(unsigned)v : v, even though the number of operations is the same.
On March 7, 2003, Angus Duggan pointed out that the 1989 ANSI C specification leaves the result of signed right-shift implementation-defined, so on some systems this hack might not work. I've read that ANSI C does not require values to be represented as two's complement, so it may not work for that reason as well (on a diminishingly small number of old machines that still use one's complement). On March 14, 2004, Keith H. Duggar sent me the patented variation above; it is superior to the one I initially came up with, <code>r=(+1|(v>>(sizeof(int)*CHAR_BIT-1)))*v</code>, because a multiply is not used. Unfortunately, this method has been <a>patented</a> in the USA on June 6, 2000 by Vladimir Yu Volkonsky and assigned to <a>Sun Microsystems</a>. On August 13, 2006, Yuriy Kaminskiy told me that the patent is likely invalid because the method was published well before the patent was even filed, such as in <a>How to Optimize for the Pentium Processor</a> by Agner Fog, dated November, 9, 1996. Yuriy also mentioned that this document was translated to Russian in 1997, which Vladimir could have read. Moreover, the Internet Archive also has an old <a>link</a> to it. On January 30, 2007, Peter Kankowski shared with me an <a>abs version</a> he discovered that was inspired by Microsoft's Visual C++ compiler output. It is featured here as the primary solution. On December 6, 2007, Hai Jin complained that the result was signed, so when computing the abs of the most negative value, it was still negative. On April 15, 2008 Andrew Shapira pointed out that the obvious approach could overflow, as it lacked an (unsigned) cast then; for maximum portability he suggested <code>(v < 0) ? (1 + ((unsigned)(-1-v))) : (unsigned)v</code>. But citing the ISO C99 spec on July 9, 2008, Vincent Lefèvre convinced me to remove it becasue even on non-2s-complement machines -(unsigned)v will do the right thing. The evaluation of -(unsigned)v first converts the negative value of v to an unsigned by adding 2<strong>N, yielding a 2s complement representation of v's value that I'll call U. Then, U is negated, giving the desired result, -U = 0 - U = 2</strong>N - U = 2<strong>N - (v+2</strong>N) = -v = abs(v).
<a name="IntegerMinOrMax">Compute the minimum (min) or maximum (max) of two integers without branching</a>
int x; // we want to find the minimum of x and y
int y;
int r; // the result goes here
r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
On some rare machines where branching is very expensive and no condition move instructions exist, the above expression might be faster than the obvious approach, r = (x < y) ? x : y, even though it involves two more instructions. (Typically, the obvious approach is best, though.) It works because if x < y, then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x. Otherwise, if x >= y, then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y. On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.
To find the maximum, use:
r = x ^ ((x ^ y) & -(x < y)); // max(x, y)
Quick and dirty versions:
If you know that INT_MIN <= x - y <= INT_MAX, then you can use the following, which are faster because (x - y) only needs to be evaluated once.
r = y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // min(x, y)
r = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y)
Note that the 1989 ANSI C specification doesn't specify the result of signed right-shift, so these aren't portable. If exceptions are thrown on overflows, then the values of x and y should be unsigned or cast to unsigned for the subtractions to avoid unnecessarily throwing an exception, however the right-shift needs a signed operand to produce all one bits when negative, so cast to signed there.
On March 7, 2003, Angus Duggan pointed out the right-shift portability issue. On May 3, 2005, Randal E. Bryant alerted me to the need for the precondition, INT_MIN <= x - y <= INT_MAX, and suggested the non-quick and dirty version as a fix. Both of these issues concern only the quick and dirty version. Nigel Horspoon observed on July 6, 2005 that gcc produced the same code on a Pentium as the obvious solution because of how it evaluates (x < y). On July 9, 2008 Vincent Lefèvre pointed out the potential for overflow exceptions with subtractions in r = y + ((x - y) & -(x < y)), which was the previous version. Timothy B. Terriberry suggested using xor rather than add and subract to avoid casting and the risk of overflows on June 2, 2009.
<a name="DetermineIfPowerOf2">Determining if an integer is a power of 2</a>
unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = v && !(v & (v - 1));
<a name="FixedSignExtend">Sign extending from a constant bit-width</a>
Sign extension is automatic for built-in types, such as chars and ints. But suppose you have a signed two's complement number, x, that is stored using only b bits. Moreover, suppose you want to convert x to an int, which has more than b bits. A simple copy will work if x is positive, but if negative, the sign must be extended. For example, if we have only 4 bits to store a number, then -3 is represented as 1101 in binary. If we have 8 bits, then -3 is 11111101. The most-significant bit of the 4-bit representation is replicated sinistrally to fill in the destination when we convert to a representation with more bits; this is sign extending. In C, sign extension from a constant bit-width is trivial, since bit fields may be specified in structs or unions. For example, to convert from 5 bits to an full integer:
int x; // convert this from using 5 bits to a full int
int r; // resulting sign extended number goes here
struct {signed int x:5;} s;
r = s.x = x;
The following is a C++ template function that uses the same language feature to convert from B bits in one operation (though the compiler is generating more, of course).
template
inline T signextend(const T x)
{
struct {T x:B;} s;
return s.x = x;
}
int r = signextend(x); // sign extend 5 bit number x to r
John Byrd caught a typo in the code (attributed to html formatting) on May 2, 2005. On March 4, 2006, Pat Wood pointed out that the ANSI C standard requires that the bitfield have the keyword "signed" to be signed; otherwise, the sign is undefined.
<a name="VariableSignExtend">Sign extending from a variable bit-width</a>
Sometimes we need to extend the sign of a number but we don't know a priori the number of bits, b, in which it is represented. (Or we could be programming in a language like Java, which lacks bitfields.)
unsigned b; // number of bits representing the number in x
int x; // sign extend this b-bit number to r
int r; // resulting sign-extended number
int const m = 1U << (b - 1); // mask can be pre-computed if b is fixed
x = x & ((1U << b) - 1); // (Skip this if bits in x above position b are already zero.)
r = (x ^ m) - m;
The code above requires four operations, but when the bitwidth is a constant rather than variable, it requires only two fast operations, assuming the upper bits are already zeroes.
A slightly faster but less portable method that doesn't depend on the bits in x above position b being zero is:
int const m = CHAR_BIT * sizeof(x) - b;
r = (x << m) >> m;
Sean A. Irvine suggested that I add sign extension methods to this page on June 13, 2004, and he provided <code>m = (1 << (b - 1)) - 1; r = -(x & ~m) | x;</code> as a starting point from which I optimized to get m = 1U << (b - 1); r = -(x & m) | x. But then on May 11, 2007, Shay Green suggested the version above, which requires one less operation than mine. Vipin Sharma suggested I add a step to deal with situations where x had possible ones in bits other than the b bits we wanted to sign-extend on Oct. 15, 2008. On December 31, 2009 Chris Pirazzi suggested I add the faster version, which requires two operations for constant bit-widths and three for variable widths.
<a name="VariableSignExtendRisky">Sign extending from a variable bit-width in 3 operations</a>
The following may be slow on some machines, due to the effort required for multiplication and division. This version is 4 operations. If you know that your initial bit-width, b, is greater than 1, you might do this type of sign extension in 3 operations by using r = (x * multipliers[b]) / multipliers[b], which requires only one array lookup.
unsigned b; // number of bits representing the number in x
int x; // sign extend this b-bit number to r
int r; // resulting sign-extended number
#define M(B) (1U << ((sizeof(x) * CHAR_BIT) - B)) // CHAR_BIT=bits/byte
static int const multipliers[] =
{
0, M(1), M(2), M(3), M(4), M(5), M(6), M(7),
M(8), M(9), M(10), M(11), M(12), M(13), M(14), M(15),
M(16), M(17), M(18), M(19), M(20), M(21), M(22), M(23),
M(24), M(25), M(26), M(27), M(28), M(29), M(30), M(31),
M(32)
}; // (add more if using more than 64 bits)
static int const divisors[] =
{
1, ~M(1), M(2), M(3), M(4), M(5), M(6), M(7),
M(8), M(9), M(10), M(11), M(12), M(13), M(14), M(15),
M(16), M(17), M(18), M(19), M(20), M(21), M(22), M(23),
M(24), M(25), M(26), M(27), M(28), M(29), M(30), M(31),
M(32)
}; // (add more for 64 bits)
#undef M
r = (x * multipliers[b]) / divisors[b];
The following variation is not portable, but on architectures that employ an arithmetic right-shift, maintaining the sign, it should be fast.
const int s = -b; // OR: sizeof(x) * CHAR_BIT - b;
r = (x << s) >> s;
Randal E. Bryant pointed out a bug on May 3, 2005 in an earlier version (that used multipliers[] for divisors[]), where it failed on the case of x=1 and b=1.
<a name="ConditionalSetOrClearBitsWithoutBranching">Conditionally set or clear bits without branching</a>
bool f; // conditional flag
unsigned int m; // the bit mask
unsigned int w; // the word to modify: if (f) w |= m; else w &= ~m;
w ^= (-f ^ w) & m;
// OR, for superscalar CPUs:
w = (w & ~m) | (-f & m);
On some architectures, the lack of branching can more than make up for what appears to be twice as many operations. For instance, informal speed tests on an AMD Athlon™ XP 2100+ indicated it was 5-10% faster. An Intel Core 2 Duo ran the superscalar version about 16% faster than the first. Glenn Slayden informed me of the first expression on December 11, 2003. Marco Yu shared the superscalar version with me on April 3, 2007 and alerted me to a typo 2 days later.
<a name="ConditionalNegate">Conditionally negate a value without branching</a>
If you need to negate only when a flag is false, then use the following to avoid branching:
bool fDontNegate; // Flag indicating we should not negate v.
int v; // Input value to negate if fDontNegate is false.
int r; // result = fDontNegate ? v : -v;
r = (fDontNegate ^ (fDontNegate - 1)) * v;
If you need to negate only when a flag is true, then use this:
bool fNegate; // Flag indicating if we should negate v.
int v; // Input value to negate if fNegate is true.
int r; // result = fNegate ? -v : v;
r = (v ^ -fNegate) + fNegate;
Avraham Plotnitzky suggested I add the first version on June 2, 2009. Motivated to avoid the multiply, I came up with the second version on June 8, 2009. Alfonso De Gregorio pointed out that some parens were missing on November 26, 2009, and received a bug bounty.
<a name="MaskedMerge">Merge bits from two values according to a mask</a>
unsigned int a; // value to merge in non-masked bits
unsigned int b; // value to merge in masked bits
unsigned int mask; // 1 where bits from b should be selected; 0 where from a.
unsigned int r; // result of (a & ~mask) | (b & mask) goes here
r = a ^ ((a ^ b) & mask);
This shaves one operation from the obvious way of combining two sets of bits according to a bit mask. If the mask is a constant, then there may be no advantage.
Ron Jeffery sent this to me on February 9, 2006.
<a name="CountBitsSetNaive">Counting bits set (naive way)</a>
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; v >>= 1)
{
c += v & 1;
}
The naive approach requires one iteration per bit, until no more bits are set. So on a 32-bit word with only the high set, it will go through 32 iterations.
<a name="CountBitsSetTable">Counting bits set by lookup table</a>
static const unsigned char BitsSetTable256[256] =
{
# define B2(n) n, n+1, n+1, n+2
# define B4(n) B2(n), B2(n+1), B2(n+1), B2(n+2)
# define B6(n) B4(n), B4(n+1), B4(n+1), B4(n+2)
B6(0), B6(1), B6(1), B6(2)
};
unsigned int v; // count the number of bits set in 32-bit value v
unsigned int c; // c is the total bits set in v
// Option 1:
c = BitsSetTable256[v & 0xff] +
BitsSetTable256[(v >> 8) & 0xff] +
BitsSetTable256[(v >> 16) & 0xff] +
BitsSetTable256[v >> 24];
// Option 2:
unsigned char * p = (unsigned char *) &v;
c = BitsSetTable256[p[0]] +
BitsSetTable256[p[1]] +
BitsSetTable256[p[2]] +
BitsSetTable256[p[3]];
// To initially generate the table algorithmically:
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) + BitsSetTable256[i / 2];
}
On July 14, 2009 Hallvard Furuseth suggested the macro compacted table.
<a name="CountBitsSetKernighan">Counting bits set, Brian Kernighan's way</a>
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only the high bit set, then it will only go once through the loop.
Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and published in 1964 in a book edited by Beckenbach.)"
<a name="CountBitsSet64">Counting bits set in 14, 24, or 32-bit words using 64-bit instructions</a>
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
// option 1, for at most 14-bit values in v:
c = (v * 0x200040008001ULL & 0x111111111111111ULL) % 0xf;
// option 2, for at most 24-bit values in v:
c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL)
% 0x1f;
// option 3, for at most 32-bit values in v:
c = ((v & 0xfff) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
c += (((v & 0xfff000) >> 12) * 0x1001001001001ULL & 0x84210842108421ULL) %
0x1f;
c += ((v >> 24) * 0x1001001001001ULL & 0x84210842108421ULL) % 0x1f;
This method requires a 64-bit CPU with fast modulus division to be efficient. The first option takes only 3 operations; the second option takes 10; and the third option takes 15.
Rich Schroeppel originally created a 9-bit version, similiar to option 1; see the Programming Hacks section of <a>Beeler, M., Gosper, R. W., and Schroeppel, R. HAKMEM. MIT AI Memo 239, Feb. 29, 1972.</a> His method was the inspiration for the variants above, devised by Sean Anderson. Randal E. Bryant offered a couple bug fixes on May 3, 2005. Bruce Dawson tweaked what had been a 12-bit version and made it suitable for 14 bits using the same number of operations on Feburary 1, 2007.
<a name="CountBitsSetParallel">Counting bits set, in parallel</a>
unsigned int v; // count bits set in this (32-bit value)
unsigned int c; // store the total here
static const int S[] = {1, 2, 4, 8, 16}; // Magic Binary Numbers
static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};
c = v - ((v >> 1) & B[0]);
c = ((c >> S[1]) & B[1]) + (c & B[1]);
c = ((c >> S[2]) + c) & B[2];
c = ((c >> S[3]) + c) & B[3];
c = ((c >> S[4]) + c) & B[4];
The B array, expressed as binary, is:
B[0] = 0x55555555 = 01010101 01010101 01010101 01010101
B[1] = 0x33333333 = 00110011 00110011 00110011 00110011
B[2] = 0x0F0F0F0F = 00001111 00001111 00001111 00001111
B[3] = 0x00FF00FF = 00000000 11111111 00000000 11111111
B[4] = 0x0000FFFF = 00000000 00000000 11111111 11111111
We can adjust the method for larger integer sizes by continuing with the patterns for the <em>Binary Magic Numbers,</em> B and S. If there are k bits, then we need the arrays S and B to be ceil(lg(k)) elements long, and we must compute the same number of expressions for c as S or B are long. For a 32-bit v, 16 operations are used.
The best method for counting bits in a 32-bit integer v is the following:
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
The best bit counting method takes only 12 operations, which is the same as the lookup-table method, but avoids the memory and potential cache misses of a table. It is a hybrid between the purely parallel method above and the earlier methods using multiplies (in the section on counting bits with 64-bit instructions), though it doesn't use 64-bit instructions. The counts of bits set in the bytes is done in parallel, and the sum total of the bits set in the bytes is computed by multiplying by 0x1010101 and shifting right 24 bits.
A generalization of the best bit counting method to integers of bit-widths upto 128 (parameterized by type T) is this:
v = v - ((v >> 1) & (T)~(T)0/3); // temp
v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); // temp
v = (v + (v >> 4)) & (T)~(T)0/255*15; // temp
c = (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * CHAR_BIT; // count
See <a>Ian Ashdown's nice newsgroup post</a> for more information on counting the number of bits set (also known as <em>sideways addition</em>). The best bit counting method was brought to my attention on October 5, 2005 by <a>Andrew Shapira</a>; he found it in pages 187-188 of <a>Software Optimization Guide for AMD Athlon™ 64 and Opteron™ Processors</a>. Charlie Gordon suggested a way to shave off one operation from the purely parallel version on December 14, 2005, and Don Clugston trimmed three more from it on December 30, 2005. I made a typo with Don's suggestion that Eric Cole spotted on January 8, 2006. Eric later suggested the arbitrary bit-width generalization to the best method on November 17, 2006. On April 5, 2007, Al Williams observed that I had a line of dead code at the top of the first method.
<a name="CountBitsFromMSBToPos">Count bits set (rank) from the most-significant bit upto a given position</a>
The following finds the the rank of a bit, meaning it returns the sum of bits that are set to 1 from the most-signficant bit downto the bit at the given position.
uint64_t v; // Compute the rank (bits set) in v from the MSB to pos.
unsigned int pos; // Bit position to count bits upto.
uint64_t r; // Resulting rank of bit at pos goes here.
// Shift out bits after given position.
r = v >> (sizeof(v) * CHAR_BIT - pos);
// Count set bits in parallel.
// r = (r & 0x5555...) + ((r >> 1) & 0x5555...);
r = r - ((r >> 1) & ~0UL/3);
// r = (r & 0x3333...) + ((r >> 2) & 0x3333...);
r = (r & ~0UL/5) + ((r >> 2) & ~0UL/5);
// r = (r & 0x0f0f...) + ((r >> 4) & 0x0f0f...);
r = (r + (r >> 4)) & ~0UL/17;
// r = r % 255;
r = (r * (~0UL/255)) >> ((sizeof(v) - 1) * CHAR_BIT);
Juha Järvi sent this to me on November 21, 2009 as an inverse operation to the computing the bit position with the given rank, which follows.
<a name="SelectPosFromMSBRank">Select the bit position (from the most-significant bit) with the given count (rank)</a>
The following 64-bit code selects the position of the rth 1 bit when counting from the left. In other words if we start at the most significant bit and proceed to the right, counting the number of bits set to 1 until we reach the desired rank, r, then the position where we stop is returned. If the rank requested exceeds the count of bits set, then 64 is returned. The code may be modified for 32-bit or counting from the right.
uint64_t v; // Input value to find position with rank r.
unsigned int r; // Input: bit's desired rank [1-64].
unsigned int s; // Output: Resulting position of bit with rank r [1-64]
uint64_t a, b, c, d; // Intermediate temporaries for bit count.
unsigned int t; // Bit count temporary.
// Do a normal parallel bit count for a 64-bit integer,
// but store all intermediate steps.
// a = (v & 0x5555...) + ((v >> 1) & 0x5555...);
a = v - ((v >> 1) & ~0UL/3);
// b = (a & 0x3333...) + ((a >> 2) & 0x3333...);
b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
// c = (b & 0x0f0f...) + ((b >> 4) & 0x0f0f...);
c = (b + (b >> 4)) & ~0UL/0x11;
// d = (c & 0x00ff...) + ((c >> 8) & 0x00ff...);
d = (c + (c >> 8)) & ~0UL/0x101;
t = (d >> 32) + (d >> 48);
// Now do branchless select!
s = 64;
// if (r > t) {s -= 32; r -= t;}
s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
t = (d >> (s - 16)) & 0xff;
// if (r > t) {s -= 16; r -= t;}
s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
t = (c >> (s - 8)) & 0xf;
// if (r > t) {s -= 8; r -= t;}
s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
t = (b >> (s - 4)) & 0x7;
// if (r > t) {s -= 4; r -= t;}
s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
t = (a >> (s - 2)) & 0x3;
// if (r > t) {s -= 2; r -= t;}
s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
t = (v >> (s - 1)) & 0x1;
// if (r > t) s--;
s -= ((t - r) & 256) >> 8;
s = 65 - s;
If branching is fast on your target CPU, consider uncommenting the if-statements and commenting the lines that follow them.
Juha Järvi sent this to me on November 21, 2009.
<a name="ParityNaive">Computing parity the naive way</a>
unsigned int v; // word value to compute the parity of
bool parity = false; // parity will be the parity of v
while (v)
{
parity = !parity;
v = v & (v - 1);
}
The above code uses an approach like Brian Kernigan's bit counting, above. The time it takes is proportional to the number of bits set.
<a name="ParityLookupTable">Compute parity by lookup table</a>
static const bool ParityTable256[256] =
{
# define P2(n) n, n^1, n^1, n
# define P4(n) P2(n), P2(n^1), P2(n^1), P2(n)
# define P6(n) P4(n), P4(n^1), P4(n^1), P4(n)
P6(0), P6(1), P6(1), P6(0)
};
unsigned char b; // byte value to compute the parity of
bool parity = ParityTable256[b];
// OR, for 32-bit words:
unsigned int v;
v ^= v >> 16;
v ^= v >> 8;
bool parity = ParityTable256[v & 0xff];
// Variation:
unsigned char * p = (unsigned char *) &v;
parity = ParityTable256[p[0] ^ p[1] ^ p[2] ^ p[3]];
Randal E. Bryant encouraged the addition of the (admittedly) obvious last variation with variable p on May 3, 2005. Bruce Rawles found a typo in an instance of the table variable's name on September 27, 2005, and he received a $10 bug bounty. On October 9, 2006, Fabrice Bellard suggested the 32-bit variations above, which require only one table lookup; the previous version had four lookups (one per byte) and were slower. On July 14, 2009 Hallvard Furuseth suggested the macro compacted table.
<a name="ParityWith64Bits">Compute parity of a byte using 64-bit multiply and modulus division</a>
unsigned char b; // byte value to compute the parity of
bool parity =
(((b * 0x0101010101010101ULL) & 0x8040201008040201ULL) % 0x1FF) & 1;
The method above takes around 4 operations, but only works on bytes.
<a name="ParityMultiply">Compute parity of word with a multiply</a>
The following method computes the parity of the 32-bit value in only 8 operations using a multiply.
unsigned int v; // 32-bit word
v ^= v >> 1;
v ^= v >> 2;
v = (v & 0x11111111U) * 0x11111111U;
return (v >> 28) & 1;
Also for 64-bits, 8 operations are still enough.
unsigned long long v; // 64-bit word
v ^= v >> 1;
v ^= v >> 2;
v = (v & 0x1111111111111111UL) * 0x1111111111111111UL;
return (v >> 60) & 1;
Andrew Shapira came up with this and sent it to me on Sept. 2, 2007.
<a name="ParityParallel">Compute parity in parallel</a>
unsigned int v; // word value to compute the parity of
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
v &= 0xf;
return (0x6996 >> v) & 1;
The method above takes around 9 operations, and works for 32-bit words. It may be optimized to work just on bytes in 5 operations by removing the two lines immediately following "unsigned int v;". The method first shifts and XORs the eight nibbles of the 32-bit value together, leaving the result in the lowest nibble of v. Next, the binary number 0110 1001 1001 0110 (0x6996 in hex) is shifted to the right by the value represented in the lowest nibble of v. This number is like a miniature 16-bit parity-table indexed by the low four bits in v. The result has the parity of v in bit 1, which is masked and returned.
Thanks to Mathew Hendry for pointing out the shift-lookup idea at the end on Dec. 15, 2002. That optimization shaves two operations off using only shifting and XORing to find the parity.
<a name="SwappingValuesSubAdd">Swapping values with subtraction and addition</a>
#define SWAP(a, b) ((&(a) == &(b)) || \
(((a) -= (b)), ((b) += (a)), ((a) = (b) - (a))))
This swaps the values of a and b <em>without using a temporary variable.</em> The initial check for a and b being the same location in memory may be omitted when you know this can't happen. (The compiler may omit it anyway as an optimization.) If you enable overflows exceptions, then pass unsigned values so an exception isn't thrown. The XOR method that follows may be slightly faster on some machines. Don't use this with floating-point numbers (unless you operate on their raw integer representations).
Sanjeev Sivasankaran suggested I add this on June 12, 2007. Vincent Lefèvre pointed out the potential for overflow exceptions on July 9, 2008
<a name="SwappingValuesXOR">Swapping values with XOR</a>
#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
This is an old trick to exchange the values of the variables a and b <em>without using extra space for a temporary variable</em>.
On January 20, 2005, Iain A. Fleming pointed out that the macro above doesn't work when you swap with the same memory location, such as SWAP(a[i], a[j]) with i == j. So if that may occur, consider defining the macro as (((a) == (b)) || (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))). On July 14, 2009, Hallvard Furuseth suggested that on some machines, (((a) ^ (b)) && ((b) ^= (a) ^= (b), (a) ^= (b))) might be faster, since the (a) ^ (b) expression is reused.
<a name="SwappingBitsXOR">Swapping individual bits with XOR</a>
unsigned int i, j; // positions of bit sequences to swap
unsigned int n; // number of consecutive bits in each sequence
unsigned int b; // bits to swap reside in b
unsigned int r; // bit-swapped result goes here
unsigned int x = ((b >> i) ^ (b >> j)) & ((1U << n) - 1); // XOR temporary
r = b ^ ((x << i) | (x << j));
As an example of swapping ranges of bits suppose we have have b = <strong>001</strong>0<strong>111</strong>1 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would be r = <strong>111</strong>0<strong>001</strong>1 (binary).
This method of swapping is similar to the general purpose XOR swap trick, but intended for operating on individual bits. The variable x stores the result of XORing the pairs of bit values we want to swap, and then the bits are set to the result of themselves XORed with x. Of course, the result is undefined if the sequences overlap.
On July 14, 2009 Hallvard Furuseth suggested that I change the 1 << n to 1U << n because the value was being assigned to an unsigned and to avoid shifting into a sign bit.
<a name="BitReverseObvious">Reverse bits the obvious way</a>
unsigned int v; // input bits to be reversed
unsigned int r = v; // r will be reversed bits of v; first get LSB of v
int s = sizeof(v) * CHAR_BIT - 1; // extra shift needed at end
for (v >>= 1; v; v >>= 1)
{
r <<= 1;
r |= v & 1;
s--;
}
r <<= s; // shift when v's highest bits are zero
On October 15, 2004, Michael Hoisie pointed out a bug in the original version. Randal E. Bryant suggested removing an extra operation on May 3, 2005. Behdad Esfabod suggested a slight change that eliminated one iteration of the loop on May 18, 2005. Then, on February 6, 2007, Liyong Zhou suggested a better version that loops while v is not 0, so rather than iterating over all bits it stops early.
<a name="BitReverseTable">Reverse bits in word by lookup table</a>
static const unsigned char BitReverseTable256[256] =
{
# define R2(n) n, n + 2*64, n + 1*64, n + 3*64
# define R4(n) R2(n), R2(n + 2*16), R2(n + 1*16), R2(n + 3*16)
# define R6(n) R4(n), R4(n + 2*4 ), R4(n + 1*4 ), R4(n + 3*4 )
R6(0), R6(2), R6(1), R6(3)
};
unsigned int v; // reverse 32-bit value, 8 bits at time
unsigned int c; // c will get v reversed
// Option 1:
c = (BitReverseTable256[v & 0xff] << 24) |
(BitReverseTable256[(v >> 8) & 0xff] << 16) |
(BitReverseTable256[(v >> 16) & 0xff] << 8) |
(BitReverseTable256[(v >> 24) & 0xff]);
// Option 2:
unsigned char * p = (unsigned char *) &v;
unsigned char * q = (unsigned char *) &c;
q[3] = BitReverseTable256[p[0]];
q[2] = BitReverseTable256[p[1]];
q[1] = BitReverseTable256[p[2]];
q[0] = BitReverseTable256[p[3]];
The first method takes about 17 operations, and the second takes about 12, assuming your CPU can load and store bytes easily.
On July 14, 2009 Hallvard Furuseth suggested the macro compacted table.
<a name="ReverseByteWith64BitsDiv">Reverse the bits in a byte with 3 operations (64-bit multiply and modulus division):</a>
unsigned char b; // reverse this (8-bit) byte
b = (b * 0x0202020202ULL & 0x010884422010ULL) % 1023;
The multiply operation creates five separate copies of the 8-bit byte pattern to fan-out into a 64-bit value. The AND operation selects the bits that are in the correct (reversed) positions, relative to each 10-bit groups of bits. The multiply and the AND operations copy the bits from the original byte so they each appear in only one of the 10-bit sets. The reversed positions of the bits from the original byte coincide with their relative positions within any 10-bit set. The last step, which involves modulus division by 2^10 - 1, has the effect of merging together each set of 10 bits (from positions 0-9, 10-19, 20-29, ...) in the 64-bit value. They do not overlap, so the addition steps underlying the modulus division behave like or operations.
This method was attributed to Rich Schroeppel in the Programming Hacks section of <a>Beeler, M., Gosper, R. W., and Schroeppel, R. HAKMEM. MIT AI Memo 239, Feb. 29, 1972.</a>
<a name="ReverseByteWith64Bits">Reverse the bits in a byte with 4 operations (64-bit multiply, no division):</a>
unsigned char b; // reverse this byte
b = ((b * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32;
The following shows the flow of the bit values with the boolean variables <code>a, b, c, d, e, f, g,</code> and <code>h</code>, which comprise an 8-bit byte. Notice how the first multiply fans out the bit pattern to multiple copies, while the last multiply combines them in the fifth byte from the right.
abcd efgh (-> hgfe dcba)
* 1000 0000 0010 0000 0000 1000 0000 0010 (0x80200802)
-------------------------------------------------------------------------------------------------
0abc defg h00a bcde fgh0 0abc defg h00a bcde fgh0
& 0000 1000 1000 0100 0100 0010 0010 0001 0001 0000 (0x0884422110)
-------------------------------------------------------------------------------------------------
0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
* 0000 0001 0000 0001 0000 0001 0000 0001 0000 0001 (0x0101010101)
-------------------------------------------------------------------------------------------------
0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
0000 d000 h000 0c00 0g00 00b0 00f0 000a 000e 0000
-------------------------------------------------------------------------------------------------
0000 d000 h000 dc00 hg00 dcb0 hgf0 dcba hgfe dcba hgfe 0cba 0gfe 00ba 00fe 000a 000e 0000
>> 32
-------------------------------------------------------------------------------------------------
0000 d000 h000 dc00 hg00 dcb0 hgf0 dcba hgfe dcba
& 1111 1111
-------------------------------------------------------------------------------------------------
hgfe dcba
Note that the last two steps can be combined on some processors because the registers can be accessed as bytes; just multiply so that a register stores the upper 32 bits of the result and the take the low byte. Thus, it may take only 6 operations.
Devised by Sean Anderson, July 13, 2001.
<a name="ReverseByteWith32Bits">Reverse the bits in a byte with 7 operations (no 64-bit):</a>
b = ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
Make sure you assign or cast the result to an unsigned char to remove garbage in the higher bits. Devised by Sean Anderson, July 13, 2001. Typo spotted and correction supplied by Mike Keith, January 3, 2002.
<a name="ReverseParallel">Reverse an N-bit quantity in parallel in 5 * lg(N) operations:</a>
unsigned int v; // 32-bit word to reverse bit order
// swap odd and even bits
v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);
// swap consecutive pairs
v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);
// swap nibbles ...
v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);
// swap bytes
v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);
// swap 2-byte long pairs
v = ( v >> 16 ) | ( v << 16);
The following variation is also O(lg(N)), however it requires more operations to reverse v. Its virtue is in taking less slightly memory by computing the constants on the fly.
unsigned int s = sizeof(v) * CHAR_BIT; // bit size; must be power of 2
unsigned int mask = ~0;
while ((s >>= 1) > 0)
{
mask ^= (mask << s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
These methods above are best suited to situations where N is large. If you use the above with 64-bit ints (or larger), then you need to add more lines (following the pattern); otherwise only the lower 32 bits will be reversed and the result will be in the lower 32 bits.
See Dr. Dobb's Journal 1983, Edwin Freed's article on Binary Magic Numbers for more information. The second variation was suggested by Ken Raeburn on September 13, 2005. Veldmeijer mentioned that the first version could do without ANDS in the last line on March 19, 2006.
<a name="ModulusDivisionEasy">Compute modulus division by 1 << s without a division operator</a>
const unsigned int n; // numerator
const unsigned int s;
const unsigned int d = 1U << s; // So d will be one of: 1, 2, 4, 8, 16, 32, ...
unsigned int m; // m will be n % d
m = n & (d - 1);
Most programmers learn this trick early, but it was included for the sake of completeness.
<a name="ModulusDivision">Compute modulus division by (1 << s) - 1 without a division operator</a>
unsigned int n; // numerator
const unsigned int s; // s > 0
const unsigned int d = (1 << s) - 1; // so d is either 1, 3, 7, 15, 31, ...).
unsigned int m; // n % d goes here.
for (m = n; n > d; n = m)
{
for (m = 0; n; n >>= s)
{
m += n & d;
}
}
// Now m is a value from 0 to d, but since with modulus division
// we want m to be 0 when it is d.
m = m == d ? 0 : m;
This method of modulus division by an integer that is one less than a power of 2 takes at most 5 + (4 + 5 * ceil(N / s)) * ceil(lg(N / s)) operations, where N is the number of bits in the numerator. In other words, it takes at most O(N * lg(N)) time.
Devised by Sean Anderson, August 15, 2001. Before Sean A. Irvine corrected me on June 17, 2004, I mistakenly commented that we could alternatively assign <code>m = ((m + 1) & d) - 1;</code> at the end. Michael Miller spotted a typo in the code April 25, 2005.
<a name="ModulusDivisionParallel">Compute modulus division by (1 << s) - 1 in parallel without a division operator</a>
// The following is for a word size of 32 bits!
static const unsigned int M[] =
{
0x00000000, 0x55555555, 0x33333333, 0xc71c71c7,
0x0f0f0f0f, 0xc1f07c1f, 0x3f03f03f, 0xf01fc07f,
0x00ff00ff, 0x07fc01ff, 0x3ff003ff, 0xffc007ff,
0xff000fff, 0xfc001fff, 0xf0003fff, 0xc0007fff,
0x0000ffff, 0x0001ffff, 0x0003ffff, 0x0007ffff,
0x000fffff, 0x001fffff, 0x003fffff, 0x007fffff,
0x00ffffff, 0x01ffffff, 0x03ffffff, 0x07ffffff,
0x0fffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff
};
static const unsigned int Q[][6] =
{
{ 0, 0, 0, 0, 0, 0}, {16, 8, 4, 2, 1, 1}, {16, 8, 4, 2, 2, 2},
{15, 6, 3, 3, 3, 3}, {16, 8, 4, 4, 4, 4}, {15, 5, 5, 5, 5, 5},
{12, 6, 6, 6 , 6, 6}, {14, 7, 7, 7, 7, 7}, {16, 8, 8, 8, 8, 8},
{ 9, 9, 9, 9, 9, 9}, {10, 10, 10, 10, 10, 10}, {11, 11, 11, 11, 11, 11},
{12, 12, 12, 12, 12, 12}, {13, 13, 13, 13, 13, 13}, {14, 14, 14, 14, 14, 14},
{15, 15, 15, 15, 15, 15}, {16, 16, 16, 16, 16, 16}, {17, 17, 17, 17, 17, 17},
{18, 18, 18, 18, 18, 18}, {19, 19, 19, 19, 19, 19}, {20, 20, 20, 20, 20, 20},
{21, 21, 21, 21, 21, 21}, {22, 22, 22, 22, 22, 22}, {23, 23, 23, 23, 23, 23},
{24, 24, 24, 24, 24, 24}, {25, 25, 25, 25, 25, 25}, {26, 26, 26, 26, 26, 26},
{27, 27, 27, 27, 27, 27}, {28, 28, 28, 28, 28, 28}, {29, 29, 29, 29, 29, 29},
{30, 30, 30, 30, 30, 30}, {31, 31, 31, 31, 31, 31}
};
static const unsigned int R[][6] =
{
{0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000},
{0x0000ffff, 0x000000ff, 0x0000000f, 0x00000003, 0x00000001, 0x00000001},
{0x0000ffff, 0x000000ff, 0x0000000f, 0x00000003, 0x00000003, 0x00000003},
{0x00007fff, 0x0000003f, 0x00000007, 0x00000007, 0x00000007, 0x00000007},
{0x0000ffff, 0x000000ff, 0x0000000f, 0x0000000f, 0x0000000f, 0x0000000f},
{0x00007fff, 0x0000001f, 0x0000001f, 0x0000001f, 0x0000001f, 0x0000001f},
{0x00000fff, 0x0000003f, 0x0000003f, 0x0000003f, 0x0000003f, 0x0000003f},
{0x00003fff, 0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f, 0x0000007f},
{0x0000ffff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff, 0x000000ff},
{0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff, 0x000001ff},
{0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff, 0x000003ff},
{0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff, 0x000007ff},
{0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff, 0x00000fff},
{0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff, 0x00001fff},
{0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff, 0x00003fff},
{0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff, 0x00007fff},
{0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff, 0x0000ffff},
{0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff, 0x0001ffff},
{0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff, 0x0003ffff},
{0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff, 0x0007ffff},
{0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff, 0x000fffff},
{0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff, 0x001fffff},
{0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff, 0x003fffff},
{0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff, 0x007fffff},
{0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff, 0x00ffffff},
{0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff, 0x01ffffff},
{0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff, 0x03ffffff},
{0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff, 0x07ffffff},
{0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff, 0x0fffffff},
{0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff, 0x1fffffff},
{0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff, 0x3fffffff},
{0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff, 0x7fffffff}
};
unsigned int n; // numerator
const unsigned int s; // s > 0
const unsigned int d = (1 << s) - 1; // so d is either 1, 3, 7, 15, 31, ...).
unsigned int m; // n % d goes here.
m = (n & M[s]) + ((n >> s) & M[s]);
for (const unsigned int * q = &Q[s][0], * r = &R[s][0]; m > d; q++, r++)
{
m = (m >> *q) + (m & *r);
}
m = m == d ? 0 : m; // OR, less portably: m = m & -((signed)(m - d) >> s);
This method of finding modulus division by an integer that is one less than a power of 2 takes at most O(lg(N)) time, where N is the number of bits in the numerator (32 bits, for the code above). The number of operations is at most 12 + 9 * ceil(lg(N)). The tables may be removed if you know the denominator at compile time; just extract the few relevent entries and unroll the loop. It may be easily extended to more bits.
It finds the result by summing the values in base (1 << s) in parallel. First every other base (1 << s) value is added to the previous one. Imagine that the result is written on a piece of paper. Cut the paper in half, so that half the values are on each cut piece. Align the values and sum them onto a new piece of paper. Repeat by cutting this paper in half (which will be a quarter of the size of the previous one) and summing, until you cannot cut further. After performing lg(N/s/2) cuts, we cut no more; just continue to add the values and put the result onto a new piece of paper as before, while there are at least two s-bit values.
Devised by Sean Anderson, August 20, 2001. A typo was spotted by Randy E. Bryant on May 3, 2005 (after pasting the code, I had later added "unsinged" to a variable declaration). As in the previous hack, I mistakenly commented that we could alternatively assign <code>m = ((m + 1) & d) - 1;</code> at the end, and Don Knuth corrected me on April 19, 2006 and suggested <code>m = m & -((signed)(m - d) >> s)</code>. On June 18, 2009 Sean Irvine proposed a change that used <code>((n >> s) & M[s])</code> instead of <code>((n & ~M[s]) >> s)</code>, which typically requires fewer operations because the M[s] constant is already loaded.
<a name="IntegerLogObvious">Find the log base 2 of an integer with the MSB N set in O(N) operations (the obvious way)</a>
unsigned int v; // 32-bit word to find the log base 2 of
unsigned int r = 0; // r will be lg(v)
while (v >>= 1) // unroll for more speed...
{
r++;
}
The log base 2 of an integer is the same as the position of the highest bit set (or most significant bit set, MSB). The following log base 2 methods are faster than this one.
<a name="IntegerLogIEEE64Float">Find the integer log base 2 of an integer with an 64-bit IEEE float</a>
int v; // 32-bit integer to find the log base 2 of
int r; // result of log_2(v) goes here
union { unsigned int u[2]; double d; } t; // temp
t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0x43300000;
t.u[__FLOAT_WORD_ORDER!=LITTLE_ENDIAN] = v;
t.d -= 4503599627370496.0;
r = (t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] >> 20) - 0x3FF;
The code above loads a 64-bit (IEEE-754 floating-point) double with a 32-bit integer (with no paddding bits) by storing the integer in the mantissa while the exponent is set to 252. From this newly minted double, 252 (expressed as a double) is subtracted, which sets the resulting exponent to the log base 2 of the input value, v. All that is left is shifting the exponent bits into position (20 bits right) and subtracting the bias, 0x3FF (which is 1023 decimal). This technique only takes 5 operations, but many CPUs are slow at manipulating doubles, and the endianess of the architecture must be accommodated.
Eric Cole sent me this on January 15, 2006. Evan Felix pointed out a typo on April 4, 2006. Vincent Lefèvre told me on July 9, 2008 to change the endian check to use the float's endian, which could differ from the integer's endian.
<a name="IntegerLogLookup">Find the log base 2 of an integer with a lookup table</a>
static const char LogTable256[256] =
{
#define LT(n) n, n, n, n, n, n, n, n, n, n, n, n, n, n, n, n
-1, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
LT(4), LT(5), LT(5), LT(6), LT(6), LT(6), LT(6),
LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7), LT(7)
};
unsigned int v; // 32-bit word to find the log of
unsigned r; // r will be lg(v)
register unsigned int t, tt; // temporaries
if (tt = v >> 16)
{
r = (t = tt >> 8) ? 24 + LogTable256[t] : 16 + LogTable256[tt];
}
else
{
r = (t = v >> 8) ? 8 + LogTable256[t] : LogTable256[v];
}
The lookup table method takes only about 7 operations to find the log of a 32-bit value. If extended for 64-bit quantities, it would take roughly 9 operations. Another operation can be trimmed off by using four tables, with the possible additions incorporated into each. Using int table elements may be faster, depending on your architecture.
The code above is tuned to uniformly distributed <em>output</em> values. If your <em>inputs</em> are evenly distributed across all 32-bit values, then consider using the following:
if (tt = v >> 24)
{
r = 24 + LogTable256[tt];
}
else if (tt = v >> 16)
{
r = 16 + LogTable256[tt];
}
else if (tt = v >> 8)
{
r = 8 + LogTable256[tt];
}
else
{
r = LogTable256[v];
}
To initially generate the log table algorithmically:
LogTable256[0] = LogTable256[1] = 0;
for (int i = 2; i < 256; i++)
{
LogTable256[i] = 1 + LogTable256[i / 2];
}
LogTable256[0] = -1; // if you want log(0) to return -1
Behdad Esfahbod and I shaved off a fraction of an operation (on average) on May 18, 2005. Yet another fraction of an operation was removed on November 14, 2006 by Emanuel Hoogeveen. The variation that is tuned to evenly distributed input values was suggested by David A. Butterfield on September 19, 2008. Venkat Reddy told me on January 5, 2009 that log(0) should return -1 to indicate an error, so I changed the first entry in the table to that.
<a name="IntegerLog">Find the log base 2 of an N-bit integer in O(lg(N)) operations</a>
unsigned int v; // 32-bit value to find the log2 of
const unsigned int b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
const unsigned int S[] = {1, 2, 4, 8, 16};
int i;
register unsigned int r = 0; // result of log2(v) will go here
for (i = 4; i >= 0; i--) // unroll for speed...
{
if (v & b[i])
{
v >>= S[i];
r |= S[i];
}
}
// OR (IF YOUR CPU BRANCHES SLOWLY):
unsigned int v; // 32-bit value to find the log2 of
register unsigned int r; // result of log2(v) will go here
register unsigned int shift;
r = (v > 0xFFFF) << 4; v >>= r;
shift = (v > 0xFF ) << 3; v >>= shift; r |= shift;
shift = (v > 0xF ) << 2; v >>= shift; r |= shift;
shift = (v > 0x3 ) << 1; v >>= shift; r |= shift;
r |= (v >> 1);
// OR (IF YOU KNOW v IS A POWER OF 2):
unsigned int v; // 32-bit value to find the log2 of
static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0,
0xFF00FF00, 0xFFFF0000};
register unsigned int r = (v & b[0]) != 0;
for (i = 4; i > 0; i--) // unroll for speed...
{
r |= ((v & b[i]) != 0) << i;
}
Of course, to extend the code to find the log of a 33- to 64-bit number, we would append another element, 0xFFFFFFFF00000000, to b, append 32 to S, and loop from 5 to 0. This method is much slower than the earlier table-lookup version, but if you don't want big table or your architecture is slow to access memory, it's a good choice. The second variation involves slightly more operations, but it may be faster on machines with high branch costs (e.g. PowerPC).
The second version was sent to me by <a>Eric Cole</a> on January 7, 2006. Andrew Shapira subsequently trimmed a few operations off of it and sent me his variation (above) on Sept. 1, 2007. The third variation was suggested to me by <a>John Owens</a> on April 24, 2002; it's faster, but <em>it is only suitable when the input is known to be a power of 2</em>. On May 25, 2003, Ken Raeburn suggested improving the general case by using smaller numbers for b[], which load faster on some architectures (for instance if the word size is 16 bits, then only one load instruction may be needed). These values work for the general version, but not for the special-case version below it, where v is a power of 2; Glenn Slayden brought this oversight to my attention on December 12, 2003.
<a name="IntegerLogDeBruijn">Find the log base 2 of an N-bit integer in O(lg(N)) operations with multiply and lookup</a>
uint32_t v; // find the log base 2 of 32-bit v
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
v |= v >> 1; // first round down to one less than a power of 2
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
r = MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];
The code above computes the log base 2 of a 32-bit integer with a small table lookup and multiply. It requires only 13 operations, compared to (up to) 20 for the previous method. The purely table-based method requires the fewest operations, but this offers a reasonable compromise between table size and speed.
If you know that v is a power of 2, then you only need the following:
static const int MultiplyDeBruijnBitPosition2[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition2[(uint32_t)(v * 0x077CB531U) >> 27];
Eric Cole devised this January 8, 2006 after reading about the entry below to <a>round up to a power of 2</a> and the method below for <a>computing the number of trailing bits with a multiply and lookup</a> using a DeBruijn sequence. On December 10, 2009, Mark Dickinson shaved off a couple operations by requiring v be rounded up to one less than the next power of 2 rather than the power of 2.
<a name="IntegerLog10">Find integer log base 10 of an integer</a>
unsigned int v; // non-zero 32-bit integer value to compute the log base 10 of
int r; // result goes here
int t; // temporary
static unsigned int const PowersOf10[] =
{1, 10, 100, 1000, 10000, 100000,
1000000, 10000000, 100000000, 1000000000};
t = (IntegerLogBase2(v) + 1) * 1233 >> 12; // (use a lg2 method from above)
r = t - (v < PowersOf10[t]);
The integer log base 10 is computed by first using one of the techniques above for finding the log base 2. By the relationship log10(v) = log2(v) / log2(10), we need to multiply it by 1/log2(10), which is approximately 1233/4096, or 1233 followed by a right shift of 12. Adding one is needed because the IntegerLogBase2 rounds down. Finally, since the value t is only an approximation that may be off by one, the exact value is found by subtracting the result of v < PowersOf10[t].
This method takes 6 more operations than IntegerLogBase2. It may be sped up (on machines with fast memory access) by modifying the log base 2 table-lookup method above so that the entries hold what is computed for t (that is, pre-add, -mulitply, and -shift). Doing so would require a total of only 9 operations to find the log base 10, assuming 4 tables were used (one for each byte of v).
Eric Cole suggested I add a version of this on January 7, 2006.
<a name="IntegerLog10Obvious">Find integer log base 10 of an integer the obvious way</a>
unsigned int v; // non-zero 32-bit integer value to compute the log base 10 of
int r; // result goes here
r = (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
(v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
(v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
This method works well when the input is uniformly distributed over 32-bit values because 76% of the inputs are caught by the first compare, 21% are caught by the second compare, 2% are caught by the third, and so on (chopping the remaining down by 90% with each comparision). As a result, less than 2.6 operations are needed on average.
On April 18, 2007, Emanuel Hoogeveen suggested a variation on this where the conditions used divisions, which were not as fast as simple comparisons.
<a name="IntegerLogFloat">Find integer log base 2 of a 32-bit IEEE float</a>
const float v; // find int(log2(v)), where v > 0.0 && finite(v) && isnormal(v)
int c; // 32-bit int c gets the result;
c = *(const int *) &v; // OR, for portability: memcpy(&c, &v, sizeof c);
c = (c >> 23) - 127;
The above is fast, but IEEE 754-compliant architectures utilize <em>subnormal</em> (also called <em>denormal</em>) floating point numbers. These have the exponent bits set to zero (signifying pow(2,-127)), and the mantissa is not normalized, so it contains leading zeros and thus the log2 must be computed from the mantissa. To accomodate for subnormal numbers, use the following:
const float v; // find int(log2(v)), where v > 0.0 && finite(v)
int c; // 32-bit int c gets the result;
int x = *(const int *) &v; // OR, for portability: memcpy(&x, &v, sizeof x);
c = x >> 23;
if (c)
{
c -= 127;
}
else
{ // subnormal, so recompute using mantissa: c = intlog2(x) - 149;
register unsigned int t; // temporary
// Note that LogTable256 was defined [earlier](#IntegerLogLookup)
if (t = x >> 16)
{
c = LogTable256[t] - 133;
}
else
{
c = (t = x >> 8) ? LogTable256[t] - 141 : LogTable256[x] - 149;
}
}
On June 20, 2004, Sean A. Irvine suggested that I include code to handle subnormal numbers. On June 11, 2005, Falk Hüffner pointed out that ISO C99 6.5/7 specified undefined behavior for the common type punning idiom <em>(int </em>)&, though it has worked on 99.9% of C compilers. He proposed using memcpy for maximum portability or a union with a float and an int for better code generation than memcpy on some compilers.
<a name="IntegerLogRootFloat">Find integer log base 2 of the pow(2, r)-root of a 32-bit IEEE float (for unsigned integer r)</a>
const int r;
const float v; // find int(log2(pow((double) v, 1\. / pow(2, r)))),
// where isnormal(v) and v > 0
int c; // 32-bit int c gets the result;
c = *(const int *) &v; // OR, for portability: memcpy(&c, &v, sizeof c);
c = ((((c - 0x3f800000) >> r) + 0x3f800000) >> 23) - 127;
So, if r is 0, for example, we have c = int(log2((double) v)). If r is 1, then we have c = int(log2(sqrt((double) v))). If r is 2, then we have c = int(log2(pow((double) v, 1./4))).
On June 11, 2005, Falk Hüffner pointed out that ISO C99 6.5/7 left the type punning idiom <em>(int </em>)& undefined, and he suggested using memcpy.
<a name="ZerosOnRightLinear">Count the consecutive zero bits (trailing) on the right linearly</a>
unsigned int v; // input to count trailing zero bits
int c; // output: c will count v's trailing zero bits,
// so if v is 1101000 (base 2), then c will be 3
if (v)
{
v = (v ^ (v - 1)) >> 1; // Set v's trailing 0s to 1s and zero rest
for (c = 0; v; c++)
{
v >>= 1;
}
}
else
{
c = CHAR_BIT * sizeof(v);
}
The average number of trailing zero bits in a (uniformly distributed) random binary number is one, so this O(trailing zeros) solution isn't that bad compared to the faster methods below.
Jim Cole suggested I add a linear-time method for counting the trailing zeros on August 15, 2007. On October 22, 2007, Jason Cunningham pointed out that I had neglected to paste the unsigned modifier for v.
<a name="ZerosOnRightParallel">Count the consecutive zero bits (trailing) on the right in parallel</a>
unsigned int v; // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
Here, we are basically doing the same operations as finding the log base 2 in parallel, but we first isolate the lowest 1 bit, and then proceed with c starting at the maximum and decreasing. The number of operations is at most 3 * lg(N) + 4, roughly, for N bit words.
Bill Burdick suggested an optimization, reducing the time from 4 * lg(N) on February 4, 2011.
<a name="ZerosOnRightBinSearch">Count the consecutive zero bits (trailing) on the right by binary search</a>
unsigned int v; // 32-bit word input to count zero bits on right
unsigned int c; // c will be the number of zero bits on the right,
// so if v is 1101000 (base 2), then c will be 3
// NOTE: if 0 == v, then c = 31.
if (v & 0x1)
{
// special case for odd v (assumed to happen half of the time)
c = 0;
}
else
{
c = 1;
if ((v & 0xffff) == 0)
{
v >>= 16;
c += 16;
}
if ((v & 0xff) == 0)
{
v >>= 8;
c += 8;
}
if ((v & 0xf) == 0)
{
v >>= 4;
c += 4;
}
if ((v & 0x3) == 0)
{
v >>= 2;
c += 2;
}
c -= v & 0x1;
}
The code above is similar to the previous method, but it computes the number of trailing zeros by accumulating c in a manner akin to binary search. In the first step, it checks if the bottom 16 bits of v are zeros, and if so, shifts v right 16 bits and adds 16 to c, which reduces the number of bits in v to consider by half. Each of the subsequent conditional steps likewise halves the number of bits until there is only 1. This method is faster than the last one (by about 33%) because the bodies of the if statements are executed less often.
Matt Whitlock suggested this on January 25, 2006. Andrew Shapira shaved a couple operations off on Sept. 5, 2007 (by setting c=1 and unconditionally subtracting at the end).
<a name="ZerosOnRightFloatCast">Count the consecutive zero bits (trailing) on the right by casting to a float</a>
unsigned int v; // find the number of trailing zeros in v
int r; // the result goes here
float f = (float)(v & -v); // cast the least significant bit in v to a float
r = (*(uint32_t *)&f >> 23) - 0x7f;
Although this only takes about 6 operations, the time to convert an integer to a float can be high on some machines. The exponent of the 32-bit IEEE floating point representation is shifted down, and the bias is subtracted to give the position of the least significant 1 bit set in v. If v is zero, then the result is -127.
<a name="ZerosOnRightModLookup">Count the consecutive zero bits (trailing) on the right with modulus division and lookup</a>
unsigned int v; // find the number of trailing zeros in v
int r; // put the result in r
static const int Mod37BitPosition[] = // map a bit value mod 37 to its position
{
32, 0, 1, 26, 2, 23, 27, 0, 3, 16, 24, 30, 28, 11, 0, 13, 4,
7, 17, 0, 25, 22, 31, 15, 29, 10, 12, 6, 0, 21, 14, 9, 5,
20, 8, 19, 18
};
r = Mod37BitPosition[(-v & v) % 37];
The code above finds the number of zeros that are trailing on the right, so binary 0100 would produce 2. It makes use of the fact that the first 32 bit position values are relatively prime with 37, so performing a modulus division with 37 gives a unique number from 0 to 36 for each. These numbers may then be mapped to the number of zeros using a small lookup table. It uses only 4 operations, however indexing into a table and performing modulus division may make it unsuitable for some situations. I came up with this independently and then searched for a subsequence of the table values, and found it was invented earlier by Reiser, according to <a>Hacker's Delight</a>.
<a name="ZerosOnRightMultLookup">Count the consecutive zero bits (trailing) on the right with multiply and lookup</a>
unsigned int v; // find the number of trailing zeros in 32-bit v
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];
Converting bit vectors to indices of set bits is an example use for this. It requires one more operation than the earlier one involving modulus division, but the multiply may be faster. The expression (v & -v) extracts the least significant 1 bit from v. The constant 0x077CB531UL is a de Bruijn sequence, which produces a unique pattern of bits into the high 5 bits for each possible bit position that it is multiplied against. When there are no bits set, it returns 0. More information can be found by reading the paper <a>Using de Bruijn Sequences to Index 1 in a Computer Word</a> by Charles E. Leiserson, Harald Prokof, and Keith H. Randall.
On October 8, 2005 <a>Andrew Shapira</a> suggested I add this. Dustin Spicuzza asked me on April 14, 2009 to cast the result of the multiply to a 32-bit type so it would work when compiled with 64-bit ints.
<a name="RoundUpPowerOf2Float">Round up to the next highest power of 2 by float casting</a>
unsigned int const v; // Round this 32-bit value to the next highest power of 2
unsigned int r; // Put the result here. (So v=3 -> r=4; v=8 -> r=8)
if (v > 1)
{
float f = (float)v;
unsigned int const t = 1U << ((*(unsigned int *)&f >> 23) - 0x7f);
r = t << (t < v);
}
else
{
r = 1;
}
The code above uses 8 operations, but works on all v <= (1<<31).
Quick and dirty version, for domain of 1 < v < (1<<25):
float f = (float)(v - 1);
r = 1U << ((*(unsigned int*)(&f) >> 23) - 126);
Although the quick and dirty version only uses around 6 operations, it is roughly three times slower than the <a>technique below</a> (which involves 12 operations) when benchmarked on an Athlon™ XP 2100+ CPU. Some CPUs will fare better with it, though.
On September 27, 2005 Andi Smithers suggested I include a technique for casting to floats to find the lg of a number for rounding up to a power of 2. Similar to the quick and dirty version here, his version worked with values less than (1<<25), due to mantissa rounding, but it used one more operation.
<a name="RoundUpPowerOf2">Round up to the next highest power of 2</a>
unsigned int v; // compute the next highest power of 2 of 32-bit v
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
In 12 operations, this code computes the next highest power of 2 for a 32-bit integer. The result may be expressed by the formula 1U << (lg(v - 1) + 1). Note that in the edge case where v is 0, it returns 0, which isn't a power of 2; you might append the expression v += (v == 0) to remedy this if it matters. It would be faster by 2 operations to use the formula and the log base 2 method that uses a lookup table, but in some situations, lookup tables are not suitable, so the above code may be best. (On a Athlon™ XP 2100+ I've found the above shift-left and then OR code is as fast as using a single BSR assembly language instruction, which scans in reverse to find the highest set bit.) It works by copying the highest set bit to all of the lower bits, and then adding one, which results in carries that set all of the lower bits to 0 and one bit beyond the highest set bit to 1. If the original number was a power of 2, then the decrement will reduce it to one less, so that we round up to the same original value.
You might alternatively compute the next higher power of 2 in only 8 or 9 operations using a lookup table for floor(lg(v)) and then evaluating 1<<(1+floor(lg(v))); Atul Divekar suggested I mention this on September 5, 2010.
Devised by Sean Anderson, Sepember 14, 2001. Pete Hart pointed me to <a>a couple newsgroup posts</a> by him and William Lewis in February of 1997, where they arrive at the same algorithm.
<a name="InterleaveTableObvious">Interleave bits the obvious way</a>
unsigned short x; // Interleave bits of x and y, so that all of the
unsigned short y; // bits of x are in the even positions and y in the odd;
unsigned int z = 0; // z gets the resulting Morton Number.
for (int i = 0; i < sizeof(x) * CHAR_BIT; i++) // unroll for more speed...
{
z |= (x & 1U << i) << i | (y & 1U << i) << (i + 1);
}
Interleaved bits (aka Morton numbers) are useful for linearizing 2D integer coordinates, so x and y are combined into a single number that can be compared easily and has the property that a number is usually close to another if their x and y values are close.
<a name="InterleaveTableLookup">Interleave bits by table lookup</a>
static const unsigned short MortonTable256[256] =
{
0x0000, 0x0001, 0x0004, 0x0005, 0x0010, 0x0011, 0x0014, 0x0015,
0x0040, 0x0041, 0x0044, 0x0045, 0x0050, 0x0051, 0x0054, 0x0055,
0x0100, 0x0101, 0x0104, 0x0105, 0x0110, 0x0111, 0x0114, 0x0115,
0x0140, 0x0141, 0x0144, 0x0145, 0x0150, 0x0151, 0x0154, 0x0155,
0x0400, 0x0401, 0x0404, 0x0405, 0x0410, 0x0411, 0x0414, 0x0415,
0x0440, 0x0441, 0x0444, 0x0445, 0x0450, 0x0451, 0x0454, 0x0455,
0x0500, 0x0501, 0x0504, 0x0505, 0x0510, 0x0511, 0x0514, 0x0515,
0x0540, 0x0541, 0x0544, 0x0545, 0x0550, 0x0551, 0x0554, 0x0555,
0x1000, 0x1001, 0x1004, 0x1005, 0x1010, 0x1011, 0x1014, 0x1015,
0x1040, 0x1041, 0x1044, 0x1045, 0x1050, 0x1051, 0x1054, 0x1055,
0x1100, 0x1101, 0x1104, 0x1105, 0x1110, 0x1111, 0x1114, 0x1115,
0x1140, 0x1141, 0x1144, 0x1145, 0x1150, 0x1151, 0x1154, 0x1155,
0x1400, 0x1401, 0x1404, 0x1405, 0x1410, 0x1411, 0x1414, 0x1415,
0x1440, 0x1441, 0x1444, 0x1445, 0x1450, 0x1451, 0x1454, 0x1455,
0x1500, 0x1501, 0x1504, 0x1505, 0x1510, 0x1511, 0x1514, 0x1515,
0x1540, 0x1541, 0x1544, 0x1545, 0x1550, 0x1551, 0x1554, 0x1555,
0x4000, 0x4001, 0x4004, 0x4005, 0x4010, 0x4011, 0x4014, 0x4015,
0x4040, 0x4041, 0x4044, 0x4045, 0x4050, 0x4051, 0x4054, 0x4055,
0x4100, 0x4101, 0x4104, 0x4105, 0x4110, 0x4111, 0x4114, 0x4115,
0x4140, 0x4141, 0x4144, 0x4145, 0x4150, 0x4151, 0x4154, 0x4155,
0x4400, 0x4401, 0x4404, 0x4405, 0x4410, 0x4411, 0x4414, 0x4415,
0x4440, 0x4441, 0x4444, 0x4445, 0x4450, 0x4451, 0x4454, 0x4455,
0x4500, 0x4501, 0x4504, 0x4505, 0x4510, 0x4511, 0x4514, 0x4515,
0x4540, 0x4541, 0x4544, 0x4545, 0x4550, 0x4551, 0x4554, 0x4555,
0x5000, 0x5001, 0x5004, 0x5005, 0x5010, 0x5011, 0x5014, 0x5015,
0x5040, 0x5041, 0x5044, 0x5045, 0x5050, 0x5051, 0x5054, 0x5055,
0x5100, 0x5101, 0x5104, 0x5105, 0x5110, 0x5111, 0x5114, 0x5115,
0x5140, 0x5141, 0x5144, 0x5145, 0x5150, 0x5151, 0x5154, 0x5155,
0x5400, 0x5401, 0x5404, 0x5405, 0x5410, 0x5411, 0x5414, 0x5415,
0x5440, 0x5441, 0x5444, 0x5445, 0x5450, 0x5451, 0x5454, 0x5455,
0x5500, 0x5501, 0x5504, 0x5505, 0x5510, 0x5511, 0x5514, 0x5515,
0x5540, 0x5541, 0x5544, 0x5545, 0x5550, 0x5551, 0x5554, 0x5555
};
unsigned short x; // Interleave bits of x and y, so that all of the
unsigned short y; // bits of x are in the even positions and y in the odd;
unsigned int z; // z gets the resulting 32-bit Morton Number.
z = MortonTable256[y >> 8] << 17 |
MortonTable256[x >> 8] << 16 |
MortonTable256[y & 0xFF] << 1 |
MortonTable256[x & 0xFF];
For more speed, use an additional table with values that are MortonTable256 pre-shifted one bit to the left. This second table could then be used for the y lookups, thus reducing the operations by two, but almost doubling the memory required. Extending this same idea, four tables could be used, with two of them pre-shifted by 16 to the left of the previous two, so that we would only need 11 operations total.
<a name="Interleave64bitOps">Interleave bits with 64-bit multiply</a>
In 11 operations, this version interleaves bits of two bytes (rather than shorts, as in the other versions), but many of the operations are 64-bit multiplies so it isn't appropriate for all machines. The input parameters, x and y, should be less than 256.
unsigned char x; // Interleave bits of (8-bit) x and y, so that all of the
unsigned char y; // bits of x are in the even positions and y in the odd;
unsigned short z; // z gets the resulting 16-bit Morton Number.
z = ((x * 0x0101010101010101ULL & 0x8040201008040201ULL) *
0x0102040810204081ULL >> 49) & 0x5555 |
((y * 0x0101010101010101ULL & 0x8040201008040201ULL) *
0x0102040810204081ULL >> 48) & 0xAAAA;
Holger Bettag was inspired to suggest this technique on October 10, 2004 after reading the multiply-based bit reversals here.
<a name="InterleaveBMN">Interleave bits by Binary Magic Numbers</a>
static const unsigned int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF};
static const unsigned int S[] = {1, 2, 4, 8};
unsigned int x; // Interleave lower 16 bits of x and y, so the bits of x
unsigned int y; // are in the even positions and bits from y in the odd;
unsigned int z; // z gets the resulting 32-bit Morton Number.
// x and y must initially be less than 65536.
x = (x | (x << S[3])) & B[3];
x = (x | (x << S[2])) & B[2];
x = (x | (x << S[1])) & B[1];
x = (x | (x << S[0])) & B[0];
y = (y | (y << S[3])) & B[3];
y = (y | (y << S[2])) & B[2];
y = (y | (y << S[1])) & B[1];
y = (y | (y << S[0])) & B[0];
z = x | (y << 1);
<a name="ZeroInWord">Determine if a word has a zero byte</a>
// Fewer operations:
unsigned int v; // 32-bit word to check if any 8-bit byte in it is 0
bool hasZeroByte = ~((((v & 0x7F7F7F7F) + 0x7F7F7F7F) | v) | 0x7F7F7F7F);
The code above may be useful when doing a fast string copy in which a word is copied at a time; it uses 5 operations. On the other hand, testing for a null byte in the obvious ways (which follow) have at least 7 operations (when counted in the most sparing way), and at most 12.
// More operations:
bool hasNoZeroByte = ((v & 0xff) && (v & 0xff00) && (v & 0xff0000) && (v & 0xff000000))
// OR:
unsigned char * p = (unsigned char *) &v;
bool hasNoZeroByte = *p && *(p + 1) && *(p + 2) && *(p + 3);
The code at the beginning of this section (labeled "Fewer operations") works by first zeroing the high bits of the 4 bytes in the word. Subsequently, it adds a number that will result in an overflow to the high bit of a byte if any of the low bits were initialy set. Next the high bits of the original word are ORed with these values; thus, the high bit of a byte is set iff any bit in the byte was set. Finally, we determine if any of these high bits are zero by ORing with ones everywhere except the high bits and inverting the result. Extending to 64 bits is trivial; simply increase the constants to be 0x7F7F7F7F7F7F7F7F.
For an additional improvement, a fast pretest that requires only 4 operations may be performed to determine if the word <em>may</em> have a zero byte. The test also returns true if the high byte is 0x80, so there are occasional false positives, but the slower and more reliable version above may then be used on candidates for an overall increase in speed with correct output.
bool hasZeroByte = ((v + 0x7efefeff) ^ ~v) & 0x81010100;
if (hasZeroByte) // or may just have 0x80 in the high byte
{
hasZeroByte = ~((((v & 0x7F7F7F7F) + 0x7F7F7F7F) | v) | 0x7F7F7F7F);
}
There is yet a faster method — use <a><code>hasless</code></a>(v, 1), which is defined below; it works in 4 operations and requires no subsquent verification. It simplifies to
#define haszero(v) (((v) - 0x01010101UL) & ~(v) & 0x80808080UL)
The subexpression (v - 0x01010101UL), evaluates to a high bit set in any byte whenever the corresponding byte in v is zero or greater than 0x80. The sub-expression ~v & 0x80808080UL evaluates to high bits set in bytes where the byte of v doesn't have its high bit set (so the byte was less than 0x80). Finally, by ANDing these two sub-expressions the result is the high bits set where the bytes in v were zero, since the high bits set due to a value greater than 0x80 in the first sub-expression are masked off by the second.
Paul Messmer suggested the fast pretest improvement on October 2, 2004. Juha Järvi later suggested <code>hasless(v, 1)</code> on April 6, 2005, which he found on <a>Paul Hsieh's Assembly Lab</a>; previously it was written in a newsgroup post on April 27, 1987 by Alan Mycroft.
<a name="ValueInWord">Determine if a word has a byte equal to n</a>
We may want to know if any byte in a word has a specific value. To do so, we can XOR the value to test with a word that has been filled with the byte values in which we're interested. Because XORing a value with itself results in a zero byte and nonzero otherwise, we can pass the result to <code>haszero</code>.
#define hasvalue(x,n) \
(haszero((x) ^ (~0UL/255 * (n))))
Stephen M Bennet suggested this on December 13, 2009 after reading the entry for <code>haszero</code>.
<a name="HasLessInWord">Determine if a word has a byte less than n</a>
Test if a word x contains an unsigned byte with value < n. Specifically for n=1, it can be used to find a 0-byte by examining one long at a time, or any byte by XORing x with a mask first. Uses 4 arithmetic/logical operations when n is constant.
Requirements: x>=0; 0<=n<=128
#define hasless(x,n) (((x)-~0UL/255*(n))&~(x)&~0UL/255*128)
To count the number of bytes in x that are less than n in 7 operations, use
#define countless(x,n) \
(((~0UL/255*(127+(n))-((x)&~0UL/255*127))&~(x)&~0UL/255*128)/128%255)
Juha Järvi sent this clever technique to me on April 6, 2005. The <code>countless</code> macro was added by Sean Anderson on April 10, 2005, inspired by Juha's <code>countmore</code>, below.
<a name="HasMoreInWord">Determine if a word has a byte greater than n</a>
Test if a word x contains an unsigned byte with value > n. Uses 3 arithmetic/logical operations when n is constant.
Requirements: x>=0; 0<=n<=127
#define hasmore(x,n) (((x)+~0UL/255*(127-(n))|(x))&~0UL/255*128)
To count the number of bytes in x that are more than n in 6 operations, use:
#define countmore(x,n) \
(((((x)&~0UL/255*127)+~0UL/255*(127-(n))|(x))&~0UL/255*128)/128%255)
The macro <code>hasmore</code> was suggested by Juha Järvi on April 6, 2005, and he added <code>countmore</code> on April 8, 2005.
<a name="HasBetweenInWord">Determine if a word has a byte between m and n</a>
When m < n, this technique tests if a word x contains an unsigned byte value, such that m < value < n. It uses 7 arithmetic/logical operations when n and m are constant.
Note: Bytes that equal n can be reported by <code>likelyhasbetween</code> as false positives, so this should be checked by character if a certain result is needed.
Requirements: x>=0; 0<=m<=127; 0<=n<=128
#define likelyhasbetween(x,m,n) \
((((x)-~0UL/255*(n))&~(x)&((x)&~0UL/255*127)+~0UL/255*(127-(m)))&~0UL/255*128)
This technique would be suitable for a fast pretest. A variation that takes one more operation (8 total for constant m and n) but provides the exact answer is:
#define hasbetween(x,m,n) \
((~0UL/255*(127+(n))-((x)&~0UL/255*127)&~(x)&((x)&~0UL/255*127)+~0UL/255*(127-(m)))&~0UL/255*128)
To count the number of bytes in x that are between m and n (exclusive) in 10 operations, use:
#define countbetween(x,m,n) (hasbetween(x,m,n)/128%255)
Juha Järvi suggested <code>likelyhasbetween</code> on April 6, 2005. From there, Sean Anderson created <code>hasbetween</code> and <code>countbetween</code> on April 10, 2005.
<a name="NextBitPermutation">Compute the lexicographically next bit permutation</a>
Suppose we have a pattern of N bits set to 1 in an integer and we want the next permutation of N 1 bits in a lexicographical sense. For example, if N is 3 and the bit pattern is 00010011, the next patterns would be 00010101, 00010110, 00011001,00011010, 00011100, 00100011, and so forth. The following is a fast way to compute the next permutation.
unsigned int v; // current permutation of bits
unsigned int w; // next permutation of bits
unsigned int t = v | (v - 1); // t gets v's least significant 0 bits set to 1
// Next set to 1 the most significant bit to change,
// set to 0 the least significant ones, and add the necessary 1 bits.
w = (t + 1) | (((~t & -~t) - 1) >> (__builtin_ctz(v) + 1));
The __builtin_ctz(v) GNU C compiler intrinsic for x86 CPUs returns the number of trailing zeros. If you are using Microsoft compilers for x86, the intrinsic is _BitScanForward. These both emit a bsf instruction, but equivalents may be available for other architectures. If not, then consider using one of the methods for counting the consecutive zero bits mentioned earlier.
Here is another version that tends to be slower because of its division operator, but it does not require counting the trailing zeros.
unsigned int t = (v | (v - 1)) + 1;
w = t | ((((t & -t) / (v & -v)) >> 1) - 1);
Thanks to Dario Sneidermanis of Argentina, who provided this on November 28, 2009.
<a>A Belorussian translation</a> (provided by <a>Webhostingrating</a>) is available. | []
|
https://avatars.githubusercontent.com/u/25558240?v=4 | zig-by-example | ibokuri/zig-by-example | 2022-01-25T05:09:10Z | Zig by Example | main | 0 | 76 | 14 | 76 | https://api.github.com/repos/ibokuri/zig-by-example/tags | NOASSERTION | [
"zig"
]
| 6,806 | false | 2025-04-22T19:27:19Z | false | false | unknown | github | []
| Zig by Example
Content and build toolchain for <em><a>Zig by Example</a></em>.
Building
To build the site:
<code>sh
tools/build</code>
To build the site continuously in a loop:
<code>sh
tools/build-loop</code>
To serve the site locally:
<code>sh
tools/serve</code>
License
This work is a derivative of "Go by Example" by <a>Mark McGranaghan</a>, used under <a>CC BY 3.0</a>.
This work is licensed under <a>CC BY 3.0</a> by Jason Phan. | []
|
https://avatars.githubusercontent.com/u/3932972?v=4 | parser-toolkit | ikskuh/parser-toolkit | 2021-08-19T09:09:46Z | A toolkit that makes it easier to write recursive-descent parsers in Zig. | master | 1 | 75 | 8 | 75 | https://api.github.com/repos/ikskuh/parser-toolkit/tags | MIT | [
"compiler",
"compiler-frontend",
"parser",
"recursive-descent-parser",
"tokenizer",
"tokenizer-parser",
"zig",
"zig-package",
"ziglang"
]
| 1,146 | false | 2025-04-30T17:25:13Z | true | true | unknown | github | []
| A parser toolkit
This repo contains a tiny parser toolkit that can be used to build new parsers and programming languages.
It provides:
<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> Configurable tokenizer
<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> Parser core (accept functions with state restoration)
<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> Compiler error management (emission, rendering, source locations)
Demo
Invoke <code>zig build run</code> to run a tiny command line calculator that can evaluate basic expressions, parens and invoke functions:
<code>$ zig build run
? 10
= 10
? 10 + 10
= 20
? 5 * 3
= 15
? a = 10
= 10
? sqrt(a)
= 3.1622776601683795
? sin(3.14)
= 0.0015926529164868282
? a = a + 1
= 11
? a = a + 1
= 12
? ^D</code>
Available functions are:
<code>zig
fn sin(v: f64) f64
fn cos(v: f64) f64
fn tan(v: f64) f64
fn sqrt(v: f64) f64
fn pow(a: f64, b: f64) f64
fn ln(v: f64) f64
fn ln10(v: f64) f64
fn ln2(v: f64) f64
fn log(b: f64, v: f64) f64</code> | [
"https://github.com/MidstallSoftware/webidl.zig",
"https://github.com/iddev5/inon"
]
|
https://avatars.githubusercontent.com/u/70155278?v=4 | napi.zig | evanwashere/napi.zig | 2022-01-23T10:57:43Z | tiny and fast napi bindings for zig | master | 0 | 74 | 2 | 74 | https://api.github.com/repos/evanwashere/napi.zig/tags | MIT | [
"bindings",
"napi",
"zig"
]
| 458 | false | 2025-05-20T20:36:54Z | false | false | unknown | github | []
| napi.zig
tiny and fast node-api bindings for zig
Features
<ul>
<li>🚀 async functions run in parallel</li>
<li>⛓️ expose c and zig functions to js</li>
<li>🔨 does not require node-gyp to build</li>
<li>[WIP] ✨ seamless serde between js and zig types</li>
<li>🎯 compile to any architecture with zig cross-compilation</li>
</ul>
Examples
<ul>
<li><a>print</a></li>
<li><a>sleep</a></li>
<li><a>base64</a></li>
</ul>
<em>more examples in <a>examples/</a> folder</em>
```zig
const std = @import("std");
const napi = @import("./src/napi.zig");
const allocator = std.heap.c_allocator;
comptime {
napi.register(init);
}
fn init(env: napi.env, exports: napi.object) !void {
try exports.set(env, "add", try napi.bind.function(env, add, "add", allocator));
}
fn add(a: u32, b: u32) u32 {
return a + b;
}
```
License
MIT © <a>Evan</a> | []
|
https://avatars.githubusercontent.com/u/63465728?v=4 | zort | alichraghi/zort | 2021-11-09T13:30:26Z | Sorting algorithms in zig | main | 2 | 70 | 6 | 70 | https://api.github.com/repos/alichraghi/zort/tags | MIT | [
"sort",
"sorting",
"sorting-algorithms",
"sorting-algorithms-implemented",
"zig",
"zig-package"
]
| 2,606 | false | 2025-04-19T10:51:10Z | true | false | unknown | github | []
| Zort
Implementation of 13 sorting algorithms in Zig
| Algorithm | Custom Comparison | Zero Allocation |
| ----------------------- | ----------------- | --------------- |
| Bubble | ✅ | ✅ |
| Comb | ✅ | ✅ |
| Heap | ✅ | ✅ |
| Insertion | ✅ | ✅ |
| Merge | ✅ | ❌ |
| PDQ | ✅ | ✅ |
| Quick | ✅ | ✅ |
| Radix (no negative yet) | ❌ | ❌ |
| Selection | ✅ | ✅ |
| Shell | ✅ | ✅ |
| Tail | ✅ | ❌ |
| Tim | ✅ | ❌ |
| Twin | ✅ | ❌ |
Usage
```zig
const zort = @import("zort");
fn asc(a: u8, b: u8) bool {
return a < b;
}
pub fn main() !void {
var arr = [_]u8{ 9, 1, 4, 12, 3, 4 };
try zort.quickSort(u8, &arr, asc);
}
```
Benchmarks
run this to see results on your machine:
<code>zig build bench -Doptimize=ReleaseFast -- comb quick radix shell std_block std_heap std_pdq tail tim twin</code>
12th Gen Intel(R) Core(TM) i5-12400F
<code>mermaid
gantt
title Sorting (ascending) 10000000 usize
dateFormat x
axisFormat %S s
section random
quick 1.670: 0,1670
comb 3.156: 0,3155
shell 5.469: 0,5467
radix 0.304: 0,304
tim 2.893: 0,2893
tail 2.400: 0,2399
twin 2.377: 0,2377
std_block 3.371: 0,3372
std_pdq 2.250: 0,2250
std_heap 5.512: 0,5514
section sorted
quick 0.829: 0,829
comb 1.179: 0,1179
shell 0.740: 0,740
radix 0.301: 0,301
tim 0.025: 0,25
tail 0.058: 0,58
twin 0.071: 0,71
std_block 0.266: 0,266
std_pdq 0.041: 0,41
std_heap 3.912: 0,3913
section reverse
quick 1.544: 0,1544
comb 1.375: 0,1375
shell 1.378: 0,1378
radix 0.303: 0,303
tim 0.822: 0,822
tail 1.364: 0,1364
twin 1.280: 0,1280
std_block 1.304: 0,1304
std_pdq 0.199: 0,199
std_heap 3.844: 0,3845
section ascending saw
quick 2.979: 0,2978
comb 2.088: 0,2089
shell 1.807: 0,1807
radix 0.322: 0,322
tim 0.473: 0,473
tail 0.486: 0,486
twin 0.465: 0,465
std_block 1.129: 0,1129
std_pdq 1.604: 0,1604
std_heap 4.246: 0,4249
section descending saw
comb 1.949: 0,1949
shell 1.694: 0,1694
radix 0.299: 0,299
tim 1.339: 0,1339
tail 1.478: 0,1478
twin 1.288: 0,1288
std_block 1.618: 0,1618
std_pdq 1.613: 0,1613
std_heap 4.262: 0,4261</code>
<code>mermaid
gantt
title Sorting (ascending) 10000000 isize
dateFormat x
axisFormat %S s
section random
quick 1.691: 0,1691
comb 3.084: 0,3084
shell 5.410: 0,5413
radix 0.332: 0,332
tim 2.951: 0,2953
tail 2.414: 0,2414
twin 2.414: 0,2414
std_block 3.346: 0,3346
std_pdq 2.309: 0,2309
std_heap 5.449: 0,5447
section sorted
quick 0.798: 0,798
comb 1.166: 0,1166
shell 0.739: 0,739
radix 0.247: 0,247
tim 0.025: 0,25
tail 0.059: 0,59
twin 0.048: 0,48
std_block 0.270: 0,270
std_pdq 0.039: 0,39
std_heap 3.816: 0,3815
section reverse
quick 1.581: 0,1581
comb 1.347: 0,1347
shell 1.234: 0,1234
radix 0.262: 0,262
tim 0.044: 0,44
tail 1.396: 0,1396
twin 0.041: 0,41
std_block 0.953: 0,953
std_pdq 0.204: 0,204
std_heap 3.713: 0,3713
section ascending saw
quick 5.516: 0,5516
comb 2.064: 0,2064
shell 1.632: 0,1632
radix 0.280: 0,280
tim 0.449: 0,449
tail 0.466: 0,466
twin 0.478: 0,478
std_block 1.157: 0,1157
std_pdq 1.618: 0,1618
std_heap 4.281: 0,4279
section descending saw
comb 2.039: 0,2040
shell 1.644: 0,1644
radix 0.279: 0,279
tim 0.465: 0,465
tail 1.492: 0,1492
twin 0.481: 0,481
std_block 1.596: 0,1596
std_pdq 1.576: 0,1576
std_heap 4.199: 0,4199</code>
Big Thank to
<a>voroskoi</a> and other contributors | []
|
https://avatars.githubusercontent.com/u/1458409?v=4 | zigish | ratfactor/zigish | 2021-06-05T18:55:34Z | A toy Unix shell written in Zig | main | 2 | 66 | 8 | 66 | https://api.github.com/repos/ratfactor/zigish/tags | MIT | [
"shell",
"unix-shell",
"zig",
"ziglang"
]
| 8 | false | 2025-03-17T04:14:59Z | true | false | unknown | github | []
| 404 | []
|
https://avatars.githubusercontent.com/u/2528778?v=4 | zig-stm32-blink | rbino/zig-stm32-blink | 2021-04-05T21:43:40Z | Use Zig to blink some LEDs | master | 1 | 65 | 9 | 65 | https://api.github.com/repos/rbino/zig-stm32-blink/tags | MIT | [
"embedded",
"stm32",
"stm32f4-discovery",
"zig"
]
| 145 | false | 2025-05-13T12:28:21Z | true | false | unknown | github | []
| Zig STM32 Blink
Make LEDs blink on an STM32F4 Discovery board using only Zig (and a linker script).
See <a>my blogpost</a> for a more thorough explanation of
what's going on.
Build
The code was tested with Zig <code>0.9.0</code>.
To build the ELF file just run:
<code>zig build</code>
Flashing
The easiest way to flash the board is to install <a><code>stlink</code>
tools</a>. Most Linux distributions should have them in their
repos, the build system will try to use the <code>st-flash</code> program.
The command to flash the board is:
<code>zig build flash</code>
After flashing the board you should see the 4 LEDs blinking in an alternating pattern.
Debugging
It's possible to use <a><code>openocd</code></a> and <code>gdb-multiarch</code> to debug the firmware
directly on the board.
In a terminal run:
<code>openocd -f board/stm32f4discovery.cfg</code>
Then from another terminal navigate to the directory containing the ELF output (i.e.
<code>zig-out/bin</code>) and run:
<code>gdb-multiarch zig-stm32-blink.elf -ex "target remote :3333"</code>
You can also manually flash the firmware inside <code>gdb</code> with:
<code>load</code>
Emulation using <code>qemu</code>
If you don't have an STM32F4 Discovery board or you just want to test the code locally, you can use
<a>xPack QEMU Arm</a>.
<em>Note</em>: you have to comment out <a>this
line</a> to make the code work
in QEMU since it doesn't support the FPU coprocessor yet.
After that, you can emulate the board with:
<code>qemu-system-gnuarmeclipse -machine STM32F4-Discovery -mcu STM32F407VG \
-kernel zig-out/bin/zig-stm32-blink.elf -gdb tcp::3333</code>
You should see the blinking LEDs on the board image, and you can connect a <code>gdb</code> instance to it (see
the previous section). | []
|
https://avatars.githubusercontent.com/u/755611?v=4 | notcurses-zig-example | dundalek/notcurses-zig-example | 2021-04-11T19:34:51Z | Demo showing how to use Notcurses library for building terminal UIs with Zig | master | 2 | 63 | 3 | 63 | https://api.github.com/repos/dundalek/notcurses-zig-example/tags | Unlicense | [
"liz",
"notcurses",
"terminal",
"tui",
"zig"
]
| 45 | false | 2025-05-03T19:12:23Z | true | false | unknown | github | []
| Notcurses Zig example
<a>Notcurses</a> is a moderm library for building terminal UIs with advanced graphics support.
This is a demo showing how to use it with <a>Zig</a> programming language.
Thanks to Zig's seamless C interop the library can be used directly without wrapper bindings.
Dependencies
<ul>
<li>Install <a>Notcurses dependencies</a></li>
<li>using <a>Nix</a>:
<code>nix-shell</code></li>
<li>for Debian/Ubuntu:
<code>sudo apt-get install build-essential cmake libncurses-dev libreadline-dev libunistring-dev libqrcodegen-dev zlib1g-dev</code></li>
<li><a>Install Zig</a> (version 0.11.0)</li>
<li>Get Notcurses to compile from sources (since distributions don't often package latest versions):
```sh
git clone https://github.com/dankamongmen/notcurses.git deps/notcurses
cd deps/notcurses
mkdir build && cd build
cmake -DUSE_MULTIMEDIA=none -DUSE_PANDOC=OFF ..</li>
</ul>
We just need <code>cmake</code> to generate some headers, no need to actually <code>make</code> since rest will be handled by Zig
In case of errors, try <code>git checkout v3.0.9</code> and re-run cmake as I tested it with this version.
```
Build and run
Build and run the demo:
<code>sh
zig build run</code>
Or build and run the binary separately:
<code>sh
zig build
./zig-cache/run/demo</code>
Liz source
The source of this demo is actually written in <a>Liz</a>, which is Zig dialect with <a>lispy syntax</a> that transpiles down to Zig code. If you feel adventurous to explore land of parentheses you can <a>download Liz</a> and compile sources with:
<code>sh
liz src/*.liz && zig build</code>
Related
See also the demo implemented in <a>Clojure</a>. | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-extras | nektro/zig-extras | 2021-08-27T02:57:51Z | An assortment of random utility functions that aren't in std and don't need to be their own pacakge. | master | 3 | 63 | 9 | 63 | https://api.github.com/repos/nektro/zig-extras/tags | MIT | [
"zig",
"zig-package"
]
| 119 | false | 2025-05-21T20:33:46Z | true | false | unknown | github | []
| zig-extras
<a></a>
<a></a>
<a></a>
<a></a>
An assortment of random utility functions that aren't in std and don't deserve their own package. | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-time | nektro/zig-time | 2021-10-17T00:34:25Z | A date and time parsing and formatting library for Zig. | master | 1 | 60 | 11 | 60 | https://api.github.com/repos/nektro/zig-time/tags | MIT | [
"time",
"wristwatch",
"zig",
"zig-package"
]
| 36 | false | 2025-05-21T20:33:48Z | true | false | unknown | github | []
| zig-time
<a></a>
<a></a>
<a></a>
<a></a>
Exposes a <code>DateTime</code> structure that can be initialized and acted upon using various methods. All public methods return a new structure.
Currently handles dates and times based on the <a>Proleptic Gregorian calendar</a> in adherence to <a>ISO 8601</a>.
Does not currently support time zones outside of UTC.
Does not handle leap seconds.
See the <code>FormatSeq</code> structure for display information on what to pass as a <code>fmt</code> string. | []
|
https://avatars.githubusercontent.com/u/20167110?v=4 | jzignet | greenfork/jzignet | 2021-11-20T14:06:55Z | Zig library to connect Janet and Zig together | master | 0 | 56 | 4 | 56 | https://api.github.com/repos/greenfork/jzignet/tags | MIT | [
"janet",
"zig",
"zig-package"
]
| 3,540 | false | 2025-05-20T16:17:09Z | true | false | unknown | github | []
| Jzignet
<a>Zig</a> is a general-purpose programming language and
toolchain for maintaining robust, optimal, and reusable software.
<a>Janet</a> is a functional and imperative programming
language and bytecode interpreter. It is a lisp-like language, but lists are
replaced by other data structures (arrays, tables (hash table), struct
(immutable hash table), tuples). The language also supports bridging to native
code written in C, meta-programming with macros, and bytecode assembly.
<a>Jzignet</a> - Zig library to connect Janet
and Zig together.
You can:
* Embed Janet programs into Zig
* Write Janet modules in Zig
* Write bindings in Zig for a C library to be used as a Janet module
Why use these bindings, besides obvious reasons such as connecting together two
wonderful languages:
* You don't need to care about conversion between Zig and C. But you have full
access to C internals if you need to.
* Plenty of tests which are great examples and guarantee minimal regressions
when updating.
* Idiomatic Zig code - everything is typed, names are properly cased,
operations on types use methods instead of prefixed global functions.
Currently supported versions:
* Zig 0.13.0
* Janet 1.37.1
Repository is available at <a>sourcehut</a>
and at <a>GitHub</a>.
How to use
If you want to just start using it, jump to the examples. Copy them or look
at the source code, it is heavily commented.
<ul>
<li><a>Embed Janet into Zig</a> --
run this example with <code>zig build run-embed_janet</code>.
For a more in-depth overview of this use case you can take a look at
@iacore's <a>blog post</a>
as well as the <a>example repository</a>.</li>
</ul>
WARNING: examples are currently <strong>not working</strong>:
<ul>
<li><a>Write Janet module in Zig</a> -- the template is broken
and needs some investigation on how to fix it.</li>
</ul>
Write bindings in Zig for a C library to be used as a Janet module - this
is very close to "Write Janet module in Zig" example, you just need to
know how to wrap a C library in Zig, this repository is a perfect example
for this.
How to include as a dependency (with zon)
<ol>
<li>Create a file named <code>build.zig.zon</code> with the following content. Put the
correct version for tar archive, and change the <code>.hash</code> value when you get
and error.</li>
</ol>
<code>zig
.{
.name = "janet-zig-test",
.version = "0.0.1",
.dependencies = .{
.jzignet = .{
.url = "https://git.sr.ht/~greenfork/jzignet/archive/0.7.2.tar.gz",
.hash = "122087fa45b016bd8ce5fbadd17ef2bd84cd1389119edd3c345486870032ea2b7217",
},
},
}</code>
<ol>
<li>Add this to <code>build.zig</code>.</li>
</ol>
```zig
const jzignet = b.dependency("jzignet", .{ .target=target, .optimize=optimize });
<code>// your executable defined here
// const exe = ...;
exe.addModule("jzignet", jzignet.module("jzignet"));
exe.linkLibrary(jzignet.artifact("jzignet"));
</code>
```
<ol>
<li>Use in your Zig code</li>
</ol>
<code>zig
const jzignet = @import("jzignet");</code>
How to include as a dependency (with git submodule)
Currently you can include jzignet as a git submodule. Janet is bundled as
a single C source amalgamation file and is compiled directly into this
library.
<ol>
<li>Include git submodule into your library, assuming further that <code>libpath</code> is
the directory where this library is installed</li>
</ol>
<code>shell
git submodule add https://github.com/greenfork/jzignet libpath</code>
<ol>
<li>Include the library in <code>build.zig</code></li>
</ol>
```zig
const jzignet = b.anonymousDependency("lib/jzignet", @import("lib/jzignet/build.zig"), .{});
<code>// your executable defined here
// const exe = ...;
exe.addModule("jzignet", jzignet.module("jzignet"));
exe.linkLibrary(jzignet.artifact("jzignet"));
</code>
```
<ol>
<li>Use in your Zig code</li>
</ol>
<code>zig
const jzignet = @import("jzignet");</code>
Differences with C API
Naming
<ul>
<li><code>janet_</code> prefix is mostly not present.</li>
<li>Every type is a Zig struct and corresponding functions are called as
methods, for example, <code>janet_table_get(table, key)</code> becomes <code>table.get(key)</code>.</li>
<li><strong>All</strong> bindings have idiomatic Zig naming even when Janet uses different
ones, for example <code>arity</code> and <code>fixarity</code> are <code>arity</code> and <code>fixArity</code> in Zig.</li>
<li>Functions like <code>janet_table</code> are available as <code>Table.init</code>, please consult
the source code for that.</li>
</ul>
Semantics
<ul>
<li>Function return types return error sets as well as optional values where it
makes sense to do so, for example, <code>table.get</code> returns <code>?Janet</code> and <code>pcall</code>
returns <code>Signal.Error!void</code>.</li>
<li>All types are wrapped into structs. Most of the types support this natively
since they are structs in C too, others (Tuple, Struct, String, Keyword,
Symbol) cannot be represented as structs directly and they are wrappers
with a <code>ptr</code> or <code>slice</code> field containing the original value.</li>
<li>All functions that have a type at the end, for example, <code>janet_get_number</code>,
instead use this signature: <code>get(comptime T: type, ...)</code>. Currently these
functions exist: <code>get</code>, <code>opt</code>, <code>wrap</code>, <code>Janet.unwrap</code>.</li>
<li>When you need to supply a pointer to the array and a length in the C version,
in Zig version you need to supply just a slice since it has both the pointer
and the length, so it's one parameter instead of two. For example,
<code>c
int janet_dobytes(JanetTable *env, const uint8_t *bytes, int32_t len, const char *sourcePath, Janet *out);</code></li>
</ul>
becomes
<code>zig
pub fn doBytes(env: *Environment, bytes: []const u8, source_path: [:0]const u8) !Janet</code>
* Abstracts are fully typed, no *void pointers to @ptrCast. Take a look at
tests for examples with abstracts, they are generally reworked to make
them easier to use.
* All functions returning <code>Signal</code> instead return <code>void</code> on <code>OK</code> and return
error otherwise with the specified signal, signature is <code>Signal.Error!void</code>.
* <code>doString</code> and <code>doBytes</code> are aliases and return <code>!Janet</code> directly instead of
accepting a reference for the return value.
* <code>string</code>, <code>keyword</code>, <code>symbol</code>, <code>nil</code> top-level functions are the only ones to
create these types and they do what you want.
* <code>Environment</code> type introduced which is internally a <code>Table</code> but allows
conceptually different operations such as defining values and executing code.
Completeness
Bindings are not complete 100% but all the generally useful things are there.
If you need any specific part of the API, feel free to contribute or just
ask (and you shall receive).
Q'n'A
Q: What's with the name?
A: "janet".replace("a", "zig")
Q: I hate that name.
A: Yes, I know.
License
MIT, see LICENSE file. | []
|
https://avatars.githubusercontent.com/u/1916079?v=4 | zig-prometheus | vrischmann/zig-prometheus | 2021-07-30T21:29:04Z | Prometheus/VictoriaMetrics client library for Zig | master | 0 | 55 | 2 | 55 | https://api.github.com/repos/vrischmann/zig-prometheus/tags | MIT | [
"prometheus",
"victoriametrics",
"zig",
"zig-package"
]
| 79 | false | 2025-05-01T14:02:27Z | true | true | 0.14.0 | github | []
| zig-prometheus
This is a <a>Zig</a> library to add <a>Prometheus</a>-inspired metrics to a library or application.
"Inspired" because it is not strictly compatible with Prometheus, the <code>Histogram</code> type is tailored for <a>VictoriaMetrics</a>.
See <a>this blog post</a> from the creator of <code>VictoriaMetrics</code> for details.
Requirements
<a>Zig master</a> is the only required dependency.
Introduction
This library only provides the following types:
* A <code>Registry</code> holding a number of metrics
* A <code>Counter</code> metric type
* A <code>Gauge</code> metric type
* A <code>Histogram</code> metric type
Examples
If you want a quick overview of how to use this library check the <a>basic example program</a>. It showcases everything.
Reference
Registry
The <code>Registry</code> is the entry point to obtain a metric type, as well as the type capable of serializing the metrics to a writer.
In an application it might be useful to have a default, global registry; in a library you probably should take one as a parameter.
Creation
Here is how to get a registry:
<code>zig
var registry = try prometheus.Registry(.{}).create(allocator);
defer registry.destroy();
...</code>
You can also configure some options for the registry:
<code>zig
var registry = try prometheus.Registry(.{ .max_metrics = 40, .max_name_len = 300 }).create(allocator);
defer registry.destroy();
...</code>
If you want to store the registry in a variable you probably want to do something like this:
<code>zig
const Registry = prometheus.Registry(.{ .max_metrics = 40, .max_name_len = 300 });
var registry = Registry.create(allocator);
defer registry.destroy();
...</code>
Now you can get metric objects which we will describe later.
Serializing the metrics
Once you have a registry you can serialize its metrics to a writer:
```zig
var registry = try prometheus.Registry(.{}).create(allocator);
defer registry.destroy();
...
var file = try std.fs.cwd().createFile("metrics.txt", .{});
defer file.close();
try registry.write(allocator, file.writer());
```
The <code>write</code> method is thread safe.
Counter
The <code>Counter</code> type is an atomic integer counter.
Here is an example of how to use a counter:
```zig
var registry = try prometheus.Registry(.{}).create(allocator);
defer registry.destroy();
var total_counter = try registry.getOrCreateCounter("http_requests_total");
var api_users_counter = try registry.getOrCreateCounter(
\http_requests{route="/api/v1/users"}
);
var api_articles_counter = try registry.getOrCreateCounter(
\http_requests{route="/api/v1/articles"}
);
total_counter.inc();
total_counter.dec();
total_counter.add(200);
total_counter.set(2400);
const counter_value = total_counter.get();
```
All methods on a <code>Counter</code> are thread safe.
Gauge
The <code>Gauge</code> type represents a numerical value that is provided by calling a user-supplied function.
A <code>Gauge</code> is created with a <em>state</em> and a <em>function</em> which is given that state every time it is called.
For example, you can imagine a gauge returning the number of connections in a connection pool, the amount of memory allocated, etc.
Basically anytime the value is instantly queryable it could be a gauge.
Of course, nothing stops you from using a counter to simulate a gauge and calling <code>set</code> on it; it's up to you.
Here is an example gauge:
```zig
var registry = try prometheus.Registry(.{}).create(allocator);
defer registry.destroy();
const Conn = struct {};
const ConnPool = struct {
conns: std.ArrayList(Conn),
};
var pool = ConnPool{ .conns = std.ArrayList.init(allocator) };
_ = try registry.getOrCreateGauge(
"http_conn_pool_size",
&pool,
struct {
fn get(p: *Pool) f64 {
return @intToFloat(f64, p.conns.items.len);
}
}.get,
);
```
Histogram
The <code>Histogram</code> type samples observations and counts them in automatically created buckets.
It can be used to observe things like request duration, request size, etc.
Here is a (contrived) example on how to use an histogram:
```zig
var registry = try prometheus.Registry(.{}).create(allocator);
defer registry.destroy();
var request_duration_histogram = try registry.getOrCreateHistogram("http_request_duration");
// Make 100 observations of some expensive operation.
var i: usize = 0;
while (i < 100) : (i += 1) {
const start = std.time.milliTimestamp();
<code>var j: usize = 0;
var sum: usize = 0;
while (j < 2000000) : (j += 1) {
sum *= j;
}
request_duration_histogram.update(@intToFloat(f64, std.time.milliTimestamp() - start));
</code>
}
```
Using labels
If you're read the <a>Prometheus data model</a>, you've seen that a metric can have labels.
Other Prometheus clients provide helpers for this, but not this library: you need to build the proper name yourself.
If you have static labels then it's easy, just write the label directly like this:
<code>zig
var http_requests_route_home = try registry.getOrCreateCounter(
\\http_requests{route="/home"}
);
var http_requests_route_login = try registry.getOrCreateCounter(
\\http_requests{route="/login"}
);
var http_requests_route_logout = try registry.getOrCreateCounter(
\\http_requests{route="/logout"}
);
...</code>
If you have dynamic labels you could write a helper function like this:
```zig
fn getHTTPRequestsCounter(
allocator: <em>mem.Allocator,
registry: </em>Registry,
route: []const u8,
) !*prometheus.Counter {
const name = try std.fmt.allocPrint(allocator, "http_requests{{route=\"{s}\"}}", .{
route,
});
return try registry.getOrCreateCounter(name);
}
fn handler(route: []const u8) void {
var counter = getHTTPRequestsCounter(allocator, registry, route);
counter.inc();
}
``` | []
|
https://avatars.githubusercontent.com/u/1699414?v=4 | kc85.zig | floooh/kc85.zig | 2021-07-02T17:55:53Z | A KC85 emulator written in Zig | main | 0 | 55 | 4 | 55 | https://api.github.com/repos/floooh/kc85.zig/tags | MIT | [
"sokol",
"zig"
]
| 1,608 | false | 2025-02-04T17:38:03Z | true | true | unknown | github | [
{
"commit": "afd2c467a6049f89edd7282749478c9bc2b57078",
"name": "sokol",
"tar_url": "https://github.com/floooh/sokol-zig/archive/afd2c467a6049f89edd7282749478c9bc2b57078.tar.gz",
"type": "remote",
"url": "https://github.com/floooh/sokol-zig"
}
]
| <blockquote>
NOTE: this project has been superseded by https://github.com/floooh/chipz and has been archived
</blockquote>
<a></a>
A simple KC85/2, /3 and /4 emulator for Windows, macOS and Linux, written in Zig. Uses the <a>sokol headers</a> for platform abstraction.
Read more about the KC85 computer series here:
<ul>
<li>https://en.wikipedia.org/wiki/KC_85</li>
<li>https://floooh.github.io/virtualkc/p010_kc85.html</li>
<li>https://floooh.github.io/2017/01/14/yakc-diamond-scroll.html</li>
</ul>
Some <a>implementation notes</a>.
Build
With Zig the 0.12.0 dev version, on Windows, macOS or Linux:
<code>zig build</code>
The default debug version will usually be fast enough. To build with optimizations use any of:
<code>zig build --release=fast
zig build --release=small
zig build --release=safe</code>
NOTE: On Linux you also need to install the ALSA, X11 and GL development packages.
Build and start into KC85/2, /3 and /4
<code>zig build run-kc852
zig build run-kc853
zig build run-kc854</code>
Run <code>zig build --help</code> to see the remaining build targets.
<blockquote>
NOTE: when running any of the games, turn down your sound volume first. The raw square-wave sound can be a bit "aggressive". You have been warned ;)
</blockquote>
Run Digger
<code>zig build run-kc853 -- -slot8 m022 -file data/digger3.tap</code>
Press [Enter] to start a new game round, and [Esc] to continue
after you died. Use the arrows keys to navigate.
Run Jungle
<code>zig build run-kc853 -- -slot8 m022 -file data/jungle.kcc</code>
Navigate with arrow keys, jump with [Space].
Run Pengo
<code>zig build run-kc853 -- -file data/pengo.kcc</code>
Navigate with the arrow keys, continue running against
an ice block to push or destroy the block.
Run FORTH on the KC85/4
<code>zig build run-kc854 -- -slot8 m026 data/forth.853</code>
On the KC85/4's command line, first activate the module,
and then start Forth:
<code>switch 8 c1[Enter]
forth[Enter]</code>
(the characters will appear uppercase, don't worry, that's normal)
Run in web browsers
Currently only running the 'plain' emulator is supported, it's not possible
to load files into the emulator (because command line parsing doesn't work
in browsers, and the Zig stdlib filesystem code doesn't work in
<code>wasm32-emscripten</code>):
<code>bash
zig build -Dtarget=wasm32-emscripten --release=fast run-kc854</code>
On the first build, the Emscripten SDK will be downloaded and installed into
the global Zig cache, this might take a couple of minutes.
Misc Stuff
For an instant nostalgia kick, start the KC85/4:
<code>zig build run-kc854</code>
...and then type this into the KC85/4 command line.
Make sure your audio volume isn't silent, but <strong>don't</strong> turn it up <em>too</em> much!
<code>save f000 f800[Enter]</code>
...type anything for the name, and hit Enter again :D | []
|
https://avatars.githubusercontent.com/u/473672?v=4 | zig-gorillas | fabioarnold/zig-gorillas | 2021-03-02T22:53:02Z | A clone of the classic QBasic Gorillas written in the Zig programming language | master | 2 | 54 | 2 | 54 | https://api.github.com/repos/fabioarnold/zig-gorillas/tags | MIT | [
"game",
"zig"
]
| 2,253 | false | 2024-11-04T04:47:52Z | true | false | unknown | github | []
| ⚡ Zig Gorillas 🦍
A clone of the classic <a>QBasic Gorillas</a> written in the <a>Zig programming language</a>.
Take turns in throwing an exploding banana at each other. Specify angle and velocity of your throw while taking the blowing wind into consideration.
Download
<ul>
<li><a>Windows (64 Bit)</a></li>
</ul>
Building from source
Requirements
<ul>
<li>A current master build of the <a>Zig compiler</a></li>
<li>Only on Windows: <a>vcpkg package manager</a> to install ...</li>
<li>The <a>SDL2 library</a></li>
</ul>
Build and run
<code>$ zig build run</code>
Credits
<ul>
<li><a>nanovg library</a> by Mikko Mononen</li>
<li><a>Press Start 2P font</a> by codeman38</li>
</ul>
License
Zig Gorillas is licensed under the MIT License, see <a>LICENSE.txt</a> for more information. | []
|
https://avatars.githubusercontent.com/u/84904715?v=4 | wasmer-zig | zigwasm/wasmer-zig | 2021-05-25T14:29:51Z | Zig bindings for the Wasmer WebAssembly runtime | main | 1 | 53 | 6 | 53 | https://api.github.com/repos/zigwasm/wasmer-zig/tags | MIT | [
"wasi",
"wasm",
"wasmer",
"zig",
"zig-library"
]
| 852 | false | 2024-09-19T11:52:59Z | true | false | unknown | github | []
| wasmer-zig
Zig bindings for the <a>Wasmer</a> WebAssembly runtime.
Disclaimer
This is a work-in-progress library so things will change without notice! Furthermore, building
this library and examples requires the latest nightly version of Zig <code>0.8.0</code>, and [<code>gyro</code>] package
manager.
Building
This library consumes the Wasmer's C API which is auto-installed with each release of Wasmer.
The current stable release of Wasmer this embedding relies on is <a>v1.0.2</a>. Therefore, make sure
you have <code>wasmer</code> binary installed and in your <code>PATH</code>.
To build this library, simply run
<code>gyro build</code>
Tests can be invoked as follows
<code>gyro build test</code>
Running examples
You can find a few examples of how this library can be used to embed Wasmer in your app and
instantiate Wasm modules in the <code>examples/</code> dir. You can run any example with
<code>gyro build run -Dexample=<example></code>
In particular, you will find there <code>examples/instance.zig</code> which is a Zig port of Wasmer's <a>instance.c</a>
example. | []
|
https://avatars.githubusercontent.com/u/26302304?v=4 | zig_vulkan | Avokadoen/zig_vulkan | 2021-06-14T21:06:28Z | Toying with vulkan and zig | main | 81 | 51 | 2 | 51 | https://api.github.com/repos/Avokadoen/zig_vulkan/tags | - | [
"glfw",
"graphics",
"raytracing",
"voxel",
"vulkan",
"zig"
]
| 7,607 | false | 2025-05-20T19:37:27Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "ztracy",
"tar_url": "https://github.com/zig-gamedev/ztracy/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/ztracy"
},
{
"commit": "master",
"name": "zgui",
"tar_url": "https://github.com/zig-gamedev/zgui.git//archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zgui.git/"
},
{
"commit": "master",
"name": "zglfw",
"tar_url": "https://github.com/zig-gamedev/zglfw.git//archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zglfw.git/"
},
{
"commit": "master",
"name": "zalgebra",
"tar_url": "https://github.com/kooparse/zalgebra.git//archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/kooparse/zalgebra.git/"
},
{
"commit": "094c4bba5cdbec167d3f6aaa98cccccd5c99145f",
"name": "zstbi",
"tar_url": "https://github.com/zig-gamedev/zstbi/archive/094c4bba5cdbec167d3f6aaa98cccccd5c99145f.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zstbi"
},
{
"commit": "42e7a8409b8150e1cbd57a8ff8cec219114bac74",
"name": "vulkan_zig",
"tar_url": "https://github.com/Snektron/vulkan-zig/archive/42e7a8409b8150e1cbd57a8ff8cec219114bac74.tar.gz",
"type": "remote",
"url": "https://github.com/Snektron/vulkan-zig"
},
{
"commit": "7a28b4dbab429ebf17ac5b26aac4d660a97052b1",
"name": "shader_compiler",
"tar_url": "https://github.com/Games-by-Mason/shader_compiler/archive/7a28b4dbab429ebf17ac5b26aac4d660a97052b1.tar.gz",
"type": "remote",
"url": "https://github.com/Games-by-Mason/shader_compiler"
}
]
|
Zig vulkan renderer
A toy renderer written in zig using vulkan and glfw
Requirements
Zig build toolchain does most of the heavy lifting. The only systems
requirement is the <a>Vulkan SDK</a>.
Make sure you download Vulkan 1.4 or up
<strong>This project uses zig 0.14.0</strong>
Run the project
Do the following steps
<code>bash
$ git clone <repo>
$ cd <folder>
$ zig build run</code>
Run tests
Currently the code base is not really well tested, but you can run the few tests by doin <code>zig build test</code>
Sources:
<ul>
<li>Vulkan fundementals: </li>
<li>https://vkguide.dev/</li>
<li>https://vulkan-tutorial.com</li>
<li>Setup Zig for Gamedev: https://dev.to/fabioarnold/setup-zig-for-gamedev-2bmf </li>
<li>Using vulkan-zig: https://github.com/Snektron/vulkan-zig/blob/master/examples</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/2389051?v=4 | zig-std-lib-fuzzing | squeek502/zig-std-lib-fuzzing | 2021-09-21T00:03:26Z | A set of fuzzers for fuzzing various parts of the Zig standard library | master | 1 | 49 | 4 | 49 | https://api.github.com/repos/squeek502/zig-std-lib-fuzzing/tags | 0BSD | [
"fuzz-testing",
"fuzzing",
"zig"
]
| 451 | false | 2025-05-17T16:23:15Z | true | false | unknown | github | []
| Fuzzing the Zig standard library
A set of fuzzers for fuzzing various parts of the <a>Zig</a> standard library. See <a>'Fuzzing Zig Code Using AFL++'</a> for more information about the particular fuzzing setup used.
Current fuzzers:
- <code>tokenizer</code> which calls <code>std.zig.Tokenizer.next</code> until it gets an <code>eof</code> token
- <code>parse</code> which calls <code>std.zig.Ast.parse</code> and then <code>std.zig.Ast.render</code>
- <code>deflate</code> which calls <code>std.compress.flate.decompressor().reader().readAllAlloc()</code>
- <code>deflate-puff</code> which compares the results of <code>puff.c</code> to Zig's <code>std.compress.flate.decompressor</code>
- <code>deflate-roundtrip</code> which sends the input through <code>compressor</code>, then through <code>decompressor</code>, and then checks that the output is the same as the input
- <code>json</code> which calls <code>std.json.parseFromSlice</code>
- <code>sin</code> which calls <code>std.math.sin</code> and compares the result to libc's <code>sin</code>/<code>sinf</code>
- <code>xz</code> which calls <code>std.compress.xz.decompress</code>
- <code>xxhash</code> which compares the results of <code>xxhash.c</code> to Zig's <code>std.hash.xxhash</code> implementation
- <code>zstandard</code> which calls the <code>std.compress.zstd</code> <code>decode</code>, <code>decodeAlloc</code>, and <code>decompressStream</code> APIs.
- <code>zstandard-compare</code> which compares the results of the <code>zstd</code> reference implementation to Zig's <code>std.compress.zstd.decompress.decode</code> implementation
- <code>zstandard-compare-alloc</code> which compares the results of the <code>zstd</code> reference implementation to Zig's <code>std.compress.zstd.decompress.decodeAlloc</code> implementation
- <code>zstandard-compare-stream</code> which compares the results of the <code>zstd</code> reference implementation to Zig's <code>std.compress.zstd.decompressStream</code> implementation
- <code>tar</code> which uses <code>std.tar.iterator</code> to simulate an untar operation (but does not write to the filesystem)
- <code>tar-fs</code> which calls <code>std.tar.pipeToFileSystem</code> (and actually writes to the filesystem)
Non-<code>std</code> fuzzers (requires <code>-Dzig-src=/path/to/zig/sources</code>):
- <code>markdown</code> which calls Autodoc's <code>markdown.Parser</code> to parse an input line by line
- <code>git</code> which calls <code>git.indexPack</code> on a Git packfile
- Requires a patch (<code>fuzzers/git.patch</code>) to be applied to upstream <code>git.zig</code> so I/O can be avoided.
- To verify the contents of the input packfile (<code>small.pack</code>):
<code>1. Create a new empty Git repository (`git init`)
2. `git unpack-objects <path/to/small.pack`
3. `git fsck` -> note the "dangling commit" ID (which matches the commit checked out below)
4. `git checkout 0a9b7c28d992347b3e237bb143c052b177ad388f`
</code>
Requires <a>AFL++</a> with <code>afl-clang-lto</code> to be installed (see <a>Compiling AFL++</a>).
Building a fuzzer
Run <code>zig build fuzz-<fuzzer name></code>, e.g. <code>zig build fuzz-tokenizer</code>
Running a fuzzer
The instrumented fuzzer will be installed to <code>zig-out/bin/fuzz-<fuzzer name></code>. You'll probably also need to run <code>mkdir outputs</code> (if you're planning on using <code>outputs</code> as an output directory) before fuzzing. Here's a simple example of running the <code>tokenizer</code> fuzzer:
<code>afl-fuzz -i inputs/tokenizer -o outputs/tokenizer -x dictionaries/zig.dict -- ./zig-out/bin/fuzz-tokenizer</code>
(the <code>-x</code> option is not necessary but using a dictionary is recommended if possible)
See <a>AFL++'s 'fuzzing the target' section</a> for more recommendations to improve fuzzing effectiveness (using multiple cores, etc).
Debugging crashes
If a crash is found during fuzzing, the companion <code>fuzz-<fuzzer name>-debug</code> executable can be used to debug the crash. For example, for the <code>tokenizer</code> fuzzer, a stack trace could be gotten with:
<code>sh
$ ./zig-out/bin/fuzz-tokenizer-debug < 'outputs/tokenizer/default/crashes/id:000000,sig:06,src:000908+000906,time:117053,op:splice,rep:16'
thread 2730086 panic: index out of bounds
/home/ryan/Programming/zig/zig/build/lib/zig/std/zig/tokenizer.zig:408:34: 0x215131 in std.zig.tokenizer.Tokenizer.next (fuzz-tokenizer-debug)
const c = self.buffer[self.index];
^
/home/ryan/Programming/zig/zig/build/lib/zig/std/zig/parse.zig:24:37: 0x20af60 in std.zig.parse.parse (fuzz-tokenizer-debug)
const token = tokenizer.next();
^
...</code>
Alternatively, the crash can be debugged via gdb:
<code>gdb -ex 'set args < outputs/tokenizer/default/crashes/id:000000,sig:06,src:000908+000906,time:117053,op:splice,rep:16' ./zig-out/bin/fuzz-tokenizer-debug</code>
Or valgrind:
<code>valgrind ./zig-out/bin/fuzz-tokenizer-debug < 'outputs/tokenizer/default/crashes/id:000000,sig:06,src:000908+000906,time:117053,op:splice,rep:16'</code>
<a><code>zigescape</code></a> can also be used to convert inputs into string literals for the creation of test cases (preferrably after using <code>afl-tmin</code> to minimize the input).
Bugs found / fixed
<code>std.zig.Tokenizer</code>
<ul>
<li>https://github.com/ziglang/zig/pull/9808</li>
<li>https://github.com/ziglang/zig/pull/9809</li>
</ul>
<code>std.compress.flate</code>
<ul>
<li><a>https://github.com/ianic/flate/issues</a> (a bunch of stuff before it was <a>submitted as a PR</a>)</li>
</ul>
obsoleted Deflate implementations
### `std.compress.deflate` (second version of Deflate)
- https://github.com/ziglang/zig/pull/10552#issuecomment-1019194395
### `std.compress.deflate` (first version of Deflate)
- https://github.com/ziglang/zig/pull/9849
- https://github.com/ziglang/zig/pull/9860
- https://github.com/ziglang/zig/pull/9880
<code>std.math</code>
<ul>
<li><code>sin</code>: https://github.com/ziglang/zig/issues/9901</li>
</ul>
<code>std.compress.xz</code>
<ul>
<li>https://github.com/ziglang/zig/issues/14500</li>
</ul>
<code>std.compress.zstandard</code>
<ul>
<li>https://github.com/ziglang/zig/pull/14394 (a whole bunch of stuff during the PR process)</li>
</ul>
<code>std.tar</code>
<ul>
<li>https://github.com/ziglang/zig/pull/19038</li>
</ul>
In upstream/third-party projects
<a><code>facebook/zstd</code></a>
<ul>
<li>https://github.com/facebook/zstd/issues/3506</li>
<li>https://github.com/facebook/zstd/issues/3507</li>
<li>https://github.com/facebook/zstd/issues/3508</li>
<li>https://github.com/facebook/zstd/issues/3482</li>
</ul>
Other tools/fuzzers
<code>zstandard-verify</code>
Requires the <code>decodecorpus</code> tool from <a>zstd</a> and the <code>zstandard-verify</code> tool from this repo (can be built with <code>zig build tools</code>). Run the following command to use it to continuously test the <code>zstandard</code> Zig decompressor with generated compressed .zst files:
<code>./tools/zstandard-decodecorpus.sh /path/to/decodecorpus ./zig-out/bin/zstandard-verify</code>
Compiling AFL++
<ul>
<li>Clone <code>https://github.com/AFLplusplus/AFLplusplus</code> (avoid recursively cloning, avoid initializing submodules--they are <em>huge</em> and unnecessary for our purposes)</li>
<li>Make sure <code>llvm-config --version</code> matches the same version that your Zig uses</li>
</ul>
<code>cd AFLplusplus
make source-only NO_NYX=1
make install</code>
(or <code>sudo make install</code> if needed) | []
|
https://avatars.githubusercontent.com/u/1519747?v=4 | protozig | kubkon/protozig | 2022-01-29T11:05:58Z | The protozig(uana), or protocol buffers implementation in Zig | main | 0 | 46 | 1 | 46 | https://api.github.com/repos/kubkon/protozig/tags | MIT | [
"protobuf",
"zig",
"zig-library"
]
| 16 | false | 2025-05-16T00:28:29Z | true | false | unknown | github | []
| protozig
Ideally, this will be a complete implementation of <a>protobuf</a>
in <a>Zig</a>.
Initially, my focus will be entirely on a standalone protobuf to Zig translator. The syntax version I'll be focusing
on will be <code>proto3</code> (in the future, happy to add the previous <code>proto2</code> version too).
How to...
You will need at least <a>Zig v0.9.0</a> in your path. Alternatively, if you can use
Nix, simply enter a new shell in the repo's root:
<code>$ nix-shell</code>
Building the <code>protozig</code> proto-to-zig translator:
<code>$ zig build install</code>
Running tests:
<code>$ zig build test</code> | []
|
https://avatars.githubusercontent.com/u/7967463?v=4 | open-reckless-drivin | natecraddock/open-reckless-drivin | 2021-02-24T17:46:02Z | A work-in-progress open source reimplementation of the classic Macintosh shareware game Reckless Drivin' | main | 4 | 45 | 1 | 45 | https://api.github.com/repos/natecraddock/open-reckless-drivin/tags | MIT | [
"game",
"macintosh",
"macintosh-arcade-games",
"zig"
]
| 13,929 | false | 2025-01-11T16:04:37Z | true | true | unknown | github | [
{
"commit": "0959f6ebf69f44d5bb0225cc94fd187ebedf8be5.tar.gz",
"name": "raylib",
"tar_url": "https://github.com/raysan5/raylib/archive/0959f6ebf69f44d5bb0225cc94fd187ebedf8be5.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/raysan5/raylib"
}
]
| Open Reckless Drivin'
This project is an attempt to reimplement the classic Macintosh shareware game
Reckless Drivin' as a cross-platform game. The source code of the original game
was released by the author Jonas Echterhoff in 2019, but relies heavily on
deprecated Macintosh system calls for most aspects of the game. Additionally,
the game data (sprites, sounds, level data, etc.) are all LZRW3 compressed
inside the resource fork of the original game, which is an additional barrier to
reimplementation.
The original source may be found at https://github.com/jechter/RecklessDrivin.
Current Status
<strong>Update:</strong> I am finished porting all my work in C to Zig. Overall I am very
pleased with the rewrite, and I appreciate all of the little improvements to the
code that were lacking in C, like knowing the length of a slice without
resorting to offsets and weird fat pointer tricks I was using previously.
At this stage, the game is not playable. But at startup all of the data is
decompressed and loaded into memory, and then promptly freed before exiting. The
next step is to start the game loop! I have chosen to ignore the main menu for
now so we can get a playable game as soon as possible.
Details
The original source contained a file called <code>Data</code> containing the resource fork.
This has been converted into a header file (<code>src/include/data</code>) to be embedded
in the executable directly. This file contains various "Packs" of data including
Apple QuickDraw images, sounds, sprites, and fonts. Work has been done to
reliably read, decompress, decrypt, and interpret the data from this resource
fork.
As an indicator of progress, PPic Packs 1000 through 1008 (the Apple QuickDraw
images) have been read from the resource fork. This verifies that the lzrw-3a
decompression is working, and is a exciting marker of progress! See the images
on the
<a>wiki</a>.
Building
So far I have only built Open Reckless Drivin' on Arch Linux, but I see no
reason why it wouldn't work elsewhere. Using the latest stable version of Zig:
<code>text
zig build</code>
The binary will be placed in <code>zig-out/bin/reckless-drivin</code>. Run with the
<code>register [name]</code> option to generate a new activation code.
To run tests
<code>zig build test</code>
Registration Keys
Jonas released the game for free after it was no longer viable to update it for
modern systems. More information can be found on the <a>game's
website</a>. The free registration
information is:
Name: Free
Code: B3FB09B1EB | []
|
https://avatars.githubusercontent.com/u/65570835?v=4 | zig-lsp | ziglibs/zig-lsp | 2021-10-24T01:35:58Z | Microsoft's Language Server Protocol implemented in Zig for use in zls and beyond! <3 | main | 1 | 45 | 2 | 45 | https://api.github.com/repos/ziglibs/zig-lsp/tags | MIT | [
"lsp",
"zig",
"zls"
]
| 203 | false | 2024-12-27T23:46:44Z | true | true | unknown | github | []
| zig-lsp
Uses https://github.com/zigtools/zig-lsp-codegen to the fullest extent permissible by my smol brain. Make sure to periodically update the autogenerated bindings!
License
MIT | []
|
https://avatars.githubusercontent.com/u/1519747?v=4 | zig-snapshots | kubkon/zig-snapshots | 2021-10-20T13:47:11Z | Preview Zig's incremental linker state in interactive HTML | main | 0 | 45 | 1 | 45 | https://api.github.com/repos/kubkon/zig-snapshots/tags | MIT | [
"visualisaton",
"zig",
"zig-package",
"zld"
]
| 532 | false | 2025-05-16T00:28:24Z | true | false | unknown | github | []
| zig-snapshots
A tool allowing you to preview a series of snapshots of Zig's incremental linker.
Usage
You will need to build Zig's stage2/self-hosted compiler with <code>-Dlink-snapshot</code> flag on:
<code>$ zig build -Dlink-snapshot</code>
Then, you can run the compiler either in a fire-and-forget or watch-for-updates manner with
<code>--debug-link-snapshot</code> flag on to generate a snapshot of the linker's state per incremental update,
all saved in the same JSON output file:
```
$ zig build-exe hello.zig --watch --debug-link-snapshot
<blockquote>
update-and-run
update-and-run
exit
</blockquote>
$ file snapshots.json
snapshots.json: JSON data
```
You should then feed the output JSON file to <code>zig-snapshots</code> which will generate an
HTML file with the linker's state per each incremental update that you can interative with:
<code>$ zig-out/bin/zig-snapshots snapshots.json
$ open snapshots.html</code>
| []
|
https://avatars.githubusercontent.com/u/32078353?v=4 | zjson | xyaman/zjson | 2021-12-16T13:36:33Z | Minimal json library with zero allocations | main | 1 | 44 | 1 | 44 | https://api.github.com/repos/xyaman/zjson/tags | MIT | [
"json",
"zig"
]
| 16 | false | 2024-12-28T00:30:22Z | true | false | unknown | github | []
| zjson
A very tiny json library, it allows you to get a json value from a path.
Inspired by <a>jsonparser</a>, a Go library.
This library is useful when you dont want to parse whole JSON file, or when
the structure is to complex to parse to structs. It <strong>allocates no memory</strong>.
<blockquote>
This library is still WIP, the API might change. There can be some bugs as it's not fully tested.
</blockquote>
API usage:
Here there is a basic example.
```zig
const input =
\ {
\ "student": [
\ {
\ "id": "01",
\ "name": "Tom",
\ "lastname": "Price"
\ },
\ {
\ "id": "02",
\ "name": "Nick",
\ "lastname": "Thameson"
\ }
\ ]
\ }
;
const lastname = try get(input, .{ "student", 1, "lastname" });
// Thameson
// Iterates an array
const students = try get(input, .{"student"});
var iter = try zjson.ArrayIterator(students);
while(try iter.next()) |s| {
const name = try get(value.bytes, .{"name"});
std.debug.print("student name: {s}\n", .{name.bytes});
}
// "student name: Tom"
// "student name: Nick"
```
For more usage examples, you can check <a>ytmusic-zig</a>. | []
|
https://avatars.githubusercontent.com/u/4252848?v=4 | zwld | Luukdegram/zwld | 2021-09-17T11:13:00Z | Experimental wasm linker | master | 0 | 43 | 1 | 43 | https://api.github.com/repos/Luukdegram/zwld/tags | MIT | [
"linker",
"wasm",
"wasm-ld",
"wasm-linker",
"wasmlinker",
"webassembly",
"zig",
"ziglang"
]
| 353 | false | 2025-05-16T00:33:50Z | true | false | unknown | github | []
| zwld
<blockquote>
<em>Note:</em> This repository has been archived as all development is now being done in <a>zld</a> and the <a>Zig toolchain</a>
</blockquote>
Experimental linker for wasm object files.
The idea is to implement a linker that stays close to wasm-ld in regards to features
~so that one day this could potentially be used within the Zig self-hosted compiler to incrementally
link Zig code with other wasm object files.~
With zwld now having been upstreamed, the main development of the linker is done directly within the Zig compiler. Features and improvements will be backported to zwld at one point. Until then, this repository is mostly inactive.
While there's no official specification for linking, <code>zwld</code> follows the wasm <a>tool-convention</a> closely.
The initial goal is to support mvp features and have a base skeleton which would provide us with enough information on how
to integrate this within the Zig compiler. The first step is to make static linking work as specified by <code>tool-convention</code>,
once that is completed, dynamic linking will be tackled.
Usage
```
Usage: zwld [options] [files...] -o [path]
Options:
-h, --help Print this help and exit
-o [path] Output path of the binary
--entry Name of entry point symbol
--global-base= Value from where the global data will start
--import-memory Import memory from the host environment
--import-table Import function table from the host environment
--initial-memory= Initial size of the linear memory
--max-memory= Maximum size of the linear memory
--merge-data-segments Enable merging data segments
--no-entry Do not output any entry point
--stack-first Place stack at start of linear memory instead of after data
--stack-size= Specifies the stack size in bytes
--features= Comma-delimited list of used features, inferred by object files if unset
```
Building
<code>zwld</code> uses the latest Zig, which can either be <a>built from source</a> or you can download
the latest <a>binary</a>.
Zwld can then be built running the following command:
<code>zig build [-Denable-logging]</code>
Right now zwld only contains debug logging, which is hidden behind the <code>enable-logging</code> flag. It is set to <code>false</code> by default. | []
|
https://avatars.githubusercontent.com/u/71897736?v=4 | coc-zig | UltiRequiem/coc-zig | 2021-08-15T19:21:39Z | 〰️ ZLS for coc.nvim | main | 0 | 42 | 8 | 42 | https://api.github.com/repos/UltiRequiem/coc-zig/tags | MIT | [
"coc",
"coc-extensions",
"coc-nvim",
"neovim",
"vim",
"zig",
"ziglang",
"zls"
]
| 369 | false | 2025-05-20T23:53:07Z | false | false | unknown | github | []
| Coc Zig
<a>Coc.nvim</a> wrapper for the
<a>Zig Language Server</a>.
Is recommended to use <a>zig.vim</a> also.
Configuration
If your <code>coc-settings.json</code>:
<code>json
"zig.enabled": true,
"zig.startUpMessage": true,
"zig.path": "zls",
"zig.debugLog": false,</code>
Install
In you Neovim run 🚀
<code>:CocInstall coc-zig</code>
Using an external plugin manager 👇
<blockquote>
⚠ This is not recommended by the coc.nvim team
</blockquote>
Packer example 📦
<code>lua
use {'UltiRequiem/coc-zig', run='yarn install --frozen-lockfile && yarn build'}</code>
Support
Open an Issue, I will check it as soon as possible 👀
Licence
Licensed under the MIT License 📄 | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | aquila | nektro/aquila | 2021-04-12T02:10:09Z | 📫 A package index for Zig projects. | master | 7 | 41 | 0 | 41 | https://api.github.com/repos/nektro/aquila/tags | NOASSERTION | [
"package-repository",
"zig"
]
| 395 | false | 2025-05-15T10:22:06Z | true | false | unknown | github | []
| Aquila
<a></a>
<a></a>
<a></a>
<a></a>
A federated package index and CI system for the Zig programming language built around the <a>Zigmod</a> package manager.
About Zig
<ul>
<li>https://ziglang.org/</li>
<li>https://github.com/ziglang/zig</li>
</ul>
Download
<ul>
<li>https://github.com/nektro/aquila/releases</li>
</ul>
Building from Source
<code>$ zigmod fetch
$ zig build</code>
Built With
<ul>
<li>Zig master (at least <code>0.10.0-dev.3316+a0d3a87ce</code>)</li>
<li>See <a><code>zigmod.yml</code></a> and <a><code>zigmod.lock</code></a></li>
</ul>
License
GNU Affero General Public License v3.0 | []
|
https://avatars.githubusercontent.com/u/39484230?v=4 | Stella-Dei | zenith391/Stella-Dei | 2021-10-26T15:22:06Z | SimEarth-like sandbox game where you can make and develop your very own planet | master | 7 | 41 | 0 | 41 | https://api.github.com/repos/zenith391/Stella-Dei/tags | GPL-3.0 | [
"3d-game",
"game",
"multiplatform",
"sandbox",
"sandbox-game",
"simulation-game",
"zig"
]
| 102,909 | false | 2025-05-13T16:34:23Z | true | true | unknown | github | [
{
"commit": "e36116987d11c4a28ab8a03ab62d71be8b81404a.tar.gz",
"name": "zalgebra",
"tar_url": "https://github.com/kooparse/zalgebra/archive/e36116987d11c4a28ab8a03ab62d71be8b81404a.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/kooparse/zalgebra"
},
{
"commit": "d9dbbe22b5f7b5f1f4772169ed93ffeed8e8124d.tar.gz",
"name": "zigimg",
"tar_url": "https://github.com/zigimg/zigimg/archive/d9dbbe22b5f7b5f1f4772169ed93ffeed8e8124d.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/zigimg/zigimg"
},
{
"commit": "95bacce05bce0622039be6db46145d5f378ba50f.tar.gz",
"name": "mach_glfw",
"tar_url": "https://github.com/hexops/mach-glfw/archive/95bacce05bce0622039be6db46145d5f378ba50f.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/hexops/mach-glfw"
}
]
| Stella Dei
Stella Dei is a sandbox game about creating planet and influencing it with your unlockable divine abilities in order to create and maintain life, civilizations, and maybe help them expand beyond.
<blockquote>
Careful. At some point you’re just playing god.
</blockquote>
It's also inspired by SimEarth.
Compiling
Dependencies
The game requires:
- Zig <a><code>2024.5.0-mach</code></a> (<code>0.13.0-dev.351+64ef45eb0</code>)
Building from source
<code>sh
$ git clone https://github.com/PixelGuys/Stella-Dei && Stella-Dei
$ zig build</code>
And now you've got an executable located inside <code>zig-out/bin/</code>. If you want to directly run the game, just do:
<code>sh
$ zig build run</code>
To distribute an executable for Windows, use:
<code>sh
$ zig build -Dtarget=native-windows -Dcpu=x86_64_v2 -Doptimize=ReleaseSafe</code> | []
|
https://avatars.githubusercontent.com/u/65570835?v=4 | tres | ziglibs/tres | 2022-01-01T21:51:09Z | ValueTree-based JSON parser | main | 1 | 39 | 4 | 39 | https://api.github.com/repos/ziglibs/tres/tags | MIT | [
"json",
"zig",
"zig-package",
"ziglang"
]
| 104 | false | 2024-07-23T01:18:08Z | true | false | unknown | github | []
| tres
<code>std.json.parse</code> but on <code>ValueTree</code>s. Stringify that supports Undefinedables, ArrayLists, and HashMaps.
Features
<ul>
<li><code>parse</code> (std.json.Value -> T)</li>
<li><code>stringify</code> (T -> []const u8)</li>
<li><code>toValue</code> (T -> std.json.Value)</li>
</ul>
All the above modes support <code>std.json</code> standard features as well as:
- Enhanced optionals (<code>tres_null_meaning</code>, see test "parse and stringify null meaning")
- String enums (<code>tres_string_enum</code>, see test "json.stringify enums")
- Field name remapping (<code>tres_remap</code>, see test "remapping")
- Map and ArrayList support (unmanaged too!)
License
MIT | []
|
https://avatars.githubusercontent.com/u/60808802?v=4 | .dotfiles | Shinyzenith/.dotfiles | 2021-10-29T10:58:30Z | My ArtixLinux rice with wayland using the river compositor. | master | 0 | 39 | 1 | 39 | https://api.github.com/repos/Shinyzenith/.dotfiles/tags | - | [
"archlinux",
"artix",
"artix-linux",
"artixlinux",
"minimal",
"minimalist",
"river",
"wayland",
"zig",
"zsh"
]
| 4,428 | false | 2025-03-08T13:39:46Z | false | false | unknown | github | []
| Screenshots
How to use this setup?
Install Artix Linux, clone this repo to <code>~/.config/.dotfiles</code>
<ol>
<li>Install ArtixLinux runit</li>
<li>Run <code>~/.config/.dotfiles/assets/sudo.sh</code> as root</li>
<li>Run <code>setup.sh</code> and delete <code>export XKB_DEFAULT_OPTIONS=caps:swapescape</code> from <code>~/.zprofile</code> if you don't want your escape key to be swapped with your caps lock key.</li>
</ol> | []
|
https://avatars.githubusercontent.com/u/3932972?v=4 | zig-serve | ikskuh/zig-serve | 2021-11-09T17:41:54Z | Server implementations for several protocols in Zig. Includes http(s), gemini and gopher | master | 1 | 38 | 5 | 38 | https://api.github.com/repos/ikskuh/zig-serve/tags | - | [
"gemini",
"gemini-protocol",
"gemini-server",
"gopher",
"gopher-protocol",
"gopher-server",
"http",
"http-server",
"https-server",
"server",
"zig",
"zig-package",
"ziglang"
]
| 1,513 | false | 2025-05-04T22:02:44Z | true | false | unknown | github | []
| zig-serve
A implementation of several network protocols for Zig:
<ul>
<li>HTTP 1.1</li>
<li>Gemini</li>
<li>Gopher</li>
<li>Finger</li>
</ul>
Disclaimer
<strong>DO NOT USE THESE SERVER IMPLEMENTATIONS IN PRODUCTION!</strong>
They are very much work-in-progress without any warranty of function or correctness. Don't even think about security right now!
Status
| Protocol | Status |
| -------- | --------------- |
| Finger | ⏸ Not started |
| Gopher | 🧪 Experimental |
| Gemini | 🧪 Experimental |
| HTTP(S) | 🧪 Experimental |
<em>Experimental</em> means that there is basic support for the protocol, but no spec compliance has been proven yet.
Development / Tasks
Create a new self-signed SSL certificate
<code>sh-console
openssl req -new -x509 -config examples/data/cert-config.cfg -nodes -newkey rsa:2048 -keyout examples/data/key.pem -out examples/data/cert.pem -days 36500</code>
RFCs & Specs
<ul>
<li><a>RFC1945</a> - Hypertext Transfer Protocol -- HTTP/1.0</li>
<li><a>RFC2616</a> - Hypertext Transfer Protocol -- HTTP/1.1</li>
<li><a>RFC7231</a> - Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content</li>
<li><a>RFC1436</a> - The Internet Gopher Protocol (a distributed document search and retrieval protocol)</li>
<li><a>Project Gemini</a> - Speculative specification</li>
<li><a>RFC1288</a> - The Finger User Information Protocol</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/3932972?v=4 | any-pointer | ikskuh/any-pointer | 2021-11-05T14:45:56Z | A type erasure library for Zig that is meant to be eventually upstreamed to std | master | 4 | 38 | 4 | 38 | https://api.github.com/repos/ikskuh/any-pointer/tags | MIT | [
"zig",
"zig-package",
"ziglang"
]
| 30 | false | 2025-03-25T16:42:18Z | true | false | unknown | github | []
| any-pointer type erasure
This package provides a single file <code>any-pointer.zig</code> that implements a type-erased pointer for Zig.
This pointer type supports three functions <code>make</code>, <code>cast</code> and <code>isNull</code> and exports the symbol <code>null_pointer</code>.
```zig
const AnyPointer = @import("any-pointer").AnyPointer;
var i: u32 = 0;
const erased = AnyPointer.make(*u32, &i);
const ptr = erased.cast(*u32);
ptr.* = 42;
std.debug.assert(i == 42);
```
In safe modes (<code>Debug</code> and <code>ReleaseSafe</code>) <code>cast</code> will type-check the pointer and might <code>@panic</code> when a type confusion would happen.
Usage
Just add a package pointing to <code>any-pointer.zig</code> to your project.
The package will export three types:
<ul>
<li><code>SafePointer</code>, which will provide type checking and panics in safe modes.</li>
<li><code>UnsafePointer</code>, which will not provide type checking and will only have the size of a single pointer.</li>
<li><code>AnyPointer</code>, which will be <code>SafePointer</code> in safe modes and <code>UnsafePointer</code> in unsafe modes.</li>
</ul>
In addition to <code>make</code>, <code>cast</code> and <code>isNull</code>, <code>SafePointer</code> also has the function <code>tryCast</code> which works like <code>cast</code>, but will return an optional. | []
|
https://avatars.githubusercontent.com/u/86482337?v=4 | jui | zig-java/jui | 2021-06-24T03:42:47Z | Ziggy bindings for the JNI | main | 0 | 37 | 5 | 37 | https://api.github.com/repos/zig-java/jui/tags | MIT | [
"bindings",
"java",
"jni",
"zig"
]
| 97 | false | 2025-01-27T08:09:01Z | true | false | unknown | github | []
| jui
jui or the Java Universal Interface is a set of Zig-intuitive bindings for JNI, the Java Native Interface.
Taking jui for a spin
```bash
Build the demo
zig build
Run the demo
java -Djava.library.path="zig-out/lib" test/src/com/jui/JNIExample.java
``` | []
|
https://avatars.githubusercontent.com/u/11307305?v=4 | JSage | sagemathinc/JSage | 2021-08-26T06:31:40Z | Something like Sage, but for the WebAssembly and JavaScript world. | main | 4 | 36 | 4 | 36 | https://api.github.com/repos/sagemathinc/JSage/tags | GPL-3.0 | [
"mathematics",
"number-theory",
"python",
"sagemath",
"webassembly",
"zig"
]
| 8,040 | false | 2024-11-20T15:40:05Z | false | false | unknown | github | []
| <strong>This repo is basically deprecated. However, work is continuing at https://github.com/sagemathinc/cowasm/tree/main/sagemath</strong>
JSage
<blockquote>
<em>"Something like the Python-based <a>SageMath</a>, but for the Javascript world."</em>
</blockquote>
Quick start
You should have Node version 16.x installed. All the compiled code is WebAssembly, so it should work on any computer with Node 16.x installed and install very quickly; in particular, nothing needs to be compiled when installing.
```python
<blockquote>
npm install @jsage/jpython
npx jsage # or npx jpython for no preparser
Welcome to JSage. Using Node.js v16.13.0.
Type dir(jsage) for available functions.
jsage: list([2 .. 2^3])
[2, 3, 4, 5, 6, 7, 8]
jsage: 2/3 + 4/5
22/15
jsage: dir(jsage)
['ComplexNumber', 'dims', 'P1List', 'ManinSymbols', 'EllipticCurve', 'factor', 'arith', 'Integer', 'ZZ', 'Rational', 'QQ', 'pari', 'misc', 'Number', 'init']
jsage: dims.dimensionCuspForms(389)
32
jsage: E = EllipticCurve('389a'); E
EllipticCurve([0, 1, 1, -2, 0])
jsage: E.analyticRank()
2
jsage: E.conductor()
389
jsage: E.anlist(20)
[0, 1, -2, -2, 2, -3, 4, -5, 0, 1, 6, -4, -4, -3, 10, 6, -4, -6, -2, 5, -6]
jsage: %time v = E.anlist(10^5);
Wall time: 170ms
jsage: M = ManinSymbols(389); P = M.presentation(1009); t = P.heckeOperator(2);
jsage: t.fcp()
[x + 2 2]
[x + 439 2]
...
[x^4 + 298<em>x^3 + 873</em>x^2 + 507<em>x + 325 2]
[x^9 + 347</em>x^8 + 408<em>x^7 + 343</em>x^6 + 673<em>x^5 + 219</em>x^4 + 736<em>x^3 + 475</em>x^2 + 326*x + 697 2]
jsage: for i in range(4): print(i, 10+i) # jsage is similar to Python...
...
0 10
1 11
2 12
3 13
```
</blockquote>
As explained below, it's also pretty easy to build JSage from source. We fully support building and developing natively using x86_64 and aarch64 Linux, and Intel and M1 MacOS. There's also a Docker build recipe.
OK, what is this?
The name "JSage" is meant to suggest a small combination of ideas from Javascript and Sage.
In 2004, I started https://www.sagemath.org/, which has gone on to be very successful in supporting pure mathematics research and teaching. Similar to Ryan Dahl who started node.js, I haven't been deeply involved in the weeds of Sage development for a long time, and also <a>similar to Ryan</a>, I've been thinking what I would do differently if I were to start Sage today in 2021. This is one possible result of mulling over that question lately.
What's the goal? What is the good for?
<strong>!! Right now I don't claim this is useful for anything at all. It's a "Proof of Concept" !!</strong>
Some potential longterm goals are listed below.
Create a ridiculously easy to distribute and install platform-independent distribution of SageMath
SageMath is a very large Python/Cython library that also includes a large number of other mathematical software systems such as PARI and Gap and Singular. Thus part of the goal is to build each of PARI, GAP, etc. using Zig. This could be distributed as a small native Electron app along with a few hundred megabytes of cross-platform WebAssembly and data files. When there's a new release of Sage, the WebAssembly files need to get rebuilt and tested once, and the resulting binary will then support all versions of Linux, Windows, MacOS, and iOS. For iOS we would use <a>a-shell</a> (or simple contribute a free package to a-shell).
<ul>
<li>There's probably <a>no way to build R</a> with Zig, so we'll toss it; the Python community has not ended up building stats around rpy2 so this is fine.</li>
<li>It might be very difficult to build Maxima via ECL (embedded common lisp) for WASM, in which case we will have to change Sage to not depend on Maxima for symbolic computation. We'll see. This is a very challenging project!</li>
</ul>
Make research level mathematical software available to the Javascript ecosystem
Javascript is the most widely deployed language, but there is essentially nothing similar to any part of Sage, Pari, Gap or Singular available natively in <a>their ecosystem</a>. Web applications, Node.js programs, and <a>sandboxed code running via WebAssembly</a> could all benefit from such software.
JIT: Just in time compiler
Modern Javascript runtimes -- in particular, Chrome V8 and Firefox SpiderMonkey -- have good just-in-time (JIT) compilers that optimize a wide range of Javascript code. It could be valuable to combine math research software with the power of Javascript JIT. The Python ecosystem's JIT story is very different than what's available in Javascript. There's Pypy, but it's more "fringe", and it has real performance issues with C extensions. There's also numba, which is amazing for what it is amazing at, but only works for very specific types of code. There's also the new <a>Pyston</a> spinoff from Dropbox.
Compared to Julia, the Javascript JIT's are also impressive due to how quickly and seamlessly it does JIT'ing, since that's a critical requirement for web pages. Sometimes Julia's JIT experience can involve waiting a long time for the JIT to happen before your code runs.
In any case, there may be situations where a program is fairly easy to write using a combination of Javascript and some of the WebAssembly libraries that come out of this project, and Javascript's JIT might also result in a very pleasant experience overall, as compared to other options.
JPython: yet another Python-to-Javascript compiler
Another experimental project you will find here is <code>jpython</code>, which is a <em>very lightweight</em> Python-to-Javascript compiler. It makes it possible to write Python code, but benefit from a Javascript JIT and all the functionality we build for WASM above. JPython runs natively in Javascript, so there is no dependence on Python itself (unlike Transcrypt). JPython is a fork of RapydScript, but with very different goals and constraints, e.g., much better conformance with the Python language, support for operator overloading, support for numerical computation, a mode to parse the "Sage preparser" language, and with a lot of what RapydScript does removed (e.g., everything related to frontend UI programming). This barely exists today though!
New low level code
Making libraries like Pari, NTL, eclib, etc. available to Javascript is just a first step. This project also includes building new tools using modern low-level high-performance languages like Zig.
Does this compete with SageMath?
Unlike <a>Julia</a> or <a>Oscar</a>, this project does not attempt to directly compete with SageMath. Indeed, one of the goals is to provide a distribution of SageMath that is easier to use, and another goal is to make the components of Sage and ultimately much of the core Sage library efficiently usable in more situations (e.g., node.js, web browsers, etc.). This project is thus about enriching the mathematical software ecosystem and expanding it beyond Python.
Build JSage from source
Dependencies to build
<ul>
<li><strong>Node.js at least version 16.x:</strong> the <code>node</code> in your path must be this recent version of node.js, which is very <a>easy to install</a> on most computers.</li>
<li><strong>Standard build tools:</strong> e.g., git, make, curl, m4, etc. For Linux see the Dockerfile remark below, and for macOS, just make sure to install XCode which includes all this.</li>
<li>This <a>Dockerfile</a> automates building JSage from source on Ubuntu Linux 20.04. It fully works on both x86_64 and aarch64 Linux, and looking at it might answer any questions about build dependencies. Also, if you're having trouble building JSage and have Docker installed, you could instead do <code>make docker</code> and build this Docker image locally.</li>
<li><strong>Tested Platforms:</strong> I've tested building on the following platforms:</li>
<li><em>x86_64 and aarch64 Linux</em> -- via the Dockerfile above</li>
<li><em>macOS 12.x with Apple Silicon</em>, and XCode installed (to provide make, git, etc.)</li>
<li>x86_64 Linux as in any <a>CoCalc</a> project with network access.</li>
<li><a>Microsoft Windows via WSL</a> -- works fine, at least using Ubuntu (the default) after <code>apt install</code> the packages in the Dockerfile.</li>
</ul>
The build takes on the order of <strong>one hour</strong> or so.
How to build
Just type "make"
<code>sh
...$ make</code>
This runs a single top level makefile to build all the packages. The build process for all individual packages is <em>also</em> accomplished using a Makefile. We don't use shell scripts or Python code to orchestrate building anything, since <code>make</code> is much cleaner and easier to read, maintain and debug.
What happens
In most subdirectories <code>foo</code> of packages, this will create some subdirectories:
<ul>
<li><code>packages/foo/dist/[native|wasm]</code> -- a native or WebAssembly build of the package; this has binaries, headers, and libs. These get used by other packages.</li>
<li><code>packages/build/[native|wasm]</code> - build artifacts for the native or WebAssembly build; can be safely deleted</li>
</ul>
Extra Packages
I have put a lot of work into getting various things to build, e.g., NTL, FLINT, Python, which are currently <em><strong>not</strong></em> needed as a dependency for the core library I find myself building. Thus they are now NOT being built by default, since they aren't needed. Really all we need so far to build what we want to build is JPython (a Python language->Javascript compiler), GMP and Pari. It's amazing how much functionality Pari has built in, which overall is much broader (but less deep in some ways) than what's available in the C/C++ ecosystem of NTL/FLINT, etc. For our purposes though (of something very cross platform and easy to maintain!), Pari is really ideal.
That said, I put a lot of work into these other packages, and maybe they will be important at some point. But don't expect them to just work.
No common prefix directory
Unlike SageMath, where everything is built into a single <code>local</code> directory, here we build everything in its own self-contained package. When a package like <code>pari</code> depends on another package like <code>gmp</code> , our Makefile for <code>pari</code> explicitly references the <code>dist</code> directory in the <code>packages/dist/gmp</code> . This makes it possible to uninstall packages, update them, etc., whereas using a common directory for everything can be a mess with possibly conflicting versions of files.
Native and Wasm
The build creates directories dist/native and dist/wasm. The <code>dist/native</code> artifacts are only of value on the computer where you ran the build, since they are architecture dependent and can easily depend on libraries on your system. In contrast, the <code>dist/wasm</code> artifacts are platform independent. They can be used nearly everywhere: on servers via WASM, on ARM computers (e.g., aarch64 linux, Apple Silicon, etc.), and in any modern web browser (though many details remain, obviously).
Contact
Email <a>[email protected]</a> if you find this interesting and want to help out. This is all as open source as possible, given what each dependency allows. This is right now entirely a <em>"project for fun and exploration"</em> with no real constraints. | []
|
https://avatars.githubusercontent.com/u/2286349?v=4 | zig-coreutils | leecannon/zig-coreutils | 2021-08-04T21:10:54Z | A single executable implementation of various coreutils. | master | 1 | 35 | 5 | 35 | https://api.github.com/repos/leecannon/zig-coreutils/tags | MIT | [
"coreutils",
"zig",
"zig-program",
"ziglang"
]
| 570 | false | 2025-05-03T10:54:49Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "tracy",
"tar_url": "https://github.com/Games-by-Mason/tracy_zig/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/Games-by-Mason/tracy_zig"
}
]
| zig-coreutils <a></a>
A single executable implementation of various coreutils.
Compatibility with GNU coreutils is only a nice to have it is not a requirement.
Wherever their options are annoying, force inefficent implementation or are very rarely used then differences are acceptable.
Any tools not in GNU coreutils are acceptable as well.
Progress
Commands completed:
<ul>
<li>basename</li>
<li>clear</li>
<li>dirname</li>
<li>false</li>
<li>groups</li>
<li>nprocs</li>
<li>touch</li>
<li>true</li>
<li>uname</li>
<li>whoami</li>
<li>yes</li>
</ul>
Commands todo:
<ul>
<li>[</li>
<li>b2sum</li>
<li>base32</li>
<li>base64</li>
<li>basenc</li>
<li>cat</li>
<li>chcon</li>
<li>chgrp</li>
<li>chmod</li>
<li>chown</li>
<li>chroot</li>
<li>cksum</li>
<li>comm</li>
<li>cp</li>
<li>csplit</li>
<li>cut</li>
<li>date</li>
<li>dd</li>
<li>df</li>
<li>diff</li>
<li>dir</li>
<li>dircolors</li>
<li>dirname</li>
<li>du</li>
<li>echo</li>
<li>env</li>
<li>expand</li>
<li>expr</li>
<li>factor</li>
<li>false</li>
<li>fmt</li>
<li>fold</li>
<li>hash</li>
<li>head</li>
<li>hostid</li>
<li>id</li>
<li>install</li>
<li>join</li>
<li>link</li>
<li>ln</li>
<li>logname</li>
<li>ls</li>
<li>md5sum</li>
<li>mkdir</li>
<li>mkfifo</li>
<li>mknod</li>
<li>mktemp</li>
<li>mv</li>
<li>nice</li>
<li>nl</li>
<li>nohup</li>
<li>nproc</li>
<li>numfmt</li>
<li>od</li>
<li>paste</li>
<li>patch</li>
<li>pathchk</li>
<li>pinky</li>
<li>pr</li>
<li>printenv</li>
<li>printf</li>
<li>ptx</li>
<li>pwd</li>
<li>readlink</li>
<li>realpath</li>
<li>rm</li>
<li>rmdir</li>
<li>runcon</li>
<li>sed</li>
<li>seq</li>
<li>sha1sum</li>
<li>sha224sum</li>
<li>sha256sum</li>
<li>sha384sum</li>
<li>sha512sum</li>
<li>shred</li>
<li>shuf</li>
<li>sleep</li>
<li>sort</li>
<li>split</li>
<li>stat</li>
<li>stdbuf</li>
<li>stty</li>
<li>sum</li>
<li>sync</li>
<li>tac</li>
<li>tail</li>
<li>tee</li>
<li>test</li>
<li>time</li>
<li>timeout</li>
<li>tr</li>
<li>truncate</li>
<li>tsort</li>
<li>tty</li>
<li>unexpand</li>
<li>uniq</li>
<li>unlink</li>
<li>uptime</li>
<li>users</li>
<li>vdir</li>
<li>wc</li>
<li>who</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/45465154?v=4 | binary-size | ee7/binary-size | 2021-10-19T08:28:08Z | Measuring the size of Nim hello-world executables. This repo was created mainly as a citation for https://nim-lang.org/blog/2022/12/21/version-20-rc.html | main | 2 | 33 | 2 | 33 | https://api.github.com/repos/ee7/binary-size/tags | MIT | [
"clang",
"gcc",
"hello-world",
"musl",
"nim",
"nim-lang",
"zig"
]
| 19 | false | 2025-02-09T11:41:16Z | false | false | unknown | github | []
| Nim binary size
"Hello, World!" binary size in Nim.
Instructions
Run
<code>sh
nim c -r build.nim</code>
which compiles the Nim program
<code>Nim
echo "Hello, World!"</code>
with various sets of compilation options.
Results
| -d:release[^1] | LTO[^2] | strip[^3] | --opt:size[^4] | statically link | Linux | macOS | Windows |
| :------------: | :-----: | :-------: | :----------------: | :------------------- | --------: | --------: | --------: |
| | | | | | 98.2 KiB | 109.4 KiB | 188.7 KiB |
| ✔️ | | | | | 67.3 KiB | 71.7 KiB | 151.5 KiB |
| ✔️ | ✔️ | | | | 39.5 KiB | 67.6 KiB | 132.0 KiB |
| ✔️ | ✔️ | ✔️ | | | 34.5 KiB | 65.1 KiB | 79.5 KiB |
| ✔️ | ✔️ | ✔️ | ✔️ | | 26.5 KiB | 49.1 KiB | 64.0 KiB |
| ✔️ | ✔️ | ✔️ | ✔️ | via <code>musl-gcc</code>[^5] | 30.0 KiB | | |
| ✔️ | ✔️ | ✔️ | ✔️ | via <code>musl-clang</code>[^6] | 30.0 KiB | | |
| ✔️ | ✔️ | ✔️ | ✔️ | via <code>zig cc</code>[^7] | 6.1 KiB | | |
[^1]: Perform a release build: <code>-d:release</code> (the default is a debug build)
[^2]: Enable Link-Time Optimization: <code>--passC:-flto --passL:-flto</code>
[^3]: Remove debug symbols: <code>--passL:-s</code>
[^4]: Optimize for reduced binary size: <code>--opt:size</code> (the default is <code>--opt:speed</code>)
[^5]: Add <code>--cc:gcc --gcc.exe:musl-gcc --gcc.linkerexe:musl-gcc --passL:-static</code>
[^6]: Add <code>--cc:clang --clang.exe:musl-clang --clang.linkerexe:musl-clang --passL:-static</code>
[^7]: Add <code>--panics:on -d:useMalloc --os:any -d:posix -d:noSignalHandler --cc=clang --clang.exe='zigcc' --clang.linkerexe='zigcc' --passC:'-target x86_64-linux-musl' --passL:'-target x86_64-linux-musl'</code>
Details
All results from 2023-03-31 on x86_64 with Nim 2.0 nightly release 2023-03-30 (corresponding to a Nim compiler built from commit <a>nim-lang/Nim@<code>2e4ba4a</code></a>).
Linux
<ul>
<li>Arch Linux</li>
<li>glibc 2.37</li>
<li>gcc 12.2.1</li>
<li>clang 15.0.7</li>
<li>musl 1.2.3</li>
<li>zig 0.10.1</li>
</ul>
macOS
<ul>
<li>macOS 12</li>
<li>clang 14.0.0</li>
</ul>
Windows
<ul>
<li>Windows Server 2022</li>
<li>Mingw-w64 11.2.0</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/2286349?v=4 | zig-libgit2 | leecannon/zig-libgit2 | 2021-08-18T07:08:41Z | Zig bindings to libgit2 | master | 0 | 33 | 6 | 33 | https://api.github.com/repos/leecannon/zig-libgit2/tags | MIT | [
"git",
"libgit2",
"zig",
"zig-library",
"zig-package",
"ziglang"
]
| 882 | false | 2025-03-07T23:30:19Z | true | false | unknown | github | []
| zig-libgit2
Warning
This project is not currently in a good state and is not 100% compatible with any of libgit2's releases.
Work on this project stalled at step one in <a>TODO</a>
Zig bindings to <a>libgit2</a>
This is an in-progress zig binding to libgit2, unfortunately libgit2 doesn't full document all possible errors so every errorable function returns the full errorset.
There is currently no plan to port all the headers within "include/git2/sys", if anyone requires any of that functionailty raise an issue.
Files fully wrapped (others maybe partially complete)
<ul>
<li>[X] annotated_commit.h</li>
<li>[X] apply.h</li>
<li>[X] attr.h</li>
<li>[X] blame.h</li>
<li>[X] blob.h</li>
<li>[X] branch.h</li>
<li>[X] buffer.h</li>
<li>[X] cert.h</li>
<li>[X] checkout.h</li>
<li>[X] cherrypick.h</li>
<li>[X] clone.h</li>
<li>[X] commit.h</li>
<li>[X] common.h</li>
<li>[X] config.h</li>
<li>[X] credential.h</li>
<li>[X] describe.h
<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> diff.h</li>
<li>[X] errors.h</li>
<li>[X] filter.h</li>
<li>[X] global.h</li>
<li>[X] graph.h</li>
<li>[X] ignore.h</li>
<li>[X] index.h</li>
<li>[X] indexer.h</li>
<li>[X] mailmap.h
<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> merge.h</li>
<li>[X] message.h</li>
<li>[X] notes.h</li>
<li>[X] object.h
<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> odb.h</li>
<li>[X] oid.h</li>
<li>[X] oidarray.h</li>
<li>[X] pack.h</li>
<li>[X] patch.h</li>
<li>[X] pathspec.h</li>
<li>[X] proxy.h</li>
<li>[X] rebase.h</li>
<li>[X] refdb.h</li>
<li>[X] reflog.h
<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> refs.h</li>
<li>[X] refspec.h</li>
<li>[X] remote.h</li>
<li>[X] repository.h</li>
<li>[X] reset.h</li>
<li>[X] revert.h</li>
<li>[X] revparse.h</li>
<li>[X] revwalk.h</li>
<li>[X] signature.h</li>
<li>[X] stash.h</li>
<li>[X] status.h</li>
<li>[X] strarray.h
<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> submodule.h</li>
<li>[X] tag.h</li>
<li>[X] trace.h</li>
<li>[X] transaction.h</li>
<li>[X] tree.h</li>
<li>[X] worktree.h</li>
<li>[X] sys/alloc.h</li>
<li>[X] sys/credential.h</li>
<li>[X] sys/diff.h</li>
<li>[X] sys/hashsig.h</li>
<li>[X] sys/path.h</li>
<li>[X] sys/repository.h</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/140233641?v=4 | ydin | kora-org/ydin | 2021-07-20T10:46:21Z | A very extendable and versatile hybrid kernel. | main | 0 | 31 | 0 | 31 | https://api.github.com/repos/kora-org/ydin/tags | MIT | [
"kernel",
"limine",
"osdev",
"zig"
]
| 3,933 | false | 2025-04-23T12:09:38Z | true | true | unknown | github | [
{
"commit": "5883690b9553d4f23e1bb1ab9ee11d7fccac92af",
"name": "limine",
"tar_url": "https://codeberg.org/kora/limine/archive/5883690b9553d4f23e1bb1ab9ee11d7fccac92af.tar.gz",
"type": "remote",
"url": "https://codeberg.org/kora/limine"
},
{
"commit": "v7.8.0-binary",
"name": "limine_bootloader",
"tar_url": "https://github.com/limine-bootloader/limine/archive/v7.8.0-binary.tar.gz",
"type": "remote",
"url": "https://github.com/limine-bootloader/limine"
},
{
"commit": "63051383b51297764a3730a76842a5c0b9a94331",
"name": "uacpi",
"tar_url": "https://github.com/UltraOS/uACPI/archive/63051383b51297764a3730a76842a5c0b9a94331.tar.gz",
"type": "remote",
"url": "https://github.com/UltraOS/uACPI"
}
]
| Ydin
A very extendable and versatile hybrid kernel. Part of the Kora operating system. | []
|
https://avatars.githubusercontent.com/u/65570835?v=4 | ini | ziglibs/ini | 2021-04-07T08:58:07Z | A teeny tiny ini parser | master | 0 | 31 | 5 | 31 | https://api.github.com/repos/ziglibs/ini/tags | MIT | [
"ini",
"ini-parser",
"zig",
"zig-package",
"ziglang"
]
| 23 | false | 2025-05-21T02:52:54Z | true | true | 0.14.0 | github | []
| INI parser library
This is a very simple ini-parser library that provides:
- Raw record reading
- Leading/trailing whitespace removal
- Comments
- Zig API
- C API
Usage example
Zig
```zig
const std = @import("std");
const ini = @import("ini");
pub fn main() !void {
const file = try std.fs.cwd().openFile("example.ini", .{});
defer file.close();
<code>var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer if (gpa.deinit() != .ok) @panic("memory leaked");
var parser = ini.parse(gpa.allocator(), file.reader(), ";#");
defer parser.deinit();
var writer = std.io.getStdOut().writer();
while (try parser.next()) |record| {
switch (record) {
.section => |heading| try writer.print("[{s}]\n", .{heading}),
.property => |kv| try writer.print("{s} = {s}\n", .{ kv.key, kv.value }),
.enumeration => |value| try writer.print("{s}\n", .{value}),
}
}
</code>
}
```
C
```c
include
include
include
int main() {
FILE * f = fopen("example.ini", "rb");
if(!f)
return 1;
struct ini_Parser parser;
ini_create_file(&parser, f, ";#", 2);
struct ini_Record record;
while(true)
{
enum ini_Error error = ini_next(&parser, &record);
if(error != INI_SUCCESS)
goto cleanup;
<code>switch(record.type) {
case INI_RECORD_NUL: goto done;
case INI_RECORD_SECTION:
printf("[%s]\n", record.section);
break;
case INI_RECORD_PROPERTY:
printf("%s = %s\n", record.property.key, record.property.value);
break;
case INI_RECORD_ENUMERATION:
printf("%s\n", record.enumeration);
break;
}
</code>
}
done:
cleanup:
ini_destroy(&parser);
fclose(f);
return 0;
}
``` | [
"https://github.com/AnErrupTion/ZigEmu",
"https://github.com/liskvork/liskvork"
]
|
https://avatars.githubusercontent.com/u/65570835?v=4 | zig-lv2 | ziglibs/zig-lv2 | 2021-03-12T01:49:18Z | Zig-intuitive bindings for LV2. | main | 1 | 31 | 0 | 31 | https://api.github.com/repos/ziglibs/zig-lv2/tags | - | [
"lv2",
"zig",
"zig-lv2",
"zig-package",
"ziglang"
]
| 52 | false | 2024-12-27T23:52:06Z | true | false | unknown | github | []
| zig-lv2
A toolkit for LV2 plugin authors written in Zig.
<strong>WARNING: Here be dragons; tons of LV2 features aren't implemented and this isn't ready for production at all.</strong>
Installing
<code>bash
git clone --recurse-submodules https://github.com/ziglibs/zig-lv2</code>
Getting Started
Check out the example in <code>examples</code> which contains both sample Zig code as well as its corresponding Turtle manifest. | []
|
https://avatars.githubusercontent.com/u/80545079?v=4 | Alka | MeKaLu/Alka | 2021-05-12T14:39:30Z | Simple, fast, easy to get started mid-level game engine written in Zig | master | 4 | 30 | 1 | 30 | https://api.github.com/repos/MeKaLu/Alka/tags | NOASSERTION | [
"game-development",
"game-engine",
"open-source",
"zig"
]
| 3,146 | false | 2024-08-27T02:40:57Z | true | false | unknown | github | []
| Alka
Game engine written in zig, compatible with <strong>zig version 0.8.0</strong>.
This engine does provide a toolset for you but generally you have to implement how they work and how should be.
For example if you want to use <code>GUI</code>, well you can and engine provides a tool for you but you have to implement how
<code>elements</code> behave, draw, etc. There is no <code>ButtonElement</code> or <code>TextBox</code>, only <code>Element</code>. Same goes for the <code>ECS</code> too.
You may need these packages to compile the engine(tested on ubuntu 21.04)
<code>libx11-dev libxcursor-dev libxrandr-dev libxinerama-dev libxi-dev libgl-dev</code>
Get started <a>now</a>
<a>Documentation</a>
Project goals
<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> Single window operations
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Input management
<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> Asset manager
<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> Custom batch 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> 2D Camera
- [X] 2D Shape drawing
<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> 2D Texture drawing
<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> 2D Text drawing
<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> Simple ecs
<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> Simple 2D lightning
<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> Simple 2D physics
<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> GUI system
<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> Audio
<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> Optional: Data packer
<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> Optional: Scripting language
<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> Optional: Vulkan implementation
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Optional: Android support
About release cycle
<ul>
<li>Versioning: major.minor.patch</li>
<li>Every x.x.3 creates a new minor, which becomes x.(x + 1).0</li>
<li>Again every x.3.x creates a new major, which becomes (x + 1).0.x</li>
<li>When a new version comes, it'll comitted as x.x.x source update</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/9265556?v=4 | zig-postgres | tonis2/zig-postgres | 2021-02-14T13:25:12Z | Zig wrapper for postgres | main | 1 | 30 | 8 | 30 | https://api.github.com/repos/tonis2/zig-postgres/tags | Apache-2.0 | [
"binding",
"postgres",
"zig"
]
| 150 | false | 2025-04-16T09:00:00Z | true | false | unknown | github | []
| zig-postgres
Light bindings around Postgres <code>libpq</code>
This is tested with zig <code>0.8</code>
Installing <code>libpg</code> on debian linux
<code>sudo apt-get install libpq-dev</code>
How to install
Add this repository as submodule
<code>git submodule add [email protected]:tonis2/zig-postgres.git dependencies/zig-postgres</code>
Add following code lines into your project <code>build.zig</code>
This code adds the package and links required libraries.
<code>zig
exe.addPackage(.{ .name = "postgres", .path = "/dependencies/zig-postgres/src/postgres.zig" });
exe.linkSystemLibrary("c");
exe.linkSystemLibrary("libpq");</code>
Running examples or tests requires <code>db</code> url attribute, for example
<code>zig build test -Ddb=postgresql://db_url</code>
<code>zig build main -Ddb=postgresql://db_url</code>
How to use
Connecting to database
```zig
const Pg = @import("postgres").Pg;
<code>var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
defer std.debug.assert(!gpa.deinit());
var db = try Pg.connect(allocator, "postgresql://root@postgresURL:26257?sslmode=disable");
</code>
```
Executing SQL
```zig
const schema =
\CREATE DATABASE IF NOT EXISTS root;
\CREATE TABLE IF NOT EXISTS users (id INT, name TEXT, age INT);
;
<code>_ = try db.exec(schema);
</code>
```
Inserting data
Be mindful that this query, uses <code>struct name</code> as lowercase letters for <code>table</code> name.
```zig
const Users = struct {
id: i16,
name: []const u8,
age: i16,
};
_ = try db.insert(Users{ .id = 1, .name = "Charlie", .age = 20 });
_ = try db.insert(Users{ .id = 2, .name = "Steve", .age = 25 });
_ = try db.insert(Users{ .id = 3, .name = "Karl", .age = 25 });
_ = try db.insert(&[_]Users{
Users{ .id = 4, .name = "Tony", .age = 25 },
Users{ .id = 5, .name = "Sara", .age = 32 },
Users{ .id = 6, .name = "Fred", .age = 11 },
});
```
Exec query with values
```zig
_ = try db.execValues("SELECT * FROM users WHERE name = {s}", .{"Charlie"});
_ = try db.execValues("INSERT INTO users (id, name, age) VALUES ({d}, {s}, {d})", .{ 5, "Tom", 32 });
```
Read query results
```zig
var result = try db.execValues("SELECT * FROM users WHERE id = {d}", .{2});
var user = result.parse(Users, null).?;
print("{d} \n", .{user.id});
print("{s} \n", .{user.name});
```
```zig
var results = try db.execValues("SELECT * FROM users WHERE age = {d}", .{25});
while (results.parse(Users, null)) |user| {
print("{s} \n", .{user.name});
}
```
```zig
var result = try db.execValues("SELECT * FROM users WHERE name = {s}", .{"Charlie"});
var user = result.parse(Users, null}).?;
if(user) print("{s} \n", .{user.name});
```
Many thanks for this <a>repository</a> | []
|
https://avatars.githubusercontent.com/u/4250341?v=4 | slingworks | JonSnowbd/slingworks | 2021-09-07T10:46:28Z | Small to Medium scale 2d Game Engine for Zig | main | 0 | 27 | 2 | 27 | https://api.github.com/repos/JonSnowbd/slingworks/tags | MIT | [
"game-engine",
"gamedev",
"zig"
]
| 18,395 | false | 2025-05-09T06:05:43Z | true | false | unknown | github | []
|
Slingworks 0.2
A simple and powerful Windows+Linux 'bring your content' engine
built in Zig and powered by GLFW/OpenGL/ImGui.
Slingworks makes no assumptions about your games content and
instead offers a framework to organize your code into simple
and fast scenes and entity collections, all with an embedded
runtime editor and powered by flexible serialization!
Slingworks is aimed at small to medium scale 2d projects that want to allow
the fanbase to create and contribute to the game as easily as developers do.
Whats missing?
Right now there are several pieces of Slingwork missing or lacking polish:
<ul>
<li>Services</li>
<li>Gamepad support</li>
<li>Linux support</li>
</ul>
Platform support
For now Slingworks is very early work in progress and supports Windows,
but it is very likely to be just 10-20 minutes of work to get working
on linux.
Dependencies
Windows:
- <a>FMod Audio, Core and Studio APIs installed</a>
Linux: (wip)
- <a>FMod Audio, Core and Studio APIs installed</a>
- <code>sudo apt install build-essential xorg-dev</code>
Getting Started
Check out the <a>wiki</a> for installation and
beginner guides to how Slingworks is used.
Wheres the example?
Check out the open source full game in development that will serve as the all encompassing example
for slingworks, named <a>Underburrow</a>!
Or for more directed advice and tutorials check out the <a>wiki</a>
My built game requested local network permissions?
This is because debug builds initialize FMod Studio with net connection
for live audio authoring.
My game crashes trying to de/serialize something?
The serializer should handle every reasonable type including basic
array lists and string hashmaps, but it is unavoidable to crash if you
attempted to serialize untagged unions, opaque, or packed types in your entities.
Credits
Thanks to <a>fontawesome</a> for being a great, lean, embeddable icon font included with the editor
to make the UI as clear as it could be. | []
|
https://avatars.githubusercontent.com/u/84904715?v=4 | wasm-zig | zigwasm/wasm-zig | 2021-05-26T07:47:12Z | Common Wasm runtime binding to C API | main | 2 | 27 | 7 | 27 | https://api.github.com/repos/zigwasm/wasm-zig/tags | MIT | [
"c-api",
"wasi",
"wasm",
"zig",
"zig-library"
]
| 14 | false | 2024-08-19T04:29:07Z | true | false | unknown | github | []
| wasm-zig
Common Wasm runtime bindings to C API.
This library is intended to be used in conjunction with some runtime-specific bindings such
as <a>wasmer-zig</a> or <a>wasmtime-zig</a>.
To add this library as your dependency, we strongly recommend <a>gyro</a>. | []
|
https://avatars.githubusercontent.com/u/893531?v=4 | VecFns | omaraaa/VecFns | 2021-12-22T12:14:36Z | Automatic Vector Math Functions In Zig | main | 0 | 26 | 3 | 26 | https://api.github.com/repos/omaraaa/VecFns/tags | MIT-0 | [
"gamedev",
"library",
"math",
"zig"
]
| 42 | false | 2025-04-22T20:52:14Z | false | false | unknown | github | []
| VecFns
Automatic vector math functions for your vector structs.
Usage
Just add <code>VecFns</code> with <code>usingnamespace</code> to your struct, you will get the usual math functions for your vector. All fields of the struct should be the same type, and also be numeric.
```zig
const VecFns = @import("./vec_fns.zig").VecFns;
const MyVec = struct {
pub usingnamespace VecFns(@This());
a: i32,
b: i32,
c: i32
};
const Vec2f = struct {
pub usingnamespace VecFns(@This());
x: f64,
y: f64,
};
```
Functions
The following functions will be in the namespace of your struct type after including <code>VecFns</code>.
<code>``zig
// Applies a function</code>f<code>to the vector.</code>args<code>is any additional arguments to be passed to</code>f`.
fn map(self: Self, comptime f: anytype, args: anytype) Self
// Same as <code>map</code> but without args argument.
fn apply(self: Self, comptime f: anytype) Self
// Applies a function <code>f</code> to 2 vectors.
fn map2(a: anytype, b: anytype, comptime f: anytype, args: anytype) Self
// Same as <code>map</code>, reduces the vector into a single value.
fn reduce(self: Self, comptime f: anytype, args: anytype) T
// Adds either 2 vectors or a vector and a scalar value.
fn add(self: Self, other: anytype) Self
// Subtracts either 2 vectors or a vector and a scalar value.
fn sub(self: Self, other: anytype) Self
// Multiplies either 2 vectors or a vector and a scalar value.
fn mul(self: Self, other: anytype) Self
// Divides either 2 vectors or a vector and a scalar value.
fn div(self: Self, other: anytype) Self
// Same as div, but uses <code>@divExact</code>
fn divExact(self: Self, other: anytype) Self
// Same as div, but uses <code>@divFloor</code>
fn divFloor(self: Self, other: anytype) Self
// Returns the sum of the vector.
fn sum(self: Self) T
// Given 2 vectors or a vector and a scalar value, returns a vector with the maximum between the 2.
fn max(self: Self, other: Self) Self
// Given 2 vectors or a vector and a scalar value, returns a vector with the minimum between the 2.
fn min(self: Self, other: Self) Self
// Checks if the vector is equal to <code>other</code> (can be a vector or a scalar)
fn eq(self: Self, other: anytype) bool
// Attempts to covert/cast the vector into another vector type.
fn into(self: Self, comptime VType: type) VType
// Joins two vector into a vector size 2*N.
fn join(self: Self, other: Self) [2 * N]T
// Returns the zero vector.
fn zero() Self
// Returns a vector where all values are <code>n</code>.
fn all(n: anytype) Self
// Coverts the vector into an array of type <code>[N]T</code>.
fn toArray(self: Self) [N]T
// Create a vector from an array.
fn fromArray(array: [N]T) Self
// Length of the vector. (Float only)
fn len(self: Self) T
// Distance between 2 vectors. (Float only)
fn distance(self: Self, other: anytype) T
// Normalizes the vector values to [0, 1]. (Float only)
fn norm(self: Self) Self | []
|
https://avatars.githubusercontent.com/u/3718227?v=4 | wasm-4-tutorial-games | christopher-kleine/wasm-4-tutorial-games | 2021-11-11T12:14:03Z | A collection of small games for the Fantasy Console WASM-4 | main | 2 | 25 | 9 | 25 | https://api.github.com/repos/christopher-kleine/wasm-4-tutorial-games/tags | - | [
"assemblyscript",
"c",
"dlang",
"fantasy-console",
"game",
"game-development",
"gamedev",
"games",
"go",
"golang",
"lua",
"nelua",
"retrogaming",
"rust",
"snake",
"snake-game",
"tutorial",
"wasm",
"webassembly",
"zig"
]
| 89 | false | 2025-04-10T07:26:39Z | false | false | unknown | github | []
| WASM-4 Tutorial Games
This repo contains the source code for different tutorial games for the Fantasy Console <a>WASM-4</a>.
The goal is to provide a one-stop-repo for all tutorials hosted on the WASM-4 website.
Snake
A famous game that can be implemented in pretty much any language, engine of framework.
It's currently implemented in:
<ul>
<li><a>AssenblyScript</a></li>
<li><a>C</a></li>
<li><a>D</a></li>
<li><a>Go</a></li>
<li><a>Nelua</a></li>
<li><a>Odin</a></li>
<li><a>Rust</a></li>
<li><a>Zig</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/1519747?v=4 | zelf | kubkon/zelf | 2021-09-14T17:06:40Z | Zig's ELF parser utility | main | 2 | 24 | 3 | 24 | https://api.github.com/repos/kubkon/zelf/tags | MIT | [
"elf",
"zig",
"zig-package"
]
| 111 | false | 2025-05-16T00:27:52Z | true | false | unknown | github | []
| zelf
Zig's ELF parsing utility - a replacement (maybe someday) utility for <code>readelf</code> written in Zig.
Usage
```
Usage: zelf [options] file
General Options:
-a, --all Equivalent of having all flags on
-g, --section-groups Display the section groups
-h, --file-header Display ELF file header
-l, --program-headers Display program headers (if present)
-S, --section-headers Display section headers
-s, --symbols Display symbol table
--dyn-syms Display the dynamic symbol table
-r, --relocs Display relocations (if present)
-d, --dynamic Display the dynamic section (if present)
--initializers Display table(s) of initializers/finalizers (if present)
-p, --string-dump= Dump the contents of section as strings
-V, --version-info Display the version sections (if present)
-W, --wide Do not shorten the names if too wide
-x, --hex-dump= Dump the contents of section as bytes
--help Display this help and exit
```
Currently supported flags. More to come.
Typical output will look something like this.
```
<blockquote>
zelf -a main.o
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: REL (Relocatable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x0
Start of program headers: 0 (bytes into file)
Start of section headers: 28208 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 0 (bytes)
Number of program headers: 0
Size of section headers: 64 (bytes)
Number of section headers: 23
Section header string table index: 22
</blockquote>
There are 23 section headers, starting at offset 0x6e30:
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
[ 0] NULL 0000000000000000 0000000000000000
0000000000000000 0000000000000000 0 0 0
[ 1] .note.gnu.pr[..] NOTE 0000000000000000 0000000000000040
0000000000000040 0000000000000000 A 0 0 8
[ 2] .note.ABI-tag NOTE 0000000000000000 0000000000000080
0000000000000020 0000000000000000 A 0 0 4
[ 3] .text PROGBITS 0000000000000000 00000000000000a0
0000000000000031 0000000000000000 AX 0 0 16
[ 4] .rela.text RELA 0000000000000000 0000000000000480
0000000000000030 0000000000000018 I 20 3 8
[ 5] .rodata.cst4 PROGBITS 0000000000000000 00000000000000d4
0000000000000004 0000000000000004 AM 0 0 4
[ 6] .eh_frame PROGBITS 0000000000000000 00000000000000d8
000000000000005c 0000000000000000 A 0 0 8
[ 7] .rela.eh_frame RELA 0000000000000000 00000000000004b0
0000000000000030 0000000000000018 I 20 6 8
[ 8] .data PROGBITS 0000000000000000 0000000000000134
0000000000000004 0000000000000000 WA 0 0 1
[ 9] .bss NOBITS 0000000000000000 0000000000000138
0000000000000000 0000000000000000 WA 0 0 1
[10] .comment PROGBITS 0000000000000000 0000000000000138
0000000000000036 0000000000000001 MS 0 0 1
[11] .note.GNU-stack PROGBITS 0000000000000000 000000000000016e
0000000000000000 0000000000000000 0 0 1
[12] .debug_aranges PROGBITS 0000000000000000 00000000000004e0
000000000000003b 0000000000000000 C 0 0 8
[13] .rela.debug_[..] RELA 0000000000000000 0000000000000520
0000000000000090 0000000000000018 I 20 12 8
[14] .debug_info PROGBITS 0000000000000000 00000000000005b0
00000000000013c4 0000000000000000 C 0 0 8
[15] .rela.debug_info RELA 0000000000000000 0000000000001978
00000000000041d0 0000000000000018 I 20 14 8
[16] .debug_abbrev PROGBITS 0000000000000000 0000000000005b48
00000000000001ac 0000000000000000 C 0 0 8
[17] .debug_line PROGBITS 0000000000000000 0000000000005cf8
0000000000000313 0000000000000000 C 0 0 8
[18] .rela.debug_line RELA 0000000000000000 0000000000006010
0000000000000030 0000000000000018 I 20 17 8
[19] .debug_str PROGBITS 0000000000000000 0000000000006040
0000000000000d1a 0000000000000001 MSC 0 0 8
[20] .symtab SYMTAB 0000000000000000 0000000000000170
0000000000000288 0000000000000018 21 19 8
[21] .strtab STRTAB 0000000000000000 00000000000003f8
0000000000000088 0000000000000000 0 0 1
[22] .shstrtab STRTAB 0000000000000000 0000000000006d5a
00000000000000d6 0000000000000000 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
D (mbind), l (large), p (processor specific)
There are no program headers in this file.
Relocation section '.rela.text' at offset 0x480 contains 2 entries:
Offset Info Type Sym. Value Sym. Name + Addend
000000000017 00150000002a R_X86_64_REX_GOTPCRELX 0000000000000000 main - 4
00000000001d 001900000029 R_X86_64_GOTPCRELX 0000000000000000 __libc_start_main - 4
Relocation section '.rela.eh_frame' at offset 0x4b0 contains 2 entries:
Offset Info Type Sym. Value Sym. Name + Addend
000000000020 000300000002 R_X86_64_PC32 0000000000000000 .text + 0
000000000050 000300000002 R_X86_64_PC32 0000000000000000 .text + 30
Relocation section '.rela.debug_aranges' at offset 0x520 contains 6 entries:
Offset Info Type Sym. Value Sym. Name + Addend
000000000006 000b0000000a R_X86_64_32 0000000000000000 .debug_info + 0
000000000010 000300000001 R_X86_64_64 0000000000000000 .text + 0
000000000036 000b0000000a R_X86_64_32 0000000000000000 .debug_info + 2e
000000000056 000b0000000a R_X86_64_32 0000000000000000 .debug_info + af4
000000000076 000b0000000a R_X86_64_32 0000000000000000 .debug_info + b34
000000000080 000300000001 R_X86_64_64 0000000000000000 .text + 30
Symbol table '.symtab' contains 27 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000000000 0 SECTION LOCAL DEFAULT 1
2: 0000000000000000 0 SECTION LOCAL DEFAULT 2
3: 0000000000000000 0 SECTION LOCAL DEFAULT 3
4: 0000000000000000 0 SECTION LOCAL DEFAULT 5
5: 0000000000000000 0 SECTION LOCAL DEFAULT 6
6: 0000000000000000 0 SECTION LOCAL DEFAULT 8
7: 0000000000000000 0 SECTION LOCAL DEFAULT 9
8: 0000000000000000 0 SECTION LOCAL DEFAULT 10
9: 0000000000000000 0 SECTION LOCAL DEFAULT 11
10: 0000000000000000 0 SECTION LOCAL DEFAULT 12
11: 0000000000000000 0 SECTION LOCAL DEFAULT 14
12: 0000000000000000 0 SECTION LOCAL DEFAULT 16
13: 0000000000000000 0 SECTION LOCAL DEFAULT 17
14: 0000000000000000 0 SECTION LOCAL DEFAULT 19
15: 0000000000000000 0 FILE LOCAL DEFAULT ABS abi-note.c
16: 0000000000000000 32 OBJECT LOCAL DEFAULT 2 __abi_tag
17: 0000000000000000 0 FILE LOCAL DEFAULT ABS init.c
18: 0000000000000000 0 FILE LOCAL DEFAULT ABS static-reloc.c
19: 0000000000000030 1 FUNC GLOBAL UNKNOWN 3 <em>dl_relocate_static_pie
20: 0000000000000000 34 FUNC GLOBAL DEFAULT 3 _start
21: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND main
22: 0000000000000000 0 NOTYPE WEAK DEFAULT 8 data_start
23: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _GLOBAL_OFFSET_TABLE</em>
24: 0000000000000000 4 OBJECT GLOBAL DEFAULT 5 _IO_stdin_used
25: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND __libc_start_main
26: 0000000000000000 0 NOTYPE GLOBAL DEFAULT 8 __data_start
``` | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-inquirer | nektro/zig-inquirer | 2021-07-29T10:59:26Z | A collection of utilities for prompting information from the user on the CLI | master | 1 | 24 | 2 | 24 | https://api.github.com/repos/nektro/zig-inquirer/tags | MIT | [
"zig",
"zig-package"
]
| 17 | false | 2025-05-21T20:33:36Z | true | false | unknown | github | []
| zig-inquirer
<a></a>
<a></a>
<a></a>
<a></a>
A collection of utilities for prompting information from the user on the CLI
Adapted from https://github.com/SBoudrias/Inquirer.js
Run example
<code>zig build run</code>
Screenshots
Usage
<ul>
<li><code>pub fn answer(writer, reader, comptime prompt: []const u8, value: []const u8) []const u8</code><ul>
<li>Prints just the done string.</li>
</ul>
</li>
<li><code>pub fn forEnum(writer, reader, comptime prompt: []const u8, alloc: *std.mem.Allocator, comptime options: enum, default: ?options) !options</code><ul>
<li>Accepts an enum and prompts the user to pick on of the fields.</li>
</ul>
</li>
<li><code>pub fn forString(writer, reader, comptime prompt: []const u8, alloc: *std.mem.Allocator, default: ?[]const u8) ![]const u8</code><ul>
<li>Base function, asks prompt and returns non-empty answer.</li>
</ul>
</li>
<li><code>pub fn forConfirm(writer, reader, comptime prompt: []const u8, alloc: *std.mem.Allocator) !bool</code><ul>
<li>Calls <code>forEnum</code> with <code>y/n</code></li>
</ul>
</li>
</ul>
TODO
<ul>
<li>number (current implementation causes compiler crash)</li>
<li>list with strings</li>
<li>string password</li>
<li>long list with autocomplete</li>
<li>date</li>
<li>time</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/86482337?v=4 | cf | zig-java/cf | 2021-08-26T04:23:30Z | Java class file parser for Zig | main | 0 | 24 | 9 | 24 | https://api.github.com/repos/zig-java/cf/tags | MIT | [
"classfile",
"classfile-parser",
"java",
"zig"
]
| 128 | false | 2024-08-04T01:23:21Z | true | false | unknown | github | []
| cf
Java <code>.class</code> file parser for Zig. Mainly extracted from <a>jaz</a>.
Tests
<code>bash
javac test/*.java
zig test cf.zig</code>
Usage
Take a look at tests in <code>src</code> to get a sense of how to use <code>cf</code>! To actually integrate it in your application, reference <code>cf.zig</code> in your <code>build.zig</code> and enjoy. :) | []
|
https://avatars.githubusercontent.com/u/27897469?v=4 | vite-plugin-zig | pluvial/vite-plugin-zig | 2022-02-01T14:05:44Z | Import Wasm modules compiled from Zig files | main | 0 | 24 | 2 | 24 | https://api.github.com/repos/pluvial/vite-plugin-zig/tags | MIT | [
"rollup",
"rollup-plugin",
"vite-plugin",
"vitejs",
"wasm",
"zig",
"ziglang"
]
| 99 | false | 2024-11-29T00:44:28Z | false | false | unknown | github | []
| vite-plugin-zig
Import WebAssembly modules compiled from Zig files.
Prerequisites
<ul>
<li>Install the <a>Zig compiler</a>: the binary can be downloaded from <a>downloads page</a>, or built from source by following the <a>GitHub Wiki instructions</a>, or using the <a>zig-bootstrap</a> scripts. As an alternative, the <a><code>@ziglang/cli</code></a> npm package can be added as a dependency, useful in a CI environment for instance.</li>
</ul>
Usage
Install with <code>npm i -D vite-plugin-zig</code> (or <code>pnpm i -D</code> or <code>yarn i -D</code>), then add the plugin to your <code>vite.config.js</code>:
```js
// vite.config.js
import zig from 'vite-plugin-zig';
/*<em> @type {import('vite').UserConfig} </em>/
export default {
plugins: [zig()],
build: { target: 'esnext' },
};
```
Write your Zig code and <code>export</code> any symbol to be used in JS code:
<code>zig
// src/main.zig
export fn add(a: i32, b: i32) i32 {
return a + b;
}</code>
If available, top-level await can be used so that importing the module feels similar to importing a regular JS module:
```js
// example.js
import { instantiate } from './src/main.zig';
// pass any custom importObject here, functions should be declared
// as extern in the Zig file
const importObject = {
// ...
};
// instantiate the compiled WebAssembly module, can also be moved
// to a Worker for instantiation in another thread
const { exports, instance } = await instantiate(importObject);
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
```
As a shorthand to avoid having to manually call <code>await instantiate()</code>, the <code>?instantiate</code> query parameter can be specified in the module import to both compile and instantiate the module at import time, allowing access to <code>instance</code> and <code>exports</code>:
```js
import { exports, instance, module } from './src/main.zig?instantiate';
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
```
If your Vite config does not allow for top-level await (by setting <code>build: { target: 'esnext' }</code>, e.g. if the framework you're using enforces a specific target value), an alternative API is provided which instead exposes Promises (<code>compiled</code> and <code>instantiated</code> respectively depending on whether <code>?instantiate</code> is used) which resolve when the compilation or instantiation of the module are complete:
```js
// example.js
import { compiled, instantiate, module } from './src/main.zig';
(async () => {
// <code>await compiled</code> can be used to populate the <code>module</code> import
// manually before instantiation if necessary
// pass any custom importObject here, functions should be declared
// as extern in the Zig file
const importObject = {
// ...
};
// instantiate the compiled WebAssembly module, can also be moved
// to a Worker for instantiation in another thread
const { exports, instance } = await instantiate(importObject);
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
})();
```
```js
// example.js
import {
exports,
instance,
instantiated,
module,
} from './src/main.zig?instantiate';
(async () => {
// manually await to populate the imports
await instantiated;
// call exported functions from the exports object
console.log(exports.add(5, 37)); // 42
})();
```
To integrate with SSR frameworks such as SvelteKit, use a dynamic import:
```svelte
import { onMount } from 'svelte';
onMount(async () => {
const wasm = await import('$lib/main.zig?instantiate');
await wasm.instantiated;
console.log(wasm.exports.add(5, 37)); // 42
});
```
Notes and TODOs
<ul>
<li>It would be great to have something similar to Rust's <code>wasm-bindgen</code> to generate JS glue code and type definitions</li>
</ul>
License
<a>MIT</a> | []
|
https://avatars.githubusercontent.com/u/4252848?v=4 | feilich | Luukdegram/feilich | 2021-07-03T13:29:41Z | Small, no dependency, TLS 1.3 implementation in Zig, for Zig. | master | 1 | 24 | 2 | 24 | https://api.github.com/repos/Luukdegram/feilich/tags | - | [
"security",
"tls",
"tls13",
"web",
"zig",
"ziglang"
]
| 280 | false | 2024-08-30T14:31:25Z | true | false | unknown | github | []
| Feilich
Feilich is a TLS 1.3 implementation in <a>zig</a>. Zig has a great async model, allowing users to write concurrent programs.
However, most TLS libraries are written in C. Unfortunately, most of those libraries do not work well (or at all) with Zig's async.
Zig also produces small binaries as well has remarkable freestanding support. This, together with explicit allocators, allows us
to produce a library that also works for kernels and embedded devices. For those reasons, and the fact I've been wanting to
learn more about how TLS works, have made me decide to write this library.
The initial goal is to implement the server side of TLS 1.3 to make it work with my Gemini library <a>lemon_pie</a>.
This is a great usecase as Gemini's specification requires the usage of TLS. As the usage of TLS 1.3 is not yet very widespread and many
libraries not offering full support for it yet, I do very much want to implement the client side of TLS 1.3 also.
TLS 1.2 is not a goal as we already have a great TLS 1.2 library for zig called <a>iguanaTLS</a>.
Although it currently only supports client side, we could perhaps PR server support in the future.
Project status
The project is currently on-hold until I have more free time to work on this besides the self-hosted compiler for the Zig programming language.
I'd like to bring this project to the point where it's fully operational for a single cipher suite. From there on, it should be fairly straight
forward to implement more suites as well as other crypto algorithms supported by TLS 1.3.
I expect to be able to continue and get it to that state Q3/Q4 of this year. Until then, this project will be stale.
Should I use this?
Maybe? I have no prior experience with TLS, nor am I some crypto expert. TLS contains some known <a>implementation pitfalls</a>,
and can be quite complex to implement correctly. For those reasons alone I cannot recommend to use this library outside experimental, hobby usage.
It would be great to bring this library to a state where others and I could recommend its usage, tho I'm not sure that is possible with my lack
of knowledge and experience in this area. | []
|
https://avatars.githubusercontent.com/u/61933599?v=4 | tuatara | q60/tuatara | 2021-09-01T19:31:39Z | Ziggidy *nix system info fetcher. WIP. | main | 0 | 24 | 0 | 24 | https://api.github.com/repos/q60/tuatara/tags | Unlicense | [
"fetch",
"info",
"neofetch",
"pfetch",
"system",
"system-info",
"zig",
"zig-lang",
"zig-programming-language",
"ziglang"
]
| 57 | false | 2025-04-29T17:26:01Z | true | false | unknown | github | []
| tuatara
<strong>tuatara</strong> is <a>ziggidy</a> <strong>*nix</strong> system info fetcher. WIP.
it is descendant of <a>disfetch</a>, although sharing some common concepts and principles, they are different.
the main difference of <strong>tuatara</strong> from <strong>disfetch</strong> is that tuatara will be highly customizable, while disfetch won't, because it covers minimalism and simplicity. though, they will share some other principles regarding showing only needed information, being fast and reliable and sharing the same handmade logos with the principle of <em>not-more-or-less-than</em> 8 rows.
Wikipedia says: “<strong>Tuatara</strong> are <a>reptiles</a> <a>endemic</a> to <a>New Zealand</a>, belonging to the <a>genus</a> <strong><em>Sphenodon</em></strong>. Although resembling most <a>lizards</a>, they are part of a distinct lineage, the order <a>Rhynchocephalia</a>. Their name derives from the <a>Māori language</a>, and means ‘peaks on the back’”.
<em>stay moist, stay ziguana, use tuatara</em>
Examples
| []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-ulid | nektro/zig-ulid | 2021-10-08T02:32:39Z | A binary implementation of ULID in Zig. | master | 1 | 23 | 1 | 23 | https://api.github.com/repos/nektro/zig-ulid/tags | MIT | [
"ulid",
"zig",
"zig-package"
]
| 21 | false | 2025-05-21T20:33:26Z | true | false | unknown | github | []
| zig-ulid
<a></a>
<a></a>
<a></a>
<a></a>
A binary implementation of ULID in Zig.
https://github.com/ulid/spec | []
|
https://avatars.githubusercontent.com/u/22148308?v=4 | zig-objcrt | hazeycode/zig-objcrt | 2022-01-21T23:02:29Z | Objective-C Runtime bindings for Zig | main | 3 | 23 | 3 | 23 | https://api.github.com/repos/hazeycode/zig-objcrt/tags | 0BSD | [
"bindings",
"objective-c",
"wrapper",
"zig"
]
| 64 | false | 2025-04-07T08:47:11Z | true | false | unknown | github | []
| zig-objcrt
Objective-C Runtime bindings for Zig..
<strong>NOTE:</strong> I don't have any plans to work on this within the near future. Archiving for reference.
Provides thin API bindings with a little added type-safety and error handling
Also provides higher-level wrappers to make working with the objc runtime a little bit nicer
<strong>NOTE:</strong> This is for working with the runtime API, user-friendly bindings to Apple Frameworks are not provided by this library but may be built on top. For bindings to Apple's C libraries, see https://github.com/kubkon/ZigKit
<strong>WARNING:</strong> In early development. Does not yet have full API coverage and needs more testing. The higher-level APIs, i.e. <code>defineAndRegisterClass</code> are very WIP as there are some things to be worked out regarding memory management. Open to suggestions and issues and PRs are most welcome.
<strong>NOTE:</strong> Currently uses translate-c on the objective-c headers that are vendored with Zig. It's perhaps better not to rely on these and replace with extern definitions?
Example usage
```zig
const objc = @import("zig-objcrt");
const NSInteger = c_long;
const NSApplicationActivationPolicyRegular: NSInteger = 0;
var application: objc.id = undefined;
pub fn main() anyerror!void {
const NSObject = try objc.getClass("NSObject");
const NSApplication = try objc.getClass("NSApplication");
<code>application = try objc.msgSendByName(objc.id, NSApplication, "sharedApplication", .{});
const AppDelegate = try objc.defineAndRegisterClass(
"AppDelegate",
NSObject,
.{},
.{
.{ "applicationDidFinishLaunching:", applicationDidFinishLaunching },
},
);
const app_delegate = try objc.new(AppDelegate);
try objc.msgSendByName(void, application, "setDelegate:", .{app_delegate});
try objc.msgSendByName(void, application, "run", .{});
</code>
}
pub fn applicationDidFinishLaunching(<em>: objc.id, </em>: objc.SEL, _: objc.id) callconv(.C) void {
objc.msgSendByName(void, application, "setActivationPolicy:", .{NSApplicationActivationPolicyRegular}) catch unreachable;
<code>objc.msgSendByName(void, application, "activateIgnoringOtherApps:", .{true}) catch unreachable;
std.debug.print("Hello from Objective-C!\n", .{});
</code>
}
``` | []
|
https://avatars.githubusercontent.com/u/8965202?v=4 | fzy.zig | gpanders/fzy.zig | 2021-11-07T18:03:09Z | Rewrite of fzy in Zig (mirror) | master | 1 | 23 | 0 | 23 | https://api.github.com/repos/gpanders/fzy.zig/tags | MIT | [
"zig"
]
| 67 | false | 2025-05-16T00:21:47Z | true | true | unknown | github | [
{
"commit": "f49b94700e0761b7514abdca0e4f0e7f3f938a93.tar.gz",
"name": "clap",
"tar_url": "https://github.com/Hejsil/zig-clap/archive/f49b94700e0761b7514abdca0e4f0e7f3f938a93.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/Hejsil/zig-clap"
}
]
| fzy.zig
Rewrite of John Hawthorn's excellent <a>fzy</a> in Zig.
See <a>Usage</a> for notable differences from the original.
Project Status
This repo is <strong>experimental</strong> and its primary purpose is for experimentation
and/or fun. Please abandon any expectations of this being a serious project.
Building
Zig 0.11.0 is required. To clone and build, run:
<code>console
$ git clone https://git.sr.ht/~gpanders/fzy.zig
$ cd fzy.zig
$ zig build</code>
This will build an <code>fzy</code> binary in <code>zig-out/bin/</code>. To install to a different
prefix, use the <code>-p</code> flag:
<code>console
$ zig build -p ~/.local</code>
By default, <code>fzy.zig</code> is built in <code>Debug</code> mode. This is very slow. If you
intend to actually use <code>fzy</code>, you should compile in either <code>ReleaseSafe</code> or
<code>ReleaseFast</code> mode:
<code>console
$ zig build -Doptimize=ReleaseSafe</code>
Usage
Usage is the same as the original <a>fzy</a> except for the following:
<ul>
<li>Input is read concurrently with key events from the user. This means you can
start typing your query right away rather than waiting for fzy to read the
entire candidate list. This is especially noticeable when the input stream is
slow.</li>
<li>Multi-select support: press <code>Ctrl-T</code> to select multiple items.</li>
<li>
A <code>-f</code>/<code>--file</code> flag allows you to read input from a file:
fzy -f input.txt
</li>
</ul>
This can of course also be done by just piping the file in over stdin:
<code> fzy < input.txt
</code>
<ul>
<li>A <code>-n</code>/<code>--no-sort</code> flag that prevents <code>fzy</code> from sorting matches.</li>
</ul>
Contributing
Questions, bugs, and patches can be sent to the <a>mailing list</a>.
License
<a>MIT</a> | []
|
https://avatars.githubusercontent.com/u/7270159?v=4 | zig-libcurl | mattnite/zig-libcurl | 2021-12-17T16:53:22Z | compile libcurl in your build.zig | main | 1 | 22 | 4 | 22 | https://api.github.com/repos/mattnite/zig-libcurl/tags | MIT | [
"build",
"https",
"libcurl",
"zig",
"zig-package"
]
| 52 | false | 2024-12-16T22:28:30Z | true | false | unknown | github | []
| libcurl build package
<a></a>
Like this project?
If you like this project or other works of mine, please consider <a>donating to or sponsoring me</a> on Github <a>:heart:</a>
How to use
This repo contains code for your <code>build.zig</code> that can statically compile libcurl, as well as some idiomatic Zig bindings for libcurl that you can use in your application. In either case below you will be able to include libcurls header with:
<code>zig
const c = @cImport({
@cInclude("curl/curl.h");
});</code>
Link and add bindings to your application
In order to statically link libcurl into your application and access the bindings with a configurable import string:
```zig
const libcurl = @import("path/to/libcurl.zig");
pub fn build(b: *std.build.Builder) void {
// ...
<code>const lib = libcurl.create(b, target, optimize);
const exe = b.addExecutable(.{
.name = "my-program",
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
const exe = b.addExecutable("my-program", "src/main.zig");
lib.link(exe, .{ .import_name = "curl" });
</code>
}
```
Now code that is part of the <code>my-program</code> executable can import the libcurl bindings with <code>@import("curl")</code>.
Only link to your application
In order to just link to the application, all you need to do is omit the <code>.import_name = "curl"</code> argument to libcurl's link options:
<code>zig
lib.link(exe, .{});</code> | []
|
https://avatars.githubusercontent.com/u/86784114?v=4 | wala | CalmSystem/wala | 2022-02-01T00:44:31Z | It aims to be for WASM what YAML is for JSON. Programming language targetting WebAssembly. Human friendly WAT | main | 0 | 22 | 1 | 22 | https://api.github.com/repos/CalmSystem/wala/tags | MIT | [
"programming-language",
"wasm",
"webassembly",
"zig"
]
| 441 | false | 2024-10-22T18:34:07Z | true | false | unknown | github | []
| Wala
A language trying to simplify <a>WebAssembly Text</a> syntax while keeping the full expressiveness and retro-compatibility. Unwittingly becoming a Zig toolchain for WASM.
Pronounced <code>\vwa.la\</code> as in french voila <em>(meaning here it is)</em>. The exact acronym's composition is unspecified but can be interpreted as <a>WebAssembly</a> Language Adaptor or What Another Linguistic Anomaly.
Philosophy
It is implemented as a set of complementary extensions over standard <a>WebAssembly Text Format</a>
```wal
func $fib export()
u64 $n -> ?
if {$n <= 2}
1
+
$fib{$n - 2}
$fib{$n - 1}
```
Is expended to:
<code>wat
(module
(func $fib (export "fib") (param $n i64) (result i64)
(if (result i64) (i64.le_u (local.get $n) (i64.const 2))
(i64.const 1)
(i64.add
(call $fib (i64.sub (local.get $n) (i64.const 2)))
(call $fib (i64.sub (local.get $n) (i64.const 1)))))))</code>
For working <a>samples</a> see: <a>fib</a>, <a>fizzbuzz</a>, <a>99bottles</a>, ...
Install
Prerequisites
<ul>
<li><a>Zig</a></li>
<li><a>Zigmod</a></li>
</ul>
Optional
<ul>
<li><a>Binaryen</a> for additional optimizations</li>
<li><a>Wasmtime</a> for WASI runtime</li>
</ul>
Building
<code>sh
git clone https://github.com/CalmSystem/wala.git
cd wala
zigmod ci
zig build -Drelease-safe
PATH=$PATH:./zig-out/bin</code>
Usage
<ul>
<li>Run built module <em>(default WASI engine: <code>--runtime wasmtime</code>)</em>
<code>sh
wala run samples/hello.wala</code></li>
<li>Convert <code>samples/fib.wala</code> to Wasm
<code>sh
wala build samples/fib.wala > fib.wasm</code></li>
</ul>
Features
Sweet expression
Deducing parentheses from indentation based on <a>Readable Lisp S-expressions Project</a>'s <a>Spir110</a>
Curly infix expressions
<ul>
<li><code>{"hello" upper}</code> -> <code>(upper "hello)</code></li>
<li><code>{a + b}</code> -> <code>(+ a b)</code></li>
<li><code>{a * b * c}</code> -> <code>(* a b c)</code></li>
<li><code>{$fn call a b c}</code> -> <code>(call $fb a b c}</code></li>
</ul>
Neoteric expression
Like function calls
<ul>
<li><code>cos(v)</code> -> <code>(cos v)</code></li>
<li><code>e()</code> -> <code>(e)</code></li>
<li><code>sum(a b c)</code> -> <code>(sum a b c)</code></li>
<li><code>f{n + 1}</code> -> <code>(f (+ n 1))</code></li>
</ul>
Short const
<ul>
<li><code>42i32</code> -> <code>(i32.const 42)</code></li>
</ul>
Operand type deduction
<ul>
<li><code>(i32.add 35 7)</code> -> <code>(i32.add (i32.const 35) (i32.const 7))</code></li>
<li><code>(i64.add 35 7)</code> -> <code>(i64.add (i64.const 35) (i64.const 7))</code></li>
</ul>
Common operators
<ul>
<li><code>(+ 35i32 7)</code> -> <code>(i32.add (i32.const 35) (i32.const 7))</code></li>
<li><code>(+ 35i64 7)</code> -> <code>(i64.add (i64.const 35) (i64.const 7))</code></li>
</ul>
Ident expansion
<ul>
<li><code>($a_func $a_param $a_global)</code> -> <code>(call $a_func (local.get $a_param) (global.get $a_global))</code></li>
</ul>
Assign operator
<ul>
<li><code>{$a_local = 5}</code> -> <code>(local.set $a_local (i32.const 5))</code></li>
<li><code>{$a_global = 5}</code> -> <code>(global.set $a_local (i32.const 5))</code></li>
</ul>
Interface types numbers
<ul>
<li><code>{42s64 <= 1}</code> -> <code>(i64.le_s (i64.const 42) (i64.const 1))</code></li>
<li><code>{42u64 <= 1}</code> -> <code>(i64.le_u (i64.const 42) (i64.const 1))</code></li>
</ul>
Define
<ul>
<li><code>{$C := 5} (call $func $C $C)</code> -> <code>(call $func (i32.const 5) (i32.const 5))</code></li>
</ul>
Planned
Result Type Deduction
No need to specify blocks and function result types
Interface integration
Allows to define, import and use <code>wit</code> declarations. See <a>fib.wasi.wal</a>
License
Distributed under the MIT license to facilitate cooperation and knowledge sharing. However, use with respect to contributors and end-users is strongly advised. See <a>LICENSE</a> for more information. | []
|
https://avatars.githubusercontent.com/u/7270159?v=4 | zig-zlib | mattnite/zig-zlib | 2021-12-17T16:30:10Z | compile zlib in your build.zig | main | 2 | 22 | 5 | 22 | https://api.github.com/repos/mattnite/zig-zlib/tags | MIT | [
"build",
"zig",
"zig-package",
"zlib"
]
| 31 | false | 2025-04-24T16:02:27Z | true | false | unknown | github | []
| zlib build package
<a></a>
Like this project?
If you like this project or other works of mine, please consider <a>donating to or sponsoring me</a> on Github <a>:heart:</a>
How to use
This repo contains code for your <code>build.zig</code> that can statically compile zlib, as well as some idiomatic Zig bindings for zlib that you can use in your application. In either case below you will be able to include zlibs header with:
<code>zig
const c = @cImport({
@cInclude("zlib.h");
});</code>
Link and add bindings to your application
In order to statically link zlib into your application and access the bindings with a configurable import string:
```zig
const zlib = @import("path/to/zlib.zig");
pub fn build(b: *std.build.Builder) void {
// ...
<code>const lib = zlib.create(b, target, mode);
const exe = b.addExecutable("my-program", "src/main.zig");
lib.link(exe, .{ .import_name = "zlib" });
</code>
}
```
Now code that is part of the <code>my-program</code> executable can import the zlib bindings with <code>@import("zlib")</code>.
Only link to your application
In order to just link to the application, all you need to do is omit the <code>.import_name = "zlib"</code> argument to zlib's link options:
<code>zig
lib.link(exe, .{});</code> | []
|
https://avatars.githubusercontent.com/u/5132833?v=4 | zterm | nfisher1226/zterm | 2021-05-26T22:10:53Z | Terminal emulator written in Zig | odin | 0 | 21 | 0 | 21 | https://api.github.com/repos/nfisher1226/zterm/tags | MIT | [
"gtk",
"terminal-emulator",
"vte",
"zig"
]
| 205 | false | 2025-04-15T15:04:34Z | true | false | unknown | github | []
| Zterm
Contents
========
* <a>Introduction</a>
* <a>Installing</a>
* <a>Building</a>
* <a>Keyboard Shortcuts</a>
* <a>Command Line Options</a>
* <a>Configuration</a>
* <a>Roadmap</a>
Introduction
Zterm (pronounced <code>Zed-Term</code>) is a simple terminal emulator using Vte and Gtk+
written using the <a>Zig</a> programming language. Some useful
features of Zterm are:
* Multiple terminals can be open in tabs and panes within a single tab
* Configurable keybindings
* Comprehensive theming options
* Control over colors used
* Choice of backgrounds - solid color, transparent, image or gradient
* Simple and small graphical interface taking up less screen space than other
similarly functional terminals
Installing
<ul>
<li>Arch Linux and derivatives - Zterm is in the <a>aur</a></li>
<li>FreeBSD - A binary tarball is provided for the latest release of FreeBSD (at
the time of release) on the <a>releases</a>
page over at <a>codeberg</a>
Other Linux distros or operating systems will have to build from source, see
<a>building</a>.</li>
</ul>
Building
You will need the Zig compiler, version 0.9.0, available from
<a>ziglang.org</a>. You will also need the Gtk-3.x and vte
libraries plus development headers installed on your system.
Zterm can be built using the <a>Zigmod</a> package
manager for Zig.
Zigmod
<code>sh
zigmod ci
zig build -Drelease-safe=true</code>
This will place the executable in <code>zig-out/bin</code> and the icon and .desktop file in
the appropriate subdirectories of <code>zig-out/share</code>. To Install somewhere else, one
can simple set the <code>prefix</code> like so.
<code>sh
zig build -Drelease-safe=true --prefix /some/directory</code>
The data directory can also be adjusted if necessary. For instance, if one wanted
to install <strong>Zterm</strong> in their home directory, with the executable in <code>~/bin</code> and
the data files in <code>~/.local/share</code>, it can be done like so.
<code>sh
zig build -Drelease-safe=true --prefix $HOME -Ddatadir=".local/share"</code>
Assuming one has <code>~/bin</code> in their <code>$PATH</code>, this should be sufficent to add a menu
entry and icon in most modern <code>Unix</code> desktop environments, without needing root
permissions.
Keyboard Shortcuts
The following table gives the default keybindings. If any customization is
desired, see <a>configuration</a>
| Shortcut | Action |
| -------- | ------ |
| Ctrl/Shift/T | New Tab |
| Ctrl/Shift/Enter | New Pane |
| Alt/R | Change Pane Orientation |
| Alt/[1-9] | Goto [num] Tab |
| Alt/UpArrow | Previous Tab |
| Ctrl/PageUp | Previous Tab |
| Alt/DownArrow | Next Tab |
| Ctrl/PageDown | Next Tab |
| Alt/RightArrow | Next Pane |
| Alt/LeftArrow | Previous Pane |
| Ctrl/Shift/Q | Quit |
Command line options
<code>sh
Usage: zterm [-h] [-e <COMMAND>] [-t <TITLE>] [-w <DIR>]
Flags:
-h, --help Display this help and exit.
-e, --command <COMMAND> Command and args to execute.
-t, --title <TITLE> Defines the window title.
-w, --working-directory <DIR> Set the terminal's working directory.</code>
Configuration
Zterm uses the <a>nestedtext</a> human readable
data format to store it's configuration. The main program options may be edited
with the <code>preferences</code> dialog without editing any files. However, at this time the
only way to change the default keybindings is by editing the file
<code>~/.config/zterm/keys.nt</code>. The file will be auto-generated if it does not exist.
All configuration options set via the <code>preferences</code> dialog will take effect
immediately. Any changes to the <code>keys.nt</code> file will require a restart to take
effect.
Roadmap
<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> Preferences dialog
<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> Remove most color handling code and replace with <code>zig-color</code> color library
<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> Finish implementing all preferences
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Background image
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Background gradient
<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> Expose charset settings
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> User editable keybindings
<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> Dialog to set keybindings
<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> Set tab title based on running program / current directory
<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> change from GtkBox widget to more flexible GtkPaned
<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> change build to utilize only zig build system | []
|
https://avatars.githubusercontent.com/u/146390816?v=4 | assimp | allyourcodebase/assimp | 2021-09-03T08:25:20Z | Open Asset Importer Library built with Zig | master | 3 | 20 | 12 | 20 | https://api.github.com/repos/allyourcodebase/assimp/tags | BSD-3-Clause | [
"3d-formats",
"assimp",
"assimp-port",
"zig",
"zig-package",
"ziglang"
]
| 81 | false | 2025-04-15T18:42:22Z | true | true | unknown | github | [
{
"commit": "v5.3.1.tar.gz",
"name": "assimp",
"tar_url": "https://github.com/assimp/assimp/archive/v5.3.1.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/assimp/assimp"
}
]
| OpenAssetImporter Library Binding for Zig
This repo is a build sdk for <a>Assimp</a> to be used with the Zig build system:
```zig
const std = @import("std");
// Import the SDK
const Assimp = @import("Sdk.zig");
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
<code>const exe = b.addExecutable("static-example", null);
exe.setBuildMode(mode);
exe.addCSourceFile("src/example.cpp", &[_][]const u8{"-std=c++17"});
exe.linkLibC();
exe.linkLibCpp();
exe.install();
// Create a new instance
var sdk = Assimp.init(b);
// And link Assimp statically to our exe and enable a default set of
// formats.
sdk.addTo(exe, .static, Assimp.FormatSet.default);
</code>
}
``` | [
"https://github.com/allyourcodebase/assimp"
]
|
https://avatars.githubusercontent.com/u/57362253?v=4 | spaceporn | tiawl/spaceporn | 2021-06-19T09:03:46Z | Wiki and Generator for space contemplators | trunk | 32 | 20 | 1 | 20 | https://api.github.com/repos/tiawl/spaceporn/tags | Unlicense | [
"glfw3",
"glsl",
"imgui",
"pixel-art",
"procedural-generation",
"shaderc",
"shaders",
"space",
"spaceporn",
"vulkan",
"wiki",
"zig",
"ziglang"
]
| 10,936 | false | 2025-05-10T14:30:23Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "cimgui_zig",
"tar_url": "https://github.com/tiawl/cimgui.zig/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/tiawl/cimgui.zig"
},
{
"commit": "master",
"name": "shaderc_zig",
"tar_url": "https://github.com/tiawl/shaderc.zig/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/tiawl/shaderc.zig"
},
{
"commit": "ea14e0efc3328a6b9e7dd53bb91b9eec2efe3f96.tar.gz",
"name": "jdz_allocator",
"tar_url": "https://github.com/joadnacer/jdz_allocator/archive/ea14e0efc3328a6b9e7dd53bb91b9eec2efe3f96.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/joadnacer/jdz_allocator"
}
]
| spaceporn
Wiki and Generator for space contemplators
Generator
<ul>
<li>
The <strong>spaceporn generator</strong> is in early stage development and is not ready to be used.
</li>
<li>
The <strong>spaceporn generator</strong> is a tool which could:
</li>
<li>display animated or static procedural pixelized space content,</li>
<li>generate procedural pixelized space pictures.</li>
</ul>
Usage
<ul>
<li>The maintainers will update this section later</li>
</ul>
Dependencies
<ul>
<li>Before installing and building the <strong>spaceporn generator</strong>, you need to install this:</li>
<li><a>Zig 0.14.0</a>,</li>
</ul>
Installing
<ul>
<li>The maintainers will update this section later.</li>
</ul>
Supported environments
OS | Building | Running
--- | --- | ---
Ubuntu 22.04 | :white_check_mark: | :white_check_mark:
Windows 2022 | :white_check_mark: | :grey_question:
<ul>
<li>:white_check_mark: : Functional</li>
<li>:grey_question: : Currently untested</li>
</ul>
<a>Wiki</a>
The <strong>spaceporn wiki</strong> is a list of GLSL tutorials and online shaders about procedural pixelized space shaders.
More details <a>here</a>
Contributing
Each component of this repository has its own contributing rules:
- <a>The generator contributing rules</a>
- <a>The wiki contributing rules</a>
License
This repository is dedicated to the public domain. See the LICENSE file for more details.
Credit
Thanks to all the <a>contributors</a> who help move the project forward.
Without each one of these links and their authors, this project will never exist:
- <a>Github - Deep-Fold's PixelSpace</a> and <a>Github - Deep-Fold's PixelPlanets</a>
- <a>Slynyrd's blog</a>
- <a>Inigo Quilez's articles</a>
- <a>FabriceNeyret2's shaders</a> and <a>shadertoyunofficial website</a>
- <a>Ek_Vitki's star tutorial</a>, <a>Ek_Vitki's nebula tutorial</a> and <a>Ek_Vitki's celestial bodies tutorial</a>
- A lot of shared Shadertoy shaders:
- <a>Shadertoy - CBS' Simplicity Galaxy shader</a>
- <a>nimitz's Noise animation - Electric shader</a>
- <a>Shadertoy - vegardno's Pixel planet shader</a>
- <a>Shadertoy - viclw17's Jupiter shader</a>
- A lot of related Github projects:
- <a>lord-123's xshader</a>
- <a>mmhobi7's xwinwrap</a>
- <a>KEKE046's xjuliabg</a>
- <a>Theldus' anipaper</a>
- <a>zaranthus' Livepaper</a>
- <a>zkburke's quanta</a>
- <a>Daniel Linssen's planetarium</a> | []
|
https://avatars.githubusercontent.com/u/1739?v=4 | hts-zig | brentp/hts-zig | 2021-10-25T10:38:07Z | ziglang + htslib | main | 0 | 20 | 0 | 20 | https://api.github.com/repos/brentp/hts-zig/tags | MIT | [
"bioinformatics",
"genomics",
"hacktoberfest",
"htslib",
"zig",
"ziglang"
]
| 184 | false | 2024-12-06T02:22:40Z | true | false | unknown | github | []
| <a></a>
WIP <a>zig</a> wrapper for <a>htslib</a> parsing of VCFs for genetic variants
I wrote this learning zig so it probably has many non-ziggy usages.
Most of the htslib VCF/Variant stuff is supported.
Usage
<blockquote>
:warning: <code>hts-zig</code> tries to allocate as little as possible, use
<code>.dup()</code> on a variant if when it's necessary to keep it in memory.
</blockquote>
```zig
const vcf = @import("src/vcf.zig")
const VCF = vcf.VCF
const allocator = std.testing.allocator;
var vcf = VCF.open("tests/test.snpeff.bcf").?; // can return null
// file and cleanup htslib memory at end of scope
defer vcf.deinit();
var variant = vcf.next().?; // .? syntax gets an optional result.
try stdout.print("\nvariant:{any}\n", .{variant}); // Variant(chr1:30859-30860 (G/C))
// # get the AD field
// # needs to allocate, this interface will likely change.
// # extract the FORMAT/sample AD field (allelic depth)
// # to get INFO, use get(vcf.Field.info, ...);
var fld = "AD";
var ads = std.ArrayList(i32).init(allocator)
defer ads.deinit();
try variant.get(vcf.Field.format, ads, fld);
// 4 samples * 2
try stdout.print("\nAD:{any}\n", .{ads.items}); // { 7, 0, 2, 0, 6, 0, 4, 0 }
// # genotypes:
var gts_mem = std.ArrayList(i32).init(allocator); // can re-use this for each variant
defer gts_mem.deinit();
var gts = try variant.genotypes(&gts_mem);
try stdout.print("\ngts:{any}\n", .{gts});
// # gts:[0/0/, 0/0/, 0/1/, 0/0/] (note trailing / is accurate as it's how it's stored in htslib)
// # region queries
var iter = try ivcf.query(chrom, 69269, 69270);
while (iter.next()) |v| {
try std.testing.expect(v.start() == 69269);
}
```
testing and dev
This will require <code>zig</code> and <code>htslib</code> installed.
<code>zig build test</code>
Zig requires very little additional work to wrap a C library, but it is
currently not able to access struct fields when the struct contains bitfields.
For this reason, we need to write functions to access fields in many htslib
structs. Those functions are <a>here</a>
TODO
<ul>
<li>[X] Add nice genotypes access methods/structs</li>
<li>[X] Add <code>vcf.query()</code> (currently only iteration from start of file is supported, not querying by genomic location.</li>
<li>[X] updating header.</li>
<li>[X] setting INFO fields.</li>
<li>[X] writing. currently everything is read-only.</li>
<li>[X] fewer allocations (pass ArrayList to functions).</li>
<li>[X] support querying vcf as well as bcf</li>
<li>[X] set_samples().
<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> fix ergonomics and think about error and null return types.</li>
</ul>
Why?
it's quite useful to learn a new language by writing something that
I'll use every day. zig looks interesting and sane | []
|
https://avatars.githubusercontent.com/u/2105009?v=4 | zyg | Opioid/zyg | 2021-07-26T07:37:12Z | Pathtracer written in zig | main | 0 | 19 | 2 | 19 | https://api.github.com/repos/Opioid/zyg/tags | - | [
"rendering",
"zig"
]
| 3,612 | false | 2025-05-21T20:39:50Z | true | false | unknown | github | []
| 404 | []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.