avatar_url
stringlengths
47
116
name
stringlengths
1
46
full_name
stringlengths
7
60
created_at
stringdate
2016-04-01 08:17:56
2025-05-20 11:38:17
description
stringlengths
0
387
default_branch
stringclasses
44 values
open_issues
int64
0
4.93k
stargazers_count
int64
0
78.2k
forks_count
int64
0
3.09k
watchers_count
int64
0
78.2k
tags_url
stringlengths
0
94
license
stringclasses
27 values
topics
listlengths
1
20
size
int64
0
4.82M
fork
bool
2 classes
updated_at
stringdate
2018-11-13 14:41:18
2025-05-22 08:23:54
has_build_zig
bool
2 classes
has_build_zig_zon
bool
2 classes
zig_minimum_version
stringclasses
50 values
repo_from
stringclasses
3 values
dependencies
listlengths
0
38
readme_content
stringlengths
0
437k
dependents
listlengths
0
21
https://avatars.githubusercontent.com/u/206480?v=4
metrics.zig
karlseguin/metrics.zig
2024-01-18T10:36:15Z
Prometheus metrics for library and application developers
master
0
52
4
52
https://api.github.com/repos/karlseguin/metrics.zig/tags
MIT
[ "metrics", "prometheus", "prometheus-client", "zig", "zig-library", "zig-package" ]
78
false
2025-05-08T08:16:28Z
true
true
unknown
github
[]
Prometheus Metric Library for Zig This library is designed for both library and application developers. I do hope to streamline setup when comptime allocations are allowed. It supports, counters, gauges and histograms and the labeled-variant of each. Please see the example project. It demonstrates how a <a>library developer</a>, and how an <a>application developer</a> can initialize and output them. Metric Setup Setup is a bit tedious, and I welcome suggestions for improvement. Let's start with a basic example. While the metrics within this library can be used directly, I believe that each library/application should create its own <code>Metrics</code> struct that encapsulates all metrics. A global instance of this struct can be created and initialized at comptime into a "noop" state. ```zig const m = @import("metrics"); // defaults to noop metrics, making this safe to use // whether or not initializeMetrics is called var metrics = m.initializeNoop(Metrics); const Metrics = struct { // counter can be a unsigned integer or floats hits: m.Counter(u32), <code>// gauge can be an integer or float connected: m.Gauge(u16), </code> }; // meant to be called within the application pub fn hit() void { metrics.hits.incr(); } // meant to be called within the application pub fn connected(value: u16) void { metrics.connected.set(value); } // meant to be called once on application startup pub fn initializeMetrics(comptime opts: m.RegistryOpts) !void { metrics = .{ .hits = m.Counter(u32).init("hits", .{}, opts), .connected = m.Gauge(u16).init("connected", .{}, opts), }; } // thread safe pub fn writeMetrics(writer: anytype) !void { return m.write(&amp;metrics, writer); } ``` The call to <code>m.initializeNoop(Metrics)</code> creates a <code>Metrics</code> and initializes each metric (<code>hits</code>, <code>connected</code> and <code>latency</code>) to a "noop" implementation (tagged unions are used). The <code>initializeMetrics</code> is called on application startup and sets these metrics to real implementation. For library developers, this means their global metrics are always safe to use (all methods call noop). For application developers, it gives them control over which metrics to enable. All metrics take a name and <strong>two options</strong>. Why two options? The first is designed for library developers, the second is designed to give application developers additional control. Currently the first option has a single field: * <code>help: ?[]const u8 = nulls</code> - Used to generate the <code># HELP $HELP</code> output line The second option should has two fields: * <code>prefix: []const u8 = ""</code> - Appends <code>prefix</code> to the start of each metric name. * <code>exclude: ?[]const []const u8 = null</code> - A list of metric names to exclude (not including the prefix). <code>CounterVec</code>, <code>GaugeVec</code>, <code>Histogram</code> and <code>HistogramVec</code> also require an allocator. Note for Library Developers Library developers are free to change the above as needed. However, having libraries consistently expose an <code>initializeMetrics</code> and <code>writeMetrics</code> should help application developers. Library developers should ask their users to call <code>try initializeMetrics(allocator, .{})</code> on startup and <code>try writeMetrics(writer)</code> to generate the metrics. The <code>RegistryOpts</code> parameter should be supplied by the application and passed to each metric-initializer as-is. Labels (vector-metrics) Every metric type supports a vectored variant. This allows labels to be attached to metrics. This metrics require an <code>std.mem.Allocator</code> and, as you'll see in the metric API section, most of their methods can fail. ```zig var metrics = m.initializeNoop(Metrics); const Metrics = struct { hits: m.CounterVec(u32, struct{status: u16, name: []const u8}), }; // All labeled metrics require an allocator pub fn initializeMetrics(allocator: Allocator, opts: m.RegistryOpts) !void { metrics = .{ .hits = try m.CounterVec(u32, struct{status: u16, name: []const u8}).init(allocator, "hits", .{}, opts), }; } ``` The labels are strongly types. Valid label types are: <code>ErrorSet</code>, <code>Enum</code>, <code>Type</code>, <code>Bool</code>, <code>Int</code> and <code>[]const u8</code> The <code>CounterVec(u32, ...)</code> has to be typed twice: once in the definition of <code>Metrics</code> and once in <code>initializeMetrics</code>. This can be improved slightly. ```zig var metrics = m.initializeNoop(Metrics); const Metrics = struct { hits: Hits, <code>const Hits = m.CounterVec(u32, struct{status: u16, name: []const u8}); </code> }; pub fn initializeMetrics(allocator: Allocator, opts: m.RegistryOpts) !void { metrics = .{ .hits = try Metrics.Hits.init(allocator, "hits", .{}, opts), }; } // Labels are compile-time checked. Using "anytype" here // is just lazy so we don't have to declare the label structure pub fn hit(labels: anytype) !void { return metrics.hits.incr(labels); } ``` The above would be called as: <code>zig // import your metrics file const metrics = @import("metrics.zig"); metrics.hit(.{.status = 200, .path = "/about.txt"});</code> Internally, every metric is a union between a "noop" and an actual implementation. This allows metrics to be globally initialized as noop and then enabled on startup. The benefit of this approach is that library developers can safely and easily use their metrics whether or not the application has enabled them. Histograms Histograms are setup like <code>Counter</code> and <code>Gauge</code>, and have a vectored-variant, but they require a comptime list of buckets: ```zig const Metrics = struct { latency: Latency, <code>const Latency = m.Histogram(f32, &amp;.{0.005, 0.01, 0.05, 0.1, 0.25, 1, 5, 10}); </code> }; pub fn initializeMetrics(opts: m.RegistryOpts) !void { metrics = .{ .latency = Metrics.Latency.init("hits", .{}, opts), }; } ``` The <code>HistogramVec</code> is even more verbose, requiring the label struct and bucket list. And, like all vectored metrics, requires an <code>std.mem.Allocator</code> and can fail: ```zig var metrics = m.initializeNoop(Metrics); const Metrics = struct { latency: Latency, <code>const Latency = m.HistogramVec( u32, struct{path: []const u8}, &amp;.{5, 10, 25, 50, 100, 250, 500, 1000} ); </code> }; pub fn initializeMetrics(allocator: Allocator, opts: m.RegistryOpts) !void { metrics = .{ .latency = try Metrics.Latency.init(allocator, "hits", .{}, opts), }; } // Labels are compile-time checked. Using "anytype" here // is just lazy so we don't have to declare the label structure // Would be called as: // @import("metrics.zig").recordLatency(.{.path = "robots.txt"}, 2); pub fn recordLatency(labels: anytype, value: u32) !void { return metrics.latency.observe(labels, value); } ``` Metrics Utility The package exposes the following utility functions. <code>initializeNoop(T) T</code> Creates an initializes metric <code>T</code> with <code>noop</code> implementation of every metric field. <code>T</code> should contain only metrics (<code>Counter</code>, <code>Gauge</code>, <code>Historgram</code> or their vectored variants) and primitive fields (int, bool, []const u8, enum, float). <code>initializeNoop(T)</code> will set any non-metric field to its default value. This method is designed to allow a global "metrics" instance to exist and be safe to use within libraries. <code>write(metrics: anytype, writer anytype) !void</code> Calls the <code>write(writer) !void</code> method on every metric field within <code>metrics</code>. Library developers are expected to wrap this method in a <code>writeMetric(writer: anytype) !void</code> function. This function requires a pointer to your metrics. Counter(T) A <code>Counter(T)</code> is used for incrementing values. <code>T</code> can be an unsigned integer or a float. Its two main methods are <code>incr()</code> and <code>incrBy(value: T)</code>. <code>incr()</code> is a short version of <code>incrBy(1)</code>. <code>init(comptime name: []const, comptime opts: Opts, comptime ropts: RegistryOpts) !Counter(T)</code> Initializes the counter. Opts is: * <code>help: ?[]const</code> - optional help text to include in the prometheus output <code>incr(self: *Counter(T)) void</code> Increments the counter by 1. <code>incrBy(self: *Counter(T), value: T) void</code> Increments the counter by <code>value</code>. <code>write(self: *const Counter(T), writer: anytype) !void</code> Writes the counter to <code>writer</code>. CounterVec(T, L) A <code>CounterVec(T, L)</code> is used for incrementing values with labels. <code>T</code> can be an unsigned integer or a float. <code>L</code> must be a struct where the field names and types will define the lables. Its two main methods are <code>incr(labels: L)</code> and <code>incrBy(labels: L, value: T)</code>. <code>incr(L)</code> is a short version of <code>incrBy(L, 1)</code>. <code>init(allocator: Allocator, comptime name: []const, comptim eopts: Opts, comptime ropts: RegistryOpts) !CounterVec(T, L)</code> Initializes the counter. Name must be given at comptime. Opts is: * <code>help: ?[]const</code> - optional help text to include in the prometheus output <code>deinit(self: *CounterVec(T, L)) void</code> Deallocates the counter <code>incr(self: *CounterVec(T, L), labels: L) !void</code> Increments the counter by 1. Vectored metrics can fail. <code>incrBy(self: *CounterVec(T, L), labels: L, value: T) !void</code> Increments the counter by <code>value</code>. Vectored metrics can fail. <code>remove(self: *CounterVec(T, L), labels: L) void</code> Removes the labeled value from the counter. Safe to call if <code>labels</code> is not an existing label. <code>write(self: *CounterVec(T, L), writer: anytype) !void</code> Writes the counter to <code>writer</code>. Gauge(T) A <code>Gauge(T)</code> is used for setting values. <code>T</code> can be an integer or a float. Its main methods are <code>incr()</code>, <code>incrBy(value: T)</code> and <code>set(value: T)</code>. <code>incr()</code> is a short version of <code>incrBy(1)</code>. <code>init(comptime name: []const, comptime opts: Opts, comptime ropts: RegistryOpts) !Gauge(T)</code> Initializes the gauge. Name must be given at comptime. Opts is: * <code>help: ?[]const</code> - optional help text to include in the prometheus output <code>incr(self: *Gauge(T)) void</code> Increments the gauge by 1. <code>incrBy(self: *Gauge(T), value: T) void</code> Increments the gauge by <code>value</code>. <code>set(self: *Gauge(T), value: T) void</code> Sets the the gauge to <code>value</code>. <code>write(self: *Gauge(T), writer: anytype) !void</code> Writes the gauge to <code>writer</code>. GaugeVec(T, L) A <code>GaugeVec(T, L)</code> is used for incrementing values with labels. <code>T</code> can be an integer or a float. <code>L</code> must be a struct where the field names and types will define the lables. Its main methods are <code>incr(labels: L)</code>, <code>incrBy(labels: L, value: T)</code> and <code>set(labels: L, value: T)</code>. <code>incr(L)</code> is a short version of <code>incrBy(L, 1)</code>. <code>init(allocator: Allocator, comptime name: []const, comptime opts: Opts, comptime ropts: RegistryOpts) !GaugeVec(T, L)</code> Initializes the gauge. Name must be given at comptime. Opts is: * <code>help: ?[]const</code> - optional help text to include in the prometheus output <code>deinit(self: *GaugeVec(T, L)) void</code> Deallocates the gauge <code>incr(self: *GaugeVec(T, L), labels: L) !void</code> Increments the gauge by 1. Vectored metrics can fail. <code>incrBy(self: *GaugeVec(T, L), labels: L, value: T) !void</code> Increments the gauge by <code>value</code>. Vectored metrics can fail. <code>set(self: *GaugeVec(T, L), labels: L, value: T) !void</code> Sets the gauge to <code>value</code>. Vectored metrics can fail. <code>remove(self: *GaugeVec(T, L), labels: L) void</code> Removes the labeled value from the gauge. Safe to call if <code>labels</code> is not an existing label. <code>write(self: *GaugeVec(T, L), writer: anytype) !void</code> Writes the gauge to <code>writer</code>. Histogram(T, []T) A <code>Histogram(T, []T)</code> is used to track the size and frequency of events. <code>T</code> can be an unsigned integer or a float. Its main methods is <code>observe(T)</code>. Observed valued will fall within one of the provided buckets, <code>[]T</code>. The buckets must be in ascending order. A final "infinite" bucket <em>should not</em> be provided. <code>init(comptime name: []const, comptime opts: Opts, comptime ropts: RegistryOpts) !Histogram(T, []T)</code> Initializes the histogram. Name must be given at comptime. Opts is: * <code>help: ?[]const</code> - optional help text to include in the prometheus output <code>observe(self: *Histogram(T, []T), value: T) void</code> Observes <code>value</code>, bucketing it based on the provided comptime buckets. <code>write(self: *Histogram(T, []T), writer: anytype) !void</code> Writes the histogram to <code>writer</code>. Histogram(T, L, []T) A <code>Histogram(T, L, []T)</code> is used to track the size and frequency of events. <code>T</code> can be an unsigned integer or a float. <code>L</code> must be a struct where the field names and types will define the lables. Its main methods is <code>observe(T)</code>. Observed valued will fall within one of the provided buckets, <code>[]T</code>. The buckets must be in ascending order. A final "infinite" bucket <em>should not</em> be provided. <code>init(allocator: Allocator, comptime name: []const, comptime opts: Opts, comptime ropts: RegistryOpts) !Histogram(T, L, []T)</code> Initializes the histogram. Name must be given at comptime. Opts is: * <code>help: ?[]const</code> - optional help text to include in the prometheus output <code>deinit(self: *Histogram(T, L, []T)) void</code> Deallocates the histogram <code>observe(self: Histogram(T, L, []T), value: T) void</code> Observes <code>value</code>, bucketing it based on the provided comptime buckets. <code>remove(self: *Histogram(T, L, []T), labels: L) void</code> Removes the labeled value from the histogram. Safe to call if <code>labels</code> is not an existing label. <code>write(self: Histogram(T, L, []T), writer: anytype) !void</code> Writes the histogram to <code>writer</code>.
[]
https://avatars.githubusercontent.com/u/109492796?v=4
learning-zig
zigcc/learning-zig
2023-09-27T00:11:03Z
《Learning Zig》中文翻译
main
1
52
8
52
https://api.github.com/repos/zigcc/learning-zig/tags
MIT
[ "documentation", "zig", "zig-doc", "zig-lang", "ziglang" ]
175
false
2025-05-19T07:38:59Z
false
false
unknown
github
[]
<a>Learning Zig</a> 中文翻译 <a></a> <a></a> <blockquote> <span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span> 迁移到 <a>zigcc.github.io</a> 仓库维护。 </blockquote>
[]
https://avatars.githubusercontent.com/u/104173612?v=4
riscv-barebones
zig-osdev/riscv-barebones
2023-07-12T14:58:25Z
Barebones RISC-V kernel template for Zig
main
0
50
2
50
https://api.github.com/repos/zig-osdev/riscv-barebones/tags
0BSD
[ "barebones", "freestanding", "kernel", "osdev", "risc-v", "starter", "template", "zig" ]
20
false
2025-05-18T14:23:28Z
true
false
unknown
github
[]
RISC-V Barebones Template This repository contains a barebones template for the RISC-V architecture. Resources <ul> <li><a>Stephen Mars' OS Blog</a></li> <li><a>OS Dev Wiki, RISC-V Bare Bones</a></li> <li><a>RISC-V Instruction Green Card</a></li> <li><a>RISC-V Unprivileged ISA</a></li> <li><a>RISC-V Privileged ISA</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/5885545?v=4
zigdown
JacobCrabill/zigdown
2023-02-23T16:17:59Z
Markdown parser in Zig
main
1
49
4
49
https://api.github.com/repos/JacobCrabill/zigdown/tags
MIT
[ "markdown", "terminal", "zig", "zig-package" ]
1,593
false
2025-05-20T14:28:18Z
true
true
0.14.0
github
[ { "commit": "5a650f9439b2b2d8ca5e498b349e25bb7308f7bb.tar.gz", "name": "stbi", "tar_url": "https://github.com/JacobCrabill/zig-stb-image/archive/5a650f9439b2b2d8ca5e498b349e25bb7308f7bb.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/JacobCrabill/zig-stb-image" }, { "commit"...
Zigdown: Markdown toolset in Zig <code>{toctree} &lt;This block will be rendered as a Table of Contents&gt;</code> Zigdown, inspired by <a>Glow</a> and <a>mdcat</a>, is a tool to parse and render Markdown-like content to the terminal or to HTML. It can also serve up a directory of files to your browser like a psuedo-static web site, or present a set of files interactively as an in-terminal slide show. This will likely forever be a WIP, but it currently supports the the most common features of simple Markdown files. <code>{warning} This is not a CommonMark-compliant Markdown parser, nor will it ever be one!</code> Features &amp; Future Work Parser 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> Headers <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 text formatting (<strong>Bold</strong>, <em>italic</em>, ~underline~) - I may change ~this~ back to strikethrough and add another syntax for underline <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> Links <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> Quote blocks <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> Unordered lists <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Ordered lists <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Code blocks, including syntax highlighting using TreeSitter <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> Task lists <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Tables <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> Autolinks Renderer 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> Console and HTML 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> Images (rendered to the console using the <a>Kitty graphics protocol</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> Web-based images (fetch from URL &amp; display in-terminal) <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> (Clickable) Links <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> Tables <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 Table of Contents creation <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> Neovim integration (Lua) - Optional: If you have Lua 5.1 system libraries, can build as a Lua plugin module <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> Markdown formatter Future Work / Missing Pieces <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> Enabling TreeSitter parsers to be used in WASM modules - Requires filling in some libC stub functions (the TS parsers use quite a few functions from the C standard library that are not available in WASM) <br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Better handling of inline code spans &amp; backtick strings <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> Character escaping <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> Complete NeoVim integration (w/ image rendering and auto-scrolling) - Requires writing a renderer in Lua using NeoVim APIs <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> <a>Link References</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> GitHub-flavored note/info boxes? (not a fan of the syntax, but such is life) <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> Color schemes for syntax highlighting Caveats Note that I am <strong>not</strong> planning to implement complete CommonMark specification support, or even full Markdown support by any definition. Rather, the goal is to support "nicely formatted" Markdown, making some simplifying assumptions about what constitutes a paragraph vs. a code block, for example. The "nicely formatted" caveat simplifies the parser somewhat, enabling easier extension for new features like special warnings, note boxes, and other custom directives. In addition to my "nicely formatted" caveat, I am also only interested in supporting a very common subset of all Markdown syntax, and ignoring anything I personally find useless or annoying to parse. Things I Will Not Support <ul> <li>Setext headings</li> <li>Thematic breaks</li> <li>Embedded HTML</li> <li>Indent-based code blocks (as opposed to fenced code blocks)</li> </ul> Usage The current version of Zig this code compiles with is <a>0.14.0</a>. I highly recommend using the <a>Zig version manager</a> to install and manage various Zig versions. <code>bash zig build run -- console test/sample.md zig build -l # List build options zig build -Dtarget=x86_64-linux-musl # Compile for x86-64 Linux using # statically-linked MUSL libC</code> <code>zig build</code> will create a <code>zigdown</code> binary at <code>zig-out/bin/zigdown</code>. Add <code>-Doptimize=ReleaseSafe</code> to enable optimizations while keeping safety checks and backtraces upon errors. The shorthand options <code>-Dsafe</code> and <code>-Dfast</code> also enable ReleaseSafe and ReleaseFast, respectively. Enabling Syntax Highlighting To enable syntax highlighting within code blocks, you must install the necessary TreeSitter language parsers and highlight queries for the languages you'd like to highlight. This can be done by building and installing each language into a location in your <code>$LD_LIBRARY_PATH</code> environment variable. Built-In Parsers Zigdown comes with a number of TreeSitter parsers and highlight queries built-in: <ul> <li>bash</li> <li>C</li> <li>C++</li> <li>CMake</li> <li>JSON</li> <li>Make</li> <li>Python</li> <li>Rust</li> <li>YAML</li> <li>Zig</li> </ul> The parsers are downloaded from Github and the relevant source files are added to the build, and the queries are stored at <code>data/queries/</code>, which contain some fixes and improvements to the original highlighting queries. Installing Parsers Using Zigdown The Zigdown cli tool can also download and install parsers for you. For example, to download, build, and install the C and C++ parsers and their highlight queries: <code>bash zigdown install-parsers c,cpp # Assumes both exist at github.com/tree-sitter on the 'master' branch zigdown install-parsers maxxnino:zig # Specify the Github user; still assumes the 'master' branch zigdown install-parsers tree-sitter:master:rust # Specify Github user, branch, and language</code> Installing Parsers Manually You can also install manually if Zigdown doesn't properly fetch the repo for you (or if the repo is not setup in a standard manner and requires custom setup). For example, to install the C++ parser from the default tree-sitter project on Github: ```bash !/usr/bin/env bash Ensure the TS_CONFIG_DIR is available export TS_CONFIG_DIR=$HOME/.config/tree-sitter/ mkdir -p ${TS_CONFIG_DIR}/parsers cd ${TS_CONFIG_DIR}/parsers Clone and build a TreeSitter parser library git clone https://github.com/tree-sitter/tree-sitter-cpp cd tree-sitter-cpp make install PREFIX=$HOME/.local/ Add the install directory to LD_LIBRARY_PATH (if not done so already) export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HOME/.local/lib/ ``` In addition to having the parser libraries available for <code>dlopen</code>, you will also need the highlight queries. For this, use the provided bash script <code>./tools/fetch_queries.sh</code>. This will install the queries to <code>$TS_CONFIG_DIR/queries</code>, which defaults to <code>$HOME/.config/tree-sitter/queries</code>. Sample Renders Console HTML
[ "https://github.com/JacobCrabill/doczy", "https://github.com/JacobCrabill/slidey" ]
https://avatars.githubusercontent.com/u/33050391?v=4
myzql
speed2exe/myzql
2023-07-29T15:22:58Z
MySQL and MariaDB driver in native Zig
main
1
49
3
49
https://api.github.com/repos/speed2exe/myzql/tags
MIT
[ "driver", "mariadb", "mysql", "sql", "zig", "zig-library", "zig-package" ]
421
false
2025-05-04T15:40:35Z
true
false
unknown
github
[]
MyZql <ul> <li>MySQL and MariaDB driver in native zig</li> </ul> Status <ul> <li>Beta</li> </ul> Version Compatibility | MyZQL | Zig | |-------------|---------------------------| | 0.0.9.1 | 0.12.0 | | 0.13.2 | 0.13.0 | | 0.14.0 | 0.14.0 | | main | 0.14.0 | Features <ul> <li>Native Zig code, no external dependencies</li> <li>TCP protocol</li> <li>Prepared Statement</li> <li>Structs from query result</li> <li>Data insertion</li> <li>MySQL DateTime and Time support</li> </ul> Requirements <ul> <li>MySQL/MariaDB 5.7.5 and up</li> </ul> TODOs <ul> <li>Config from URL</li> <li>Connection Pooling</li> <li>TLS support</li> </ul> Add as dependency to your Zig project <ul> <li> <code>build.zig</code> <code>zig //... const myzql_dep = b.dependency("myzql", .{}); const myzql = myzql_dep.module("myzql"); exe.addModule("myzql", myzql); //...</code> </li> <li> <code>build.zig.zon</code> <code>zon // ... .dependencies = .{ .myzql = .{ // choose a tag according to "Version Compatibility" table .url = "https://github.com/speed2exe/myzql/archive/refs/tags/0.13.2.tar.gz", .hash = "1220582ea45580eec6b16aa93d2a9404467db8bc1d911806d367513aa40f3817f84c", } }, // ...</code> </li> </ul> Usage <ul> <li>Project integration example: <a>Usage</a></li> </ul> Connection ```zig const myzql = @import("myzql"); const Conn = myzql.conn.Conn; pub fn main() !void { // Setting up client var client = try Conn.init( allocator, &amp;.{ .username = "some-user", // default: "root" .password = "password123", // default: "" .database = "customers", // default: "" <code> // Current default value. // Use std.net.getAddressList if you need to look up ip based on hostname .address = std.net.Address.initIp4(.{ 127, 0, 0, 1 }, 3306), // ... }, ); defer client.deinit(); // Connection and Authentication try client.ping(); </code> } ``` Querying ```zig const OkPacket = protocol.generic_response.OkPacket; pub fn main() !void { // ... // You can do a text query (text protocol) by using <code>query</code> method on <code>Conn</code> const result = try c.query("CREATE DATABASE testdb"); <code>// Query results can have a few variant: // - ok: OkPacket =&gt; query is ok // - err: ErrorPacket =&gt; error occurred // In this example, res will either be `ok` or `err`. // We are using the convenient method `expect` for simplified error handling. // If the result variant does not match the kind of result you have specified, // a message will be printed and you will get an error instead. const ok: OkPacket = try result.expect(.ok); // Alternatively, you can also handle results manually for more control. // Here, we do a switch statement to handle all possible variant or results. switch (result.value) { .ok =&gt; |ok| {}, // `asError` is also another convenient method to print message and return as zig error. // You may also choose to inspect individual fields for more control. .err =&gt; |err| return err.asError(), } </code> } ``` Querying returning rows (Text Results) <ul> <li>If you want to have query results to be represented by custom created structs, this is not the section, scroll down to "Executing prepared statements returning results" instead. ```zig const myzql = @import("myzql"); const QueryResult = myzql.result.QueryResult; const ResultSet = myzql.result.ResultSet; const ResultRow = myzql.result.ResultRow; const TextResultRow = myzql.result.TextResultData; const ResultSetIter = myzql.result.ResultSetIter; const TableTexts = myzql.result.TableTexts; const TextElemIter = myzql.result.TextElemIter;</li> </ul> pub fn main() !void { const result = try c.queryRows("SELECT * FROM customers.purchases"); <code>// This is a query that returns rows, you have to collect the result. // you can use `expect(.rows)` to try interpret query result as ResultSet(TextResultRow) const rows: ResultSet(TextResultRow) = try query_res.expect(.rows); // Allocation free interators const rows_iter: ResultRowIter(TextResultRow) = rows.iter(); { // Option 1: Iterate through every row and elem while (try rows_iter.next()) |row| { // ResultRow(TextResultRow) var elems_iter: TextElemIter = row.iter(); while (elems_iter.next()) |elem| { // ?[] const u8 std.debug.print("{?s} ", .{elem}); } } } { // Option 2: Iterating over rows, collecting elements into []const ?[]const u8 while (try rows_iter.next()) |row| { const text_elems: TextElems = try row.textElems(allocator); defer text_elems.deinit(allocator); // elems are valid until deinit is called const elems: []const ?[]const u8 = text_elems.elems; std.debug.print("elems: {any}\n", .{elems}); } } // You can also use `collectTexts` method to collect all rows. // Under the hood, it does network call and allocations, until EOF or error // Results are valid until `deinit` is called on TableTexts. const rows: ResultSet(TextResultRow) = try query_res.expect(.rows); const table = try rows.tableTexts(allocator); defer table.deinit(allocator); // table is valid until deinit is called std.debug.print("table: {any}\n", .{table.table}); </code> } ``` Data Insertion <ul> <li>Let's assume that you have a table of this structure: <code>sql CREATE TABLE test.person ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age INT )</code></li> </ul> ```zig const myzql = @import("myzql"); const QueryResult = myzql.result.QueryResult; const PreparedStatement = myzql.result.PreparedStatement; const OkPacket = myzql.protocol.generic_response.OkPacket; pub fn main() void { // In order to do a insertion, you would first need to do a prepared statement. // Allocation is required as we need to store metadata of parameters and return type const prep_res = try c.prepare(allocator, "INSERT INTO test.person (name, age) VALUES (?, ?)"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); <code>// Data to be inserted const params = .{ .{ "John", 42 }, .{ "Sam", 24 }, }; inline for (params) |param| { const exe_res = try c.execute(&amp;prep_stmt, param); const ok: OkPacket = try exe_res.expect(.ok); // expecting ok here because there's no rows returned const last_insert_id: u64 = ok.last_insert_id; std.debug.print("last_insert_id: {any}\n", .{last_insert_id}); } // Currently only tuples are supported as an argument for insertion. // There are plans to include named structs in the future. </code> } ``` Executing prepared statements returning results as structs ```zig const ResultSetIter = myzql.result.ResultSetIter; const QueryResult = myzql.result.QueryResult; const BinaryResultRow = myzql.result.BinaryResultRow; const TableStructs = myzql.result.TableStructs; const ResultSet = myzql.result.ResultSet; fn main() !void { const prep_res = try c.prepare(allocator, "SELECT name, age FROM test.person"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); <code>// This is the struct that represents the columns of a single row. const Person = struct { name: []const u8, age: u8, }; // Execute query and get an iterator from results const res: QueryResult(BinaryResultRow) = try c.executeRows(&amp;prep_stmt, .{}); const rows: ResultSet(BinaryResultRow) = try res.expect(.rows); const iter: ResultSetIter(BinaryResultRow) = rows.iter(); { // Iterating over rows, scanning into struct or creating struct const query_res = try c.executeRows(&amp;prep_stmt, .{}); // no parameters because there's no ? in the query const rows: ResultSet(BinaryResultRow) = try query_res.expect(.rows); const rows_iter = rows.iter(); while (try rows_iter.next()) |row| { { // Option 1: scanning into preallocated person var person: Person = undefined; try row.scan(&amp;person); person.greet(); // Important: if any field is a string, it will be valid until the next row is scanned // or next query. If your rows return have strings and you want to keep the data longer, // use the method below instead. } { // Option 2: passing in allocator to create person const person_ptr = try row.structCreate(Person, allocator); // Important: please use BinaryResultRow.structDestroy // to destroy the struct created by BinaryResultRow.structCreate // if your struct contains strings. // person is valid until BinaryResultRow.structDestroy is called. defer BinaryResultRow.structDestroy(person_ptr, allocator); person_ptr.greet(); } } } { // collect all rows into a table ([]const Person) const query_res = try c.executeRows(&amp;prep_stmt, .{}); // no parameters because there's no ? in the query const rows: ResultSet(BinaryResultRow) = try query_res.expect(.rows); const rows_iter = rows.iter(); const person_structs = try rows_iter.tableStructs(Person, allocator); defer person_structs.deinit(allocator); // data is valid until deinit is called std.debug.print("person_structs: {any}\n", .{person_structs.struct_list.items}); } </code> } ``` Temporal Types Support (DateTime, Time) <ul> <li>Example of using DateTime and Time MySQL column types.</li> <li>Let's assume you already got this table set up: <code>sql CREATE TABLE test.temporal_types_example ( event_time DATETIME(6) NOT NULL, duration TIME(6) NOT NULL )</code></li> </ul> ```zig const DateTime = myzql.temporal.DateTime; const Duration = myzql.temporal.Duration; fn main() !void { { // Insert const prep_res = try c.prepare(allocator, "INSERT INTO test.temporal_types_example VALUES (?, ?)"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); <code> const my_time: DateTime = .{ .year = 2023, .month = 11, .day = 30, .hour = 6, .minute = 50, .second = 58, .microsecond = 123456, }; const my_duration: Duration = .{ .days = 1, .hours = 23, .minutes = 59, .seconds = 59, .microseconds = 123456, }; const params = .{.{ my_time, my_duration }}; inline for (params) |param| { const exe_res = try c.execute(&amp;prep_stmt, param); _ = try exe_res.expect(.ok); } } { // Select const DateTimeDuration = struct { event_time: DateTime, duration: Duration, }; const prep_res = try c.prepare(allocator, "SELECT * FROM test.temporal_types_example"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); const res = try c.executeRows(&amp;prep_stmt, .{}); const rows: ResultSet(BinaryResultRow) = try res.expect(.rows); const rows_iter = rows.iter(); const structs = try rows_iter.tableStructs(DateTimeDuration, allocator); defer structs.deinit(allocator); std.debug.print("structs: {any}\n", .{structs.struct_list.items}); // structs.rows: []const DateTimeDuration // Do something with structs } </code> } ``` Arrays Support <ul> <li>Assume that you have the SQL table: <code>sql CREATE TABLE test.array_types_example ( name VARCHAR(16) NOT NULL, mac_addr BINARY(6) )</code></li> </ul> ```zig fn main() !void { { // Insert const prep_res = try c.prepare(allocator, "INSERT INTO test.array_types_example VALUES (?, ?)"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); <code> const params = .{ .{ "John", &amp;[_]u8 { 0xFE } ** 6 }, .{ "Alice", null } }; inline for (params) |param| { const exe_res = try c.execute(&amp;prep_stmt, param); _ = try exe_res.expect(.ok); } } { // Select const Client = struct { name: [16:1]u8, mac_addr: ?[6]u8, }; const prep_res = try c.prepare(allocator, "SELECT * FROM test.array_types_example"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); const res = try c.executeRows(&amp;prep_stmt, .{}); const rows: ResultSet(BinaryResultRow) = try res.expect(.rows); const rows_iter = rows.iter(); const structs = try rows_iter.tableStructs(DateTimeDuration, allocator); defer structs.deinit(allocator); std.debug.print("structs: {any}\n", .{structs.struct_list.items}); // structs.rows: []const Client // Do something with structs } </code> } <code>`` - Arrays will be initialized by their sentinel value. In this example, the value of the</code>name<code>field corresponding to</code>John<code>'s row will be</code>[16:1]u8 { 'J', 'o', 'h', 'n', 1, 1, 1, ... }` - If the array doesn't have a sentinel value, it will be zero-initialized. - Insufficiently sized arrays will silently truncate excess data <code>BoundedArray</code> Support <ul> <li>Assume that you have the SQL table: <code>sql CREATE TABLE test.bounded_array_types_example ( name VARCHAR(16) NOT NULL, address VARCHAR(128) )</code></li> </ul> ```zig const std = @import("std"); fn main() !void { { // Insert const prep_res = try c.prepare(allocator, "INSERT INTO test.bounded_array_types_example VALUES (?, ?)"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); <code> const params = .{ .{ "John", "5 Rosewood Avenue Maryville, TN 37803"}, .{ "Alice", null } }; inline for (params) |param| { const exe_res = try c.execute(&amp;prep_stmt, param); _ = try exe_res.expect(.ok); } } { // Select const Client = struct { name: std.BoundedArray(u8, 16), address: ?std.BoundedArray(u8, 128), }; const prep_res = try c.prepare(allocator, "SELECT * FROM test.bounded_array_types_example"); defer prep_res.deinit(allocator); const prep_stmt: PreparedStatement = try prep_res.expect(.stmt); const res = try c.executeRows(&amp;prep_stmt, .{}); const rows: ResultSet(BinaryResultRow) = try res.expect(.rows); const rows_iter = rows.iter(); const structs = try rows_iter.tableStructs(Client, allocator); defer structs.deinit(allocator); std.debug.print("structs: {any}\n", .{structs.struct_list.items}); // structs.rows: []const Client // Do something with structs } </code> } ``` <ul> <li>Insufficiently sized <code>BoundedArray</code>s will silently truncate excess data</li> </ul> Unit Tests <ul> <li><code>zig test src/myzql.zig</code></li> </ul> Integration Tests <ul> <li>Start up mysql/mariadb in docker: ```bash</li> </ul> MySQL docker run --name some-mysql --env MYSQL_ROOT_PASSWORD=password -p 3306:3306 -d mysql ```bash MariaDB docker run --name some-mariadb --env MARIADB_ROOT_PASSWORD=password -p 3306:3306 -d mariadb <code>- Run all the test: In root directory of project:</code>bash zig build -Dtest-filer='...' integration_test ``` Philosophy Correctness Focused on correct representation of server client protocol. Low-level and High-level APIs Low-level apis should contain all functionality you need. High-level apis are built on top of low-level ones for convenience and developer ergonomics. Binary Column Types support <ul> <li>MySQL Colums Types to Zig Values ```</li> <li>Null -&gt; ?T</li> <li>Int -&gt; u64, u32, u16, u8</li> <li>Float -&gt; f32, f64</li> <li>String -&gt; []u8, []const u8, enum ```</li> </ul>
[ "https://github.com/deatil/zig-say" ]
https://avatars.githubusercontent.com/u/6756180?v=4
llvm-zig
kassane/llvm-zig
2023-04-21T16:26:20Z
LLVM bindings written in Zig
main
0
45
5
45
https://api.github.com/repos/kassane/llvm-zig/tags
MIT
[ "ffi-bindings", "libclang", "llvm", "llvm-bindings", "llvm-c", "llvm-c-api", "zig", "zig-package" ]
81
false
2025-04-30T16:37:58Z
true
true
0.14.0
github
[ { "commit": null, "name": "test_runner", "tar_url": null, "type": "remote", "url": "git+https://gist.github.com/karlseguin/c6bea5b35e4e8d26af6f81c22cb5d76b#1f317ebc9cd09bc50fd5591d09c34255e15d1d85" } ]
LLVM bindings for Zig The purpose of this repository is to learn about the <a><code>llvm</code></a> compiler infrastructure and practice some <a><code>zig</code></a>. Requirement <ul> <li><a>zig v0.14.0</a> or higher.</li> </ul> How to use Make your project using <code>console zig init</code> Add this llvm-zig module in <code>build.zig.zon</code>: <code>console zig fetch --save=llvm git+https://github.com/kassane/llvm-zig</code> in <code>build.zig</code>: <code>zig // [...] const llvm_dep = b.dependency("llvm", .{ // &lt;== as declared in build.zig.zon .target = target, // the same as passing `-Dtarget=&lt;...&gt;` to the library's build.zig script .optimize = optimize, // ditto for `-Doptimize=&lt;...&gt;` }); const llvm_mod = llvm_dep.module("llvm"); // &lt;== get llvm bindings module // and/or const clang_mod = llvm_dep.module("clang"); // &lt;== get clang bindings module /// your executable config exe.root_module.addImport("llvm", llvm_mod); // &lt;== add llvm module exe.root_module.addImport("clang", clang_mod); // &lt;== add clang module // [...]</code> License This project is licensed under the <a>MIT</a> license.
[]
https://avatars.githubusercontent.com/u/109492796?v=4
zig-idioms
zigcc/zig-idioms
2023-11-24T07:05:32Z
Common idioms used in Zig
main
0
44
1
44
https://api.github.com/repos/zigcc/zig-idioms/tags
MIT
[ "zig", "zig-lang", "ziglang" ]
15
false
2025-03-18T05:45:17Z
false
false
unknown
github
[]
Zig idioms <a></a> <blockquote> Zig, despite its simplicity, harbors unique features rarely found in other programming languages. This project aims to collect these techniques, serving as a valuable complement to the <a>Zig Language Reference</a>. </blockquote> Each idiom is accompanied by an illustrative example named after its corresponding sequence number. These examples can be executed using the command <code>zig build run-{number}</code>, or <code>zig build run-all</code> to execute all. 01. Zig files are structs <blockquote> Source: https://ziglang.org/documentation/master/#import </blockquote> Zig source files are implicitly structs, with a name equal to the file's basename with the extension truncated. <code>@import</code> returns the struct type corresponding to the file. ```zig // Foo.zig pub var a: usize = 1; b: usize, const Self = @This(); pub fn inc(self: *Self) void { self.b += 1; } // main.zig const Foo = @import("Foo.zig"); pub fn main() !void { const foo = Foo{ .b = 100 }; std.debug.print("Type of Foo is {any}, foo is {any}\n", .{ @TypeOf(Foo), @TypeOf(foo), }); foo.inc(); std.debug.print("foo.b = {d}\n", .{foo.b}); } ``` This will output <code>text Type of Foo is type, foo is foo foo.b = 101</code> 02. Naming Convention <blockquote> Source: https://www.openmymind.net/Zig-Quirks/ </blockquote> In general: <ul> <li>Functions are <code>camelCase</code></li> <li>Types are <code>PascalCase</code></li> <li>Variables are <code>lowercase_with_underscores</code></li> </ul> So we know <code>file_path</code> is mostly a variable, and <code>FilePath</code> is mostly a type. One exception to those rules is functions that return types. They are <code>PascalCase</code>, eg: <code>zig pub fn ArrayList(comptime T: type) type { return ArrayListAligned(T, null); }</code> Normally, file names are <code>lowercase_with_underscore</code>. However, files that expose a type directly (like our first example), follow the type naming rule. Thus, the file should be named <code>Foo.zig</code>, not <code>foo.zig</code>. 03. Dot Literals In Zig <code>.{ ... }</code> is everywhere, it can be used to initialize struct/tuple/enum, depending on its context. ```zig const Rect = struct { w: usize, h: usize, }; const Color = enum { Red, Green, Blue }; fn mySquare(x: usize) usize { return x * x; } pub fn main() !void { const rect: Rect = .{ .w = 1, .h = 2 }; const rect2 = .{ .w = 1, .h = 2 }; std.debug.print("Type of rect is {any}\n", .{@TypeOf(rect)}); std.debug.print("Type of rect2 is {any}\n", .{@TypeOf(rect2)}); <code>const c: Color = .Red; const c2 = .Red; std.debug.print("Type of c is {any}\n", .{@TypeOf(c)}); std.debug.print("Type of c2 is {any}\n", .{@TypeOf(c2)}); // We can use .{ ... } to construct a tuple of tuples // This can be handy when test different inputs of functions. inline for (.{ .{ 1, 1 }, .{ 2, 4 }, .{ 3, 9 }, }) |case| { try std.testing.expectEqual(mySquare(case.@"0"), case.@"1"); } </code> } ``` This will output <code>text Type of rect is main.Rect Type of rect2 is struct{comptime w: comptime_int = 1, comptime h: comptime_int = 2} Type of c is main.Color Type of c2 is @TypeOf(.enum_literal)</code> Other learning materials <ul> <li><a>Problems of C, and how Zig addresses them</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/9960133?v=4
tcc-riscv32-wasm
lupyuen/tcc-riscv32-wasm
2024-01-26T04:03:08Z
TCC (Tiny C Compiler) for 64-bit RISC-V, compiled to WebAssembly with Zig Compiler
main
0
44
5
44
https://api.github.com/repos/lupyuen/tcc-riscv32-wasm/tags
LGPL-2.1
[ "nuttx", "riscv", "riscv64", "romfs", "tcc", "webassembly", "zig", "ziglang" ]
46,853
true
2025-05-09T15:42:14Z
false
false
unknown
github
[]
Tiny C Compiler - C Scripting Everywhere - The Smallest ANSI C compiler Features: <ul> <li> SMALL! You can compile and execute C code everywhere, for example on rescue disks. </li> <li> FAST! tcc generates optimized x86 code. No byte code overhead. Compile, assemble and link about 7 times faster than 'gcc -O0'. </li> <li> UNLIMITED! Any C dynamic library can be used directly. TCC is heading toward full ISOC99 compliance. TCC can of course compile itself. </li> <li> SAFE! tcc includes an optional memory and bound checker. Bound checked code can be mixed freely with standard code. </li> <li> Compile and execute C source directly. No linking or assembly necessary. Full C preprocessor included. </li> <li> C script supported : just add '#!/usr/local/bin/tcc -run' at the first line of your C source, and execute it directly from the command line. </li> </ul> Documentation: 1) Installation on a i386/x86_64/arm/aarch64/riscv64 Linux/macOS/FreeBSD/NetBSD/OpenBSD hosts. ./configure make make test make install Notes: For FreeBSD, NetBSD and OpenBSD, gmake should be used instead of make. For Windows read tcc-win32.txt. makeinfo must be installed to compile the doc. By default, tcc is installed in /usr/local/bin. ./configure --help shows configuration options. 2) Introduction We assume here that you know ANSI C. Look at the example ex1.c to know what the programs look like. The include file can be used if you want a small basic libc include support (especially useful for floppy disks). Of course, you can also use standard headers, although they are slower to compile. You can begin your C script with '#!/usr/local/bin/tcc -run' on the first line and set its execute bits (chmod a+x your_script). Then, you can launch the C code as a shell or perl script :-) The command line arguments are put in 'argc' and 'argv' of the main functions, as in ANSI C. 3) Examples ex1.c: simplest example (hello world). Can also be launched directly as a script: './ex1.c'. ex2.c: more complicated example: find a number with the four operations given a list of numbers (benchmark). ex3.c: compute fibonacci numbers (benchmark). ex4.c: more complicated: X11 program. Very complicated test in fact because standard headers are being used ! As for ex1.c, can also be launched directly as a script: './ex4.c'. ex5.c: 'hello world' with standard glibc headers. tcc.c: TCC can of course compile itself. Used to check the code generator. tcctest.c: auto test for TCC which tests many subtle possible bugs. Used when doing 'make test'. 4) Full Documentation Please read tcc-doc.html to have all the features of TCC. Additional information is available for the Windows port in tcc-win32.txt. License: TCC is distributed under the GNU Lesser General Public License (see COPYING file). Fabrice Bellard.
[]
https://avatars.githubusercontent.com/u/1338143?v=4
smol-string
Senryoku/smol-string
2023-10-31T06:25:03Z
Compression for browsers' localStorage. Alternative to lz-string written in Zig.
main
1
44
1
44
https://api.github.com/repos/Senryoku/smol-string/tags
MIT
[ "browser", "compression", "localstorage", "typescript", "web", "zig" ]
5,993
false
2025-05-10T19:12:19Z
true
false
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/6136245?v=4
verkle-crypto
jsign/verkle-crypto
2023-05-20T22:08:15Z
Cryptography for Ethereum Verkle Trees
main
0
41
3
41
https://api.github.com/repos/jsign/verkle-crypto/tags
MIT
[ "bandersnatch", "cryptography", "ethereum", "inner-product-argument", "multiproof", "verkle", "zig" ]
290
false
2025-02-06T06:17:42Z
true
true
unknown
github
[]
verkle-crypto A pure Zig implementation of Verkle Tree cryptography. Features This library is feature complete: - [X] Relevant finite field arithmetic. - [X] Bandersnatch and Banderwagon group implementations. - [X] Pedersen Hashing for trie-key caculations. - [X] Proof creation and verification. Some notes about the implementation: - Both trie-key calculation and proof verification are very efficient. - This library has no external dependencies. - No assembly is used, so it can be compiled to all <a>supported targets</a>. - This library is single-threaded. It's planned to add multi-threading support in the future. - Comptetitive with (or faster, single threaded) than <a>go-ipa</a> or <a>rust-verkle</a>. This library isn't audited nor battle-tested, so it isn't recommended to be used in production. Test ``` $ zig build test --summary all Build Summary: 3/3 steps succeeded; 48/48 tests passed test success └─ run test 48 passed 4s MaxRSS:344M └─ zig test ReleaseSafe native success 14s MaxRSS:388M ``` Bench <code>AMD Ryzen 7 3800XT</code>: ``` $ zig build bench -Dtarget=native -Doptimize=ReleaseFast Setting up fields benchmark... Legendre symbol... takes 9µs Field square root... takes 8µs Field inverse... takes 6µs Field batch inverse (100 elements)... takes 13µs Mul... takes 21ns Add... takes 5ns Benchmarking Pedersen hashing... with 1 elements... takes 6µs with 2 elements... takes 7µs with 4 elements... takes 10µs with 8 elements... takes 15µs with 16 elements... takes 26µs with 32 elements... takes 46µs with 64 elements... takes 88µs with 128 elements... takes 170µs with 256 elements... takes 343µs Setting up IPA benchmark... proving takes 55ms, verifying takes 4ms Setting up multiproofs benchmark... Benchmarking 100 openings... proving takes 73ms, verifying takes 5ms Benchmarking 1000 openings... proving takes 120ms, verifying takes 12ms Benchmarking 5000 openings... proving takes 336ms, verifying takes 39ms Benchmarking 10000 openings... proving takes 607ms, verifying takes 72ms ``` License MIT.
[]
https://avatars.githubusercontent.com/u/152073653?v=4
zenolith
zenolith-ui/zenolith
2023-11-26T13:08:10Z
The GUI engine to end them all! Mirror of https://git.mzte.de/zenolith/zenolith
master
0
41
0
41
https://api.github.com/repos/zenolith-ui/zenolith/tags
GPL-3.0
[ "gui", "retained-mode-gui", "widget", "widget-toolkit", "zig", "zig-package" ]
272
false
2025-04-26T20:22:25Z
true
true
unknown
github
[ { "commit": null, "name": "statspatch", "tar_url": null, "type": "remote", "url": "git+https://git.mzte.de/LordMZTE/statspatch.git#fe27cf710f1db156acb8be4365d1a1a6365c6d95" } ]
Zenolith Zenolith is my attempt at a retained-mode, platform-agnostic, zig-native GUI engine. <strong><a>Join the Matrix room here!</a></strong> Warning: Zenolith is in an extremely early stage! Many important features such as text editing are not yet implemented. Expect breaking changes! Attention GitHub users! Zenolith is mirrored on GitHub to make it easier to discover, however, this mirror is read-only! Do not open issues or pull requests on GitHub! All development happens on <a>MZTE Git</a>. Contributing Pull requests are always welcome! If you'd like to fix a bug, improve documentation or implement a feature on the TODO list below, go ahead! If you'd like to suggest a new feature or design change, please open an issue first to discuss it! <strong>All commits must follow <a>Conventional Commits</a>!</strong> TODO <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> Painter API <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-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> Textures <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> Text <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> Multi-Color chunks <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> Multi-Font chunks <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> Triangles <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> Matrix Transformations? <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> Drawing of partial widgets <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> stencils? <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> Widgets <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> Box (FlowBox-like algorithm) <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> Button <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> Label <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> Word Wrapping <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> Character Wrapping <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> Ellipsization <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 Edit <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 Line <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> Multi Line <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> Tabbed Pane <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> Split Pane <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> Scrolled Pane <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> Focus 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> 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> Built-in themes <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> Layout overflow handling <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> Logo <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> Treevents (Tree-Bound, downwards 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> Backevents (Tree-Bound, upwards 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> Platform events (Platform event loop 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> Wrap Backevents <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> Attreebutes (Tree-Bound, inhereted widget properties) <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> Documentation <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> In-Code <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> Book <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> Examples <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> CI/CD <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>SDL2 Backend</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> Mach 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> TUI 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> WASM 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> Lazy rendering of subtrees Gallery
[ "https://github.com/zenolith-ui/zenolith-sdl2" ]
https://avatars.githubusercontent.com/u/23202896?v=4
android-build
zongou/android-build
2023-10-27T01:48:06Z
This NDK can run on Linux / MacOS / Windows / FreeBSD / OpenBSD 7.3 / NetBSD for both the x86_64 and AARCH64 architectures.
main
1
40
11
40
https://api.github.com/repos/zongou/android-build/tags
-
[ "aarch64", "android", "ndk", "zig" ]
18
false
2025-05-19T06:38:03Z
false
false
unknown
github
[]
Android Build Enviroment Build Android Application and Android targetd binary on unsupported os/arch. For example: <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> 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> prooted linux distro on 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> aarch64-linux Setup enviroment to build android app Setup SDK First. Install JDK. <blockquote> <strong><em>NOTE that on android prooted alpine. jdk &gt; 17 may not work</em></strong> </blockquote> Then run <code>sh ./setup_sdk.sh [PREFIX_DIR]</code> Setup NDK First. Get NDK <a>official</a> / <a>github</a> and decompress Then. Run <code>sh ./setup_ndk.sh [ANDROID_NDK_ROOT]</code> Get aapt2 <ul> <li>https://github.com/ReVanced/aapt2/actions</li> <li>https://github.com/lzhiyong/android-sdk-tools/releases</li> </ul> <blockquote> aapt2 is needed when building android application. </blockquote> Example: Compiling termux in prooted alpine <code>sh apt update apt install git -y git clone https://github.com/zongou/termux-app cd termux-app echo "ndk.dir=${ANDROID_NDK_ROOT}" &gt;&gt; local.properties echo "android.aapt2FromMavenOverride=/usr/local/bin/aapt2 &gt;&gt; local.properties gradlew assembleRelease</code> Setup toolchain for compiling C/C++ programs only First. Get NDK <a>official</a> / <a>github</a> and decompress Then. Run <code>sh ./setup_toolchain.sh [ANDROID_NDK_ROOT]</code> Test <code>bash ./bin/aarch64-linux-android21-clang tests/hello.c -o hello-c file hello-c ./bin/aarch64-linux-android21-clang++ tests/hello.cpp -o hello-cpp file hello-cpp</code> How does it work? We can make use of NDK prebuilted sysroot and clang resource dir with host clang toolchain. ```sh TOOLCHAIN="/toolchains/llvm/prebuilt/linux-x86_64" RESOURCE_DIR="${TOOLCHAIN}/lib/clang/" SYSROOT="${TOOLCHAIN}/sysroot" TARGET="aarch64-linux-android21" clang \ -resource-dir "${RESOURCE_DIR}" \ --sysroot="${SYSROOT}" \ --target="${TARGET}" \ -xc - \ -o "hello-c" \ &lt;&lt;-EOF #include <code> int main() { printf("%s\n", "Hello, C!"); return 0; } EOF </code> ```
[]
https://avatars.githubusercontent.com/u/35434089?v=4
zig_workbench
DarknessFX/zig_workbench
2023-10-26T21:57:08Z
DarknessFX Zig templates, projects, programs, libs and tools.
main
0
39
1
39
https://api.github.com/repos/DarknessFX/zig_workbench/tags
MIT
[ "allegro5", "cuda", "dear-imgui", "directx11", "imgui", "lua", "lvgl", "microui", "nanovg", "nuklear", "raylib", "sdl2", "sdl3", "sfml2", "sokol", "vscode", "webgpu", "webview", "zig", "ziglang" ]
60,661
false
2025-04-22T15:14:21Z
false
false
unknown
github
[]
<code> .----------------. .----------------. .----------------. | .--------------. || .--------------. || .--------------. | | | ________ | || | _________ | || | ____ ____ | | | | |_ ___ `. | || | |_ ___ | | || | |_ _||_ _| | | | | | | `. \ | || | | |_ \_| | || | \ \ / / | | | | | | | | | || | | _| | || | &gt; `' &lt; | | | | _| |___.' / | || | _| |_ | || | _/ /'`\ \_ | | | | |________.' | || | |_____| | || | |____||____| | | | | | || | | || | | | | '--------------' || '--------------' || '--------------' | '----------------' '----------------' '----------------' DarknessFX @ https://dfx.lv | Twitter: @DrkFX </code> About I'm studying and learning <a>Zig Language</a> (started Nov 19, 2023), sharing here my Zig projects, templates, libs and tools. Using Windows 10, Zig x86_64 Version : <strong>0.13.0</strong> <blockquote> <span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span> This is a student project, code will run and build without errors (mostly because I just throw away errors), it is not a reference of "<em>best coding practices</em>". Suggestions or contributions changing the code to the "<em>right way and best practices</em>" are welcome. </blockquote> Templates | Folder | Description | /Subsystem | | ------------- | ------------- | ------------- | | <strong><a>Base</a></strong> | Template for a console program. | Console | | <strong><a>BaseEx</a></strong> | Template for a console program that hide the console window. | Console | | <strong><a>BaseWin</a></strong> | Template for a Windows program. | Windows | | <strong><a>BaseWinEx</a></strong> | Template for a Windows program, Windows API as submodule. | Windows | | <strong><a>BaseImGui</a></strong> | Template with <a>Dear ImGui</a> via <a>Dear Bindings</a>. Extra: <a>ImGui_Memory_Editor</a>. Renderers: OpenGL2, OpenGL3, DirectX11, SDL3 OpenGL3, SDL2 OpenGL2, SDL3_Renderer, SDL2_Renderer | Both | | <strong><a>BaseRayLib</a></strong> | Template with <a>RayLib</a> and <a>RayGUI</a>. | Console + Web | | <strong><a>BaseSDL2</a></strong> | Template with <a>SDL2</a>. | Windows | | <strong><a>BaseSDL3</a></strong> | Template with <a>SDL3</a>. | Windows | | <strong><a>BaseSFML2</a></strong> | Template with <a>SFML2</a> via <a>CSFML2</a> C bindings. | Console | | <strong><a>BaseSokol</a></strong> | Template with <a>Sokol</a>. Extras UI: <a>Dear ImGui</a> via <a>cimgui</a>, <a>Nuklear</a>. | Windows | | <strong><a>BaseAllegro</a></strong> | Template with <a>Allegro5</a>. | Console | | <strong><a>BaseNanoVG</a></strong> | Template with <a>NanoVG</a> using GLFW3 OpenGL3. | Console | | <strong><a>BaseLVGL</a></strong> | Template with <a>LVGL</a> UI. | Console | | <strong><a>BaseMicroui</a></strong> | Template with <a>microui</a>. Renderers: SDL2, Windows GDI. | Windows | | <strong><a>BaseNuklear</a></strong> | Template with <a>Nuklear</a> UI using Windows GDI native. | Windows | | <strong><a>BaseWebview</a></strong> | Template with <a>Webview</a>. | Console | | <strong><a>BaseOpenGL</a></strong> | Template with <a>OpenGL</a> (GL.h). | Windows | | <strong><a>BaseDX11</a></strong> | Template with <a>DirectX Direct3D 11</a>. | Windows | | <strong><a>BaseVulkan</a></strong> | Template with <a>Vulkan</a>, versions: Win32API, GLFW3 . | Both | | <strong><a>BaseGLFW</a></strong> | Template with <a>GLFW</a> and <a>GLAD</a>. | Console | | <strong><a>BaseWasm</a></strong> | Template with <a>BaseWasm</a> using Emscripten. | Web | | <strong><a>BaseWebGPU</a></strong> | Template with <a>WebGPU</a> using Emscripten and Dawn. | Windows + Web | | <strong><a>BaseLua</a></strong> | Template with <a>Lua</a> scripting language. | Console | | <strong><a>BaseSQLite</a></strong> | Template with <a>SQLite</a> database. | Console | | <strong><a>BaseLMDB</a></strong> | Template with <a>LMDB</a> database. | Console | | <strong><a>BaseDuckDB</a></strong> | Template with <a>DuckDB</a> database. | Console | | <strong><a>BaseODE</a></strong> | Template with <a>ODE</a> Open Dynamics Engine physics. | Console | | <strong><a>BaseChipmunk2D</a></strong> | Template with <a>Chipmunk2D</a> physics. | Console | | <strong><a>BaseBox2D</a></strong> | Template with <a>Box2D</a> physics. | Console | | <strong><a>BaseZstd</a></strong> | Template with <a>Zstd</a> fast lossless compression. | Console | | <strong><a>BaseCUDA</a></strong> | Template with <a>Nvidia CUDA</a> . | Console | | <strong><a>BaseClay</a></strong> | FAILED: Template with <a>Clay</a> UI using <a>RayLib</a> renderer. | Windows | Usage | Steps | Path example | | ------------- | ------------- | | Duplicate the template folder. | C:\zig_workbench\BaseWin Copy\ | | Rename copy folder to your project name. | C:\zig_workbench\MyZigProgram\ | | Copy *tools/updateProjectName.bat* to your project Tools folder. | C:\zig_workbench\MyZigProgram\Tools\ | | Run *updateProjectName.bat*. | C:\zig_workbench\MyZigProgram\Tools\updateProjectName.bat | | Open *YourProject VSCode Workspace*. | C:\zig_workbench\MyZigProgram\MyZigProgram VSCode Workspace.lnk | &gt; <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> &gt; Current VSCode + ZLS extension do not accept **@cInclude** relative to project folder and will break builds. &gt; After open your new project, remember to edit **.zig** files **@cInclude** including your full path and using / folder separator. Zig have a useful built in feature: *zig init* that creates a basic project. I customized this basic project to fit my use cases, mostly to output to **bin** folder instead of **zig-out\bin**, have main.zig in the project root instead of src folder and use my [VSCode Setup](#about-vscode-tips-and-tricks). About Dear ImGui Using Dear ImGui Docking 1.91.5 and Dear Bindings (20241108) All necessary libraries are inside the template. Note: - When changing renderers, make sure to rename all files (Main.zig, Build.zig, .vscode/Tasks.json). - Check tools/RunAll.bat to get a list of **Zig Run** commands to launch rendereres without renaming files. ImGui_Memory_Editor: Edited from Dear Bindings output. Sample inside all ImGui templates and usage details at <a target="_blank">cimgui_memory_editor.h</a> About LVGL Using <a target="_blank">LVGL from source</a> (20231105, 9.0 Preview). Used parts of code from <a target="_blank">lv_port_pc_visual_studio</a> (lv_conf and main source). All necessary libraries are inside the template. Download Demos and Examples folders from the GitHub source (and don't forget to add all .C files necessary to build). About microui microui.c and microui.h are inside the project folder. Normally I would recommend to download from the official repository but sadly microui is outdated (last update 3 years ago) and I applied <a target="_blank">community pull requests</a> to the source code. It was necessary because the original code crashed with <i>runtime error: member access within misaligned address</i> and without the <a target="_blank">fix</a> this project would not work. About Nuklear Using Nuklear from source (20241231). I had to make some changes to the nuklear_gdi.h header to fix cImport errors, it failed with duplicate symbols (added inline) and later missing functions (removed static). About RayLib Using <a target="_blank">RayLib from source</a> (v5.0 from 20250102). About Allegro Using <a target="_blank">Allegro5 from nuget package</a> (v5.2.10 from 20241127). About SDL2 &nbsp;&nbsp;Using SDL2 v2.28.4. &nbsp;&nbsp;Download SDL2 from: <a target="_blank">GitHub SDL2 Releases Page</a>. &nbsp;&nbsp;For Windows devs: <a target="_blank">SDL2-devel-2.28.4-VC.zip 2.57 MB</a>. &nbsp;&nbsp;Check <a target="_blank">BaseSDL2/lib/SDL2/filelist.txt</a> for a description &nbsp;&nbsp;of the folder structure and expected files path location. About SDL3 &nbsp;&nbsp;Built from source in 20250122, version 3.2.1. Options to build using Shared or Static library. About SFML2 &nbsp;&nbsp;Using CSFML2 v2.6.1 from https://www.sfml-dev.org/download/csfml/ . About GLFW and GLAD GLFW 3.3.8 (Win64 Static). GLAD 2.0 (OpenGL 3.3 Compatibility). All necessary libraries are inside the template. About WebGPU SDL2 and Dawn Native. All necessary libraries are inside the template. &nbsp; Requirements: . [Emscripten](https://emscripten.org/) installed. . Change a few hard-coded paths to reflect your local emscripten paths. About Nvidia Cuda Requirements: - Visual Studio from https://visualstudio.microsoft.com/downloads/ - Nvidia CUDA SDK from https://developer.nvidia.com/cuda-downloads (I'm using Nvidia CUDA SDK 12.6.3) If you get an error while installing CUDA SDK, use Custom Installation and disable the following: Nsight VSE Visual Studio Integration Nsight Systems Nsight compute Nvidia GeForce Experience Other components Driver components If you want, you can install Nsight with its own installer. Failed: About Clay Everything is working from the code/template part, but Zig's cImport fails to import Clay's macros with variadic arguments (...) . Sharing here for anyone interested. Programs | Folder | Description | /Subsystem | | ------------- | ------------- | ------------- | | <strong>ToSystray</strong> | Give other Windows programs ability to "Minimize to Systray". Binary version ready to use is available to download at <a>Releases Page - ToSystray_v.1.0.0</a> | Windows | <strong>zTime</strong> | Similar to Linux TIME command, add zTime in front of your command to get the time it took to execute. Binary version ready to use is available to download at <a>Releases Page - zTime v1.0.1</a>. | Console ToSystray Usage Usage: ToSystray.exe "Application.exe" "Application Name" &nbsp;&nbsp; Example: ToSystray.exe "C:\Windows\System32\Notepad.exe" "Notepad" zTime Usage &nbsp;&nbsp;Examples, run in your Command Prompt, Windows Terminal or Powershell: &nbsp;&nbsp;&nbsp;&nbsp;C:\&gt;zTime zig build &nbsp;&nbsp;&nbsp;&nbsp;C:\&gt;zTime dir &nbsp;&nbsp;&nbsp;&nbsp;C:\&gt;zTime bin\ReleaseFast\YourProject.exe &nbsp;&nbsp;Suggestion: &nbsp;&nbsp;Copy zTime.exe to your Zig folder, this way the application will &nbsp;&nbsp;share the Environment Path and can be executed from anywhere. Projects | Folder | Description | | ------------- | ------------- | | <strong>ModernOpenGL</strong> | <a>Mike Shah</a> <a>ModernOpenGL</a> Youtube Tutorials ported to Zig + SDL3.1.2 OpenGL 4.6. | | <strong>zig_raylib_examples</strong> | WIP <a>RayLib</a> examples ported to Zig. | | <strong>zTinyRasterizer</strong> | WIP <a>Lisitsa Nikita</a> tiny CPU rasterization engine ported to Zig. | ModernOpenGL Info All files at Lib/SDL3 are the original ones from SDL Github, GLAD generated for 4.6 Core. For this project I did not use any zig binds or wrappers, just plain cImport. A copy of SDL.h and glad.h exist at Lib root just replacing &lt;&gt; with "", this change made easier for VSCode and ZLS display auto-complete. I tried to @cImport GLM OpenGL Mathematics "C" version cGML, @import ziglm and glm-zig, but each have their own quirks and styles while I'm wanted to keep the source code similar to the episodes, for this reason I built my own GLM.ZIG library with just a handful of used functions. There are some small changes implemented from the original tutorial code, mostly adding full Translate, Rotate, Scale, Keyboard and Mouse Movement. The Window Caption have a brief instruction of the keyboard settings and also, as my default, I used SHIFT+ESC to close the program. Libraries | Folder | Description | | ------------- | ------------- | | <strong>dos_color.zig</strong> | Helper to output colors to console (std.debug.print) or debug console (OutputDebugString). | | <strong>string.zig</strong> | WIP String Type. | Libraries usage &nbsp;&nbsp;Create a /lib/ folder in your project folder. &nbsp;&nbsp;Copy the library file to /lib/ . &nbsp;&nbsp;Add const libname = @Import("lib/lib_name.zig"); to your source code. Tools <blockquote> <span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span> All tools should be run from <strong>YourProjectFolder\Tools\</strong> folder, do not run it directly in the main folder. </blockquote> | Folder | Description | | ------------- | ------------- | | <strong>updateProjectName.bat</strong> | Read parent folder name as your ProjectName and replace template references to ProjectName. | | <strong>buildReleaseStrip.bat</strong> | Call "zig build-exe" with additional options (ReleaseSmall, strip, single-thread), emit assembly (.s), llvm bitcode (.ll, .bc), C header, zig build report. | | <strong>clean_zig-cache.bat</strong> | Remove zig-cache from <strong>all</strong> sub folders. | Tools_ContextMenu | Folder | Description | | ------------- | ------------- | | <strong>zig.ico</strong> | Zig logo Icon file (.ico). (Resolutions 64p, 32p, 16p) | | <strong>zig_256p.ico</strong> | Zig logo Icon file (.ico) with higher resolutions . (Resolutions 256p, 128p, 64p, 32p, 16p) | | <strong>zig_contextmenu.bat</strong> | Launcher used by Windows Explorer context menu, copy to Zig folder PATH. | | <strong>zig_icon.reg</strong> | Associate an icon for .Zig files, add Build, Run, Test to Windows Explorer context menu. <a>Read more details</a> in the file comments. | | <strong>zig_icon_cascade.reg</strong> | Alternative of zig_icon.reg, groups all options inside a Zig submenu. <a>Read more details</a> in the file comments. | Tools to help setup Windows Explorer to apply icons to .ZIG files and add context menu short-cuts to Build, Run and Test. 📷zig_icon.reg - screenshot After run zig_icon.reg, Windows Explorer will look like: 📷zig_icon_cascade.reg - screenshot After run zig_icon_cascade.reg, Windows Explorer will look like: About VSCode (Tips and Tricks) I'm using <a>VSCode</a> to program in Zig and using <a>Zig Language</a> extension from <a>ZLS - Zig Language Server</a>. Extensions that I use and recommend &nbsp;&nbsp;<a target="_blank">C/C++</a> from Microsoft. (**essential to enable Debug mode**.) &nbsp;&nbsp;<a target="_blank">C/C++ Extension Pack</a> from Microsoft. (non-essential) &nbsp;&nbsp;<a target="_blank">C/C++ Themes</a>. (non-essential) &nbsp;&nbsp;<a target="_blank">Hex Editor</a> from Microsoft. (**essential in Debug mode**) &nbsp;&nbsp;<a target="_blank">OverType</a> from DrMerfy. (non-essential? Add Insert key mode) &nbsp;&nbsp;<a target="_blank">Material Icon Theme</a> from Philipp Kief. (non-essential, but make VSCode looks better) VSCode RADDebugger I'm using VSCode with Cppvsdbg for a while but its features are lackluster, recently I tried RadDebugger and it works surprisingly well. I "hacked" a custom command into launch.json as a shortcut to start a RadDebugger session with the latest debug build.This is not feature in all .vscode/launch.json templates, if you are interested the additional launch.json settings are: { "name": "Debug with RadDebugger", "type": "cppdbg", "request": "launch", "presentation": { "hidden": false, "group": "", "order": 3 }, "program": "${workspaceFolder}/bin/Debug/${workspaceFolderBasename}.exe", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "preLaunchTask": "${defaultBuildTask}", "externalConsole": true, "avoidWindowsConsoleRedirection": true, "MIMode": "gdb", "miDebuggerPath": "C:/Unreal/RadDebugger/raddbg.exe", "miDebuggerArgs": "-q -auto_step -project ${workspaceFolder}/bin/Debug/${workspaceFolderBasename}.exe", "logging": { "engineLogging": true, "trace": true, "traceResponse": true } }, Remember to fix the hard-coded paths (at miDebuggerPath) to reflect your local folder to RADDebugger path. Ctrl+R is the new F5 I changed a few VSCode keybindings for better use, mostly because Zig offer multiple options for Build, Run, Test, Generate Docs, and I setup VSCode Tasks.json with all available options. The most important key binding change is <strong>CTRL+T</strong> to open TASKS menu, because VSCode keep the last task as first menu item, just pressing ENTER will: save current file and run the last task. Zig Build is fast and <em>Template/.vscode/launch.json</em> is already setup so VSCode <strong>F5</strong> key (Start with Debugger) will activate Zig Build and start debug, it works great and fast. But even better is <strong>Zig Run Main</strong>, the way zig run compile and start (without debugger) is a lot faster and helps a lot to iterate and productivity. <strong>CTRL+T, Enter</strong> became one of my most used keyboard shortcut inside VSCode and <strong>CTRL+R</strong> to repeat the last task. 📷Task menu screenshot VSCode Keybindings details VSCode Keybindings file location at %APPDATA%\Code\User\keybindings.json CTRL+T : Removed showAllSymbols and added runTask. Reason : Easy access to Tasks menu and repeatable action to run last action. CTRL+R : Removed all bindings. Reason: Because this key binding try to reload the current document or display a different menu that also will try to close the current document... If I need I can go to menu File &gt; Open Recent File instead of this shortcut that risk to close what I'm working. [ { "key": "ctrl+t", "command": "-workbench.action.showAllSymbols" }, { "key": "ctrl+t", "command": "workbench.action.tasks.runTask" } { "key": "ctrl+r", "command": "-workbench.action.reloadWindow", "when": "isDevelopment" }, { "key": "ctrl+r", "command": "-workbench.action.quickOpenNavigateNextInRecentFilesPicker", "when": "inQuickOpen &amp;&amp; inRecentFilesPicker" }, { "key": "ctrl+r", "command": "-workbench.action.openRecent" }, { "key": "ctrl+t", "command": "workbench.action.tasks.runTask" }, { "key": "ctrl+r", "command": "workbench.action.tasks.reRunTask" } ] Copy your libraries DLL to Zig folder When using libraries that have .DLL (for example SDL2_ttf.dll) the task Zig Run Main will fail because it cannot find the DLL and the exe was built somewhere in zig-cache, the error is "The terminal process ... terminated with exit code: 53.". The easier way to fix this error is to copy the library DLL to your Zig PATH folder. Personal observation about VSCode I have a Love/Hate relationship with VSCode, I only used it to code for Arduino and ESP32 with <a>Platform.io</a> and the hate is always when the editor try to be "smart and helpful". Yellow lightbulbs sometimes show up to notify "There are no fix", JSON files organized to easier read key items are reordered because "that is how JSON should be ordered", at least 10% of keys typed are wasted deleting things that VSCode put there to help me. And my favorite gripe: You select a function name in the Intellisense combo, it prints at your source code "YourFunction([cursor here])" BUT it don't display the arguments list, you need to backspace to delete the ( opening parenthesis, type ( and now the tooltip show up with the arguments list. Credits <a>Zig Language</a> from ZigLang.org. <a>SDL2, SDL3</a> from libSDL.org. <a>GLFW</a> from GLFW.org. <a>GLAD</a> from Dav1dde. <a>microui</a> from rxi. <a>Dear ImGui</a> from Omar Cornut. <a>Dear Bindings</a> from Ben Carter. <a>LVGL</a> from LVGL Kft. <a>ModernOpenGL</a> from Mike Shah. <a>RayLib</a> and <a>RayGUI</a> from Ramon Santamaria (@raysan5). <a>WebGPU</a> and <a>Wasm</a> from World Wide Web Consortium. <a>Dawn</a> from Google. <a>Sokol</a> from Floooh. <a>cimgui</a> from Sonoro1234. <a>Nuklear</a> from Micha Mettke. <a>Clay</a> from Nic Barker. <a>Allegro5</a> from Allegro 5 Development Team. <a>NanoVG</a> from Memononen. <a>SFML2</a> from Laurent Gomila. <a>Webview</a> from Webview Team. <a>Lua</a> from PUC-Rio. <a>SQLite</a> from SQLite Consortium. <a>LMDB</a> from Symas Corporation. <a>DuckDB</a> from DuckDB Foundation. <a>ODE</a> from Russ L. Smith. <a>Chipmunk2D</a> from Howling Moon Software. <a>Box2D</a> from Erin Catto. <a>zstd</a> from Meta. <a>TinyRasterizer</a> from <a>Lisitsa Nikita</a>. <a>Vulkan</a> from Khronos Group. <a>Nvidia CUDA</a> from Nvidia. License MIT - Free for everyone and any use. DarknessFX @ https://dfx.lv | Twitter: @DrkFX https://github.com/DarknessFX/zig_workbench SEO Helper Giving Google a little help pairing Zig + LIB words, because it find my twitter posts easier than this repo: WinEx = Zig Windows program template with Windows API as submodule sample example. ImGui = Zig ImGui Windows program template with renderers: OpenGL3, DirectX11, SDL3 OpenGL3, SDL2 OpenGL2, SDL3_Renderer, SDL2_Renderer sample example. LVGL = Zig LVGL Windows program template sample example. microui = Zig microui Windows program template with renderers: SDL2, Windows GDI sample example. RayLib = Zig RayLib and RayGUI Windows program template sample example. SDL2 = Zig SDL2 Windows program template sample example. SDL3 = Zig SDL3 Windows program template sample example. OpenGL = Zig OpenGL GL.h Windows program template sample example. DX11 = Zig DirectX Direct3D 11 DX11 Windows program template sample example. Vulkan = Zig Vulkan Windows program template sample example. GLFW = Zig GLFW GLAD Windows program template sample example. Wasm = Zig WASM program template sample example. WebGPU = Zig WebGPU WASM program template sample example. Sokol = Zig Sokol Dear ImGui Nuklear UI program template sample example. Nuklear = Zig Nuklear UI program template sample example. Clay = Zig Clay UI program template sample example. Allegro = Zig Allegro5 program template sample example. NanoVG = Zig NanoVG program template sample example. Webview = Zig Webview program template sample example. Lua = Zig Lua scripting language program template sample example. SQLite = Zig SQLite database program template sample example. LMDB = Zig LMDB transactional database program template sample example. ODE = Zig ODE Open Dynamics Engine physics program template sample example. Chipmunk2D = Zig Chipmunk2D physics program template sample example. Box2D = Zig Box2D physics program template sample example. zstd = Zig Zstd fast lossless compression program template sample example. CUDA = Zig NVIDIA CUDA program template sample example.
[]
https://avatars.githubusercontent.com/u/20110944?v=4
zig-minirv32
ringtailsoftware/zig-minirv32
2023-02-15T12:03:08Z
Zig RISC-V32 emulator with Linux and baremetal examples
master
0
38
3
38
https://api.github.com/repos/ringtailsoftware/zig-minirv32/tags
-
[ "emulator", "linux", "risc-v", "zig" ]
6,930
false
2025-05-16T13:17:43Z
true
false
unknown
github
[]
zig-minirv32ima Toby Jaffey https://mastodon.me.uk/@tobyjaffey A pure zig port of https://github.com/cnlohr/mini-rv32ima Blog posts documenting some of this: <ul> <li>https://www.ringtailsoftware.co.uk/zig-rv32/</li> <li>https://www.ringtailsoftware.co.uk/zig-baremetal/</li> </ul> Tested with <code>zig 0.14.0</code> Build emulator <code>zig build &amp;&amp; ./zig-out/bin/zigrv32ima linux.bin </code> Type ctrl-<code>a</code> then <code>x</code> to exit. Samples <code>samples/hello</code> Minimal "Hello world" in zig <code>cd samples/hello zig build ../../zig-out/bin/zigrv32ima zig-out/bin/hello.bin </code> <code>samples/shell</code> Interactive shell (https://github.com/ringtailsoftware/zig-embshell/) <code>cd samples/shell zig build ../../zig-out/bin/zigrv32ima zig-out/bin/shell.bin </code> <code>samples/mandelbrot</code> ASCII mandelbrot set <code>cd samples/mandelbrot zig build ../../zig-out/bin/zigrv32ima zig-out/bin/mandelbrot.bin </code> Notes Testing with qemu <code>qemu-system-riscv32 -machine virt -nographic -bios foo.bin </code> Libc usage libc is linked for access to the raw terminal. To remove, comment out <code>lib.linkSystemLibraryName("c");</code> in <code>build.zig</code>. The <code>term</code> struct could be replaced by this minimal stub: <code>const term = struct { pub fn init() void { } pub fn getch() ?u8 { return null; } }; </code>
[]
https://avatars.githubusercontent.com/u/46632215?v=4
zig-nes
jakehffn/zig-nes
2023-06-09T21:59:40Z
NES emulator written in Zig⚡
main
5
38
0
38
https://api.github.com/repos/jakehffn/zig-nes/tags
-
[ "6502", "6502-emulation", "emulation", "emulator", "imgui", "nes", "zig" ]
437
false
2025-04-18T00:31:52Z
true
false
unknown
github
[]
ZigNES 🕹️ NES emulator written in Zig with GUI using imgui. Currently, only mappers 0 and 1 are supported. Build Clone this repository somewhere on your machine with the following: <code>git clone --recurse-submodules https://github.com/jakehffn/zig-nes.git &amp;&amp; cd zig-nes</code> If environment variables for <code>SDL2_PATH</code> and <code>GLEW_PATH</code> are set, ZigNES can be built with, <code>zig build</code> The build file also expects the <code>SDL2</code> shared libary to have the extension, <code>.dll</code>, so other distributions of <code>SDL2</code> may require a little tweaking to <code>build.zig</code>. Usage Controls | Key | Action | |-----|---------| | W,A,S,D | D-Pad | | J | A Button | | K | B Button | | Space | Select | | Return | Start | CPU tests To test the CPU, Tom Harte's <a>nes6502 tests</a> are used. This is a suite of 10,000 tests for each of the 256 opcodes, both legal and illegal, which describes the initial and final state of the CPU after running one instruction. Currently, the <code>ZigNES</code> CPU passes all 1.5 million test cases for the set of legal opcodes, excluding cycle timings. The test set itself is not included in this repository due to the size of download. If you would like to run the tests yourself, the test runner expects the test cases to exist at the path <code>.\test-files\tom_harte_nes6502\v1</code> relative to the root of this project.
[]
https://avatars.githubusercontent.com/u/64311472?v=4
zcached
sectasy0/zcached
2023-12-11T16:27:15Z
Lightweight and efficient in-memory caching system akin to databases like Redis.
master
6
38
3
38
https://api.github.com/repos/sectasy0/zcached/tags
AGPL-3.0
[ "cache", "database", "key-value", "nosql", "zcached", "zig" ]
5,917
false
2025-05-21T02:03:10Z
true
true
unknown
github
[]
zcached - A Lightweight In-Memory Cache System Welcome to <code>zcached</code>, a nimble and efficient in-memory caching system resembling databases like Redis. This README acts as a comprehensive guide, aiding in comprehension, setup, and optimal utilization. Introduction <code>zcached</code> aims to offer rapid, in-memory caching akin to widely-used databases such as Redis. Its focus lies in user-friendliness, efficiency, and agility, making it suitable for various applications requiring swift data retrieval and storage. Crafted using Zig, a versatile, modern, compiled programming language, <code>zcached</code> prides itself on a zero-dependency architecture. This unique feature enables seamless compilation and execution across systems equipped with a Zig compiler, ensuring exceptional portability and deployment ease. Features <ul> <li><strong>Zero-Dependency Architecture</strong>: Entirely built using Zig, ensuring seamless execution across systems with a Zig compiler, enhancing portability (except openssl, but it's optional).</li> <li><strong>Lightweight Design</strong>: Engineered for efficiency, <code>zcached</code> boasts a small memory footprint and minimal CPU usage, optimizing performance while conserving resources.</li> <li><strong>Optimized Efficiency</strong>: Prioritizing swift data handling, <code>zcached</code> ensures prompt operations to cater to diverse application needs.</li> <li><strong>Diverse Data Type Support</strong>: Accommodates various data structures like strings, integers, floats, and lists, enhancing utility across different use cases.</li> <li><strong>Evented I/O and Multithreading</strong>: Leveraging evented I/O mechanisms and multithreading capabilities, zcached efficiently manages concurrent operations, enhancing responsiveness and scalability.</li> <li><strong>TLS Support</strong>: Ensures secure data transmission with encryption, protecting data integrity and confidentiality during client-server communication.</li> </ul> Usage While <code>zcached</code> lacks a CLI, you can utilize nc (netcat) from the terminal to send commands to the server. SET Set a key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <code>bash echo "*3\r\n\$3\r\nSET\r\n\$9\r\nmycounter\r\n:42\r\nx03" | netcat -N localhost 7556</code> <code>bash echo "*3\r\n\$3\r\nSET\r\n\$9\r\nmycounter\r\n%2\r\n+first\r\n:1\r\n+second\r\n:2\r\nx03" | netcat -N localhost 7556</code> Command Breakdown: <ul> <li><code>*3\r\n</code> - number of elements in the array (commands are always arrays)</li> <li><code>\$3\r\nSET\r\n</code> - <code>$3</code> denotes the following string as 3 bytes long, SET is the command</li> <li><code>\$9\r\nmycounter\r\n</code> - <code>$9</code> means that the next string is 9 bytes long, <code>mycounter</code> is the key</li> <li><code>:42\r\n</code> - <code>:</code> indicates the next string is a number, <code>42</code> is the value</li> </ul> GET Retrieve the value of a key. If the key doesn’t exist, <code>-not found</code> is returned. GET only accepts strings as keys. <code>bash echo "*2\r\n\$3\r\nGET\r\n\$9\r\nmycounter\r\n\x03" | netcat -N localhost 7556</code> PING Returns <code>PONG</code>. This command is often used to test if a connection is still alive, or to measure latency. <code>bash echo "*1\r\n\$4\r\nPING\r\n\x03" | netcat -N localhost 7556</code> Running Tests Run the tests using <code>zig</code> in the root directory of the project: <code>bash zig build test</code> Documentation <ul> <li>For release history, see the <a>release_history.md</a></li> <li>For building/installation process please refer to the <a>installation.md</a></li> <li>For supported types and their encodings, see the <a>types.md</a></li> <li>For supported commands, see the <a>commands.md</a></li> </ul> Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
[]
https://avatars.githubusercontent.com/u/6811788?v=4
zimpl
permutationlock/zimpl
2023-11-13T12:08:52Z
Simple comptime generic interfaces for Zig
main
0
37
1
37
https://api.github.com/repos/permutationlock/zimpl/tags
MIT
[ "generics", "interfaces", "polymorphism", "traits", "vtables", "zig" ]
207
false
2025-05-01T09:39:47Z
true
true
unknown
github
[]
Zimpl Zig interfaces A dead simple implementation of <a>static dispatch</a> interfaces in Zig that emerged from a tiny subset of <a>ztrait</a>. See <a>here</a> for some motivation. Also included is a compatible implementation of <a>dynamic dispatch</a> interfaces via <code>comptime</code> generated <a>vtables</a>. Inspired by <a><code>interface.zig</code></a>. <em>Warning: Zimpl is still mostly an exploratory project.</em> Static dispatch <code>Impl</code> <code>Zig pub fn Impl(comptime Ifc: fn (type) type, comptime T: type) type { ... }</code> Definitions If <code>T</code> is a single-item pointer type, then define <code>U(T)</code> to be the child type, i.e. <code>T = *U(T)</code>, otherwise define <code>U(T)=T</code>. Arguments The function <code>Ifc</code> must always return a struct type. If <code>U(T)</code> has a declaration matching the name of a field from <code>Ifc(T)</code> that cannot coerce to the type of that field, then a compile error will occur (and a pretty good one now, thank you Zig Core Team). Return value The type <code>Impl(Ifc, T)</code> is a struct type with the same fields as <code>Ifc(T)</code>, but with the default value of each field set equal to the declaration of <code>U(T)</code> of the same name, if such a declaration exists. Example ```Zig // An interface pub fn Reader(comptime T: type) type { return struct { ReadError: type = anyerror, read: fn (reader_ctx: T, buffer: []u8) anyerror!usize, }; } // A collection of functions using the interface pub const io = struct { pub inline fn read( reader_ctx: anytype, reader_impl: Impl(Reader, @TypeOf(reader_ctx)), buffer: []u8, ) reader_impl.ReadError!usize { return @errorCast(reader_impl.read(reader_ctx, buffer)); } <code>pub inline fn readAll( reader_ctx: anytype, reader_impl: Impl(Reader, @TypeOf(reader_ctx)), buffer: []u8, ) reader_impl.ReadError!usize { return readAtLeast(reader_ctx, reader_impl, buffer, buffer.len); } pub inline fn readAtLeast( reader_ctx: anytype, reader_impl: Impl(Reader, @TypeOf(reader_ctx)), buffer: []u8, len: usize, ) reader_impl.ReadError!usize { assert(len &lt;= buffer.len); var index: usize = 0; while (index &lt; len) { const amt = try read(reader_ctx, reader_impl, buffer[index..]); if (amt == 0) break; index += amt; } return index; } </code> }; test "define and use a reader" { const FixedBufferReader = struct { buffer: []const u8, pos: usize = 0, <code> pub const ReadError = error{}; pub fn read(self: *@This(), out_buffer: []u8) ReadError!usize { const len = @min(self.buffer[self.pos..].len, out_buffer.len); @memcpy(out_buffer[0..len], self.buffer[self.pos..][0..len]); self.pos += len; return len; } }; const in_buf: []const u8 = "I really hope that this works!"; var reader = FixedBufferReader{ .buffer = in_buf }; var out_buf: [16]u8 = undefined; const len = try io.readAll(&amp;reader, .{}, &amp;out_buf); try testing.expectEqualStrings(in_buf[0..len], out_buf[0..len]); </code> } test "use std.fs.File as a reader" { var buffer: [19]u8 = undefined; var file = try std.fs.cwd().openFile("my_file.txt", .{}); try io.readAll(file, .{}, &amp;buffer); <code>try std.testing.expectEqualStrings("Hello, I am a file!", &amp;buffer); </code> } test "use std.os.fd_t as a reader via an explicitly defined interface" { var buffer: [19]u8 = undefined; const fd = try std.os.open("my_file.txt", std.os.O.RDONLY, 0); try io.readAll( fd, .{ .read = std.os.read, .ReadError = std.os.ReadError, }, &amp;buffer, ); <code>try std.testing.expectEqualStrings("Hello, I am a file!", &amp;buffer); </code> } ``` Dynamic dispatch <code>VIfc</code> <code>Zig pub fn VIfc(comptime Ifc: fn (type) type) type { ... }</code> Arguments The <code>Ifc</code> function must always return a struct type. Return value Returns a struct of the following form: ```Zig struct { ctx: *anyopaque, vtable: VTable(Ifc), <code>pub fn init( comptime access: CtxAccess, ctx: anytype, impl: Impl(Ifc, CtxType(@TypeOf(ctx), access)), ) @This() { return .{ .ctx = if (access == .indirect) @constCast(ctx) else ctx, .vtable = vtable(Ifc, access, @TypeOf(ctx), impl), }; } </code> }; <code>`` The struct type</code>VTable(Ifc)<code>contains one field for each field of</code>Ifc(*anyopaque)` that is a (optional) function. The type of each vtable field is converted to a (optional) function pointer with the same signature. The <code>init</code> function constructs a virtual interface from a given runtime context and interface implementation. Since the context is stored as a type-erased pointer, the <code>access</code> parameter is provided to allow vtables to be constructed for implementations that rely on non-pointer contexts. ```Zig pub const CtxAccess = enum { direct, indirect }; fn CtxType(comptime Ctx: type, comptime access: CtxAccess) type { return if (access == .indirect) @typeInfo(Ctx).Pointer.child else Ctx; } ``` If <code>access</code> is <code>.direct</code>, then the type-erased <code>ctx</code> pointer stored in <code>VIfc(Ifc)</code> is cast as the correct pointer type and passed directly to concrete member function implementations. Otherwise, if <code>access</code> is <code>.indirect</code>, <code>ctx</code> is a pointer to the actual context, and it is dereferenced and passed by value to member functions. Example ```Zig // An interface pub fn Reader(comptime T: type) type { return struct { // non-function fields are fine, but vtable interfaces ignore them ReadError: type = anyerror, read: fn (reader_ctx: T, buffer: []u8) anyerror!usize, }; } // A collection of functions using virtual 'Reader' interfaces pub const vio = struct { pub inline fn read(reader: VIfc(Reader), buffer: []u8) anyerror!usize { return reader.vtable.read(reader.ctx, buffer); } <code>pub inline fn readAll(reader: VIfc(Reader), buffer: []u8) anyerror!usize { return readAtLeast(reader, buffer, buffer.len); } pub fn readAtLeast( reader: VIfc(Reader), buffer: []u8, len: usize, ) anyerror!usize { assert(len &lt;= buffer.len); var index: usize = 0; while (index &lt; len) { const amt = try read(reader, buffer[index..]); if (amt == 0) break; index += amt; } return index; } </code> }; test "define and use a reader" { const FixedBufferReader = struct { buffer: []const u8, pos: usize = 0, <code> pub const ReadError = error{}; pub fn read(self: *@This(), out_buffer: []u8) ReadError!usize { const len = @min(self.buffer[self.pos..].len, out_buffer.len); @memcpy(out_buffer[0..len], self.buffer[self.pos..][0..len]); self.pos += len; return len; } }; const in_buf: []const u8 = "I really hope that this works!"; var reader = FixedBufferReader{ .buffer = in_buf }; var out_buf: [16]u8 = undefined; const len = try vio.readAll(Reader.init(.direct, &amp;reader, .{}), &amp;out_buf); try testing.expectEqualStrings(in_buf[0..len], out_buf[0..len]); </code> } test "use std.fs.File as a reader" { var buffer: [19]u8 = undefined; var file = try std.fs.cwd().openFile("my_file.txt", .{}); try vio.readAll(Reader.init(.indirect, &amp;file, .{}), &amp;buffer); <code>try std.testing.expectEqualStrings("Hello, I am a file!", &amp;buffer); </code> } test "use std.os.fd_t as a reader via an explicitly defined interface" { var buffer: [19]u8 = undefined; const fd = try std.os.open("my_file.txt", std.os.O.RDONLY, 0); try vio.readAll( Reader.init( .indirect, &amp;fd, .{ .read = std.os.read, .ReadError = std.os.ReadError }, ), &amp;buffer, ); <code>try std.testing.expectEqualStrings("Hello, I am a file!", &amp;buffer); </code> } ```
[]
https://avatars.githubusercontent.com/u/6221162?v=4
zig_gpt2
EugenHotaj/zig_gpt2
2023-06-07T02:25:03Z
GPT-2 inference engine written in Zig
main
0
37
5
37
https://api.github.com/repos/EugenHotaj/zig_gpt2/tags
-
[ "gpt-2", "inference-engine", "zig" ]
18,002
false
2025-03-13T15:53:15Z
true
false
unknown
github
[]
zig_gpt2 GPT-2 inference engine written in Zig. Generation time: ~28ms per token. Features: <ul> <li>No third-party dependencies besides BLAS (Accelerate or OpenBLAS).</li> <li>No memory allocations at runtime.</li> <li>Can run <a>NanoGPT</a>.</li> </ul> How to Run: Download the GPT-2 checkpoint from OpenAI. <code>bash python3 download_weights.py</code> Build the Zig binary and run it with a prompt to generate completions: <code>bash zig build -DOptimize=ReleaseFast ./zig-out/bin/zig_gpt2 "Marcus Aurelius said"</code> How to Test: Generate test data by forwarding random tensors through PyTorch ops. <code>bash python3 generate_test_data.py</code> Run tests. Verifies Zig ops produce the same output as PyTorch. <code>bash zig build test</code> TODO Implementation: * ✅ Implement basic ops: Embedding, Linear, LayerNorm, GELU, Softmax, CausalSelfAttention. * ✅ Implement transformer modules: MLP, Transformer block. * ✅ Implement the full GPT model. * ✅ Implement sampling from the model. * ✅ Implement BPE encoding/decoding. Efficiency: * ✅ Replace custom linear algebra kernels with BLAS. * ✅ Stream output as each new token is generated. * ✅ Create central set of memory buffers and reuse them for each layer. No allocations at runtime. * ✅ Add KV cache. * Parallelize <code>softmax</code> and <code>gelu</code> operations.
[]
https://avatars.githubusercontent.com/u/8823448?v=4
neotest-zig
lawrence-laz/neotest-zig
2023-10-01T13:29:42Z
Test runner for Zig in Neovim using Neotest backend.
main
5
37
7
37
https://api.github.com/repos/lawrence-laz/neotest-zig/tags
MIT
[ "lua", "neotest", "neovim", "test", "zig" ]
82
false
2025-04-12T07:26:03Z
false
false
unknown
github
[]
Neotest Zig ⚡ <a>Neotest</a> test runner for <a>Zig</a>. https://github.com/lawrence-laz/neotest-zig/assets/8823448/9a003d0a-9ba4-4077-aa1b-3c0c90717734 ⚙️ Requirements <ul> <li><a><code>zig</code> v0.14 installed</a> and available in PATH<ul> <li>If you are using <code>zig</code> v0.13, then use the tagged <code>neotest-zig</code> 1.3.* version.</li> </ul> </li> <li><a>Neotest</a></li> <li><a>Treesitter</a> with <a>Zig support</a></li> </ul> 📦 Setup Install &amp; configure using the package manager of your choice. Example using lazy.nvim: <code>lua return { "nvim-neotest/neotest", dependencies = { "lawrence-laz/neotest-zig", -- Installation "nvim-lua/plenary.nvim", "nvim-treesitter/nvim-treesitter", "antoinemadec/FixCursorHold.nvim", }, config = function() require("neotest").setup({ adapters = { -- Registration require("neotest-zig")({ dap = { adapter = "lldb", } }), } }) end }</code> ⭐ Features <ul> <li>Can run tests in individual <code>.zig</code> files and projects using <code>build.zig</code> </li> <li>Does not support a mix of individual files and <code>build.zig</code>:w</li> <li><code>buil.zig</code> must have a standard <code>test</code> step</li> <li>Exact test filtering</li> <li>Timing all tests individually</li> </ul> 📄 Logs Enabling logging in <code>neotest</code> automatically enables logging in <code>neotest-zig</code> as well: <code>lua require("neotest").setup({ log_level = vim.log.levels.TRACE, -- ... })</code> The logs can be openned by: <code>vim :exe 'edit' stdpath('log').'/neotest-zig.log'</code>
[]
https://avatars.githubusercontent.com/u/9384699?v=4
ztick
flouthoc/ztick
2023-03-11T09:43:23Z
tiny desktop utility to keep notes ( with no features ). Written in zig and gtk4
main
0
36
0
36
https://api.github.com/repos/flouthoc/ztick/tags
-
[ "gnome", "gtk4", "zig" ]
1,164
false
2025-04-12T19:30:46Z
true
false
unknown
github
[]
ztick Tiny notes app written in Zig and Gtk4. Motivation for writing this app is majorly personal use and learning zig. I hope it helps other folks to learn zig. <ul> <li>Render Ubuntu</li> </ul> <ul> <li>Render Fedora</li> </ul> Build <code>zig build</code> Should produce output binary in <code>zig-out</code> directory. Prerequisite <ul> <li>Zig</li> <li>Gtk4</li> </ul> Instructions By default <code>ztick</code> writes all pages in a static file, in the current directory of the <code>ztick</code> binary. Note Following project is under development and a hobby project.
[]
https://avatars.githubusercontent.com/u/152205304?v=4
exercises
ziglings-org/exercises
2023-11-27T17:33:04Z
This is the mirror of Ziglings
main
0
36
29
36
https://api.github.com/repos/ziglings-org/exercises/tags
MIT
[ "mirrored-repository", "zig", "ziglang" ]
1,447
false
2025-05-12T19:52:06Z
true
false
unknown
github
[]
Ziglings Welcome to Ziglings! This project contains a series of tiny broken programs (and one nasty surprise). By fixing them, you'll learn how to read and write <a>Zig</a> code. Those broken programs need your help! (You'll also save the planet from evil aliens and help some friendly elephants stick together, which is very sweet of you.) This project was initiated by <a>Dave Gauer</a> and is directly inspired by the brilliant and fun <a>rustlings</a> project. Indirect inspiration comes from <a>Ruby Koans</a> and the Little LISPer/Little Schemer series of books. Intended Audience This will probably be difficult if you've <em>never</em> programmed before. But no specific programming experience is required. And in particular, you are <em>not</em> expected to have any prior experience with "systems programming" or a "systems" level language such as C. Each exercise is self-contained and self-explained. However, you're encouraged to also check out these Zig language resources for more detail: <ul> <li>https://ziglang.org/learn/</li> <li>https://ziglearn.org/</li> <li>https://ziglang.org/documentation/master/</li> <li><a>Zig in Depth! (video series)</a></li> </ul> Also, the <a>Zig community</a> is incredibly friendly and helpful! Getting Started Install a <a>development build</a> of the Zig compiler. (See the "master" section of the downloads page.) Verify the installation and build number of <code>zig</code> like so: <code>$ zig version 0.15.0-dev.xxxx+xxxxxxxxx</code> Clone this repository with Git: <code>git clone https://codeberg.org/ziglings/exercises.git ziglings cd ziglings</code> Then run <code>zig build</code> and follow the instructions to begin! <code>zig build</code> Note: The output of Ziglings is the unaltered output from the Zig compiler. Part of the purpose of Ziglings is to acclimate you to reading these. A Note About Versions <strong>Hint:</strong> To check out Ziglings for a stable release of Zig, you can use the appropriate tag. The Zig language is under very active development. In order to be current, Ziglings tracks <strong>development</strong> builds of the Zig compiler rather than versioned <strong>release</strong> builds. The last stable release was <code>0.14.0</code>, but Ziglings needs a dev build with pre-release version "0.15.0" and a build number at least as high as that shown in the example version check above. It is likely that you'll download a build which is <em>greater</em> than the minimum. Once you have a build of the Zig compiler that works with Ziglings, they'll continue to work together. But keep in mind that if you update one, you may need to also update the other. Version Changes Version-0.14.0-dev.1573 * <em>2024-09-16</em> zig 0.14.0-dev.1573 - introduction of labeled switch, see <a>#21257</a> * <em>2024-09-02</em> zig 0.14.0-dev.1409 - several changes in std.builtin, see <a>#21225</a> * <em>2024-08-04</em> zig 0.14.0-dev.1224 - several changes in build system, see <a>#21115</a> * <em>2024-08-04</em> zig 0.14.0-dev.839 - several changes in build system, see <a>#20580</a>, <a>#20600</a> * <em>2024-06-17</em> zig 0.14.0-dev.42 - changes in <code>std.mem.split and tokenize</code> - see <a>#15579</a> * <em>2024-05-29</em> zig 0.13.0-dev.339 - rework std.Progress - see <a>#20059</a> * <em>2024-03-21</em> zig 0.12.0-dev.3518 - change to @fieldParentPtr - see <a>#19470</a> * <em>2024-03-21</em> zig 0.12.0-dev.3397 - rename std.os to std.posix - see <a>#5019</a> * <em>2024-03-14</em> zig 0.12.0-dev.3302 - changes in <code>std.fmt</code> - floating-point formatting implementation - see <a>#19229</a> * <em>2024-02-05</em> zig 0.12.0-dev.2618 - changes in <code>build system</code> - from <code>Step.zig_exe</code> to <code>Step.graph.zig_exe</code> - see <a>#18778</a> * <em>2024-01-05</em> zig 0.12.0-dev.2043 - rename of <code>std.Build.FileSource</code> to <code>std.Build.LazyPath</code> - see <a>#16353</a> * <em>2023-10-24</em> zig 0.12.0-dev.1243 - changes in <code>std.ChildProcess</code>: renamed exec to run - see <a>#5853</a> * <em>2023-06-26</em> zig 0.11.0-dev.4246 - changes in compile step (now it can be null) * <em>2023-06-26</em> zig 0.11.0-dev.3853 - removal of destination type from all cast builtins * <em>2023-06-20</em> zig 0.11.0-dev.3747 - <code>@enumToInt</code> is now <code>@intFromEnum</code> and <code>@intToFloat</code> is now <code>@floatFromInt</code> * <em>2023-05-25</em> zig 0.11.0-dev.3295 - <code>std.debug.TTY</code> is now <code>std.io.tty</code> * <em>2023-04-30</em> zig 0.11.0-dev.2704 - use of the new <code>std.Build.ExecutableOptions.link_libc</code> field * <em>2023-04-12</em> zig 0.11.0-dev.2560 - changes in <code>std.Build</code> - remove run() and install() * <em>2023-04-07</em> zig 0.11.0-dev.2401 - fixes of the new build system - see <a>#212</a> * <em>2023-02-21</em> zig 0.11.0-dev.2157 - changes in <code>build system</code> - new: parallel processing of the build steps * <em>2023-02-21</em> zig 0.11.0-dev.1711 - changes in <code>for loops</code> - new: Multi-Object For-Loops + Struct-of-Arrays * <em>2023-02-12</em> zig 0.11.0-dev.1638 - changes in <code>std.Build</code> cache_root now returns a directory struct * <em>2023-02-04</em> zig 0.11.0-dev.1568 - changes in <code>std.Build</code> (combine <code>std.build</code> and <code>std.build.Builder</code> into <code>std.Build</code>) * <em>2023-01-14</em> zig 0.11.0-dev.1302 - changes in <code>@addWithOverflow</code> (now returns a tuple) and <code>@typeInfo</code>; temporary disabled async functionality * <em>2022-09-09</em> zig 0.10.0-dev.3978 - change in <code>NativeTargetInfo.detect</code> in build * <em>2022-09-06</em> zig 0.10.0-dev.3880 - Ex 074 correctly fails again: comptime array len * <em>2022-08-29</em> zig 0.10.0-dev.3685 - <code>@typeName()</code> output change, stage1 req. for async * <em>2022-07-31</em> zig 0.10.0-dev.3385 - std lib string <code>fmt()</code> option changes * <em>2022-03-19</em> zig 0.10.0-dev.1427 - method for getting sentinel of type changed * <em>2021-12-20</em> zig 0.9.0-dev.2025 - <code>c_void</code> is now <code>anyopaque</code> * <em>2021-06-14</em> zig 0.9.0-dev.137 - std.build.Id <code>.Custom</code> is now <code>.custom</code> * <em>2021-04-21</em> zig 0.8.0-dev.1983 - std.fmt.format() <code>any</code> format string required * <em>2021-02-12</em> zig 0.8.0-dev.1065 - std.fmt.format() <code>s</code> (string) format string required Advanced Usage It can be handy to check just a single exercise: <code>zig build -Dn=19</code> Or run all exercises, starting from a specific one: <code>zig build -Ds=27</code> Or let Ziglings pick an exercise for you: <code>zig build -Drandom</code> You can also run without checking for correctness: <code>zig build -Dn=19 test</code> Or skip the build system entirely and interact directly with the compiler if you're into that sort of thing: <code>zig run exercises/001_hello.zig</code> Calling all wizards: To prepare an executable for debugging, install it to zig-cache/bin with: <code>zig build -Dn=19 install</code> To get a list of all possible options, run: ``` zig build -Dn=19 -l install Install 019_functions2.zig to prefix path uninstall Uninstall 019_functions2.zig from prefix path test Run 019_functions2.zig without checking output ... ``` To reset the progress (have it run all the exercises that have already been completed): <code>zig build -Dreset</code> What's Covered The primary goal for Ziglings is to cover the core Zig language. It would be nice to cover the Standard Library as well, but this is currently challenging because the stdlib is evolving even faster than the core language (and that's saying something!). Not only would stdlib coverage change very rapidly, some exercises might even cease to be relevant entirely. Having said that, there are some stdlib features that are probably here to stay or are so important to understand that they are worth the extra effort to keep current. Conspicuously absent from Ziglings are a lot of string manipulation exercises. This is because Zig itself largely avoids dealing with strings. Hopefully there will be an obvious way to address this in the future. The Ziglings crew loves strings! Zig Core Language <ul> <li>[x] Hello world (main needs to be public)</li> <li>[x] Importing standard library</li> <li>[x] Assignment</li> <li>[x] Arrays</li> <li>[x] Strings</li> <li>[x] If</li> <li>[x] While</li> <li>[x] For</li> <li>[x] Functions</li> <li>[x] Errors (error/try/catch/if-else-err)</li> <li>[x] Defer (and errdefer)</li> <li>[x] Switch</li> <li>[x] Unreachable</li> <li>[x] Enums</li> <li>[x] Structs</li> <li>[x] Pointers</li> <li>[x] Optionals</li> <li>[x] Struct methods</li> <li>[x] Slices</li> <li>[x] Many-item pointers</li> <li>[x] Unions</li> <li>[x] Numeric types (integers, floats)</li> <li>[x] Labelled blocks and loops</li> <li>[x] Loops as expressions</li> <li>[x] Builtins</li> <li>[x] Inline loops</li> <li>[x] Comptime</li> <li>[x] Sentinel termination</li> <li>[x] Quoted identifiers @""</li> <li>[x] Anonymous structs/tuples/lists</li> <li>[ ] Async &lt;--- ironically awaiting upstream Zig updates</li> <li>[X] Interfaces</li> <li>[X] Bit manipulation</li> <li>[X] Working with C</li> <li>[ ] Opaque types (anyopaque)</li> <li>[X] Threading</li> <li>[x] Labeled switch</li> <li>[x] Vector operations (SIMD)</li> </ul> Zig Standard Library <ul> <li>[X] String formatting</li> <li>[X] Testing</li> <li>[X] Tokenization</li> <li>[X] File handling</li> </ul> Contributing Contributions are very welcome! I'm writing this to teach myself and to create the learning resource I wished for. There will be tons of room for improvement: <ul> <li>Wording of explanations</li> <li>Idiomatic usage of Zig</li> <li>Additional exercises</li> </ul> Please see <a>CONTRIBUTING</a> in this repo for the full details.
[]
https://avatars.githubusercontent.com/u/119983202?v=4
ziggy-pydust-template
spiraldb/ziggy-pydust-template
2023-08-31T10:20:02Z
A template for building Python extensions in Zig using Pydust toolkit.
develop
7
35
2
35
https://api.github.com/repos/spiraldb/ziggy-pydust-template/tags
Apache-2.0
[ "python", "zig" ]
249
false
2025-03-12T00:51:16Z
false
false
unknown
github
[]
Ziggy Pydust Template This repository contains a template for writing and packaging native Python extension modules in Zig using <a>Pydust</a> framework. This template includes: <ul> <li>A Python Poetry project.</li> <li>A <code>src/</code> directory containing a Pydust Python module.</li> <li>Pytest setup for running both Python and Zig unit tests.</li> <li>GitHub Actions workflows for building and publishing the package.</li> <li>VSCode settings for recommended extensions, debugger configurations, etc.</li> </ul> We recommend heading to <a>Getting Started</a>.
[]
https://avatars.githubusercontent.com/u/51416554?v=4
zvm
hendriknielaender/zvm
2023-08-28T21:33:11Z
⚡ Fast and simple zig version manager (zvm)
main
13
34
4
34
https://api.github.com/repos/hendriknielaender/zvm/tags
MIT
[ "version", "version-manager", "zig", "ziglang", "zvm" ]
2,116
false
2025-04-09T17:45:16Z
true
false
unknown
github
[]
⚡ Zig Version Manager (<code>zvm</code>) ⚡ Fast and simple zig version manager zvm is a command-line tool that allows you to easily install, manage, and switch between multiple versions of Zig. Features <ul> <li>List available Zig/zls versions (both remote and local).</li> <li>Install specific Zig or zls versions.</li> <li>Switch between installed Zig or zls versions.</li> <li>Remove installed Zig or zls versions.</li> <li>Display the current zvm version and helpful usage information.</li> </ul> Install To install zvm with Homebrew, aka. <code>brew</code>, run the following commands: <code>bash brew tap hendriknielaender/zvm brew install zvm</code> Now add this line to your <code>~/.bashrc</code>, <code>~/.profile</code>, or <code>~/.zshrc</code> file. <code>bash export PATH="$HOME/.zm/current/zig:$PATH"</code> Windows PowerShell <code>ps1 irm https://raw.githubusercontent.com/hendriknielaender/zvm/master/install.ps1 | iex</code> Command Prompt <code>cmd powershell -c "irm https://raw.githubusercontent.com/hendriknielaender/zvm/master/install.ps1 | iex"</code> Shell Completions <code>zvm</code> provides built-in shell completion scripts for both Zsh and Bash. This enhances the command-line experience by allowing tab-completion of subcommands, flags, etc. Zsh <strong>Generate</strong> the Zsh completion script: <code>bash zvm completions zsh &gt; _zvm</code> <strong>Move</strong> <code>_zvm</code> into a directory that Zsh checks for autoloaded completion scripts. For example: <code>bash mkdir -p ~/.zsh/completions mv _zvm ~/.zsh/completions</code> <strong>Add</strong> this to your <code>~/.zshrc</code>: <code>bash fpath+=(~/.zsh/completions) autoload -U compinit &amp;&amp; compinit</code> <strong>Reload</strong> your shell: <code>bash source ~/.zshrc</code> Bash <strong>Generate</strong> the Bash completion script: <code>bash zvm completions bash &gt; zvm.bash</code> <strong>Source</strong> it in your <code>~/.bashrc</code> (or <code>~/.bash_profile</code>): <code>bash echo "source $(pwd)/zvm.bash" &gt;&gt; ~/.bashrc source ~/.bashrc</code> Usage <strong>General Syntax:</strong> <code>bash zvm &lt;command&gt; [arguments]</code> <strong>Available Commands:</strong> - <code>zvm ls</code> or <code>zvm list</code> Lists all available versions of Zig or zls remotely by default. Use <code>--system</code> to list only locally installed versions. <code>bash zvm ls zvm ls --system zvm ls zls --system</code> <ul> <li> <code>zvm i</code> or <code>zvm install</code> Installs the specified version of Zig or zls. <code>bash zvm install &lt;version&gt; # Installs Zig and zls for the specified version zvm install --mirror=0 # Installs Zig with a specified mirror url zvm install zig &lt;version&gt; # Installs only Zig for the specified version zvm install zls &lt;version&gt; # Installs only zls for the specified version</code> </li> <li> <code>zvm use</code> Switches to using the specified installed version of Zig or zls. <code>bash zvm use &lt;version&gt; # Use this version of Zig and zls if installed zvm use zig &lt;version&gt; # Use this version of Zig only zvm use zls &lt;version&gt; # Use this version of zls only</code> </li> <li> <code>zvm remove</code> Removes the specified installed version of Zig or ZLS. <code>bash zvm remove &lt;version&gt; # Removes this version of Zig and/or zls if installed zvm remove zig &lt;version&gt; # Removes only the specified Zig version zvm remove zls &lt;version&gt; # Removes only the specified zls version</code> </li> <li> <code>zvm clean</code> Remove old download artifacts. </li> <li> <code>zvm --version</code> Displays the current version of zvm. </li> <li> <code>zvm --help</code> Displays detailed usage information. </li> </ul> <strong>Examples:</strong> ```bash List all available remote Zig versions zvm ls List all installed local Zig versions zvm ls --system List all installed local zls versions zvm ls zls --system List of available Zig mirrors zvm ls --mirror Install Zig version 0.12.0 zvm install 0.12.0 Use Zig version 0.12.0 zvm use zig 0.12.0 Remove Zig version 0.12.0 zvm remove zig 0.12.0 Remove old download artifacts. zvm clean ``` Compatibility Notes Zig is in active development and the APIs can change frequently, making it challenging to support every dev build. This project currently aims to be compatible with stable, non-development builds to provide a consistent experience for the users. <strong><em>Supported Version</em></strong>: As of now, zvm is tested and supported on Zig version <strong><em>0.14.0</em></strong>. Contributing Contributions, issues, and feature requests are welcome! Clarification Please note that our project is <strong>not</strong> affiliated with <a>ZVM</a> maintained by @tristanisham. Both projects operate independently, and any similarities are coincidental.
[]
https://avatars.githubusercontent.com/u/109492796?v=4
zig-msgpack
zigcc/zig-msgpack
2024-01-07T08:35:23Z
zig messagpack implementation / msgpack.org[zig]
main
0
33
3
33
https://api.github.com/repos/zigcc/zig-msgpack/tags
MIT
[ "msgpack", "msgpack-rpc", "zig", "zig-package" ]
115
false
2025-05-03T16:23:08Z
true
true
0.14.0
github
[]
MessagePack for Zig This is an implementation of <a>MessagePack</a> for <a>Zig</a>. an article introducing it: <a>Zig Msgpack</a> Features <ul> <li>Supports all MessagePack types(except timestamp)</li> <li>Efficient encoding and decoding</li> <li>Simple and easy-to-use API</li> </ul> NOTE The current protocol implementation has been completed, but it has not been fully tested. Only limited unit testing has been conducted, which does not cover everything. Getting Started <blockquote> About 0.13 and previous versions, please use <code>0.0.6</code> </blockquote> <code>0.14.0</code> \ <code>nightly</code> <ol> <li>Add to <code>build.zig.zon</code></li> </ol> ```sh zig fetch --save https://github.com/zigcc/zig-msgpack/archive/{commit or branch}.tar.gz Of course, you can also use git+https to fetch this package! ``` <ol> <li>Config <code>build.zig</code></li> </ol> <code>``zig // To standardize development, maybe you should use</code>lazyDependency()<code>instead of</code>dependency()` const msgpack = b.dependency("zig-msgpack", .{ .target = target, .optimize = optimize, }); // add module exe.root_module.addImport("msgpack", msgpack.module("msgpack")); ``` Related projects <ul> <li><a>getty-msgpack</a></li> <li><a>znvim</a></li> </ul>
[ "https://github.com/jinzhongjia/znvim" ]
https://avatars.githubusercontent.com/u/2172297?v=4
night.zig
jsomedon/night.zig
2023-05-19T05:51:27Z
Simple tool that just install & update zig nightly.
main
2
32
2
32
https://api.github.com/repos/jsomedon/night.zig/tags
MIT
[ "zig" ]
33
false
2025-05-05T09:56:01Z
false
false
unknown
github
[]
night.zig Simple tool that just install &amp; update <code>zig</code> nightly. Usage ```bash USAGE: nz SUBCOMMANDS: update Update both zig nightly toolchain &amp; nz itself update nightly Update zig nightly toolchain only update nz Update nz itself only cleanup Remove outdated nightly toolchains version Show nz version info help Show this message ``` Dependencies <ul> <li><code>bash</code></li> <li><code>curl</code></li> <li><code>jq</code></li> <li><code>basename</code></li> <li><code>tar</code></li> <li><code>find</code></li> <li><code>readlink</code></li> </ul> You will mostly have everything preinstalled except <code>jq</code>. Installation Run this in terminal: <code>bash curl "https://raw.githubusercontent.com/jsomedon/night.zig/main/nz" | bash -s -- _bootstrap</code> You can also optionally install shell completion scripts, you can find them under <code>completions</code> folder. For now only bash completion script is implemented. Bash (using bash-completion on Linux) On Linux, completion scripts for <code>bash-completion</code> are commonly stored in <code>/etc/bash_completion.d/</code> for system-wide commands, but can be stored in <code>~/.local/share/bash-completion/completions</code> for user-specific commands. Install <code>bash-completion</code> package with your distributions' package manager first -- packages' name might vary, then: <code>bash mkdir -p ~/.local/share/bash-completion/completions mv nz.comp.bash ~/.local/share/bash-completion/completions/</code> You may have to log out and log back in to your shell session for the changes to take effect. Bash (using bash-completion on macOS/Homebrew) On macOS, homebrew stores <code>bash-completion</code> scripts within the homebrew directory. Install <code>bash-completion</code> brew formula, then put <code>nz.comp.bash</code> into <code>$(brew --prefix)/etc/bash_completion.d</code>: <code>bash brew install bash-completion # or bash-completion@2 if your bash version is 4.2+ mkdir -p $(brew --prefix)/etc/bash_completion.d mv nz.comp.bash $(brew --prefix)/etc/bash_completion.d/</code> Bash (not using bash-completion) For quick installation, you can simply download the <code>nz.comp.bash</code> script somewhere on your machine, then <code>source</code> the script in your bash profile file. Uninstallation Both <code>nz</code> and nightly bins are installed in <code>~/.night.zig/</code>, so just remove that folder: <code>bash rm -rf ~/.night.zig</code> If you installed shell completion scripts, remove them from their respective dirs as well. Rant I just started looking into <code>zig</code> yesterday, and I couldn't believe fine folks of <code>zig</code> community are manually grabbing the nightly bins without any tools? So here we have this one. I didn't fully test architecture &amp; os detection logic, only on <code>x86_64-linux</code> and <code>aarch64-macos</code>. I may rewrite this little tool in <code>zig</code> when I get comfortable enough with <code>zig</code>, so that you don't need dependencies and what not. But no promise on that. License MIT
[]
https://avatars.githubusercontent.com/u/206480?v=4
smtp_client.zig
karlseguin/smtp_client.zig
2023-08-18T10:15:56Z
SMTP client for Zig
master
1
31
4
31
https://api.github.com/repos/karlseguin/smtp_client.zig/tags
MIT
[ "smtp-client", "zig", "zig-library", "zig-package" ]
109
false
2025-03-21T00:15:47Z
true
true
unknown
github
[]
SMTP Client for Zig Zig only supports TLS 1.3. Furthermore, the TLS implementation <a>has known issues</a>. This library does not work with Amazon SES as Amazon SES does not support TLS 1.3 (Amazon's documentation says that TLS 1.3 is supported with StartTLS but this does not appear to be the case (OpenSSL also reports an error)). The library supports the <code>PLAIN</code>, <code>LOGIN</code> and <code>CRAM-MD5</code> mechanisms of the <code>AUTH</code> extension. Installation Add this to your build.zig.zon ```zig .dependencies = .{ .smtp_client = .{ .url = "https://github.com/karlseguin/smtp_client.zig/archive/refs/heads/master.tar.gz", //the correct hash will be suggested by zig } } ``` And add this to you build.zig <code>zig const smtp_client = b.dependency("smtp_client", .{ .target = target, .optimize = optimize, }); exe.addModule("smtp_client", smtp_client.module("smtp_client"));</code> Basic Usage ```zig const std = @import("std"); const smtp = @import("smtp_client"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const config = smtp.Config{ .port = 25, .encryption = .none, .host = "localhost", .allocator = allocator, // .username = "username", // .password = "password", }; try smtp.send(.{ .from = "admin@localhost", .to = &amp;.{"user@localhost"}, .subject = "This is the Subject" .text_body = "This is the text body", .html_body = "<b>This is the html body</b>", }, config); } ``` Encryption Prefer using <code>.encryption = .tls</code> where possible. Most modern email vendors provide SMTP over TLS and support TLS 1.3. <code>.encryption = .start_tls</code> is also supported, but StartTLS is vulnerable to man-in-the-middle attack. <code>.encryption = .none</code> will not use any encryption. In this mode, authentication via <code>LOGIN</code> or <code>PLAIN</code> will be rejected. <code>.encryption = .insecure</code> will not use any encryption. In this mode, authentication via <code>LOGIN</code> or <code>PLAIN</code> will be allowed and passwords will be sent in plain text. Regardless of the encryption setting, the library will favor authenticating via <code>CRAM-MD5</code> if the server supports it. Client The <code>smtp.send</code> and <code>smtp.sendAll</code> functions are wrappers around an <code>smtp.Client</code>. Where <code>send</code> and <code>sendAll</code> open a connection, send one or more messages and then close the connection, an <code>smtp.Client</code> keeps the connection open until <code>deinit</code> is called. The client is <strong>not</strong> thread safe. ```zig var client = try smtp.connect({ .port = 25, .encryption = .none, .host = "localhost", .allocator = allocator, // .username = "username", // .password = "password", }); defer client.deinit(); try client.hello(); try client.auth(); // Multiple messages can be sent here try client.sendMessage(.{ .subject = "This is the Subject" .text_body = "This is the text body", }); // Once this is called, no more messages can be sent try client.quit(); ``` <code>hello</code> and <code>auth</code> can be called upfront, while <code>from</code>, <code>to</code> and <code>sendMessage</code> can be called repeatedly. To make the Client thread safe, protect the call to <code>sendMessage</code> with a mutex. Message The <code>smtp.Message</code> which is passed to <code>smtp.send</code>, <code>smtp.sendAll</code> and <code>client.sendMessage</code> has the following fields: <ul> <li><code>from: Address</code> - The address the email is from</li> <li><code>to: ?[]const Address</code> - A list of addresses to send the email to</li> <li><code>cc: ?[]const Address</code> - A list of addresses to cc the email to</li> <li><code>bcc: ?[]const Address</code> - A list of addresses to bcc the email to</li> <li><code>subject: ?[]const u8 = null</code> - The subject</li> <li><code>text_body: ?[]const u8 = null</code> - The Text body</li> <li><code>html_body: ?[]const u8 = null</code> - The HTML body</li> </ul> The <code>timestamp: ?i64 = null</code> field can also be set. This is used when writing the <code>Date</code> header. By default <code>std.time.timestamp</code>. Only advance usage should set this. As an alternative to setting the above fields, the <code>data: ?[]const u8 = null</code> field can be set. This is the complete raw data to send following the SMTP <code>DATA</code> command. When specified, the rest of the fields are ignored. The <code>data</code> must comform to <a>RFC 2822 - Internet Message Format</a>, including a trailing <code>\r\n.\r\n</code>. I realize that a union would normally be used to make <code>data</code> and the other fields mutually exclusive. However, the use of <code>data</code> is considered an advanced feature, and adding union simply makes the API more complicated for 99% of the cases which would not use it. Message.Address The <code>Message.Address</code> structure has two fields: <ul> <li><code>name: ?[]const u8 = null</code> - the optional name</li> <li><code>address: []const u8</code> - the email address </li> </ul> Performance Tip 1 - sendAll The <code>sendAll</code> function takes an array of <code>smtp.Message</code>. It is much more efficient than calling <code>send</code> in a loop. ```zig var config = smtp.Config{ // same configuration as send }; var sent: usize = 0; const messages = [_]smtp.Message{ .{ .from = "...", .to = &amp;.{"..."}, .subject = "...", .text_body = "...", }, .{ .from = "...", .to = &amp;.{"..."}, .subject = "...", .text_body = "...", } }; try smtp.sendAll(&amp;messages, config, &amp;sent); ``` <code>sendAll</code> can fail part way, resulting in some messages being sent while others are not. <code>sendAll</code> stops at the first encountered error. The last parameter to <code>sendAll</code> is set to the number of successfully sent messages, thus it's possible for the caller to know which messages were and were not sent (e.g. if <code>sent == 3</code>, then messages 1, 2 and 3 were sent, message 4 failed and it, along with all subsequent messages, were not sent). Of course, when we say "successfully sent", we only mean from the point of view of this library. SMTP being asynchronous means that this library can successfully send the message to the configured upstream yet the message never reaches the final recipient(s). Tip 2 - CA Bundle If you're using TLS encryption (via either <code>.encryption = .tls</code> or <code>.encryption = .start_tls</code>), you can improve performance by providing your own CA bundle. When <code>send</code> or <code>sendAll</code> are called without a configured <code>ca_bundle</code>, one is created on each call, which involves reading and parsing your OS' root certificates from disk (again, on every call). You can create a certificate bundle on app start, using: <code>zig var ca_bundle = std.crypto.Certificate.Bundle{} try ca_bundle.rescan(allocator); defer ca_bundle.deinit(allocator);</code> And then pass the bundle to <code>send</code> or <code>sendAll</code>: <code>zig var config = smtp.Config{ .port = 25, .host = "localhost", .encryption = .tls, .ca_bundle = ca_bundle, // ... };</code> Tip 3 - Skip DNS Resolution Every call to <code>send</code> and <code>sendAll</code> requires a DNS lookup on <code>config.host</code>. The <code>sendTo</code> and <code>sendAllTo</code> functions, which take an <code>std.net.Address</code>, can be used instead. When using these functions, <code>config.host</code> must still be set to the valid host when <code>.tls</code> or <code>.start_tls</code> is used. Similarly, instead of <code>connect</code> to create a <code>Client</code>, <code>connectTo</code> can be used which takes an <code>std.net.Address</code>. Allocator <code>config.allocator</code> is required in two cases: 1. <code>send</code>, <code>sendAll</code> or <code>connect</code> are used, OR 2. <code>config.ca_bundle</code> is not specified and <code>.tls</code> or <code>.start_tls</code> are used Put differently, <code>config.allocator</code> can be null when both these cases are true: 1. <code>sendTo</code>, <code>sendAllTo</code> or <code>connectTo</code> are used, AND 2. <code>config.ca_bundle</code> is provided or <code>.encryption</code> is set to <code>.none</code> or <code>.insecure</code>. Put differently again, <code>config.allocator</code> is only used by the library to (a) call <code>std.net.tcpConnectToHost</code> which does a DNS lookup and (b) manage the <code>std.crypto.Certificate.Bundle</code>. If <code>config.allocator</code> is required but not specified, the code will return an error.
[]
https://avatars.githubusercontent.com/u/7832610?v=4
zig-sokol-crossplatform-starter
geooot/zig-sokol-crossplatform-starter
2023-11-11T02:40:27Z
A template for an app that runs on iOS, Android, PC, and Mac. Built with Sokol, and using Zig
main
0
30
2
30
https://api.github.com/repos/geooot/zig-sokol-crossplatform-starter/tags
Unlicense
[ "android", "ios", "sokol", "zig", "ziglang" ]
190
false
2025-05-13T14:29:29Z
true
true
0.12.0
github
[ { "commit": "dfbfaf077ced93bb3274a138c8d4a303d635984a", "name": "sokol", "tar_url": "https://github.com/floooh/sokol-zig/archive/dfbfaf077ced93bb3274a138c8d4a303d635984a.tar.gz", "type": "remote", "url": "https://github.com/floooh/sokol-zig" }, { "commit": null, "name": "kubazip", ...
zig-sokol-crossplatform-starter A template for an app that runs on iOS, Android, PC and Mac. Built using <a>the Zig programming language</a>, and using the <a><code>floooh/sokol</code></a> graphics/app library. Also, taken inspiration from <a><code>kubkon/zig-ios-example</code></a>, <a><code>MasterQ32/ZigAndroidTemplate</code></a>, and <a><code>cnlohr/rawdrawandroid</code></a> Clone <code>git clone https://github.com/geooot/zig-sokol-crossplatform-starter.git</code> Required Dependencies You will need the <code>0.14</code> release of Zig, you can find it <a>here</a>. For iOS - xcode - Edit <code>build.zig</code> with <code>APP_NAME</code> and <code>BUNDLE_PREFIX</code> changed as necessary. For Android - <a>Android SDK</a> install with <code>ANDROID_HOME</code> environment variable set. - Java JDK, and <code>keytool</code> (should be included in JDK install). <code>$JAVA_HOME</code> should be set to the install location - Edit <code>build.zig</code> with <code>ANDROID_</code> prefixed constants as necessary. You probably only need to change <code>*_VERSION</code> const's to match what you have installed in your android SDK (check <code>$ANDROID_HOME</code>). - Edit <code>build.zig</code> with <code>APP_NAME</code> and <code>BUNDLE_PREFIX</code> changed as necessary. For PC/Mac - Nothing! Just <code>zig build run</code>. Build and Run Make sure to perform the edits and get the dependencies described in <a>"Required Dependencies"</a> before continuing below. ```sh $ zig build run # builds and runs executable on your computer $ zig build # builds everything (iOS, android, your computer) $ zig build ios # generates iOS project (in zig-out/MyApp.xcodeproj). # - You have to open xcode and build from there $ zig build android # builds android apks (in zig-out/MyApp.apks). # - You have to use <code>zig build bundletool -- install-apks --apks=zig-out/MyApp.apks</code> # to install it to a device. # - But you use the <code>.aab</code> file when submitting to Google Play. $ zig build default # builds a executable for your computer ``` Quirks and Features Features - Ability to build for your PC, iOS, and Android - Android App Bundle support. - XCode project is an artifact. Configuration using YAML instead (thanks to <code>xcodegen</code>) - Pretty easy to modify build system (thanks to Zig). - Small binaries, fast loading times! Quirks - Not really easy to debug for android. Surprisingly the xcode debugger works pretty well. - Still need XCode to finish the build for iOS. It's needed for code signing and final linking. Things that would be cool to add in the future In no particular order <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 sokol-zig to be a zig dependency rather than a git submodule <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> Can we get rid of the dependency on <code>xcodegen</code> and <code>bundletool</code>? I think we can at least use zig package manager to fetch those dependencies on build. We need zip support (xcodegen releases itself as a zip file rather than a tarball) and single file download support (bundletool packages itself as a single <code>.jar</code>) to make that possible. - Even crazier idea: reimplement <code>xcodegen</code> and <code>bundletool</code> as zig libraries. <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> In my sleep I still think about <code>kubkon/zig-ios-example</code> since it doesn't require generating a xcode project at all. I think in reality, people might need <strong>some</strong> xcode project generation support, but like... <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> Github Action CI/CD workflows. <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> Add minimal WASM/WASI builds (lets move past emscripten). License This is Public Domain software with the UNLICENSE license. All code except for the following exceptions are under the UNLICENSE license. - <code>build/auto-detect.zig</code> falls under the MIT License <a>[[See here]]</a>. - <code>sokol-zig</code> (and sokol in general) fall under the Zlib license <a>[[See here]]</a>.
[]
https://avatars.githubusercontent.com/u/480330?v=4
zig-router
Cloudef/zig-router
2023-12-20T16:17:51Z
Straightforward HTTP-like request routing.
master
1
29
1
29
https://api.github.com/repos/Cloudef/zig-router/tags
MIT
[ "backend", "http", "routing", "web-framework", "zig" ]
35
false
2025-03-14T19:07:49Z
true
true
unknown
github
[ { "commit": "a78731bfc9a577ff57ca9bba05959a99a0898b64", "name": "getty", "tar_url": "https://github.com/getty-zig/getty/archive/a78731bfc9a577ff57ca9bba05959a99a0898b64.tar.gz", "type": "remote", "url": "https://github.com/getty-zig/getty" } ]
zig-router Straightforward HTTP-like request routing. Project is tested against zig 0.13.0 Sample ```zig const router = @import("zig-router"); const MyJsonBody = struct { float: f32, text: []const u8, number_with_default: u32 = 42, }; fn putJson(body: MyJsonBody) !Response { log.info("float: {}", .{body.float}); log.info("text: {s}", .{body.text}); log.info("number_with_default: {}", .{body.number_with_default}); return .{ .body = "ok" }; } const MyPathParams = struct { id: []const u8, bundle: u32, }; fn getDynamic(params: MyPathParams) !Response { log.info("id: {s}", .{params.id}); log.info("bundle: {}", .{params.bundle}); return .{}; } const MyQuery = struct { id: []const u8 = "plz give me a good paying stable job", bundle: u32 = 42, }; fn getQuery(query: MyQuery) !Response { log.info("id: {s}", .{query.id}); log.info("bundle: {}", .{query.bundle}); return .{}; } fn getError() !void { return error.EPIC_FAIL; } fn onRequest(arena: *std.heap.ArenaAllocator, request: Request) !void { router.Router(.{ router.Decoder(.json, router.JsonBodyDecoder(.{}, 4096).decode), }, .{ router.Route(.PUT, "/json", putJson, .{}), router.Route(.GET, "/dynamic/:id/paths/:bundle", getDynamic, .{}), router.Route(.GET, "/query", getQuery, .{}), router.Route(.GET, "/error", getError, .{}), }).match(arena.allocator(), .{ .method = request.method, .path = request.path, .query = request.query, .body = .{ .reader = request.body.reader() } }, .{ arena.allocator() }) catch |err| switch (err) { error.not_found =&gt; return .{ .status = .not_found }, error.bad_request =&gt; return .{ .status = .bad_request }, else =&gt; return err, }; } ``` Depend Run the following command in zig project root directory. <code>sh zig fetch --save git+https://github.com/Cloudef/zig-router.git</code> In <code>build.zig</code> file add the following for whichever modules <code>zig-router</code> is required. <code>zig const zig_router = b.dependency("zig-router", .{}); exe.root_module.addImport("zig-router", zig_router.module("zig-router"));</code> You can now import the <code>zig-router</code> from zig code. <code>zig const router = @import("zig-router");</code>
[]
https://avatars.githubusercontent.com/u/2242?v=4
zig-lambda-runtime
softprops/zig-lambda-runtime
2023-11-13T05:01:53Z
an aws lambda runtime for zig
main
2
29
2
29
https://api.github.com/repos/softprops/zig-lambda-runtime/tags
MIT
[ "aws", "aws-lambda", "zig", "ziglang" ]
64
false
2025-04-24T20:51:54Z
true
true
0.12.0
github
[]
zig lambda runtime An implementation of the <a>aws lambda runtime</a> for <a>zig</a> ⚡ 🦎 <a></a> <a></a> 🍬 features <ul> <li>⚡ small and fast</li> </ul> Zig is impressively fast and small by default and can be made even faster and smaller with common <code>optimize</code> compilation flags. ❄ avg cold start duration <code>11ms</code> 💾 avg memory <code>10MB</code> ⚡ avg duration <code>1-2ms</code> <ul> <li>📦 painless and easy packaging</li> </ul> Zig comes with a self-contained build tool that makes cross compilation for aws deployment targets painless <code>zig build -Dtarget=aarch64-linux -Doptimize={ReleaseFast,ReleaseSmall}</code> Coming soon... <ul> <li>streaming response support</li> </ul> By default aws lambda buffers and then returns a single response to client but can be made streaming with opt in configuration <ul> <li>event struct types</li> </ul> At present it is up to lambda functions themselves to parse the and self declare event payloads structures and serialize responses. We would like to provide structs for common aws lambda event and response types to make that easier examples Below is an example echo lambda that echo's the event that triggered it. ```zig const std = @import("std"); const lambda = @import("lambda"); pub fn main() !void { // 👇 wrap a free standing fn in a handler type var wrapped = lambda.wrap(handler); // 👇 start the runtime with this handler try lambda.run(null, wrapped.handler()); } fn handler(allocator: std.mem.Allocator, context: lambda.Context, event: []const u8) ![]const u8 { _ = allocator; _ = context; return event; } ``` 📼 installing Create a new exec project with <code>zig init-exe</code>. Copy the echo handler example above into <code>src/main.zig</code> Create a <code>build.zig.zon</code> file to declare a dependency <blockquote> .zon short for "zig object notation" files are essentially zig structs. <code>build.zig.zon</code> is zigs native package manager convention for where to declare dependencies </blockquote> <code>diff .{ .name = "my-first-zig-lambda", .version = "0.1.0", .dependencies = .{ + // 👇 declare dep properties + .lambda = .{ + // 👇 uri to download + .url = "https://github.com/softprops/zig-lambda-runtime/archive/refs/tags/v0.2.0.tar.gz", + // 👇 hash verification + .hash = "12202c21b4111b1b549508847b0de394f2188d16560287e532441457314d7c0671fa", + }, }, .minimum_zig_version = "0.12.0", .paths = .{""}, }</code> <blockquote> the hash below may vary. you can also depend any tag with <code>https://github.com/softprops/zig-lambda-runtime/archive/refs/tags/v{version}.tar.gz</code> or current main with <code>https://github.com/softprops/zig-lambda-runtime/archive/refs/heads/main/main.tar.gz</code>. to resolve a hash, omit it and let zig tell you the expected value. </blockquote> 🔧 building This library targets the provided lambda runtime, prefer <code>provided.al2023</code> the latest, which assumes an executable named <code>bootstrap</code>. To produce one of these, add the following in your <code>build.zig</code> file ```diff const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); <code>const optimize = b.standardOptimizeOption(.{}); </code> <ul> <li>// 👇 de-reference lambda dep from build.zig.zon</li> <li>const lambda = b.dependency("lambda", .{</li> <li>.target = target,</li> <li>.optimize = optimize,</li> <li>}).module("lambda"); // 👇 create an execuable named <code>bootstrap</code>. the name <code>bootstrap</code> is important var exe = b.addExecutable(.{ .name = "bootstrap", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, });</li> <li>// 👇 add the lambda module to executable</li> <li> exe.addModule("lambda", lambda); b.installArtifact(exe); } ``` </li> </ul> Then build an arm linux executable by running <code>zig build -Dtarget=aarch64-linux --summary all</code> <blockquote> We're using <code>aarch64</code> because we'll be deploying to the <code>arm64</code> lambda runtime architecture below Also consider optimizing for faster artifact with <code>zig build -Dtarget=aarch64-linux -Doptimize=ReleaseFast --summary all</code> or smaller artifact with <code>zig build -Dtarget=aarch64-linux -Doptimize=ReleaseSmall --summary all</code>. The default is a <code>Debug</code> build which trades of speed and size for faster compilation. See <code>zig build --help</code> for more info </blockquote> 📦 packaging Package your function in zip file (aws lambda assumes a zip file) <code>zip -jq lambda.zip zig-out/bin/bootstrap</code> 🪂 deploying The follow shows how to deploy a lambda using a standard aws deployment tool, <a>aws sam cli</a>. Create a <code>template.yml</code> sam deployment template ```yaml AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Resources: Function: Type: AWS::Serverless::Function Properties: # 👇 use the latest provided runtime Runtime: provided.al2023 # 👇 deploy on arm architecture, it's more cost effective Architectures: - arm64 MemorySize: 128 # 👇 the zip file containing your <code>bootstrap</code> binary # example: zip -jq lambda.zip zig-out/bin/bootstrap CodeUri: "lambda.zip" # 👇 required for zip but not used by the zig runtime, put any value you like here Handler: handler FunctionName: !Sub "${AWS::StackName}" Policies: - AWSLambdaBasicExecutionRole ``` Create a <code>samconfig.toml</code> to store some local sam cli defaults <blockquote> this file is can be updated overtime to evolve with your infra as your infra needs evolved </blockquote> ```toml version = 1.0 [default.deploy.parameters] resolve_s3 = true s3_prefix = "zig-lambda-demo" stack_name = "zig-lambda-demo" region = "us-east-1" fail_on_empty_changeset = false capabilities = "CAPABILITY_IAM" ``` Then run <code>sam deploy</code> to deploy it 🥹 for budding ziglings Does this look interesting but you're new to zig and feel left out? No problem, zig is young so most us of our new are as well. Here are some resources to help get you up to speed on zig <ul> <li><a>the official zig website</a></li> <li><a>zig's one-page language documentation</a></li> <li><a>ziglearn</a></li> <li><a>ziglings exercises</a></li> </ul> - softprops 2023
[]
https://avatars.githubusercontent.com/u/149461062?v=4
core
PhantomUIx/core
2023-10-24T22:21:19Z
A truly cross-platform GUI toolkit for Zig.
master
3
29
2
29
https://api.github.com/repos/PhantomUIx/core/tags
MIT
[ "phantomui", "ui-framework", "zig" ]
382
false
2025-05-16T06:17:27Z
true
true
unknown
github
[ { "commit": "256cf2655bb887a30c57d8cbc1b9590643f0a824.tar.gz", "name": "zigimg", "tar_url": "https://github.com/TUSF/zigimg/archive/256cf2655bb887a30c57d8cbc1b9590643f0a824.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/TUSF/zigimg" }, { "commit": "67d2e2e1891cd467fb7cb7c07...
Phantom UI A truly cross-platform GUI toolkit for Zig.
[ "https://github.com/JamWils/zig-graphics-experiments", "https://github.com/ZigEmbeddedGroup/microzig", "https://github.com/allyourcodebase/boost-libraries-zig", "https://github.com/kassane/beast", "https://github.com/kassane/context" ]
https://avatars.githubusercontent.com/u/16268616?v=4
zig-sqlite
nDimensional/zig-sqlite
2023-11-27T00:01:40Z
Simple, low-level, explicitly-typed SQLite bindings for Zig.
main
1
29
3
29
https://api.github.com/repos/nDimensional/zig-sqlite/tags
MIT
[ "sqlite", "sqlite3", "zig" ]
55
false
2025-05-01T00:07:34Z
true
true
0.14.0
github
[ { "commit": null, "name": "sqlite_amalgamation", "tar_url": null, "type": "remote", "url": "https://www.sqlite.org/2025/sqlite-amalgamation-3490100.zip" } ]
zig-sqlite Simple, low-level, explicitly-typed SQLite bindings for Zig. Table of Contents <ul> <li><a>Installation</a></li> <li><a>Usage</a></li> <li><a>Methods</a></li> <li><a>Queries</a></li> <li><a>Notes</a></li> <li><a>Build options</a></li> <li><a>License</a></li> </ul> Installation This library uses and requires Zig version <code>0.14.0</code> or later. Add the dependency to <code>build.zig.zon</code>: <code>zig .{ .dependencies = .{ .sqlite = .{ .url = "https://github.com/nDimensional/zig-sqlite/archive/refs/tags/v0.2.1-3490100.tar.gz", // .hash = "", }, }, }</code> Then add <code>sqlite</code> as an import to your root modules in <code>build.zig</code>: ```zig fn build(b: *std.Build) void { const app = b.addExecutable(.{ ... }); // ... <code>const sqlite = b.dependency("sqlite", .{}); app.root_module.addImport("sqlite", sqlite.module("sqlite")); </code> } ``` Usage Open databases using <code>Database.open</code> and close them with <code>db.close()</code>: ```zig const sqlite = @import("sqlite"); { // in-memory database const db = try sqlite.Database.open(.{}); defer db.close(); } { // persistent database const db = try sqlite.Database.open(.{ .path = "path/to/db.sqlite" }); defer db.close(); } ``` Execute one-off statements using <code>Database.exec</code>: <code>zig try db.exec("CREATE TABLE users (id TEXT PRIMARY KEY, age FLOAT)", .{});</code> Prepare statements using <code>Database.prepare</code>, and finalize them with <code>stmt.finalize()</code>. Statements must be given explicit comptime params and result types, and are typed as <code>sqlite.Statement(Params, Result)</code>. <ul> <li>The comptime <code>Params</code> type must be a struct whose fields are (possibly optional) float, integer, <code>sqlite.Blob</code>, or <code>sqlite.Text</code> types.</li> <li>The comptime <code>Result</code> type must either be <code>void</code>, indicating a method that returns no data, or a struct of the same kind as param types, indicating a query that returns rows.</li> </ul> <code>sqlite.Blob</code> and <code>sqlite.Text</code> are wrapper structs with a single field <code>data: []const u8</code>. Methods If the <code>Result</code> type is <code>void</code>, use the <code>exec(params: Params): !void</code> method to execute the statement several times with different params. ```zig const User = struct { id: sqlite.Text, age: ?f32 }; const insert = try db.prepare(User, void, "INSERT INTO users VALUES (:id, :age)"); defer insert.finalize(); try insert.exec(.{ .id = sqlite.text("a"), .age = 21 }); try insert.exec(.{ .id = sqlite.text("b"), .age = null }); ``` Queries If the <code>Result</code> type is a struct, use <code>stmt.bind(params)</code> in conjunction with <code>defer stmt.reset()</code>, then <code>stmt.step()</code> over the results. <blockquote> ℹ️ Every <code>bind</code> should be paired with a <code>reset</code>, just like every <code>prepare</code> is paired with a <code>finalize</code>. </blockquote> ```zig const User = struct { id: sqlite.Text, age: ?f32 }; const select = try db.prepare( struct { min: f32 }, User, "SELECT * FROM users WHERE age &gt;= :min", ); defer select.finalize(); // Get a single row { try select.bind(.{ .min = 0 }); defer select.reset(); <code>if (try select.step()) |user| { // user.id: sqlite.Text // user.age: ?f32 std.log.info("id: {s}, age: {d}", .{ user.id.data, user.age orelse 0 }); } </code> } // Iterate over all rows { try select.bind(.{ .min = 0 }); defer select.reset(); <code>while (try select.step()) |user| { std.log.info("id: {s}, age: {d}", .{ user.id.data, user.age orelse 0 }); } </code> } // Iterate again, with different params { try select.bind(.{ .min = 21 }); defer select.reset(); <code>while (try select.step()) |user| { std.log.info("id: {s}, age: {d}", .{ user.id.data, user.age orelse 0 }); } </code> } ``` Text and blob values must not be retained across steps. <strong>You are responsible for copying them.</strong> Notes Crafting sensible Zig bindings for SQLite involves making tradeoffs between following the Zig philosophy ("deallocation must succeed") and matching the SQLite API, in which closing databases or finalizing statements may return error codes. This library takes the following approach: <ul> <li><code>Database.close</code> calls <code>sqlite3_close_v2</code> and panics if it returns an error code.</li> <li><code>Statement.finalize</code> calls <code>sqlite3_finalize</code> and panics if it returns an error code.</li> <li><code>Statement.step</code> automatically calls <code>sqlite3_reset</code> if <code>sqlite3_step</code> returns an error code.</li> <li>In SQLite, <code>sqlite3_reset</code> returns the error code from the most recent call to <code>sqlite3_step</code>. This is handled gracefully.</li> <li><code>Statement.reset</code> calls both <code>sqlite3_reset</code> and <code>sqlite3_clear_bindings</code>, and panics if either return an error code.</li> </ul> These should only result in panic through gross misuse or in extremely unusual situations, e.g. <code>sqlite3_reset</code> failing internally. All "normal" errors are faithfully surfaced as Zig errors. Build options <code>zig struct { SQLITE_ENABLE_COLUMN_METADATA: bool = false, SQLITE_ENABLE_DBSTAT_VTAB: bool = false, SQLITE_ENABLE_FTS3: bool = false, SQLITE_ENABLE_FTS4: bool = false, SQLITE_ENABLE_FTS5: bool = false, SQLITE_ENABLE_GEOPOLY: bool = false, SQLITE_ENABLE_ICU: bool = false, SQLITE_ENABLE_MATH_FUNCTIONS: bool = false, SQLITE_ENABLE_RBU: bool = false, SQLITE_ENABLE_RTREE: bool = false, SQLITE_ENABLE_STAT4: bool = false, SQLITE_OMIT_DECLTYPE: bool = false, SQLITE_OMIT_JSON: bool = false, SQLITE_USE_URI: bool = false, }</code> Set these by passing e.g. <code>-DSQLITE_ENABLE_RTREE</code> in the CLI, or by setting <code>.SQLITE_ENABLE_RTREE = true</code> in the <code>args</code> parameter to <code>std.Build.dependency</code>. For example: ```zig pub fn build(b: *std.Build) !void { // ... <code>const sqlite = b.dependency("sqlite", .{ .SQLITE_ENABLE_RTREE = true }); </code> } ``` License MIT © nDimensional Studios
[]
https://avatars.githubusercontent.com/u/44501064?v=4
zig-tls12
melonedo/zig-tls12
2023-12-28T13:49:53Z
HTTP client capable of TLS 1.2.
main
1
28
5
28
https://api.github.com/repos/melonedo/zig-tls12/tags
MIT
[ "tls", "tls12", "zig", "ziglang" ]
297
false
2025-05-15T01:43:55Z
true
false
unknown
github
[]
Zig-TLS12 HTTP client capable of TLS 1.2. You may use <code>HttpClient</code> in the same way you use <code>std.http.Client</code>. The only difference of <code>HttpClient</code> from <code>std.http.Client</code> is that <code>std.crypto.tls.Client</code> which supports TLS 1.3 is replaced by a TLS 1.2 capable <code>TlsClient</code>. Usage Add to <code>build.zig.zon</code>: <code>zig .{ .dependencies = .{ // other dependencies... .tls12 = .{ // Check releases for other versions .url = "https://github.com/melonedo/zig-tls12/archive/refs/heads/main.zip", // Let zon find out .hash = "12341234123412341234123412341234123412341234123412341234123412341234", }, }, }</code> Add to <code>build.zig</code>: <code>zig // const exe = b.addExecutable(...); const tls12 = b.dependency("tls12", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("tls12", tls12.module("zig-tls12"));</code> In zig program: <code>zig // Drop-in replacement of std.http.Client const HttpClient = @import("tls12");</code> Example This is tested againt zig version <code>0.12.0-dev.3674+a0de07760</code>. Zig's HTTP interface has changed so it DOES NOT WORK on 0.11 and below. ```zig const std = @import("std"); // With zon: const HttpClient = @import("tls12"); // With stdlib: const HttpClient = std.http.Client; const HttpClient = @import("HttpClient.zig"); pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); <code>var client = HttpClient{ .allocator = allocator }; defer client.deinit(); try client.initDefaultProxies(allocator); const url = "https://httpbin.org"; const uri = try std.Uri.parse(url); var server_header_buffer: [1024 * 1024]u8 = undefined; var req = try HttpClient.open(&amp;client, .GET, uri, .{ .server_header_buffer = &amp;server_header_buffer, .redirect_behavior = @enumFromInt(10), }); defer req.deinit(); try req.send(); try req.wait(); const body = try req.reader().readAllAlloc(allocator, 16 * 1024 * 1024); defer allocator.free(body); std.debug.print("{s}: {s}\n", .{ url, body }); </code> } ```
[]
https://avatars.githubusercontent.com/u/206480?v=4
buffer.zig
karlseguin/buffer.zig
2023-06-24T09:53:44Z
A poolable string builder (aka string buffer) for Zig
master
0
28
2
28
https://api.github.com/repos/karlseguin/buffer.zig/tags
MIT
[ "zig" ]
58
false
2025-04-24T14:17:10Z
true
false
unknown
github
[]
String Builder / Buffer For Zig Behaves a lot like a <code>std.ArrayList(u8)</code> but with a cleaner interface and pooling capabilities. ```zig const Buffer = @import("buffer").Buffer; // Starts off with a static buffer of 100 bytes // If you go over this, memory will be dynamically allocated // It's like calling ensureTotalCapacity on an ArrrayList, but // those 100 bytes (aka the static portion of the buffer) are // re-used when pooling is used var buf = try Buffer.init(allocator, 100); try buf.writeByte('o'); try buf.write("ver 9000!1"); buf.truncate(1); buf.len(); // 10 buf.string(); // "over 9000!" ``` You can call <code>buf.writer()</code> to get an <code>std.io.Writer</code>. You can use <code>writeU16Big</code>, <code>writeU32Big</code>, <code>writeU64Big</code> and <code>writeU16Little</code>, <code>writeU32Little</code>, <code>writeU64Little</code> to write integer values. Views A common pattern is to include a 2 or 4 byte payload length prefix to messages. However, this length might not until after the message is generated. The <code>skip</code> functions exist specifically to solve the problem: ```zig var buf = try Buffer.init(allocator, 100); // skip 4 bytes, reserving a "view" to the start of the skipped location var view = buf.skip(4); try buf.write("hello world"); try buf.writeByte('!'); // fill in those first 4 bytes with the lenght (which we now know.) view.writeU32Little(@intCast(buf.len()); ``` The <code>view</code> exposes most of the same methods as the Buffer, but cannot grow and does not perform bound checking. Pooling ```zig const Pool = @import("string_builder").Pool; // Creates pool of 100 Buffers, each configured with a static buffer // of 10000 bytes var pool = try Pool.init(allocator, 100, 10000); var buf = try pool.acquire(); defer pool.release(buf); ``` The <code>Pool</code> is thread-safe. The <code>Buffer</code> is not thread safe. For a more advanced use case, <code>pool.acquireWithAllocator(std.mem.Allocator)</code> can be used. This has a specific purpose: to allocate the static buffer upfront using [probably] a general purpose allocator, but for any dynamic allocation to happen with a [probably] arena allocator. This is meant for the case where an arena allocator is available which outlives the checked out buffer. In such cases, using the arena allocator for any potential dynamic allocation by the buffer will offer better performance.
[]
https://avatars.githubusercontent.com/u/10215376?v=4
zilliam
ymndoseijin/zilliam
2023-08-16T04:04:50Z
A Geometric Algebra library for Zig
main
1
28
1
28
https://api.github.com/repos/ymndoseijin/zilliam/tags
MIT
[ "3d-graphics", "clifford-algebras", "geometric-algebra", "zig", "zig-package" ]
183
false
2025-05-06T16:41:08Z
true
true
unknown
github
[ { "commit": "07fd1acfe20e05e260ede883b762c878e8724dac.tar.gz", "name": "comath", "tar_url": "https://github.com/InKryption/comath/archive/07fd1acfe20e05e260ede883b762c878e8724dac.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/InKryption/comath" } ]
zilliam Zilliam is a Geometric Algebra library that generates a SIMD optimized library for any given Cl(p,q,r) algebra. It can be used for: <ul> <li>PGA (projective geometric algebra, for which Zilliam has a special for generating all needed mask types) where you can easily construct points, lines and planes in any dimension and do projection, rotations, intersections and more between all of them under the same syntax. It has many uses for computer graphics and physics. It can also model conformal transformations using CGA.</li> <li>Modelling complex numbers, quaternions, dual numbers and many more other Clifford algebras under a single interface, generating SIMD optimized code for all of them. This makes it possible to use Zilliam for automatic differentiation, complex analysis</li> <li>Calculate Lorentz boosts and more using an STA (spacetime algebra) which also provides a very useful model for doing Electrodynamics work.</li> </ul> For all these applications, Zilliam gives you access to useful functions such as the trigonometric functions, the exponential and also useful concepts such as the Poincare dual and wedge operations. It also provides a sort of operation overloading through a <a>comath</a> interface, which allows you to evaluate complex expressions more easily and without much compile time cost. It currently has the following operations (syntax for the eval function): - a<em>b: geo - ~a: reverse - a^b: wedge - a&amp;b: regressive - </em>a: dual - a|b: inner product - #a: grade involution - a$k: grade projection - %a: undual It generates SIMD operations for any generic Clifford algebra for all these operations, and for any generic type as well: ```zig const Alg = Algebra(i32, 2, 1, 1); try std.testing.expectEqualSlices( i32, &amp;(try Alg.eval("(14<em>e1) - (21</em>e2) - (7<em>e12) - 24", .{})).val, &amp;(try Alg.eval("(2</em>e1+3<em>e2+5</em>e12) * (11<em>e1+13</em>e2+17*e12)", .{})).val, ); try std.testing.expectEqualSlices( i32, &amp;(try Alg.eval("109 + 654<em>e0 + 129</em>e1 + 127<em>e2 + 214</em>e12", .{})).val, &amp;(try Alg.eval("(23<em>e0+2</em>e1+3<em>e2+5</em>e12+7) | (31<em>e0+11</em>e1+13<em>e2+17</em>e12+19)", .{})).val, ); ``` As you can see, it also uses the amazing <a>comath</a> library to overload operations. In the case where you know the grade of the multivectors you are working with (which is most practical cases), zilliam generates types for like k-vector plus the even subalgebra and dispatches among them. ```zig const Alg = Algebra(f32, 3, 0, 1); const Blades = getBlades(Alg); const Types = Blades.Types; const Vector = Types[1]; const Bivector = Types[2]; const Trivector = Types[3]; pub fn main() !void { const BivectorBatch = Bivector.getBatchType(2); const VectorBatch = Vector.getBatchType(2); <code>for (0..Bivector.Count) |a_i| { for (0..Vector.Count) |b_i| { var a = BivectorBatch{}; var b = VectorBatch{}; a.val[a_i] = .{ 1, 2 }; b.val[b_i] = .{ 1, 2 }; var buf: [2048]u8 = undefined; // This is a Trivector, it gets properly dispatched const res = a.wedge(b); for (0..2) |i| { const r_w = res.get(i); var r_s = try a.get(i).print(&amp;buf); std.debug.print("{s} ^ ", .{r_s}); r_s = try b.get(i).print(&amp;buf); std.debug.print("{s} = ", .{r_s}); r_s = try r_w.print(&amp;buf); std.debug.print("{s}\n", .{r_s}); } std.debug.print("\n", .{}); } } </code> } // ... // 1.0000e13 ^ 1.0000e0 = 1.0000e013 // 2.0000e13 ^ 2.0000e0 = 4.0000e013 // ... ``` For more examples and a guide for using Zilliam on your project, check the <a>wiki</a>. Todo <ul> <li>Add more general utilities beyond just the PGA one and improve the calculation of functions</li> <li>Eventually, hook it up to my graphics library to start doing visualizations (maybe something on par with ganja.js)</li> </ul> References <ul> <li>Thanks to <a>klein</a> specially, who gave me the idea to generate SIMD operations and something to compare the generated code to.</li> <li>Also thanks to the people at <a>biVector.net</a> and specially their <a>/tools</a> page, whose tables and calculators helped me verifying the correctness of my own code.</li> </ul>
[]
https://avatars.githubusercontent.com/u/1461520?v=4
onnxruntime.zig
recursiveGecko/onnxruntime.zig
2023-05-28T06:15:35Z
Incomplete experimental Zig wrapper for ONNX Runtime with examples (Silero VAD, NSNet2)
master
0
27
4
27
https://api.github.com/repos/recursiveGecko/onnxruntime.zig/tags
MPL-2.0
[ "examples", "onnx", "onnxruntime", "zig", "ziglang" ]
47,116
false
2025-04-02T20:58:01Z
true
true
unknown
github
[ { "commit": "master", "name": "onnxruntime_linux_x64", "tar_url": "https://github.com/microsoft/onnxruntime/releases/download/v1.17.1/onnxruntime-linux-x64-1.17.1.tgz/archive/master.tar.gz", "type": "remote", "url": "https://github.com/microsoft/onnxruntime/releases/download/v1.17.1/onnxruntime-...
Zig wrapper for ONNX Runtime Work in progress, implementing vertical slices of ONNX Runtime API surface as they're needed. Examples Please note that examples don't have a functioning CLI interface at this point, some paths are hardcoded at the top of <code>main.zig</code>. To build or run the examples, run: ```bash Run Silero VAD cd examples/silero_vad zig build run Run NSNet2 cd examples/nsnet2 zig build run ``` Licensing <code>/src/*</code>, <code>/examples/*/src/*</code> and any other first party code - Mozilla Public License 2.0 (<code>/LICENSE.txt</code>) <code>/examples/nsnet2/data/*.onnx</code> - NSNet2 ONNX models are <a>MIT licensed by Microsoft</a>. <code>/examples/silero_vad/data/*.onnx</code> - Silero VAD ONNX models are <a>MIT licensed by Silero Team</a>. <code>/examples/*/data/*.wav</code> - Example WAV files are unlicensed. Please open a GitHub issue to request removal if you believe these files are infringing on your copyright and fall outside the scope of fair use.
[]
https://avatars.githubusercontent.com/u/49204493?v=4
cutransform
lennyerik/cutransform
2023-05-09T20:46:15Z
CUDA kernels in any language supported by LLVM
main
0
27
0
27
https://api.github.com/repos/lennyerik/cutransform/tags
MIT
[ "c", "cuda", "gpgpu", "gpu-compute", "llvm", "llvm-ir", "nvidia", "ptx", "rust", "zig" ]
53
false
2025-05-14T18:33:22Z
false
false
unknown
github
[]
cutransform Are you tired of having to write your CUDA kernel code in C++? This project aims to make it possible to compile CUDA kernels written in any language supported by LLVM without much hassle. Specifically, this is basically a transpiler from LLVM-IR to NVVM-IR. Importantly, languages like plain C, Rust and Zig are all supported. Expecially CUDA in Rust is not yet very good and <a>Rust-CUDA</a> has been stale since July 2022. Maybe we can fix that by using a different approach to the problem of CUDA codegen. <strong>This is not a CUDA runtime API wrapper! You cannot run the kernels with this project alone!</strong> If you're just looking for a simple way to write CUDA in Rust though, you're in luck. <a>cust</a> is a really good wrapper around the CUDA API. How it works In order to compile a kernel in any language with an LLVM frontend, we <ul> <li>Invoke the standard compiler for the language and tell it to output LLVM bitcode for the nvptx64-nvidia-cuda target</li> <li>Pass the generated bitcode to the code transformer (cutransform)</li> <li>The transformer will parse the bitcode and add required attributes and functions and structs</li> <li>It will output this modified version of the bitcode</li> <li>Finally the bitcode can simply be passed through the llvm-bitcode compiler, llc to generate the PTX assembly</li> <li>(Optional) Additionally can now choose to assemble the PTX to a SASS (cubin) program for your specific graphics card using Nvidia's proprietary ptxas assembler</li> </ul> Setup You should already have <ul> <li>clang</li> <li>llvm</li> <li>cuda</li> </ul> Then compile the cutransform binary: <code>cd cutransform cargo build --release </code> If the build fails with an error message from the <code>llvm-sys</code> crate, you likely have a build of LLVM without the static libraries. This is the default for newer LLVM binary distributions. To build with a dynamically linked LLVM, run: <code>cargo build --release --features dynamic-llvm </code> instead. Rust example usage First, make sure you have the nvptx Rust target installed: <code>rustup target add nvptx64-nvidia-cuda </code> Here is an example Rust kernel: ```rust ![no_std] extern "C" { fn threadIdxX() -&gt; u32; } [no_mangle] pub extern "C" fn kernel(arr: <em>mut u32) { unsafe { let idx = threadIdxX() as usize; </em>arr.add(idx) = 123; } } ``` <strong>Please note that all kernel functions should have a name starting with the word "kernel". Otherwise they won't be exported.</strong> To compile the Rust kernel to LLVM bitcode, run: <code>rustc -O -C opt-level=3 -o kernel.bc --emit llvm-bc --target nvptx64-nvidia-cuda -C target-cpu=sm_86 -C target-feature=+ptx75 --crate-type lib kernel.rs </code> You can change <code>sm_86</code> flag to the minimum supported compute capability of your kernel (8.6 is the newest supported in clang and it's mostly for 30-series cards and onwards). Refer to <a>this Wikipedia page</a> for a list of cards and their supported compute capabilities. Now, run cutransform on the llvm bitcode <code>cutransform/target/release/cutransform kernel.bc </code> Finally, compile the new bitcode to PTX: <code>llc -O3 -mcpu=sm_86 -mattr=+ptx75 kernel.bc </code> Now you can also choose to assemble the PTX for your card: <code>ptxas --allow-expensive-optimizations true -o kernel.cubin --gpu-name sm_89 kernel.s </code> Where you can again change <code>sm_89</code> to the compute capability of your card. Compute capability 8.9 is for 40-series cards. For a complete and integrated example, see the <code>rust-example</code> crate included in this repo. C example usage Here is an example C kernel: ```c extern int threadIdxX(void); void kernel(int *arr) { arr[threadIdxX()] = 123; } ``` <strong>Please note that all kernel functions should have a name starting with the word "kernel". Otherwise they won't be exported.</strong> To compile the C kernel to LLVM bitcode, run: <code>clang -cc1 -O3 -triple=nvptx64-nvidia-cuda -target-cpu sm_86 -target-feature +ptx75 -emit-llvm-bc -o kernel.bc kernel.c </code> Now, run cutransform on the llvm bitcode <code>cutransform/target/release/cutransform kernel.bc </code> Finally, compile the new bitcode to PTX: <code>llc -O3 -mcpu=sm_86 -mattr=+ptx75 kernel.bc </code> Now you can also choose to assemble the PTX for your card: <code>ptxas --allow-expensive-optimizations true -o kernel.cubin --gpu-name sm_89 kernel.s </code> Where you can again change <code>sm_89</code> to the compute capability of your card. Compute capability 8.9 is for 40-series cards. For a complete and integrated example, see the <code>c-example</code> folder included in this repo. Zig example usage Here is an example Zig kernel: ```zig extern fn threadIdxX() i32; export fn kernel(arr: [*]u32) callconv(.C) void { arr[@intCast(usize, threadIdxX())] = 123; } // Override the default entrypoint pub fn _start() callconv(.Naked) void {} ``` <strong>Please note that all kernel functions should have a name starting with the word "kernel". Otherwise they won't be exported.</strong> To compile the Zig kernel to LLVM bitcode, run: <code>zig build-obj -O ReleaseSmall -target nvptx64-cuda -mcpu sm_86+ptx75 -fno-emit-asm -femit-llvm-bc=kernel.bc kernel.zig </code> Now, run cutransform on the llvm bitcode <code>cutransform/target/release/cutransform kernel.bc </code> Finally, compile the new bitcode to PTX: <code>llc -O3 -mcpu=sm_86 -mattr=+ptx75 kernel.bc </code> Now you can also choose to assemble the PTX for your card: <code>ptxas --allow-expensive-optimizations true -o kernel.cubin --gpu-name sm_89 kernel.s </code> Where you can again change <code>sm_89</code> to the compute capability of your card. Compute capability 8.9 is for 40-series cards. For a complete and integrated example, see the <code>zig-example</code> folder included in this repo.
[]
https://avatars.githubusercontent.com/u/6811788?v=4
ztrait
permutationlock/ztrait
2023-10-03T23:18:53Z
A simple version of Rust style type traits in Zig
main
0
27
0
27
https://api.github.com/repos/permutationlock/ztrait/tags
MIT
[ "generics", "zig" ]
126
false
2025-04-23T05:45:51Z
true
true
unknown
github
[]
Zig Type Traits <em>Disclaimer: This was an exploratory project that I no longer believe should be used for practical purposes. Everything I leared in this project was refined into the <a>zimpl library</a> which I will continue to maintain.</em> An attempt at implementing something along the lines of Rust type traits in Zig. Using this library you can define traits and compile-time verify that types implement them. I wrote <a>an article</a> about working with <code>anytype</code> which reflects on developing this library. Related Links Below are some related projects and Zig proposal threads that I read while implementing the library. <ul> <li><a>Zig Compile-Time-Contracts</a></li> <li>Zig issues: <a>#1268</a>, <a>#1669</a>, <a>#6615</a>, <a>#17198</a></li> </ul> I don't have any strong position on proposed changes to the Zig language regarding generics, and I respect the Zig team's reasoning for keeping the type system simple. Basic use A trait is simply a comptime function taking a type and returning a struct type containing only declarations. Each declaration of the returned struct is a required declaration that a type must have if it implements the trait. Below is a trait that requires implementing types to define an integer sub-type <code>Count</code>, define an <code>init</code> function, and define member functions <code>increment</code> and <code>read</code>. <code>``Zig pub fn Incrementable(comptime Type: type) type { return struct { // below is the same as</code>pub const Count = type` except that during // trait verification it requires that '@typeInfo(Type.Count) == .Int' pub const Count = hasTypeId(.Int); <code> pub const init = fn () Type; pub const increment = fn (*Type) void; pub const read = fn (*const Type) Type.Count; }; </code> } ``` A type that implements the above <code>Incrementable</code> trait is provided below. ```Zig const MyCounter = struct { pub const Count = u32; <code>count: Count, pub fn init() @This() { return .{ .count = 0 }; } pub fn increment(self: *@This()) void { self.count += 1; } pub fn read(self: *const @This()) Count { return self.count; } </code> }; ``` To require that a generic type parameter implements a given trait you simply need to add a comptime verification line at the start of your function. ```Zig pub fn countToTen(comptime Counter: type) void { comptime where(Counter, implements(Incrementable)); <code>var counter = Counter.init(); while (counter.read() &lt; 10) { counter.increment(); } </code> } ``` <strong>Note:</strong> If we don't specify that trait verification is comptime then verification might be evaluated later during compilation. This results in regular duck-typing errors rather than trait implementation errors. If we define a type that fails to implement the <code>Incrementable</code> trait and pass it to <code>countToTen</code>, then the call to <code>where</code> will produce a compile error. ```Zig const MyCounterMissingDecl = struct { pub const Count = u32; <code>count: Count, pub fn init() @This() { return .{ .count = 0 }; } pub fn read(self: *const @This()) Count { return self.count; } </code> }; ``` <code>Shell trait.zig:12:13: error: trait 'count.Incrementable(count.MyCounterMissingDecl)' failed: missing decl 'increment'</code> Combining traits Multiple traits can be type checked with a single call. ```Zig pub fn HasDimensions(comptime _: type) type { return struct { pub const width = comptime_int; pub const height = comptime_int; }; } pub fn computeAreaAndCount(comptime T: type) void { comptime where(T, implements(.{ Incrementable, HasDimensions })); <code>var counter = T.init(); while (counter.read() &lt; T.width * T.height) { counter.increment(); } </code> } ``` Constraining sub-types Traits can require types to declare sub-types that implement traits. ```Zig pub fn HasIncrementable(comptime _: type) type { return struct { pub const Counter = implements(Incrementable); }; } ``` ```Zig pub fn useHolderToCountToTen(comptime T: type) void { comptime where(T, implements(HasIncrementable)); <code>var counter = T.Counter.init(); while (counter.read() &lt; 10) { counter.increment(); } </code> } ``` ```Zig pub const CounterHolder = struct { pub const Counter = MyCounter; }; pub const InvalidCounterHolder = struct { pub const Counter = MyCounterMissingDecl; }; ``` <code>Shell trait.zig:12:13: error: trait 'count.HasIncrementable(count.InvalidCounterHolder)' failed: decl 'Counter': trait 'count.Incrementable(count.MyCounterMissingDecl)' failed: missing decl 'increment'</code> Declaring that a type implements a trait Alongside enforcing trait implementation in generic functions, types themselves can declare that they implement a given trait. ```Zig const MyCounter = struct { comptime { where(@This(), implements(Incrementable)); } <code>// ... </code> }; ``` Then with <code>testing.refAllDecls</code> you can run <code>zig test</code> to automatically verify that these traits are implemented. <code>Zig test { std.testing.refAllDecls(@This); }</code> Credit to "NewbLuck" on the Zig Discord for pointing out this nice pattern. Pointer types Often one will want to pass a pointer type to a function taking <code>anytype</code>, and it turns out that it is still quite simple to do trait checking. Single item pointers allow automatic dereferencing in Zig, e.g. <code>ptr.decl</code> is <code>ptr.*.decl</code>, so it makes sense to define that a pointer type <code>*T</code> implements a trait if <code>T</code> implements the trait. To accomplish this, types are passed through an <code>Unwrap</code> function before trait checking occurs. <code>Zig pub fn Unwrap(comptime Type: type) type { return switch (@typeInfo(Type)) { .Pointer =&gt; PointerChild(Type), else =&gt; Type, }; }</code> Therefore the following function will work just fine with pointers to types that implement <code>Incrementable</code>. ```Zig pub fn countToTen(counter: anytype) void { comptime where(@TypeOf(counter), implements(Incrementable)); <code>while (counter.read() &lt; 10) { counter.increment(); } </code> } ``` Slice types For slice parameters we usually want the caller to be able to pass both <code>*[_]T</code> and <code>[]T</code>. The library provides the <code>SliceChild</code> helper function to verify that a type can coerce to a slice andt extract its child type. ```Zig pub fn incrementAll(list: anytype) void { comptime where(SliceChild(@TypeOf(list)), implements(Incrementable)); <code>for (list) |*counter| { counter.increment(); } </code> } ``` The above function works directly on parameters that can coerce to a slice, but if required we can force coercion to a slice type as shown below. ```Zig pub fn incrementAll(list: anytype) void { comptime where(SliceChild(@TypeOf(list)), implements(Incrementable)); <code>const slice: []SliceChild(@TypeOf(list)) = list; for (slice) |*counter| { counter.increment(); } </code> } ``` Interfaces: restricting access to declarations Using <code>where</code> and <code>implements</code> we can require that types have declaration satisfying trait requirements. We cannot, however, prevent code from using declarations beyond the scope of the checked traits. Thus it is on the developer to keep traits up to date with how types are actually used. Constructing interfaces within a function The <code>interface</code> function provides a method to formally restrict traits to be both necessary and sufficient requirements for types. Calling <code>interface(Type, Trait)</code> will construct a comptime instance of a generated struct type that contains a field for each declaration of <code>Type</code> that has a matching declaration in <code>Trait</code>. The fields of this interface struct should then be used in place of the declarations of <code>Type</code>. ```Zig pub fn countToTen(counter: anytype) void { const ifc = interface(@TypeOf(counter), Incrementable); <code>while (ifc.read(counter) &lt; 10) { ifc.increment(counter); } </code> } ``` Interface construction performs the same type checking as <code>where</code>. Flexible interface parameters The type returned by <code>interface(U, T)</code> is <code>Interface(U, T)</code>, a struct type containing one field for each declaration of <code>T</code> with default value equal to the corresponding declaration of <code>U</code> (if it exists and has the correct type). A more flexible way to work with interfaces is to take an <code>Interface</code> struct as an explicit <code>comptime</code> parameter. <code>Zig pub fn countToTen(counter: anytype, ifc: Interface(@TypeOf(Counter), Incrementable)) void { while (ifc.read(counter) &lt; 10) { ifc.increment(counter); } }</code> This allows the caller to override declarations, or provide a custom interface for a type that doesn't have the required declarations. Unfortunately, this style of interfaces does not allow trait declarations to depend on one another. A restricted version of the <code>Incrementable</code> interface that will play well with the interface parameter convention is provided below. <code>Zig pub fn Incrementable(comptime Type: type) type { return struct { pub const increment = fn (*Type) void; pub const read = fn (*const Type) usize; }; }</code> An example of what is possible with this convention is shown below. ```Zig const USize = struct { pub fn increment(i: <em>usize) void { i.</em> += 1; } <code>pub fn read(i: *const usize) usize { return i.*; } </code> }; var my_count: usize = 0; countToTen(&amp;my_count, .{ .increment = USize.increment, .read = USize.read }); ``` Extending the library to support other use cases Users can define their own helper functions as needed by wrapping and expanding the trait module. ```Zig // mytrait.zig // expose all declaraions from the standard trait module const zt = @import("ztrait"); pub usingnamespace zt; // define your own convenience functions pub fn BackingInteger(comptime Type: type) type { comptime zt.where(Type, zt.isPackedContainer()); <code>return switch (@typeInfo(Type)) { inline .Struct, .Union =&gt; |info| info.backing_integer.?, else =&gt; unreachable, }; </code> } ``` Returns syntax: traits in function definitions Sometimes it can be useful to have type signatures directly in function definitions. Zig currently does not support this, but there is a hacky workaround using the fact that Zig can evaluate a <code>comptime</code> function in the return type location. <code>Zig pub fn sumIntSlice(comptime I: type, list: []const I) Returns(I, .{ where(I, hasTypeId(.Int)), }) { var count: I = 0; for (list) |elem| { count += elem; } return count; }</code> The first parameter of <code>Returns</code> is the actual return type of the function, while the second is an unreferenced <code>anytype</code> parameter. <code>Zig pub fn Returns(comptime ReturnType: type, comptime _: anytype) type { return ReturnType; }</code> <strong>Warning:</strong> Error messages can be less helpful when using <code>Returns</code> because the compile error occurs while a function signature is being generated. This can result in the line number of the original call not be reported unless building with <code>-freference-trace</code> (and even then the call site may still be obscured in some degenerate cases).
[]
https://avatars.githubusercontent.com/u/135145066?v=4
dotenv
dying-will-bullet/dotenv
2023-06-05T04:40:06Z
Loads environment variables from .env for Zig projects.
master
1
27
8
27
https://api.github.com/repos/dying-will-bullet/dotenv/tags
MIT
[ "dotenv", "dotenv-loader", "environment-variables", "zig", "ziglang" ]
47
false
2025-04-26T10:28:01Z
true
true
unknown
github
[]
dotenv 🌴 <a></a> <a></a> dotenv is a library that loads environment variables from a <code>.env</code> file into <code>std.os.environ</code>. Storing configuration in the environment separate from code is based on The <a>Twelve-Factor</a> App methodology. This library is a Zig language port of <a>nodejs dotenv</a>. Test with Zig 0.13.0 Quick Start Automatically find the <code>.env</code> file and load the variables into the process environment with just one line. ```zig const std = @import("std"); const dotenv = @import("dotenv"); pub fn main() !void { const allocator = std.heap.page_allocator; <code>try dotenv.load(allocator, .{}); </code> } ``` By default, it will search for a file named <code>.env</code> in the working directory and its parent directories recursively. Of course, you can specify a path if desired. <code>zig pub fn main() !void { try dotenv.loadFrom(allocator, "/app/.env", .{}); }</code> <strong>Since writing to <code>std.os.environ</code> requires a C <code>setenv</code> call, linking with C is necessary.</strong> If you only want to read and parse the contents of the <code>.env</code> file, you can try the following. ```zig pub fn main() !void { var envs = try dotenv.getDataFrom(allocator, ".env"); <code>var it = envs.iterator(); while (it.next()) |*entry| { std.debug.print( "{s}={s}\n", .{ entry.key_ptr.*, entry.value_ptr.*.? }, ); } </code> } ``` This does not require linking with a C library. The caller owns the memory, so you need to free both the key and value in the hashmap. <code>.env</code> Syntax <code>NAME_1="VALUE_1" NAME_2='VALUE_2' NAME_3=VALUE_3</code> Multiline values The value of a variable can span multiple lines(quotes are required). <code>PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- ABCD... -----END RSA PRIVATE KEY-----"</code> Comments Comments start with a <code>#</code>. ``` This is a comment NAME="VALUE" # comment ``` Variable Expansion You can reference a variable using <code>${}</code>, and the variable should be defined earlier. ``` HO="/home" ME="/koyori" HOME="${HO}${ME}" # equal to HOME=/home/koyori ``` LICENSE MIT License Copyright (c) 2023-2024, Hanaasagi
[ "https://github.com/algoflows/zig-s3" ]
https://avatars.githubusercontent.com/u/87281783?v=4
vzcc
malisipi/vzcc
2023-04-11T18:36:32Z
Zig CC for V
main
0
27
0
27
https://api.github.com/repos/malisipi/vzcc/tags
MPL-2.0
[ "cross-c", "vlang", "zig", "zigcc" ]
9
false
2025-01-04T17:58:40Z
false
false
unknown
github
[]
Zig CC for V <blockquote> A cross-compiler for V </blockquote> For Linux <ol> <li> Install V and Zig </li> <li> Install this application <code>bash v install malisipi.vzcc</code> or <code>bash git clone https://github.com/malisipi/vzcc mkdir ~/.vmodules/malisipi/ mv vzcc ~/.vmodules/malisipi/vzcc</code> </li> <li> Compile this application <code>bash v ~/.vmodules/malisipi/vzcc</code> </li> <li> Allow to run &amp; Symlink zig_cc file <code>bash sudo chmod +x ~/.vmodules/malisipi/vzcc/src/zig_cc sudo ln -sr ~/.vmodules/malisipi/vzcc/src/zig_cc /bin/zig_cc</code> </li> <li> Symlink this application (Optional) <code>bash sudo ln -sr ~/.vmodules/malisipi/vzcc/vzcc /bin/vzcc</code> </li> <li> You're ready to go </li> </ol> How To Use? ```basg vzcc [input_file] [output_file] ===&gt; a.v a.out vzcc [input_file] [target_os] [output_file] ===&gt; a.v windows a.exe vzcc [input_file] [target_arch] [target_os] [output_file] ===&gt; a.v x86_64 windows a.exe vzcc [input_file] [target_arch] [target_os] [output_file] [target_flags] ===&gt; a.v x86_64 windows a.exe -gnu [target_arch]: If undefined, your os arch will be used as target [target_os]: If undefined, your os will be used as target [target_flags]: "" is default ```
[]
https://avatars.githubusercontent.com/u/129234716?v=4
beachdemo.zig
beachglasslabs/beachdemo.zig
2023-05-14T06:35:58Z
Netflix clone in Zig, AlpineJS, and HtmX.
master
0
26
4
26
https://api.github.com/repos/beachglasslabs/beachdemo.zig/tags
-
[ "alpinejs", "htmx", "zig" ]
2,377
false
2025-05-15T07:31:15Z
true
true
unknown
github
[ { "commit": "refs", "name": "zap", "tar_url": "https://github.com/zigzap/zap/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/zigzap/zap" } ]
beachdemo.zig - netflix clone in This is meant to be a technical exploration of various technologies to be used in our actual decentralized video streaming app. This particular project is written in ZAX (Zig/Zap Alpinejs htmX :stuck_out_tongue_winking_eye:): * This is the rewrite of an earlier <a>rewrite</a> written in <a>Juila</a>: * The original UI is based on a great video tutorial I found on <a>Youtube</a> and you can find my own <a>nextjs</a> version <a>here</a>. * I rewrote the UI to be based on <a>HTMX</a> and <a>Alpinejs</a> instead of the original <a>next.js</a>. * The backend is completely rewritten in <a>zig</a>. * Sepcial thanks to <a>Rene</a> for <a>zap</a> and all the help along the way. * The users and sessions are ephemeral to remove the dependency on Mongodb Atlas in the <a>original</a> version. To test it out: 1. <code>git clone git@github.com:beachglasslabs/beachdemo.zig.git</code> 2. <code>npm install</code> to install npm packages 3. <code>cp env.oauth.sample.json env.oauth.json</code> and then optionally fill out the oauth2 information from <a>github</a> and <a>google</a> 4. <code>npm run dev</code> to start the server 5. go to <a>http://localhost:3000</a> on your browser
[]
https://avatars.githubusercontent.com/u/1160419?v=4
bobby-carrot
TheWaWaR/bobby-carrot
2023-07-06T18:32:41Z
Game Bobby Carrot in Rust/Haxe/Zig
master
0
25
2
25
https://api.github.com/repos/TheWaWaR/bobby-carrot/tags
-
[ "clone", "game", "haxe", "heaps", "rust", "zig" ]
1,222
false
2025-05-02T08:01:45Z
false
false
unknown
github
[]
A Bobby Carrot Game Clone Written in: * Rust (<a>rust-sdl2</a>) * Haxe (<a>heaps.io</a>) * Zig (:sparkles: <a>jok</a>) The Rust version is the first try, tested on Linux/MacOS. The Haxe version is probably the most portable version, tested on WebGL/MacOS(with HashLink) The Zig version is my favorite, since Zig is fun to write and jok is a nice game engine, tested on Linux/MacOS Screenshot
[]
https://avatars.githubusercontent.com/u/206480?v=4
validate.zig
karlseguin/validate.zig
2023-04-17T10:31:47Z
A validation framework for Zig
master
0
25
1
25
https://api.github.com/repos/karlseguin/validate.zig/tags
MIT
[ "validation-library", "zig", "zig-library" ]
173
false
2025-04-30T05:00:11Z
true
true
unknown
github
[ { "commit": "59d7e8a5551926f510d52ce68ab83c5a5fae674e.tar.gz", "name": "typed", "tar_url": "https://github.com/karlseguin/typed.zig/archive/59d7e8a5551926f510d52ce68ab83c5a5fae674e.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/karlseguin/typed.zig" } ]
An data validator for Zig This is a work in progress and fairly opinionated. It's currently focused around validating JSON data. It supports nested objects and arrays, and attempts to generate validation messages that are both user-friendly (i.e. can be displayed to users as-is) and developer-friendly (e.g. can be customized as needed). Quick Example The first step is to create "validators" using a <code>Builder</code>: ```zig const Builder = @import("validate").Builder; // If we want to validate a "movie" that looks like: // {"title": "A Movie", "year": 2000, "score": 8.4, "tags": ["drama", "sci-fi"]} // First, we create a new builder. In more advanced cases, we can pass application-specific data // into our validation (so that we can do more advanced app-specific logic). In this example, we // won't use a state, so our builder takes a state type of <code>void</code>: var builder = try validate.Builder(void).init(allocator); // Validators are often long lived (e.g. the entire lifetime of the program), so deinit'ing the builder // here might not be what you want. // defer builder.deinit(allocator); // Next we use our builder to create a validator for each of the individual fields: var year_validator = builder.int(u16, .{.min = 1900, .max = 2050, .required = true}); var title_validator = builder.string(.{.min = 2, .max = 100, .required = true}); var score_validator = builder.float(f64, .{.min = 0, .max = 10}); var tag_validator = builder.string(.{.choices = &amp;.{"action", "sci-fi", "drama"}}); // An array validator is like any other validator, except the first parameter is an optional // validator to apply to each element in the array. var tagsValidator = builder.array(&amp;tagValidator, .{.max = 5}); // An object validate is like any other validator, except the first parameter is a list of // fields, each field containing the input key and the validator: const movieValidator = builder.object(&amp;.{ builder.field("year", year_validator), builder.field("title", title_Validator), builder.field("score", score_validator), builder.field("tags", tags_validator), }, .{}); ``` Validators are thread-safe. With validators defined, we can validate data. Validation happens (1) on an input, (2) using a validator built with a Builder and (3) with a validation context. The context collects errors and maintains various internal state (e.g. when validating values in an array, it tracks the array index so that a more meaningful error message can be generated). A context is not thread safe. ```zig const Context = @import("validate").Context; // validate.zig supports arbitrary application state, hence Context is a generic (and takes a type) and the 3rd parameter to init is the state. We'll cover this later. For now we use void and a void state of {}: var context = try validate.Context(void).init(allocator, .{.max_errors = 10, .max_nesting = 4}, {}); defer context.deinit(); const jsonData = "{\"year\": \"nope\", \"score\": 94.3, \"tags\": [\"scifi\"]}"; const input = try movieValidator.validateJsonS(body, &amp;context); if (!validator.isValid()) { try std.json.stringify(validator.errors(), .{.emit_null_optional_fields = false}, SOME_WRITER); return; } ``` // On success, validateJsonS returns a thin wrapper around <code>typed.Value</code> // which lets us get values: const title = movie.string("title").? // ... ``` The above sample outputs the validation errors as JSON to stdout. Given the <code>jsonData</code> in the snippet, the output would be: <code>json [ {"field": "year" ,"code": 4, "err": "must be an int"}, {"field": "title" ,"code": 1, "err": "is required"}, {"field": "score", "code": 14, "err": "cannot be greater than 10", "data": {"max": 1.0e+01}}, {"field": "tags.0", "code": 10, "err": "must be one of: action, sci-fi, drama", "data": {"valid": ["action", "sci-fi", "drama"]}} ]</code> Concepts Builder The <code>validate.Builder</code> is used to create validators. The full Builder API is described later. Validators are optimized for long-term / repeated use, so the Builder does more setup than might initially be obvious. Validators don't require a huge amount of allocations, but some of the allocations could be considered subtle. For example, if a "name" validator gets placed in a "user" object, a "user.name" value is created as part of the "Builder" phase. Doing this upfront once mean that the "user.name" field is ready to be used (and re-used) when validation errors happen. All this is to say that the Builder's <code>init</code> takes the provided <code>std.mem.Allocator</code> and creates and uses an ArenaAllocator. Individual validators do not have a <code>deinit</code> function. Only the <code>Builder</code> itself does. In many applications, a single Builder will be created on startup and can be freed on shutdown. Context When it comes time to actually validate data, a <code>validate.Context</code> is created. The context collects errors and the internal state necessary for validation as well as for generating meaningful errors. In the simplest case, a context is created (or taken from a validate.Pool), and passed to validator. However, in more advanced cases, particularly when a custom function is given to a validator, applications might interact with the context directly, either to access parts of the input and/or add custom validation errors. When validating, this library attempts to minimize memory allocations as much as possible. In some cases, this is not possible. Specifically, when an error is added for an array value, the field name is dynamic, e.g, "user.favorites.4". State While this library has common validation rules for things like string length, min and max values, array size, etc., it also accepts custom validation functions. Sometimes these functions are simple and stateless. In other cases it can be desirable to have some application-specific data. For example, in a multi-tenancy application, data validation might depend on tenant-specific configuration. The <code>Builder</code> and <code>Context</code> types explored above are generic functions which return a <code>Builder(T)</code> and <code>Context(T)</code>. When the <code>validateJsonS</code> function is called, a <code>state T</code> is provided, which is then passed to custom validation functions: <code>``zig // Our builder will build validators that expect a</code><em>Custom<code>instance // (</code>Custom` is a made-up application type) var builder = try validate.Builder(</em>Custom).init(allocator); // Our nameValidator specifies a custom validation function, <code>validateName</code> var nameValidator = builder.string({.required = true, .function = validateName}) ... fn validateName(value: []const u8, context: <em>Context(</em>Customer)) !?[]const u8 { const customer = context.state; // can do custom validation based on the customer } ``` We then specify the same <code>*Customer</code> type when creating our Context and provide the instance: <code>zig const customer: *Customer = // TODO: the current customer var context = try Context(*Customer).init(allocator, .{}, customer);</code> Errors Generated errors are meant to be both user-friendly and developer-friendly. At a minimum, every error has a <code>code</code> and <code>err</code> field. <code>err</code> is a user-safe English string describing the error. It's "user-safe" because the errors are still generic, such as "must have no more than 10 items" as opposed to a more app-specific "cannot pick more than 10 addons". The <code>code</code> is an integer that is unique to each type of error. For example, a <code>code=1</code> means that a required field was missing. Most errors will also contain a <code>field</code> string. This is the full field name, including nesting and zero-based array indexes, such as <code>user.favorite.2.id</code>. This field is optional - sometimes validation errors don't belong to a specific field. Some errors also have a <code>data</code> object. The inclusion and structure of the <code>data</code> object is specific to the <code>code</code>. For example, a error with <code>code=1</code> (required) always has a null <code>data</code> field (or no data field if the errors are serialized with the <code>emit_null_optional_fields = true</code> option). An error with <code>code=8</code> (string min length) always has a <code>data: {min: N}</code>. Between the <code>code</code>, <code>data</code> and <code>field</code> fields, developers should be able to programmatically consume and customize the errors. Typed Validation of data happens by calling <code>validateJsonS</code> on an <code>object</code> validator. This function returns a <code>typed.Value</code> instance which is a thin wrapper around <code>typed.Value</code> (see <a>typed.zig</a>). The goal of <code>typed.Value</code> is to provide a user-friendly API to extract the input data safely. The returned <code>Typed</code> object and its data are only valid as long as the <code>validate.Context</code> that was passed into <code>validateJson</code> is. Custom Functions Most validators accept a custom function. This custom function will only be called if all other validators pass. Importantly, if a value is <code>null</code> and <code>required = false</code>, the custom validator <strong>is</strong> called with <code>null</code>. The signature of these functions is: <code>zig *const fn(value: ?T, context: *Context(S)) !?T</code> Where <code>T</code> is the type of value being validated. For a bool validator, <code>T</code> will be <code>bool</code>, for a string validator <code>T</code> will be <code>[]const u8</code>. There are a few important things to note about custom validators. First, as already mentioned, if the value is not required and is null, the custom validator <strong>is</strong> called with null. Thus, the type of <code>value</code> is <code>?T</code>. Second, custom validators can return a new value to replace the existing one, hence the return type of <code>?T</code>. Returning <code>null</code> will maintain the existing value. Finally, the provided <code>context</code> is useful for both simple and complex cases. At the very least, you'll need to call <code>context.add(...)</code> to add errors from your validator. API Builder The builder is used to create and own validators. When <code>deinit</code> is called on the builder, all of the validators created from it are no longer valid. ```zig var builder = try validate.Builder(void).init(allocator); // The builder must live as long as any validator it creates. // defer builder.deinit() ``` Int Validator An int validator is created via the <code>builder.int</code> function. This function takes an integer type and configuration structure. The full possible configuration, with default values, is show below: ```zig const age_validator = builder.int(.{ // whether the value is required or not .required = false, <code>// the minimum allowed value (inclusive of min), null == no limit .min = null, // ?T // the maximum allowed value (inclusive of max), null == no limit .max = null, // ?T // when true, will accept a string input and attempt to convert it to an integer .parse = false, // a custom validation function that will receive the value to validate // along with a validation.Context. function: ?*const fn(value: ?T, context: *Context(S)) anyerror!?T = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.int</code> can panic. <code>builder.tryInt</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. Float Validator A float validator is created via the <code>builder.float</code> function. This function takes a float type and configuration structure. The full possible configuration, with default values, is show below: ```zig const rating_validator = builder.float(.{ // whether the value is required or not .required = false, <code>// the minimum allowed value (inclusive of min), null == no limit .min = null, // ?T // the maximum allowed value (inclusive of max), null == no limit .max = null, // ?T // when false, integers will be accepted and converted to an f64 // when true, if an integer is given, validation will fail .strict = false, // when true, will accept a string input and attempt to convert it to a float .parse = false, // a custom validation function that will receive the value to validate // along with a validation.Context. function: ?*const fn(value: ?T, context: *Context(S)) anyerror!?T = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.float</code> can panic. <code>builder.tryFloat</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. Bool Validator A bool validator is created via the <code>builder.bool</code> function. This function takes a configuration structure. The full possible configuration, with default values, is show below: ```zig const enabled_validator = builder.boolean(.{ // whether the value is required or not .required = false, <code>// when true, will accept a string input and attempt to convert it to a boolean // "1", "t", "true" == true (string comparison is case insensitive) // "0", "f", "false" == false (string comparison is case insensitive) .parse = false, // a custom validation function that will receive the value to validate // along with a validation.Context. function: ?*const fn(value: ?bool, context: *Context(S)) anyerror!?bool = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.bool</code> can panic. <code>builder.tryBool</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. String Validator A string validator is created via the <code>builder.string</code> function. This function takes a configuration structure. The full possible configuration, with default values, is show below: ```zig const name_validator = builder.string(.{ // whether the value is required or not .required = false, <code>// the minimum length (inclusive of min), null == no limit .min = null, // usize // the maximum length(inclusive of max), null == no limit .max = null, // usize // a list of valid choices, this list is case sensitive .choices = null, // []const []const u8 // a regular expression pattern, currently using POSIX regex, but likely to change in the future .pattern = null // []const u8 // a custom validation function that will receive the value to validate // along with a validation.Context. function: ?*const fn(value: ?[]const u8, context: *Context(S)) anyerror!?[]const u8 = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.string</code> can panic. <code>builder.tryString</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. UUID Validator A UUID validator is created via the <code>builder.uuid</code> function. This function takes a configuration structure. The full possible configuration, with default values, is show below: ```zig const name_validator = builder.string(.{ // whether the value is required or not .required = false, <code>// a custom validation function that will receive the value to validate // along with a validation.Context. function: ?*const fn(value: ?[]const u8, context: *Context(S)) anyerror!?[]const u8 = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.uuid</code> can panic. <code>builder.tryUuid</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. Any Validator A type-less validator is created via <code>builder.any</code> function. Unlike all other validators, this validator does not validate the type of the value. This validator is useful when the type of a field is only known at runtime and a custom validation function is used. This function takes a configuration structure. The full possible configuration, with default values, is show below: ```zig const default_validator = builder.any(.{ // whether the value is required or not .required = false, <code>// a custom validation function that will receive the value to validate // along with a validation.Context. function: ?*const fn(value: ?[]typed.Value, context: *Context(S)) anyerror!?typed.Value = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.any</code> can panic. <code>builder.tryAny</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. Array Validator An array validator is created via the <code>builder.array</code> function. The array validator can validate the array itself (e.g. it's length) as well as each item within in. As such, this function takes both an optional validator to apply to the array values, as well as a configuration structure. The full possible configuration, with default values, is show below: ```zig // name_validator will be applies to each value in the array. // null can also be provided, in which case array items will not be validated // (but the array itself will still be validated based on the provided configuration) const names_validator = builder.array(name_validator, .{ // whether the value is required or not .required = false, <code>// the minimum length (inclusive of min), null == no limit .min = null, // usize // the maximum length(inclusive of max), null == no limit .max = null, // usize // a custom validation function that will receive the value to validate // along with a validation.Context. .function = ?*const fn(value: ?typed.Array, context: *Context(S)) anyerror!?typed.Array = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.array</code> can panic. <code>builder.tryArray</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. Typically, this validator is invoked as part of an object validator. However, it is possible to call <code>validateJsonValue</code> directly on this validator by providing a <code>std.typed.Value</code> and a validation Context. Object Validator The object validator is similar but also different from the others. Like the other validators, it's created via the <code>builder.object</code> function. And, like the other validators, it takes a configuration object that defines how the object value itself should be validated. However, unlike the other validators (but a little like the array validator), <code>builder.object</code> takes a <code>name =&gt; validator</code> map which defines the validator to use for each value in the object. ```zig var user_validator = builder.object(name_validator, &amp;.{ builder.field("age", age_validator), builder.field("name", name_validtor), }, .{ // whether the value is required or not .required = false, <code>// a custom validation function that will receive the value to validate // along with a validation.Context function: ?*const fn(value: ?typed.Map, context: *Context(S)) anyerror!?typed.Map = null, </code> }); ``` In rare cases (e.g. OOM) <code>builder.object</code> can panic. <code>builder.tryObject</code> function can be used to return an ErrorSet which can be caught/unwrapped/propagated. One created, either <code>validateJsonS</code> or <code>validateJsonV</code> are used to kick-off validation. <code>validateJsonS</code> takes a <code>[]const u8</code>. <code>validateJsonV</code> takes an <code>?std.typed.Value</code>. These return a <code>typed.Value</code> (see <a>typed.zig</a> on sucess. On error, the context's <code>isValid()</code> will return false, and the errors can be fetched using <code>context.errors()</code>. Dynamic Required Oftentimes you'll need validators which only differ in their <code>required</code> configuration. For example, an HTTP API might require a <code>name</code> on create, but leave the name as <code>optional</code> on update. For <code>int</code>, <code>float</code>, <code>bool</code>, <code>string</code> and <code>any</code> validators, <code>setRequired(bool, builder)</code> can be called to clone the original validator with the specified <code>required</code>. For example, our above <code>user_validator</code> uses a non-required <code>name_validator</code>. We could change this to required by doing: <code>zig var user_validator = builder.object(name_validator, &amp;.{ builder.field("age", age_validator), builder.field("name", name_validator.setRequired(true, builder)), }, .{});</code> Context In simple cases, the context is an after thought: it is created and passed to <code>validateJsonS</code> or <code>validateJsonV</code>. Creation To create a context with no custom state, use: <code>zig var context = validate.Context(void).init(allocator, .{ .max_errors = 20, .max_nesting = 10, }, {});</code> To create a context with custom state, say a <code>*Customer</code>, use: <code>zig var context = validate.Context(*Customer).init(allocator, .{ .max_errors = 20, .max_nesting = 10, }, the_customer);</code> <code>max_errors</code> limits how many errors will be collected. Additional errors will be silently dropped. (This is an optimization so that we can statically allocate an array to hold errors, which makes more sense since validate.Pool provides a re-usable pool of validation contexts). <code>max_nesting</code> limits the depth of the object to validate, specifically with respect to arrays. Object and array validators can be nested in any combination, but array validators are difficult as they introduce dynamic field names (e.g. "users.5.favorites.193.name"). The context must keep a stack of array indexes. This is statically allocated (the stack is merely an []usize, so setting this to a larger value should be fine). Pool A thread-safe re-usable pool of Contexts can be created and used: ```zig var pool = validate.Pool(S).init(allocator, .{ // how many contexts to keep in the pool .size = 50, // u16 <code>// Configuration for each individual context .max_errors = 20, .max_nesting = 10, </code> }) ``` Contexts can thus be acquired from the pool and released back into the pool: <code>zig var context = try pool.acquire(); defer pool.release(context);</code> The pool is non-blocking. If empty, a context is dynamically created. The pool will never grow beyond the configured sized.
[]
https://avatars.githubusercontent.com/u/49339966?v=4
ZigEmu
AnErrupTion/ZigEmu
2023-06-05T20:08:47Z
A QEMU frontend made in Zig.
main
0
24
3
24
https://api.github.com/repos/AnErrupTion/ZigEmu/tags
GPL-2.0
[ "frontend", "gui", "ini", "qemu", "zig" ]
991
false
2025-03-16T19:04:32Z
true
true
unknown
github
[ { "commit": "eff2fd1e0c2748e6a2ceb66a263db8d5a8a7365e.tar.gz", "name": "dvui", "tar_url": "https://github.com/david-vanderson/dvui/archive/eff2fd1e0c2748e6a2ceb66a263db8d5a8a7365e.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/david-vanderson/dvui" }, { "commit": "7ab77196a...
ZigEmu ZigEmu is a QEMU frontend made in Zig. It uses the <a>dvui</a> and <a>zig-ini</a> libraries. QEMU ZigEmu currently tracks QEMU v8.2.x. Screenshot
[]
https://avatars.githubusercontent.com/u/260114?v=4
zig-steamworks
menduz/zig-steamworks
2023-06-06T22:27:04Z
Steamwork bindings for Zig
main
0
24
2
24
https://api.github.com/repos/menduz/zig-steamworks/tags
Apache-2.0
[ "game-development", "steamworks", "zig" ]
5,050
false
2025-05-02T14:43:45Z
true
true
unknown
github
[]
zig-steamworks Zig bindings for Steamworks, compatible with v1.57 (March 2023). The bindings are autogenerated from the C bindings and are compatible with - macOS (both Apple Silicon and Intel) - linux (x86_64) - windows (x86_64) Main branch is compatible with Zig 0.14.0 Including the Steamworks SDK Due to licence agreements, you must bring your own SDK. This project assumes it is located in the ./steamworks folder. But you can have it anywhere else. Linking the Steamworks libraries. ```zig // build.zig const zig_steamworks = @import("zig-steamworks/linker.zig"); fn main() !void { // ... const exe = b.addExecutable( ... ); // link steamworks to this executable _ = try zig_steamworks.linkSteamLibrary(b, exe, "steamworks"); // relative path to steamworks ^^^^^^^^^^ // you must include the steam_appid.txt file in your final directory try zig_steamworks.copy(comptime zig_steamworks.thisDir() ++ "/src", "zig-out/bin", "steam_appid.txt"); } ``` Build it For convenience, this repository offers already built bindings for Zig in the <code>src</code> folder. Until Zig modules and package manager are mature, the recommended course of action is to copy these files into your project. To re-build the files run the following command <code>node generate.js path_to_steamworks/public/steam/steam_api.json</code> Example ```zig const std = @import("std"); const steam = @import("steam.zig"); /// callback hook for debug text emitted from the Steam API pub fn SteamAPIDebugTextHook(nSeverity: c_int, pchDebugText: [*c]const u8) callconv(.C) void { // if you're running in the debugger, only warnings (nSeverity &gt;= 1) will be sent // if you add -debug_steamapi to the command-line, a lot of extra informational messages will also be sent std.debug.print("SteamAPIDebugTextHook sev:{} msg: {s}\n", .{ nSeverity, pchDebugText }); } /// get an authentication ticket for our user fn authTicket(identity: <em>steam.SteamNetworkingIdentity) !void { var rgchToken: </em>[2048]u8 = try std.heap.c_allocator.create([2048]u8); var unTokenLen: c_uint = 0; var m_hAuthTicket = steam.SteamUser().GetAuthSessionTicket(rgchToken, 2048, &amp;unTokenLen, identity); std.debug.print("GetAuthSessionTicket={} len={} token={s}", .{ m_hAuthTicket, unTokenLen, rgchToken }); } pub fn main() !void { if (steam.SteamAPI_RestartAppIfNecessary(480)) { // if Steam is not running or the game wasn't started through Steam, SteamAPI_RestartAppIfNecessary starts the // local Steam client and also launches this game again. <code> // Once you get a public Steam AppID assigned for this game, you need to replace k_uAppIdInvalid with it and // removed steam_appid.txt from the game depot. @panic("SteamAPI_RestartAppIfNecessary"); } if (steam.SteamAPI_Init()) { std.debug.print("Steam initialized correctly. \n", .{}); } else { @panic("Steam did not init\n"); } steam.SteamClient().SetWarningMessageHook(SteamAPIDebugTextHook); defer steam.SteamAPI_Shutdown(); std.debug.print("User {?}\n", .{steam.SteamUser().GetSteamID()}); var sock = steam.SteamNetworkingSockets_SteamAPI(); var pInfo: *steam.SteamNetworkingFakeIPResult_t = try std.heap.c_allocator.create(steam.SteamNetworkingFakeIPResult_t); defer std.heap.c_allocator.destroy(pInfo); sock.GetFakeIP(0, pInfo); std.debug.print("GetFakeIP: {}\n", .{pInfo}); if (!pInfo.m_identity.IsEqualTo(pInfo.m_identity)) @panic("not equal"); var pDetails: *steam.SteamNetAuthenticationStatus_t = try std.heap.c_allocator.create(steam.SteamNetAuthenticationStatus_t); defer std.heap.c_allocator.destroy(pDetails); var connectionStatus = sock.GetAuthenticationStatus(pDetails); std.debug.print("GetAuthenticationStatus: {} {}\n", .{ connectionStatus, pDetails }); var pIdentity: *steam.SteamNetworkingIdentity = try std.heap.c_allocator.create(steam.SteamNetworkingIdentity); std.heap.c_allocator.destroy(pIdentity); var r = sock.GetIdentity(pIdentity); std.debug.print("GetIdentity={} {}\n", .{ r, pIdentity }); try authTicket(pIdentity); </code> } ``` Alignment Steamworks is packed with <code>pragma packs</code>, I've tried dozens of approaches even brute forcing all structs, but getting the right alignment for every struct was impossible. So I took the good-enough-and-not-so-elegant path of delegating the alignment to the C compiler entirely and then forcing Zig to copy everything with the generated code. In effect, you will see a lot of <code>align(...)</code> in the generated code. In practice both Mac and Linux alignments are the same. Please do the following steps for each steamworks release that is added to this repo. Mind the diff in the steamworks headers to remove the private fields (search for <code>// ZIG:</code>). To generate the linux alignment file from aarch64 Mac hosts ```bash open a docker container using x86_64 docker run -v $(pwd):/mnt -w /mnt --rm -it --platform linux/amd64 mcr.microsoft.com/devcontainers/typescript-node:0-18 zsh install zig sudo bash .devcontainer/install-zig.sh run the script and grab a coffee bash ./create-align-info-linux.sh ``` To generate the mac alignment file from Mac ```bash run the script bash ./create-align-info-mac.sh ``` To generate the mac alignment file from Windows ```bash run the script .\create-align-info-mac.bat ```
[]
https://avatars.githubusercontent.com/u/82354458?v=4
zig-lmdb
canvasxyz/zig-lmdb
2023-09-12T23:25:41Z
Zig bindings for LMDB
main
1
23
5
23
https://api.github.com/repos/canvasxyz/zig-lmdb/tags
MIT
[ "key-value-store", "lmdb", "zig" ]
52
false
2025-05-17T18:09:48Z
true
true
0.14.0
github
[ { "commit": "refs", "name": "lmdb", "tar_url": "https://github.com/LMDB/lmdb/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/LMDB/lmdb" } ]
zig-lmdb Zig bindings for LMDB. Built and tested with Zig version <code>0.14.0</code>. Table of Contents <ul> <li><a>Installation</a></li> <li><a>Usage</a></li> <li><a>API</a></li> <li><a><code>Environment</code></a></li> <li><a><code>Transaction</code></a></li> <li><a><code>Database</code></a></li> <li><a><code>Cursor</code></a></li> <li><a><code>Stat</code></a></li> <li><a>Benchmarks</a></li> </ul> Installation Add zig-lmdb to <code>build.zig.zon</code> <code>zig .{ .dependencies = .{ .lmdb = .{ .url = "https://github.com/canvasxyz/zig-lmdb/archive/refs/tags/v0.2.0.tar.gz", // .hash = "...", }, }, }</code> Usage An LMDB environment can either have multiple named databases, or a single unnamed database. To use a single unnamed database, open a transaction and use the <code>txn.get</code>, <code>txn.set</code>, <code>txn.delete</code>, and <code>txn.cursor</code> methods directly. ```zig const lmdb = @import("lmdb"); pub fn main() !void { const env = try lmdb.Environment.init("path/to/db", .{}); defer env.deinit(); <code>const txn = try lmdb.Transaction.init(env, .{ .mode = .ReadWrite }); errdefer txn.abort(); try txn.set("aaa", "foo"); try txn.set("bbb", "bar"); try txn.commit(); </code> } ``` To use named databases, open the environment with a non-zero <code>max_dbs</code> value. Then open each named database using <code>Transaction.database</code>, which returns a <code>Database</code> struct with <code>db.get</code>/<code>db.set</code>/<code>db.delete</code>/<code>db.cursor</code> methods. You don't have to close databases, but they're only valid during the lifetime of the transaction. ```zig const lmdb = @import("lmdb"); pub fn main() !void { const env = try lmdb.Environment.init("path/to/db", .{ .max_dbs = 2 }); defer env.deinit(); <code>const txn = try lmdb.Transaction.init(env, .{ .mode = .ReadWrite }); errdefer txn.abort(); const widgets = try txn.database("widgets", .{ .create = true }); try widgets.set("aaa", "foo"); const gadgets = try txn.database("gadgets", .{ .create = true }); try gadgets.set("aaa", "bar"); try txn.commit(); </code> } ``` API <code>Environment</code> ```zig pub const Environment = struct { pub const Options = struct { map_size: usize = 10 * 1024 * 1024, max_dbs: u32 = 0, max_readers: u32 = 126, read_only: bool = false, write_map: bool = false, no_tls: bool = false, no_lock: bool = false, mode: u16 = 0o664, }; <code>pub const Info = struct { map_size: usize, max_readers: u32, num_readers: u32, }; pub fn init(path: [*:0]const u8, options: Options) !Environment pub fn deinit(self: Environment) void pub fn transaction(self: Environment, options: Transaction.Options) !Transaction pub fn sync(self: Environment) !void pub fn stat(self: Environment) !Stat pub fn info(self: Environment) !Info pub fn resize(self: Environment, size: usize) !void // mdb_env_set_mapsize </code> }; ``` <code>Transaction</code> ```zig pub const Transaction = struct { pub const Mode = enum { ReadOnly, ReadWrite }; <code>pub const Options = struct { mode: Mode, parent: ?Transaction = null, }; pub fn init(env: Environment, options: Options) !Transaction pub fn abort(self: Transaction) void pub fn commit(self: Transaction) !void pub fn get(self: Transaction, key: []const u8) !?[]const u8 pub fn set(self: Transaction, key: []const u8, value: []const u8) !void pub fn delete(self: Transaction, key: []const u8) !void pub fn cursor(self: Database) !Cursor pub fn database(self: Transaction, name: ?[*:0]const u8, options: Database.Options) !Database </code> }; ``` <code>Database</code> ```zig pub const Database = struct { pub const Options = struct { reverse_key: bool = false, integer_key: bool = false, create: bool = false, }; <code>pub const Stat = struct { psize: u32, depth: u32, branch_pages: usize, leaf_pages: usize, overflow_pages: usize, entries: usize, }; pub fn open(txn: Transaction, name: ?[*:0]const u8, options: Options) !Database pub fn get(self: Database, key: []const u8) !?[]const u8 pub fn set(self: Database, key: []const u8, value: []const u8) !void pub fn delete(self: Database, key: []const u8) !void pub fn cursor(self: Database) !Cursor pub fn stat(self: Database) !Stat </code> }; ``` <code>Cursor</code> ```zig pub const Cursor = struct { pub const Entry = struct { key: []const u8, value: []const u8 }; <code>pub fn init(db: Database) !Cursor pub fn deinit(self: Cursor) void pub fn getCurrentEntry(self: Cursor) !Entry pub fn getCurrentKey(self: Cursor) ![]const u8 pub fn getCurrentValue(self: Cursor) ![]const u8 pub fn setCurrentValue(self: Cursor, value: []const u8) !void pub fn deleteCurrentKey(self: Cursor) !void pub fn goToNext(self: Cursor) !?[]const u8 pub fn goToPrevious(self: Cursor) !?[]const u8 pub fn goToLast(self: Cursor) !?[]const u8 pub fn goToFirst(self: Cursor) !?[]const u8 pub fn goToKey(self: Cursor, key: []const u8) !void pub fn seek(self: Cursor, key: []const u8) !?[]const u8 </code> }; ``` <blockquote> ⚠️ Always close cursors <strong>before</strong> committing or aborting the transaction. </blockquote> Benchmarks <code>zig build bench</code> 1k entries | | iterations | min (ms) | max (ms) | avg (ms) | std | ops / s | | :----------------------- | ---------: | -------: | -------: | -------: | -----: | -------: | | get random 1 entry | 100 | 0.0001 | 0.0069 | 0.0002 | 0.0007 | 4082799 | | get random 100 entries | 100 | 0.0089 | 0.0204 | 0.0118 | 0.0045 | 8473664 | | iterate over all entries | 100 | 0.0175 | 0.0290 | 0.0221 | 0.0023 | 45156084 | | set random 1 entry | 100 | 0.0498 | 0.1814 | 0.0582 | 0.0159 | 17169 | | set random 100 entries | 100 | 0.0750 | 0.1275 | 0.0841 | 0.0068 | 1189692 | | set random 1k entries | 10 | 0.2495 | 0.2606 | 0.2557 | 0.0035 | 3911596 | | set random 50k entries | 10 | 8.8281 | 12.4414 | 9.8183 | 1.1449 | 5092551 | 50k entries | | iterations | min (ms) | max (ms) | avg (ms) | std | ops / s | | :----------------------- | ---------: | -------: | -------: | -------: | -----: | -------: | | get random 1 entry | 100 | 0.0002 | 0.0072 | 0.0011 | 0.0008 | 914620 | | get random 100 entries | 100 | 0.0194 | 0.0562 | 0.0232 | 0.0058 | 4312356 | | iterate over all entries | 100 | 0.4243 | 0.7743 | 0.5451 | 0.0315 | 91727484 | | set random 1 entry | 100 | 0.0446 | 0.3028 | 0.0577 | 0.0263 | 17342 | | set random 100 entries | 100 | 0.3673 | 0.6541 | 0.4756 | 0.0776 | 210273 | | set random 1k entries | 10 | 0.7499 | 0.9015 | 0.8379 | 0.0474 | 1193519 | | set random 50k entries | 10 | 14.2130 | 14.7817 | 14.4931 | 0.1797 | 3449915 | 1m entries | | iterations | min (ms) | max (ms) | avg (ms) | std | ops / s | | :----------------------- | ---------: | -------: | -------: | -------: | -----: | -------: | | get random 1 entry | 100 | 0.0004 | 0.0270 | 0.0025 | 0.0029 | 397152 | | get random 100 entries | 100 | 0.0440 | 0.1758 | 0.0668 | 0.0198 | 1496224 | | iterate over all entries | 100 | 9.9925 | 13.8858 | 10.6677 | 0.5131 | 93741223 | | set random 1 entry | 100 | 0.0538 | 0.3763 | 0.0721 | 0.0374 | 13874 | | set random 100 entries | 100 | 0.6510 | 2.2153 | 1.7443 | 0.1971 | 57330 | | set random 1k entries | 10 | 6.9965 | 11.5011 | 10.2719 | 1.6529 | 97353 | | set random 50k entries | 10 | 39.9164 | 42.6653 | 41.1931 | 1.0043 | 1213796 |
[]
https://avatars.githubusercontent.com/u/72305366?v=4
zig-zag-zoe
zigster64/zig-zag-zoe
2023-07-05T10:05:20Z
Multiplayer TicTacToe - in Zig - using HTMX for that zero-javascript experience
main
8
23
1
23
https://api.github.com/repos/zigster64/zig-zag-zoe/tags
MIT
[ "game", "htmx", "multiplayer-game", "tictactoe", "tictactoe-game", "zig", "zig-package" ]
823
false
2025-02-22T05:36:55Z
true
true
unknown
github
[ { "commit": "master", "name": "httpz", "tar_url": "https://github.com/karlseguin/http.zig/archive/master.tar.gz", "type": "remote", "url": "https://github.com/karlseguin/http.zig" }, { "commit": "main", "name": "zts", "tar_url": "https://github.com/zigster64/zts/archive/main.tar....
zig-zag-zoe Multiplayer TicTacToe - in Zig - using HTMX for that zero-javascript experience Online demo here http://zig-zag-zoe.com .. (running on a t4g-nano instance on AWS - Linux ARM64, using less than 2mb memory for the whole container) ** Uses Latest Zig 0.12.0 official release ** Install Get Zig - https://ziglang.org/download/ ZigZagZoe now tracks : - Zig 0.12.dev from nightly builds Last successful build / test using 0.12.0-dev.2139+e025ad7b4 <ul> <li>http.zig #blocking branch with .hash = "1220b9cb100296f9ecbea1d5d335a074884e978c2f4fa9781cdeec47e2d222119b65",</li> </ul> Is not currently working with the non-blocking / async branch of http.zig <code>git clone https://github.com/zigster64/zig-zag-zoe.git cd zig-zag-zoe zig build</code> Build and Run ``` zig build .. or zig build run ``` Now point your browsers at http://localhost:3000 .. or the equivalent address on the local network On boot, the system will print a list of valid URLs that should be able to find the game. Note that for multi-user play, you must bring up multiple browser tabs. Works best if you spawn a couple of new windows from the browser, and shrink them so they can sit side by side. How to Play Please visit teh Wiki / User Manual at https://github.com/zigster64/zig-zag-zoe/wiki/Zig-Zag-Zoe-%E2%80%90-Zero-Wing-Edition Bugs There are a few lingering bugs that I havent got around to fixing yet. Audio support on iOS + Safari is a lost cause - can fix it, but it requires a lot of JS code, and I figure that is outside the scope of a nice clean Zig application that Im trying to build here. Also appreciate any other thrashing / trying to break the application, as it all helps make the Zig http ecosystem much more robust. Thanks. Contributions Yep, thats cool. Just go through the regular channels <ul> <li>raise an issue</li> <li>post a PR</li> </ul> If you have questions or RFCs - you can either post them as an issue here, or discuss on Zig discord. Dont be too sad if it takes &gt; 48hr for me to respond though ... will do my best. More Modes and Gameplay ideas Thinking up some new random modes to add to make the game harder - ideas most welcome. <ul> <li>Poison square ... make the grid square permanently unusable</li> <li>Skip ... skip the next player's turn, they miss out</li> <li>Reverso ... like uno reverso, reverses the order in which players take turns</li> <li>Team Play ... allow multiple users to collab as a team</li> <li>Exotic Victory Conditions ... Not just lines, but other shapes to allow victory</li> </ul> Whats Interesting, from a Code point of view ? This code is interesting, and worth a read for the following reasons : <ul> <li>Its all written in Zig. http://ziglang.org. Fast / Safe / Easy to read - pick all 3</li> <li>It uses the excellent http.zig library https://github.com/karlseguin/http.zig to do all the web stuff. I have had exactly zero issues using this lib.</li> <li>Single file binary, which includes the game, a web server, all assets such as HTML, images and audio. 1 file - no litter on your filesystem</li> <li>Generated docker image = 770Kb (compressed) All it has is the compiled executable (2.5MB), which includes only a single binary, nothing else.</li> <li>Run stats - in ReleaseFast mode running a 2 player game, uses less than 2MB RAM to run, and hardly any CPU. Its pretty resource efficient.</li> <li>Its about as simple as doing the same thing in Go, there is really nothing too nasty required in the code. </li> <li>The router, and all the HTML contents is part of the Game object ... the implications of this are that it is possible to create 'web components' using this zig/htmx approach that are all self contained, and can be imported into other projects, without having to know about connecting up routes, or pulling in content. Interesting.</li> <li>Uses SSE / Event Streams to keep it all realtime with pub/sub updates for multiple players. Is simple, and it works, and requires only a trivial amount of code to do.</li> <li>Demonstrates how to do threading, thread conditions / signalling, and using mutexes to make object updates thread safe. Its a bit tricky to do cleanly still, but I guess that concurrency was never meant to be easy. Its certainly no harder than doing the some concurrency in Go</li> <li>No websockets needed</li> <li>There is pretty much NO JAVASCRIPT on the frontend. It uses HTMX https://htmx.org ... which is an alternative approach to web clients, where the frontend is pure hypertext, and everything is done on the backend</li> <li>There is a tiny bit of JS, to play some audio, and to update the session ID, but im still thinking up a way of getting rid of that as well.</li> <li>Uses std.fmt.print() as the templating engine. I didnt know before, but you can use named tags inside the comptime format string, and use those to reference fields in the args param. </li> </ul> Actually makes for a half decent templating tool, without having to find and import a templating lib. ie <code>response.print("I can use {[name]s} and {[address]s} in a fmt.print statement, and it references fields from the struct passed ", .{ .name = "Johnny Ziggy", .address = "22 Zig Street, Zigville, 90210" });</code> Thats pretty good - dont really need a templating engine to do most things like that then, can just use std.fmt.print. In fact, this is better than using a template engine, because you can store the HTML in actual <code>.html</code> files ... which means your editor goes into full HTML mode! Otherwise, need to come up with yet another JSX like thing, and then write a bunch of editor tooling to understand it. Yuk ! Keep it simple I reckon, just use std.fmt, and just use <code>.html</code> files. Not sure if its worth adding a templating lib - at least to do loops and some basic flow control, because its often much much better to take the full power of a real language instead, and just emit formatted fragments. Go has a pretty comprehensive and well done Text Templating tool in the stdlib, but its quite a pain to use and impossible to debug when thing do go wrong, compared to doing the hard stuff in a real language. HTMX thoughts Yeah, its pretty cool, worth adding to your toolbelt. Not sure its really a 'replacement' for SPA type apps - I think it might be painful for larger apps. Not sure, havnt tried yet. What it is 100% excellent for though is for doing apps where there is a lot of shared state between users. (Like a turn based game !) In that case, doing everything on the server, and not having any state at all on the frontend to sync, is really ideal. Its a good fit to this sort of problem. Its super robust. You can do horrible things like reboot the backend, or hard refresh the front end(s) ... and it maintains state without a hiccup, and without needing any exception handling code at all. Very nice. It would be a nightmare doing this in react. There are some very complex things you could do with a turn-based-multiplayer-game type of model though (doesnt have to be a game even) And being able to do that without touching JS, or writing a tonne of code to synch state on the frontends is really nice. Its also a reasonable model for doing shared state between GUI frontends, just using the HTTP/SSE protocol too. Its just HTTP requests, so the networking is totally portable.
[]
https://avatars.githubusercontent.com/u/5464072?v=4
gimme
nektro/gimme
2023-03-02T04:16:35Z
A yummy collection of useful Allocators.
master
2
22
1
22
https://api.github.com/repos/nektro/gimme/tags
MIT
[ "zig", "zig-package" ]
16
false
2025-02-16T06:11:14Z
true
false
unknown
github
[]
gimme <code>gimme</code> is a yummy collection of useful <code>Allocator</code>s. Check out <a><code>src/lib.zig</code></a> for more.
[]
https://avatars.githubusercontent.com/u/65570835?v=4
tree-sitter-zig
ziglibs/tree-sitter-zig
2023-04-22T21:31:47Z
Zig tree-sitter grammar
main
2
21
2
21
https://api.github.com/repos/ziglibs/tree-sitter-zig/tags
MIT
[ "tree-sitter", "zig" ]
1,982
false
2024-11-26T05:01:11Z
true
false
unknown
github
[]
tree-sitter-zig <a>tree-sitter</a> grammar inspired by and partially built on <a>maxxnino/tree-sitter-zig</a> that's going to be made simple to query and structure-preserving on error rather than 100% adherent to the Zig spec. This grammar can successfully parse every behavior testcase, all std files, and all compiler files. Tests <code>bash npm i</code> Then: <code>bash .\node_modules\.bin\tree-sitter generate; .\node_modules\.bin\tree-sitter parse .\test\samples\hello.zig</code> <code>bash node .\test\valid.mjs --path=C:\Programming\Zig\zig\test\cases</code>
[]
https://avatars.githubusercontent.com/u/5464072?v=4
zig-tracer
nektro/zig-tracer
2023-09-20T23:00:09Z
Generic tracing library for Zig, supports multiple backends.
master
4
21
7
21
https://api.github.com/repos/nektro/zig-tracer/tags
MIT
[ "zig", "zig-package" ]
33
false
2025-05-21T20:33:47Z
true
false
unknown
github
[]
zig-tracer <a></a> <a></a> <a></a> <a></a> Generic tracing library for Zig, supports multiple backends. Usage in your program: ```zig const std = @import("std"); const tracer = @import("tracer"); pub const build_options = @import("build_options"); pub const tracer_impl = tracer.spall; // see 'Backends' section below pub fn main() !void { try tracer.init(); defer tracer.deinit(); <code>// main loop while (true) { try tracer.init_thread(); defer tracer.deinit_thread(); handler(); } </code> } fn handler() void { const t = tracer.trace(@src()); defer t.end(); } ``` <code>@src()</code> values are sometimes absolute paths so backends may use this value to trim it to only log relative paths <code>zig exe_options.addOption(usize, "src_file_trimlen", std.fs.path.dirname(std.fs.path.dirname(@src().file).?).?.len);</code> Backends <ul> <li><code>none</code> this is the default and causes tracing calls to become a no-op so that <code>tracer</code> can be added to libraries transparently</li> <li><code>log</code> uses <code>std.log</code> to print on function entrance.</li> <li><code>chrome</code> writes a json file in the <code>chrome://tracing</code> format described <a>here</a> and <a>here</a>.</li> <li><code>spall</code> writes a binary file compatible with the <a>Spall</a> profiler.</li> <li>more? feel free to open an issue with requests!</li> </ul> Any custom backend may also be used that defines the following functions: <ul> <li><code>pub fn init() !void</code></li> <li><code>pub fn deinit() void</code></li> <li><code>pub fn init_thread(dir: std.fs.Dir) !void</code></li> <li><code>pub fn deinit_thread() void</code></li> <li><code>pub inline fn trace_begin(ctx: tracer.Ctx, comptime ifmt: []const u8, iargs: anytype) void</code></li> <li><code>pub inline fn trace_end(ctx: tracer.Ctx) void</code></li> </ul>
[]
https://avatars.githubusercontent.com/u/20256717?v=4
unnamed-voxel-tracer
Game4all/unnamed-voxel-tracer
2023-11-18T08:47:20Z
🧊 Voxel raytracer prototype written in Zig using OpenGL
master
0
21
0
21
https://api.github.com/repos/Game4all/unnamed-voxel-tracer/tags
MIT
[ "glsl", "opengl", "raytracer", "voxel", "zig" ]
11,145
false
2025-05-15T08:03:40Z
true
true
unknown
github
[ { "commit": "affdd6ae6f2ac2c3b9162784bdad345c561eeeea", "name": "mach_glfw", "tar_url": "https://github.com/slimsag/mach-glfw/archive/affdd6ae6f2ac2c3b9162784bdad345c561eeeea.tar.gz", "type": "remote", "url": "https://github.com/slimsag/mach-glfw" }, { "commit": "c6aa077003b53aaa39295412...
<code>unnamed-voxel-tracer</code> Voxel raytracer prototype written in Zig using OpenGL. <strong>Controls</strong> <code>W, A, S, D - Camera movemement, Space - Fly higher Shift - Fly less higher R - Reload shaders</code> License Licensed under MIT License, check <code>LICENSE</code> in repo root for more information.
[]
https://avatars.githubusercontent.com/u/1552770?v=4
tree-sitter
neurocyte/tree-sitter
2023-09-25T22:10:02Z
tree-sitter and many popular parsers built as a single package with zig
master
0
21
16
21
https://api.github.com/repos/neurocyte/tree-sitter/tags
MIT
[ "tree-sitter", "zig" ]
64
false
2025-05-15T14:30:09Z
true
false
unknown
github
[]
404
[ "https://github.com/EngineersBox/Flow" ]
https://avatars.githubusercontent.com/u/53349189?v=4
zentig_ecs
freakmangd/zentig_ecs
2023-04-18T21:48:53Z
Zig ECS library
main
0
20
2
20
https://api.github.com/repos/freakmangd/zentig_ecs/tags
MIT
[ "ecs", "game-development", "gamedev", "zig", "zig-package" ]
6,392
false
2025-05-04T09:51:18Z
true
true
unknown
github
[ { "commit": "f40bb8a935b4878c707c3fccfd5c234cfcb43bf2", "name": "zmath", "tar_url": "https://github.com/zig-gamedev/zmath/archive/f40bb8a935b4878c707c3fccfd5c234cfcb43bf2.tar.gz", "type": "remote", "url": "https://github.com/zig-gamedev/zmath" } ]
zentig_ecs A Zig ECS library. Zentig is designed for scalability and ease of use, while staying out of your way. It's heavily inspired by everything that makes <a>bevy_ecs</a> so great and <a>Unity</a> so approachable. WARNING: It is not recommended to use zentig for anything major in it's current state. While it is functional and I use it frequently, it is far from battle tested. That being said, if you encounter any problems please feel free to open an issue! Installation Fetching for zig master: <code>zig fetch --save git+https://github.com/freakmangd/zentig_ecs</code> Fetching for zig 0.14.0: <code>zig fetch --save https://github.com/freakmangd/zentig_ecs/archive/refs/tags/0.14.0.tar.gz</code> In both cases, place this in your <code>build.zig</code>: <code>zig const zentig = b.dependency("zentig_ecs", .{}); exe.root_module.addImport("ztg", zentig.module("zentig"));</code> And import it in your project: <code>zig const ztg = @import("ztg");</code> Overview An entity is just a <code>usize</code>: <code>zig pub const Entity = usize;</code> A basic component: <code>zig pub const Player = struct { name: []const u8, };</code> A basic system: <code>zig pub fn playerSpeak(q: ztg.Query(.{Player})) !void { for (q.items(Player)) |plr| { std.debug.print("My name is {s}\n", .{plr.name}); } }</code> Registering systems/components into a world: <code>zig const MyWorld = blk: { var wb = ztg.WorldBuilder.init(&amp;.{}); wb.addComponents(&amp;.{Player}); wb.addSystemsToStage(.update, playerSpeak); break :blk wb.Build(); };</code> Calling systems is easily integratable into your game framework: ```zig test "running systems" { var world = MyWorld.init(testing.allocator); defer world.deinit(); try world.runStage(.load); try world.runUpdateStages(); try world.runStage(.draw); // Support for user defined stages try world.runStageList(&amp;.{ .post_process, .pre_reset, .post_mortem }); } ``` Scalability The <code>.include()</code> function in <code>WorldBuilder</code> makes it easy to compartmentalize your game systems. As well as integrate third party libraries with only one extra line! <code>main.zig</code>: <code>zig // .include() looks for a `pub fn include(comptime *WorldBuilder) (!)void` def // in each struct. If the function errors it's a compile error, // but the signature can return either `!void` or `void` wb.include(&amp;.{ ztg.base, @import("player.zig"), @import("my_library"), });</code> <code>player.zig</code>: <code>zig pub fn include(comptime wb: *ztg.WorldBuilder) void { wb.addComponents(.{ Player, PlayerGun, PlayerHUD }); wb.addSystemsToStage(.update, .{ update_player, update_gun, update_hud }); }</code> <code>my_library/init.zig</code>: <code>zig pub fn include(comptime wb: *ztg.WorldBuilder) void { wb.include(&amp;.{ // Namespaces can be included more than once to "ensure" // they are included if you depend on them ztg.base, //... }); }</code> Getting Started See this short tutorial on creating systems and components <a>here</a> Full Examples See full examples in the <a>examples folder</a> Framework Support zentig is framework agnostic, it doesn't include any drawing capabilities. For that you need something like Raylib, I've created a library that wraps common Raylib components and provides systems that act on those components <a>here</a>. That page provides installation instructions and usage examples.
[]
https://avatars.githubusercontent.com/u/21150830?v=4
zig-flutter-embedder
ConnorRigby/zig-flutter-embedder
2023-04-12T20:46:14Z
FlutterEmbedderGLFW.cc ported to idomatic zig
main
0
20
1
20
https://api.github.com/repos/ConnorRigby/zig-flutter-embedder/tags
BSD-3-Clause
[ "flutter", "flutter-embedder", "glfw", "opengl", "zig" ]
7
false
2025-04-15T22:48:48Z
true
false
unknown
github
[]
Zig Flutter Embedder Usage The setup for this is currently sort of convoluted. TODO: automate this process in the future.. <ul> <li><a>Get Zig</a></li> <li><a>Get Flutter</a></li> <li>Get a statically linked library for your platform: <code>find / -name "engine.version"</code></li> <li>Unzip that into this directory: <code>unzip flutter_embedder</code></li> <li>Create a new flutter app (or copy your own): <code>flutter create myapp</code></li> <li>Create a bundle: <code>cd myapp &amp;&amp; flutter build bundle</code></li> <li><code>zig build run</code></li> </ul> Screenshots and Demos TODO: add more examples Docs, Links, etc These links helped me, but to be quite honest, only in spirit. They contain almost no useful information. <ul> <li><a>unhelpfully empty official documentation</a></li> <li><a>annoyingly unhelpful official Discord</a></li> <li><a>woefully incomplete official embedder example</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/159547333?v=4
tree-sitter-zig
tree-sitter-grammars/tree-sitter-zig
2023-08-06T18:58:30Z
Zig grammar for tree-sitter
master
2
19
4
19
https://api.github.com/repos/tree-sitter-grammars/tree-sitter-zig/tags
MIT
[ "parser", "tree-sitter", "zig" ]
639
false
2025-05-06T12:36:22Z
false
false
unknown
github
[]
tree-sitter-zig <a></a> <a></a> <a></a> <a></a> <a></a> <a></a> Zig grammar for <a>tree-sitter</a>. References <ul> <li><a>Zig Grammar</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/206480?v=4
aolium-api
karlseguin/aolium-api
2023-07-14T02:37:20Z
API server for aolium.com
master
0
18
1
18
https://api.github.com/repos/karlseguin/aolium-api/tags
MPL-2.0
[ "blogging", "zig" ]
3,257
false
2024-12-07T19:18:45Z
true
true
unknown
github
[ { "commit": "6946917979ec263574cb5586032f655e8c6728d9.tar.gz", "name": "httpz", "tar_url": "https://github.com/karlseguin/http.zig/archive/6946917979ec263574cb5586032f655e8c6728d9.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/karlseguin/http.zig" }, { "commit": "2ef2f773a9...
Aolium API Server This is the source code for the API server of .
[]
https://avatars.githubusercontent.com/u/6756180?v=4
awesome-concurrency
kassane/awesome-concurrency
2023-06-03T13:30:30Z
null
main
0
18
5
18
https://api.github.com/repos/kassane/awesome-concurrency/tags
-
[ "awesome", "awesome-list", "concurrent-programming", "coroutines", "cplusplus", "cpp", "golang", "llvm", "rust", "zig" ]
101
false
2025-05-20T15:56:10Z
false
false
unknown
github
[]
Awesome Concurrency Sub-lists <ul> <li><a>Libraries</a></li> </ul> Memory consistency models <ul> <li><a>Atomic vs. Non-Atomic Operations</a></li> <li><a>Atomic reference counting (with Zig code samples)</a></li> <li><a>Memory Barriers: a Hardware View for Software Hackers</a></li> <li><a>Memory Models: A Case For Rethinking Parallel Languages and Hardware</a></li> <li><a>Java Memory Model</a></li> <li><a>Foundations of the C++ Concurrency Memory Model</a></li> <li><a>Explanation of the Linux-Kernel Memory Consistency Model</a></li> <li><a>Frightening Small Children and Disconcerting Grown-ups: Concurrency in the Linux Kernel</a></li> <li><a>Memory Models</a> by <a>Russ Cox</a></li> <li><a>Hardware MM</a></li> <li><a>Programming Language MM</a></li> <li><a>Updating the Go MM</a></li> <li><a>Repairing Sequential Consistency in C/C++11</a> + <a>P0668R5: Revising the C++ memory model</a></li> <li><a>A Promising Semantics for Relaxed-Memory Concurrency</a></li> <li><a>Bounding Data Races in Space and Time</a> + <a>Multicore OCaml Memory model</a></li> <li><a>C++ Memory Ordering at Compile Time</a></li> <li><a>The Problem of Programming Language Concurrency Semantics</a></li> <li><a>Understandnig Atomics and Memory Ordering</a></li> <li><a>Weak memory concurrency in C/C++11</a></li> <li><a>Weak Memory Consistency</a></li> <li><a>Weakly Consistent Concurrency</a></li> <li><a>Memory Order in C++</a></li> <li><a>Atomics And Concurrency</a></li> <li><a>A Relaxed Guide to memory_order_relaxed - by Paul McKenney &amp; Hans Boehm</a></li> </ul> Examples C++ <ul> <li><a><code>intro.multithread</code></a></li> <li><a><code>atomics.order</code></a></li> <li><a><code>atomics.fences</code></a></li> <li><a><code>std::memory_order</code></a></li> <li><a>C++ reference - Memory Model</a></li> </ul> <a>Index</a> Rust <ul> <li><a>The Rust Reference / Memory model</a></li> <li><a>The Rustonomicon / Atomics</a></li> </ul> Java <ul> <li><a>Java Memory Model</a></li> </ul> Go <ul> <li><a>Go Memory Model</a></li> <li><a>Don't be clever</a></li> </ul> D <ul> <li><a>D Memory Model</a></li> <li><a>D Wiki - C++ to D Concurrency</a></li> </ul> LLVM <ul> <li><a>LLVM Atomic Instructions and Concurrency Guide</a></li> </ul> Atomics impl <ul> <li><a>C/C++11 mappings to processors</a></li> <li><a>The JSR-133 Cookbook for Compiler Writers</a></li> </ul> Futures <ul> <li><a>Futures and Promises</a></li> <li><a>Your Server as a Function</a>, <a>Systems Programming at Twitter</a>, <a>Finagle – Concurrent Programming with Futures</a></li> <li><a>Futures for C++11 at Facebook</a>, <a>Folly Futures</a>, </li> <li><a>Zero-cost futures in Rust</a>, <a>Designing futures for Rust</a>, <a>RFC</a></li> </ul> Fibers <ul> <li><a>Fibers in C++: Understanding the basics</a></li> <li><a>Fibers, Oh My!</a></li> <li><a>Project Loom: Fibers and Continuations for the Java Virtual Machine</a></li> <li><a>State of Loom, Part 1</a>, <a>Part 2</a></li> <li><a>C++ / Distinguishing coroutines and fibers</a></li> <li><a>C++ / Fibers under the magnifying glass</a></li> <li><a>Lightweight concurrency in lua</a></li> <li><a>D - Fibers</a></li> </ul> Coroutines Stackless <ul> <li><a>Stackless Coroutine in Asio</a></li> <li><a>On Duff's Device and Coroutines</a></li> </ul> Assymmetric Transfer <ul> <li><a>Coroutine Theory</a></li> <li><a>Writing custom C++20 coroutine systems</a></li> <li><a>Revisiting Coroutines by Ana Lúcia de Moura and Roberto Ierusalimschy</a></li> </ul> Stacks <ul> <li><a>Segmented Stacks in LLVM</a></li> <li><a>Rust / Abandoning segmented stacks in Rust</a></li> <li><a>Go / How Stacks are Handled in Go</a>, <a>Continious Stacks Design Doc</a></li> <li><a>Rust / Futures and Segmented Stacks</a></li> <li><a>Continuation Passing for C - A space-efficient implementation of concurrency</a></li> <li><a>C++ / call/cc (call-with-current-continuation): A low-level API for stackful context switching</a></li> </ul> Schedulers <ul> <li><a>Making the Tokio scheduler 10x faster</a></li> <li><a>Rust / Work-Stealing Scheduler Discussion</a></li> <li><a>Scalable Go Scheduler Design Doc</a></li> <li><a>Dmitry Vyukov — Go scheduler: Implementing language with lightweight concurrency</a></li> <li><a>GopherCon 2020: Austin Clements - Pardon the Interruption: Loop Preemption in Go 1.14</a></li> <li><a>"Runtime scheduling: theory and reality" by Eben Freeman</a></li> </ul> Impls <ul> <li>[Golang] <a>Runtime</a></li> <li>[Rust] <a>Tokio Multi-Threaded Runtime</a></li> <li>[Dlang] <a>Phobos - Multiple Declarations</a></li> <li>[Kotlin] <a>Coroutine Runtime</a></li> <li>[Scala] <a>Cats Effect</a></li> </ul> Channels <ul> <li><a>Go channels on steroids</a></li> <li><a>Scalable FIFO Channels for Programming via Communicating Sequential Processes</a></li> <li><a>Fast and Scalable Channels in Kotlin Coroutines</a></li> </ul> Asynchronous Programming <ul> <li><a>Асинхронность в программировании</a></li> <li><a>Асинхронность: назад в будущее</a></li> <li><a>Kotlin Coroutines Proposal</a></li> <li><a>Zero-cost futures in Rust</a>, <a>Designing futures for Rust</a></li> </ul> Async / await <ul> <li>C#: <a>Механика asnyc/await в C#</a></li> <li>Kotlin: <a>Coroutines / Implementation details</a></li> <li>C++:</li> <li><a>Understanding operator co_await</a></li> <li><a>Understanding the promise type</a></li> <li><a>Understanding the Compiler Transform</a></li> <li><a>Understanding Symmetric Transfer</a></li> </ul> Syntax <ul> <li><a>What Color is Your Function?</a>, <a>Hacker news</a></li> <li>C#: <a>Asynchrony in C# 5 Part Six: Whither async?</a></li> <li>Rust: <a>A final proposal for await syntax</a>, <a>Await Syntax Write Up</a></li> <li>Kotlin: <a>How do you color your functions?</a></li> <li>Zig: <a>What is Zig's “Colorblind” Async/Await?</a></li> </ul> Structured Concurrency <ul> <li><a>Notes on structured concurrency, or: Go statement considered harmful</a></li> <li><a>Structured Concurrency Group</a>, <a>Resources</a></li> <li><a>Roman Elizarov – Structured concurrency</a></li> <li><a>Lewis Baker – Structured Concurrency: Writing Safer Concurrent Code with Coroutines and Algorithms</a></li> <li><a>Eric Niebler – Structured Concurrency</a></li> <li><a>Josua Wuyts - Tree-Structured Concurrency</a></li> <li><a>Sebastiaan Koppe - Structured Concurrency in D(Video)</a></li> </ul> Cancellation <ul> <li><a>Timeouts and cancellation for humans</a></li> </ul> Data race detection <ul> <li><a>ThreadSanitizer – data race detection in practice</a>, <a>compiler-rt/lib/tsan/rtl</a></li> <li><a>FastTrack: Efficient and Precise Dynamic Race Detection</a></li> </ul> Verification <ul> <li><a>Dynamic Partial-Order Reduction for Model Checking Software</a></li> <li><a>Finding and Reproducing Heisenbugs in Concurrent Programs</a></li> <li><a>CDSCHECKER: Checking Concurrent Data Structures Written with C/C++ Atomics</a></li> <li><a>How We Test Concurrent Primitives in Kotlin Coroutines</a></li> </ul> Tools <ul> <li>Rust: <a>Loom - concurrency permutation testing</a></li> <li>Kotlin: <a>Lincheck - framework for testing concurrent</a></li> </ul> Fearless Concurrency <ul> <li>Rust: <a>Fearless Concurrency</a></li> <li>Pony: <a>Reference capabilities</a></li> <li>C++: <a>Clang Thread-Safety Analysis</a></li> <li>D: <a>Fearless - Safe Concurrency in D</a></li> <li><a>Joe Duffy (Project Midori) – 15 Years of Concurrency</a></li> </ul> Consistency models for concurrent objects <ul> <li><a>Linearizability: A Correctness Condition for Concurrent Objects </a></li> <li><a>Consistency Models Map</a></li> <li><a>Linearizability versus Serializability</a></li> <li><a>Strong consistency models</a></li> </ul> Lock-freedom Data Structures / Algorithms <ul> <li><a>Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms</a></li> <li><a>A Scalable Lock-free Stack Algorithm</a></li> <li><a>The Baskets Queue</a></li> <li><a>Lock-free deques and doubly linked lists</a></li> <li><a>A Practical Multi-Word Compare-and-Swap Operation</a></li> </ul> Memory Management <ul> <li><a>Hazard Pointers: Safe Memory Reclamation for Lock-Free Objects</a></li> <li><a>Epoch-Based Memory Reclamation</a></li> <li><a>Differential Reference Counting</a></li> <li><a>Implementing a Lock-free <code>atomic_shared_ptr</code></a></li> <li><a>folly / <code>AtomicSharedPtr</code></a></li> <li><a>Automem Hands Free RAII in D</a></li> </ul> Misc <ul> <li><a>Roman Elizarov — Lock-Free Algorithms for Kotlin Coroutines</a></li> <li><a>Lock-free структуры данных</a></li> <li><a>LockFree Programming a_Mental Model - Xorvoid</a></li> <li><a>Zig's I/O and Concurrency Story by King Protty</a> [Video]</li> <li><a>CppCon 2016 - "Elegant Asynchronous Code" by Nat Goodspeed</a> [Video]</li> </ul> Transactions <ul> <li><a> Martin Kleppmann – Transactions: myths, surprises and opportunities</a>, <a>slides &amp; references</a></li> <li><a>A Critique of ANSI SQL Isolation Levels</a></li> <li><a>Serializable Isolation for Snapshot Databases</a></li> <li><a>What Write Skew Looks Like</a></li> <li><a>A Read-Only Transaction Anomaly Under Snapshot Isolation</a></li> <li><a>Google Percolator</a></li> <li><a>Serializable Snapshot Isolation in PostgreSQL</a></li> <li><a>PostgreSQL SSI Implementation Notes</a></li> <li><a>A History of Transaction Histories</a> </li> </ul> Demystifying Database Systems <ul> <li><a>An Introduction to Transaction Isolation Levels</a></li> <li><a>Correctness Anomalies Under Serializable Isolation</a></li> <li><a>Introduction to Consistency Levels</a> </li> <li><a>Isolation levels vs. Consistency levels</a></li> </ul> Hardware Transactional Memory <ul> <li><a>Maurice Herlihy – Transactional Memory</a>, <a>slides</a></li> <li><a>Gil Tene – Understanding Hardware Transactional Memory</a></li> <li><a>Is Parallel Programming Hard, And, If So, What Can You Do About It?</a>, 17.3</li> <li><a>Глава 16 – Programming with Intel Transactional Synchronization Extensions</a></li> <li><a>Глава 15 – Intel TSX Recommendations</a></li> <li><a>TSX Anti-Patterns</a></li> <li><a>Lock Elision Implementation Guide</a></li> </ul> Software Transactional Memory <ul> <li>[D] <a>Software Transactional Memory in D (Video)</a> by Brad Roberts</li> <li>[C++] <a>CppCon 2015 - “Transactional Memory in Practice"</a> by Brett Hall</li> <li>[Scala, ZIO] <a>Introduction to Software Transactional Memory</a></li> <li><a>A (brief) retrospective on transactional memory</a> by Joe Duffy</li> </ul> IO <ul> <li><a>Lord of io_uring</a></li> <li><a>A Universal I/O Abstraction for C++</a></li> <li><a>A Programmer-Friendly I/O Abstraction Over io_uring and kqueue</a></li> </ul> Acknowledgments <strong>Author:</strong> <a>Roman Lipovsky</a> Original repository: <a>from Gitlab - Awesome-Concurrency</a>
[]
https://avatars.githubusercontent.com/u/124872?v=4
nonce-extension
jedisct1/nonce-extension
2023-11-02T11:33:52Z
Make AES-GCM safe to use with random nonces, for any practical number of messages.
main
0
18
1
18
https://api.github.com/repos/jedisct1/nonce-extension/tags
NOASSERTION
[ "aes", "aes-gcm", "derive-key-aes-gcm", "dndk-gcm", "double-nonce-derive-key-aes-gcm", "extension", "nonce", "zig", "zig-package" ]
17
false
2025-04-17T23:56:09Z
false
false
unknown
github
[]
Derive-Key-AES-GCM AES-GCM is a very common choice of authenticated encryption algorithm. Unfortunately, it has some <a>pretty low usage limits</a>. Using it with a large amount of messages requires extra care to ensure that nonces never repeat, and that keys are frequently rotated. The TLS protocol hides that complexity, but applications using AES-GCM directly need to be aware of these limitations in order to use AES-GCM safely. Ideally, nonces should be large, allowing applications to safely generate them randomly, with a negligible collision probability. But AES-GCM, as commonly implemented and required by IETF protocols, is limited to 96-bit (12 bytes) nonces, which is not enough to avoid collisions. AES-GCM keys are also expected to be replaced way before 2^32 messages have been encrypted. During the 2023 NIST Workshop on Block Ciphers, Shay Gueron presented a clever way to overcome these limitations, and extend a key lifetime to "forever": the <a>Derive-Key-AES-GCM</a> construction. This construction allows larger nonces to be used with AES-GCM, thus extending the key lifetime. With AES-256 and 192-bit nonces, a practically unlimited number of messages can be encrypted using a single key, and with nonces that can be randomly generated. It significantly improves the safety of AES-GCM with minor overhead. When instantiated with <code>AES-128</code>, the <code>Derive-Key</code> construction derives a fresh <code>AES-128</code> encryption key from a key and a nonce that can be up to 120 bits (theorically 126, but 120 for practical purposes). That encryption key can then be used with <code>AES-128-GCM</code>, along with a static nonce. When instantiated with <code>AES-256</code>, the <code>Double-Nonce-Derive-Key</code> construction derives a fresh <code>AES-256</code> encryption key from a key and a nonce that can be up to 232 bits (but 192 is enough for all practical purposes). That encryption key can then be used with <code>AES-128-GCM</code>, along with a static nonce, and the guarantee that keys will never repeat. This repository contains easy-to-use implementations of these constructions (<code>aes256-gcm-dndk</code>, <code>aes128-gcm-dndk</code>).
[]
https://avatars.githubusercontent.com/u/51416554?v=4
zig-htmx
hendriknielaender/zig-htmx
2024-01-11T16:52:12Z
Example chat app written in zig + htmx
main
0
18
0
18
https://api.github.com/repos/hendriknielaender/zig-htmx/tags
MIT
[ "chat", "htmx", "websockets", "zap", "zig" ]
46
false
2025-05-13T12:40:13Z
true
true
unknown
github
[ { "commit": "23b70b8881fa704d3ff73480c2309a71a4c0bd58.tar.gz", "name": "zap", "tar_url": "https://github.com/zigzap/zap/archive/23b70b8881fa704d3ff73480c2309a71a4c0bd58.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/zigzap/zap" } ]
Zig-HTMX Chat Application Overview The Zig-HTMX Chat Application is a real-time chat platform that combines the power of Zig for server-side operations with HTMX on the frontend. This application uses WebSockets for seamless, real-time communication between users. Features <ul> <li><strong>Real-Time Messaging:</strong> Instantly send and receive messages using WebSockets.</li> <li><strong>Zig Backend:</strong> Utilizes the efficiency and safety of Zig programming language.</li> <li><strong>HTMX Frontend:</strong> Dynamic and responsive UI without writing JavaScript.</li> <li><strong>Minimalist Design:</strong> Easy-to-use interface focusing on functionality.</li> </ul> Prerequisites Before running the Zig-HTMX Chat Application, ensure you have the following installed: - Zig (latest version) - A modern web browser supporting HTMX and WebSockets Installation <ol> <li><strong>Clone the Repository</strong> <code>bash git clone https://github.com/hendriknielaender/zig-htmx.git cd zig-htmx</code></li> <li><strong>Build the Zig Server(zap)</strong> <code>bash zig build</code></li> <li><strong>Run the server</strong> <code>bash zig-out/bin/zig-htmx</code></li> <li><strong>Access the Application</strong> <code>bash Open your web browser and go to http://localhost:3010.</code></li> </ol>
[]
https://avatars.githubusercontent.com/u/524033?v=4
zigradio
vsergeev/zigradio
2023-02-24T11:40:24Z
A lightweight software-defined radio framework built with Zig
master
0
17
0
17
https://api.github.com/repos/vsergeev/zigradio/tags
MIT
[ "radio", "sdr", "zig", "zigradio" ]
372
false
2025-05-14T08:19:11Z
true
true
unknown
github
[]
ZigRadio <a></a> <a></a> <a></a> <strong>ZigRadio</strong> is a lightweight flow graph signal processing framework for software-defined radio. It provides a suite of source, sink, and processing blocks, with a simple API for defining flow graphs, running flow graphs, and creating blocks. ZigRadio has an API similar to that of <a>LuaRadio</a> and is also MIT licensed. ZigRadio can be used to rapidly prototype software radios, modulation/demodulation utilities, and signal processing experiments. Example Wideband FM Broadcast Radio Receiver ``` zig const std = @import("std"); const radio = @import("radio"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; <code>const frequency: f64 = 91.1e6; // 91.1 MHz const tune_offset = -250e3; var source = radio.blocks.RtlSdrSource.init(frequency + tune_offset, 960000, .{ .debug = true }); var if_translator = radio.blocks.FrequencyTranslatorBlock.init(tune_offset); var if_filter = radio.blocks.LowpassFilterBlock(std.math.Complex(f32), 128).init(200e3, .{}); var if_downsampler = radio.blocks.DownsamplerBlock(std.math.Complex(f32)).init(4); var fm_demod = radio.blocks.FrequencyDiscriminatorBlock.init(75e3); var af_filter = radio.blocks.LowpassFilterBlock(f32, 128).init(15e3, .{}); var af_deemphasis = radio.blocks.FMDeemphasisFilterBlock.init(75e-6); var af_downsampler = radio.blocks.DownsamplerBlock(f32).init(5); var sink = radio.blocks.PulseAudioSink(1).init(); var top = radio.Flowgraph.init(gpa.allocator(), .{ .debug = true }); defer top.deinit(); try top.connect(&amp;source.block, &amp;if_translator.block); try top.connect(&amp;if_translator.block, &amp;if_filter.block); try top.connect(&amp;if_filter.block, &amp;if_downsampler.block); try top.connect(&amp;if_downsampler.block, &amp;fm_demod.block); try top.connect(&amp;fm_demod.block, &amp;af_filter.block); try top.connect(&amp;af_filter.block, &amp;af_deemphasis.block); try top.connect(&amp;af_deemphasis.block, &amp;af_downsampler.block); try top.connect(&amp;af_downsampler.block, &amp;sink.block); _ = try top.run(); </code> } ``` Check out some more <a>examples</a> of what you can build with ZigRadio. Installation Fetch the ZigRadio package: <code>zig fetch --save git+https://github.com/vsergeev/zigradio#master</code> Add ZigRadio as a dependency to your <code>build.zig</code>: <code>const radio = b.dependency("radio", .{}); ... exe.root_module.addImport("radio", radio.module("radio")); exe.linkLibC();</code> Optimization <code>ReleaseFast</code> is recommended for real-time applications. libc is required for loading dynamic libraries used for acceleration and I/O. Building ZigRadio requires Zig version 0.14.0. <code>$ git clone https://github.com/vsergeev/zigradio.git $ cd zigradio</code> Build examples: <code>shell $ zig build examples</code> Try out one of the <a>examples</a> with an <a>RTL-SDR</a> dongle: <code>$ ./zig-out/bin/example-rtlsdr_wbfm_mono 89.7e6</code> Project Structure <ul> <li><a>src/</a> - Sources<ul> <li><a>radio.zig</a> - Top-level package</li> <li><a>core/</a> - Core framework</li> <li><a>blocks/</a> - Blocks<ul> <li><a>sources/</a> - Sources</li> <li><a>sinks/</a> - Sinks</li> <li><a>signal/</a> - Signal blocks</li> <li><a>composites/</a> - Composite blocks</li> </ul> </li> <li><a>utils/</a> - Utility functions</li> <li><a>vectors/</a> - Generated test vectors</li> </ul> </li> <li><a>examples/</a> - Examples</li> <li><a>benchmarks/</a> - Benchmark Suite</li> <li><a>docs/</a> - Documentation</li> <li><a>build.zig</a> - Zig build script</li> <li><a>build.zig.zon</a> - Zig package manifest</li> <li><a>CHANGELOG.md</a> - Change log</li> <li><a>LICENSE</a> - MIT License</li> <li><a>README.md</a> - This README</li> </ul> Testing Run unit tests with: <code>$ zig build test</code> Test vectors are generated with Python 3 and NumPy/SciPy: <code>$ zig build generate</code> Benchmarking Run the benchmark suite with: <code>$ zig build benchmark</code> License ZigRadio is MIT licensed. See the included <a>LICENSE</a> file.
[]
https://avatars.githubusercontent.com/u/51416554?v=4
zRPC
hendriknielaender/zRPC
2023-08-04T17:22:39Z
⛓️ gRPC library for zig built on C Core library
main
6
17
1
17
https://api.github.com/repos/hendriknielaender/zRPC/tags
MIT
[ "grpc", "grpc-client", "grpc-server", "zig", "ziglang" ]
105
false
2025-04-23T14:28:50Z
true
false
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> Still work in progress. </blockquote> ⚡zRPC - gRPC for Zig (Built on C Core Library) This is a gRPC library for the Zig programming language built on top of the C Core library. It provides an efficient and expressive way to communicate between microservices using the gRPC protocol in Zig. Features <ul> <li><strong>Full Integration with Zig</strong>: Seamless usage with Zig's build system and standard library.</li> <li><strong>Performance</strong>: Built on top of the robust gRPC C Core library.</li> <li><strong>Bi-directional Streaming</strong>: Support for full-duplex streaming RPCs.</li> <li><strong>Pluggable</strong>: Supports custom authentication, load balancing, retries, etc.</li> </ul> Requirements <ul> <li>Zig compiler version 0.x.x or newer.</li> </ul> Installation WIP
[]
https://avatars.githubusercontent.com/u/41810442?v=4
zig-gpio
Elara6331/zig-gpio
2023-12-12T03:21:42Z
A Zig library for controlling GPIO lines on Linux systems
master
0
17
5
17
https://api.github.com/repos/Elara6331/zig-gpio/tags
MIT
[ "gpio", "gpiochip", "linux", "zig" ]
40
false
2025-05-16T03:23:55Z
true
true
unknown
github
[]
zig-gpio <strong>zig-gpio</strong> is a Zig library for controlling GPIO lines on Linux systems This library can be used to access GPIO on devices such as <a>Raspberry Pis</a> or the <a>Milk-V Duo</a> (which is the board I created it for and tested it with). This is my first Zig project, so I'm open to any suggestions! <em>There's a companion article available on my website: https://www.elara.ws/articles/milkv-duo.</em> Compatibility <strong>zig-gpio</strong> uses the v2 character device API, which means it will work on any Linux system running kernel 5.10 or above. All you need to do is find out which <code>gpiochip</code> device controls which pin and what the offsets are, which you can do by either finding documentation online, or using the <code>gpiodetect</code> and <code>gpioinfo</code> tools from this repo or from <code>libgpiod</code>. Commands <strong>zig-gpio</strong> provides replacements for some of the <code>libgpiod</code> tools, such as <code>gpiodetect</code> and <code>gpioinfo</code>. You can build all of them using <code>zig build commands</code> or specific ones using <code>zig build &lt;command&gt;</code> (for example: <code>zig build gpiodetect</code>). Try it yourself! Here's an example of a really simple program that requests pin 22 from <code>gpiochip2</code> and makes it blink at a 1 second interval. That pin offset is the LED of a Milk-V Duo board, so if you're using a different board, make sure to change it. ```zig const std = @import("std"); const gpio = @import("gpio"); pub fn main() !void { var chip = try gpio.getChip("/dev/gpiochip2"); defer chip.close(); std.debug.print("Chip Name: {s}\n", .{chip.name}); <code>var line = try chip.requestLine(22, .{ .output = true }); defer line.close(); while (true) { try line.setHigh(); std.time.sleep(std.time.ns_per_s); try line.setLow(); std.time.sleep(std.time.ns_per_s); } </code> } ``` For more examples, see the <a>_examples</a> directory. You can build all the examples using the <code>zig build examples</code> command. Using zig-gpio in your project If you don't have a zig project already, you can create one by running <code>zig init-exe</code> in a new folder. To add <code>zig-gpio</code> as a dependency, there are two steps: <ol> <li>Add <code>zig-gpio</code> to your <code>build.zig.zon</code> file</li> <li>Add <code>zig-gpio</code> to your <code>build.zig</code> file</li> </ol> If you don't have a <code>build.zig.zon</code> file, create one. If you do, just add <code>zig-gpio</code> as a dependency. Here's what it should look like: ```zig .{ .name = "my_project", .version = "0.0.1", <code>.dependencies = .{ .gpio = .{ .url = "https://gitea.elara.ws/Elara6331/zig-gpio/archive/v0.0.2.tar.gz", .hash = "1220e3af3194d1154217423d60124ae3a46537c2253dbfb8057e9b550526d2885df1", } } </code> } ``` Then, in your <code>build.zig</code> file, add the following before <code>b.installArtifact(exe)</code>: <code>zig const gpio = b.dependency("gpio", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("gpio", gpio.module("gpio"));</code> And that's it! You should now be able to use <code>zig-gpio</code> via <code>@import("gpio");</code>
[]
https://avatars.githubusercontent.com/u/51416554?v=4
http2.zig
hendriknielaender/http2.zig
2024-01-30T17:22:10Z
🌐 HTTP/2 server for zig
main
16
17
1
17
https://api.github.com/repos/hendriknielaender/http2.zig/tags
MIT
[ "http-server", "http2", "zig", "zig-library", "zig-package" ]
373
false
2025-05-11T23:44:46Z
true
true
0.13.0
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> Still work in progress. </blockquote> A HTTP/2 Zig library according to the HTTP/2 RFCs. [![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/hendriknielaender/http2.zig/blob/HEAD/LICENSE) ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/hendriknielaender/http2.zig) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/hendriknielaender/http2.zig/blob/HEAD/CONTRIBUTING.md) ![h2spec Conformance](https://img.shields.io/badge/h2spec-71%2F74%20tests%20passing-red) Features <ul> <li>Connection management</li> <li>Stream handling</li> <li>Frame parsing and serialization</li> <li>Compliance with HTTP/2 specifications</li> </ul> Installation You can use <code>zig fetch</code> to conveniently set the hash in the <code>build.zig.zon</code> file and update an existing dependency. Run the following command to fetch the http2.zig package: <code>shell zig fetch https://github.com/hendriknielaender/http2.zig/archive/&lt;COMMIT&gt;.tar.gz --save</code> Using <code>zig fetch</code> simplifies managing dependencies by automatically handling the package hash, ensuring your <code>build.zig.zon</code> file is up to date. Option 1 (build.zig.zon) <ol> <li>Declare http2.zig as a dependency in <code>build.zig.zon</code>:</li> </ol> <code>diff .{ .name = "my-project", .version = "1.0.0", .paths = .{""}, .dependencies = .{ + .http2 = .{ + .url = "https://github.com/hendriknielaender/http2.zig/archive/&lt;COMMIT&gt;.tar.gz", + }, }, }</code> <ol> <li>Add the module in <code>build.zig</code>:</li> </ol> ```diff const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); <ul> <li>const opts = .{ .target = target, .optimize = optimize };</li> <li> const http2_module = b.dependency("http2", opts).module("http2"); const exe = b.addExecutable(.{ .name = "test", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); + exe.root_module.addImport("http2", http2_module); exe.install(); ... } ``` </li> <li> Get the package hash: </li> </ul> <code>shell $ zig build my-project/build.zig.zon:6:20: error: url field is missing corresponding hash field .url = "https://github.com/hendriknielaender/http2.zig/archive/&lt;COMMIT&gt;.tar.gz", ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ note: expected .hash = "&lt;HASH&gt;",</code> <ol> <li>Update <code>build.zig.zon</code> package hash value:</li> </ol> <code>diff .{ .name = "my-project", .version = "1.0.0", .paths = .{""}, .dependencies = .{ .http2 = .{ .url = "https://github.com/hendriknielaender/http2.zig/archive/&lt;COMMIT&gt;.tar.gz", + .hash = "&lt;HASH&gt;", }, }, }</code> Usage Connection To create an HTTP/2 connection, use the <code>Connection</code> struct. This struct handles the initialization, sending of the HTTP/2 preface, settings, and managing streams. ```zig const std = @import("std"); const http2 = @import("http2"); const Connection = http2.Connection(std.io.AnyReader, std.io.AnyWriter); pub fn main() !void { const address = try std.net.Address.resolveIp("0.0.0.0", 8081); var listener = try address.listen(.{ .reuse_address = true }); defer listener.deinit(); <code>std.debug.print("Listening on 127.0.0.1:8081...\n", .{}); while (true) { var conn = try listener.accept(); defer conn.stream.close(); std.debug.print("Accepted connection from: {any}\n", .{conn.address}); var server_conn = Connection.init(@constCast(&amp;std.heap.page_allocator), conn.stream.reader().any(), conn.stream.writer().any(), true) catch |err| { std.debug.print("Failed to initialize connection: {}\n", .{err}); continue; }; defer server_conn.deinit(); // Handle connection and errors during the process server_conn.handleConnection() catch |err| { std.debug.print("Error handling connection: {}\n", .{err}); }; std.debug.print("Connection from {any} closed\n", .{conn.address}); } </code> } ```
[]
https://avatars.githubusercontent.com/u/9482395?v=4
struct-env
Hanaasagi/struct-env
2023-05-24T05:24:24Z
deserialize env vars into typesafe structs
master
1
17
3
17
https://api.github.com/repos/Hanaasagi/struct-env/tags
MIT
[ "environment-variables", "zig" ]
23
false
2025-04-03T19:41:08Z
true
true
unknown
github
[]
struct-env 🌱 𝒉𝒂𝒏𝒅𝒍𝒊𝒏𝒈 𝒆𝒏𝒗𝒊𝒓𝒐𝒏𝒎𝒆𝒏𝒕 𝒗𝒂𝒓𝒊𝒂𝒃𝒍𝒆𝒔 𝒊𝒏 𝒂 𝒕𝒚𝒑𝒆-𝒔𝒂𝒇𝒆 𝒘𝒂𝒚. <a></a> <a></a> <strong>NOTE: Supported Zig Version is 0.14.0</strong> What is <code>struct-env</code> <code>struct-env</code> provides a way to handle environment variables using struct fields. Its advantage is the automatic deserialization of environment variables into the specified types. For example, instead of using <code>std.mem.eql(u8, foo, "true")</code> to determine the truth value of an env-var, <code>struct-env</code> allows us to simply use <code>foo: bool</code> to deserialize it into a boolean type. Quick Start Below is a basic example: ```zig const std = @import("std"); const struct_env = @import("struct-env"); const MyEnv = struct { home: []const u8, foo: ?[]const u8, bar: []const u8 = "bar", }; pub fn main() !void { const allocator = std.heap.page_allocator; <code>const env = try struct_env.fromEnv(allocator, MyEnv); defer struct_env.free(allocator, env); std.debug.print("HOME is {s}\n", .{env.home}); std.debug.print("FOO is {any}\n", .{env.foo == null}); std.debug.print("BAR is {s}\n", .{env.bar}); </code> } ``` Here are some examples of this program's output. You can find more examples in the <code>examples</code> directory. <code>$ zig run [file] HOME is /home/username FOO is true BAR is bar</code> <code>$ FOO="foo" BAR="bar" zig run [file] HOME is /home/username FOO is false BAR is bar</code> <code>struct-env</code> assumes that there is an environment variable corresponding to each struct field, with the same name in all uppercase letters. For instance, a struct field <code>foo_bar</code> would be expected to have an environment variable named <code>FOO_BAR</code>. Structs with fields of type Optional(<code>?</code> prefix) can be successfully deserialized even if their associated environment variable is not present. Of course, if the variable does not exist, you can set a default value. <code>struct-env</code> also supports deserializing slice from comma separated env var values. Env-var with common prefix The common pattern for prefixeing env var names for a specific app is supported using the <code>fromPrefixedEnv</code>. Asumming your env vars are prefixed with <code>APP_</code>, the example may look like ```zig const MyEnv = struct { // APP_NAME name : []const u8, }; const env = try struct_env.fromPrefixedEnv(allocator, MyEnv, "APP_"); defer struct_env.free(allocator, env); ``` Supported types: <ul> <li>Built-in types, such as <code>[]const u8</code>, <code>i32</code></li> <li>Optional types, such as <code>?u32</code></li> <li>Slice types, such as <code>[][]const u8</code></li> </ul> License MIT Thanks to those who have helped me on Reddit and Stack Overflow.
[]
https://avatars.githubusercontent.com/u/47036475?v=4
Orng
Rakhyvel/Orng
2023-03-04T02:40:25Z
Orng is a modern systems programming language designed for developers who want fine-grained control without sacrificing expressiveness
main
54
17
3
17
https://api.github.com/repos/Rakhyvel/Orng/tags
MIT
[ "compiler", "compiler-design", "functional-programming", "general-purpose", "language", "language-design", "procedural", "programming", "programming-language", "zig", "ziglang" ]
6,615
false
2025-04-27T05:20:35Z
true
false
unknown
github
[]
<a></a> <em>For When Life Gives You Orngs...</em> Orng Programming Language <blockquote> <strong>⚠️WARNING</strong>! Orng is still a work in progress! Expect exciting changes and improvements. </blockquote> 🍊 What is Orng? Orng is a versatile systems programming language I've been developing that gives developers control without sacrificing expressiveness. It is designed to be both lightweight and simple, making it a great choice for enthusiasts and professionals alike. <ul> <li>Visit <a>the website (coming soon)</a> to learn more about Orng.</li> <li>Tutorials can be found <a>here (coming soon)</a>.</li> <li>Documentation can be found <a>here (coming soon)</a>.</li> </ul> 🚀 Quick Start ```sh Orng compiler requires Zig 0.13.0 at the moment git clone --recursive https://github.com/Rakhyvel/Orng.git Set the Orng Standard Library path environment variable For Linux: export ORNG_STD_PATH="/wherever/you/put/Orng/std" For Windows: $env:ORNG_STD_PATH="/wherever/you/put/Orng/std" Build Orng cd Orng zig build orng ``` A fancy hello-world example: ```rs fn main(sys: System) -&gt; !() { greet("Orng! 🍊", sys.stdout) catch unreachable } fn greet(recipient: String, out: $T impl Writer) -&gt; T::Error!() { try out.&gt;println("Hello, {s}", recipient) } ``` Run it with: <code>sh orng run</code> ✨ Standout Features Orng comes with a wide range of features that make it a powerful and flexible programming language, including: First-Class Types In Orng, types are first class citizens. Pass types as function arguments, return them from functions, and create powerful generic abstractions. ```rs fn make_array_type(const n: Int, const T: Type) -&gt; Type { [n]T } fn main() { let x: template(4, Char) = ('1', '2', '3', '4') println("{c} squared is 9", x[3]) } ``` <a>More examples</a> Parametric Effect System Say goodbye to hidden side effects! Orng forbids global variables and requires all objects to be explicitly passed as parameters, making your program's behavior transparent and predictable. ```rs // We can tell this function doesn't do anything dangerous fn something_harmless(x: T) { /<em> ... </em>/ } // We can tell this function probably mutates it's arguments fn maybe_mutate(x: &amp;mut T) { /<em> ... </em>/ } // We can tell this function probably allocates memory fn maybe_alloc(alloc: impl Allocator) { /<em> ... </em>/ } // We can tell this function probably does stuff with IO fn maybe_write(reader: impl Reader, writer: impl Writer) { /<em> ... </em>/ } ``` Traits Traits offer a flexible way to define behavior that can be attatched to any type. Instead of deep inheritance hierarchies, Orng lets you extend types with new capabilities through simple composable traits. ```rs trait Counter { fn increment(&amp;mut self) -&gt; Int fn total(&amp;self) -&gt; Int fn reset(&amp;mut self) -&gt; () } impl Counter for (count: Int, max: Int) { fn increment(&amp;mut self) -&gt; Int { self.count = (self.count + 1) % self.max self.count } <code>fn total(&amp;self) -&gt; Int { self.count } fn reset(&amp;mut self) -&gt; () { self.count = 0 } </code> } fn main(sys: System) -&gt; !() { let mut counter = (0, 5) try sys.stdout.&gt;println("{d}", counter.&gt;increment()) // Prints 1 try sys.stdout.&gt;println("{d}", counter.&gt;increment()) // Prints 2 } ``` <a>More examples</a> Algebraic Data Types Algebraic Data Types (ADTs) allow you to define types that can be one of several variants with zero runtime overhead. Represent complex state machines, parse abstract syntax trees, or handle error conditons with a single, compact type definition. ```rs const Shape = ( | circle: (radius: Float) | rectangle: (width: Float, height: Float) | triangle: (base: Float, height: Float)) fn calculate_area(shape: Shape) -&gt; Float { match shape { .circle(r) =&gt; 3.14 * r * r .rectangle(w, h) =&gt; w * h .triangle(b, h) =&gt; 0.5 * b * h } } ``` <a>More</a> <a>examples</a> Pattern Matching &amp; Destructuring Pattern matching in Orng lets you elagantly deconstruct complex data structures with a single, readable expression. Forget verbose <code>if-else</code> chains and nested conditionals - match on ADTs, extract values, and handle different cases with unprecedented clarity. ```rs const Person = (name: String, age: Int, job: String) fn classify_person(person: Person) -&gt; String { match person { (name, age, "Teacher") if age &gt; 50 =&gt; "Veteran Educator" (name, <em>, "Doctor") =&gt; "Medical professional" (</em>, age, _) if age &lt; 18 =&gt; "Baby 👶" } } ``` <a>More examples</a> Seamless C Interoperability Compile to C and parse C header files with ease. Orng bridges the gap between low-level system programming and high-level expressiveness. <a>More examples</a> 🤝 Get Involved Contributions of all kinds are welcome: - 🐛 Report bugs - 📝 Improve documentation - 💡 Suggest features - 🧑‍💻 Submit pull requests Check out <a>CONTRIBUTING.md</a> for more info! 📄 License Orng is open-source and released under the MIT License. See <code>LICENSE</code> for details.
[]
https://avatars.githubusercontent.com/u/8823448?v=4
zig-enumerable
lawrence-laz/zig-enumerable
2023-12-19T20:10:14Z
Iterator tools for functional data processing.
main
0
16
0
16
https://api.github.com/repos/lawrence-laz/zig-enumerable/tags
MIT
[ "enumerable", "functional", "iterators", "itertools", "linq", "zig", "zig-package" ]
127
false
2024-08-18T18:01:34Z
true
true
0.13.0
github
[]
Zig Enumerable ⚡ Functional vibes for data processing as sequences. ```zig const std = @import("std"); const enumerable = @import("enumerable"); test "example" { try expectEqualIter( "(1,2,3)", enumerable.from(std.mem.tokenizeAny(u8, "foo=1;bar=2;baz=3", "=;").buffer) .where(std.ascii.isDigit) .intersperse(',') .prepend('(') .append(')'), ); } ``` 📦 Get started <code>bash zig fetch --save https://github.com/lawrence-laz/zig-enumerable/archive/master.tar.gz</code> ```zig // build.zig const enumerable = b.dependency("enumerable", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("enumerable", enumerable.module("enumerable")); ```
[]
https://avatars.githubusercontent.com/u/8604855?v=4
zig-zipf
toziegler/zig-zipf
2023-12-02T10:49:51Z
Zig implementation of a fast, bounded, Zipf-distributed random number generator.
main
0
16
2
16
https://api.github.com/repos/toziegler/zig-zipf/tags
Apache-2.0
[ "random-number-generators", "zig", "zipf" ]
36
false
2025-04-09T10:27:48Z
true
true
unknown
github
[]
Zig Zipf: A Zipf-Distributed RNG Welcome to Zig Zipf! This is a Zig implementation of a fast, discrete, bounded, Zipf-distributed random number generator. Our implementation offers a robust and efficient solution for generating <a>Zipf-distributed</a> numbers, ideal for various applications ranging from statistical modeling, natural language processing, database benchmarking and load testing. Background Our work is a direct port of Jon Gjengset's zipf implementation in Rust, which can be found <a>here</a>. This Rust implementation is itself a port of the Apache Commons' RejectionInversionZipfSampler, originally written in Java. The foundational method for our implementation is sourced from the research by Wolfgang Hörmann and Gerhard Derflinger in their paper "Rejection-inversion to generate variates from monotone discrete distributions," published in ACM Transactions on Modeling and Computer Simulation (TOMACS) 6.3 (1996). Quick Start: Minimal Example Get started quickly with this minimal example in Zig: ```zig const std = @import("std"); const zipf = @import("zipf"); pub fn main() !void { var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.posix.getrandom(std.mem.asBytes(&amp;seed)); break :blk seed; }); const rand = prng.random(); var zipf_distribution = try zipf.ZipfDistribution.init(1000000, 1.07); <code>const number = zipf_distribution.next(&amp;rand); std.debug.print("number {d}", .{number}); </code> } ``` Installation Guide Add the Library with Zon <ol> <li>Declare zig zipf as a dependency in build.zig.zon: <code>zig .dependencies = .{ .zipf = .{ // This can be found by navigating to // https://github.com/toziegler/zig-zipf/releases and obtaining the // link to the tar file for the latest release. .url = "https://github.com/toziegler/zig-zipf/archive/refs/tags/v1.1.tar.gz", .hash = "122041950ce7abb1709e3e4a905429359724f11be50a223b77b9f7c1e4ce6200a942", // You may also leave out the .hash field. This will cause `zig build` // to tell you the correct hash when you go to build your project, and // you can include it here. }, },</code> Release Hashes:</li> <li>v1.1: <code>122041950ce7abb1709e3e4a905429359724f11be50a223b77b9f7c1e4ce6200a942</code></li> <li> v1.0: <code>122003ade97e0a690c28fb264aeedf6958ec57ee94087438dd6d1e7dbcffc7dab461</code> </li> <li> Add the module in <code>build.zig</code> ```diff const exe = b.addExecutable(.{ .name = "zigzipfexample", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); </li> <li> const zipf = b.dependency("zipf", .{ </li> <li>.target = target,</li> <li>.optimize = optimize,</li> <li>});</li> <li>exe.root_module.addImport("zipf", zipf.module("zipf")); ```</li> </ol> Add the Library with Git Submodules <ol> <li> Create a directory for libraries and add Zig Zipf as a submodule: <code>mkdir libs &amp;&amp; cd $_ git submodule add git@github.com:toziegler/zig-zipf.git</code> </li> <li> In your <code>build.zig.zon</code> file, include the following: <code>.dependencies = .{ .zipf = .{ .path = "./libs/zig-zipf/", }, },</code> </li> <li> Finally, in your <code>build.zig</code> file, add the following lines: <code>const zipf = b.dependency("zipf", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zipf", zipf.module("zipf"));</code> </li> </ol>
[]
https://avatars.githubusercontent.com/u/99076655?v=4
ggml-zig
coderonion/ggml-zig
2023-06-25T12:12:54Z
[ ggml: Tensor library for machine learning ] written in zig.
main
1
15
2
15
https://api.github.com/repos/coderonion/ggml-zig/tags
-
[ "aigc", "auto-differentiation", "chatglm", "chatgpt", "deep-learning", "ggml", "gpt", "gpt4", "large-language-models", "llama", "llm", "machine-learning", "tensor", "wizardcoder", "zig", "ziglang" ]
15
false
2025-03-24T07:00:18Z
true
false
unknown
github
[]
ggml-zig Zig bindings for <a>ggml: Tensor library for machine learning</a> .
[]
https://avatars.githubusercontent.com/u/7308253?v=4
confy
heysokam/confy
2023-06-09T21:26:11Z
Comfortable and Configurable buildsystem for C, C++, Zig and Nim
master
0
15
0
15
https://api.github.com/repos/heysokam/confy/tags
GPL-3.0
[ "buildsystem", "c", "configurable", "cpp", "cross-platform", "ergonomic", "nim", "simple", "zig", "zigcc" ]
1,199
false
2025-05-19T03:17:36Z
false
false
unknown
github
[]
confy: Comfortable and Configurable buildsystem Confy is a buildsystem for compiling code with ZigCC. Inspired by SCons, without the issues of a typeless language. You can expect: - Ergonomic, readable and minimal/simple syntax. - Behaves like a library. Build your own binary that runs the compilation commands. - Imperative, not declarative. You own the control flow. - Sane project configuration defaults. - Builds with <code>zig cc</code>. Auto-downloads the latest version for the host. Preview Minimal build file: <code>nim import confy Program.new("hello.c").build.run</code> How to Use <blockquote> TODO: Full <strong>how-to</strong> guide @<a>doc/howto</a> See the <a>examples</a> folder in the meantime </blockquote> Configuration All the configuration variables are stored @<a>confy/cfg.nim</a>. To change them, add <code>cfg.theVariable = value</code> at the top of your <code>build.nim</code> file. <code>nim import confy cfg.dirs.src = "./code" # Changes the source code folder from its default `dirs.root/"src"`. cfg.dirs.bin = "./build" # Changes the binaries output folder from its default `dirs.root/"bin"`. cfg.verbose = on # Makes the cli output information completely verbose. (for debugging) cfg.quiet = on # Makes the cli output information to be as minimal as possible. (for cleaner cli output) (default: on) # Note: verbose = on will ignore quiet being active. (default: off)</code> Design Decisions <blockquote> <em>Summary of: <a>doc/design.md</a></em> </blockquote> Please read the @<a>how to</a> doc before reading this section: Imperative, not Declarative When most people think of a build tool, they think of declarativeness. This is <strong>not</strong> what Confy is. Confy is completely imperative. This is by design. What you tell Confy to do, it will do <strong>immediately</strong>. The core idea driving Confy is to let you fully own your buildsystem. Its your project, and only you can know what your project/tooling needs, and in which exact order. <code>build.nim</code> is not a buildscript Confy is a buildsystem <strong>library</strong>. The premade caller provides you with an easy way to run it as if it was a binary, but confy is, by design, <strong>not</strong> a binary app. <strong>Your build file</strong> <em>(not confy, big difference)</em> will be a full systems binary application, that you compile with nim's compiler <em>(or automated with confy's premade caller)</em> to build your project. Why ZigCC ZigCC comes with all of these features <strong>builtin</strong>, out of the box. No extra setup: - Automatic Caching - Cross-platform Cross-compilation <em>(from any system to any system, not just some to some)</em> - Auto-dependency resolution - Preconfigured Sanitization - Sane and Modern optimization defaults - Pre-packed libc ... and all of that fits in a self-contained 50mb download.... !! Compare that to setting up gcc/mingw/msys/msvc/clang/osxcross ... etc, etc, etc There is a clear winner here.
[]
https://avatars.githubusercontent.com/u/1159529?v=4
turnip
linuxy/turnip
2023-03-28T16:48:59Z
An embedded virtual file system for games and other projects
main
0
15
0
15
https://api.github.com/repos/linuxy/turnip/tags
-
[ "filesystem", "squashfs", "zig" ]
51
false
2025-04-26T18:04:56Z
true
false
unknown
github
[]
turnip An embedded virtual file system for games and other projects Builds against zig 0.11.0-dev.2477+2ee328995+ <code>git clone --recursive https://github.com/linuxy/turnip.git</code> Example integration: https://github.com/linuxy/coyote-snake/tree/turnip To package assets in folder assets (zig-out output): * <code>zig build assets</code> To build examples * <code>zig build -Dexamples=true</code> To build coyote-snake example (from branch) * <code>zig build -Dgame=true</code> Integrating Turnip in your project build.zig ```Zig const std = @import("std"); const turnip = @import("vendor/turnip/build.zig"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); <code>turnip.squashFsTool(b, target, optimize); if(b.option(bool, "game", "Build game") == true) buildGame(b, target, optimize); </code> } pub fn buildGame(b: *std.Build, target: std.zig.CrossTarget, optimize: std.builtin.OptimizeMode) void { <code>const exe = b.addExecutable(.{ .root_source_file = .{ .path = "src/coyote-snake.zig"}, .optimize = optimize, .target = target, .name = "snake", }); exe.linkLibC(); //Turnip exe.addModule("turnip", turnip.module(b)); exe.main_pkg_path = "."; turnip.squashLibrary(b, exe, target, optimize); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the app"); run_step.dependOn(&amp;run_cmd.step); </code> } ``` game.zig ```Zig const Turnip = @import("turnip").Turnip; var embedded_assets = @embedFile("../zig-out/assets.squashfs"); //Initialize &amp; load turnip assets self.assets = Turnip.init(); try self.assets.loadImage(embedded_assets, 0); //Read texture from virtual FS pub inline fn loadTexture(game: <em>Game, path: []const u8) !?</em>c.SDL_Texture { var buffer: [1024:0]u8 = std.mem.zeroes([1024:0]u8); var fd = try game.assets.open(@ptrCast([*]const u8, path)); <code>var data: []u8 = &amp;std.mem.zeroes([0:0]u8); var size: c_int = 0; while(true) { var sz = @intCast(c_int, try game.assets.read(fd, &amp;buffer, 1024)); if(sz &lt; 1) break; data = try std.mem.concat(allocator, u8, &amp;[_][]const u8{ data, &amp;buffer }); size += sz; } defer allocator.free(data); var texture = c.IMG_LoadTexture_RW(game.renderer, c.SDL_RWFromMem(@ptrCast(?*anyopaque, data), size), 1) orelse { c.SDL_Log("Unable to load image: %s", c.SDL_GetError()); return error.SDL_LoadTexture_RWFailed; }; try game.assets.close(fd); return texture; </code> } ```
[]
https://avatars.githubusercontent.com/u/39483951?v=4
efm32-freertos-zig
FranciscoLlobet/efm32-freertos-zig
2023-06-13T05:46:16Z
MISO an embedded Zig IoT example
master
0
15
0
15
https://api.github.com/repos/FranciscoLlobet/efm32-freertos-zig/tags
NOASSERTION
[ "iot", "lwm2m", "mcuboot", "microzig", "mqtt-c", "mqtt-client", "tls", "zig", "ziglang" ]
25,493
false
2025-04-21T17:08:55Z
true
true
unknown
github
[ { "commit": "c6c9ec4516f57638e751141085c9d76120990312.tar.gz", "name": "microzig", "tar_url": "https://github.com/ZigEmbeddedGroup/microzig/archive/c6c9ec4516f57638e751141085c9d76120990312.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/ZigEmbeddedGroup/microzig" } ]
MISO <code>MISO</code> is an example application that combines the power of the <a>Zig programming language</a> together with a curated selection of services supported by the XDK110 sensor. Status <a></a> <blockquote> zig-build passing means that a binary build is possible. Further testing on target is necessary. </blockquote> Disclaimers <code>MISO</code> is not affiliated with LEGIC Identsystems Ltd, the LEGIC XDK Secure Sensor Evaluation Kit, the Rust Foundation or the Rust Project. Furthermore, it's important to note that this codebase should not be used in use cases which have strict safety and/or availability requirements. Important documents <ul> <li><a>LICENSE.md</a></li> <li><a>CONTRIBUTING.md</a></li> </ul> What's inside? The current version of <code>MISO</code> boasts a set of features, including: <ul> <li>read configuration files from a SD card,</li> <li>provide configuration persistance using non-volatile memory (NVM),</li> <li>connect to a designated WiFi AP,</li> <li>get a sNTP timestamp from an internet server and run a real-time clock (RTC) with seconds (s) resolution,</li> <li>provide a HTTP file download client for firmware updates</li> <li>mbedTLS PSK and x509 certificate authentication tested with TLS (MQTTS) and DTLS (COAPS),</li> <li>HW Watchdog (7s idle timeout)</li> <li>Bootloader with support for MCUBoot firmware containers</li> </ul> Either a binary with LwM2M via secure COAP (DTLS) or MQTT via TLS can be loaded at a time. Main bugs <ul> <li>The LwM2M client will do a watchdog reset after approximately 7 minutes.</li> <li>The current architecture is dependent on FreeRTOS.</li> <li>Current no entropy is being queried when starting MbedTLS functionality.</li> </ul> Wish List <ul> <li>Implementation of SimpleLink File Storage</li> <li>Stability improvements of the LwM2M client</li> <li>Stability improvements of the connection manager</li> <li>Memory optimization of statically allocated memory.</li> <li>Improvements on documentation.</li> <li>Programming via openOCD</li> <li>Programming scripts via console</li> <li>HTTP deployment script for FW update</li> <li>MQTT FW update</li> </ul> Non-Features For design, and legal reasons, the following hardware capabilities of the XDK110 will not be supported: <ul> <li>BLE</li> <li>Light Sensor</li> <li>Acoustic sensor / Microphone AKU340</li> <li>Other IP protocols</li> </ul> Project Setup Zig Download and install the Zig Compiler <ul> <li><a>Zig Getting-Started</a></li> <li><a>Download Zig</a></li> </ul> Installation Hints <blockquote> This software has been tested using the <a>Windows x86-64Bit 0.11.0</a>, macOS (via brew) and <a>python ziglang</a> builds. </blockquote> Install the Arm GNU Toolchain <blockquote> The Arm GNU Toolchain is now optional for building since <code>MISO</code>'s move to <code>picolibc</code>. </blockquote> Install the Arm GNU toolchain if debugging the code is required. https://developer.arm.com/downloads/-/arm-gnu-toolchain-downloads Picolibc Picolibc is provided precompiled using the clang compiler on Ubuntu WSL. Code Checkout Perform a recursive clone: <code>shell git clone --recursive https://github.com/FranciscoLlobet/efm32-freertos-zig.git</code> Alternatively clone and update submodules: <code>shell git clone https://github.com/FranciscoLlobet/efm32-freertos-zig.git cd .\efm32-freertos-zig\ git submodule init git submodule update</code> Build and deploy <code>powershell zig build</code> <code>zig build</code> will build the binaries for: <ul> <li><a><code>boot.bin</code></a> (bootloader)</li> <li><a><code>lwm2m.bin</code></a> (LwM2M app)</li> <li><a><code>mqtt.bin</code></a> (MQTT app)</li> </ul> And the corresponding <code>elf</code> files for direct debugger (SWD) deployment. <blockquote> Links only work in your local system after build </blockquote> If using the python-based <code>ziglang</code> package: <blockquote> <code>python -m ziglang build</code> </blockquote> Automatization and tasks The automatization toolchain requires Python 3.x and modules like <code>invoke</code>/<code>ìnv</code>, <code>doit</code>. Furthermore it also requires a working copy of <code>OpenSSL</code> Automatisation See the <a><code>zig-build.yml</code></a> Github workflow for the current automatisation workflow Tasks Base dependencies Get the tooling dependencies <code>console python -m pip install --upgrade pip setuptools wheel -r requirements.txt</code> mcuboot dependencies <code>console inv get-mcuboot-deps</code> Generate private FW signing key To generate the firmware signing key: <code>console inv private-key</code> <blockquote> Keep the private key safe. </blockquote> Sign and verify FW images <ul> <li>Via invoke:</li> </ul> <code>console inv sign-fw-images</code> <ul> <li>Via do-it:</li> </ul> <code>console doit</code> Used 3rd party software Base Tooling <ul> <li><a>MicroZig</a></li> <li><a>regz</a></li> <li><a>picolibc</a></li> </ul> MCAL and MCU peripheral services <ul> <li><a>EFM32 Gecko SDK</a></li> </ul> RTOS <ul> <li><a>FreeRTOS</a></li> </ul> Firmware Container <ul> <li><a>MCUBoot</a></li> </ul> Crypto and (D)TLS provider <ul> <li><a>mbedTLS</a></li> </ul> Wifi Connectivity <ul> <li><a>TI Simplelink CC3100-SDK</a></li> </ul> Filesystem <ul> <li><a>FatFs 15</a>.</li> </ul> Utils <ul> <li><a>jsmn</a>. Jsmn, a very simple JSON parser.</li> </ul> Protocol Providers <ul> <li><a>Paho MQTT Embedded-C</a>. MQTT v3.1.1 protocol service.</li> <li><a>Wakaama</a>. LWM2M protocol service.</li> <li><a>PicoHTTParser</a>. Tiny HTTP request and response parser.</li> </ul> Bosch SensorTec Sensor APIs <ul> <li>BMA2-Sensor-API</li> <li>BME280_driver</li> <li>BMG160_driver</li> <li>BMI160_driver</li> <li>BMM150-Sensor-API</li> </ul> Configuration fields Configuration can be loaded via SD card by <code>config.txt</code> | Field | Description | Type | | |----------------|------------------------|-----------------------|----------------------| | wifi.ssid | Wifi WPA2 SSID | String | Mandadory | | wifi.key | Wifi WPA2 SSID Key | String | Mandatory | | lwm2m.endpoint | LWM2M endpoint | String | If LwM2M is compiled | | lwm2m.uri | LWM2M Server Uri | URI String | If LwM2M is compiled | | lwm2m.psk.id | LwM2M DTLS Psk ID | String | Optional | | lwm2m.psk.key | LwM2M DTLS PSK Key | Base64 encoded String | Optional | | ntp.url[] | sNTP server URI/URL | URI String Array | Not implemented | | http.uri | Firmware image URI | URI String | Mandatory | | http.key | Firmware public key | Base64 encoded string | Mandatory | <code>json { "wifi": { "ssid": "WIFI_SSID", "key": "WIFI_KEY" }, "lwm2m": { "endpoint": "LWM2M_DEVICE_NAME", "uri": "coaps://leshan.eclipseprojects.io:5684", "psk": { "id": "LWM2M_DTLS_PSK_ID", "key": "LWM2M_DTLS_PSK_KEY_BASE64" }, "bootstrap": false, }, "ntp": { "url": [ "0.de.pool.ntp.org", "1.de.pool.ntp.org" ] }, "mqtt": { "url": "mqtts://MQTT_BROKER_HOST:8883", "device": "MQTT_DEVICE_ID", "username": "MQTT_USER_NAME", "password": "MQTT_PASSWORD", "psk": { "id": "MQTT_PSK_TLS_ID", "key": "MQTT_PSK_TLS_KEY_BASE64" }, "cert": { "client": "MQTT_CERT", "server_cert": "MQTT_SERVER_C" } }, "http": { "url": "http://HTTP_HOST:80/app.bin", "key": "APP_PUB_KEY_BASE64" } }</code> Signature Algorithms <code>MISO</code> uses elliptic curve cryptography for signature creation and validation of configuration and firmware images using the ECDSA (<em>Eliptic Curve Digital Signature Algorithm</em>). Parameters: <ul> <li><code>P-256</code> Weierstrass curve</li> <li><code>prime256v1</code>(OpenSSL)</li> <li><code>secp256r1</code>(mbedTLS)</li> <li><code>SHA256</code> hash digest.</li> </ul> <blockquote> The algorithms have been tested using OpenSSL on host (MacOS, Win11) and mbedTLS on target (EFM32/XDK110) </blockquote> Encryption Algorithms and TLS Cyphersuites PSK Cyphersuite AES-Based Suites <ul> <li>TLS_PSK_WITH_AES_128_GCM_SHA256</li> <li>TLS_PSK_WITH_AES_128_CCM_8</li> <li>TLS_PSK_WITH_AES_128_CCM</li> </ul> ECDHE <ul> <li>TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8</li> <li>TLS_ECDHE_ECDSA_WITH_AES_128_CCM</li> </ul> Eliptic curves <ul> <li>MBEDTLS_ECP_DP_SECP256R1_ENABLED</li> </ul> Reference <ul> <li><a>https://wiki.openssl.org/index.php/Command_Line_Elliptic_Curve_Operations</a></li> </ul> Firmware Update To perform a firmware update, the <code>MISO</code> application needs to fetch an unecrypted firmware image signed in a MCUboot container These files can be stored in a HTTP server that must support <a>range requests</a> for the downloads. The public key is provided in the configuration file. The firmware update process takes the firmware container and the locally stored public key to perform the validation. <blockquote> FW download has been tested on a non-public (https://nginx.org) server. </blockquote> Notes <blockquote> <strong>Some of following actions actions have also corresponding <code>inv</code> tasks described previously.</strong> </blockquote> Generate the private key <blockquote> This is an example using openssl. Please keep the private key secret and offline. </blockquote> <code>console openssl ecparam -genkey -name prime256v1 -noout -out fw_private_key.pem</code> Public Key in PEM Format Generate the public key in PEM format. <code>console openssl ec -in fw_private_key.pem -pubout -out fw.pub</code> Public Key in DER Format <code>console openssl ec -in fw_private_key.pem -pubout -outform DER -out fw.der</code> Convert DER to Base64 <code>console openssl base64 --in fw.der --out fw.b64</code> Use the base64 output as a one-line string in the config (<code>http.key</code>) Generate FW container Use the MCUBoot <a><code>imgtool</code></a> script to sign and generate the fw container. The firmware container header is <code>0x80</code> (128) bytes long and the start address is currently <code>0x40000</code> (256kB) <code>console python .\csrc\mcuboot\mcuboot\scripts\imgtool.py sign -v "0.1.2" -F 0x40000 -R 0xff --header-size 0x80 --pad-header -k .\fw_private_key.pem --overwrite-only --public-key-format full -S 0xB0000 --align 4 .\zig-out\firmware\lwm2m.bin lwm2m_sig.bin</code> Verify the content of the firmware container. <code>console python .\csrc\mcuboot\mcuboot\scripts\imgtool.py dumpinfo .\lwm2m_sig.bin</code> Configuration signature Sign Configuration For signing the configuration, please create a private key <code>console openssl ecparam -genkey -name prime256v1 -noout -out private_key.pem</code> Generate the public key <code>console openssl ec -in private_key.pem -pubout -out config.pub</code> <ul> <li><code>private_key.pem</code> a private key used for signing the configuration.</li> <li><code>config.pub</code> a public key used for signing the configuration.</li> <li><code>config.sig</code> a signature file.</li> </ul> <code>console openssl dgst -sha256 -sign private_key.pem -out config.sig config.txt</code> Verify Configuration <code>console openssl dgst -sha256 -verify config.pub -signature config.sig config.txt</code> Build picolibc <code>console meson setup --cross-file scripts/cross-clang-thumbv7m-none-eabi-miso.txt --optimization 2 ./build --wipe</code>
[]
https://avatars.githubusercontent.com/u/6756180?v=4
sokol-d
kassane/sokol-d
2023-12-11T19:41:35Z
D bindings for the sokol headers (https://github.com/floooh/sokol)
main
7
15
4
15
https://api.github.com/repos/kassane/sokol-d/tags
Zlib
[ "bindings", "cross-platform", "d", "dlang", "emscripten", "sokol", "wasm", "zig" ]
2,563
false
2025-05-21T16:08:17Z
true
true
unknown
github
[ { "commit": "v1.91.9", "name": "imgui", "tar_url": "https://github.com/floooh/dcimgui/archive/v1.91.9.tar.gz", "type": "remote", "url": "https://github.com/floooh/dcimgui" }, { "commit": "4.0.7", "name": "emsdk", "tar_url": "https://github.com/emscripten-core/emsdk/archive/4.0.7....
<a></a> <a></a> Auto-generated <a>D</a> bindings for the <a>sokol headers</a>. Targets <ul> <li>Native</li> <li>Wasm (<code>-Dtarget=wasm32-emscripten-none</code>) - LTO enabled on release-mode.</li> </ul> By default, the backend 3D API will be selected based on the target platform: <ul> <li>macOS: Metal</li> <li>Windows: D3D11</li> <li>Linux: GL</li> </ul> BUILD <strong>Required</strong> <ul> <li><a>zig</a> v0.14.0 or master</li> <li><a>ldc</a> v1.40.0 or latest-CI (nightly)</li> </ul> Supported platforms are: Windows, macOS, Linux (with X11) On Linux install the following packages: libglu1-mesa-dev, mesa-common-dev, xorg-dev, libasound-dev (or generally: the dev packages required for X11, GL and ALSA development) ```bash build sokol library + all examples [default: static library] zig build build sokol shared library + all examples zig build -Dshared build sokol library only zig build -Dartifact Run Examples zig build run-blend zig build run-bufferoffsets zig build run-clear zig build run-cube zig build run-debugtext zig build run-mrt zig build run-saudio zig build run-instancing zig build run-offscreen zig build run-sgl_context zig build run-sgl_points zig build run-user_data zig build run-noninterleaved zig build run-texcube zig build run-quad zig build run-triangle zig build run-shapes zig build run-vertexpull zig build run-imgui -Dimgui # optional: -Dimgui-version=docking zig build run-droptest -Dimgui # optional: -Dimgui-version=docking zig build --help Project-Specific Options: -Dgl=[bool] Force OpenGL (default: false) -Dgles3=[bool] Force OpenGL ES3 (default: false) -Dwgpu=[bool] Force WebGPU (default: false, web only) -Dx11=[bool] Force X11 (default: true, Linux only) -Dwayland=[bool] Force Wayland (default: false, Linux only, not supported in main-line headers) -Degl=[bool] Force EGL (default: false, Linux only) -Dimgui=[bool] Add support for sokol_imgui.h bindings -Dsokol_imgui_cprefix=[string] Override Dear ImGui C bindings prefix for sokol_imgui.h (see SOKOL_IMGUI_CPREFIX) -Dcimgui_header_path=[string] Override the Dear ImGui C bindings header name (default: cimgui.h) -Dimgui-version=[enum] Select ImGui version to use Supported Values: default docking -Dubsan=[bool] Enable undefined behavior sanitizer -Dtsan=[bool] Enable thread sanitizer -Dartifact=[bool] Build artifacts (default: false) -DbetterC=[bool] Omit generating some runtime information and helper functions (default: false) -DzigCC=[bool] Use zig cc as compiler and linker (default: false) -Dshaders=[bool] Build shaders (default: false) -Dtarget=[string] The CPU architecture, OS, and ABI to build for -Dcpu=[string] Target CPU features to add or subtract -Dofmt=[string] Target object format -Ddynamic-linker=[string] Path to interpreter on the target system -Doptimize=[enum] Prioritize performance, safety, or binary size Supported Values: Debug ReleaseSafe ReleaseFast ReleaseSmall -Dshared=[bool] Build sokol dynamic library (default: static) <code>`` (also run</code>zig build -l` to get a list of build targets) Shaders Checkout <a>sokol-tools</a> for a sokol shader pipeline! It supports these D bindings and all shaders in the examples folder here have been compiled using it with <code>-f sokol_d</code>! <code>bash zig build -Dshaders # (re)generate D bindings from shaders.</code> License and attributions This code is released under the zlib license (see <a>LICENSE</a> for info). Parts of <code>gen_d.py</code> have been copied and modified from the zig-bindings<a>^1</a> and rust-bindings<a>^2</a> for sokol. The sokol headers are created by Andre Weissflog (floooh) and sokol is released under its own license<a>^3</a>.
[]
https://avatars.githubusercontent.com/u/15308111?v=4
i18n-experiment
Vexu/i18n-experiment
2023-05-15T23:14:56Z
An experiment at creating an translation library for use with Zig.
main
0
14
0
14
https://api.github.com/repos/Vexu/i18n-experiment/tags
MIT
[ "i18n", "zig" ]
70
false
2025-02-20T07:40:33Z
true
false
unknown
github
[]
i18n experiment An experiment at creating an translation library for use with Zig. One goal is that starting to use this should be as easy as replacing all instances like <code>writer.print("...", .{...})</code> with <code>i18n.format(writer, "...", .{...})</code> where the format string becomes the key for translation. Translations are specified in <code>$LOCALE.def</code> files so for code like <code>zig i18n.format(writer, "Hello {s}!", .{name});</code> A finnish translation file <code>fi_FI.def</code> would contain something like: ``` Comment explaining something about this translation def "Hello {%name}!" "Moikka {%name}!" end ```
[]
https://avatars.githubusercontent.com/u/988098?v=4
barely-http2
richiejp/barely-http2
2023-04-30T13:38:25Z
Barely working HTTP/2 Zig library
main
0
14
0
14
https://api.github.com/repos/richiejp/barely-http2/tags
-
[ "http2", "static-site-server", "zig" ]
28
false
2025-01-23T20:20:40Z
false
false
unknown
github
[]
Barely HTTP/2 in Zig Something like the minimum Zig implementation of HTTP/2 to serve a request from Curl. I still need to use TLS and ALPN to get browsers working. There are quite some comments in the source code and a blog article: https://richiejp.com/barely-http2-zig This is for a follow on article to: https://richiejp.com/zig-vs-c-mini-http-server Serve files Run the following ```sh $ zig run src/self-serve2.zig -- /static/site info: Listening on 127.0.0.1:9000; press Ctrl-C to exit... ``` Then in a different terminal <code>sh $ curl -s -v --http2-prior-knowledge http://localhost:9000</code> Just print frame info A second entry point in the main lib just prints the HTTP/2 frames it receives. <code>sh $ zig run src/http2.zig</code>
[]
https://avatars.githubusercontent.com/u/1552770?v=4
thespian
neurocyte/thespian
2024-02-08T22:09:11Z
thespian: an actor library for Zig, C & C++ applications
master
0
14
1
14
https://api.github.com/repos/neurocyte/thespian/tags
MIT
[ "actor-model", "cpp", "zig", "zig-package" ]
218
false
2025-04-30T14:07:53Z
true
true
unknown
github
[ { "commit": "1fccb83c70cd84e1dff57cc53f7db8fb99909a94.tar.gz", "name": "cbor", "tar_url": "https://github.com/neurocyte/cbor/archive/1fccb83c70cd84e1dff57cc53f7db8fb99909a94.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/neurocyte/cbor" }, { "commit": "24d28864ec5aae6146d88...
Thespian Fast &amp; flexible actors for Zig, C &amp; C++ applications To build: <code>./zig build</code> See <code>tests/*</code> for many interesting examples.
[ "https://github.com/neurocyte/flow" ]
https://avatars.githubusercontent.com/u/34946442?v=4
stitch
cryptocode/stitch
2023-03-26T17:04:23Z
Append resources to your executables
main
0
14
0
14
https://api.github.com/repos/cryptocode/stitch/tags
MIT
[ "zig", "zig-library", "zig-package" ]
50
false
2025-05-09T15:04:12Z
true
true
unknown
github
[]
&nbsp; &nbsp; Stitch is a tool and library for Zig and C for adding and retrieving resources to and from executables. Why not just use <code>@embedFile</code> / <code>#embed</code>? Stitch serves a different purpose, namely to let build systems, and <em>users</em> of your software, create self-contained executables. For example, instead of requiring users to install an interpreter and execute <code>mylisp fib.lisp</code>, they can simply run <code>./fib</code> or <code>fib.exe</code> Resoures can be anything, such as scripts, images, text, templates config files and other executables. Some use cases <ul> <li>Self extracting tools, like an installer</li> <li>Create executables for scripts written in your interpreted programming language</li> <li>Include a sample config file, which is extracted on first run. The user can then edit this.</li> <li>An image in your own format that's able to display itself when executed</li> </ul> Building the project To build with Zig 0.13, use the <code>zig-&lt;version&gt;</code> tag/release. To build with Zig 0.14 or master, use the main branch (last tested with Zig version <code>0.15.0-dev.11+5c57e90ff</code>) <code>zig build</code> will put a <code>bin</code> and <code>lib</code> directory in your output folder (e.g. zig-out) <ul> <li>bin/stitch is a standalone tool for attaching resources to executables. This can also be done programmatically using the library</li> <li>lib/libstitch is a library for reading attached resources from the current executable, and for adding resources to executables (like the standalone tool)</li> </ul> Using the tool This example adds two scripts to a Lisp interpreter that supports, through the stitch library, reading embedded scripts: ```bash stitch ./mylisp std.lisp fib.lisp --output fib ./fib 8 21 ``` Resources can be named explicitly <code>bash stitch ./mylisp std=std.lisp fibonacci=fib.lisp --output fib</code> If a name is not given, the filename (without path) is used. The stitch library supports finding resources by name or index. The <code>--output</code> flag is optional. By default, resources are added to the original executable (first argument) Stitching programmatically Let's say you want your interpreted programming language to support producing binaries. An easy way to do this is to create an interpreter executable that reads scripts attached to itself using stitch. You can provide interpreter binaries for all the OS'es you wanna support, or have the Zig build file do this if your user is building the interpreter. In the example below, a Lisp interpreter uses the stitch library to support creating self-contained executables: <code>bash ./mylisp --create-exe sql-client.lisp --output sql-client</code> The resulting binary can now be executed: <code>./sql-client</code> You can make the <code>mylisp</code> binary understand stitch attachments and then make a copy of it and stitch it with the scripts. Alternatively, you can have separate interpreter binaries specifically for reading stitched scripts. Using the library from C Include the <code>stitch.h</code> header and link to the library. Here's an example, using the included C test program: <code>bash zig build-exe c-api/test/c-test.c -Lzig-out/lib -lstitch -Ic-api/include ./c-test</code> Binary layout The binary layout specification can be used by other tools that wants to parse files produced by Stitch, without using the Stitch library. <a>Specification</a>
[]
https://avatars.githubusercontent.com/u/88117897?v=4
CortexC
alvarorichard/CortexC
2023-07-19T03:01:10Z
Interpreter is a minimalist yet powerful tool designed to interpret and execute a subset of the C programming language.
main
0
13
1
13
https://api.github.com/repos/alvarorichard/CortexC/tags
MIT
[ "binary", "c", "education", "evaluation", "intepreter", "interpreter", "open-source", "parsing", "programming-language", "tokenization", "zig" ]
24,306
false
2024-12-24T17:51:07Z
true
false
unknown
github
[]
Simple C Interpreter <a></a> <a></a> <a></a> <a></a> This repository contains a simple interpreter for a subset of the C language, written in C itself. It includes a tokenizer, a parser, and an evaluator for assembly instructions. The interpreter is capable of interpreting and running simple C programs, but it does not support all features of the C language. Overview The interpreter is divided into several parts: <ul> <li> Definitions and Enumerations: The code starts with the definition of several constants and structures that are used throughout the program. It also defines a number of enumerations that represent different types of tokens that can be encountered in the input code. </li> <li> Tokenization: The next() function is responsible for tokenizing the input code. It reads characters from the input and classifies them into different types of tokens. </li> <li> Expression Parsing: The expr() and factor() functions are used for parsing expressions in the input code. However, these functions are not fully implemented in the provided code. </li> <li> Program Parsing: The program() function is responsible for parsing the entire program. It repeatedly calls the next() function to get tokens and processes them accordingly. </li> <li> Evaluation: The eval() function is an interpreter for the assembly instructions. It reads and executes the instructions one by one. </li> <li> Main Function: The main() function is the entry point of the program. It initializes the necessary data structures, reads the input code from a file, calls the program() function to parse the code, and finally calls the eval() function to execute the parsed code. </li> </ul> How to use the interpreter To use the interpreter, you need to have a C compiler installed on your system. You can compile the interpreter itself using the following command: Clone this repository and compile the interpreter using the following command: <code>bash git clone https://github.com/alvarorichard/CortexC.git</code> Navigate to the directory containing the source code: <code>bash cd CortexC</code> Compile the source code using the following command: <code>bash clang main.c -lfunction_parameter -o main</code> Then, you can use the compiled interpreter to interpret and run a C program as follows: <code>bash zig build</code> Please note that the interpreter is quite simple and may not support all features of the C language. Also, the code seems to be incomplete and may not work correctly as is. For example, the expr() and factor() functions are not fully implemented. Contributing Contributions are welcome! If you find a bug or want to add a new feature, feel free to create a pull request.
[]
https://avatars.githubusercontent.com/u/22280250?v=4
zon_get_fields
Durobot/zon_get_fields
2023-12-27T18:10:39Z
Utility functions to get field values from the abstract syntax tree generated from ZON (Zig Object Notation) text using Zig stdlib
main
0
13
3
13
https://api.github.com/repos/Durobot/zon_get_fields/tags
MIT
[ "zig", "zig-package", "ziglang", "zon" ]
192
false
2025-05-05T08:19:00Z
true
true
0.12.0-dev.3097+5c0766b6c
github
[]
zon_get_fields Several functions to facilitate the process of walking Abstract Syntax Trees (ASTs) generated from <a>ZON</a> text, and fetch the values of the fields from the AST. But first you have to call <code>std.zig.Ast.parse</code> to tokenize and parse your ZON, creating the AST. Updated to work with and tested with Zig <strong>0.14.0-dev.3046+08d661fcf</strong>. The latest commit is not going to work with earlier versions of Zig 0.14.0-dev, because of the breaking changes in lib/std/builtin.zig (change of names of struct fields, like <code>Array.sentinel</code> to <code>sentinel_ptr</code> or <code>StructField.default_value</code> to <code>default_value_ptr</code>). Support for older versions, like Zig <strong>0.12.0</strong>, <strong>0.12.1</strong>, <strong>0.13.0</strong>, and <strong>0.14.0-dev.91+a154d8da8</strong> was dropped because of <a>this breaking change in the standard library</a>. If you need a version of zon_get_fields that works with older Zig versions, <a>get this release</a>. It still probably won't work with Zig 0.11, but you're welcome to try it and report back, although I'm not too keen on backporting. <strong>zon_get_fields</strong> is licensed under the <a>the MIT License</a>. You are more than welcome to drop <code>zon_get_fields.zig</code> into your project (don't forget to <code>const zgf = @import("zon_get_fields.zig");</code>), or you can use the Zig package manager: <ol> <li>In your project's <code>build.zig.zon</code>, in <code>.dependencies</code>, add</li> </ol> <code>zig .zon_get_fields = .{ .url = "https://github.com/Durobot/zon_get_fields/archive/&lt;GIT COMMIT HASH, 40 HEX DIGITS&gt;.tar.gz", .hash = "&lt;ZIG PACKAGE HASH, 68 HEX DIGITS&gt;" // Use arbitrary hash, get correct hash from the error }</code> <ol> <li>In your project's <code>build.zig</code>, in <code>pub fn build</code>, before <code>b.installArtifact(exe);</code>, add</li> </ol> <code>zig const zgf = b.dependency("zon_get_fields", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zon_get_fields", zgf.module("zon_get_fields"));</code> <ol> <li> Add <code>const zgf = @import("zon_get_fields");</code>in your source file(s). </li> <li> Build your project with <code>zig build</code>, as you normally do. </li> </ol> Things I like: <ol> <li>Hey, it works! At least it looks like it does, and since nothing like this exists in the standard library, I consider it a success;</li> <li>You can throw your struct and an AST at a function (<code>pub fn zonToStruct</code>), and have your struct filled with data. The fields that have matching values in the provided AST, that is, and you get to know what was filled and what was not - look and the returned struct;</li> <li>Or you can fetch the values of the fields you need using string paths to indicate them, calling <code>pub fn getFieldVal</code>. It's fine if all you need is a couple of fields;</li> <li>All the basics are covered - signed and unsigned integers and floats, strings, single characters, booleans, nested structs, arrays, arrays of arrays, arrays of structs (in fact, any combination of structs and arrays should work).</li> </ol> Things I don't really like: <ol> <li>No AST validity verification. Thinking about ZON schemas or similar in the future, maybe?</li> <li>If you use the second approach, <code>pub fn getFieldVal</code>, for every field you want to read you've got to specify the path. The path is split, the AST is walked, and if you have rather large structures to fetch, a lot of this work is repeated for each field. Not the best approach performance-wise. But you can switch to <code>pub fn zonToStruct</code>, which fills all the fields it can it one go;</li> <li>An ugly hack that I had to use in order to get negative values from the fields, both integers and floating point. See <code>fn fulllTokenSlice</code>. I can't be sure my approach works correctly in all situations, or will continue to work in the future, so I feel really uneasy about using it;</li> </ol> For examples of how to use them, turn to the test sections in <code>zon_parse.zig</code>: <ol> <li>Find <code>zonToStruct Tests</code> <a>comment</a> for <code>pub fn zonToStruct</code> approach - filling your struct all at once;</li> <li>Find <code>getFieldVal Tests</code> <a>comment</a> for <code>pub fn getFieldVal</code>approach - fetching field values one by one, as you provide string paths to each field.</li> </ol> Or check out the short examples below (you can compile and run them with <code>zig build example_zon_to_struct</code> and <code>zig build example_get_field_val</code> commands). Say you've got this ZON file (<code>my.zon</code>): <code>zon .{ .database = .{ .host = "127.0.0.1", .port = 5432, .user = "superadmin", .password = "supersecret", }, .decimal_separator = '.', .months_in_year = 12, .newline_char = '\n', .pi = 3.14159265359, .hello = "こんにちは", .unicode_char = '⚡', .primes = .{ 2, 3, 5, 7, 11 }, .factorials = .{ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800 }, .slc_of_structs = .{ .{ .ham = 10, .eggs = 2 }, .{ .ham = 5 } }, .slc_of_arrays = .{ .{ 10, 20, 30 }, .{ 40, 50, }, }, .slc_of_slices = .{ .{ 1, 2, 3 }, .{ 4, 5 }, .{ 6 } } }</code> Then you can either: 1. Define a struct, pass a pointer to it together with AST built from <code>my.zon</code> to pub <code>fn zonToStruct</code>, get your struct filled, and get a report struct which mirrors the fields of your struct, indicating whether they were filled or not (see <a>this table</a> for report struct field types): ```zig const std = @import("std"); const zgf = @import("zon_get_fields.zig"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocr = gpa.allocator(); <code>// `Ast.parse` requires a sentinel (0) terminated slice, so we pass 0 as the sentinel value (last arg) const zon_txt = try std.fs.cwd().readFileAllocOptions(allocr, "my.zon", std.math.maxInt(usize), null, @alignOf(u8), 0); defer allocr.free(zon_txt); var ast = try std.zig.Ast.parse(allocr, zon_txt, .zon); defer ast.deinit(allocr); const MyStruct = struct // Field order is not important { const DatabaseSettings = struct { host: []const u8 = &amp;.{}, // Since this is a slice of _const_ u8, // it will be addressing the string in ast.source port: u16 = 0, user: []u8 = &amp;.{}, // Having a slice field requires passing a non-null allocator // to zonToStruct, and freeing `user` when we're done password: [20]u8 = [_]u8 {33} ** 20, // This array is filled with string/array elements up // to this field's capacity, or padded with 0 bytes, // if ZON string/array hasn't got enough elements }; const MyStruct = struct { ham: u32 = 0, eggs: u32 = 0 }; database: DatabaseSettings = .{}, decimal_separator: u8 = 0, months_in_year: u8 = 0, newline_char: u8 = 0, pi: f64 = 0.0, hello: []const u8 = &amp;.{}, // Same as hello: []const u8 = undefined; hello.len = 0; unicode_char: u21 = 0, primes: [10]u8 = [_]u8 { 0 } ** 10, factorials: [10]u32 = [_]u32 { 0 } ** 10, slc_of_structs: []MyStruct = &amp;.{}, slc_of_arrays: [][3]u32 = &amp;.{}, slc_of_slices: [][]u32 = &amp;.{}, }; var ms = MyStruct {}; // We MUST provide `allocr` if there are slices in ms, otherwise a null is fine. const report = try zgf.zonToStruct(&amp;ms, ast, allocr); defer allocr.free(ms.database.user); // Must free `user` since it's a slice of non-const u8's. defer allocr.free(ms.slc_of_structs); defer allocr.free(report.slc_of_structs); // Must also free the slice of structs in `report` defer allocr.free(ms.slc_of_arrays); defer allocr.free(report.slc_of_arrays); defer { for (ms.slc_of_slices) |s| allocr.free(s); // Deallocate nested slices first allocr.free(ms.slc_of_slices); // THEN deallocate the outer slice allocr.free(report.slc_of_slices); // `report` contains a slice of `ZonFieldResult` enums } std.debug.print("Field = database.host value = {s}\n", .{ ms.database.host }); std.debug.print("Field = database.port value = {d}\n", .{ ms.database.port }); std.debug.print("Field = database.user value = {s}\n", .{ ms.database.user }); std.debug.print("Field = database.password value = {s}\n", .{ ms.database.password }); std.debug.print("Field = decimal_separator value = {c}\n", .{ ms.decimal_separator }); std.debug.print("Field = months_in_year value = {d}\n", .{ ms.months_in_year }); std.debug.print("Field = newline_char value = 0x{X:0&gt;2}\n", .{ ms.newline_char }); std.debug.print("Field = pi value = {d}\n", .{ ms.pi }); std.debug.print("Field = hello value = {s}\n", .{ ms.hello }); std.debug.print("Field = unicode_char value = {u}\n", .{ ms.unicode_char }); std.debug.print("Field = primes value = [ ", .{}); for (ms.primes) |p| std.debug.print("{}, ", .{ p }); std.debug.print("]\n", .{}); std.debug.print("Field = factorials value = [ ", .{}); for (ms.factorials) |f| std.debug.print("{}, ", .{ f }); std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_structs value = [ ", .{}); for (ms.slc_of_structs) |s| std.debug.print("{{ ham = {}, eggs = {} }}, ", .{ s.ham, s.eggs }); std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_arrays value = [ ", .{}); for (ms.slc_of_arrays) |a| { std.debug.print("[ ", .{}); for (a) |e| std.debug.print("{}, ", .{ e }); std.debug.print("], ", .{}); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_slices value = [ ", .{}); for (ms.slc_of_slices) |s| { std.debug.print("[ ", .{}); for (s) |e| std.debug.print("{}, ", .{ e }); std.debug.print("], ", .{}); } std.debug.print("]\n\n", .{}); // `report` describes the state of corresponding fields in `ms` std.debug.print("Report =\n{s}\n", .{ std.json.fmt(report, .{ .whitespace = .indent_4 }) }); </code> } ``` <ol> <li>Or you can fetch the values one by one using <code>pub fn getFieldVal</code>:</li> </ol> ```zig const std = @import("std"); const zgf = @import("zon_get_fields.zig"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocr = gpa.allocator(); <code>// `Ast.parse` requires a sentinel (0) terminated slice, so we pass 0 as the sentinel value (last arg) const zon_txt = try std.fs.cwd().readFileAllocOptions(allocr, "my.zon", std.math.maxInt(usize), null, @alignOf(u8), 0); defer allocr.free(zon_txt); var ast = try std.zig.Ast.parse(allocr, zon_txt, .zon); defer ast.deinit(allocr); var fld_name: []const u8 = "database.host"; const dbhost_str = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, dbhost_str }); fld_name = "database.port"; const dbport_u16 = try zgf.getFieldVal(u16, ast, fld_name); std.debug.print("Field = {s} value = {d}\n", .{ fld_name, dbport_u16 }); fld_name = "database.user"; const dbhost_user = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, dbhost_user }); fld_name = "database.password"; const dbhost_password = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, dbhost_password }); fld_name = "decimal_separator"; const dec_separ_u8 = try zgf.getFieldVal(u8, ast, fld_name); std.debug.print("Field = {s} value = {c}\n", .{ fld_name, dec_separ_u8 }); fld_name = "months_in_year"; const months_in_year_u8 = try zgf.getFieldVal(u8, ast, fld_name); std.debug.print("Field = {s} value = {d}\n", .{ fld_name, months_in_year_u8 }); fld_name = "newline_char"; const newline_char_u8 = try zgf.getFieldVal(u8, ast, fld_name); std.debug.print("Field = {s} value = 0x{X:0&gt;2}\n", .{ fld_name, newline_char_u8 }); fld_name = "pi"; const pi_f64 = try zgf.getFieldVal(f64, ast, fld_name); std.debug.print("Field = {s} value = {d}\n", .{ fld_name, pi_f64 }); fld_name = "hello"; const hello_unicode_str = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, hello_unicode_str }); fld_name = "unicode_char"; const unicode_char_u21 = try zgf.getFieldVal(u21, ast, fld_name); std.debug.print("Field = {s} value = {u}\n", .{ fld_name, unicode_char_u21 }); std.debug.print("Field = primes value = [ ", .{}); var buf = [_]u8 { 0 } ** 22; for (0..5) |i| { const buf_slice = try std.fmt.bufPrint(&amp;buf, "primes[{d}]", .{i}); const int_u8 = try zgf.getFieldVal(u8, ast, buf_slice); std.debug.print("{d}, ", .{ int_u8 }); } std.debug.print("]\n", .{}); std.debug.print("Field = factorials value = [ ", .{}); for (0..12) |i| { const buf_slice = try std.fmt.bufPrint(&amp;buf, "factorials[{d}]", .{i}); const int_u32 = try zgf.getFieldVal(u32, ast, buf_slice); std.debug.print("{d}, ", .{ int_u32 }); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_structs value = [ ", .{}); for (0..2) |i| { const ham_buf_slice = try std.fmt.bufPrint(&amp;buf, "slc_of_structs[{d}].ham", .{i}); const ham_int_u32 = try zgf.getFieldVal(u32, ast, ham_buf_slice); const eggs_buf_slice = try std.fmt.bufPrint(&amp;buf, "slc_of_structs[{d}].eggs", .{i}); const eggs_int_u32 = zgf.getFieldVal(u32, ast, eggs_buf_slice) catch |err| { // We actually must check these things for all fields std.debug.print("{{ ham = {d}, eggs = {} }}, ", .{ ham_int_u32, err }); continue; }; std.debug.print("{{ ham = {d}, eggs = {d} }}, ", .{ ham_int_u32, eggs_int_u32 }); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_arrays value = [ ", .{}); for (0..2) |i| { std.debug.print("[ ", .{}); for (0..(3 - i)) |j| { const buf_slice = try std.fmt.bufPrint(&amp;buf, "slc_of_arrays[{d}].[{d}]", .{i, j}); const int_u32 = try zgf.getFieldVal(u32, ast, buf_slice); std.debug.print("{d}, ", .{ int_u32 }); } std.debug.print("], ", .{}); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_slices value = [ ", .{}); for (0..3) |i| { std.debug.print("[ ", .{}); for (0..(3 - i)) |j| { const buf_slice = try std.fmt.bufPrint(&amp;buf, "slc_of_slices[{d}].[{d}]", .{i, j}); const int_u32 = try zgf.getFieldVal(u32, ast, buf_slice); std.debug.print("{d}, ", .{ int_u32 }); } std.debug.print("], ", .{}); } std.debug.print("]\n", .{}); </code> } ``` Report struct field types | Target struct field | Report struct field | | ---------------------------------------- | ------------------------------------------------------------ | | Primitive types (integers, floats, etc.) | ZonFieldResult enum. | | Array of elements of a primitive type | Array of ZonFieldResult enum elements. | | Array of arrays, structs or slices | Array of arrays, structs, slices, or ZonFieldResult enums (for target array of slices of primitive elements).The type of report array element depends on the type of target array elements. | | Struct | Struct. Field types depend on target struct field types. | | Slice of elements of a primitive type | ZonFieldResult enum. | | Slice of arrays | Slice of arrays. Report array element type depends on the target array element type.<strong>Note</strong>: (1) allocator must be provided (not null), since report slice has to be allocated; (2) caller owns the report struct and must deallocate this report slice. | | Slice of structs | Slice of structs. Report struct field types depend on the target struct field types.<strong>Note</strong>: (1) allocator must be provided (not null), since report slice has to be allocated; (2) caller owns the report struct and must deallocate this report slice. | | Slice of slices | If target nested slices contain primitive type elements (integers, floats, etc.), then the report will contain a slice of ZonFieldResult enum elements.If target nested slices contain structs, arrays or slices, then the report will contain a slice of matching structs, arrays or slices. See target struct field types 'struct', 'array' or 'slice' above.<strong>Note</strong>: (1) allocator must be provided (not null), since report slice has to be allocated; (2) caller owns the report struct and must deallocate this report slice. |
[]
https://avatars.githubusercontent.com/u/13811862?v=4
langs-in-zig
thechampagne/langs-in-zig
2023-05-29T15:44:17Z
A list of programming languages implemented in Zig, for inspiration.
main
0
13
1
13
https://api.github.com/repos/thechampagne/langs-in-zig/tags
CC-BY-4.0
[ "awesome", "awesome-list", "programming-language", "programming-languages", "zig" ]
45
false
2025-04-27T19:05:27Z
false
false
unknown
github
[]
Languages Written in Zig This is a list of languages implemented in Zig. It is intended as a source of inspiration and comparison, and as a directory of potentially interesting projects in this vein. Inspired by <a>langs-in-rust</a>. What Can Be Included? <ol> <li>Is it a language?</li> <li>Is it written in Zig?</li> </ol> Then it can be included in this list! List of Languages | Name | ⭐ Stars | ☀️ Status | Description | |:-----|:---------|:-----------|:-----------| | <a>Bun</a> | 41,608 | ☀️ Active | Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one. | | <a>Zig</a> | 22,426 | ☀️ Active | General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software. | | <a>Cyber</a> | 787 | ☀️ Active | Fast and concurrent scripting. | | <a>buzz</a> | 552 | ☀️ Active | 👨‍🚀 buzz, A small/lightweight statically typed scripting language (in development) | | <a>Aro</a> | 508 | ☀️ Active | A C compiler with the goal of providing fast compilation and low memory usage with good diagnostics. | | <a>bog</a> | 419 | ☀️ Active | Small, strongly typed, embeddable language. | | <a>LoLa</a> | 151 | ☀️ Active | LoLa is a small programming language meant to be embedded into games. | | <a>zigself</a> | 110 | ☀️ Active | An implementation of the Self programming language. | | <a>Mocha</a> | 55 | ☀️ Active | An elegant configuration language for both humans and machines. | | <a>Jazmin</a> | 9 | ☀️ Active | Zig implementation of Jasmin | | <a>ZigScript</a> | 8 | ☀️ Active | A companion scripting language for Zig developers. | | <a>Foray</a> | 7 | ☀️ Active | A concatenative language written in Zig | | <a>Orng</a> | 2 | ☀️ Active | Orng is a versatile general purpose programming language that gives developers control while still being expressive. | | <a>monkeyZ</a> | 0 | ☀️ Active | An interpreter for the monkeyZ language. | | <a>lox-zig</a> | 0 | ☀️ Active | A bytecode VM compiler / interpreter for the Lox language. | | <a>keto</a> | 0 | ☀️ Active | keto is an experimental scripting language based on "Crafting Interpreters" by Robert Nystrom. | | <a>ts-parser-zig</a> | 0 | ☀️ Active | A Hand Written TypeScript parser. | | <a>Zua</a> | 115 | 🌙 Inactive | An implementation of Lua 5.1 in Zig, for learning purposes | | <a>Luf</a> | 30 | 🌙 Inactive | Statically typed, embeddable, scripting language written in Zig. | | <a>zed</a> | 10 | 🌙 Inactive | The zed Programming Language is inspired by AWK in its main mode of operating on text files divided into records (usually lines), and columns within thos recoeds. | | <a>APScript</a> | 5 | 🌙 Inactive | An interpreter for the AP© Computer Science Principles pseudocode language. | | <a>djot.zig</a> | 5 | 🌙 Inactive | A parser for parsing djot files and converting them to HTML. | | <a>zbfi</a> | 1 | 🌙 Inactive | BrainFuck :robot: language interpreter. | | <a>kule-lang</a> | 1 | 🌙 Inactive | kule shader language. | | <a>brainfuck-interpreter</a> | 0 | 🌙 Inactive | Brainfuck interpreter. | | <a>zQasm</a> | 0 | 🌙 Inactive | OpenQASM parser. | License <ul> <li><code>update.py</code> - <a>MIT</a></li> <li>Everything else - <a>CC-BY-4.0</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/24609692?v=4
webgpu-wasm-zig
seyhajin/webgpu-wasm-zig
2024-01-19T17:42:44Z
🚀 A minimal WebGPU example written in Zig, compiled to WebAssembly (wasm). 🛠️ Ideal for experimenting and preparing for native development without install dependencies (dawn, wgpu-rs).
master
0
13
1
13
https://api.github.com/repos/seyhajin/webgpu-wasm-zig/tags
MIT
[ "3d-graphics", "emscripten", "wasm", "webassembly", "webgpu", "zig", "zig-package" ]
207
false
2025-05-19T14:57:36Z
true
false
unknown
github
[]
webgpu-wasm-zig A minimal WebGPU example written in Zig, compiled to WebAssembly (wasm). ![👁️](https://views.whatilearened.today/views/github/seyhajin/webgpu-wasm-zig.svg) Getting started Clone <code>bash git clone https://github.com/seyhajin/webgpu-wasm-zig.git</code> Alternatively, download <a>zip</a> from Github repository and extract wherever you want. Build Build the example with <code>zig build</code> command, which will generate 3 new files (<code>.html</code>, <code>.js</code>, <code>.wasm</code>). Command <code>zig build --sysroot [path/to/emsdk]/upstream/emscripten/cache/sysroot</code> Example with Emscripten installed with Homebrew (<code>brew install emscripten</code>, v4.0.8) on macOS : <code>zig build --sysroot /usr/local/Cellar/emscripten/4.0.8/libexec/cache/sysroot</code> Or automatically search for the active version : <code>zig build --sysroot `readlink -f $(brew --prefix emscripten)`/libexec/cache/sysroot</code> <blockquote> <span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span> <code>build.zig</code> is preconfigured to build to <code>wasm32-emscripten</code> target only. <span class="bg-red-100 text-red-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-red-900 dark:text-red-300">CAUTION</span> Must provide Emscripten sysroot via <code>--sysroot</code> argument. </blockquote> Run Launch a web server to run example before open it to WebGPU compatible web browser (Chrome Canary, Brave Nightly, etc.). e.g. : launch <code>python3 -m http.server</code> and open web browser to <code>localhost:8000</code>. <blockquote> [!TIP] Use <a>Live Server</a> extension in Visual Studio Code to open the HTML file. This extension will update automatically page in real-time when you rebuild the example. </blockquote> Prerequisites <ul> <li><a>zig</a>, works with Zig 0.14.0+ version</li> <li><a>emscripten</a>, version 4.0+</li> <li>git (optional)</li> <li>python3 (optional)</li> </ul>
[]
https://avatars.githubusercontent.com/u/32988993?v=4
retro-zig
anyputer/retro-zig
2023-08-25T21:28:20Z
libretro zig bindings
main
2
13
1
13
https://api.github.com/repos/anyputer/retro-zig/tags
MIT
[ "cross-platform-development", "emulation", "gamedev-framework", "libretro", "libretro-api", "zig" ]
276
false
2025-05-12T02:56:09Z
true
true
unknown
github
[ { "commit": "d5f381759825ee0bac29bc294d47aa05be4ab7b5", "name": "zigglgen", "tar_url": "https://github.com/castholm/zigglgen/archive/d5f381759825ee0bac29bc294d47aa05be4ab7b5.tar.gz", "type": "remote", "url": "https://github.com/castholm/zigglgen" } ]
<code>_ _ _ _ __ ___| |_ _ __ ___ ___(_) __ _ (_) | '__/ _ \ __| '__/ _ \ ____|_ / |/ _` | | | | | | __/ |_| | | (_) |_____/ /| | (_| | | | |_| \___|\__|_| \___/ /___|_|\__, |___|_|____ |___/___________|</code> Hand-written libretro bindings for the Zig programming language. My hope is that this will be useful for people creating emulators and game engines in Zig, for years to come. Consider giving a ⭐ if you like what you see! <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 is currently missing a bunch of functionality, and is not yet stable. Furthermore, while Zig itself is a very nice little language, you should expect breaking changes. Nonetheless, have fun! </blockquote> Getting started Prerequisites <ul> <li>⚡ Zig 0.14</li> <li>👾 RetroArch or another libretro frontend</li> <li>🖼️ Optional: Cairo graphics library (to build the Cairo example)</li> </ul> Building example cores <code>sh zig build -Doptimize=ReleaseSmall</code> This gives you very tiny shared objects. Running (RetroArch) To run the <code>basic</code> example: <code>sh retroarch -L ./zig-out/lib/libbasic_libretro.so</code>
[]
https://avatars.githubusercontent.com/u/9002722?v=4
pc
cgbur/pc
2023-08-13T04:41:34Z
Difference calculations for the terminal
main
0
12
1
12
https://api.github.com/repos/cgbur/pc/tags
MIT
[ "calculator", "command-line-tool", "percent-change", "percentage", "productivity-tools", "statistics", "terminal", "tools", "zig" ]
201
false
2024-10-22T21:40:32Z
true
false
unknown
github
[]
<code>pc</code> - Change Calculator for the Terminal <code>pc</code> is a lightweight, blazing-fast tool that simplifies both the calculation and the understanding of differences between numbers. It allows you to quickly evaluate performance changes and offers meaningful human-formatted output, all within the convenience of your terminal. ✨ Features <ul> <li>🔥 <strong>Fashionable Output:</strong> Human readable, colorful, and easy to understand</li> <li>🎯 <strong>Always Accurate:</strong> Calculates percent change correctly every time</li> <li>🚀 <strong>Blazing Fast:</strong> Don't wait, get your results instantly</li> <li>❤️ <strong>Zig-Powered:</strong> Crafted with love using Zig</li> </ul> 🛠️ Usage 💻 Basic Calculation Compute percentage changes and differences effortlessly: <code>sh ❯ pc 18024 19503 11124 12321 340200 424212 1000000000 ↑ 8.21% 1.08x [ 17.60KiB → 19.05KiB ] ↓ -43.0% 0.57x [ 19.0KiB → 10.9KiB ] ↑ 10.8% 1.11x [ 10.9KiB → 12.0KiB ] ↑ 2661% 27.6x [ 12KiB → 332KiB ] ↑ 24.7% 1.25x [ 332.2KiB → 414.3KiB ] ↑ 235631% 2357x [ 414KiB → 954MiB ]</code> 🎓 Friendly Sizes by Default Large numbers are automatically translated into familiar sizes like GiB, MiB, KiB: <code>sh ❯ pc 1124122523 2421252122 ↑ 115.4% 2.15x [ 1.0GiB → 2.3GiB ]</code> Need raw numbers? Use the <code>-r</code> option: <code>sh ❯ pc 1124122523 2421252122 -r ↑ 115.4% 2.15x [ 1124122496 → 2421252096 ]</code> 🔀 Flexibility with Delimiters By default, <code>pc</code> tokenizes the input with the default delimiters (<code>\n\t\r,;:|</code>). Use the <code>--delimiters</code> or <code>-d</code> option to specify additional delimiters: <code>sh ❯ echo "15@20@3 6" | pc -d "@" ↑ 33.3% 1.33x [ 15 → 20 ] ↓ -85% 0.15x [ 20 → 3 ] ↑ 100% 2x [ 3 → 6 ]</code> 📐 Fixed Calculation Use the <code>--fixed</code> or <code>-f</code> flags to evaluate changes relative to a specific reference point in your series. You can specify positive or negative indices to choose the reference number. Evaluate changes relative to the first number (default): <code>sh ❯ pc 1 2 3 4 -f ↑ 100% 2x [ 1 → 2 ] ↑ 200% 3x [ 1 → 3 ] ↑ 300% 4x [ 1 → 4 ]</code> Or choose a different reference point (one-based): <code>sh ❯ pc 1 2 3 4 -f 2 ↓ -50% 0.50x [ 2 → 1 ] ↑ 50% 1.50x [ 2 → 3 ] ↑ 100% 2x [ 2 → 4 ]</code> Or index from the end of the series with negative numbers: <code>sh ❯ pc 1 2 3 4 -f -1 ↓ -75% 0.25x [ 4 → 1 ] ↓ -50% 0.50x [ 4 → 2 ] ↓ -25% 0.75x [ 4 → 3 ]</code> 📄 Output Formats Specify the output format with the <code>--format</code> option. Currently, <code>pc</code> supports the following formats: <ul> <li>Human-readable (default)</li> <li>JSON</li> <li>CSV</li> </ul> JSON Output <code>sh ❯ pc 18024 19503 --format json | jq [ { "percent": 8.20572566986084, "times": 1.082057237625122, "prev": 18024, "cur": 19503 } ]</code> CSV Output <code>sh ❯ pc 18024 19503 --format csv percent,times,prev,cur 8.20572566986084,1.082057237625122,18024,19503</code> For the full command list, simply run: <code>sh pc --help</code> 📥 Installation Prebuilt Binaries Available Find them on the <a>releases</a> page. Supported Releases <ul> <li>Linux: <code>aarch64-linux-pc</code>, <code>riscv64-linux-pc</code>, <code>x86_64-linux-pc</code></li> <li>macOS: <code>aarch64-macos-pc</code></li> <li>Windows: <code>x86_64-windows-pc.exe</code></li> </ul> Installation Example for Linux (x86_64) <code>bash wget -O pc https://github.com/cgbur/pc/releases/latest/download/x86_64-linux-pc chmod +x pc mv pc ~/.local/bin/pc</code> Replace the file name in the URL with the corresponding one for other Linux architectures. Build from Source To build from source, you'll need <a>Zig</a>: <code>sh git clone https://github.com/cgbur/pc.git cd pc zig build -Doptimize=ReleaseSafe cp zig-out/bin/pc ~/.local/bin/pc</code> 📝 Future Plans <ul> <li>[ ] Think of more features to add</li> </ul>
[]
https://avatars.githubusercontent.com/u/198496?v=4
fy
nooga/fy
2023-10-25T21:37:21Z
A a tiny concatenative programming language JIT compiled to aarch64 machine code.
master
0
12
0
12
https://api.github.com/repos/nooga/fy/tags
MIT
[ "compiler", "concatenative", "concatenative-language", "functional-programming", "jit", "stack-based", "zig" ]
195
false
2024-12-26T22:52:21Z
true
true
unknown
github
[ { "commit": "e18781dbc559e9a7aa3d6fa327335815803306dc.tar.gz", "name": "zigline", "tar_url": "https://github.com/alimpfard/zigline/archive/e18781dbc559e9a7aa3d6fa327335815803306dc.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/alimpfard/zigline" } ]
fy Short for <em>funky yak</em>, <em>flying yacht</em>, or <em>funny yodeling</em> depending on your mood. Also <em>fuck yeah</em>. <code>fy</code> is a tiny concatenative programming language JIT compiled to aarch64 machine code. <code>fy</code> is a toy, of the kind where the batteries constantly leak and only that weird guy in suspenders plays with it. Join <a>#fy on concatenative Discord</a>. Building <code>fy</code> is written in Zig and targets aarch64 exclusively. You'll need a Zig compiler and a 64-bit ARM machine such as AppleSilicon or a Raspberry Pi. Build with: <code>sh zig build</code> Run with: <code>sh ./zig-out/bin/fy</code> Check <code>--help</code> for the latest news on available flags and arguments. Examples Examples can be found in <code>examples/</code>. Features <a>There is no plan.</a>
[]
https://avatars.githubusercontent.com/u/6881800?v=4
zig-recover
dimdin/zig-recover
2024-02-05T15:36:56Z
zig panic recover
main
0
12
0
12
https://api.github.com/repos/dimdin/zig-recover/tags
MIT
[ "zig", "zig-library", "zig-package", "ziglang" ]
20
false
2025-05-12T17:19:38Z
true
true
0.14.0
github
[]
Zig Panic Recover Recover calls a function and regains control of the calling thread when the function panics or behaves undefined. Recover is licensed under the terms of the <a>MIT License</a>. How to use Recover <code>call</code>, calls <code>function</code> with <code>args</code>, if the function does not panic, will return the called function's return value. If the function panics, will return <code>error.Panic</code>. ``` const recover = @import("recover"); try recover.call(function, args); ``` Prerequisites <ol> <li> Enabled runtime safety checks, such as unreachable, index out of bounds, overflow, division by zero, incorrect pointer alignment, etc. </li> <li> In the root source file define panic as recover.panic or override the default panic handler and call recover <code>panicked</code>. <code>pub const panic = recover.panic;</code> </li> <li>Excluding Windows, linking to C standard library is required.</li> </ol> Example Returns error.Panic because function division panics with runtime error "division by zero". ``` fn division(num: u32, den: u32) u32 { return num / den; } try recover.call(division, .{1, 0}); ``` Testing For recover to work for testing, you need a custom test runner with a panic handler: <code>pub const panic = @import("recover").panic;</code> To test that <code>foo(0)</code> panics: <code>test "foo(0) panics" { const err = recover.call(foo, .{0}); std.testing.expectError(error.Panic, err). }</code> Proper Usage <ul> <li>Recover is useful for testing panic and undefined behavior runtime safety checks.</li> <li>It is <strong>not</strong> recommended to use recover as a general exception mechanism.</li> </ul>
[]
https://avatars.githubusercontent.com/u/35711760?v=4
av1an-command-gen
gianni-rosato/av1an-command-gen
2023-12-25T06:12:11Z
A tool for easily generating Av1an commands for AV1 encoding. Written in Zig.
main
1
12
1
12
https://api.github.com/repos/gianni-rosato/av1an-command-gen/tags
BSD-3-Clause
[ "av1", "av1an", "encoding", "zig" ]
15
false
2025-04-29T22:02:00Z
true
true
unknown
github
[]
Av1an Command Generator A tool for easily generating Av1an commands for AV1 encoding. Written in Zig. Description This program generates an AV1 video encoding command for use with <a>Av1an</a>, a chunked AV1 encoding tool for use with <a>aomenc</a>, <a>SVT-AV1</a>, and <a>rav1e</a>. This tool takes in the video resolution, frame rate, desired encoder, speed preset, and target bitrate range as command line arguments. Based on these parameters, it calculates settings like tile columns/rows, lag-in-frames, CRF, and encoder speed preset. Then, it injects these into a generated encoding command string. The output is a full <code>av1an</code> command that can be run to encode a video based on the specified settings. Usage <code>bash av1an-command-gen [width] [height] [fps] [encoder] [speed] [bitrate_target]</code> <ul> <li><code>width</code> - Input video width in pixels </li> <li><code>height</code> - Input video height in pixels</li> <li><code>fps</code> - Input video frame rate</li> <li><code>encoder</code> - <code>aom</code>, <code>svt</code>, or <code>rav1e</code></li> <li><code>speed</code> - <code>slower</code>, <code>slow</code>, <code>med</code>, <code>fast</code>, <code>faster</code> </li> <li><code>bitrate_target</code> - <code>lowest</code>, <code>low</code>, <code>med</code>, <code>high</code></li> </ul> Examples Generate a command for encoding a 1280x720 video at 24 fps using rav1e at 'med' speed and 'low' bitrate target: <code>bash av1an-command-gen 1280 720 24 rav1e med low</code> Generate a command for encoding a 1920x1080 video at 30 fps using svt-av1 at 'fast' speed and 'high' bitrate target: <code>bash av1an-command-gen 1920 1080 30 svt fast high</code> Building This program requires the <a>Zig</a> v0.11.0 programming language. To build: <code>bash zig build</code> This will produce a standalone binary <code>av1an-command-gen</code> in <code>zig-out/bin/</code>. Contributing Contributions are welcome! Please open an issue or pull request on GitHub. License This project is licensed under the BSD 3-Clause License - see the <a>LICENSE</a> file for details.
[]
https://avatars.githubusercontent.com/u/103538756?v=4
salem
Dr-Nekoma/salem
2023-10-14T05:16:39Z
An interpreter for the Sal programming language written in Zig
master
0
12
1
12
https://api.github.com/repos/Dr-Nekoma/salem/tags
Unlicense
[ "concatenative", "interpreter", "language", "programming-language", "public-domain", "unlicense", "zig" ]
42
false
2025-05-09T02:19:28Z
true
true
unknown
github
[]
Salem Salem is the Sal Execution Model. It is a Zig implementation of the <a>Sal</a> programming language. Data model <ul> <li>Basic data types:</li> <li><a>RRB-Trees</a> for arrays and byte arrays</li> <li>B-Trees, for dictionaries, sets and multisets</li> <li>Pairs and Variables</li> <li>Primitive and constructed functions</li> <li>A very minimal object system (needed for efficient mutual recursion)</li> <li> Promises for lazy evaluation </li> <li> Numeric tower: </li> <li>Fixnums</li> <li>Arbitrary precision integers</li> <li>Ratios</li> <li>Complex numbers and quaternions (restricted to rational coefficients)</li> <li><a>Multisets (we will treat numbers as a proper subtype of multisets)</a></li> <li>We are explicitly not supporting IEEE 754 Floats, but we may at some point support <a>Posits</a></li> </ul> Inspirations <ul> <li><a>Clojure</a></li> <li><a>John Shutt's Kernel</a> and <a>Vau Calculus</a></li> <li><a>Racket</a></li> <li><a>colorForth</a></li> <li><a>RetroForth</a></li> <li><a>Joy</a></li> <li><a>Factor</a></li> <li><a>Mercury</a></li> <li><a>Lua</a></li> <li><a>Erlang</a></li> <li><a>Haskell</a></li> <li><a>Zig</a></li> <li><a>Roc</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/67269576?v=4
zig-pico-cmake
nemuibanila/zig-pico-cmake
2023-10-14T22:50:26Z
Build zig projects that use the Raspberry PI Pico SDK
main
1
12
4
12
https://api.github.com/repos/nemuibanila/zig-pico-cmake/tags
MIT
[ "cyw43", "raspberry-pi-pico", "raspberry-pi-pico-sdk", "rp2040", "zig" ]
28
false
2025-05-17T11:02:46Z
true
false
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/47667941?v=4
forge
daylinmorgan/forge
2023-09-07T20:13:48Z
build nim binaries for all the platforms
main
0
12
0
12
https://api.github.com/repos/daylinmorgan/forge/tags
MIT
[ "nim", "nimble", "zig" ]
50
false
2025-01-31T06:15:34Z
false
false
unknown
github
[]
forge <a></a> A basic toolchain to forge (cross-compile) your multi-platform <code>nim</code> binaries. Why? <code>Nim</code> is a great language and the code is as portable as any other code written in C. But who wants to manage C toolchains or CI/CD DSL's to cross-compile your code into easily sharable native executable binaries Installation In order to use <code>forge</code> you must first install <a><code>zig</code></a> as all compilation is done using a thin wrapper around <code>zig cc</code>. <blockquote> <span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span> Future versions may use an automated/isolated <code>zig</code> installation. </blockquote> <code>sh nimble install https://github.com/daylinmorgan/forge</code> Usage <code>Forge</code> provide two key methods to compile your <code>nim</code> source <code>forge cc</code> and <code>forge release</code>. <code>forge cc</code> To compile a single binary for a platform you can use <code>forge cc</code>. Example: <code>sh forge cc --target x86_64-linux-musl -- -d:release src/forge.nim -o:forge</code> <code>forge release</code> This command is useful for generating many compiled binaries like you may be accustomed to seeing from <code>go</code> or <code>rust</code> cli's. <code>Forge release</code> will make attempts to infer many values based on the assumption that it's likely run from the root directory of a <code>nim</code> project with a <code>&lt;project&gt;.nimble</code> You can either specify all commands on the CLI or use a config file. Example: <code>sh forge release --target,=x86_64-linux-musl,x86_64-macos-none --bin src/forge.nim</code> Result: <code>dist ├── forge-v2023.1001-x86_64-linux-musl │ └── forge └── forge-v2023.1001-x86_64-macos-none └── forge</code> The output directories used for each binary are determined by a format string: <code>${name}-v${version}-${target}</code>. You can modify this with additional info at runtime like using date instead of version string: <code>--format "\${name}-$(date +'%Y%M%d')-\${target}"</code>. You can also create a config file by default at <code>./.forge.cfg</code> that controls the behavior of <code>forge release</code>: ```dosini flags are specified at the top level nimble # key without value for booleans format = "${name}-${target}" outdir = forge-dist use sections to list targets/bins with optional args [target] x86_64-linux-musl = "--debugInfo:on" x86_64-linux-gnu [bin] src/forge src/forgecc = "--opt:size" # use a custom flag for this binary ``` Example: <code>sh forge release --verbose --dryrun</code> Output: ``` forge release -V --dryrun forge || config = | nimble true | outdir forge-dist | format ${name}-${target} | version 2023.1001 | targets: | x86_64-linux-musl|--debugInfo:on | x86_64-linux-gnu | bins: | src/forge | src/forgecc|--opt:size forge || dry run...see below for commands forge || compiling 2 binaries for 2 targets nimble c --cpu:amd64 --os:Linux --cc:clang --clang.exe='forgecc' --clang.linkerexe='forgecc' --passC:'-target x86_64-linux-musl' --passL:'-target x86_64-linux-musl' -d:release --outdir:'dist/forge-x86_64-linux-musl' --debugInfo:on src/forge nimble c --cpu:amd64 --os:Linux --cc:clang --clang.exe='forgecc' --clang.linkerexe='forgecc' --passC:'-target x86_64-linux-musl' --passL:'-target x86_64-linux-musl' -d:release --outdir:'dist/forge-x86_64-linux-musl' --debugInfo:on --opt:size src/forgecc nimble c --cpu:amd64 --os:Linux --cc:clang --clang.exe='forgecc' --clang.linkerexe='forgecc' --passC:'-target x86_64-linux-gnu' --passL:'-target x86_64-linux-gnu' -d:release --outdir:'dist/forge-x86_64-linux-gnu' src/forge nimble c --cpu:amd64 --os:Linux --cc:clang --clang.exe='forgecc' --clang.linkerexe='forgecc' --passC:'-target x86_64-linux-gnu' --passL:'-target x86_64-linux-gnu' -d:release --outdir:'dist/forge-x86_64-linux-gnu' --opt:size src/forgecc ``` Acknowledgements Thanks to <a>Andrew Kelley</a> and the many <code>zig</code> <a>contributors</a>.
[]
https://avatars.githubusercontent.com/u/499599?v=4
zcmd.zig
liyu1981/zcmd.zig
2024-01-14T08:57:24Z
zcmd is a single file lib to replace zig's std.childProcess.run with the ability of running pipeline like bash..
main
1
12
1
12
https://api.github.com/repos/liyu1981/zcmd.zig/tags
MIT
[ "zig", "zig-package" ]
10,022
false
2025-01-09T14:45:10Z
true
true
0.12.0
github
[]
zcmd.zig <code>zcmd</code> is a single file lib (<code>zcmd.zig</code>) to replace zig's <code>std.childProcess.run</code>. It has almost identical API like <code>std.childProcess.run</code>, but with the ability of running pipeline like <code>bash</code>. Example like execution of single command (replacement of zig's <code>std.childProcess.run</code>) <code>zig const result = try Zcmd.run(.{ .allocator = allocator, .commands = &amp;[_][]const []const u8{ &amp;.{ "uname", "-a" }, }, });</code> the differences to <code>std.childProcess.run</code> is it will take <code>commands</code> instead of single <code>command</code>. It can run a <code>bash</code> like pipeline like follows (<em>to recursively find and list the latest modified files in a directory with subdirectories and times</em>) <code>zig const result = try Zcmd.run(.{ .allocator = allocator, .commands = &amp;[_][]const []const u8{ &amp;.{ "find", ".", "-type", "f", "-exec", "stat", "-f", "'%m %N'", "{}", ";" }, &amp;.{ "sort", "-nr" }, &amp;.{ "head", "-1" }, }, });</code> It can also accept an input from outside as stdin to command or command pipeline, like follows <code>zig const f = try std.fs.cwd().openFile("tests/big_input.txt", .{}); defer f.close(); const content = try f.readToEndAlloc(allocator, MAX_OUTPUT); defer allocator.free(content); const result = try Zcmd.run(.{ .allocator = allocator, .commands = &amp;[_][]const []const u8{ &amp;.{"cat"}, &amp;.{ "wc", "-lw" }, }, .stdin_input = content, });</code> When there is something failed inside pipeline, we will report back <code>stdout</code> and <code>stderr</code> just like <code>bash</code>, like below example <code>zig const result = try Zcmd.run(.{ .allocator = allocator, .commands = &amp;[_][]const []const u8{ &amp;.{ "find", "nonexist" }, &amp;.{ "wc", "-lw" }, }, }); defer result.deinit(); try testing.expectEqualSlices( u8, result.stdout.?, " 0 0\n", ); try testing.expectEqualSlices( u8, result.stderr.?, "find: nonexist: No such file or directory\n", );</code> Please check <a>example/zcmd_app</a> for an example on how to use <code>zcmd.zig</code>. use <code>zcmd.zig</code> in <code>build.zig</code> Originally <code>zcmd.zig</code> is functions I wrote in <code>build.zig</code> to auto generating files with commands, so it is important that can use this in <code>build.zig</code>. So <code>zcmd.zig</code> exposed itself for <code>build.zig</code> too. To use that we will need to normally introduce <code>zcmd.zig</code> to <code>build.zig.zon</code> (see Usage below). Then in your <code>build.zig</code>, do following to use it <code>zig // when import in build.zig, the zcmd is exposed in nested const zcmd const zcmd = @import("zcmd").zcmd; // then next can use zcmd.run as above</code> Please check <a>example/zcmd_build_app</a> for detail version how to use in this way. Usage through Zig Package Manager use following bash in your project folder (with <code>build.zig.zon</code>) <code>zig fetch --save https://github.com/liyu1981/zcmd.zig/archive/refs/tags/v0.2.2.tar.gz</code> you can change the version <code>v0.1.0</code> to other version if there are in <a>release</a> page. or simply just copy <code>zcmd.zig</code> file to your project It is a single file lib with no dependencies! Zig Docs Zig docs is hosted in github pages at: <a>https://liyu1981.github.io/zcmd.zig/</a>, please go there to find what apis <code>zcmd.zig</code> provides. Coverage <code>zcmd.zig</code> is rigorously tested. Run unit tests at repo checkout root folder with <code>zig test src/zcmd.zig</code>. For coverage test, as <code>kcov</code> is working in a way of 'debug every line and record', it can not work with <code>zcmd</code> tests. <code>zcmd</code> tests will fork many sub processes and if one of them be stopped the whole pipeline hangs. I am still in searching of what's the best method to cover.
[]
https://avatars.githubusercontent.com/u/9273964?v=4
pdf-nano
GregorBudweiser/pdf-nano
2023-11-24T19:25:33Z
A small PDF encoder written in Zig
main
0
12
0
12
https://api.github.com/repos/GregorBudweiser/pdf-nano/tags
MIT
[ "pdf", "pdf-generation", "typescript", "wasm", "zig" ]
53
false
2025-05-13T07:59:44Z
true
false
unknown
github
[]
Welcome! <strong>PDF-Nano</strong> is a small(ish) library for generating simple PDF files. The goal of PDF-Nano is to have a lightweight PDF-library usable from Zig, C and Wasm. Features The main feature is PDF-Nano's small size. Compiled to wasm, it weighs <strong>less than 64kb</strong>, making it suitable for embedded devices. To keep the code/binary small only a minimal set of features have been and will be added. Currently the following is supported: - Text (Latin-1 charset support only) - Lines - Tables (fixed layout) - Colors (font, storke, fill/table background) - Alignment (left, center, right) On the todo list: - Text justify - Optionally repeat table header on new page Not on the todo list (due to code size): - TrueType fonts (if you need a small library you probably don't have space for fonts anyway) - Pictures such as jpg, png (this would require an image decoder + logic to encode into pdf's raster format) - Compression How to build PDF-Nano is written in Zig, so you will need the Zig compiler. Then simply compile for your target platform (e.g. wasm): <code>zig build -Doptimize=ReleaseSmall -Dtarget=wasm32-freestanding </code> Build compatibility | PDF-Nano | Zig | |--------------|----------------------------| | <strong>v0.5.0</strong> | <strong>v0.13.0</strong> | | v0.4.0 | v0.13.0 | | v0.3.0 | v0.12.0-dev.3291+17bad9f88 | | v0.2.0 | v0.11.0 | | v0.1.0 | v0.11.0 | Usage PDF-Nano provides a text-editor like interface, meaning it handles layouting/positioning for you. See an <a>example here</a>. ```c include int main(int argc, char** argv) { encoder_handle handle = createEncoder(A4, PORTRAIT); addText(handle, "Hello world!"); saveAs(handle, "hello.pdf"); freeEncoder(handle); return 0; } ``` There is also a <a>typescript wrapper</a>.
[]
https://avatars.githubusercontent.com/u/22038970?v=4
turbo
paoda/turbo
2023-08-01T20:17:05Z
NDS emulator in Zig ⚡
main
0
11
0
11
https://api.github.com/repos/paoda/turbo/tags
-
[ "emulator", "nds", "opengl", "sdl2", "zig" ]
198
false
2024-11-11T21:57:32Z
true
true
unknown
github
[ { "commit": "c0193e9247335a6c1688b946325060289405de2a", "name": "zig-clap", "tar_url": "https://github.com/Hejsil/zig-clap/archive/c0193e9247335a6c1688b946325060289405de2a.tar.gz", "type": "remote", "url": "https://github.com/Hejsil/zig-clap" }, { "commit": null, "name": "zba-gdbstub...
404
[]
https://avatars.githubusercontent.com/u/59206988?v=4
zig-flutter
ExpidusOS-archive/zig-flutter
2023-04-05T18:04:08Z
Flutter w/ Zig
master
0
11
0
11
https://api.github.com/repos/ExpidusOS-archive/zig-flutter/tags
GPL-3.0
[ "flutter", "flutter-engine", "zig" ]
44
false
2025-02-01T04:06:57Z
true
false
unknown
github
[]
zig-flutter Flutter w/ Zig
[]
https://avatars.githubusercontent.com/u/20256717?v=4
dustpile
Game4all/dustpile
2023-07-30T13:11:15Z
🧪GPU accelerated falling sand sim in Zig
main
0
11
0
11
https://api.github.com/repos/Game4all/dustpile/tags
-
[ "compute-shader", "falling-sand", "opengl", "zig", "ziglang" ]
1,706
false
2024-12-30T17:02:46Z
true
true
unknown
github
[ { "commit": "affdd6ae6f2ac2c3b9162784bdad345c561eeeea", "name": "mach_glfw", "tar_url": "https://github.com/hexops/mach-glfw/archive/affdd6ae6f2ac2c3b9162784bdad345c561eeeea.tar.gz", "type": "remote", "url": "https://github.com/hexops/mach-glfw" } ]
<code>dustpile</code> GPU falling sand sim in Zig Uses <a>generated OpenGL bindings</a> to interact with the GPU. Requires zig master to compile <code>- B : Change brush type - W : Reset world - Space : Pause / Resume simulation - P : Step simulation - 1-9 : Switch to element</code>
[]
https://avatars.githubusercontent.com/u/135469732?v=4
sqids-zig
sqids/sqids-zig
2023-12-03T17:26:14Z
Official Zig port of Sqids. Generate short unique IDs from numbers.
main
0
11
1
11
https://api.github.com/repos/sqids/sqids-zig/tags
MIT
[ "hashids", "id", "id-generator", "short-id", "short-url", "sqids", "uid", "unique-id", "unique-id-generator", "zig", "zig-lang", "zig-library", "ziglang" ]
43
false
2025-03-11T03:40:42Z
true
true
unknown
github
[]
<a>Sqids Zig</a> <a>Sqids</a> (<em>pronounced "squids"</em>) is a small library that lets you <strong>generate unique IDs from numbers</strong>. It's good for link shortening, fast &amp; URL-safe ID generation and decoding back into numbers for quicker database lookups. Features: <ul> <li><strong>Encode multiple numbers</strong> - generate short IDs from one or several non-negative numbers</li> <li><strong>Quick decoding</strong> - easily decode IDs back into numbers</li> <li><strong>Unique IDs</strong> - generate unique IDs by shuffling the alphabet once</li> <li><strong>ID padding</strong> - provide minimum length to make IDs more uniform</li> <li><strong>URL safe</strong> - auto-generated IDs do not contain common profanity</li> <li><strong>Randomized output</strong> - Sequential input provides nonconsecutive IDs</li> <li><strong>Many implementations</strong> - Support for <a>multiple programming languages</a></li> </ul> 🧰 Use-cases Good for: <ul> <li>Generating IDs for public URLs (eg: link shortening)</li> <li>Generating IDs for internal systems (eg: event tracking)</li> <li>Decoding for quicker database lookups (eg: by primary keys)</li> </ul> Not good for: <ul> <li>Sensitive data (this is not an encryption library)</li> <li>User IDs (can be decoded revealing user count)</li> </ul> 🚀 Getting started To add sqids-zig to your Zig application or library, follow these steps: <ol> <li>Fetch the package at the desired commit:</li> </ol> <code>terminal zig fetch --save https://github.com/lvignoli/sqids-zig/archive/&lt;commitID&gt;.tar.gz</code> <ol> <li>Declare the dependecy in the <code>build.zig.zon</code> file, with the hash obtained during the fetch:</li> </ol> <code>zig .dependencies = .{ .sqids = .{ .url = "https://github.com/lvignoli/sqids-zig/archive/&lt;commitID&gt;.tar.gz", .hash = "&lt;hash&gt;", }, }</code> <ol> <li>In your <code>build.zig</code>, make the <code>sqids</code> module available for import:</li> </ol> ```zig const sqids_dep = b.dependency("sqids", .{}); const sqids_mod = sqids_dep.module("sqids"); [...] exe.addModule("sqids", sqids_mod); // for an executable lib.addModule("sqids", sqids_mod); // for a library tests.addModule("sqids", sqids_mod); // for tests ``` <ol> <li>Use it in Zig source code with:</li> </ol> <code>zig const sqids = @import("sqids");</code> (The import string is the one provided in the <code>addModule</code> call.) <blockquote> [!TIP] Check <a>lvignoli/sqidify</a> for a self-contained Zig executable example. </blockquote> 👩‍💻 Examples Simple encode &amp; decode: ```zig const s = try sqids.Sqids.init(allocator, .{}) defer s.deinit(); const id = try s.encode(&amp;.{1, 2, 3}); defer allocator.free(id); // Caller owns the memory. const numbers = try s.decode(id); defer allocator.free(numbers); // Caller owns the memory. ``` <blockquote> <strong>Note</strong> 🚧 Because of the algorithm's design, <strong>multiple IDs can decode back into the same sequence of numbers</strong>. If it's important to your design that IDs are canonical, you have to manually re-encode decoded numbers and check that the generated ID matches. </blockquote> The <code>sqids.Options</code> struct is used at initialization to customize the encoder. Enforce a <em>minimum</em> length for IDs: <code>zig const s = try sqids.Sqids.init(allocator, .{.min_length = 10}); const id = try s.encode(&amp;.{1, 2, 3}); // "86Rf07xd4z"</code> Randomize IDs by providing a custom alphabet: <code>zig const s = try sqids.Sqids.init(allocator, .{.alphabet = "FxnXM1kBN6cuhsAvjW3Co7l2RePyY8DwaU04Tzt9fHQrqSVKdpimLGIJOgb5ZE"}); const id = try s.encode(&amp;.{1, 2, 3}); // "B4aajs"</code> Prevent specific words from appearing anywhere in the auto-generated IDs: <code>zig const s = try sqids.Sqids.init(allocator, .{.blocklist = &amp;.{"86Rf07"}}); const id = try s.encode(&amp;.{1, 2, 3}); // "se8ojk"</code> 📝 License <a>MIT</a>
[]
https://avatars.githubusercontent.com/u/6806645?v=4
zig-php
arshidkv12/zig-php
2024-01-15T13:30:05Z
PHP extension written in Zig
main
0
10
2
10
https://api.github.com/repos/arshidkv12/zig-php/tags
GPL-2.0
[ "php", "php-zig", "zig" ]
440
false
2025-05-14T12:38:06Z
true
false
unknown
github
[]
PHP Zig Extension Skeleton This project provides a skeleton for building a PHP extension written in Zig. The goal of this project is to leverage Zig's performance and safety features within the PHP ecosystem. This guide will walk you through how to build and test the extension. Requirements <ul> <li><strong>PHP</strong>: You need a PHP installation with the ability to compile extensions (e.g., <code>phpize</code>).</li> <li><strong>Zig</strong>: Install the Zig programming language from <a>Zig's official site</a>.</li> <li><strong>GNU Make</strong>: Required to build the extension.</li> <li><strong>Autotools</strong>: Required for <code>phpize</code> and <code>./configure</code>.</li> </ul> System Dependencies (Linux/macOS) ```bash sudo apt-get install php-dev make autoconf Or for macOS using Homebrew brew install autoconf make php ``` <a></a> Installation Instructions <ol> <li>Clone the repository:</li> </ol> <code>git clone https://github.com/arshidkv12/zig-php.git cd zig-php</code> <ol> <li>Install PHP development headers and dependencies, such as phpize.</li> <li>Run the build process.</li> </ol> Building the Extension Edit build.zig file. Add correct cwd_relative php path. To build it: <ol> <li><code>zig build</code></li> <li><code>phpize</code></li> <li><code>./configure</code></li> <li><code>make</code></li> </ol> To test it: <code>php -d extension=./modules/my_php_extension.so -r "echo hello_world();"</code> Should output: <code>Hello from ZIG!</code>
[]
https://avatars.githubusercontent.com/u/4337696?v=4
zig-wasix
nikneym/zig-wasix
2023-09-14T20:15:44Z
WASIX extensions for Zig ⚡
main
0
10
1
10
https://api.github.com/repos/nikneym/zig-wasix/tags
-
[ "wasi", "wasix", "wasm", "wasmer", "webassembly", "zig" ]
32
false
2025-02-10T04:57:58Z
true
true
unknown
github
[]
Zig-WASIX WASIX extensions for Zig ⚡. This module let's you to create programs with Wasmer &amp; WASIX that can run on edge or be sandboxed. Installation Install via Zig package manager (Copy the full SHA of latest commit hash from GitHub): <code>sh zig fetch --save https://github.com/nikneym/zig-wasix/archive/&lt;latest-commit-hash&gt;.tar.gz</code> In your <code>build</code> function at <code>build.zig</code>, make sure your build step and source files are aware of the module: ```zig const dep_opts = .{ .target = target, .optimize = optimize }; const wasix_dep = b.dependency("wasix", dep_opts); const wasix_module = wasix_dep.module("wasix"); exe_mod.addImport("wasix", wasix_module); ``` Building Projects Now you can build your projects by targeting WASM &amp; WASI and run on Wasmer, as the following: ```sh zig build -Dtarget=wasm32-wasi wasmer run zig-out/bin/.wasm You may want to have networking and other stuff be enabled wasmer run --enable-all --net zig-out/bin/.wasm ``` Documentation You can refer to <a>wasix.org</a> for documentation and further API reference.
[]
https://avatars.githubusercontent.com/u/535600?v=4
way-z
psnszsn/way-z
2023-05-28T11:49:17Z
Zig Wayland client and app toolkit
main
0
10
1
10
https://api.github.com/repos/psnszsn/way-z/tags
MPL-2.0
[ "wayland", "zig" ]
470
false
2025-04-02T20:55:27Z
true
true
unknown
github
[ { "commit": "94ed6af7b2aaaeab987fbf87fcee410063df715b", "name": "libxev", "tar_url": "https://github.com/mitchellh/libxev/archive/94ed6af7b2aaaeab987fbf87fcee410063df715b.tar.gz", "type": "remote", "url": "https://github.com/mitchellh/libxev" } ]
Way-Z Native Zig Wayland client library and widget toolkit Description This project has a few different parts: <ul> <li>Wayland client library (in <code>wayland/</code>): This can be used to crate a statically linked binary capable of displaying CPU rendered graphics.</li> <li>Widget toolkit (in <code>toolkit/</code>): This builds over the wayland client and povides a Data Oriented library for creating GUI apps</li> <li>Apps (in <code>apps/</code>): Demo apps built using the widget toolkit</li> </ul> Getting Started Dependencies <ul> <li>Zig 0.14.0-dev.3086+b3c63e5de</li> </ul> Runnig examples <ul> <li><code>zig build run-hello</code></li> </ul> Inspired by <ul> <li><a>Serenity OS</a></li> <li><a>Druid</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/5464072?v=4
zig-mime
nektro/zig-mime
2023-02-28T04:18:01Z
null
main
0
10
1
10
https://api.github.com/repos/nektro/zig-mime/tags
MIT
[ "zig", "zig-package" ]
20
false
2025-05-21T20:33:13Z
true
false
unknown
github
[]
zig-mime <a></a> <a></a> <a></a> <a></a> Query the MIME type of a file extension. https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types
[]
https://avatars.githubusercontent.com/u/11963669?v=4
zprob
pblischak/zprob
2023-05-02T00:31:38Z
A Zig Module for Random Number Distributions
main
1
10
1
10
https://api.github.com/repos/pblischak/zprob/tags
LGPL-3.0
[ "module", "probability", "random-sampling", "statistics", "zig" ]
2,170
false
2025-04-22T20:51:26Z
true
true
unknown
github
[]
zprob <i> A Zig Module for Random Number Distributions </i> The <code>zprob</code> module implements functionality for working with probability distributions in pure Zig, including generating random samples and calculating probabilities using mass/density functions. The instructions below will get you started with integrating <code>zprob</code> into your project, as well as introducing some basic use cases. For more detailed information on the different APIs that <code>zprob</code> implements, please refer to the <a>docs site</a>. Getting Started <code>RandomEnvironment</code> API Below we show a small example program that introduces the <code>RandomEnvironment</code> struct, which provides a high-level interface for sampling from distributions and calculating probabilities. It automatically generates and stores everything needed to begin generating random numbers (seed + random generator), and follows the standard Zig convention of initialization with an <code>Allocator</code> that handles memory allocation. ```zig const std = @import("std"); const zprob = @import("zprob"); pub fn main() !void { // Set up main memory allocator and defer deinitilization var gpa = std.heap.DebugAllocator(.{}){}; const allocator = gpa.allocator(); defer { const status = gpa.deinit(); std.testing.expect(status == .ok) catch { @panic("Memory leak!"); }; } <code>// Set up random environment and defer deinitialization var env = try zprob.RandomEnvironment.init(allocator); defer env.deinit(); // Generate random samples const binomial_sample = try env.rBinomial(10, 0.8); const geometric_sample = try env.rGeometric(3.0); // Generate slices of random samples. The caller is responsible for cleaning up // the allocated memory for the slice. const binomial_slice = try env.rBinomialSlice(100, 20, 0.4); defer allocator.free(binomial_samples); </code> } ``` To initialize a <code>RandomEnvironment</code> with a particular seed, use the <code>initWithSeed</code> method: <code>zig var env = try zprob.RandomEnvironment.initWithSeed(1234567890, allocator); defer env.deinit();</code> Distributions API While the easiest way to get started using <code>zprob</code> is with the <code>RandomEnvironment</code> struct, for users wanting more fine-grained control over the construction and usage of different probability distributions, <code>zprob</code> provides a lower level "Distributions API". ```zig const std = @import("std"); const zprob = @import("zprob"); pub fn main() !void { // Set up random generator. const seed: u64 = @intCast(std.time.microTimestamp()); var prng = std.Random.DefaultPrng.init(seed); var rand = prng.random(); <code>var beta = zprob.Beta(f64).init(&amp;rand); var binomial = zprob.Binomial(u8, f64).init(&amp;rand); var b1: f64 = undefined; var b2: u8 = undefined; for 0..100 |_| { b1 = try beta.sample(1.0, 5.0); b2 = try binomial.sample(20, b1); } </code> } ``` Example Projects As mentioned briefly above, there are several projects in the <a>examples/</a> folder that demonstrate the usage of <code>zprob</code> for different applications: <ul> <li><strong>approximate_bayes:</strong> Uses approximate Bayesian computation to estimate the posterior mean and standard deviation of a normal distribution using a small sample of observations.</li> <li><strong>compound_distributions:</strong> Illustrates how to generate samples from compound probability distributions such as the Beta-Binomial.</li> <li><strong>distribution_sampling:</strong> Shows the basics of the "Distributions API" through the construction of distribution structs with different underlying types.</li> <li><strong>enemy_spawner:</strong> Shows a gamedev motivated use case where distinct enemy types are sampled with different frequencies, are given different stats based on their type, and are placed randomly on the level map.</li> </ul> Available Distributions <strong>Discrete Probability Distributions</strong> <a>Bernoulli</a> :: <a>Binomial</a> :: <a>Geometric</a> :: <a>Multinomial</a> :: <a>Negative Binomial</a> :: <a>Poisson</a> :: <a>Uniform</a> <strong>Continuous Probability Distributions</strong> <a>Beta</a> :: <a>Cauchy</a> :: <a>Chi-squared</a> :: <a>Dirichlet</a> :: <a>Exponential</a> :: <a>Gamma</a> :: <a>Normal</a> :: <a>Uniform</a> Installation To include <code>zprob</code> in your Zig project, you can add it to your <code>build.zig.zon</code> file using the <code>zig fetch</code> command. The <code>main</code> branch tracks the latest release of Zig (currently v0.14.0) and can be added as follows: <code>zig fetch --save git+https://github.com/pblischak/zprob/</code> The <code>nightly</code> branch tracks the Zig <code>master</code> branch and can be added by adding <code>#nightly</code> to the git URL: <code>zig fetch --save git+https://github.com/pblischak/zprob/#nightly</code> Then, in the <code>build.zig</code> file, add the following lines within the <code>build</code> function to include <code>zprob</code> as a module: ```zig pub fn build(b: *std.Build) void { // exe setup... <code>const zprob_dep = b.dependency("zprob", .{ .target = target, .optimize = optimize, }); const zprob_module = zprob_dep.module("zprob"); exe.root_module.addImport("zprob", zprob_module); // additional build steps... </code> } ``` Check out the build files in the <a>examples/</a> folder for some demos of complete sample code projects. Issues If you run into any problems while using <code>zprob</code>, please consider filing an issue describing the problem, as well as any steps that may be required to reproduce the problem. Contributing We are open for contributions! Please see our contributing guide for more information on how you can help build new features for <code>zprob</code>. Other Useful Links <ul> <li><a>https://ziglang.org/documentation/master/std/#std.Random</a></li> <li><a>https://zig.guide/standard-library/random-numbers</a></li> <li><a>https://github.com/statrs-dev/statrs</a></li> <li><a>https://github.com/rust-random/rand_distr</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/1552770?v=4
notcurses-zig
neurocyte/notcurses-zig
2023-03-25T14:23:35Z
Zig bindings and packaging for notcurses
master
0
10
1
10
https://api.github.com/repos/neurocyte/notcurses-zig/tags
MIT
[ "tui", "zig", "zig-package" ]
29
false
2025-03-20T12:52:26Z
true
true
unknown
github
[ { "commit": "82365801e2042b1b9c62d199df5958f1d87f9fd0.tar.gz", "name": "notcurses", "tar_url": "https://github.com/neurocyte/notcurses/archive/82365801e2042b1b9c62d199df5958f1d87f9fd0.tar.gz.tar.gz", "type": "remote", "url": "https://github.com/neurocyte/notcurses" }, { "commit": "83c901...
Zig bindings and package for notcurses This package provides build scripts and basic (WIP) bindings for building notcurses applications in Zig. See <code>src/ncinputtest.zig</code> for a basic example application. Should generally build with zig nightly.
[]
https://avatars.githubusercontent.com/u/6756180?v=4
anotherBuildStep
kassane/anotherBuildStep
2024-01-29T18:21:59Z
zig build add-on (add more toolchains [LLVM-based] support)
main
6
10
0
10
https://api.github.com/repos/kassane/anotherBuildStep/tags
MPL-2.0
[ "build-system", "cross-compilation", "cross-compile", "d", "dlang", "flang", "fortran", "rust", "swift", "zig", "zig-package" ]
122
false
2025-05-05T18:10:52Z
true
true
0.14.0
github
[]
anotherBuildStep (a.k.a aBS) Overview <code>anotherBuildStep</code> is a project designed to leverage the Zig build system (<code>build.zig</code>) for building projects with various other toolchains. This allows developers to use Zig as a unified build system across different environments and toolsets. TODO <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> ldc2 support <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> flang-new support <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> rustc (no cargo) support <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> ~~rustc (cargo) support~~ (need to figure out how to get the cargo build system to work) <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> swiftc-6 support Required <ul> <li><a>zig</a> v0.14.0 or master</li> </ul> Supported <ul> <li><a>ldc2</a> v1.38.0 or latest-CI</li> <li><a>flang</a> (a.k.a flang-new) LLVM-18.1.3 or master</li> <li><a>rustc</a> stable or nightly</li> <li><a>swift</a> v6.0 or main-snapshots</li> </ul> Usage Make new project or add to existing project: In project folder, add this package as dependency on your <code>build.zig.zon</code> <code>bash $ zig fetch --save=abs git+https://github.com/kassane/anotherBuildStep</code> - add <code>const abs = @import("abs")</code> in <code>build.zig</code> ```zig const std = @import("std"); // get build.zig from pkg to extend your build.zig project (only pub content module) const abs = @import("abs"); // Dlang const ldc2 = abs.ldc2; // Fortran const flang = abs.flang; // Rust const rustc = abs.rust; // Swift const swiftc = abs.swift; // zig-cc wrapper const zcc = abs.zcc; pub fn build(b: *std.Build) !void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); <code>const exeDlang = try ldc2.BuildStep(b, .{ .name = "d_example", .target = target, .optimize = optimize, .sources = &amp;.{ "src/main.d", }, .dflags = &amp;.{ "-w", }, }); b.default_step.dependOn(&amp;exeDlang.step); // or const exeFortran = try flang.BuildStep(b, .{ .name = "fortran_example", .target = target, .optimize = optimize, .sources = &amp;.{ "src/main.f90", }, .use_zigcc = true, }); b.default_step.dependOn(&amp;exeFortran.step); // or const exeRust = try rustc.BuildStep(b, .{ .name = "rust_example", .target = target, .optimize = optimize, .source = b.path("src/main.rs"), .rflags = &amp;.{ "-C", "panic=abort", }, }); b.default_step.dependOn(&amp;exeRust.step); // or const exeSwift = try swift.BuildStep(b, .{ .name = "swift_example", .target = target, .optimize = optimize, .sources = &amp;.{ "examples/main.swift", }, .use_zigcc = true, }); b.default_step.dependOn(&amp;exeSwift.step); </code> } ```
[]