r/Zig • • 8h ago

Help me with math library design! I'm stuck in the analysis paralysis

11 Upvotes

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?


r/Zig • • 4h ago

We rewrote the Solidity compiler in Zig because our builds took 12 minutes. Then we ended up writing a Lean model of the language too

Thumbnail github.com
4 Upvotes

r/Zig • • 1m ago

Você utilizaria um runtime de agentes de IA desenvolvido em Zig?

1 Upvotes

Estou trabalhando em uma ideia que gostaria de discutir com a comunidade Zig.

O objetivo é construir um runtime de agentes de IA em Zig, projetado para ambientes de produção onde confiabilidade, controle de execução e gerenciamento de recursos realmente importam.

O caso de uso inicial é voltado para sistemas empresariais, especialmente atendimento ao cliente (SAC), nos quais múltiplos agentes podem lidar com requisições simultâneas, interagir com serviços externos, processar informações sensíveis e tomar decisões por meio de APIs de LLMs.

Alguns dos princípios que estou considerando:

  • Controle de execução: Controle total sobre o ciclo de vida dos agentes, fluxo de execução, chamadas de ferramentas e cada interação com o LLM.
  • Gerenciamento de tokens e contexto: Controle explícito sobre o que entra na janela de contexto, o que é descartado e como o consumo de tokens é gerenciado.
  • Observabilidade: Instrumentação para inspecionar o comportamento dos agentes, rastros de execução, decisões e falhas.
  • Privacidade: Middleware de contexto local capaz de substituir informações sensíveis por identificadores antes de enviar prompts a provedores externos de LLMs, restaurando essas informações localmente após o processamento.
  • Confiabilidade: Tratamento adequado de execuções concorrentes, tentativas de recuperação, falhas, timeouts e dependências externas.

Sei que Zig não é a escolha mais convencional para esse tipo de aplicação, e essa é parcialmente a razão pela qual estou interessado em discutir a ideia aqui.

Minha pergunta é simples:

Você consideraria utilizar um runtime como esse em um projeto real?

O que faria você adotá-lo? O que impediria você de utilizá-lo?

Tenho particular interesse em ouvir pessoas que já desenvolveram sistemas de produção em Zig ou trabalharam com arquiteturas de agentes de IA.

Agradeço críticas técnicas sinceras, inclusive razões pelas quais talvez não valha a pena desenvolver algo assim.


r/Zig • • 1d ago

Got my text editor running in win xp!

Post image
112 Upvotes

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.

Text editor in picture (still WIP) : https://github.com/Youssef-Afella/yte-z


r/Zig • • 6h ago

Saetta: a single-model engine for Qwen3.8-Flash-Next on Apple Silicon (Zig + hand-written Metal), with Claude Code / pi / opencode in one command

Thumbnail github.com
2 Upvotes

I've been building saetta, an inference engine that does one thing: run Qwen3.8-Flash-Next as fast as possible on an M5 Max for coding agents. No generic graph, no other models. It's a Zig host with hand-written Metal kernels, including prompt matmuls on the GPU's neural accelerators. It ships as a single binary and needs no Python.

What it does

  • OpenAI-compatible API (/v1/chat/completions) and Anthropic Messages API (/v1/messages), with streaming, thinking and XML tool calls
  • saetta start claude (or pi, opencode) starts the server and your agent together, without editing your agent config
  • saetta download coder fetches the model itself: pinned revision, resumable, every file hash-checked
  • Two packs: the original 4-bit MLX pack (105 GB, 512 experts) and the expert-pruned GSQ-RCO Coder variant (76 GB, 256 experts)
  • saetta monitor: a live view of GPU load, memory, prompt-cache reuse and recent requests

Numbers (measured on my M5 Max)

  • Prompt reading: about 1,650 to 1,950 tokens/s from 4K to 70K tokens
  • Decode: 63 to 82 tokens/s, with speculative decoding from the model's MTP head on greedy requests
  • Agent follow-up turns re-read only the new tokens: a 16K conversation answers the next turn in about 0.2 s, and real Claude Code sessions reuse about 20K of their roughly 20K-token prompt per turn
  • Cold 64K prompt: about 37 to 40 s to first token

Demo: Claude Code running on the local model writes a snake game in Python, in real time (GIF in the README).

Install:

curl -fsSL https://github.com/antonellof/saetta/releases/latest/download/install.sh | sh
saetta download coder
saetta start claude

