I built a Sudoku game where the entire engine is written in Zig, compiled to WASM, and shared across three front ends: a native terminal renderer, a web shell, and an Android app (WebView over the same core). One engine, no per-platform game logic.
It's pre-release and I need closed-test testers for the Play Store (12 testers, 14 days). If you have an Android phone, install it and keep it for two weeks — no daily use needed.
oksolc now supports solc 0.8.37, 0.8.38 and 0.8.39, as well as solc 0.8.36.
Before oksolc 0.2.5, the compiler targeted only solc 0.8.36. A project pinned to a later release had no way to get the same bytecode from oksolc that its own solc produces.
What oksolc is
oksolc is a new Solidity compiler written in Zig. It accepts the same Standard JSON input as solc, and on the 12 projects we measured it built 3.3 to 6.0 times faster than solc's via-IR pipeline.
We wrote it for our own use while developing Chainwall. The goal was shorter build times during contract development.
oksolc provides a command-line tool, a C library with the same interface as libsolc, and a Zig module. The supported compilation path is optimized via-IR through Standard JSON.
What changed in oksolc 0.2.5
The default is now solc 0.8.39, and --solc-version selects any of the three earlier releases. The selected release controls pragma checks, code generation, diagnostics and metadata.
block.slotnum and Yul slotnum() compile on the Amsterdam EVM version from the solc 0.8.37 target onwards.
solc fixed four via-IR bugs between solc 0.8.37 and solc 0.8.39: SOL-2026-4, SOL-2026-6, SOL-2026-7 and SOL-2026-8 in the Solidity compiler bug list. oksolc applies the same fixes on every target.
Checked and unchecked arithmetic get separate constant helpers, and Yul returndatacopy calls that can revert keep their bounds checks.
I compiled the 14 projects bundled with the oksolc benchmark with both compilers, on each of the three new solc releases. The complete Standard JSON output was the same every time. The README reports the same result for 17 workloads.
The solc 0.8.36 target keeps the security fixes and the constant-helper fix, so its bytecode can differ from solc 0.8.36. The README documents each difference.
Build times on 12 open-source projects
For each project we sent the same Standard JSON build request to solc 0.8.39 and to oksolc 0.2.5 targeting solc 0.8.39. oksolc ran on 1 job and on 4 jobs. The benchmark records a result only when both compilers produce the same bytecode. Both compilers ran the optimized via-IR pipeline, so these times compare oksolc with solc via-IR, not with solc's default pipeline.
Project
solc 0.8.39
oksolc, 1 job
oksolc, 4 jobs
Sablier v2 1.2.0
523.1 s
208.4 s
145.9 s
EigenLayer 0.3.0
175.1 s
77.9 s
40.0 s
Solady 0.1.26
58.1 s
29.2 s
17.5 s
Uniswap v4 (2024-06-06)
39.3 s
18.2 s
7.4 s
Pendle v2 (2026-09-16)
26.0 s
12.1 s
6.8 s
OpenZeppelin 4.8.0
20.9 s
9.7 s
3.7 s
OpenZeppelin 4.7.0
18.9 s
8.8 s
3.2 s
Liquity (2024-10-30)
14.7 s
7.0 s
3.4 s
OpenZeppelin 4.9.0
13.6 s
6.4 s
2.7 s
OpenZeppelin 5.0.2
10.8 s
5.1 s
2.0 s
OpenZeppelin 5.6.1
10.3 s
4.9 s
1.7 s
Uniswap v4 (2022-06-16)
6.6 s
3.1 s
1.3 s
With a single job, oksolc built every project 2.0 to 2.5 times faster than solc. With 4 jobs, it was 3.3 to 6.0 times faster. Building all twelve took 15 minutes 17 seconds with solc and 3 minutes 56 seconds with oksolc on 4 jobs.
Incremental builds are faster still. In a serve or watch session, oksolc keeps the compiler in memory and reuses work between edits.
I measured on my Apple Silicon MacBook Air with 16 GB of memory. The solc times and the oksolc 4-job times are the median of 3 runs after 1 warmup run. The 1-job times are single runs. On 4 jobs, oksolc used more memory than solc on most projects, for example a peak of 5.3 GiB against 2.4 GiB on Solady. Sablier v2 peaked at about 8 GiB with either compiler in these runs, and its three runs varied more than any other project's.
Sablier v2, the largest project in the set, went from 8 minutes 43 seconds with solc to 2 minutes 26 seconds with oksolc on 4 jobs, with the same bytecode.
How to use it
You need Zig 0.17.1. Build oksolc from the release tag:
git clone https://github.com/okcontract/oksolc
cd oksolc
git checkout v0.2.5
zig build -Doptimize=ReleaseFast
./zig-out/bin/oksolc version
For a Foundry project, point foundry.toml at the oksolc executable and enable optimized via-IR:
oksolc can serve a local page for browsing a compiled project. It lists the project's source files next to the file you select, with an outline of everything that file declares.
For each contract the page also shows the ABI and the creation and runtime bytecode with their sizes. You can search the project, and two side panels list diagnostics and references.
The browser is left out of a default build. Build with -Dbrowser=true, which needs Bun 1.4.5 and TypeScript 7.0.2, then run it from your project:
oksolc serve --browse
Open http://127.0.0.1:8080. serve watches the Solidity files in src/ and recompiles when they change. To browse a single Standard JSON request instead, run oksolc browse --request input.json.
Including the browser adds about 0.3 MB to the binary.
What should it show next? Open an issue and tell us.
Try it on your project
Build one of your own projects with oksolc and compare the result with solc. If the two differ, open an issue on github.com/okcontract/oksolc and include the output of oksolc version --json.
If oksolc is useful to you, star the repository. For new releases, follow us on X at @okcontract.
A Zig library for safely handling process signals, with both blocking wait and callback usage modes.
Introduction
Handling POSIX signals is not especially difficult, but it is unsafe because an asynchronous signal handler can interrupt normal thread execution at any instruction. Inside this interruption context, operations such as locking, allocating memory, I/O buffering, modifying complex shared state, or waiting for another thread can deadlock, re-enter code, introduce data races, or cause undefined behavior. The usual recommendation is to do as little as possible in a handler. The classic self-pipe trick is well suited to this problem.
This library implements that self-pipe design (along with asynchronous tasks in Zig 0.16).
Blocking the main thread while waiting for a signal is a common use case. We usually do not need to worry about graceful shutdown because a normally exiting main function executes defer statements.
const std = ("std");
const signals = ("signals");
pub fn main() !void {
try signals.init(&.{ .INT, .TERM }); // <- Register the signals to handle during initialization
defer signals.deinit(); // <- Remember to call deinit
std.debug.print("Waiting for SIGINT/SIGTERM...\n", .{});
const sig = try signals.wait(); // <- Block here until a signal arrives
std.debug.print("Received: {s}\n", .{@tagName(sig)});
std.debug.print("Goodbye!\n", .{});
}
Sometimes a long-running task blocks execution first, or you need to hand off the responsibility for blocking. In that case, use callbacks. Implement graceful shutdown in the callback:
const std = ("std");
const signals = ("signals");
var should_exit: std.Io.Event = .unset; // <- Whether the program should exit
const Context = struct {
io: std.Io,
fn onSignal(ctx: *anyopaque, sig: std.posix.SIG) void {
const self: *Context = u/ptrCast(@alignCast(ctx));
std.debug.print("Received: {s}\n", .{@tagName(sig)});
should_exit.set(self.io); // <- Tell the blocking location to exit
}
};
pub fn main(init: std.process.Init) !void {
const io = init.io;
var context: Context = .{ .io = io };
try signals.initCallback(
io,
&.{ .INT, .TERM },
&context,
Context.onSignal,
);
defer signals.deinit();
std.debug.print("Waiting for SIGINT/SIGTERM via callback...\n", .{});
try should_exit.wait(io); // <- Block until the exit event is received
std.debug.print("Goodbye!\n", .{});
}
When a signal arrives, our callback code runs inside a separate asynchronous task. It does not interrupt the execution of any context and is therefore substantially safer than native POSIX signal behavior.
Notes
This library is well tested only on Linux; availability on other platforms is uncertain. It is also not the most modern approach: the more modern option is signalfd, a Linux-specific mechanism. However, the self-pipe technique is the classic solution.
I want to start building some serious zig projects, but I don't want to implement everything from scratch (unless I have to) and I really want to build on others work.
Using ptrCast to get an unsigned pointer to a signed variable with a bitsize that's not a power of 2 shows nonsensical data.
Reproducible example (in debug):
const std = @import("std");
test "reading an i30 through a u30 pointer" {
var x: i30 = -1;
const view: *u30 = @ptrCast(&x);
std.debug.print("bytes of x: {x}\n", .{std.mem.asBytes(&x)});
try std.testing.expectEqual(std.math.maxInt(u30), view.*);
}
output:
bytes of x: ffffffff
expected 1073741823, found 4294967295
Somehow view.* is larger than the maximum value u30 should be able to hold. It is actually the u32 max value.
edit: I tried using an LLM to investigate this and the cause is actually very interesting.
The issue has to do with the padding bits. A signed write to a bit size with padding bits sets every padding bit to the sign bit. That's the case because it makes reads into something like an i30 very simple, you just load the four bytes and read them like you would an i32 without any adjustments (in two's complement negative numbers essentially count "down" from negative one which is 111..111 so adding additional 1 bits to a negative number is the same as adding additional 0 bits to a positive number).
Unsigned writes always write 0 into the padding bits for the same reason, it lets you read the full bytes with no masking and get the same values.
The problem is that this mechanism breaks when the type that was assumed when writing into memory isn't the one that's assumed when reading from it. The padding bits still don't get masked out and you get 32 bit data that doesn't make sense for 30 logical bits.
This edit is mainly me trying to explain this to myself. Sorry if the terminology is wrong, I don't have any formal CS education (though I should be starting my CS degree at October of next year).
Andrew dare bash on C++ yet their own error messages are so helpful and informative
error: cannot format slice without a specifier (i.e. {s}, {x}, {b64}, or {any})
compileError("cannot format slice without a specifier (i.e. {s}, {x}, {b64}, or {any})");
And what does the reference trace shows? the userland where failure happened right? Nope, a bunch of trace inside the std library. So we just need to hunt down all the places we print?
Is this the suppposed compiler behaviour, something I am missing here guys? Cause this definitely isn't the first kind of errors that point to the std library instead of userland, other common culprit being allocators.
I’m about to start the process of upgrading my kernel written in Zig—from 0.16.0 to the 0.17.1, and I'd love some advice from others who have gone through a similar process, especially on bare-metal or systems migrations.
What was your strategy for tackling the task? What sort of problems did you encounter and how did you overcome them?
Appreciate any insights or approaches you've found effective!
A tool for cleaning redundant code from templates, currently used to clean Zig project templates generated by zig init.
Introduction
This tool extracts cleanup information from patches generated by git-diff. It does not scan for code targets or comments. Therefore, it is effectively generic and can perform cleanup from external patches. The built-in patches are actually located in the src/diff_patchs source directory.
It is filled with a large number of comments (115 lines) and example code (more than half). This may help beginners, but it is meaningless for experienced users. In my view, this is all "noise."
Use pureinit to clean it (it detects the version in build.zig.zon and uses the corresponding patch):
$ pureinit
Patch info:
+-----------------------+----------+-----+--------+
| name | from | env | ver |
+=======================+==========+=====+========+
| zig-init.0.17.1.patch | builting | zig | 0.17.1 |
+-----------------------+----------+-----+--------+
Apply patch to: '.'? [y/N]: y
INFO Applying build.zig
INFO Applying build.zig.zon
INFO Applying src/main.zig
INFO Applying src/root.zig
This post has been translated into English using Google Translate. Text was originally in Russian.
I got bored, so I decided to write a small library for creating simple and energy-efficient graphics applications in retained-mode. I used raylib as a base (it's sufficient for now, and later I might try rewriting it for Vulkan).
At the time of this post, the library is very crude and not suitable for large projects. I only started writing in Zig in September 2026, so the code quality may be poor.
Main goals
I don't plan to make this anything serious, but I do adhere to a few points:
Energy-efficient: A graphics application should use resources only when absolutely necessary, and use them as little as possible. This is why I chose retained-mode, as it significantly reduces CPU load without slowing down the application.
Flexibility: The library should allow the developer to customize it as they wish.
Lightweight: A minimal graphical application in Aspect can weight ~68KiB.
Built-in components
The library provides a small set of built-in components, some of the most basic ones: Button, TextField (which still doesn't function as expected, lol), Selection, ColumnChart, Toggler, and so on.
Interesting
This library divides the entire application into several parts (model and functions: reveal, update, build, reflect), allowing for systematization of all application events and flexible interface control.
Supported Zig versions
The library currently relies on Zig 0.17.0.
Supported OS
The library has been successfully tested on Debian Linux and Windows 11.
What's next In the near future
I'll try to implement relative positioning, which will reduce the need to worry about setting absolute coordinates for each component. Naturally, over time I will add/improve the built-in components.
Мне стало скучно, и я решил написать небольшую библиотеку для создания простых и энергоэффективных графических приложений в режиме сохранения. В качестве основы я взял raylib (пока этого достаточно, а позже, возможно, попробую переписать под Vulkan).
На момент публикации этой темы библиотека является очень сырой и не подходит для больших проектов. И на Zig я начал писать только с сентября 2026 года, поэтому качество кода может хромать.
Основные цели библиотеки
Я не планирую делать из этого что-то серьёзное, но тем не менее придерживаюсь некоторым пунктам:
Энергоэффективность: Графическое приложение должно использовать ресурсы только тогда, когда это действительно необходимо, и использовать их как можно меньше. Именно поэтому я выбрал режим сохранения, так как он позволяет сильно снижает нагрузку на CPU, при этом не замедляя работу приложения.
Гибкость: Библиотека должна позволять разработчику настроить что-либо так, как ему угодно.
Малый вес: Минимальное графическое приложение на Aspect может весить ~68KiB.
Встроенные компоненты
Библиотека предоставляет небольшой набор встроенных компонентов, прямо самых базовых: Button, TextField (который ещё не функционирует как хотелось бы, лол), Selection, ColumnChart, Toggler и так далее.
Интересное
Данная библиотека разделяет всё приложение на несколько частей (модель и функции reveal, update, build, reflect), что позволяет систематизировать все события приложения и гибко контролировать интерфейс.
Поддерживаемые версии Zig
Сейчас библиотека опирается на Zig 0.17.0.
Поддерживаемые ОС
Библиотека успешно протестирована на Debian Linux и Windows 11.
Что буду делать дальше
В ближайшее время я попробую реализовать взаиморасположение (или относительное позиционирование), что позволит реже задумываться над заданием абсолютных координат для каждого компонента. Естественно со временем буду добавлять/улучшать встроенные компоненты.
Hey guys, I just want to know if ZLS supports C libraries like GTK that I am using here? Maybe it is because I am using it in Neovim, but I have no idea. Can any kind soul help me out? I miss my suggested options that I usually get.
Hello everyone, I’d like to introduce shinobi, a library for translating Ninja’s ‘build.ninja’ files into the Zig build system. The goal of this project is to make it easier to compile C/C++ libraries through Zig’s build system for easier integration into Zig projects. This should help reduce the need to maintain a Zig build script for the C/C++ library.
Currently, shinobi comes as both a single ‘shinobi.zig’ file or as a precompiled binary that can generate ‘build.zig’ files. An initial version v0.1.0 has been released. This project has only been tested on Windows and Linux.
The repository comes with an example of how this can be used within a project’s ‘build.zig’ script. This library has also had minimal testing with the ‘glfw3’ and ‘bgfx’ projects.
Let me know if you have any comments, suggestions or if you run into any issues.
I'm trying to replace my CMake build system with build.zig, and everything is going well. The only issue with the entire process is linking against LLVM. It simply doesn't work. Using plain clang and -lLLVM-23 works, but even if the flag is passed with linkSystemLibrary it doesn't link properly. Is there a known way to link against LLVM with build.zig?
We just open-sourced Zean (Zig + Lean), a toolkit for translating supported Zig functions into executable Lean models and proving their behavior. It came out of our formal verification work on oksolc, our Solidity compiler written in Zig.
Zean works from AIR, Zig's analyzed intermediate representation. An instrumented compiler captures supported functions from AIR, and a translator emits executable Lean program definitions. Specifications and proofs live in separate handwritten Lean modules.
A verification library derives the proof obligations for memory access, initialization, permissions, arithmetic, control flow and supported calls. You write the contracts and loop invariants. If an obligation still needs a mathematical argument, you supply that too, and Lean checks the proofs. Unsupported operations are rejected, and unresolved obligations stay open.
The caller has to establish that the source has enough initialized words and the destination has enough writable storage. For the source-preservation contract, the two ranges also have to be disjoint. Under those assumptions the proofs show there are no invalid accesses or uninitialized reads. A successful run copies the source contents into the destination and preserves memory outside it. Modeled allocation exhaustion is an explicit permitted failure, and termination is a separate property.
Change the loop bound from < length to <= length and you get an extra boundary access that the original contract can't justify. The tutorial also includes deliberately false claims that must fail verification.
When the Zig source changes, you recapture the function to regenerate the model, then replay the proofs.
This release covers memory-safety examples derived from Ziglings, buffer updates, copy loops, helper calls and a captured specialization of std.mem.replaceScalar. It supports restricted AIR fragments, with explicit target and layout constraints. The capture pipeline, the Zig frontend and the native backend remain trust boundaries, so the proofs don't establish correctness of the final native binary or of the whole compiler.
The idea is to keep design iteration in Zig and prove a component's contracts once it has settled.
To try it you need Zig 0.17.1 and elan:
git clone https://github.com/okcontract/zean
cd zean
elan toolchain install leanprover/lean4:v4.35.0
zig build ziglings
It's released under Apache 2.0. If you write Zig or Lean, I'd like to know which functions you'd want to verify with it first.
I have a program being written in c++ (that I intend to cross compile for different platforms for testing and deployment).
I saw that zigs build system was excellent for this exact use case, but because of how much zig changes between versions (I'm on 0.17.1), I wanted to know if there are any caveats for writing the build script.
I'm currently designing a math library in Zig, that I plan on using for my game/engine.
However, I've never designed a library before, so I'm really stuck, because there are so many decisions to be made, and I'm hesitant. I don't want to step forward in the wrong direction and shoot myself in the foot later on.
Here is what's bugging me:
- *Generic vs Explicit types*
I started writing a generic type style library, but since I'm inexperienced and can't really comprehend the library as a whole yet, I was bumping into million corners. I just said fuck it and wrote explicit types with a lot of repetition. However, is it really a big deal? I'm only trying to have like Vec2, Vec3, Vec4 and Mat2, Mat3 and Mat4. I don't think I'll need anything more than this.
- *How should Vec type look like?*
It seems more convenient to iterate over and do stuff if it was just an array of floats, right? But there is a lot more convenience to be had when writing my_vec.x or my_vec.y instead of my_vec[0] and my_vec[1]. I could use some help regarding tradeoffs here to help me decide what I really want in the long run.
- *SIMD complications*
As I said previously, if I store vectors as an array of floats, is it wasteful to then copy them into a SIMD vector and do operations on it? Should they be SIMD vector from the start?
Also, there are some register width constraints, so I'm not sure how to do that, do I collect them and operate on a larger vector (in a bulk), or is it fine to just use various small operations?
Is all this data passing from one side to the other more efficient? Do I really get THAT much more speed when using SIMD for vectors and matrices of the size 2, 3 and 4?
- *How should Mat type look like?*
This greatly depends on the previous questions. But should Mat then be an array of my vectors? Array of SIMD vectors? Or just a 2D array of floats? Any tradeoff tips would be greatly appreciated.
- *Row-major vs Column-major for matrices?*
Row major makes WAY MORE SENSE to me, but I've read that for compatibility purposes, or some memory tricks in certain cases, it's handier to have column major matrices. Also, it's what GLM (which I'm trying to "replace") is using. Any tips for tradeoffs in the long run?
Zig no longuer supports anything below win10 (it relies on new functions from the ntdll that winxp doesn't have). But luckely, their platform layer is so thin you can just fake the existance of missing functions (34 missing function exactly) at link time. That's what I did in this project : https://github.com/Youssef-Afella/zigxp
I wanna say that I'm not an expert at any of this, I started the project to push myself learn more about OSs and kernels in the first place so any contribution or correction is really appreciated.
It's very unsafe, unpredictable (also breaks multithreading) and probably should have panicked whenever a function of those gets called instead on returning a success message, but if you are looking for an easy drop in solution to see your app in winxp, there you go.
Hey everyone — as a Linux user working on local browser-based design tools, I kept running into the wall where existing open-source CAD kernels either use purely polygonal CSG (OpenSCAD) or require 15+ MB WASM builds (OpenCASCADE) without native implicit field modeling.
I spent the last few months building OpenCAD from scratch in Zig and WebAssembly:
- Pure Math Core (<1 MB WASM): Every curve, surface, and field is an equation evaluated with forward-mode automatic differentiation (dual numbers) and interval arithmetic.
- 3-in-1 Representation: Combines constrained 2D sketches & SE(3) B-Rep sweeps, CSG booleans, and implicit SDF fields (like stress-driven gyroids) in one engine, exporting to STEP and STL.
- Zero-Copy Shared Memory: Uses a single `SharedArrayBuffer` between the Zig WASM kernel, Three.js, and external WASM extensions so simulation fields can drive geometry directly without file exports.
It's still early (currently refining boolean seam triangles and B-Rep edge cases), and I'd love for you to try breaking it and let me know what you think!
I've been using VS Code with the Zig extension to learn, but ngl the tooling makes it way harder for us mere humans.
Like, for complex types generated by comptime, VS Code basically provides zero useful hints. You're stuck reading docs and compiling over and over to test stuff. Check this out:
VS Code can't give you any meaningful help with MyIntType or MyFloatType. Total black box. 🤡
And it gets worse. For some dead simple errors, VS Code won't even yell at you until you actually compile. Like this:
fn a() []bool {
return 12;
}
Like bro, that's a straight-up type mismatch and the editor just sits there doing absolutely nothing. 💀
So I recently had the "genius" idea to just let AI generate Zig code for me. Tbh, AI can look up docs and catch compilation errors way faster than I ever could. It's actually carrying me rn.
From the looks of it, the tooling situation isn't getting fixed anytime soon.
And here's the dark irony: Zig is literally a language that positions itself as "AI-resistant" or whatever, yet writing it as a human is genuinely uncomfortable, while AI seems to handle it just fine. Kinda funny in a sad way, ngl.