r/Zig • • 15h ago

Got my text editor running in win xp!

Post image
97 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 • • 16h ago

Zig-inspired ZeroPage programming language for C64 cross compiling

Thumbnail gallery
19 Upvotes

r/Zig • • 16h ago

Zig is actually brutal to learn, man 💀

0 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 • • 3d ago

Zig is boring and I love it

146 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

45 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 • • 4d 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 • • 6d 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 • • 7d 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 • • 7d 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 • • 7d ago

What should compile-time code be allowed to do?

Thumbnail reddit.com
19 Upvotes

r/Zig • • 8d 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 • • 11d 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 • • 12d 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 • • 11d 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 • • 13d 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


r/Zig • • 15d ago

Updates on Cole, and Version 0.1.4 announcement

Thumbnail reddit.com
9 Upvotes

Hello everyone, I wanted to share my Zig project with you, I hope it is suitable for this subreddit.

Cole is essentially a recreational attempt to create a Zig-like language in Zig, through trial and error. I'm testing how far I can go as a self-taught programmer and trying to create an easy-to-get-in project for people wanting a door into compiler dev.

Any feedback (especially offensive ones) is welcome!

Edit: This project is also how I learned Zig in the first place!


r/Zig • • 15d ago

"Mixing initialized and uninitialized data bloats the executable size"?

17 Upvotes

I was reading the source for this pacman game written in Zig and Sokol, and there's a comment on line 401: "keep the big undefined data out of the state struct, mixing initialized and uninitialized data bloats the executable size". From what I gather, this has to do how static memory is stored in the binary, which is a little beyond me but makes sense. But what should I do about it? The repo has it segregated into its own top-level struct, but why can't it be a sub-struct like the other things in State? It doesn't seem very ergonomic to have a second state struct of members whose only unifying feature is that they're "too big".


r/Zig • • 15d ago

How I easily reduced allocation overhead in my database

Thumbnail
github.com
25 Upvotes

r/Zig • • 16d ago

Please, help me with understanding std.Io.Reader.discardRemaining()

22 Upvotes

I am writing a small tic-tac-toe program in ZIg, because I want to practice what I have learnt by doing exercises from Ziglings. I got to the part where I needed to take a single byte of a user's input.

For that I used Reader's takeByte() method:

pub fn main(init: std.process.Init) !void {
    const stdin = std.Io.File.stdin();
    var stdin_buffer: [1]u8 = undefined; // I only need the first byte
    var stdin_reader = stdin.reader(init.io, &stdin_buffer);
    // ...
    const b = try stdin_reader.interface.takeByte();
    // ...
}

Well, here Zig forced me to learn that a terminal has its input queue and that if I don't deal with the rest of potential input bytes, they will be carried on, so an input like this 3rm -rf will kill my computer, because my program will consume the "3" and then my terminal will execute the rest of the input.

I needed a way to discard the rest of the bytes. In my research I have also learned about Termios interface that I can use in order to control my terminal. And Zig's std has tools for that:

pub fn main(init: std.process.Init) !void {
    const stdin = std.Io.File.stdin();
    const termios = try std.posix.tcgetattr(stdin.handle);
    defer std.posix.tcsetattr(stdin.handle, .FLUSH, termios) catch {};
    // ...
    const b = try stdin_reader.interface.takeByte();
    // ...
}

And it worked! But I then thought controlling terminal for simple user input had to be an overkill, and that there had to be a simpler way.

So, finally, I have found std.Io.Reader.discardRemaining():

pub fn main(init: std.process.Init) !void {
    // ...
    const b = try stdin_reader.interface.takeByte();
    const discardedLength = try stdin_reader.interface.discardRemaining();
    // ...
}

But now the problem is that my program hangs inside the discardRemaining and never leaves. The closest issue I could find was this one, but it was fixed in version 0.15 and I am now on Zig version 0.17.0.

Could you, please, help me understand, what I am missing here? I am pretty sure I forgot (more probably I don't know) to do something.

Your help is much appreciated!


r/Zig • • 16d ago

My zig-made hobby hypervisor booting multiple guests!

Thumbnail
gallery
63 Upvotes

(hobby project-showcase)

source: https://github.com/NoamRothschild/hypervisor

context:

since my hypervisor got linux running, I did a ton of work, including

- simulating the existence of more than 1 physical core per guest

- launching multiple guests

- starting networking (expose virtio-net driver and MAC addr to guest)

this was.. a lot of work...

in short, I had to:

- learn how linux probes for the cpu count, and make it see them all

- learn how computers launch secondary cores

- cry and bang my head against the wall because I knew nothing

- virtualize the hardware responsible for bringing the cores

- write a scheduler so they all will run

- learn about PCI and use it to expose a network device

and much much more!

In the GIF:

on the left are the hypervisors logs, and on the right are two linux instances booting up. you can see the linux logs and at the end even running commands on them.

In the Image:

one linux instance with 8 cores running. in the output of the cat command you can see CPU0..CPU7

>,<

AI Disclaimer

I do use AI for my projects. This does not mean the projects are "vibe-coded", but AI-Assisted. I read every line of code, I learn every bit of technology, and I never commit code I don't understand or couldn't replicate on my own without AI.

AI is a powerful technology, and when used in the right places (for instance, learning) it can enable you to go to places you couldn't otherwise go to.