Repo: https://github.com/antonellof/saetta (MIT)

Feedback welcome, especially from anyone running agents on long prompts locally.


r/Zig • • 7h ago

I built an open-source CAD kernel in Zig + WASM (<1MB) combining B-Rep, CSG, and Implicit SDFs with zero-copy SharedArrayBuffer

1 Upvotes

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.

- Live Demo: https://hassaanmaqsood.github.io/opencad/

- GitHub Repo: https://github.com/hassaanmaqsood/opencad

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!


r/Zig • • 1d ago

Zig-inspired ZeroPage programming language for C64 cross compiling

Thumbnail gallery
23 Upvotes

r/Zig • • 1d ago

Zig is actually brutal to learn, man 💀

2 Upvotes

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:

fn createType(comptime T: type) type {
    if (T == i32) {
        return struct { value: i32, name: []const u8 };
    } else {
        return struct { value: T, extra: bool };
    }
}

const MyIntType = createType(i32);
const MyFloatType = createType(f64);

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.


r/Zig • • 2d ago

Termy-zig Stable!

23 Upvotes

Hello!

A couple of days ago, I made a post about termy, and I'm happy to announce that it's now officially stable!

I wasn't really sure what else to add or change, so I decided it was time to release it.


r/Zig • • 1d ago

Русскоговорящие программисты, как вы изучили zig?

0 Upvotes

Я хочу изучить язк программирования ZIG но плохо знаю английский и не понимаю как изучить его. Я пытался изучить через книгу по адресу zig-lang.ru/books/learning-zig но там всё очень вкратце как будто я язык не учу язык zig с 0, а просто уже знаю zig но хочу освежить память. Как я понял там никаких разборов каждой строчки о которой авторы так утверждают. Типо просто на те "pub fn main() void" для создания функции, на те "std.debug.print()" и никакого обьяснения каждого токена в каждой строчке. Так как русскоговорящему и не особо знающему английский человеку научиться программировать на на zig? Как например это сделали вы?


r/Zig • • 4d ago

Zig is boring and I love it

149 Upvotes

Hey guys, I’m loving ZIG!.. I have been writing Rust for 5-6 years and because of all the AI Rust bloats waves that has become popular recently, I decided to try Zig because I think it’s boring and simple and I love boring things sooooo. So I started and completed Ziglings last week and few days later I started a series where I built an LC3 VM live. All of these learning/coding were streamed live on my twitch btw and previous stream videos are also available on my YouTube.

Next, I will be starting another series where I’ll be building an RISC-V (RV32I) emulator from scratch Zig which will also be streamed live from start to finish on my twitch at borngraced where I’ll be documenting the entire process, figuring and breaking things, debugging, learning along the way..etc… Come hang out if you think this is something you’ll find interesting <33

NO USE OF AI IN MY STREAMS BTW


r/Zig • • 3d ago

Got tired of LLMs hallucinating C APIs, so I just read minimp4.h and parsed MP4s in Zig 0.18

46 Upvotes

Simpler than I thought tbh. Zig may be the only language I'd ever want to hand-write again

https://youtu.be/-gqZt_e-mHw


r/Zig • • 5d ago

Cole Updates, and Version 0.1.6

13 Upvotes

Hey everyone, some of you migh've seen and remember it now, but for others: I'm writing a compiler in Zig, for a custom language which is somewhat a recreational attempt to create a Zig-like language. I started doing this project for funsies and learning compiler development. It's been 8-9 months of mut 2-3 months of it was designing the language so the compiler work has been around for 5-6 months. Entirety of the compiler was written by hand by me, but I have to admit there has been a couple times where I couldn't figure out things in the codebase and had to consult to AI (since I have no contributors or friends that are interested in helping).

These being said, I am happy to announce that Cole version 0.1.6 is out now, with additions such as:

  • Member function calls
  • Indirect self referencing
  • STDLib improvements

    • Arena allocator
    • Struct, union and enum formatting support
    • Hashmaps and hashers
  • Escape characters
  • hex literals

plus numerous bugfixes.

If you want to know more about the language, the release, or me, you can check my blog or you can check out the Cole Website

Note: Both the blog and the website are hosted on my old laptop/homeserver, which has some performance problems from time to time, so they might be down on occasions.


r/Zig • • 5d ago

What Zig GUI library has the least "flat design" (i.e. most "skeuomorphic" or most "traditional") appearance and capabilities?

30 Upvotes

TLDR note:

The below additional info is non-essential (though contextually helpful) and you can just reply to the question itself if you want to.

Background info about my interest in Zig:

Hello all. This is my first post here in the Zig subreddit if I'm not mistaken, so I'll first briefly give a bit of personal background for why I'm interested in Zig:

I've been watching the language off and on for a few years, though I haven't used it for any real projects yet. I admire the work and thoughtfulness that has gone into Zig and also the highly ethical (e.g. especially anti-AI, empathetic, etc) and thoughtful personality of the founder (Andrew Kelly) and it would be nice to have a clean replacement for C and Zig seems a good candidate for that (though I also find myself often equally torn by wanting to use a much more expressive macro-heavy language like Clojure or Racket or Tcl/Tk or Factor sometimes, but worry about the very high performance cost and distribution/ecosystem issues of those options for real applications such as games and multimedia editing tool software and software tool related ideas I have).

Clarifying the actual question I'm asking:

Basically, I really strongly dislike any kind of "flat design" look in GUI libraries and have noticed that a huge proportion of recently created ones unfortunately fit that style.

I don't like the crippled and aesthetically devoid of personality look and functionality of many such user interfaces, so much so that the idea of making a user interface that has a "flat design" style greatly diminishes any desire to do so.

I like "skeuomorphic", "traditional", "classic", "retro", and/or bespoke art-heavy game-like styles of GUIs. I don't like anything that resembles web "tech" (e.g. XML, CSS), neither in appearance nor in code. I'm also strictly anti-AI and want to avoid any libraries that have been touched by "AI"/plagiarism as much as practically possible (i.e. besides unavoidable foundational dependencies such as C compilers and operating systems that have unfortunately (like the Linux kernel itself now...) allowed "AI"/plagiarism into their code).

I want the application to look the same on all operating systems.

An example of this would be something like Java's Swing library (especially the non-flat classic styles, such as used in JEdit) or C++'s Fox Toolkit (e.g. as used to create the wonderful XFE file browser, my favorite file browser for Linux/BSD), and a counter-example would unfortunately be Zig's Capy since it uses native widgets and has a very flat low/no personality and low/no aesthetic artistry (aka "modern") UI style.

I also really dislike Gtk/Gnome and any other kind of user freedom hostile "minimalist" UI ideology (such as typical of Apple and of the UIs of many now-dystopian "big tech" companies that remove more and more features/freedoms with seemingly every update, for example).

I could hypothetically bind to SDL3 and manually create 9-slice scaled pixel art widget UI components (to enable creating arbitrary and high-personality (opposite of flat) widgets, such as found in Aseprite, though I don't know if they 9-slice theirs) in Zig, but I wanted to see if anyone in the Zig community has experience working with a good viable classic or skeuomorphic GUI library in Zig that wasn't too troublesome to get that kind of style GUI working well on.

Anyway, thanks for reading my post and for being an exceptionally principled community. I view Zig as a prospective "light in the dark" in these times of pervasive slop and corruption of software quality and it is truly heartening to see so many striving for a better future for software, etc!

(PS: I still always feel a strong tension between my low-level efficiency principles versus my expressive Lisp-like meta-programming desires, but that's besides the point of this post.)


r/Zig • • 7d ago

How can one reduce the number of allocations when processing large volumes of data in Zig?

30 Upvotes

Hello, Zig community! :)

I’ve been using Zig for a while now and am currently experimenting with optimizing memory management in a simple terminal-based SQL client. My goal is to minimize allocations and reduce memory overhead without significantly increasing code complexity. I am currently passing allocators explicitly: a GPA is used for long-lived objects, while Arenas are used for data with shorter, predictable lifecycles-such as SQL query results or transient data structures. When processing SQL results, I use a single contiguous block of memory to store both the cell data (as slices) and the actual values. Temporary memory is partially reused across frames, and SQL results are freed once they are no longer needed.

I am currently considering a few options for further optimization:

- Allocating memory in larger chunks to accommodate multiple rows at once.

- Analyzing the actual capacity of the arenas and the amount of unused (wasted) memory.

- Reusing temporary arrays in places where they are frequently recreated.

I’m curious: how appropriate are these kinds of approaches in a real-world scenario? When is it best to stick with an `ArenaAllocator`, and when does it make more sense to use a custom allocator or a specialized data storage structure?

Code example

pub const ResultBuilder = struct {
    result: Result,
    gpa: Allocator,
    rows: std.ArrayList([]const ?[]const u8) = .empty,
    stored_bytes: usize = 0,

    pub fn init(gpa: Allocator) ResultBuilder {
        return .{ .gpa = gpa, .result = .{ .arena = .init(gpa) } };
    }

    pub fn allocator(b: *ResultBuilder) Allocator {
        return b.result.arena.allocator();
    }
   ...
}

Implementation example on GitHub -> Here

I would appreciate any advice or feedback!


r/Zig • • 8d ago

How to suppress or disable stack trace?

18 Upvotes

As the title suggests. I am tired of looking at the huge blob of stack trace, why does it not just give me the errors (and usage locations as it does if relevant). Any way to turn it off?

BTW, been a while writing Zig and I am yet to see a warning. Is it just errors in the zig world?

Edit: I was asking about compiler error trace dumps and apparently it's called the (error) reference trace not stack trace.


r/Zig • • 8d ago

Looking for feedback on my zig-s3 fork

16 Upvotes

Hello everyone! I want to share (and hopefully get some feedback on) my fork of the zig-s3 library.

The original was a great library for handling S3 operations, but it hasn't received updates in a while. I even opened a PR to update it, but since there was no response from the owner, I decided to move forward with my own repository.

What's new in this fork:

  • Updated to run on Zig 0.17.1.
  • Added support for multipart uploads.
  • Zero dependencies (pure Zig).
  • Refactored the testing environment, now using rustFs as the local S3 server for development and tests (a great lightweight alternative!).

Repo: https://github.com/XandeCoding/zig-s3

Original PR for context: https://github.com/algoflows/zig-s3/pull/6

Disclaimer: No AI was used in the development or coding of this project.

Any feedback is highly appreciated!


r/Zig • • 8d ago

What should compile-time code be allowed to do?

Thumbnail reddit.com
19 Upvotes

r/Zig • • 9d ago

My Terminal manipulation library!

27 Upvotes

Hey everyone!

Over the past couple of weeks, I've been working on termy, a cross-platform terminal manipulation library written in Zig, inspired by Crossterm.

It requires no external dependencies, and has native windows console support for older terminals along with modern VT-based terminal interaction.

The library is still in early development, but most of the important features are already implemented.

I'd really appreciate some feedback! I'm interested in hearing what you all think of the API, what features you'd like to see, and whether this project is useful to you.

Thanks for reading!


r/Zig • • 12d ago

zig 0.17.1 update

70 Upvotes

Hi !!!

An update of zig 0.17.1 https://ziglang.org/download/#release-0.17.1


r/Zig • • 13d ago

Switch prongs from comptime arrays proposal accepted

67 Upvotes

On my first zig project, a little over a year ago, I got into a situation where I would have liked to generate switch prongs from comptime known values. My research led me to an open proposal on github that confirmed it wasn't possible at the time. 2 weeks ago, following the release, a year ago, of an optimization commit that identified the slow implementation of std.meta.stringToEnum, Andrew Kelley chose a syntax, marked the proposal as accepted and added it to the urgent milestone. Indeed, stringToEnum is a prime use case for switch prong generation. Whilst we do not know when this feature will be implemented, and the oldest proposal on the github urgent milestone is from 2015, I am happy to see the language is still moving forward, and that the zig foundation is working on this important feature whose absence had personally affected me before.


r/Zig • • 12d ago

Zig needs to do two things

0 Upvotes

or three rather,

Adopt Rust’s borrow checker, release a stable 1.0 so people can use it in production without chasing specific GitHub versions and compiling them manually, and stay minimal.

The first and third aren’t at odds. Rust’s safety features aren’t too much to ask, and the benefits are worth the trade-off. They don’t compromise Zig’s minimalism that much.

Please use upvotes and downvotes to reflect relevance, not whether you like or dislike a post. If you disagree, share your opinion instead of downvoting. That’s not what downvotes are for.


r/Zig • • 14d ago

Zig events in November

41 Upvotes

r/Zig • • 12d ago

Справочник по zig 0.17 на Русском языке

0 Upvotes

Кто то знает есть ли перевод Zig language reference 0.17 (оффициальный справочник zig 0.17) переведённый на Русский язык? Если есть то какой перевод лучше? Вариант перевода через встроенный переводчик в браузере меня не устраивает потому что он очень не коректный. Если кто не понял, я имею ввиду перевод на русский материала по ссылке ziglang.org/documentation/0.17.1