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/191431411?v=4
ZigServeX
QubitSync/ZigServeX
2024-12-21T05:58:53Z
null
main
0
0
0
0
https://api.github.com/repos/QubitSync/ZigServeX/tags
NOASSERTION
[ "htmx", "zig", "ziglang" ]
10
false
2025-01-13T13:05:16Z
true
true
0.13.0
github
[ { "commit": "master", "name": "zap", "tar_url": "https://github.com/zigzap/zap/archive/master.tar.gz", "type": "remote", "url": "https://github.com/zigzap/zap" } ]
Daily-Decode-
[]
https://avatars.githubusercontent.com/u/118304846?v=4
mini-RTS-zig-bot
pwalig/mini-RTS-zig-bot
2025-01-18T19:34:42Z
bot client for https://github.com/pwalig/mini-RTS-server
main
7
0
0
0
https://api.github.com/repos/pwalig/mini-RTS-zig-bot/tags
GPL-2.0
[ "bot", "command-line", "game-bot", "learning-zig", "rts-game", "tcp", "tcp-client", "zig", "zig-lang", "zig-language", "zig-programming-language", "ziglang" ]
85
false
2025-02-04T14:26:46Z
true
false
unknown
github
[]
mini-RTS-zig-bot bot client for <a>mini-RTS-game</a> Build with Zig <code>git clone https://github.com/pwalig/mini-RTS-zig-bot.git cd mini-RTS-zig-bot zig build -Doptimize=ReleaseSmall</code> Optionally set <code>-Doptimize=ReleaseFast</code>. <code>ReleaseSmall</code> is prefered due to fairly large delay between game ticks, meaning zig-bot does not need to be super performant. For information about installing zig see: https://ziglang.org/learn/getting-started/ Running the program <code>./mini-rts-zig-bot.exe &lt;host&gt; &lt;port&gt; [runModeOptions] ./mini-rts-zig-bot.exe [infoOptions]</code> Arguments: <ul> <li><code>&lt;host&gt;</code> - IPv4 address of the server</li> <li><code>&lt;port&gt;</code> - Port number of the server</li> </ul> <code>[runModeOptions]</code>: <ul> <li><code>--gamesToPlay &lt;number&gt;</code> - Play <code>&lt;number&gt;</code> games then exit (by default zig-bot tries to play unlimited number of games)</li> <li><code>--dontWin</code> - Stop mining resource when the bot is only one unit apart from winning</li> </ul> <code>[infoOptions]</code>: <ul> <li><code>-h</code>, <code>--help</code> - Print help and exit</li> <li><code>-v</code>, <code>--version</code> - Print version number and exit</li> </ul> Compatibility zig-bot is compatible with <a>mini-RTS-server</a> Version compatibility chart | version | 1.x.x | 2.x.x | 3.x.x | | --- | --- | --- | --- | | <strong>1.x.x</strong> | :x: | :x: | :heavy_check_mark: | <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> columns: server versions rows: zig-bot versions x stands for any version number </blockquote> Generally server will be 2 major versions ahead.
[]
https://avatars.githubusercontent.com/u/56176644?v=4
zerv
pchchv/zerv
2024-08-12T10:18:04Z
HTTP/1.1 server written in zig.
main
0
0
0
0
https://api.github.com/repos/pchchv/zerv/tags
Apache-2.0
[ "http", "http-server", "zig", "ziglang" ]
246
false
2025-03-26T07:16:11Z
true
true
unknown
github
[]
zerv HTTP/1.1 server written in zig. ```zig const std = @import("std"); const zerv = @import("zerv"); pub fn main() !void { const allocator = gpa.allocator(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; // In more advance cases, // a custom “Handler” will be used instead of “void”. // The last parameter is the handler instance, // since the handler is “void”, // the value void ({}) is passed. var server = try zerv.Server(void).init(allocator, .{.port = 5882}, {}); defer { // clean shutdown, finishes serving any live request server.stop(); server.deinit(); } var router = server.router(.{}); router.get("/api/user/:id", getUser, .{}); // blocks try server.listen(); } fn getUser(req: <em>zerv.Request, res: </em>zerv.Response) !void { res.status = 200; try res.json(.{.id = req.param("id").?, .name = "Teg"}, .{}); } ``` Examples See the <a>examples</a> folder for examples. If you clone this repository, you can run <code>zig build example_#</code> to run a specific example: <code>bash $ zig build example_1 listening http://localhost:8800/</code> Installation 1) Add zerv as a dependency in your <code>build.zig.zon</code>: <code>bash zig fetch --save git+https://github.com/pchchv/zerv#master</code> 2) In your <code>build.zig</code>, add the <code>zerv</code> module as a dependency you your program: ```zig const zerv = b.dependency("zerv", .{ .target = target, .optimize = optimize, }); // the executable from your call to b.addExecutable(...) exe.root_module.addImport("zerv", zerv.module("zerv")); ``` Why not std.http.Server <code>std.http.Server</code> is very slow and assumes well-behaved clients. There are many implementations of the Zig HTTP server. Most of them bypass <code>std.http.Server</code> and tend to be slow. Benchmarks will help to verify this. It should be canceled that some wrap C libraries and run faster. zerv is written in Zig, without using <code>std.http.Server</code>. On M2, a basic request can reach 140K requests per second. Handler When a non-void Handler is used, the value given to <code>Server(H).init</code> is passed to every action. This is how application-specific data can be passed into your actions. ```zig const pg = @import("pg"); const std = @import("std"); const zerv = @import("zerv"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); var db = try pg.Pool.init(allocator, .{ .connect = .{ .port = 5432, .host = "localhost"}, .auth = .{.username = "user", .database = "db", .password = "pass"} }); defer db.deinit(); var app = App{ .db = db, }; var server = try zerv.Server(*App).init(allocator, .{.port = 5882}, &amp;app); var router = server.router(.{}); router.get("/api/user/:id", getUser, .{}); try server.listen(); } const App = struct { db: *pg.Pool, }; fn getUser(app: <em>App, req: </em>zerv.Request, res: *zerv.Response) !void { const user_id = req.param("id").?; var row = try app.db.row("select name from users where id = $1", .{user_id}) orelse { res.status = 404; res.body = "Not found"; return; }; defer row.deinit() catch {}; try res.json(.{ .id = user_id, .name = row.get([]u8, 0), }, .{}); } ``` Custom Dispatch Beyond sharing state, your custom handler can be used to control how zerv behaves. By defining a public <code>dispatch</code> method you can control how (or even <strong>if</strong>) actions are executed. For example, to log timing, you could do: ```zig const App = struct { pub fn dispatch(self: <em>App, action: zerv.Action(</em>App), req: <em>zerv.Request, res: </em>zerv.Response) !void { var timer = try std.time.Timer.start(); <code>// your `dispatch` doesn't _have_ to call the action try action(self, req, res); const elapsed = timer.lap() / 1000; // ns -&gt; us std.log.info("{} {s} {d}", .{req.method, req.url.path, elapsed}); </code> } }; ``` Per-Request Context The 2nd parameter, <code>action</code>, is of type <code>zerv.Action(*App)</code>. This is a function pointer to the function you specified when setting up the routes. As we've seen, this works well to share global data. But, in many cases, you'll want to have request-specific data. Consider the case where you want your <code>dispatch</code> method to conditionally load a user (maybe from the <code>Authorization</code> header of the request). How would you pass this <code>User</code> to the action? You can't use the <code>*App</code> directly, as this is shared concurrently across all requests. To achieve this, we'll add another structure called <code>RequestContext</code>. You can call this whatever you want, and it can contain any fields of methods you want. <code>zig const RequestContext = struct { // You don't have to put a reference to your global data. // But chances are you'll want. app: *App, user: ?User, };</code> We can now change the definition of our actions and <code>dispatch</code> method: ```zig fn getUser(ctx: <em>RequestContext, req: </em>zerv.Request, res: *zerv.Response) !void { // can check if ctx.user is != null } const App = struct { pub fn dispatch(self: <em>App, action: zerv.Action(</em>RequestContext), req: <em>zerv.Request, res: </em>zerv.Response) !void { var ctx = RequestContext{ .app = self, .user = self.loadUser(req), } return action(&amp;ctx, req, res); } fn loadUser(self: <em>App, req: </em>zerv.Request) ?User { // todo, maybe using req.header("authorizaation") } }; ``` zerv infers the type of the action based on the 2nd parameter of your handler's <code>dispatch</code> method. If you use a <code>void</code> handler or your handler doesn't have a <code>dispatch</code> method, then you won't interact with <code>zerv.Action(H)</code> directly. Not Found If your handler has a public <code>notFound</code> method, it will be called whenever a path doesn't match a found route: <code>zig const App = struct { pub fn notFound(_: *App, req: *zerv.Request, res: *zerv.Response) !void { std.log.info("404 {} {s}", .{req.method, req.url.path}); res.status = 404; res.body = "Not Found"; } };</code> Error Handler If your handler has a public <code>uncaughtError</code> method, it will be called whenever there's an unhandled error. This could be due to some internal zerv bug, or because your action return an error. <code>zig const App = struct { pub fn uncaughtError(self: *App, _: *Request, res: *Response, err: anyerror) void { std.log.info("500 {} {s} {}", .{req.method, req.url.path, err}); res.status = 500; res.body = "sorry"; } };</code> Notice that, unlike <code>notFound</code> and other normal actions, the <code>uncaughtError</code> method cannot return an error itself. Takeover For the most control, you can define a <code>handle</code> method. This circumvents most of zerv's dispatching, including routing. Frameworks like JetZig hook use <code>handle</code> in order to provide their own routing and dispatching. When you define a <code>handle</code> method, then any <code>dispatch</code>, <code>notFound</code> and <code>uncaughtError</code> methods are ignored by zerv. <code>zig const App = struct { pub fn handle(app: *App, req: *Request, res: *Response) void { // todo } };</code> The behavior <code>zerv.Server(H)</code> is controlled by The library supports both simple and complex use cases. A simple use case is shown below. It's initiated by the call to <code>zerv.Server()</code>: ```zig const std = @import("std"); const zerv = @import("zerv"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); <code>var server = try zerv.Server().init(allocator, .{.port = 5882}); // overwrite the default notFound handler server.notFound(notFound); // overwrite the default error handler server.errorHandler(errorHandler); var router = server.router(.{}); // use get/post/put/head/patch/options/delete // you can also use "all" to attach to all methods router.get("/api/user/:id", getUser, .{}); // start the server in the current thread, blocking. try server.listen(); </code> } fn getUser(req: <em>zerv.Request, res: </em>zerv.Response) !void { // status code 200 is implicit. <code>// The json helper will automatically set the res.content_type = zerv.ContentType.JSON; // Here we're passing an inferred anonymous structure, but you can pass anytype // (so long as it can be serialized using std.json.stringify) try res.json(.{.id = req.param("id").?, .name = "Teg"}, .{}); </code> } fn notFound(_: <em>zerv.Request, res: </em>zerv.Response) !void { res.status = 404; <code>// you can set the body directly to a []u8, but note that the memory // must be valid beyond your handler. Use the res.arena if you need to allocate // memory for the body. res.body = "Not Found"; </code> } // note that the error handler return <code>void</code> and not <code>!void</code> fn errorHandler(req: <em>zerv.Request, res: </em>zerv.Response, err: anyerror) void { res.status = 500; res.body = "Internal Server Error"; std.log.warn("zerv: unhandled exception for request: {s}\nErr: {}", .{req.url.raw, err}); } ``` Memory and Arenas Any allocations made for the response, such as the body or a header, must remain valid until <strong>after</strong> the action returns. To achieve this, use <code>res.arena</code> or the <code>res.writer()</code>: ```zig fn arenaExample(req: <em>zerv.Request, res: </em>zerv.Response) !void { const query = try req.query(); const name = query.get("name") orelse "stranger"; res.body = try std.fmt.allocPrint(res.arena, "Hello {s}", .{name}); } fn writerExample(req: <em>zerv.Request, res: </em>zerv.Response) !void { const query = try req.query(); const name = query.get("name") orelse "stranger"; try std.fmt.format(res.writer(), "Hello {s}", .{name}); } ``` Alternatively, you can explicitly call <code>res.write()</code>. Once <code>res.write()</code> returns, the response is sent and your action can cleanup/release any resources. <code>res.arena</code> is actually a configurable-sized thread-local buffer that fallsback to an <code>std.heap.ArenaAllocator</code>. In other words, it's fast so it should be your first option for data that needs to live only until your action exits. zerv.Request The following fields are the most useful: <ul> <li><code>method</code> - an zerv.Method enum</li> <li><code>arena</code> - A fast thread-local buffer that fallsback to an ArenaAllocator, same as <code>res.arena</code>.</li> <li><code>url.path</code> - the path of the request (<code>[]const u8</code>)</li> <li><code>address</code> - the std.net.Address of the client</li> </ul> If you give your route a <code>data</code> configuration, the value can be retrieved from the optional <code>route_data</code> field of the request. Path Parameters The <code>param</code> method of <code>*Request</code> returns an <code>?[]const u8</code>. For example, given the following path: <code>zig router.get("/api/users/:user_id/favorite/:id", user.getFavorite, .{});</code> Then we could access the <code>user_id</code> and <code>id</code> via: <code>zig pub fn getFavorite(req *http.Request, res: *http.Response) !void { const user_id = req.param("user_id").?; const favorite_id = req.param("id").?; ...</code> In the above, passing any other value to <code>param</code> would return a null object (since the route associated with <code>getFavorite</code> only defines these 2 parameters). Given that routes are generally statically defined, it should not be possible for <code>req.param</code> to return an unexpected null. However, it <em>is</em> possible to define two routes to the same action: ```zig router.put("/api/users/:user_id/favorite/:id", user.updateFavorite, .{}); // currently logged in user, maybe? router.put("/api/use/favorite/:id", user.updateFavorite, .{}); ``` In which case the optional return value of <code>param</code> might be useful. Header Values Similar to <code>param</code>, header values can be fetched via the <code>header</code> function, which also returns a <code>?[]const u8</code>: ```zig if (req.header("authorization")) |auth| { } else { // not logged in?: } ``` Header names are lowercase. Values maintain their original casing. To iterate over all headers, use: <code>zig var it = req.headers.iterator(); while (it.next()) |kv| { // kv.key // kv.value }</code> QueryString The framework does not automatically parse the query string. Therefore, its API is slightly different. ```zig const query = try req.query(); if (query.get("search")) |search| { } else { // no search parameter }; ``` On first call, the <code>query</code> function attempts to parse the querystring. This requires memory allocations to unescape encoded values. The parsed value is internally cached, so subsequent calls to <code>query()</code> are fast and cannot fail. The original casing of both the key and the name are preserved. To iterate over all query parameters, use: <code>zig var it = req.query().iterator(); while (it.next()) |kv| { // kv.key // kv.value }</code> Body The body of the request, if any, can be accessed using <code>req.body()</code>. This returns a <code>?[]const u8</code>. Json Body The <code>req.json(TYPE)</code> function is a wrapper around the <code>body()</code> function which will call <code>std.json.parse</code> on the body. This function does not consider the content-type of the request and will try to parse any body. ```zig if (try req.json(User)) |user| { } ``` JsonValueTree Body The <code>req.jsonValueTree()</code> function is a wrapper around the <code>body()</code> function which will call <code>std.json.Parse</code> on the body, returning a <code>!?std.jsonValueTree</code>. This function does not consider the content-type of the request and will try to parse any body. <code>zig if (try req.jsonValueTree()) |t| { // probably want to be more defensive than this const product_type = r.root.Object.get("type").?.String; //... }</code> JsonObject Body The even more specific <code>jsonObject()</code> function will return an <code>std.json.ObjectMap</code> provided the body is a map <code>zig if (try req.jsonObject()) |t| { // probably want to be more defensive than this const product_type = t.get("type").?.String; //... }</code> Form Data The body of the request, if any, can be parsed as a "x-www-form-urlencoded "value using <code>req.formData()</code>. The <code>request.max_form_count</code> configuration value must be set to the maximum number of form fields to support. This defaults to 0. This behaves similarly to <code>query()</code>. On first call, the <code>formData</code> function attempts to parse the body. This can require memory allocations to unescape encoded values. The parsed value is internally cached, so subsequent calls to <code>formData()</code> are fast and cannot fail. The original casing of both the key and the name are preserved. To iterate over all fields, use: <code>zig var it = (try req.formData()).iterator(); while (it.next()) |kv| { // kv.key // kv.value }</code> Once this function is called, <code>req.multiFormData()</code> will no longer work (because the body is assumed parsed). Multi Part Form Data Similar to the above, <code>req.multiFormData()</code> can be called to parse requests with a "multipart/form-data" content type. The <code>request.max_multiform_count</code> configuration value must be set to the maximum number of form fields to support. This defaults to 0. This is a different API than <code>formData</code> because the return type is different. Rather than a simple string=&gt;value type, the multi part form data value consists of a <code>value: []const u8</code> and a <code>filename: ?[]const u8</code>. On first call, the <code>multiFormData</code> function attempts to parse the body. The parsed value is internally cached, so subsequent calls to <code>multiFormData()</code> are fast and cannot fail. The original casing of both the key and the name are preserved. To iterate over all fields, use: <code>zig var it = req.multiFormData.iterator(); while (it.next()) |kv| { // kv.key // kv.value.value // kv.value.filename (optional) }</code> Once this function is called, <code>req.formData()</code> will no longer work (because the body is assumed parsed). Advance warning: This is one of the few methods that can modify the request in-place. For most people this won't be an issue, but if you use <code>req.body()</code> and <code>req.multiFormData()</code>, say to log the raw body, the content-disposition field names are escaped in-place. It's still safe to use <code>req.body()</code> but any content-disposition name that was escaped will be a little off. zerv.Response The following fields are the most useful: <ul> <li><code>status</code> - set the status code, by default, each response starts off with a 200 status code</li> <li><code>content_type</code> - an zerv.ContentType enum value. This is a convenience and optimization over using the <code>res.header</code> function.</li> <li><code>arena</code> - A fast thread-local buffer that fallsback to an ArenaAllocator, same as <code>req.arena</code>.</li> </ul> Body The simplest way to set a body is to set <code>res.body</code> to a <code>[]const u8</code>. <strong>However</strong> the provided value must remain valid until the body is written, which happens after the function exists or when <code>res.write()</code> is explicitly called. Dynamic Content You can use the <code>res.arena</code> allocator to create dynamic content: <code>zig const query = try req.query(); const name = query.get("name") orelse "stranger"; res.body = try std.fmt.allocPrint(res.arena, "Hello {s}", .{name});</code> Memory allocated with <code>res.arena</code> will exist until the response is sent. io.Writer <code>res.writer()</code> returns an <code>std.io.Writer</code>. Various types support writing to an io.Writer. For example, the built-in JSON stream writer can use this writer: <code>zig var ws = std.json.writeStream(res.writer(), 4); try ws.beginObject(); try ws.objectField("name"); try ws.emitString(req.param("name").?); try ws.endObject();</code> JSON The <code>res.json</code> function will set the content_type to <code>zerv.ContentType.JSON</code> and serialize the provided value using <code>std.json.stringify</code>. The 2nd argument to the json function is the <code>std.json.StringifyOptions</code> to pass to the <code>stringify</code> function. This function uses <code>res.writer()</code> explained above. Header Value Set header values using the <code>res.header(NAME, VALUE)</code> function: <code>zig res.header("Location", "/");</code> The header name and value are sent as provided. Both the name and value must remain valid until the response is sent, which will happen outside of the action. Dynamic names and/or values should be created and or dupe'd with <code>res.arena</code>. <code>res.headerOpts(NAME, VALUE, OPTS)</code> can be used to dupe the name and/or value: <code>zig try res.headerOpts("Location", location, .{.dupe_value = true});</code> <code>HeaderOpts</code> currently supports <code>dupe_name: bool</code> and <code>dupe_value: bool</code>, both default to <code>false</code>. Writing By default, zerv will automatically flush your response. In more advance cases, you can use <code>res.write()</code> to explicitly flush it. This is useful in cases where you have resources that need to be freed/released only after the response is written. ``` Router You get an instance of the router by calling <code>server.route(.{})</code>. Currently, the configuration takes a single parameter: <ul> <li><code>middlewares</code> - A list of middlewares to apply to each request. These middleware will be executed even for requests with no matching route (i.e. not found). An individual route can opt-out of these middleware, see the <code>middleware_strategy</code> route configuration.</li> </ul> You can use the <code>get</code>, <code>put</code>, <code>post</code>, <code>head</code>, <code>patch</code>, <code>trace</code>, <code>delete</code> or <code>options</code> method of the router to define a router. You can also use the special <code>all</code> method to add a route for all methods. These functions can all <code>@panic</code> as they allocate memory. Each function has an equivalent <code>tryXYZ</code> variant which will return an error rather than panicking: ```zig // this can panic if it fails to create the route router.get("/", index, .{}); // this returns a !void (which you can try/catch) router.tryGet("/", index, .{}); ``` The 3rd parameter is a route configuration. It allows you to speficy a different <code>handler</code> and/or <code>dispatch</code> method and/or <code>middleware</code>. <code>zig // this can panic if it fails to create the route router.get("/", index, .{ .dispatcher = Handler.dispathAuth, .handler = &amp;auth_handler, .middlewares = &amp;.{cors_middleware}, });</code> Configuration The last parameter to the various <code>router</code> methods is a route configuration. In many cases, you'll probably use an empty configuration (<code>.{}</code>). The route configuration has three fields: <ul> <li><code>dispatcher</code> - The dispatch method to use. This overrides the default dispatcher, which is either zerv built-in dispatcher or <a>your handler's <code>dispatch</code> method</a>.</li> <li><code>handler</code> - The handler instance to use. The default handler is the 3rd parameter passed to <code>Server(H).init</code> but you can override this on a route-per-route basis.</li> <li><code>middlewares</code> - A list of <a>middlewares</a> to run. By default, no middlewares are run. By default, this list of middleware is appended to the list given to <code>server.route(.{.middlewares = .{....})</code>.</li> <li><code>middleware_strategy</code> - How the given middleware should be merged with the global middlewares. Defaults to <code>.append</code>, can also be <code>.replace</code>.</li> <li><code>data</code> - Arbitrary data (<code>*const anyopaque</code>) to make available to <code>req.route_data</code>. This must be a <code>const</code>.</li> </ul> You can specify a separate configuration for each route. To change the configuration for a group of routes, you have two options. The first, is to directly change the router's <code>handler</code>, <code>dispatcher</code> and <code>middlewares</code> field. Any subsequent routes will use these values: ```zig var server = try zerv.Server(Handler).init(allocator, .{.port = 5882}, &amp;handler); var router = server.router(.{}); // Will use Handler.dispatch on the &amp;handler instance passed to init // No middleware router.get("/route1", route1, .{}); router.dispatcher = Handler.dispathAuth; // uses the new dispatcher router.get("/route2", route2, .{}); router.handler = &amp;Handler{.public = true}; // uses the new dispatcher + new handler router.get("/route3", route3, .{.handler = Handler.dispathAuth}); ``` This approach is error prone though. New routes need to be carefully added in the correct order so that the desired handler, dispatcher and middlewares are used. A more scalable option is to use route groups. Groups Defining a custom dispatcher or custom global data on each route can be tedious. Instead, consider using a router group: <code>zig var admin_routes = router.group("/admin", .{ .handler = &amp;auth_handler, .dispatcher = Handler.dispathAuth, .middlewares = &amp;.{cors_middleware}, }); admin_routes.get("/users", listUsers, .{}); admin_routs.delete("/users/:id", deleteUsers, .{});</code> The first parameter to <code>group</code> is a prefix to prepend to each route in the group. An empty prefix is acceptable. Thus, route groups can be used to configure either a common prefix and/or a common configuration across multiple routes. Casing You <strong>must</strong> use a lowercase route. You can use any casing with parameter names, as long as you use that same casing when getting the parameter. Parameters Routing supports parameters, via <code>:CAPTURE_NAME</code>. The captured values are available via <code>req.params.get(name: []const u8) ?[]const u8</code>. Glob You can glob an individual path segment, or the entire path suffix. For a suffix glob, it is important that no trailing slash is present. <code>zig // prefer using a custom `notFound` handler than a global glob. router.all("/*", not_found, .{}); router.get("/api/*/debug", .{})</code> When multiple globs are used, the most specific will be selected. E.g., give the following two routes: <code>zig router.get("/*", not_found, .{}); router.get("/info/*", any_info, .{})</code> A request for "/info/debug/all" will be routed to <code>any_info</code>, whereas a request for "/over/9000" will be routed to <code>not_found</code>. Limitations The router has several limitations which might not get fixed. These specifically resolve around the interaction of globs, parameters and static path segments. Given the following routes: <code>zig router.get("/:any/users", route1, .{}); router.get("/hello/users/test", route2, .{});</code> You would expect a request to "/hello/users" to be routed to <code>route1</code>. However, no route will be found. Globs interact similarly poorly with parameters and static path segments. Resolving this issue requires keeping a stack (or visiting the routes recursively), in order to back-out of a dead-end and trying a different path. This seems like an unnecessarily expensive thing to do, on each request, when, in my opinion, such route hierarchies are uncommon. Middlewares In general, use a <a>custom dispatch</a> function to apply custom logic, such as logging, authentication and authorization. If you have complex route-specific logic, middleware can also be leveraged. A middleware is a struct which exposes a nested <code>Config</code> type, a public <code>init</code> function and a public <code>execute</code> method. It can optionally define a <code>deinit</code> method. See the built-in <a>CORS middleware</a> or the sample <a>logger middleware</a> for examples. A middleware instance is created using <code>server.middleware()</code> and can then be used with the router: ```zig var server = try zerv.Server(void).init(allocator, .{.port = 5882}, {}); // the middleware method takes the struct name and its configuration const cors = try server.middleware(zerv.middleware.Cors, .{ .origin = "https://www.openmymind.net/", }); // apply this middleware to all routes (unless the route // explicitly opts out) var router = server.router(.{.middlewares = .{cors}}); // or we could add middleware on a route-per-route bassis router.get("/v1/users", .{.middlewares = &amp;.{cors}}); // by default, middlewares on a route are appended to the global middlewares // we can replace them instead by specifying a middleware_strategy router.get("/v1/metrics", .{.middlewares = &amp;.{cors}, .middleware_strategy = .replace}); ``` Cors zerv comes with a built-in CORS middleware: <code>zerv.middlewares.Cors</code>. Its configuration is: <ul> <li><code>origin: []const u8</code></li> <li><code>headers: ?[]const u8 = null</code></li> <li><code>methods: ?[]const u8 = null</code></li> <li><code>max_age: ?[]const u8 = null</code></li> </ul> The CORS middleware will include a <code>Access-Control-Allow-Origin: $origin</code> to every request. For an OPTIONS request where the <code>sec-fetch-mode</code> is set to <code>cors, the</code>Access-Control-Allow-Headers<code>,</code>Access-Control-Allow-Methods<code>and</code>Access-Control-Max-Age` response headers will optionally be set based on the configuration. Configuration The second parameter given to <code>Server(H).init</code> is an <code>zerv.Config</code>. When running in <a>blocking mode</a> (e.g. on Windows) a few of these behave slightly, but not drastically, different. There are many configuration options. <code>thread_pool.buffer_size</code> is the single most important value to tweak. Usage of <code>req.arena</code>, <code>res.arena</code>, <code>res.writer()</code> and <code>res.json()</code> all use a fallback allocator which first uses a fast thread-local buffer and then an underlying arena. The total memory this will require is <code>thread_pool.count * thread_pool.buffer_size</code>. Since <code>thread_pool.count</code> is usually small, a large <code>buffer_size</code> is reasonable. <code>request.buffer_size</code> must be large enough to fit the request header. Any extra space might be used to read the body. However, there can be up to <code>workers.count * workers.max_conn</code> pending requests, so a large <code>request.buffer_size</code> can take up a lot of memory. Instead, consider keeping <code>request.buffer_size</code> only large enough for the header (plus a bit of overhead for decoding URL-escape values) and set <code>workers.large_buffer_size</code> to a reasonable size for your incoming request bodies. This will take <code>workers.count * workers.large_buffer_count * workers.large_buffer_size</code> memory. Buffers for request bodies larger than <code>workers.large_buffer_size</code> but smaller than <code>request.max_body_size</code> will be dynamic allocated. In addition to a bit of overhead, at a minimum, zerv will use: <code>zig (thread_pool.count * thread_pool.buffer_size) + (workers.count * workers.large_buffer_count * workers.large_buffer_size) + (workers.count * workers.min_conn * request.buffer_size)</code> Possible values, along with their default, are: ```zig try zerv.listen(allocator, &amp;router, .{ // Port to listen on .port = 5882, <code>// Interface address to bind to .address = "127.0.0.1", // unix socket to listen on (mutually exclusive with host&amp;port) .unix_path = null, // configure the workers which are responsible for: // 1 - accepting connections // 2 - reading and parsing requests // 3 - passing requests to the thread pool .workers = .{ // Number of worker threads // (blocking mode: handled differently) .count = 2, // Maximum number of concurrent connection each worker can handle // (blocking mode: currently ignored) .max_conn = 500, // Minimum number of connection states each worker should maintain // (blocking mode: currently ignored) .min_conn = 32, // A pool of larger buffers that can be used for any data larger than configured // static buffers. For example, if response headers don't fit in in // $response.header_buffer_size, a buffer will be pulled from here. // This is per-worker. .large_buffer_count = 16, // The size of each large buffer. .large_buffer_size = 65536, // Size of bytes retained for the connection arena between use. This will // result in up to `count * min_conn * retain_allocated_bytes` of memory usage. .retain_allocated_bytes = 4096, }, // configures the threadpool which processes requests. The threadpool is // where your application code runs. .thread_pool = .{ // Number threads. If you're handlers are doing a lot of i/o, a higher // number might provide better throughput // (blocking mode: handled differently) .count = 4, // The maximum number of pending requests that the thread pool will accept // This applies back pressure to the above workers and ensures that, under load // pending requests get precedence over processing new requests. .backlog = 500, // Size of the static buffer to give each thread. Memory usage will be // `count * buffer_size`. If you're making heavy use of either `req.arena` or // `res.arena`, this is likely the single easiest way to gain performance. .buffer_size = 8192, }, // options for tweaking request processing .request = .{ // Maximum body size that we'll process. We can allocate up // to this much memory per request for the body. Internally, we might // keep this memory around for a number of requests as an optimization. .max_body_size: usize = 1_048_576, // This memory is allocated upfront. The request header _must_ fit into // this space, else the request will be rejected. .buffer_size: usize = 4_096, // Maximum number of headers to accept. // Additional headers will be silently ignored. .max_header_count: usize = 32, // Maximum number of URL parameters to accept. // Additional parameters will be silently ignored. .max_param_count: usize = 10, // Maximum number of query string parameters to accept. // Additional parameters will be silently ignored. .max_query_count: usize = 32, // Maximum number of x-www-form-urlencoded fields to support. // Additional parameters will be silently ignored. This must be // set to a value greater than 0 (the default) if you're going // to use the req.formData() method. .max_form_count: usize = 0, // Maximum number of multipart/form-data fields to support. // Additional parameters will be silently ignored. This must be // set to a value greater than 0 (the default) if you're going // to use the req.multiFormData() method. .max_multiform_count: usize = 0, }, // options for tweaking response object .response = .{ // The maximum number of headers to accept. // Additional headers will be silently ignored. .max_header_count: usize = 16, }, .timeout = .{ // Time in seconds that keepalive connections will be kept alive while inactive .keepalive = null, // Time in seconds that a connection has to send a complete request .request = null // Maximum number of a requests allowed on a single keepalive connection .request_count = null, }, .websocket = .{ // refer to https://github.com/pchchv/websocket.zig#config max_message_size: ?usize = null, small_buffer_size: ?usize = null, small_buffer_pool: ?usize = null, large_buffer_size: ?usize = null, large_buffer_pool: ?u16 = null, }, </code> }); ``` Blocking Mode kqueue (BSD, MacOS) or epoll (Linux) are used on supported platforms. On all other platforms (most notably Windows), a more naive thread-per-connection with blocking sockets is used. The comptime-safe, <code>zerv.blockingMode() bool</code> function can be called to determine which mode zerv is running in (when it returns <code>true</code>, then you're running the simpler blocking mode). While you should always run zerv behind a reverse proxy, it's particularly important to do so in blocking mode due to the ease with which external connections can DOS the server. In blocking mode, <code>config.workers.count</code> is hard-coded to 1. (This worker does considerably less work than the non-blocking workers). If <code>config.workers.count</code> is &gt; 1, than those extra workers will go towards <code>config.thread_pool.count</code>. In other words: In non-blocking mode, if <code>config.workers.count = 2</code> and <code>config.thread_pool.count = 4</code>, then you'll have 6 threads: 2 threads that read+parse requests and send replies, and 4 threads to execute application code. In blocking mode, the same config will also use 6 threads, but there will only be: 1 thread that accepts connections, and 5 threads to read+parse requests, send replies and execute application code. The goal is for the same configuration to result in the same # of threads regardless of the mode, and to have more thread_pool threads in blocking mode since they do more work. In blocking mode, <code>config.workers.large_buffer_count</code> defaults to the size of the thread pool. In blocking mode, <code>config.workers.max_conn</code> and <code>config.workers.min_conn</code> are ignored. The maximum number of connections is simply the size of the thread_pool. If you aren't using a reverse proxy, you should always set the <code>config.timeout.request</code>, <code>config.timeout.keepalive</code> and <code>config.timeout.request_count</code> settings. In blocking mode, consider using conservative values: say 5/5/5 (5 second request timeout, 5 second keepalive timeout, and 5 keepalive count). You can monitor the <code>zerv_timeout_active</code> metric to see if the request timeout is too low. Timeouts The configuration settings under the <code>timeouts</code> section are designed to help protect the system against basic DOS attacks (say, by connecting and not sending data). However it is recommended that you leave these null (disabled) and use the appropriate timeout in your reverse proxy (e.g. NGINX). The <code>timeout.request</code> is the time, in seconds, that a connection has to send a complete request. The <code>timeout.keepalive</code> is the time, in second, that a connection can stay connected without sending a request (after the initial request has been sent). The connection alternates between these two timeouts. It starts with a timeout of <code>timeout.request</code> and after the response is sent and the connection is placed in the "keepalive list", switches to the <code>timeout.keepalive</code>. When new data is received, it switches back to <code>timeout.request</code>. When <code>null</code>, both timeouts default to 2_147_483_647 seconds (so not completely disabled, but close enough). The <code>timeout.request_count</code> is the number of individual requests allowed within a single keepalive session. This protects against a client consuming the connection by sending unlimited meaningless but valid HTTP requests. When the three are combined, it should be difficult for a problematic client to stay connected indefinitely. If you're running zerv on Windows (or, more generally, where <code>zerv.blockingMode()</code> returns true), please <a>read the section</a> as this mode of operation is more susceptible to DOS. Metrics A few basic metrics are collected using <a>metrics.zig</a>, a prometheus-compatible library. These can be written to an <code>std.io.Writer</code> using <code>try zerv.writeMetrics(writer)</code>. As an example: ```zig pub fn metrics(_: <em>zerv.Request, res: </em>zerv.Response) !void { const writer = res.writer(); try zerv.writeMetrics(writer); <code>// if we were also using pg.zig // try pg.writeMetrics(writer); </code> } ``` Since zerv does not provide any authorization, care should be taken before exposing this. The metrics are: <ul> <li><code>zerv_connections</code> - counts each TCP connection</li> <li><code>zerv_requests</code> - counts each request (should be &gt;= zerv_connections due to keepalive)</li> <li><code>zerv_timeout_active</code> - counts each time an "active" connection is timed out. An "active" connection is one that has (a) just connected or (b) started to send bytes. The timeout is controlled by the <code>timeout.request</code> configuration.</li> <li><code>zerv_timeout_keepalive</code> - counts each time an "keepalive" connection is timed out. A "keepalive" connection has already received at least 1 response and the server is waiting for a new request. The timeout is controlled by the <code>timeout.keepalive</code> configuration.</li> <li><code>zerv_alloc_buffer_empty</code> - counts number of bytes allocated due to the large buffer pool being empty. This may indicate that <code>workers.large_buffer_count</code> should be larger.</li> <li><code>zerv_alloc_buffer_large</code> - counts number of bytes allocated due to the large buffer pool being too small. This may indicate that <code>workers.large_buffer_size</code> should be larger.</li> <li><code>zerv_alloc_unescape</code> - counts number of bytes allocated due to unescaping query or form parameters. This may indicate that <code>request.buffer_size</code> should be larger.</li> <li><code>zerv_internal_error</code> - counts number of unexpected errors within zerv. Such errors normally result in the connection being abruptly closed. For example, a failing syscall to epoll/kqueue would increment this counter.</li> <li><code>zerv_invalid_request</code> - counts number of requests which zerv could not parse (where the request is invalid).</li> <li><code>zerv_header_too_big</code> - counts the number of requests which zerv rejects due to a header being too big (does not fit in <code>request.buffer_size</code> config).</li> <li><code>zerv_body_too_big</code> - counts the number of requests which zerv rejects due to a body being too big (is larger than <code>request.max_body_size</code> config).</li> </ul> Testing The <code>zerv.testing</code> namespace exists to help application developers setup an <code>*zerv.Request</code> and assert an <code>*zerv.Response</code>. Imagine we have the following partial action: ```zig fn search(req: <em>zerv.Request, res: </em>zerv.Response) !void { const query = try req.query(); const search = query.get("search") orelse return missingParameter(res, "search"); <code>// TODO ... </code> } fn missingParameter(res: *zerv.Response, parameter: []const u8) !void { res.status = 400; return res.json(.{.@"error" = "missing parameter", .parameter = parameter}, .{}); } ``` We can test the above error case like so: ```zig const ht = @import("zerv").testing; test "search: missing parameter" { // init takes the same Configuration used when creating the real server // but only the config.request and config.response settings have any impact var web_test = ht.init(.{}); defer web_test.deinit(); <code>try search(web_test.req, web_test.res); try web_test.expectStatus(400); try web_test.expectJson(.{.@"error" = "missing parameter", .parameter = "search"}); </code> } ``` Building the test Request The testing structure returns from <code>zerv.testing.init</code> exposes helper functions to set param, query and query values as well as the body: ```zig var web_test = ht.init(.{}); defer web_test.deinit(); web_test.param("id", "99382"); web_test.query("search", "tea"); web_test.header("Authorization", "admin"); web_test.body("over 9000!"); // OR web_test.json(.{.over = 9000}); // OR // This requires ht.init(.{.request = .{.max_form_count = 10}}) web_test.form(.{.over = "9000"}); // at this point, web_test.req has a param value, a query string value, a header value and a body. ``` As an alternative to the <code>query</code> function, the full URL can also be set. If you use <code>query</code> AND <code>url</code>, the query parameters of the URL will be ignored: <code>zig web_test.url("/power?over=9000");</code> Asserting the Response There are various methods to assert the response: <code>zig try web_test.expectStatus(200); try web_test.expectHeader("Location", "/"); try web_test.expectHeader("Location", "/"); try web_test.expectBody("{\"over\":9000}");</code> If the expected body is in JSON, there are two helpers available. First, to assert the entire JSON body, you can use <code>expectJson</code>: <code>zig try web_test.expectJson(.{.over = 9000});</code> Or, you can retrieve a <code>std.json.Value</code> object by calling <code>getJson</code>: <code>zig const json = try web_test.getJson(); try std.testing.expectEqual(@as(i64, 9000), json.Object.get("over").?.Integer);</code> For more advanced validation, use the <code>parseResponse</code> function to return a structure representing the parsed response: <code>zig const res = try web_test.parsedResponse(); try std.testing.expectEqual(@as(u16, 200), res.status); // use res.body for a []const u8 // use res.headers for a std.StringHashMap([]const u8) // use res.raw for the full raw response</code> HTTP Compliance This implementation may never be fully HTTP/1.1 compliant, as it is built with the assumption that it will sit behind a reverse proxy that is tolerant of non-compliant upstreams (e.g. nginx). (One example I know of is that the server doesn't include the mandatory Date header in the response.) Server Side Events Server Side Events can be enabled by calling <code>res.startEventStream()</code>. This method takes an arbitrary context and a function pointer. The provided function will be executed in a new thread, receiving the provided context and an <code>std.net.Stream</code>. Headers can be added (via <code>res.headers.add</code>) before calling <code>startEventStream()</code>. <code>res.body</code> must not be set (directly or indirectly). Calling <code>startEventStream()</code> automatically sets the <code>Content-Type</code>, <code>Cache-Control</code> and <code>Connection</code> header. ```zig fn handler(_: <em>Request, res: </em>Response) !void { try res.startEventStream(StreamContext{}, StreamContext.handle); } const StreamContext = struct { fn handle(self: StreamContext, stream: std.net.Stream) void { while (true) { // some event loop stream.writeAll("event: ....") catch return; } } } ``` Websocket zerv integrates with <a>https://github.com/pchchv/websocket.zig</a> by calling <code>zerv.upgradeWebsocket()</code>. First, your handler must have a <code>WebsocketHandler</code> declaration which is the WebSocket handler type used by <code>websocket.Server(H)</code>. ```zig const websocket = zerv.websocket; const Handler = struct { // App-specific data you want to pass when initializing // your WebSocketHandler const WebsocketContext = struct { }; // See the websocket.zig documentation. But essentially this is your // Application's wrapper around 1 websocket connection pub const WebsocketHandler = struct { conn: *websocket.Conn, <code>// ctx is arbitrary data you passs to zerv.upgradeWebsocket pub fn init(conn: *websocket.Conn, _: WebsocketContext) { return .{ .conn = conn, } } // echo back pub fn clientMessage(self: *WebsocketHandler, data: []const u8) !void { try self.conn.write(data); } </code> } }; ``` With this in place, you can call zerv.upgradeWebsocket() within an action: <code>zig fn ws(req: *zerv.Request, res: *zerv.Response) !void { if (try zerv.upgradeWebsocket(WebsocketHandler, req, res, WebsocketContext{}) == false) { // this was not a valid websocket handshake request // you should probably return with an error res.status = 400; res.body = "invalid websocket handshake"; return; } // Do not use `res` from this point on }</code> In websocket.zig, <code>init</code> is passed a <code>websocket.Handshake</code>. This is not the case with the zerv integration - you are expected to do any necessary validation of the request in the action. It is an undefined behavior if <code>Handler.WebsocketHandler</code> is not the same type passed to <code>zerv.upgradeWebsocket</code>.
[]
https://avatars.githubusercontent.com/u/149815296?v=4
timeout
posix-utilities/timeout
2024-09-12T03:53:12Z
POSIX.1-2024 timeout
main
2
0
0
0
https://api.github.com/repos/posix-utilities/timeout/tags
MPL-2.0
[ "posix", "posix-2024", "timeout", "zig" ]
17
false
2024-09-12T19:08:26Z
false
false
unknown
github
[]
<a><code>timeout</code></a> POSIX.1-2024 timeout <code>sh timeout [options] &lt;duration&gt; &lt;command&gt; [arguments...]</code> ```text -f send timeout signal to the proccess only, not the process group (when the group is sent the signal, 'timeout' briefly ignores it) -k kill the process with SIGKILL after duration (respects -f) -p preserve original exit status, regardless if timeout occured -s TERM by default, or the chosen signal such as 10, 10s, 2.5m, 24h, or 1.5d ``` Exit Status <code>text 0 no error (or no error from &lt;command&gt; with -p) &lt;n&gt; the return status of &lt;command&gt; (with -p) 124 if killed by timeout (if -p is NOT specified) 125 all other errors (if -p is NOT specified) 126 command not executable 127 command not found</code> Build Zig ```sh curl https://weib.sh/zig@v0.14 | sh source ~/.config/envman/PATH.env zig targets | jq -r ".libc[]" | sort -r ``` <code>sh zig build-exe ./timeout.zig -O ReleaseSmall mv ./timeout ~/bin/</code> ```sh zig build-exe ./timeout.zig -O ReleaseSmall -target aarch64-macos-none -femit-bin=timeout-darwin-apple-aarch64 zig build-exe ./timeout.zig -O ReleaseSmall -target x86_64-macos-none -femit-bin=timeout-darwin-apple-x86_64 works on musl too (no gnu/libc dependency) zig build-exe ./timeout.zig -O ReleaseSmall -target x86_64-linux-gnu -femit-bin=timeout-linux-unknown-x86_64 zig build-exe ./timeout.zig -O ReleaseSmall -target aarch64-linux-gnu -femit-bin=timeout-linux-unknown-aarch64 zig build-exe ./timeout.zig -O ReleaseSmall -target arm-linux-gnueabihf -femit-bin=timeout-linux-unknown-armv7l zig build-exe ./timeout.zig -O ReleaseSmall -target arm-linux-gnueabi -femit-bin=timeout-linux-unknown-armv6l not supported yet (will require windows allocator and win signal mapping) zig build-exe ./timeout.zig -O ReleaseSmall -target x86_64-windows-gnu -femit-bin=timeout-windows-pc-x86_64 zig build-exe ./timeout.zig -O ReleaseSmall -target aarch64-windows-gnu -femit-bin=timeout-windows-pc-aarch64 ``` Go ```sh curl https://weib.sh/go | sh source ~/.config/envman/PATH.env go tool dist list ``` <code>sh go build -o ./timeout ./timeout.go mv ./timeout ~/bin/</code> ```sh GOOS=darwin GOARCH=amd64 GOAMD64=v2 go build -o ./timeout-darwin-apple-x86_64 ./timeout.go GOOS=darwin GOARCH=arm64 go build -o ./timeout-darwin-apple-aarch64 ./timeout.go GOOS=linux GOARCH=amd64 GOAMD64=v2 go build -o ./timeout-linux-uknown-x86_64 ./timeout.go GOOS=linux GOARCH=arm64 go build -o ./timeout-linux-uknown-aarch64 ./timeout.go GOOS=linux GOARCH=arm GOARM=v7 go build -o ./timeout-linux-uknown-armv7l ./timeout.go GOOS=linux GOARCH=arm GOARM=v6 go build -o ./timeout-linux-uknown-armv6l ./timeout.go not supported yet (will require build tags and windows syscalls) GOOS=windows GOARCH=amd64 GOAMD64=v2 go build -o ./timeout-windows-pc-x86_64 ./timeout.go GOOS=windows GOARCH=arm64 go build -o ./timeout-windows-pc-aarch64 ./timeout.go ```
[]
https://avatars.githubusercontent.com/u/62779291?v=4
zig-bntx
shimamura-sakura/zig-bntx
2024-08-17T03:11:25Z
extract textures from switch bntx
main
0
0
0
0
https://api.github.com/repos/shimamura-sakura/zig-bntx/tags
MIT
[ "bntx", "switch", "zig" ]
5
false
2024-08-17T13:19:06Z
false
false
unknown
github
[]
zig-bntx use zig 0.14 outputs raw data (unswizzled blocks), you need to load it by yourself currently not handling TileMode field build zig build-exe main.zig run ./main bntxfile.bntx outfile.data
[]
https://avatars.githubusercontent.com/u/96076981?v=4
ZigRipples
JohanRimez/ZigRipples
2024-08-21T10:46:30Z
Graphic demonstration featuring ZIG & SDL2
main
0
0
0
0
https://api.github.com/repos/JohanRimez/ZigRipples/tags
MIT
[ "sdl2", "zig" ]
10
false
2024-09-18T11:34:08Z
true
true
0.13.0
github
[]
404
[]
https://avatars.githubusercontent.com/u/80385231?v=4
ChronoZig
Pranavh-2004/ChronoZig
2025-01-06T18:19:53Z
A command-line stopwatch timer built with Zig, featuring start, stop, reset, and elapsed time functionalities.
main
0
0
0
0
https://api.github.com/repos/Pranavh-2004/ChronoZig/tags
MIT
[ "cli-tool", "stopwatch", "time-tracker", "timer", "zig", "ziglang" ]
2
false
2025-01-06T18:25:37Z
true
false
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/18555580?v=4
Unity-zig
lcp5y3/Unity-zig
2024-12-11T20:03:50Z
Unity build with zig build system
main
0
0
0
0
https://api.github.com/repos/lcp5y3/Unity-zig/tags
MIT
[ "zig", "zig-package" ]
8
false
2024-12-27T11:04:31Z
true
true
unknown
github
[ { "commit": "refs", "name": "Unity", "tar_url": "https://github.com/ThrowTheSwitch/Unity/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/ThrowTheSwitch/Unity" } ]
Unity Zig Using zig build system to build <a>Unity</a> unit test library. Adding It to your project First update your <em>build.zig.zon</em> with: <code>bash zig fetch --save git+https://github.com/lcp5y3/Unity-zig.git#v2.6.0</code> After that you can link <code>Unity</code> with your project by adding the following lines to your <code>build.zig</code> ```zig const unity_dep = b.dependency("unity_zig", .{ .target = target, .optimize = optimize, }); exe.linkLibrary(unity_dep.artifact("unity")); ``` Building the lib If you only want to build Unity to get .a and header, run: <code>bash zig build</code> You will find the Statically lib <em>libunity.a</em> in zig-out folder.
[]
https://avatars.githubusercontent.com/u/576065?v=4
zig-learnopengl
thekorn/zig-learnopengl
2024-08-15T03:13:43Z
LearnOpenGL in zig
main
0
0
0
0
https://api.github.com/repos/thekorn/zig-learnopengl/tags
-
[ "opengl", "zig" ]
66
false
2024-12-15T12:00:19Z
true
true
unknown
github
[]
learnOpenGL in zig My journey following the <a>learnOpenGL</a> tutorials in zig. Run each chapter <code>bash $ zig build hello_window</code> development In order to make implementation easier, translate the c code to zig: <code>bash $ zig translate-c $(pkg-config --cflags glfw3) src/cImports.h &gt; translated_c.zig</code> In order to create a local env, with proper versions of zig, zls and glfw you can use nix to create a dev shell <code>bash $ nix develop -c zsh</code> debugging using lldb run bin using lldb <code>bash $ lldb ./zig-out/bin/shaders_6.7 (lldb) target create "./zig-out/bin/shaders_6.7" Current executable set to '/Users/thekorn/devel/github.com/thekorn/zig-learnopengl/zig-out/bin/shaders_6.7' (arm64). (lldb) breakpoint set -f shader.zig -l 38 Breakpoint 1: where = shaders_6.7`lib.shader.Shader.create + 220 at shader.zig:39:48, address = 0x0000000100001404 (lldb) r Process 45400 launched: '/Users/thekorn/devel/github.com/thekorn/zig-learnopengl/zig-out/bin/shaders_6.7' (arm64) Maximum nr of vertex attributes supported: 16 2024-08-21 12:53:37.078226+0200 shaders_6.7[45400:2512915] flock failed to lock list file (/var/folders/jj/nppjk2p91652kl8z71xwrxrr0000gn/C//com.apple.metal/16777235_594/functions.list): errno = 35 Process 45400 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 frame #0: 0x0000000100001404 shaders_6.7`lib.shader.Shader.create(vert_code=(ptr = "#version 330 core\nlayout(location = 0) in vec3 aPos;\n\nvoid main()\n{\n gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n}\n", len = 123), frag_code=(ptr = "#version 330 core\nout vec4 FragColor;\n\nuniform vec4 ourColor;\n\nvoid main()\n{\n FragColor = ourColor;\n}\n", len = 105)) at shader.zig:39:48 36 37 try check_shader_error(vertexShader); 38 -&gt; 39 const fragmentShader = c.glCreateShader(c.GL_FRAGMENT_SHADER); 40 defer c.glDeleteShader(fragmentShader); 41 42 const fragmentSrcPtr: ?[*]const u8 = frag_code.ptr; Target 0: (shaders_6.7) stopped. (lldb) frame variable ([]u8) vert_code = (ptr = "#version 330 core\nlayout(location = 0) in vec3 aPos;\n\nvoid main()\n{\n gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n}\n", len = 123) ([]u8) frag_code = (ptr = "#version 330 core\nout vec4 FragColor;\n\nuniform vec4 ourColor;\n\nvoid main()\n{\n FragColor = ourColor;\n}\n", len = 105) (unsigned int) vertexShader = 1 (unsigned char *) vert_src_ptr = 0x0000000100098f84 "#version 330 core\nlayout(location = 0) in vec3 aPos;\n\nvoid main()\n{\n gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n}\n" (unsigned int) fragmentShader = 0 (unsigned char *) fragmentSrcPtr = 0x00000001380325a8 "" (unsigned int) shaderProgram = 1 (lldb)</code>
[]
https://avatars.githubusercontent.com/u/1856197?v=4
zig-wasm-parser
FOLLGAD/zig-wasm-parser
2024-09-02T21:17:29Z
Experimenting with WASM compilation from Zig
main
0
0
0
0
https://api.github.com/repos/FOLLGAD/zig-wasm-parser/tags
-
[ "zig" ]
71
false
2025-03-08T23:21:53Z
true
true
unknown
github
[ { "commit": "refs", "name": "mecha", "tar_url": "https://github.com/Hejsil/mecha/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/Hejsil/mecha" } ]
Partial-JSON parser A "partial" JSON parser for WASM. Why? LLM stream parsing is hard. Parsers are often used to extract data from unstructured text. One of the most common data formats is JSON, and while it's streaming, it might look like this: <code>json { "name": "John Doe", "age": 30, "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "123</code> Since this is not valid JSON, it is difficult to extract the data, especially multiple times a second in-browser while waiting for the LLM response. What Partial-JSON does is it parses the JSON in a streaming fashion, and returns a valid JSON object with correct syntax, letting you display the available data real-time to the user. For the above input, Partial-JSON would return: <code>json { "name": "John Doe", "age": 30, "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } }</code> Fast The parser is implemented in Zig, and compiled to WebAssembly. It is able to parse and correct a 50kb JSON document in 1.3ms. Building <code>bash $ zig build zig build -Dtarget=wasm32-wasi</code> Demo Check <a>the demo</a> for a live demo. Also found in the <a>example</a> folder.
[]
https://avatars.githubusercontent.com/u/16691430?v=4
ziggres
Tiltimus/ziggres
2024-10-05T21:22:29Z
A lightweight PostgreSQL client for Zig
main
0
0
0
0
https://api.github.com/repos/Tiltimus/ziggres/tags
MIT
[ "postgresql", "zig" ]
2,844
false
2025-04-28T20:38:14Z
true
true
0.14.0
github
[]
Ziggres This library is a PostgreSQL driver written in Zig. Provides the basic functionality to perform queries. See examples folder for more. Installation <code>zig .{ .name = "my-project", .version = "0.0.0", .dependencies = .{ .ziggres = .{ .url = "https://github.com/Tiltimus/ziggres/archive/&lt;git-ref-here&gt;.tar.gz", .hash = &lt;hash-generated&gt;, }, }, }</code> And in your <code>build.zig</code>: ```zig const ziggres = b.dependency("ziggres", .{ .target = target, .optimize = optimize, }); exe.addModule("ziggres", ziggres.module("ziggres")); ``` Basic Example ```zig const connect_info = ConnectInfo{ .host = "", .port = , .database = "", .username = "", .password = "", // .tls = .tls, }; var client = try Client.connect( allocator, connect_info, ); defer client.close(); var data_reader = try client.prepare( , &amp;.{}, ); defer data_reader.deinit(); while (try data_reader.next()) |data_row| { // Do something with the data_row } ``` Client The client is the primary interface for interacting with the database, and it offers the following functions. Simple This function uses PostgreSQL’s Simple Query Flow and includes its own reader to iterate over each query in the statement. If you need to pass parameters to your queries, do not use this function. Instead, use prepared statements to help prevent SQL injection. ```zig var simple_reader = try client.simple(); while (try simple_reader.next()) |data_reader| { defer data_reader.deinit(); <code>while (try data_reader.next()) |dr| { switch (simple_reader.index) { 0 =&gt; { // First query in the simple reader }, 1 =&gt; { // Second query in the simple reader }, // And so on else =&gt; unreachable, } } </code> } ``` Extended This function uses PostgreSQL’s Extended Query Flow. With this approach, you can use named prepared statements and portals, specify how many rows to fetch at a time, and choose the format type if you want to send or receive binary data. ```zig var data_reader = try client.extended(); defer data_reader.deinit(); <code>while (try data_reader.next()) |data_row| { // Do whatever you want with the data row } </code> ``` Prepare This prepared function wraps the extended call and defaults some of the settings to keep it simple. Use this function if you want to use an unnamed statement. ```zig var data_reader = try client.prepare( , &amp;.{}, ); defer data_reader.deinit(); while (try data_reader.next()) |data_row| { // Do whatever you want with the data row } ``` Execute The execute function wraps the prepared call and discards the data reader if you are not interested in the result. <code>zig try client.execute(&lt;sql&gt;, &amp;.{});</code> Begin Begin is a convenient wrapper that runs the BEGIN command in SQL to start a transaction. <code>zig try client.begin();</code> Commit Commit is a convenient wrapper that runs the COMMIT command in SQL to commit a transaction. <code>zig try client.commit();</code> Savepoint Savepoint creates a savepoint that you can roll back or release to perform the respective operations. <code>zig try client.savepoint("point");</code> Rollback Rollback rolls back to the specified savepoint. If no savepoint is provided, it will roll back the entire transaction. <code>zig try client.rollback(null); // Null for whole transaction or savedpoint name</code> Release Release releases the specified savepoint. <code>zig try client.release("point");</code> CopyIn Provides a way to bulk-insert data into the database using PostgreSQL's COPY command from the client side. ```zig var copy_in = try client.copyIn( copy_in_sql, &amp;.{}, ); for (0..1000) |_| { // Look at postgres docs for formatting / depends on query try copy_in.write("Firstname\tLastname\t-1\n"); } ``` CopyOut Allows you to retrieve bulk data from the database using the COPY command and stream it to the client side. Note CopyData is memory is caller owned. Call deinit to claim memory back. ```zig var copy_out = try client.copyOut( copy_out_sql, &amp;.{}, ); while (try copy_out.read()) |row| { // CopyData row do whatever } ``` DataReader DataReader manages the reading of query results from a database operation. It tracks the operation’s state, row data, and metadata for result processing, and it provides methods for iterating through rows and accessing query metadata. Next Next retrieves the next data row from the query results. It returns a pointer to the Backend.DataRow or null when there are no more rows. The caller owns the memory and must call deinit to clear the internal buffer. Drain Drain consumes all remaining rows in the result set, deinitializing each row as it's processed, and continues until the result set is exhausted. Rows Rows returns the number of rows affected by the query. Call this after the command has been drained and there are no more rows to return. If there are no rows, it returns 0. DataRow A struct containing a buffer of the data row returned by the database. Ownership is held by the caller, and you must call deinit to free its memory. This struct provides the raw bytes for each value; it's the caller’s responsibility to transform these bytes into any needed format. Get Retrieves the next column’s bytes from the buffer. This function expects a non-null value and will produce an error on null. Optional Retrieves the next column’s bytes from the buffer, allowing for a possible null value. Pool The Pool is a basic connection pool that allows you to set minimum and maximum connections, timeouts, and retry attempts. It also wraps the client function calls for convenience. Will improve later on with keep alive feature and more. Note: acquire will block until it times out if it cannot get a client. ```zig const connect_info = ConnectInfo{ .host = "localhost", .port = 5433, .database = "ziggres", .username = "scram_user", .password = "password", }; const settings = Client.Pool.Settings{ .min = 1, .max = 3, .timeout = 30_000_000_000, .attempts = 3, }; var pool = try Client.Pool.init( allocator, connect_info, settings, ); defer pool.deinit(); const client = try pool.acquire(); defer pool.release(client); // Do whatever with client or grab more ``` Authentication Support | Method | Description | | ------ | ----------- | | md5 | Don’t use this | | scram | SHA-256 is supported but SHA-256-PLUS is not yet available | | gss (GSSAPI) | Not supported | | sspi | Not supported | | kerberos | Not supported |
[]
https://avatars.githubusercontent.com/u/85955025?v=4
wayland-gfx-project
Liam-Malone/wayland-gfx-project
2024-10-19T16:03:50Z
Learning Graphics Programming With Vulkan and From-Scratch Wayland Gfx
master
4
0
0
0
https://api.github.com/repos/Liam-Malone/wayland-gfx-project/tags
-
[ "graphics", "graphics-programming", "handmade", "vulkan", "wayland", "wayland-client", "zig" ]
5,245
false
2025-05-05T12:26:17Z
true
true
unknown
github
[ { "commit": null, "name": "vulkan", "tar_url": null, "type": "relative", "url": "deps/vulkan" } ]
Graphics Project This is a hobby project in which I am exploring everything related to creating, interactive, graphical (3D) programs to run on modern linux desktop systems. This involves: <ul> <li>Connecting to the host Wayland compositor</li> <li>Request creation of a window</li> <li>Processing &amp; responding to system events</li> <li>Processing &amp; responding to user inputs</li> <li>Rendering &amp; presenting frames to the screen</li> </ul> To accomplish all this (without relying on external libraries), I needed to: <ul> <li>Write my own tool to generate code based from a given list of wayland protocol specifications (<a>found here</a>).</li> <li>Write my own framework for communicating with the wayland compositor through the wayland wire protocol (<a>found here</a>).</li> <li>Write a tool for parsing xkb_v1 keyboard keymap formats (<a>found here</a>).</li> <li>Use Vulkan to create and write to the on-GPU buffers to render to the screen.</li> </ul> Goals <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Basic Window <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> Vulkan-Based 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> Input Event Handling <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> Hello Triangle <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> Texture/Image Rendering <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/Font Rendering <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> Rendering 3D Objects &amp; Scenes <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> Lighting Simulation Next Steps <ul> <li>[-] System event queue</li> <li>[-] Hello Triangle <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> (?) Switch from VkImage -&gt; Vulkan Surface <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> Vulkan Synchronization <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> Vulkan Swapchain Creation Pipeline <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> Image loading/rendering</li> </ul> Potential Future Goals <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> Cross Platform Support (Mac/Windows) <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> Game (/Engine) Based on This Project Milestones Hit: <ul> <li> 01:00am - 04/12/2024: First Vulkan Rendered Window </li> <li> 01:00am - 08/12/2024: Fixed Coloring For a Proper Background Clearing </li> </ul>
[]
https://avatars.githubusercontent.com/u/178647336?v=4
fluentci-demo-zig
fluentci-demos/fluentci-demo-zig
2024-08-18T16:18:49Z
FluentCI demo CI pipeline using Zig
main
0
0
1
0
https://api.github.com/repos/fluentci-demos/fluentci-demo-zig/tags
MIT
[ "cicd", "continuous-integration", "wasm", "zig" ]
6
false
2024-08-29T08:22:10Z
true
true
unknown
github
[]
FluentCI CI demo for Zig <a></a> This is an example application and CI pipeline showing how to build, test a <a>Zig</a> application using FluentCI.
[]
https://avatars.githubusercontent.com/u/48863749?v=4
zarginator
Dan149/zarginator
2024-12-07T15:21:47Z
Easy-to-use argument-parser for Zig.
main
0
0
0
0
https://api.github.com/repos/Dan149/zarginator/tags
-
[ "argparse", "argument-parser", "cmdline", "library", "zig", "zig-library", "zig-package", "ziglang" ]
8
false
2024-12-07T17:12:43Z
true
true
unknown
github
[]
Zarginator Easy-to-use command line args management library for zig. How to add Zarginator package to your zig project: First add Zarginator to your <em>build.zig.zon</em> dependencies: <code>zig fetch --save git+https://github.com/Dan149/zarginator/#HEAD</code> Then add the dependency to your <em>build.zig</em> file: ``` (...) const zarginator_package = b.dependency("zarginator", .{ .target = target, .optimize = optimize, }); const zarginator_module = zarginator_package.module("zarginator"); exe.root_module.addImport("zarginator", zarginator_module); ``` How to use Zarginator: Import: <code>const zarg = @import("zarginator");</code> See <a>main.zig</a> file and Flag struct in <a>root.zig</a> file.
[ "https://github.com/Dan149/noice" ]
https://avatars.githubusercontent.com/u/25110884?v=4
the-super-tiny-compiler
zdurham/the-super-tiny-compiler
2024-12-06T22:44:26Z
Implementation of "the super tiny compiler", but in zig
main
0
0
0
0
https://api.github.com/repos/zdurham/the-super-tiny-compiler/tags
-
[ "compilers", "zig" ]
4,915
false
2024-12-14T20:01:44Z
true
true
unknown
github
[]
The super tiny compiler (in zig) This is a re-implementation (without the AST transformation step) of the <a>super tiny compiler</a>. I wrote this in zig to learn more about the language while also exploring compilers. To run the program, you can either build it with <code>zig build</code> and then run the program in <code>zig-out/bin/tiny-compiler-zig</code>, or run <code>zig build run</code>.
[]
https://avatars.githubusercontent.com/u/22024133?v=4
zig-installer
4thel00z/zig-installer
2025-01-16T10:43:39Z
zig-installer, installs any recent zig version for you, straight from the zig homepage. Written in go.
master
0
0
0
0
https://api.github.com/repos/4thel00z/zig-installer/tags
GPL-3.0
[ "install", "version-manager", "zig", "ziglang" ]
18
false
2025-01-16T21:09:55Z
false
false
unknown
github
[]
<code>zig-installer</code> What this project is about A cli for installing the Zig compiler. It automatically downloads, verifies, and installs Zig from official releases with support for custom installation paths and multiple versions. Installation <code>bash go install github.com/4thel00z/zig-installer/...@latest</code> Usage Examples Basic Installation <code>bash sudo zig-installer</code> This will grab the latest master version and install it to <code>/usr/local</code>. Install Specific Version <code>bash sudo zig-installer --version=0.11.0</code> Custom Installation Path <code>bash sudo zig-installer \ --bin-dir=/opt/zig/bin \ --lib-dir=/opt/zig/lib</code> Using Environment Variables <code>bash export ZIG_VERSION=0.11.0 export ZIG_BIN_DIR=/opt/zig/bin export ZIG_LIB_DIR=/opt/zig/lib sudo zig-installer</code> Configuration Options | Flag | Environment Variable | Default | Description | |------|---------------------|---------|-------------| | <code>--version</code> | <code>ZIG_VERSION</code> | master | Version to install | | <code>--bin-dir</code> | <code>ZIG_BIN_DIR</code> | /usr/local/bin | Binary installation path | | <code>--lib-dir</code> | <code>ZIG_LIB_DIR</code> | /usr/local/lib | Library installation path | | <code>--tar-dest</code> | <code>ZIG_TAR_DEST</code> | /tmp/zig.tar.xz | Download location | | <code>--dest</code> | <code>ZIG_DEST</code> | /tmp/zig | Temporary extraction path | | <code>--index-url</code> | <code>ZIG_INDEX_URL</code> | ziglang.org/... | Download index URL | Features <ul> <li>🚀 Fast downloads</li> <li>📦 Proper library installation</li> <li>🔧 Highly configurable</li> <li>🖥️ Cross-platform support</li> <li>🔐 Checksum verification</li> </ul> Sample Output <code>💡 info: found existing file, checking checksum... ✅ success: existing file matches checksum, skipping download 👉 step: extracting... 👉 step: installing... 👉 step: cleaning up... ✅ success: Zig 0.11.0 installed successfully! 🎉</code> Troubleshooting Permission Errors ```bash Run with sudo for system directories sudo zig-installer ``` Custom Location Without Root ```bash Install to user-owned directory zig-installer --bin-dir=$HOME/.local/bin --lib-dir=$HOME/.local/lib ``` License This project is licensed under the GPL-3 license.
[]
https://avatars.githubusercontent.com/u/23489037?v=4
zzzlinux
lacc97/zzzlinux
2025-01-05T23:42:11Z
Convenience library for linux in Zig
master
0
0
0
0
https://api.github.com/repos/lacc97/zzzlinux/tags
Apache-2.0
[ "linux", "zig" ]
39
false
2025-01-26T19:27:30Z
true
false
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/98668553?v=4
ClipPad
EsportToys/ClipPad
2024-09-08T10:28:38Z
A barebones plaintext scratch pad.
main
0
0
0
0
https://api.github.com/repos/EsportToys/ClipPad/tags
GPL-3.0
[ "notepad", "winapi", "windows", "zig", "zig-package", "ziglang" ]
111
false
2025-03-29T15:15:41Z
true
false
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/46850171?v=4
voxel_renderer
JadonBelair/voxel_renderer
2025-01-20T07:15:24Z
A Small Voxel Engine Written in Zig
main
0
0
0
0
https://api.github.com/repos/JadonBelair/voxel_renderer/tags
MIT
[ "graphics-programming", "voxel-engine", "zig" ]
13,579
false
2025-04-02T23:57:07Z
true
true
unknown
github
[ { "commit": "29c59b12e87b22f2e6ee758bbfabc801363a2aa1", "name": "sokol", "tar_url": "https://github.com/floooh/sokol-zig/archive/29c59b12e87b22f2e6ee758bbfabc801363a2aa1.tar.gz", "type": "remote", "url": "https://github.com/floooh/sokol-zig" }, { "commit": "35b76fae19f9d0a1ed541db621d7c4...
Voxel Renderer A prototype minecraft-style voxel renderer written in zig using the sokol library for graphics. Features <ul> <li>Chunk based rendering</li> <li>Infinite terrain generation</li> <li>Smart loading/unloading of out-of-view chunks</li> </ul> Zig Version Requires Zig version 0.13.0 Controls <ul> <li>WASD - Movement</li> <li>Shift - Go Down</li> <li>Space - Go Up</li> <li>Esc - Toggle Mouse Lock</li> </ul> Screenshot Known Issues There is some kind of vram leak going on internally and I'm not to sure why that is.
[]
https://avatars.githubusercontent.com/u/54503497?v=4
simple-calculator
RetroDev256/simple-calculator
2024-10-09T03:10:40Z
null
master
0
0
0
0
https://api.github.com/repos/RetroDev256/simple-calculator/tags
MIT
[ "zig" ]
14
false
2024-11-01T00:39:43Z
true
true
unknown
github
[]
Super simple calculator. <code>Have fun learning!</code>
[]
https://avatars.githubusercontent.com/u/11700503?v=4
zpix
braheezy/zpix
2024-11-02T17:25:41Z
Image decoding
main
0
0
0
0
https://api.github.com/repos/braheezy/zpix/tags
-
[ "jpeg", "png", "zig" ]
5,458
false
2025-05-10T00:29:32Z
true
true
0.14.0
github
[ { "commit": "181dd2c6a69a8392a8457a5e80e3ab2e4871e643", "name": "SDL", "tar_url": "https://github.com/allyourcodebase/SDL/archive/181dd2c6a69a8392a8457a5e80e3ab2e4871e643.tar.gz", "type": "remote", "url": "https://github.com/allyourcodebase/SDL" } ]
zpix Image decoding library in pure Zig. It supports: <strong>JPEG</strong> <ul> <li>Baseline and Progressive formats</li> <li>Gray, YCbCr, RGBA, and YCMK color formats.</li> </ul> <strong>PNG</strong> <ul> <li>Gray 1, 2, 4, 8, and 16 bit</li> <li>Gray + alpha 8 bit and 16 bit</li> <li>Truecolor 8 bit and 16 bit</li> <li>Truecolor + alpha, 8 bit and 16 bit</li> <li>Paletted 1, 2, 4, and 8 bit</li> <li>Interlaced</li> </ul> Here's proof! The Mac image viewer on the left, and a SDL image viewer in Zig using <code>zpix</code> to view a JPEG file: Usage Add to project: <code>zig fetch --save git+https://github.com/braheezy/zpix </code> In your <code>build.zig</code>: <code>const zpix = b.dependency("zpix", .{}); root_module.addImport("zjpeg", zpix.module("jpeg")); root_module.addImport("png", zpix.module("png")); // Or the whole module that has everything exe.root_module.addImport("zpix", zpix.module("zpix")); </code> In your program, load an image file ```zig const jpeg = @import("jpeg"); // or const jpeg = @import("zpix").jpeg; const img = if (std.mem.eql(u8, file_ext, ".jpg") or std.mem.eql(u8, file_ext, ".jpeg")) try jpeg.load(allocator, arg) else if (std.mem.eql(u8, file_ext, ".png")) png: { const img = png.load(allocator, arg) catch { std.process.exit(0); }; break :png img; } else return error.UnsupportedFileExtension; defer { img.free(allocator); } // Do something with pixels ``` See <a><code>examples/zpixview.zig</code></a> for an example with SDL. Development Run using <code>zig</code>: <code>zig build run -- &lt;input image&gt; </code> Or build and run: <code>zig build ./zig-out/bin/zzpixview &lt;input image&gt; </code>
[ "https://github.com/zig-gamedev/zig-gamedev" ]
https://avatars.githubusercontent.com/u/2442833?v=4
game-of-life.zig
insolor/game-of-life.zig
2024-11-22T09:30:38Z
WIP: Game of life with infinite (sparse) field implemented in zig
main
0
0
0
0
https://api.github.com/repos/insolor/game-of-life.zig/tags
MIT
[ "game-of-life", "game-of-life-zig", "zig", "ziglang" ]
68
false
2025-05-11T20:21:35Z
true
true
unknown
github
[ { "commit": "master", "name": "raylib_zig", "tar_url": "https://github.com/Not-Nik/raylib-zig/archive/master.tar.gz", "type": "remote", "url": "https://github.com/Not-Nik/raylib-zig" } ]
Game of Life in Zig <a></a> <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> WORK IN PROGRESS </blockquote> This is an implementation of <a>Conway's Game of Life</a> in <a>Zig</a> programming language with infinite field. The field is represented as a sparse 2D array of blocks. Started as a reimplementation of a prototype of the same idea in python: <a>insolor/game-of-life</a> Plans: <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> Infinite field <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> Engine (calculate next field state) <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> GUI (raylib) <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> Mouse and keyboard control - Optimizations: - Parallelization? - Reuse memory instead of destroying and creating of fields? - Some cool stuff: - Fish-eye view?
[]
https://avatars.githubusercontent.com/u/163546630?v=4
aio
zon-dev/aio
2024-11-28T07:28:52Z
AIO in zig
main
0
0
0
0
https://api.github.com/repos/zon-dev/aio/tags
MIT
[ "aio", "asyncio", "io-uring", "iouring", "kqueue", "zig" ]
131
false
2025-05-18T07:30:03Z
true
true
0.14.0
github
[]
aio AIO in zig zig version: 0.14.0-dev.2318+3ce6de876
[]
https://avatars.githubusercontent.com/u/139704089?v=4
template-zig
RespiteFromReality/template-zig
2025-01-20T11:59:39Z
Barebones zig app template
main
0
0
0
0
https://api.github.com/repos/RespiteFromReality/template-zig/tags
-
[ "zig" ]
6
false
2025-05-17T14:47:39Z
true
true
0.14.0
github
[]
Template Zig A barebones zig application template, for zig stable releases. Usage <ul> <li>Click <code>Use this template</code> -&gt; <code>Create new repository</code></li> <li>Name and create your repository</li> <li>Clone it with git</li> <li>Change the <code>.name</code> and <code>version</code> inside <code>build.zig.zon</code> to whatever you want. (Changing the .name field also invalidates the .fingerprint value)</li> <li>Run <code>zig build</code> it will generate a new <code>.fingerprint</code> value, replace the old value with the new one.</li> <li>Make your app!</li> </ul> Older templates Because GitHub templates don't have any versioning scheme, older templates are available as branches - Tick <code>Include all branches</code> box when creating your repository - Switch the default branch to the version you want to use - Remove all other branches - Rename the branch to main/master - Follow regular usage instructions
[]
https://avatars.githubusercontent.com/u/146390816?v=4
libxkbcommon
allyourcodebase/libxkbcommon
2024-12-18T19:33:32Z
libxkbcommon ported to the zig build system
master
0
0
0
0
https://api.github.com/repos/allyourcodebase/libxkbcommon/tags
MIT
[ "zig", "zig-package" ]
56
false
2025-05-20T22:40:15Z
true
true
0.14.0
github
[ { "commit": "master", "name": "libxkbcommon", "tar_url": "https://github.com/xkbcommon/libxkbcommon/archive/master.tar.gz", "type": "remote", "url": "https://github.com/xkbcommon/libxkbcommon" }, { "commit": "master", "name": "libxml2", "tar_url": "https://github.com/allyourcodeb...
<a></a> libxkbcommon This is <a>libxkbcommon</a>, packaged for <a>Zig</a>. Installation First, update your <code>build.zig.zon</code>: ``` Initialize a <code>zig build</code> project if you haven't already zig init zig fetch --save git+https://github.com/allyourcodebase/libxkbcommon.git#1.9.2 ``` You can then import <code>libxkbcommon</code> in your <code>build.zig</code> with: ```zig const libxkbcommon_dependency = b.dependency("libxkbcommon", .{ .target = target, .optimize = optimize, <code>// Set the XKB config root. // Will default to "${INSTALL_PREFIX}/share/X11/xkb" i.e. `zig-out/share/X11/xkb`. // Most distributions will use `/usr/share/X11/xkb`. // // The value `""` will not set a default config root directory. // To configure the config root at runtime, use the "XKB_CONFIG_ROOT" environment variable. // // This example will assume that the config root of the host system is in `/usr`. // This does not work on distributions that don't follow the Filesystem Hierarchy Standard (FHS) like NixOS. .@"xkb-config-root" = "/usr/share/X11/xkb", // The X locale root. // Will default to "${INSTALL_PREFIX}/share/X11/locale" i.e. `zig-out/share/X11/locale`. // Most distributions will use `/usr/share/X11/locale`. // // To configure the config root at runtime, use the "XLOCALEDIR" environment variable. // // This example will assume that the config root of the host system is in `/usr`. // This does not work on distributions that don't follow the Filesystem Hierarchy Standard (FHS) like NixOS. .@"x-locale-root" = "/usr/share/X11/locale", </code> }); your_exe.linkLibrary(libxkbcommon_dependency.artifact("libxkbcommon")); ``` For more information, please refer to the <a>User-configuration</a> docs of libxkbcommon.
[ "https://github.com/allyourcodebase/libxkbcommon", "https://github.com/allyourcodebase/tracy" ]
https://avatars.githubusercontent.com/u/20785524?v=4
smoko
lobes/smoko
2024-10-25T05:04:30Z
Put your displays to sleep after a delay. So you can go on smoko.
base
2
0
0
0
https://api.github.com/repos/lobes/smoko/tags
Unlicense
[ "cli", "zig" ]
65,172
false
2025-01-28T03:06:24Z
true
true
unknown
github
[]
smoko Australian slang for putting the tools down and taking a break for an unknown period of time. You tell it when you want to go on smoko. At that time, smoko will put your displays to sleep. So you can down tools for a moment. And go on smoko. Go drink a glass of water. Go put your feet on some grass. Go powernap. Do whatever you want. You're on smoko. Installation Build from Source Currently the only option. Install zig Homebrew <code>sh brew install zig</code> <em>Optional: also install zig language server</em> <code>sh brew install zls</code> Clone the Repo <code>sh git clone git@github.com:lobes/smoko.git cd smoko</code> Build Smoko <code>sh zig build</code> Set a smoko <code>sh smoko now</code> - immediately puts your displays in sleep mode Sub-Commands Smoko is a bucket of sub commands: <code>smoko now</code> <code>smoko in 7</code> <code>smoko at 3</code> <code>smoko s</code> <code>smoko pass</code> <code>smoko moveto in 11</code> <code>smoko moveto at noon</code> <code>smoko wipe</code> <code>smoko help</code> Smoko in x = add a smoko that will call it x mins from now Smoko at x[am|pm] = add a smoko that will call it at next x[am|pm] (always look forwards in time) Smoko s = give me a list of the currently queued smokos and how long until they call it Smoko clear = terminate all smokos in the queue and tell me how long until they would have called it
[]
https://avatars.githubusercontent.com/u/86095656?v=4
base64
twfksh/base64
2025-01-28T07:33:18Z
base64 encoder-decoder written in Zig
main
0
0
0
0
https://api.github.com/repos/twfksh/base64/tags
-
[ "base64", "base64-decoding", "base64-encoding", "zig", "ziglang" ]
8
false
2025-01-29T10:24:06Z
true
true
unknown
github
[]
base64 encoder base64 decoder
[]
https://avatars.githubusercontent.com/u/96076981?v=4
ZigJulia
JohanRimez/ZigJulia
2024-09-12T09:48:47Z
Graphic demonstration featuring ZIG & SDL2
master
0
0
0
0
https://api.github.com/repos/JohanRimez/ZigJulia/tags
MIT
[ "sdl2", "zig" ]
6
false
2024-09-18T11:33:47Z
true
true
0.13.0
github
[]
404
[]
https://avatars.githubusercontent.com/u/54503497?v=4
jitter_rng
RetroDev256/jitter_rng
2024-11-01T00:38:01Z
null
master
0
0
0
0
https://api.github.com/repos/RetroDev256/jitter_rng/tags
MIT
[ "zig", "zig-library", "zig-package" ]
11
false
2024-11-02T00:56:20Z
true
true
unknown
github
[]
Say hello to easy-peasy true random! This library exposes a std.Random interface and jitter() function - both will use CPU timing jitter to generate random numbers. We make the following assumptions: - Your system has a CPU that supports high resolution timers - Your system runs other processes at the same time as this one - Your system has a non-deterministic CPU scheduler - Your CPU is not some esoteric architecture While all of these assumptions must be held to ensure current theory, in many cases not all of them are necessary to gain true randomness. These assumptions mean that the CPU's internal timer is not tied to the current execution of the program. External variables such as CPU heat, the CPU frequency, the CPU scheduler, and even cache misses will further add entropy to the timings of when instructions occur. We harvest this entropy simply by sampling the high resolution CPU timer. ``` ramen:[retrodev]:~/repos/Zig/jitter_rng$ zig build run -Doptimize=ReleaseFast | RNG_test stdin RNG_test using PractRand version 0.95 RNG = RNG_stdin, seed = unknown test set = core, folding = standard(unknown format) rng=RNG_stdin, seed=unknown length= 2 megabytes (2^21 bytes), time= 2.1 seconds no anomalies in 111 test result(s) rng=RNG_stdin, seed=unknown length= 4 megabytes (2^22 bytes), time= 6.2 seconds no anomalies in 127 test result(s) rng=RNG_stdin, seed=unknown length= 8 megabytes (2^23 bytes), time= 12.5 seconds no anomalies in 139 test result(s) rng=RNG_stdin, seed=unknown length= 16 megabytes (2^24 bytes), time= 24.4 seconds no anomalies in 153 test result(s) rng=RNG_stdin, seed=unknown length= 32 megabytes (2^25 bytes), time= 43.6 seconds no anomalies in 169 test result(s) rng=RNG_stdin, seed=unknown length= 64 megabytes (2^26 bytes), time= 82.5 seconds no anomalies in 182 test result(s) rng=RNG_stdin, seed=unknown length= 128 megabytes (2^27 bytes), time= 160 seconds no anomalies in 199 test result(s) rng=RNG_stdin, seed=unknown length= 256 megabytes (2^28 bytes), time= 313 seconds no anomalies in 217 test result(s) rng=RNG_stdin, seed=unknown length= 512 megabytes (2^29 bytes), time= 547 seconds no anomalies in 232 test result(s) ... And so on ... ``` Disclaimer: Please use battle-tested software, I provide no guaruntees whatsoever. In the case that your computer doesn't support this high resolution timer, the RNG may simply return 0 at all times. Beware.
[]
https://avatars.githubusercontent.com/u/7109515?v=4
python_vs_c_vs_zig
ramonmeza/python_vs_c_vs_zig
2024-11-15T21:42:03Z
A performance comparison of different algorithms implemented in Python, C, and Zig.
main
0
0
0
0
https://api.github.com/repos/ramonmeza/python_vs_c_vs_zig/tags
-
[ "algorithms", "c", "python", "quicksort", "sorting", "zig", "zig-program" ]
15
false
2025-02-08T14:10:55Z
true
false
unknown
github
[]
Algorithm Performance Showdown A performance comparison test on different algorithms implemented in Python, C, and Zig. <code>app.py</code> <a>Source File</a> This application takes in the CLI arguments, creates a <code>TestReport</code>, creates randomized test data and passes that data to the algorithm. The <code>TestReport</code> is then saved, which saves data related to the tests in JSON format into a <code>reports</code> subdirectory. CLI Usage ```sh usage: app.py [-h] [--num-iterations NUM_ITERATIONS] [--num-elements NUM_ELEMENTS] [--algorithm {c_quicksort,py_quicksort,zig_quicksort}] options: -h, --help show this help message and exit --num-iterations, -n NUM_ITERATIONS Number of iterations to run for each algorithm. --num-elements, -e NUM_ELEMENTS Number of elements in the test data used as input for each algorithm. --algorithm, -a {c_quicksort,py_quicksort,zig_quicksort} The algorithm to test. ``` <code>build.zig</code> You will need to build the C libraries and Zig libraries using <code>zig build</code>. For more advanced usage, utilize the CLI arguments. CLI Usage ```sh Usage: zig build [steps] [options] Steps: install (default) Copy build artifacts to prefix path uninstall Remove build artifacts from prefix path c_quicksort Build the c_quicksort shared library. zig_quicksort Build the zig_quicksort shared library. all Build all libraries. ``` Sorting Algorithms Quicksort | Argument | Value | | ---------------- | ----- | | <code>num_iterations</code> | 100 | | <code>num_elements</code> | 1000 | <code>PythonImpl</code> Results <a>Source File</a> <code>json { "algorithm": "py_quicksort", "num_iterations": 100, "num_elements": 1000, "total_elapsed_time": 0.09324749999359483, "average": 0.0009324749999359483, "minimum": 0.0007798000006005168, "maximum": 0.0015515000050072558 }</code> <code>CImpl</code> Results <a>Source File</a> <code>json { "algorithm": "c_quicksort", "num_iterations": 100, "num_elements": 1000, "total_elapsed_time": 0.01527510002051713, "average": 0.0001527510002051713, "minimum": 0.00012479999713832512, "maximum": 0.00027260000206297264 }</code> <code>ZigImpl</code> Results <a>Source File</a> <code>json { "algorithm": "zig_quicksort", "num_iterations": 100, "num_elements": 1000, "total_elapsed_time": 0.013725400021940004, "average": 0.00013725400021940003, "minimum": 0.00012479999713832512, "maximum": 0.00026839999918593094 }</code> Join the Conversation If you have comments or suggestions, or just want to lurk around the thread for this repo, check it out on <a>Ziggit</a>. https://ziggit.dev/t/comparing-python-zig-and-c/6883
[]
https://avatars.githubusercontent.com/u/46354333?v=4
wls-zig
vspaz/wls-zig
2025-01-19T17:46:01Z
WLS, weighted linear regression in pure Zig w/o any 3d party dependencies or frameworks.
main
0
0
0
0
https://api.github.com/repos/vspaz/wls-zig/tags
-
[ "least-square-fit", "least-square-method", "weighted-linear-regression", "weighted-regression", "wls", "zig", "ziglang" ]
33
false
2025-03-06T23:48:51Z
true
true
0.14.0
github
[]
wls-zig <code>wls-zig</code> is the implementation of weighted linear regression in pure <strong>Zig</strong> w/o any 3d party dependencies or frameworks. Installation <ol> <li> Run the following command inside your project: <code>shell zig fetch --save git+https://github.com/vspaz/wls-zig.git#main</code> it should add the following dependency to your project <em>build.zig.zon</em> file, e.g. <code>zig .dependencies = .{ .wls = .{ .url = "git+https://github.com/vspaz/wls-zig.git?ref=main#f4dfc9a98f8f538d6d25d7d3e1e431fe77d54744", .hash = "wls-0.1.0-NK6PrjMoAABYyveo97dzY5AugQxqcGgExHsaDVMxx1wm", }, }</code> </li> <li> Navigate to <em>build.zig</em> file located in the root directory and add the following 2 lines as shown below: </li> </ol> ```zig const exe = b.addExecutable(.{ .name = "your project name", .root_module = exe_mod, }); <code>// add these 2 lines! const wlszig = b.dependency("wls", .{}); exe.root_module.addImport("wls", wlszig.module("wls")); </code> <code>`` 3. Test the project build with</code>zig build` There should be no error! <ol> <li>mport <code>wls-zig</code> lib in your code as follows: <code>zig const wls = @import("wls");</code> and you're good to go! :rocket:</li> </ol> Examples ```zig pub const Wls = @import("wls").Wls; pub const asserts = @import("wls").asserts; pub fn main() !void { const x_points = [<em>]f64{ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0 }; const y_points = [</em>]f64{ 1.0, 3.0, 4.0, 5.0, 2.0, 3.0, 4.0 }; const weights = [_]f64{ 1.0, 2.0, 3.0, 1.0, 8.0, 1.0, 5.0 }; <code>const wls_model = Wls.init(&amp;x_points, &amp;y_points, &amp;weights); const fitted_model = wls_model.fit_linear_regression(); if (fitted_model) |line| { asserts.assert_almost_equal(2.14285714, line.intercept, 1.0e-6); asserts.assert_almost_equal(0.150862, line.slope, 1.0e-6); } </code> } ``` Description WLS is based on the OLS method and help solve problems of model inadequacy or violations of the basic regression assumptions. Estimating a linear regression with WLS is can be hard w/o special stats packages, such as Python statsmodels or Pandas. References <ul> <li><a>Wikipedia: Weighted least squares</a></li> <li><a>Introduction to Linear Regression Analysis, 5th edition</a></li> <li><a>Least Squares Regression Analysis in Terms of Linear Algebra</a> </li> </ul>
[]
https://avatars.githubusercontent.com/u/633183?v=4
env-logger
knutwalker/env-logger
2025-01-25T01:28:04Z
A pretty and simple logger for Zig
main
0
0
0
0
https://api.github.com/repos/knutwalker/env-logger/tags
MIT
[ "cli", "env-logger", "logging", "zig" ]
417
false
2025-04-11T22:25:18Z
true
true
0.14.0
github
[]
env-logger <a></a> A pretty logger for Zig, inspired by <a>pretty_env_logger</a>. The logger works together with the <code>std.log</code> API. It provides a <code>logFn</code> function that can be set to your <code>std.Options</code>. Quick start example ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{}); <code>std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Installation Update to latest version: <code>sh zig fetch --save git+https://github.com/knutwalker/env-logger.git</code> Add to <code>build.zig</code>: <code>zig exe.root_module.addImport("env-logger", b.dependency("env-logger", .{}).module("env-logger"));</code> <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> <code>env-logger</code> tracks Zig <code>0.14.0</code> </blockquote> Examples Starting example Setting up the logger happens in two steps: <ol> <li>Call <code>env_logger.setup(.{})</code> and set the value as your <code>std.Options</code>.</li> <li>Call <code>env_logger.init(.{})</code> once and as early as possible to initialize the logger.</li> </ol> <code>env-logger</code> will read the <code>ZIG_LOG</code> environment variable and parse it as the log level. It logs colored messages to stderr by default. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{}); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Trace level Zig does not define a <code>.trace</code> log level in <code>std.log.Level</code>. <code>env-logger</code> can still log trace messages at a <code>.trace</code> level. First enable this in the <code>setup</code> opts. To log a trace message, prefix a debug message with <code>TRACE:</code> (including the colon and space). ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{ .enable_trace_level = true, }); pub fn main() !void { env_logger.init(.{}); <code>if (!env_logger.defaultLevelEnabled(.trace)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=trace ...`\n", .{}); } std.log.debug("TRACE: debug message", .{}); std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Custom environment variable By default, the logger will look for the <code>ZIG_LOG</code> environment variable in order to configure the log level. If you want to use a different environment variable, set the name in the<code>filter</code> option. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{ .filter = .{ .env = .{ .name = "MY_LOG_ENV" } }, }); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env MY_LOG_ENV=debug ...`\n", .{}); } std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Scoped logging Scoped loggers other than the <code>.default</code> scope will be included in the log message. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{}); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } const log = std.log.scoped(.scope); log.debug("debug message", .{}); log.info("info message", .{}); log.warn("warn message", .{}); log.err("error message", .{}); </code> } ``` Dynamic log level The log level can also be set programmatically instead of using the environment variable. It can also be changed at runtime. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{ .filter = .{ .level = .info }, }); <code>std.log.debug("you don't see me", .{}); std.log.info("but I am here", .{}); // env_logger.set_log_level(.debug); std.log.debug("now you see me", .{}); </code> } ``` Custom <code>std.Options</code> In case you want to set other <code>std.Options</code>, you can use the <code>env_logger.setupWith</code> function. Alternatively, you can use the <code>env_logger.setupFn</code> function and set the <code>logFn</code> field. This allows you to statically disable certain log levels since the <code>setup</code> function sets the <code>log_level</code> field to <code>.debug</code>. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setupWith( .{}, // The second argument is the std.Options that will be set. .{ .fmt_max_depth = 64, }, ); pub fn main() !void { env_logger.init(.{}); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Only log messages You can disable the level and logger parts of the log message and only render the message itself. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{ .render_level = false, .render_logger = false, }); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } const log = std.log.scoped(.scope); log.debug("debug message", .{}); log.info("info message", .{}); log.warn("warn message", .{}); log.err("error message", .{}); </code> } ``` Add timestamps You can also add timestamps to the log messages. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{ .render_timestamp = true, }); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Log to different outputs By default, the logger logs to stderr, but it can also be configured to log to stdout, append to a file, or write to a writer. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); <code>var args = try std.process.argsWithAllocator(allocator); defer args.deinit(); _ = args.next() orelse return; // skip the executable name const output_filename = args.next() orelse { std.debug.print("Usage: log_to_file $FILENAME\n", .{}); std.process.exit(1); }; var output: env_logger.InitOptions.Output = .stderr; var buf: ?std.ArrayList(u8) = null; defer if (buf) |b| b.deinit(); if (std.mem.eql(u8, output_filename, "-")) { output = .stdout; } else if (std.mem.eql(u8, output_filename, "+")) { buf = .init(allocator); output = .{ .writer = buf.?.writer().any() }; } else { const output_file = try std.fs.cwd().createFile( output_filename, // Set `truncate` to false to append to the file. .{ .truncate = false }, ); output = .{ .file = output_file }; } env_logger.init(.{ .output = output }); if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); if (buf) |b| { std.debug.print("Contents of buffer:\n{s}\n", .{b.items}); } </code> } ``` Configure colors By default, the logger will detect if the terminal supports colors and use them. You can disable this by setting the <code>enable_color</code> option to <code>false</code>. Alternatively, you can force the logger to use colors by setting the <code>force_color</code> option to <code>true</code>. ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { env_logger.init(.{ // disable all use of colors, .enable_color = false, // force the use of colors, also for files and writers .force_color = true, }); <code>if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } // try piping stderr to a file, it's still colored std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Configure allocators Parsing and constructing the log filter requires allocations. By default, the logger uses the <code>std.heap.page_allocator</code> for this. If you want to use a different allocator, you can set the <code>allocator</code> option to a <code>std.mem.Allocator</code>. Since the filter is supposed to be kept for the remainder of the program's lifetime, you can set two different allocators, one for all the parsing (e.g. a gpa, like the <code>DebugAllocator</code>), and another one for the final filter allocation (e.g. an arena allocator). ```zig const std = @import("std"); const env_logger = @import("env-logger"); pub const std_options = env_logger.setup(.{}); pub fn main() !void { var gpa: std.heap.DebugAllocator(.{ .verbose_log = true }) = .init; defer if (gpa.deinit() == .leak) @panic("memory leak"); <code>var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); env_logger.init(.{ .allocator = .{ .split = .{ .parse_gpa = gpa.allocator(), .filter_arena = arena.allocator(), } } }); if (!env_logger.defaultLevelEnabled(.debug)) { std.debug.print("To see all log messages, run with `env ZIG_LOG=debug ...`\n", .{}); } std.log.debug("debug message", .{}); std.log.info("info message", .{}); std.log.warn("warn message", .{}); std.log.err("error message", .{}); </code> } ``` Contributing Contributions are welcome! Please open an issue or a pull request if you have any suggestions or improvements. License env-logger is licensed under the <a>MIT License</a>
[]
https://avatars.githubusercontent.com/u/14921224?v=4
aoc24-zig
drewsilcock/aoc24-zig
2024-12-03T22:19:26Z
Advent of Code 2024 in Zig
main
0
0
0
0
https://api.github.com/repos/drewsilcock/aoc24-zig/tags
-
[ "advent-of-code", "zig" ]
59
false
2024-12-19T17:35:24Z
true
true
unknown
github
[]
Advent of Code in Zig Implementing <a>Advent of Code 2024</a> in Zig. <strong>Disclaimer:</strong> This is the first time I've written Zig so it's probably not using best practices and whatnot. Any helpful feedback welcome 😎 Getting started First, <a>Install zig</a>, e.g. <code>brew install zig</code>. To run a particular day challenge: ```bash In debug mode zig run src/main.zig -- In release mode zig build -Doptimize=ReleaseFast ./zig-out/bin/aoc24 ``` Benchmarks Benchmarks from running on my M3 Pro: | Challenge | Status | Time (mean ± σ) | Range (min … max) | Details | | --------- | ------ | --------------- | ----------------- | ------- | | #1 | Done | 8.1 ms ± 0.5 ms | 3.5 ms … 22.3 ms | User: 2.0 ms, System: 5.7 ms, Runs: 353 | | #2 | Todo | | | | | #3 | Todo | | | | | #4 | Todo | | | | | #5 | Todo | | | | | #6 | Todo | | | | | #7 | Todo | | | | | #8 | Todo | | | | | #9 | Todo | | | | | #10 | Todo | | | | | #11 | Todo | | | | | #12 | Todo | | | | | #13 | Todo | | | | | #14 | Todo | | | | | #15 | Todo | | | | | #16 | Todo | | | | | #17 | Todo | | | | | #18 | Todo | | | | | #19 | Todo | | | | | #20 | Todo | | | | | #21 | Todo | | | | | #22 | Todo | | | | | #23 | Todo | | | | | #24 | Todo | | | | | #25 | Todo | | | | (Note: benchmarks run using <code>hyperfine -N --warmup 5 './zig-out/bin/aoc24 &lt;day n#&gt;'</code>.)
[]
https://avatars.githubusercontent.com/u/96076981?v=4
ZigMarching
JohanRimez/ZigMarching
2024-09-11T20:05:36Z
Graphic demonstration featuring ZIG & SDL2
main
0
0
0
0
https://api.github.com/repos/JohanRimez/ZigMarching/tags
MIT
[ "sdl2", "sdl2-image", "zig" ]
12
false
2024-09-18T11:33:55Z
true
true
0.13.0
github
[]
404
[]
https://avatars.githubusercontent.com/u/96076981?v=4
ZigFireworks
JohanRimez/ZigFireworks
2024-08-21T10:41:58Z
Graphic demonstration featuring ZIG & SDL2
main
0
0
0
0
https://api.github.com/repos/JohanRimez/ZigFireworks/tags
MIT
[ "sdl2", "zig" ]
8
false
2024-09-18T11:33:34Z
true
true
0.13.0
github
[]
404
[]
https://avatars.githubusercontent.com/u/9116281?v=4
zigstersfpl
g41797/zigstersfpl
2024-09-09T06:22:22Z
What was your first programming language?
main
0
0
0
0
https://api.github.com/repos/g41797/zigstersfpl/tags
MIT
[ "post", "zig", "zigsters" ]
23
false
2024-11-26T13:08:35Z
true
true
unknown
github
[]
What was your first programming language? <a></a> The result of the survey <a>What was your first programming language?</a>: - Participated: 139 Zigsters. - Programming languages: 29. - Winner: BASIC(47/139). - Oldest: FORTRAN(1965). - Youngest: Rust(2024). By # of Zigsters | Language | Zigsters | |:---------|---------:| |BASIC|47| |C|14| |Python|10| |C++|9| |Java|9| |Pascal|6| |ASM|5| |JS|5| |C#|4| |PHP|4| |FORTRAN|3| |Scratch|3| |Delphi|2| |Logo|2| |Perl|2| |ActionScript|1| |Arduino|1| |Bash|1| |COBOL|1| |DOS Batch|1| |Euphoria|1| |Fusion|1| |GML|1| |MATLAB|1| |R|1| |Ruby|1| |Rust|1| |TorqueScript|1| |UnrealScript|1| Per year | Year | Language | Zigsters | |:-----:|:---------|---------:| |1965|FORTRAN|1| |1971|ASM|1| |1972|FORTRAN|1| |1973|BASIC|1| |1975|BASIC|1| |1976|BASIC|1| |1977|BASIC|1| |1978|ASM|2| |1979|BASIC|2| |1981|ASM|1| | |BASIC|2| | |C|1| |1982|BASIC|5| |1983|BASIC|1| |1984|BASIC|3| |1986|BASIC|5| |1987|BASIC|1| |1988|BASIC|3| | |C|2| |1989|BASIC|1| |1990|Logo|1| |1991|Logo|1| |1992|BASIC|2| |1993|BASIC|3| | |C|1| | |COBOL|1| | |Pascal|1| |1994|BASIC|3| | |C|1| |1995|BASIC|3| |1996|BASIC|1| | |C++|1| | |DOS Batch|1| | |Perl|1| |1997|BASIC|1| |1998|Perl|1| | |UnrealScript|1| |2000|Delphi|1| | |Euphoria|1| |2002|BASIC|1| | |C++|1| | |GML|1| | |Java|1| | |PHP|1| |2003|BASIC|2| | |JS|1| | |Pascal|1| |2004|C|1| | |Python|1| |2005|ActionScript|1| | |Fusion|1| | |PHP|1| | |Python|1| |2006|Java|1| |2007|JS|1| | |PHP|1| | |TorqueScript|1| |2008|C|1| | |Ruby|1| |2009|C++|1| | |Java|1| | |Python|1| | |Scratch|1| |2010|Java|2| |2011|Bash|1| | |FORTRAN|1| | |Pascal|1| |2012|C++|1| | |Scratch|1| |2013|C|1| | |C#|1| | |Scratch|1| |2014|C++|1| | |Java|2| | |Python|1| |2015|C++|1| | |Java|1| | |PHP|1| | |Python|2| | |R|1| |2016|BASIC|1| | |C|1| | |C#|1| | |Pascal|1| |2017|Arduino|1| |2018|C#|2| | |C++|1| | |JS|1| |2019|Python|1| |2020|C|1| | |C++|1| | |MATLAB|1| | |Python|3| |2021|Java|1| |2022|C|2| | |Delphi|1| |2023|JS|1| |2024|Rust|1|
[]
https://avatars.githubusercontent.com/u/23698404?v=4
zig-calc
desktopgame/zig-calc
2024-08-21T14:25:22Z
simple calcuulator written in zig
develop
0
0
0
0
https://api.github.com/repos/desktopgame/zig-calc/tags
-
[ "zig", "ziglang" ]
26
false
2024-08-24T05:03:05Z
true
true
unknown
github
[]
zig-calc zig-calc is simple calculator, written in zig. only basic arithmetic operations, constant, and function supported. example ```` zig build run -- 3 + 4 <blockquote> 7 zig build run -- 12 + (3 * 4) 24 zig build run -- -3 * 2 -6 zig build run -- 5 + (-3) 2 zig build run -- max(1,2) 2 zig build run -- min(1,2) 1 zig build run -- avg(4,4,4,4) 4 ```` </blockquote> When used from Powershell, enclose the parentheses in double quotation marks. ```` zig build run -- "5 + (-3)" <blockquote> 2 ```` </blockquote>
[]
https://avatars.githubusercontent.com/u/13668008?v=4
tameboy
sylvrs/tameboy
2024-08-15T03:09:07Z
A Zig-based GameBoy emulator written for the browser
master
0
0
0
0
https://api.github.com/repos/sylvrs/tameboy/tags
-
[ "emulator", "gameboy", "wasm", "zig" ]
173
false
2024-08-15T03:14:38Z
true
true
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/184568612?v=4
zollections
zigzedd/zollections
2024-10-11T09:17:44Z
[MIRROR] Zig collections library.
main
0
0
0
0
https://api.github.com/repos/zigzedd/zollections/tags
MIT
[ "collections", "zig", "zig-library", "zig-package" ]
11
false
2025-01-08T22:24:08Z
true
true
0.13.0
github
[]
<a> </a> Zollections <a>Documentation</a> | <a>API</a> Zig collections library Zollections is part of <a><em>zedd</em></a>, a collection of useful libraries for zig. Zollections <em>Zollections</em> is a collections library for Zig. It's made to ease memory management of dynamically allocated slices and elements. Versions Zollections 0.1.1 is made and tested with zig 0.13.0. How to use Install In your project directory: <code>shell $ zig fetch --save https://code.zeptotech.net/zedd/zollections/archive/v0.1.1.tar.gz</code> In <code>build.zig</code>: <code>zig // Add zollections dependency. const zollections = b.dependency("zollections", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zollections", zollections.module("zollections"));</code> Examples These examples are taken from tests in <a><code>tests/collection.zig</code></a>. Simple collection ```zig // Allocate your slice. const slice = try allocator.alloc(*u8, 3); // Create your slice elements. slice[0] = try allocator.create(u8); slice[1] = try allocator.create(u8); slice[2] = try allocator.create(u8); // Create a collection with your slice of elements. const collection = try zollections.Collection(u8).init(allocator, slice); // Free your collection: your slice and all your elements will be freed. defer collection.deinit(); ``` Recursive free ```zig // Create a pointer to a slice. const slicePointer = try allocator.create([]*u8); // Allocate your slice in the pointed slice. slicePointer.<em> = try allocator.alloc(</em>u8, 3); // Create slice elements. slicePointer.<em>[0] = try allocator.create(u8); slicePointer.</em>[1] = try allocator.create(u8); slicePointer.*[2] = try allocator.create(u8); // Allocate your slice or pointers to slices. const slice = try allocator.alloc(<em>[]</em>u8, 1); slice[0] = slicePointer; // Create a collection with your slice of elements. const collection = try zollections.Collection([]*u8).init(allocator, slice); // Free your collection: your slice and all your slices and their elements will be freed. defer collection.deinit(); ``` Custom structure deinitialization ```zig /// An example structure. const ExampleStruct = struct { const Self = @This(); <code>allocator: std.mem.Allocator, buffer: []u8, /// Initialize a new example struct. pub fn init(bufSiz: usize) !Self { const allocator = std.testing.allocator; return .{ .allocator = allocator, .buffer = try allocator.alloc(u8, bufSiz), }; } /// Deinitialize the example struct. pub fn deinit(self: *Self) void { self.allocator.free(self.buffer); } </code> }; // Allocate your slice. const slice = try allocator.alloc(<em>ExampleStruct, 3); // Create your slice elements with custom structs and their inner init / deinit. slice[0] = try allocator.create(ExampleStruct); slice[0].</em> = try ExampleStruct.init(4); slice[1] = try allocator.create(ExampleStruct); slice[1].<em> = try ExampleStruct.init(8); slice[2] = try allocator.create(ExampleStruct); slice[2].</em> = try ExampleStruct.init(16); // Create a collection with your slice of elements. const collection = try zollections.Collection(ExampleStruct).init(allocator, slice); // Free your collection: your slice and all your elements will be deinitialized and freed. defer collection.deinit(); ```
[ "https://github.com/zigzedd/zrm" ]
https://avatars.githubusercontent.com/u/2442833?v=4
aoc2024.zig
insolor/aoc2024.zig
2024-12-01T22:10:52Z
Advent of Code 2024 in zig
main
0
0
0
0
https://api.github.com/repos/insolor/aoc2024.zig/tags
-
[ "advent-of-code", "advent-of-code-2024", "advent-of-code-2024-zig", "zig", "ziglang" ]
74
false
2024-12-14T14:55:48Z
true
true
unknown
github
[]
Advent of Code 2024 <a>https://adventofcode.com/2024</a>
[]
https://avatars.githubusercontent.com/u/47543854?v=4
pgz
vikassandhu999/pgz
2025-01-18T03:25:37Z
Native PostgreSQL Driver for Zig
main
0
0
0
0
https://api.github.com/repos/vikassandhu999/pgz/tags
-
[ "database", "driver", "postgres", "zig" ]
42
false
2025-01-31T06:13:28Z
true
true
unknown
github
[]
Native PostgreSQL Driver for Zig A from-scratch PostgreSQL driver written entirely in Zig. This project aims to implement the PostgreSQL wire protocol, handling authentication, queries, and data parsing without relying on libpq or other C dependencies.
[ "https://github.com/star-tek-mb/migrator" ]
https://avatars.githubusercontent.com/u/35064754?v=4
W
wooster0/W
2024-12-16T11:28:46Z
Fantasy computer
main
0
0
0
0
https://api.github.com/repos/wooster0/W/tags
-
[ "assembly-language", "fantasy-computer", "fantasy-console", "wayland", "wayland-client", "zig" ]
25
false
2024-12-16T11:40:33Z
true
false
unknown
github
[]
W A virtual computer (fantasy computer) with its own assembly language and system interface. The whole thing is a single program that can both assemble source files and run the resulting machine code. In an optimize mode other than Debug or ReleaseSafe, the program makes zero usage of the Zig standard library, uses zero error codes (a feature of the Zig language), and does not panic (i.e. no <code>@panic</code>/<code>std.debug.panic</code>, etc.). Instead it uses pure libc (see <code>c.zig</code> for everything used) with zero abstractions and in case of an error the program simply exits after printing the error message instead of propagating anything. This makes the binary size incredibly small: <code>$ zig build -Doptimize=ReleaseSmall $ wc -c zig-out/bin/W 19944 zig-out/bin/W</code> This program does link libc and uses it for all the interactions with the operating system which does offload a lot of things as libc is not statically linked. 0.01 MBs is still impressive considering that this program on its own can 1. assemble programs, 2. execute them, and 3. has a graphical interface opening a window using Wayland in which user programs are executed. This only runs on Unix-like operating systems (or perhaps only Linux) by talking to the Wayland server directly, without any graphics library in between. It depends on libc and a wayland-client system library. I'm archiving this project here as it is with TODOs and all left in the source code that I wouldn't understand now. To assemble a source file pass the source file with the extension .W: <code>$ W COUNTER.W</code> To run a source file pass the machine code file without an extension: <code>$ W COUNTER</code> To view the manual, run: <code>$ W</code> I'm repeating it here: ``` MANUAL ====== ADDI (INTEGER): ADD INTEGER CLRS (INTEGER): CLEAR SCREEN CPTO (REGISTER): COPY REGISTER VALUE TO REGISTER DECR (REGISTER): DECREMENT DDEC (NONE): DISABLE DECIMAL MODE DRAW (INTEGER): DRAW PIXELS EDEC (NONE): ENABLE DECIMAL MODE GOTO (INTEGER): JUMP TO ADDRESS HALT (NONE): HALT EXECUTION IFEQ (INTEGER): IF EQUAL, EXECUTE NEXT INSTRUCTION; OTHERWISE SKIP IFNE (INTEGER): IF NOT EQUAL, EXECUTE NEXT INSTRUCTION; OTHERWISE SKIP IFPP (NONE): IF POINTER PRESSED, EXECUTE NEXT INSTRUCTION; OTHERWISE SKIP INCR (REGISTER): INCREMENT LDPP (NONE): LOAD POINTER POSITION INTO X AND Y LDKK (NONE): LOAD KEYBOARD KEY INTO W LOAD (INTEGER): LOAD PRNT (NONE): PRINT W AS CHARACTER TO (X, Y) RSTR (REGISTER): POP FROM STACK SAVE (REGISTER): PUSH TO STACK SEXH (INTEGER): SET EXCEPTION HANDLER SCLR (INTEGER): SET COLOR SETW (INTEGER): SET W SETX (INTEGER): SET X SETY (INTEGER): SET Y TRGT (REGISTER): SET OPERATION TARGET WAIT (INTEGER): DO NOTHING FOR AN AMOUNT OF MILLISECONDS NONE: NO ARGUMENT INTEGER: 32-BIT INTEGER ARGUMENT REGISTER: W, X, Y, OR XY ``` To compile from source and run the moon example: <code>.../W$ zig build .../W$ zig-out/bin/W MOON.W .../W$ zig-out/bin/W MOON</code> What's special about the encoding of the instructions is that all mnemonics are 4 bytes and the encoding is the same: the same 4 bytes used for the mnemonic. This is particularly useful for writing self-modifying code. You can look at a hexdump of an assembled program and see the instructions because they're ASCII: <code>$ zig-out/bin/W CHICKEN.W $ hexdump -C CHICKEN 00000000 43 4c 52 53 b7 01 00 00 53 43 4c 52 a7 01 00 00 |CLRS....SCLR....| 00000010 44 52 41 57 67 01 00 00 49 4e 43 52 58 53 43 4c |DRAWg...INCRXSCL| 00000020 52 ab 01 00 00 44 52 41 57 67 01 00 00 49 4e 43 |R....DRAWg...INC| 00000030 52 58 53 43 4c 52 ab 01 00 00 44 52 41 57 67 01 |RXSCLR....DRAWg.| 00000040 00 00 49 4e 43 52 58 53 43 4c 52 a7 01 00 00 44 |..INCRXSCLR....D| 00000050 52 41 57 67 01 00 00 53 45 54 58 00 00 00 00 49 |RAWg...SETX....I| 00000060 4e 43 52 59 53 43 4c 52 b3 01 00 00 44 52 41 57 |NCRYSCLR....DRAW| 00000070 67 01 00 00 49 4e 43 52 58 53 43 4c 52 b3 01 00 |g...INCRXSCLR...| 00000080 00 44 52 41 57 67 01 00 00 49 4e 43 52 58 53 43 |.DRAWg...INCRXSC| 00000090 4c 52 b3 01 00 00 44 52 41 57 67 01 00 00 49 4e |LR....DRAWg...IN| 000000a0 43 52 58 53 43 4c 52 b3 01 00 00 44 52 41 57 67 |CRXSCLR....DRAWg| 000000b0 01 00 00 53 45 54 58 00 00 00 00 49 4e 43 52 59 |...SETX....INCRY| 000000c0 53 43 4c 52 ab 01 00 00 44 52 41 57 67 01 00 00 |SCLR....DRAWg...|</code>
[]
https://avatars.githubusercontent.com/u/476352?v=4
ourio
rockorager/ourio
2025-04-22T19:56:48Z
An asynchronous IO runtime
main
0
61
0
61
https://api.github.com/repos/rockorager/ourio/tags
MIT
[ "zig", "zig-package" ]
168
false
2025-05-21T04:08:08Z
true
true
0.14.0
github
[ { "commit": "8250aa9184fbad99983b32411bbe1a5d2fd6f4b7", "name": "tls", "tar_url": "https://github.com/ianic/tls.zig/archive/8250aa9184fbad99983b32411bbe1a5d2fd6f4b7.tar.gz", "type": "remote", "url": "https://github.com/ianic/tls.zig" } ]
Ourio Ourio (prounounced "oreo", think "Ouroboros") is an asynchronous IO runtime built heavily around the semantics of io_uring. The design is inspired by <a>libxev</a>, which is in turn inspired by <a>TigerBeetle</a>. Ourio has only a slightly different approach: it is designed to encourage message passing approach to asynchronous IO. Users of the library give each task a Context, which contains a pointer, a callback, <em>and a message</em>. The message is implemented as a u16, and generally you should use an enum for it. The idea is that you can minimize the number of callback functions required by tagging tasks with a small amount of semantic meaning in the <code>msg</code> field. Ourio has io_uring and kqueue backends. Ourio supports the <code>msg_ring</code> capability of io_uring to pass a completion from one ring to another. This allows a multithreaded application to implement message passing using io_uring (or kqueue, if that's your flavor). Multithreaded applications should plan to use one <code>Ring</code> per thread. Submission onto the runtime is not thread safe, any message passing must occur using <code>msg_ring</code> rather than directly submitting a task to another Ourio also includes a fully mockable IO runtime to make it easy to unit test your async code. Tasks Deadlines and Cancelation Each IO operation creates a <code>Task</code>. When scheduling a task on the runtime, the caller receives a pointer to the <code>Task</code> at which point they could cancel it, or set a deadline. ```zig // Timers are always relative time const task = try rt.timer(.{.sec = 3}, .{.cb = onCompletion, .msg = 0}); // If the deadline expired, the task will be sent to the onCompletion callback // with a result of error.Canceled. Deadlines are always absolute time try task.setDeadline(rt, .{.sec = std.time.timestamp() + 3}); // Alternatively, we can hold on to the pointer for the task while it is with // the runtime and cancel it. The Context we give to the cancel function let's // us know the result of the cancelation, but we will also receive a message // from the original task with error.Canceled. We can ignore the cancel result // by using the default context value try task.cancel(rt, .{}); ``` Passing tasks between threads Say we <code>accept</code> a connection in one thread, and want to send the file descriptor to another for handling. ```zig // Spawn a thread with a queue of 16 entries. When this function returns, the // the thread is idle and waiting to receive tasks via msgRing const thread = main_rt.spawnThread(16); const target_task = try main_rt.getTask(); target_task.* { .userdata = &amp;foo, .msg = @intFromEnum(Msg.some_message), .cb = Worker.onCompletion, .req = .{ .userfd = fd }, }; // Send target_task from the main_rt thread to the thread Ring. The // thread_rt Ring will then // process the task as a completion, ie // Worker.onCompletion will be called with this task. That thread can then // schedule a recv, a write, etc on the file descriptor it just received. Or do // arbitrary work _ = try main_rt.msgRing(&amp;thread.ring, target_task, .{}); ``` Multiple Rings on the same thread You can have multiple Rings in a single thread. One could be a priority Ring, or handle specific types of tasks, etc. Poll any <code>Ring</code> from any other <code>Ring</code>. ```zig const fd = rt1.backend.pollableFd(); _ = try rt2.poll(fd, .{ .cb = onCompletion, .msg = @intFromEnum(Msg.rt1_has_completions)} ); ``` Example An example implementation of an asynchronous writer to two file descriptors: ```zig const std = @import("std"); const io = @import("ourio"); const posix = std.posix; pub const MultiWriter = struct { fd1: posix.fd_t, fd1_written: usize = 0, <code>fd2: posix.fd_t, fd2_written: usize = 0, buf: std.ArrayListUnmanaged(u8), pub const Msg = enum { fd1, fd2 }; pub fn init(fd1: posix.fd_t, fd2: posix.fd_t) MultiWriter { return .{ .fd1 = fd1, .fd2 = fd2 }; } pub fn write(self: *MultiWriter, gpa: Allocator, bytes: []const u8) !void { try self.buf.appendSlice(gpa, bytes); } pub fn flush(self: *MultiWriter, rt: *io.Ring) !void { if (self.fd1_written &lt; self.buf.items.len) { _ = try rt.write(self.fd1, self.buf.items[self.fd1_written..], .{ .ptr = self, .msg = @intFromEnum(Msg.fd1), .cb = MultiWriter.onCompletion, }); } if (self.fd2_written &lt; self.buf.items.len) { _ = try rt.write(self.fd2, self.buf.items[self.fd2_written..], .{ .ptr = self, .msg = @intFromEnum(Msg.fd2), .cb = MultiWriter.onCompletion, }); } } pub fn onCompletion(rt: *io.Ring, task: io.Task) anyerror!void { const self = task.userdataCast(MultiWriter); const result = task.result.?; const n = try result.write; switch (task.msgToEnum(MultiWriter.Msg)) { .fd1 =&gt; self.fd1_written += n, .fd2 =&gt; self.fd2_written += n, } const len = self.buf.items.len; if (self.fd1_written &lt; len or self.fd2_written &lt; len) return self.flush(rt); self.fd1_written = 0; self.fd2_written = 0; self.buf.clearRetainingCapacity(); } </code> }; pub fn main() !void { var gpa: std.heap.DebugAllocator(.{}) = .init; var rt: io.Ring = try .init(gpa.allocator(), 16); defer rt.deinit(); <code>// Pretend I created some files const fd1: posix.fd_t = 5; const fd2: posix.fd_t = 6; var mw: MultiWriter = .init(fd1, fd2); try mw.write(gpa.allocator(), "Hello, world!"); try mw.flush(&amp;rt); try rt.run(.until_done); </code> } ```
[]
https://avatars.githubusercontent.com/u/10281587?v=4
libqt6zig
rcalixte/libqt6zig
2025-03-07T13:05:40Z
Qt 6 for Zig
master
0
42
2
42
https://api.github.com/repos/rcalixte/libqt6zig/tags
MIT
[ "bindings", "gui-library", "qt", "qt6", "zig", "zig-package", "ziglang" ]
7,732
false
2025-05-22T00:46:33Z
true
true
unknown
github
[]
![MIT License](https://img.shields.io/badge/License-MIT-green) [![Go Report Card](https://goreportcard.com/badge/github.com/rcalixte/libqt6zig)](https://goreportcard.com/report/github.com/rcalixte/libqt6zig) [![Static Badge](https://img.shields.io/badge/v0.14%20(stable)-f7a41d?logo=zig&amp;logoColor=f7a41d&amp;label=Zig)](https://ziglang.org/download/) MIT-licensed Qt 6 bindings for Zig This library is a straightforward binding of the Qt 6.4+ API. You must have a working Qt 6 C++ development toolchain to use this binding. The <a>Building</a> section below has instructions for installing the required dependencies. This library is designed to be used as a dependency in a larger application and not as a standalone library. The versioning scheme used by this library is based on the Qt version used to generate the bindings with an additional nod to the library revision number. Any breaking changes to the library will be reflected in the changelog. These bindings are based on the <a>MIQT bindings for Go</a> that were released in 2024. The bindings are complete for QtCore, QtGui, QtWidgets, QtCharts, QtMultimedia, QtMultimediaWidgets, QtNetwork, QtPrintSupport, QtSpatialAudio, QtSvg, QtWebChannel, QtWebEngine, QScintilla, and others. There is support for slots/signals, subclassing, custom widgets, async via Qt, etc., but the bindings may be immature or unstable in some ways. It is fairly easy to encounter segmentation faults with improper handling. Q3 of the <a>FAQ</a> is a decent entry point for newcomers. Please try out the library and start a <a>discussion</a> if you have any questions or issues relevant to this library. TABLE OF CONTENTS <ul> <li><a>Supported Platforms</a></li> <li><a>License</a></li> <li><a>Examples</a></li> <li><a>Building</a></li> <li><a>Usage</a></li> <li><a>FAQ</a></li> <li><a>Special Thanks</a></li> </ul> Supported platforms | OS | Arch | Linkage (Bindings) | Status | | ------- | ------ | ------------------ | ------- | | FreeBSD | x86_64 | Static | ✅ Works | | Linux | arm64 | Static | ✅ Works | | Linux | x86_64 | Static | ✅ Works | License The <code>libqt6zig</code> bindings are licensed under the MIT license. You must also meet your Qt license obligations. Examples The <a><code>helloworld</code></a> example follows: ```zig const std = @import("std"); const qt6 = @import("libqt6zig"); const qapplication = qt6.qapplication; const qpushbutton = qt6.qpushbutton; const qwidget = qt6.qwidget; var counter: isize = 0; pub fn main() void { // Initialize Qt application const argc = std.os.argv.len; const argv = std.os.argv.ptr; _ = qapplication.New(argc, argv); <code>const text = "Hello world!"; const widget = qwidget.New2(); if (widget == null) @panic("Failed to create widget"); defer qwidget.QDelete(widget); // We don't need to free the button, it's a child of the widget const button = qpushbutton.New5(text, widget); qpushbutton.SetFixedWidth(button, 320); qpushbutton.OnClicked(button, button_callback); qwidget.Show(widget); _ = qapplication.Exec(); std.debug.print("OK!\n", .{}); </code> } fn button_callback(self: ?*anyopaque) callconv(.c) void { counter += 1; var buffer: [64]u8 = undefined; const text = "You have clicked the button {} time(s)"; const formatted = std.fmt.bufPrintZ(&amp;buffer, text, .{counter}) catch @panic("Failed to bufPrintZ"); qpushbutton.SetText(self, formatted); } ``` Full examples are available in the <a><code>libqt6zig-examples</code></a> repository. Building FreeBSD (native) <ul> <li><em>Tested with FreeBSD 14 / Qt 6.8</em></li> </ul> For dynamic linking with the Qt 6 system libraries: <code>bash sudo pkg install qt6-base qt6-charts qt6-multimedia qt6-pdf qt6-svg qt6-webchannel qt6-webengine qscintilla2-qt6 zig</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> The <code>zig</code> package may need to be downloaded or compiled and installed separately if the latest stable version is not available in the default repositories. </blockquote> Linux (native) <ul> <li> <em>Tested with Debian 12 + 13 / Qt 6.4 + 6.8</em> </li> <li> <em>Tested with Linux Mint 22 / Qt 6.4</em> </li> <li> <em>Tested with Ubuntu 24.04 / Qt 6.4</em> </li> <li> <em>Tested with Fedora 41 / Qt 6.8</em> </li> <li> <em>Tested with EndeavourOS Mercury / Qt 6.8</em> </li> </ul> For dynamic linking with the Qt 6 system libraries: <ul> <li><strong>Debian-based distributions</strong>:</li> </ul> <code>bash sudo apt install qt6-base-dev libqscintilla2-qt6-dev qt6-base-private-dev qt6-charts-dev qt6-multimedia-dev qt6-pdf-dev qt6-svg-dev qt6-webchannel-dev qt6-webengine-dev</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> The <code>zig</code> package must be downloaded and installed separately. </blockquote> <ul> <li><strong>Fedora-based distributions</strong>:</li> </ul> <code>bash sudo dnf install qt6-qtbase-devel qscintilla-qt6-devel qt6-qtcharts-devel qt6-qtmultimedia-devel qt6-qtpdf-devel qt6-qtsvg-devel qt6-qtwebchannel-devel qt6-qtwebengine-devel zig</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> The <code>zig</code> package will need to be downloaded and installed separately if the latest stable version is not available in the default repositories. </blockquote> <ul> <li><strong>Arch-based distributions</strong>:</li> </ul> <code>bash sudo pacman -S qt6-base qscintilla-qt6 qt6-charts qt6-multimedia qt6-svg qt6-webchannel qt6-webengine zig</code> Once the required packages are installed, the library can be built from the root of the repository: <code>bash zig build</code> Users of Arch-based distributions need to <strong>make sure that all packages are up-to-date</strong> first and will need to add the following option to support successful compilation: <code>bash zig build -Denable-workaround</code> The compiled libraries can be installed to the system in a non-default location by adding the <code>--prefix-lib-dir</code> option to the build command: <code>bash sudo zig build --prefix-lib-dir /usr/local/lib/libqt6zig # creates /usr/local/lib/libqt6zig/{libraries}</code> To skip the restricted extras: <code>bash zig build -Dskip-restricted</code> To see the full list of build options available: <code>bash zig build --help</code> Usage <ul> <li>Import the library into your project:</li> </ul> <code>bash zig fetch --save git+https://github.com/rcalixte/libqt6zig</code> Append <code>#&lt;tag&gt;</code>, <code>#&lt;commit&gt;</code>, or <code>#&lt;branch&gt;</code> to the end of the URL to pin to a specific version of the library. <ul> <li>Add the library to your <code>build.zig</code> file:</li> </ul> ```zig const qt6zig = b.dependency("libqt6zig", .{ .target = target, .optimize = .ReleaseFast, }); // After defining the executable, add the module from the library exe.root_module.addImport("libqt6zig", qt6zig.module("libqt6zig")); // Link the compiled libqt6zing libraries to the executable // qt_lib_name is the name of the target library without prefix and suffix, e.g. qapplication, qwidget, etc. exe.root_module.linkLibrary(qt6zig.artifact(qt_lib_name)); ``` <strong>Extra options are required for building on Arch-based distributions. Refer to the build system at the examples link below for more details.</strong> <ul> <li>Use the library in your code:</li> </ul> ```zig // the main qt6 module to import const qt6 = @import("libqt6zig"); // C ABI Qt typedefs (if needed) const C = qt6.C; // Qt class imports for Zig const qapplication = qt6.qapplication; const qwidget = qt6.qwidget; const qnamespace_enums = qt6.qnamespace_enums; ``` Full examples of the build system and sample applications can be found in the <a><code>libqt6zig-examples</code></a> repository. Cross-compilation is not supported by this library at this time. FAQ Q1. Can I release a proprietary, commercial app with this binding? Yes. You must also meet your Qt license obligations: either dynamically link Qt library files under the LGPL or purchase a Qt commercial license for static linking. Q2. How long does it take to compile? Under normal conditions, the first compilation of the entire library should take less than 10 minutes, assuming the hardware in use is at or above the level of that of a consumer-grade mid-tier machine released in the past decade. Once the build cache is warmed up, subsequent compilations should be very fast, on the order of seconds. For client applications that use and configure a specific subset of the main library, the expected compilation time should be much shorter, e.g. compiling the <code>helloworld</code> example, only linking the libraries needed and without a warm cache, should take under 30 seconds. Q3. How does the <code>libqt6zig</code> API differ from the official Qt C++ API? Supported Qt C++ class methods are implemented 1:1 as structs of functions where the function names in Zig correspond to the PascalCase equivalent of the Qt C++ method and the struct names are lowercase equivalents of the Qt C++ class name. <a>The official Qt documentation</a> should be used for reference and is included in the library wrapper source code (though not all links are guaranteed to work perfectly, nor is this functionality in scope for this project). <ul> <li><code>QWidget::show()</code> is projected as <code>qwidget.Show(?*anyopaque)</code></li> <li><code>QPushButton::setText(QString)</code> is projected as <code>qpushbutton.SetText(?*anyopaque, []const u8)</code></li> </ul> As a mental model, developers consuming this library should keep in mind that there are essentially two different tracks of memory management required for clean operation: one for the C++ side and one for the Zig side. The Zig side is managed by the developer and the C++ side has variant ownership semantics. Ownership semantics are documented throughout the <a>C++ documentation</a>. There are bits of idiomatic Zig in the library in the form of allocators as parameters to functions but much of the code is not idiomatic for Zig due to the complexity of the Qt C++ API. Knowledge of the Qt C++ API is required to understand and make full use of the library. While not an exhaustive list, there are some key topics to understand: <ul> <li><a>Qt object ownership</a></li> <li><a>Qt signals and slots</a></li> <li><a>Qt's property system</a></li> <li><a>Qt's Meta-Object system</a></li> <li><a>Qt widgets</a></li> </ul> The <code>QByteArray</code>, <code>QString</code>, <code>QList&lt;T&gt;</code>, <code>QVector&lt;T&gt;</code>, <code>QMap&lt;K,V&gt;</code>, <code>QHash&lt;K,V&gt;</code> types are projected as plain Zig types: <code>[]u8</code>, <code>[]const u8</code>, <code>[]T</code>, <code>AutoHashMapUnmanaged[K]V</code>, and <code>StringHashMapUnmanaged[V]</code>. Therefore, it is not possible to call any of the Qt type's methods and some Zig equivalent method must be used instead. (The raw C ABI is also available due to the headers being required to define Qt types in Zig, but it is not recommended for use beyond Qt class type definitions where needed.) This library was constructed with the goal of enabling single-language application development. Anything beyond that boundary is up to the developer to implement. <ul> <li> Zig string types are internally converted to <code>QString</code> using <code>QString::fromUtf8</code>. Therefore, the Zig string input must be UTF-8 to avoid <a>mojibake</a>. If the Zig input string contains binary data, the conversion would corrupt such bytes into U+FFFD (�). On return to Zig space, this becomes <code>\xEF\xBF\xBD</code>. </li> <li> The iteration order of a Qt <code>QMap</code>/<code>QHash</code> will differ from the Zig API map iteration order. <code>QMap</code> is iterated by key order, but the Zig maps used by the library and <code>QHash</code> iterate in an undefined internal order. Future versions of <code>libqt6zig</code> may provide a way to iterate in a specific order. </li> </ul> There is a helper library that contains some types and functions that are useful for the C ABI but these are not required for the Zig API. Where Qt returns a C++ object by value (e.g. <code>QSize</code>), the binding may have moved it to the heap, and in Zig, this may be represented as a pointer type. In such cases, the caller is the owner and must free the object (using either <code>QDelete</code> methods for the type or deallocating or destroying via the allocators). This means code using <code>libqt6zig</code> can look similar to the Qt C++ equivalent code but with the addition of proper memory management. The <code>connect(targetObject, targetSlot)</code> methods are projected as <code>On(targetObject, fn() callconv(.c)...)</code>. While the parameters in the methods themselves are more convenient to use, the documentation comments in the Zig source code should be used for reference for the proper usage of the parameter types and Qt vtable references. The example code above includes a simple callback function that can be used as a reference. <ul> <li>You can also override virtual methods like <code>PaintEvent</code> in the same way. Where supported, there are additional <code>On</code> and <code>QBase</code> variants:</li> <li><code>OnPaintEvent</code>: Set an override callback function to be called when <code>PaintEvent</code> is invoked. For certain methods, even with the override set, the base class implementation can still be called by Qt internally and these calls can not be prevented.</li> <li><code>QBasePaintEvent</code>: Invoke the base class implementation of <code>PaintEvent</code>. This is useful for when the custom implementation requires the base class implementation. (When there is no override set, the <code>QBase</code> implementation is equivalent to <code>PaintEvent</code>.)</li> </ul> Qt class inherited types are projected via opaque pointers and <code>@ptrCast</code> in Zig. For example, to pass a <code>var myLabel: ?*QLabel</code> to a function taking only the <code>?*QWidget</code> base class, it should be sufficient to pass <code>myLabel</code> and the library will automatically cast it to the correct type and Qt vtable reference. <ul> <li>When a Qt subclass adds a method overload (e.g. <code>QMenu::sizeHint(QMenu*)</code> vs <code>QWidget::sizeHint(QWidget*)</code>), the base class version is shadowed and can only be called via <code>qwidget.SizeHint(?*anyopaque)</code> while the subclass implementation can be called directly, e.g. <code>qmenu.SizeHint(?*anyopaque)</code>. Inherited methods are shadowed for convenience as well, e.g. <code>qmenu.Show(?*anyopaque)</code> is equivalent to <code>qwidget.Show(?*anyopaque)</code>. While the library aims to simplify usage, consideration should still be given to the Qt documentation for the proper usage of the parameter types and Qt vtable references.</li> </ul> Qt expects fixed OS threads to be used for each QObject. When you first call <code>qapplication.New</code>, that will be considered the <a>Qt main thread</a>. <ul> <li>When accessing Qt objects from inside another thread, it's safest to use <code>Threading.Async()</code> (from this library) to access the Qt objects from Qt's main thread. The <a>Threading library</a> documents additional available strategies within the source code.</li> </ul> Qt C++ enums are projected as Zig enum structs of <code>i32</code> or <code>i64</code> values with the same names. For example, <code>Qt::AlignmentFlag</code> is projected as <code>enums.AlignmentFlag</code> within the <code>libqnamespace</code> module and exported by default as <code>qnamespace_enums.AlignmentFlag</code> though developers are free to use whatever naming convention they prefer for imports. Enums are currently defined as either <code>i32</code> or <code>i64</code> (where necessary) in the Zig API and as <code>i64</code> when expected as a parameter or returned as a type by the Zig API. Some C++ idioms that were difficult to project were omitted from the binding. This can be improved in the future. Q4. What build modes are supported by the library? Currently, only <code>ReleaseFast</code>, <code>ReleaseSafe</code>, and <code>ReleaseSmall</code> are supported. The <code>Debug</code> build mode is not supported. This may change in the future. The default build mode is <code>ReleaseFast</code>. To change the build mode: <code>bash zig build -Doptimize=ReleaseSafe</code> or <code>bash zig build --release=safe</code> Q5. Can I use Qt Designer and the Qt Resource system? MIQT (the upstream Qt bindings for Go) has a custom implementation of Qt <code>uic</code> and <code>rcc</code> tools, to allow using <a>Qt Designer</a> for form design and resource management. There is work in progress to support Qt Designer with this library in the future. Q6. How can I add bindings for another Qt library? Fork this repository and add your library to the <code>genbindings/config-libraries</code> file. <a>Read more »</a> Special Thanks <ul> <li> <a>@mappu</a> for the <a>MIQT</a> bindings that provided the phenomenal foundation for this project </li> <li> <a>@arnetheduck</a> for proving the value of collaboration on the back-end of this project while working across different target languages </li> </ul>
[ "https://github.com/rcalixte/libqt6zig-examples" ]
https://avatars.githubusercontent.com/u/8210099?v=4
zli
xcaeser/zli
2025-05-14T20:39:08Z
📟 A blazing fast Zig CLI framework. Build ergonomic, high-performance command-line tools with ease.
main
1
41
3
41
https://api.github.com/repos/xcaeser/zli/tags
MIT
[ "cli", "zig", "zig-library" ]
69
false
2025-05-20T20:32:45Z
true
true
0.14.0
github
[]
📟 zli A <strong>blazing-fast</strong>, zero-cost CLI framework for Zig — inspired by Cobra (Go) and clap (Rust). Build modular, ergonomic, and high-performance CLIs with ease. <a></a> <a></a> <a></a> <a></a> <blockquote> [!TIP] 🧱 Each command is modular and self-contained. </blockquote> 📚 Documentation See <a>docs.md</a> for full usage, examples, and internals. 🚀 Highlights <ul> <li>Modular commands &amp; subcommands</li> <li>Fast flag parsing (<code>--flag</code>, <code>--flag=value</code>, shorthand <code>-abc</code>)</li> <li>Type-safe support for <code>bool</code>, <code>int</code>, <code>string</code></li> <li>Auto help/version/deprecation handling</li> <li>Works like Cobra or clap, but in Zig</li> </ul> 📦 Installation <code>sh zig fetch --save=zli https://github.com/xcaeser/zli/archive/v3.1.6.tar.gz</code> Add to your <code>build.zig</code>: <code>zig const zli_dep = b.dependency("zli", .{ .target = target }); exe.root_module.addImport("zli", zli_dep.module("zli"));</code> 🗂 Suggested Structure <code>your-app/ ├── build.zig ├── src/ │ ├── main.zig │ └── cli/ │ ├── root.zig │ ├── run.zig │ └── version.zig</code> <ul> <li>Each command is in its own file</li> <li>You explicitly register subcommands</li> <li>Root is the entry point</li> </ul> 🧪 Example ```zig // src/main.zig const std = @import("std"); const cli = @import("cli/root.zig"); pub fn main() !void { const allocator = std.heap.smp_allocator; var root = try cli.build(allocator); defer root.deinit(); <code>try root.execute(); </code> } ``` ```zig // src/cli/root.zig const std = @import("std"); const zli = @import("zli"); const run = @import("run.zig"); const version = @import("version.zig"); pub fn build(allocator: std.mem.Allocator) !*zli.Command { const root = try zli.Command.init(allocator, .{ .name = "blitz", .description = "Your dev toolkit CLI", }, showHelp); <code>try root.addCommands(&amp;.{ try run.register(allocator), try version.register(allocator), }); return root; </code> } fn showHelp(ctx: zli.CommandContext) !void { try ctx.command.printHelp(); <code>// try ctx.command.listCommands(); </code> } ``` ```zig // src/cli/run.zig const std = @import("std"); const zli = @import("zli"); const now_flag = zli.Flag{ .name = "now", .shortcut = "n", .description = "Run immediately", .flag_type = .Bool, .default_value = .{ .Bool = false }, }; pub fn register(allocator: std.mem.Allocator) !*zli.Command { const cmd = try zli.Command.init(allocator, .{ .name = "run", .description = "Run your workflow", }, run); <code>try cmd.addFlag(now_flag); return cmd; </code> } fn run(ctx: zli.CommandContext) !void { const now = ctx.command.getBoolValue("now"); std.debug.print("Running now: {}\n", .{now}); <code>// do something with ctx: ctx.root, ctx.direct_parent, ctx.command ... // do whatever you want here </code> } ``` ```zig // src/cli/version.zig const std = @import("std"); const zli = @import("zli"); pub fn register(allocator: std.mem.Allocator) !*zli.Command { return zli.Command.init(allocator, .{ .name = "version", .shortcut = "v", .description = "Show CLI version", }, show); } fn show(ctx: zli.CommandContext) !void { std.debug.print("{}\n", .{ctx.root.options.version}); } ``` ✅ Features Checklist <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> Commands &amp; subcommands <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> Flags &amp; shorthands <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> Type-safe flag values <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> Help/version auto 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> Deprecation notices <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> Positional args <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> Command aliases <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> Persistent flags 📝 License MIT. See <a>LICENSE</a>. Contributions welcome.
[]
https://avatars.githubusercontent.com/u/2793150?v=4
zigft
chung-leong/zigft
2025-03-20T12:13:19Z
Zig function transform library
main
1
37
0
37
https://api.github.com/repos/chung-leong/zigft/tags
MIT
[ "zig", "zig-package" ]
7,014
false
2025-05-16T19:26:08Z
true
true
0.14.0
github
[]
Zigft Zigft is a small library that lets you perform function transform in Zig. Consisting of just two files, it's designed to be used in source form. Simply download the file you need from this repo, place it in your <code>src</code> directory, and import it into your own code. <a><code>fn-transform.zig</code></a> provides the library's core functionality. <a><code>fn-binding.zig</code></a> meanwhile gives you the ability to bind variables to a function. This project's code was developed original for <a>Zigar</a>. Check it out of you haven't already learned of its existence. fn-transform.zig <code>fn-transform.zig</code> provides a single function: <a><code>spreadArgs()</code></a>. It takes a function that accepts a tuple as the only argument and returns a new function where the tuple elements are spread across the argument list. For example, if the following function is the input: <code>zig fn hello(args: std.meta.Tuple(&amp;.{ i8, i16, i32, i64 })) bool { // ...; }</code> Then <code>spreadArgs(hello, null)</code> will return: <code>zig *const fn (i8, i16, i32, i64) bool</code> Because you have full control over the definition of the tuple at comptime, <code>spreadArgs()</code> basically lets you to generate any function you want. The only limitation is that its arguments cannot be <code>comptime</code> or <code>anytype</code>. It's easier to see the function's purpose in action. Here're some usage scenarios: Adding debug output to a function: ```zig const std = @import("std"); const fn_transform = @import("./fn-transform.zig"); fn attachDebugOutput(comptime func: anytype, comptime name: []const u8) @TypeOf(func) { const FT = @TypeOf(func); const fn_info = @typeInfo(FT).@"fn"; const ns = struct { inline fn call(args: std.meta.ArgsTuple(FT)) fn_info.return_type.? { std.debug.print("{s}: {any}\n", .{ name, args }); return @call(.auto, func, args); } }; return fn_transform.spreadArgs(ns.call, fn_info.calling_convention); } pub fn main() void { const ns = struct { fn hello(a: i32, b: i32) void { std.debug.print("sum = {d}\n", .{a + b}); } }; const func = attachDebugOutput(ns.hello, "hello"); func(123, 456); } <code></code> hello: { 123, 456 } sum = 579 ``` "Uninlining" an explicitly inline function: ```zig const std = @import("std"); const fn_transform = @import("./fn-transform.zig"); fn Uninlined(comptime FT: type) type { const f = @typeInfo(FT).@"fn"; if (f.calling_convention != .@"inline") return FT; return @Type(.{ .@"fn" = .{ .calling_convention = .auto, .is_generic = f.is_generic, .is_var_args = f.is_var_args, .return_type = f.return_type, .params = f.params, }, }); } fn uninline(func: anytype) Uninlined(@TypeOf(func)) { const FT = @TypeOf(func); const f = @typeInfo(FT).@"fn"; if (f.calling_convention != .@"inline") return func; const ns = struct { inline fn call(args: std.meta.ArgsTuple(FT)) f.return_type.? { return @call(.auto, func, args); } }; return fn_transform.spreadArgs(ns.call, .auto); } pub fn main() void { const ns = struct { inline fn hello(a: i32, b: i32) void { std.debug.print("sum = {d}\n", .{a + b}); } }; const func = uninline(ns.hello); std.debug.print("fn address = {x}\n", .{@intFromPtr(&amp;func)}); } <code></code> fn address = 10deb00 ``` Converting a function that returns an error code into one that returns an error union: ```zig const std = @import("std"); const fn_transform = @import("./fn-transform.zig"); const OriginalErrorEnum = enum(c_int) { OK, APPLE_IS_ROTTING, BANANA_STINKS, CANTALOUPE_EXPLODED, }; fn originalFn() callconv(.c) OriginalErrorEnum { return .CANTALOUPE_EXPLODED; } const NewErrorSet = error{ AppleIsRotting, BananaStink, CantaloupeExploded, }; fn Translated(comptime FT: type) type { return @Type(.{ .@"fn" = .{ .calling_convention = .auto, .is_generic = false, .is_var_args = false, .return_type = NewErrorSet!void, .params = @typeInfo(FT).@"fn".params, }, }); } fn translate(comptime func: anytype) Translated(@TypeOf(func)) { const error_list = init: { const es = @typeInfo(NewErrorSet).error_set.?; var list: [es.len]NewErrorSet = undefined; inline for (es, 0..) |e, index| { list[index] = @field(NewErrorSet, e.name); } break :init list; }; const FT = @TypeOf(func); const TFT = Translated(FT); const ns = struct { inline fn call(args: std.meta.ArgsTuple(TFT)) NewErrorSet!void { const result = @call(.auto, func, args); if (result != .OK) { const index: usize = @intCast(@intFromEnum(result) - 1); return error_list[index]; } } }; return fn_transform.spreadArgs(ns.call, .auto); } pub fn main() !void { const func = translate(originalFn); try func(); } <code></code> error: CantaloupeExploded /home/cleong/zigft/fn-transform.zig:97:13: 0x10de01e in call0 (example-enum-to-error) return func(.{}); ^ /home/cleong/zigft/example-enum-to-error.zig:58:5: 0x10ddf53 in main (example-enum-to-error) try func(); ``` fn-binding.zig <code>fn-binding.zig</code> provides a <a>set of functions</a> related to function binding. <a><code>bind()</code></a> and <a><code>unbind()</code></a> are the pair you will most likely use. The first argument to <code>bind()</code> can be either <code>fn (...)</code> or <code>*const fn (...)</code>. The second argument is a tuple containing arguments for the given function. The function returned by <code>bind()</code> depends on the tuple's content. If it provides a complete set of arguments, then the returned function will have an empty argument list. That is the case for the following example: ```zig const std = @import("std"); const fn_binding = @import("./fn-binding.zig"); pub fn main() !void { var funcs: [5]<em>const fn () void = undefined; for (&amp;funcs, 0..) |</em>ptr, index| ptr.* = try fn_binding.bind(std.debug.print, .{ "hello: {d}\n", .{index + 1} }); defer for (funcs) |f| fn_binding.unbind(f); for (funcs) |f| f(); } <code></code> hello: 1 hello: 2 hello: 3 hello: 4 hello: 5 ``` If you wish to bind to arguments in the middle of the argument list while leaving preceding ones unbound, you can do so with the help of explicit indices: ```zig const std = @import("std"); const fn_binding = @import("./fn-binding.zig"); pub fn main() !void { const ns = struct { fn hello(a: i8, b: i16, c: i32, d: i64) void { std.debug.print("a = {d}, b = {d}, c = {d}, d = {d}\n", .{ a, b, c, d }); } }; const func1 = try fn_binding.bind(ns.hello, .{ .@"2" = 300 }); defer fn_binding.unbind(func1); func1(1, 2, 4); const func2 = try fn_binding.bind(ns.hello, .{ .@"-2" = 301 }); defer fn_binding.unbind(func2); func2(1, 2, 4); } <code></code> a = 1, b = 2, c = 300, d = 4 a = 1, b = 2, c = 301, d = 4 ``` Negative indices mean "from the end". Binding to inline functions is possible: ```zig const std = @import("std"); const fn_binding = @import("./fn-binding.zig"); pub fn main() !void { const ns = struct { inline fn hello(a: i32, b: i32) void { std.debug.print("sum = {d}\n", .{a + b}); } }; const func = try fn_binding.bind(ns.hello, .{ .@"-1" = 123 }); func(3); } <code></code> sum = 126 ``` Binding to inline functions with <code>comptime</code> or <code>anytype</code> arguments is impossible, however. As you've seen already in the example involving <a><code>std.debug.print()</code></a>, binding to functions with <code>comptime</code> and <code>anytype</code> arguments is permitted as long as the resulting function will have no such arguments. In a <code>comptime</code> context, <code>bind()</code> would create a comptime binding. You would basically get a regular, not-dynamically-generated function: ```zig const std = @import("std"); const fn_binding = @import("./fn-binding.zig"); pub fn main() !void { const ns = struct { const dog = fn_binding.bind(std.debug.print, .{ "Woof!\n", .{} }) catch unreachable; const cat = fn_binding.bind(std.debug.print, .{ "Meow!\n", .{} }) catch unreachable; const fox = fn_binding.define(std.debug.print, .{ "???\n", .{} }); }; ns.dog(); ns.cat(); ns.fox(); } <code></code> Woof! Meow! ??? ``` Use <a><code>define()</code></a> instead in this scenario if you dislike the appearance of <code>catch unreachable</code>. <a><code>closure()</code></a> lets you conveniently creating a closure with the help of an inline struct type: ```zig const std = @import("std"); const fn_binding = @import("./fn-binding.zig"); pub fn main() !void { var funcs: [5]<em>const fn (i32) void = undefined; for (&amp;funcs, 0..) |</em>ptr, index| ptr.* = try fn_binding.close(struct { number: usize, <code> pub fn print(self: @This(), arg: i32) void { std.debug.print("Hello: {d}, {d}\n", .{ self.number, arg }); } }, .{ .number = index }); defer for (funcs) |f| fn_binding.unbind(f); for (funcs) |f| f(123); </code> } <code></code> Hello: 0, 123 Hello: 1, 123 Hello: 2, 123 Hello: 3, 123 Hello: 4, 123 ``` The function in the struct can have any name. It must be the only public function. Limitations Function binding requires hardware-specific code. CPU architectures currently supported: <code>x86_64</code>, <code>x86</code>, <code>aarch64</code>, <code>arm</code>, <code>riscv64</code>, <code>riscv32</code>, <code>powerpc64</code>, <code>powerpc64le</code>, <code>powerpc</code>. Support for earlier versions of Zig Zigft is designed for Zig 0.14.0. The code in fn-transform.zig will work in 0.13.0--after you have replaced <code>.@"struct"</code> and <code>.@"fn"</code> with <code>.Struct</code> and <code>.Fn</code>. The code in fn-binding.zig cannot be made to work in 0.13.0 when <code>optimize</code> is <code>Debug</code> due to the compiler insisting on initializing uninitialized variables to <code>0xAAA...A</code>.
[]
https://avatars.githubusercontent.com/u/1548114?v=4
parcom
dokwork/parcom
2025-02-20T07:51:40Z
Parser combinators for Zig, ready to parse on-the-fly. Consume input, not memory.
main
0
30
0
30
https://api.github.com/repos/dokwork/parcom/tags
MIT
[ "parser", "parser-combinators", "zig", "zig-library", "zig-package", "ziglang" ]
65
false
2025-05-16T10:35:43Z
true
true
0.14.0
github
[]
parcom <a></a> <em>Consume input, not memory.</em> <blockquote> <span class="bg-yellow-100 text-yellow-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300">WARNING</span> This library is underdeveloped. API is not stable. </blockquote> This library provides an implementation of the parser combinators. Three different types of parser implementations exist: <ul> <li>The base parser implementations contain the logic for parsing input and serve as the fundamental building blocks;</li> <li>The <code>ParserCombinator</code>provides methods to combine parsers and create new ones;</li> <li>The <code>TaggedParser</code> erases the type of the underlying parser and simplifies the parser's type declaration.</li> </ul> Every parser provides the type of the parsing result as a constant <code>ResultType: type</code>. <code>Parcom</code> offers two options for consuming data: - parse the entire input string at once, - or consume and parse byte by byte from <code>AnyReader</code>. When the input is a reader, <code>Parcom</code> works as a buffered reader. It reads few bytes to the buffer and then parse them. The result of parsing by any parser can be a value of type <code>ResultType</code> in successful case, or <code>null</code> if parsing was failed. In successful case not whole input can be consumed. If you have to be sure, that every byte was consumed and parsed, use the <a><code>end()</code></a> parser explicitly. Installation Fetch <code>Parcom</code> from github: <code>sh zig fetch --save git+https://github.com/dokwork/parcom</code> Check that it was added to the list of dependencies in your <code>build.zig.zon</code> file: <code>zig ... .dependencies = .{ .parcom = .{ .url = "git+https://github.com/dokwork/parcom#b93b8fb14f489007f27d42f8254f12b7d57d07da", .hash = "parcom-0.3.0-Hs8wfHFUAQBhhH-swYl1wrMLSh76uApvVzYBl56t90Ua", }, },</code> Add <code>Parcom</code> module to your <code>build.zig</code>: <code>zig const parcom = b.dependency("parcom", .{ .target = target, .optimize = optimize, }); ... exe.root_module.addImport("parcom", parcom.module("parcom"));</code> Quick start Let's create a parser, which will parse and execute a simple math expression with follow grammar: ``` The <code>number</code> is a sequence of unsigned integer numbers Number := [0-9]+ The <code>value</code> is a <code>number</code> or an <code>expression</code> in brackets Value := Number / '(' Expr ')' The <code>sum</code> is an operation of adding or substraction of two or more values Sum := Value (('+' / '-') Value)* The <code>expression</code> is result of evaluation the combination of values and operations Expr := evaluate(Sum) ``` Our parser will be capable of parsing and evaluating mathematical expressions that include addition and subtraction operations, unsigned integers, and nested expressions within brackets. Base parser The <code>number</code> from the grammar above is a sequence of symbols from the range ['0', '9']. Parcom has a constructor of the parser of bytes in a range, but we will create our own parser starting from the base parser <code>AnyChar</code>. <code>AnyChar</code> is a simplest parser consumed the input. It returns the next byte from the input, or <code>null</code> if the input is empty. To parse only numeric symbols we should provide a classifier - function that receives the result of a parser and returns true only if it is an expected value: ```zig const parcom = @import("parcom"); // ResultType: u8 const num_char = parcom.anyChar().suchThat({}, struct { fn condition(_: void, ch: u8) bool { return switch (ch) { '0' ... '9' =&gt; true, else =&gt; false, }; } }.condition); <code>`` Every function required i combinators in</code>Parcom<code>library has a</code>context` parameter. That gives more flexibility for possible implementations of that functions. Repeat parsers Next, we should continue applying our parser until we encounter the first non-numeric symbol or reach the end of the input. To achieve this, we need to store the parsed results. The simplest solution is to use a sentinel array: <code>zig // ResultType: [10:0]u8 const number = num_char.repeatToSentinelArray(.{ .max_count = 10 });</code> But that option is available only for parsers with scalar result types. For more general cases a regular array can be used. If you know exact count of elements in the parsed sequence, you can specified it to have an array with exact length as result: <code>zig // ResultType: [3]u8 const number = num_char.repeatToArray(3);</code> However, this is a rare case. More often, the exact number of elements is unknown, but the maximum number can be estimated: <code>zig // ResultType: struct { [10]u8, usize } const number = num_char.repeatToArray(.{ .max_count = 10 });</code> In such cases, the result is a tuple consisting of the array and a count of the parsed items within it. For cases, when impossible to predict the maximum count we can allocate a slice to store the parsed results: ```zig // ResultType: []u8 const number = num_char.repeat(allocator, .{}); // Don't forget to free the memory, allocated for the slice! <code>or use an arbitrary storage and a function to add an item to it:</code>zig var list = std.ArrayList(u8).init(allocator); defer list.deinit(); // ResultType: *std.ArrayList(u8) const p = anyChar().repeatTo(&amp;list, .{}, std.ArrayList(u8).append); ``` Notice, that no matter which combinator you use to collected repeated numbers, you have to set the <code>.min_count</code> to 1, because of empty collection of chars is not a number! <code>zig // ResultType: []u8 const number = num_char.repeat(allocator, .{ .min_count = 1 });</code> <strong>RepeatOptions</strong> All repeated combinators except the <code>repeatToArray(usize)</code> receive the <code>RepeatOptions</code>, a structure with minimum and maximum counts of the elements in the sequence. All parsers stop when reach the maximum count and fail if don't reach the minimum. Try one or try another We'll postpone the <code>value</code> parser for now, and instead of that will focus on creating a parsers for the '+' and '-' symbols. <code>zig // ResultType: i32 const value: ParserCombinator(???) = ???;</code> First of all, we should be able to parse every symbol separately. The <code>char</code> parser is the best candidate for it: <code>zig const plus = parcom.char('+'); const minus = parcom.char('-');</code> Next, we have to choose one of them. To accomplish this, let's combine parsers to a new one, that first attempt one, and if it fails, it will try the other: <code>zig // ResultType: parcom.Either(u8, u8) const plus_or_minus = plus.orElse(minus);</code> The result type of the new parser is <code>parcom.Either(L, R)</code>, an alias for <code>union(enum) { left: L, right: R }</code> type. Combine results We have a parser for operations and we assume that we have a parser for values as well. This is sufficient to build the <code>Sum</code> parser, which, as you may recall, follows this structure: <code>Sum := Value (('+' / '-') Value)*</code> Let's start from the part in brackets. We have to combine the <code>plus_or_minus</code> parser with <code>value</code> parser and repeat result: <code>zig // ResultType: []struct{ parcom.Either(u8, u8), i32 } plus_or_minus.andThen(value).repeat(allocator, .{});</code> The <code>andThen</code> combinator runs the left parser and then the right. If both parsers were successful, it returns a tuple of results. Finally, we can combine the value with the new parser to have the version of the <code>expression</code> parser that follows the grammar: <code>zig // ResultType: struct{ i32, []struct{ parcom.Either(u8, u8), i32 } } const sum = value.andThen(plus_or_minus.andThen(value).repeat(allocator, .{}));</code> Transform the result So far so good. We are ready to create a parser that will not only parse the input, but also sum of parsed values: <code>zig const expr = sum.transform(i32, {}, struct { fn evaluate(_: void, value: struct{ i32, []struct{ Either(u8, u8), i32 } }) !i32 { var result: i32 = value[0]; for (value[1]) |op_and_arg| { switch(op_and_arg[0]) { .left =&gt; result += op_and_arg[1], .right =&gt; result -= op_and_arg[1], ) } return result; } }.evaluate);</code> The combinator <code>transform</code> requires a context and a function for transformation. It runs the left parser and applies the function to the parsed result. Tagged parser Now the time to build the <code>value</code> parser: <code>Value := Number / '(' Expr ')'</code> This is a recursive parser that not only forms part of the <code>expression</code> parser but also depends on it. How we can implement this? First of all, let's wrap the <code>expression</code> parser to the function: ```zig const std = @import("std"); const parcom = @import("parcom"); fn expression(allocator: std.mem.Allocator) ??? { <code>// ResultType: u8 const num_char = parcom.anyChar().suchThat({}, struct { fn condition(_: void, ch: u8) bool { return switch (ch) { '0' ... '9' =&gt; true, else =&gt; false, }; } }.condition); // ResultType: i32 const number = num_char.repeat(allocator, .{ .min_count = 1 }).transform(i32, {}, struct { fn parseInt(_: void, value: []u8) !i32 { return try std.fmt.parseInt(i32, value, 10); } }.parseInt); // ResultType: i32 const value = ???; // ResultType: parcom.Either(u8, u8) const plus_or_minus = parcom.char('+').orElse(parcom.char('-')); // ResultType: struct{ i32, []struct{ parcom.Either(u8, u8), i32 } } const sum = value.andThen(plus_or_minus.andThen(value).repeat(allocator, .{})); const expr = sum.transform(i32, {}, struct { fn evaluate(_: void, v: struct{ i32, []struct{ parcom.Either(u8, u8), i32 } }) !i32 { var result: i32 = v[0]; for (v[1]) |op_and_arg| { switch(op_and_arg[0]) { .left =&gt; result += op_and_arg[1], .right =&gt; result -= op_and_arg[1], } } return result; } }.evaluate); return expr; </code> } <code>The type of `ParserCombinator` in `Parcom` can be very cumbersome, and it is often impractical to manually declare it as a function's type. However, Zig requires this type to allocate enough memory for the parser instance. While most parsers in `Parcom` are simply namespaces, this is not true for all of them. What can we do is moving our parser to heap and replace particular type by the pointer to it. This is exactly how the `TaggedParser` works. It has a pointer to the original parser, and a pointer to a function responsible for parsing the input. More over, the `TaggedParser` has explicit `ResultType`:</code>zig const std = @import("std"); const parcom = @import("parcom"); fn expression(allocator: std.mem.Allocator) parcom.TaggedParser(i32) { ... return expr.taggedAllocated(allocator); } ``` Deferred parser Let's go ahead and finally build the <code>value</code> parser: <code>zig const value = number.orElse( parcom.char('(').rightThen(expression(allocator)).leftThen(parcom.char(')') );</code> Pay attention on <code>rightThen</code> and <code>leftThen</code> combinators. Unlike the <code>andThen</code> combinator, these two do not produce a tuple. Instead, they ignore one value and return another. The <code>rightThen</code> uses only result of the right parser, and <code>leftThen</code> of the left parser respectively. It means, that both brackets will be parsed, but ignored in the example above. But this is not all. Unfortunately, such implementation of the <code>value</code> parser will lead to infinite loop of invocations the <code>expression</code> function. We can solve this by invoking the function only when we need to parse an expression within brackets. The <code>Parcom</code> has the <code>deferred</code> parser for such purposes. It receives the <code>ResultType</code> of <code>TaggedParser</code> which should be returned by the function, a context that should be passed to the function and pointer to the function: <code>zig const value = number.orElse( parcom.char('(').rightThen(parcom.deferred(i32, allocator, expression)).leftThen(parcom.char(')')) );</code> When the tagged parsed completes its deferred work, the <code>deinit</code> method will be invoked, and memory will be freed. But, do not forget to invoke <code>deinit</code> manually, when you create the <code>TaggedParser</code> outside the <code>deferred</code> parser! Complete solution ```zig const std = @import("std"); const parcom = @import("parcom"); fn expression(allocator: std.mem.Allocator) !parcom.TaggedParser(i32) { // ResultType: u8 const num_char = parcom.anyChar().suchThat({}, struct { fn condition(_: void, ch: u8) bool { return switch (ch) { '0' ... '9' =&gt; true, else =&gt; false, }; } }.condition); // ResultType: i32 const number = num_char.repeat(allocator, .{ .min_count = 1 }).transform(i32, {}, struct { fn parseInt(_: void, value: []u8) !i32 { return try std.fmt.parseInt(i32, value, 10); } }.parseInt); // ResultType: i32 const value = number.orElse( parcom.char('(').rightThen(parcom.deferred(i32, allocator, expression)).leftThen(parcom.char(')')) ) .transform(i32, {}, struct { fn getFromEither(_: void, v: parcom.Either(i32, i32)) !i32 { return switch (v) { .left =&gt; v.left, .right =&gt; v.right, }; } }.getFromEither); // ResultType: parcom.Either(u8, u8) const plus_or_minus = parcom.char('+').orElse(parcom.char('-')); // ResultType: struct{ i32, []struct{ parcom.Either(u8, u8), i32 } } const sum = value.andThen(plus_or_minus.andThen(value).repeat(allocator, .{})); // ResultType: i32 const expr = sum.transform(i32, {}, struct { fn evaluate(_: void, v: struct{ i32, []struct{ parcom.Either(u8, u8), i32 } }) !i32 { var result: i32 = v[0]; for (v[1]) |op_and_arg| { switch(op_and_arg[0]) { .left =&gt; result += op_and_arg[1], .right =&gt; result -= op_and_arg[1], } } return result; } }.evaluate); return expr.taggedAllocated(allocator); } test "9-(5+2) == 2" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const parser = try expression(arena.allocator()); try std.testing.expectEqual(2, try parser.parseString("9-(5+2)")); } ``` Cutting the input In some cases it is reasonable not to consume the entire input to the string, and instead parse it on-the-fly. For such cases, the <code>Parcom</code> library provides the <code>parseFromReader</code> method, which takes a <code>std.io.AnyReader</code> as the input. During the parsing, all consumed bytes are stored in an internal buffer to make it possible to rollback the input and try another parser (such as with the <code>orElse</code> combinator). While this approach may lead to the same result as reading the whole input to the string, rollback may not make sense for some parsers. For example, when parsing JSON, encountering the '{' symbol means the entire JObject must be parsed. If parsing cannot proceed, it indicates that the input is malformed, and all parsers will failed. It means, that the input can be cropped right before the '{' symbol. In the example above can be reasonable to cut the input when the left brace is parsed: <code>zig ... const value = number.orElse( parcom.char('(').cut().rightThen(parcom.deferred(i32, allocator, expression)).leftThen(parcom.char(')')) // added this ^ ) ...</code> Cropping the input, when possible, can significantly reduce required memory and may improve the speed of parsing. See <a>this example</a> for more details. Debug When something is going wrong during the parsing, and a correct at first glance parser returns null, it can be difficult to understand the root cause without additional insights. In <code>Parcom</code> you can turn on logging for any particular parser to see how it works during the parsing. For example, let's turn on logging for the expression parser from the example above (with added <code>cut</code> combinator) <code>zig ... return expr.logged(.{ .label = "EXPR", .scope = .example }).taggedAllocated(allocator); }</code> and run it on a string with unexpected symbol '!': <code>zig test "parse unexpected symbol" { // don't forget to turn on debug level for the test std.testing.log_level = .debug; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const parser = try expression(arena.allocator()); try std.testing.expectEqual(2, try parser.parseString("9-(!5+2)")); }</code> Now, we have enough insights to understand what happened and where it occurred: <code>error: 'expression.test.parse unexpected symbol' failed: [example] (debug): The parsing by the &lt;EXPR&gt; has been started from position 0: [9]-(!5+2) [example] (debug): The parsing by the &lt;EXPR&gt; has been started from position 3: …[!]5+2) [example] (debug): The parsing is failed at position 3: …[!]5+2) [example] (debug): End parsing by the &lt;EXPR&gt;. Cut 3 items during the parsing process. [parcom] (warn): Imposible to reset the input from 3 to 2 at position 3: …[!]5+2). [example] (debug): An error error.ResetImposible occured on parsing by &lt;EXPR&gt; at position 3: …[!]5+2) [example] (debug): End parsing by the &lt;EXPR&gt;. Cut 3 items during the parsing process.</code> Documentation <a>https://dokwork.github.io/parcom/index.html</a> Examples <ul> <li><a>The parser of a math expression</a></li> <li><a>The json parser</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/998922?v=4
zsp
dbushell/zsp
2025-03-03T13:05:17Z
⚡ ZSP is my personal ZSH prompt written in Zig
main
0
24
0
24
https://api.github.com/repos/dbushell/zsp/tags
MIT
[ "zig", "ziglang", "zsh" ]
52
false
2025-05-15T14:04:28Z
true
true
0.14.0
github
[ { "commit": "4030f154ba0cd29910bec4e809955e730d8f0ed7", "name": "minizign", "tar_url": "https://github.com/jedisct1/zig-minisign/archive/4030f154ba0cd29910bec4e809955e730d8f0ed7.tar.gz", "type": "remote", "url": "https://github.com/jedisct1/zig-minisign" } ]
⚡ ZSP ZSP is my personal ZSH prompt written in <a>Zig</a>. From the blog: <ul> <li><a>"I built a ZSH Prompt with Zig"</a></li> <li><a>"Zig App Release and Updates via Github"</a></li> </ul> This is a hobby project for me to learn Zig software development. Usage Ensure <code>zsp</code> binary is in <code>$PATH</code> and add to <code>.zshrc</code>: <code>zsh source &lt;(zsp --zsh)</code> See <a><code>src/shell/zsh.sh</code></a> for the source. 🚧 Under Construction! I'm working on new features as I use the prompt day-to-day. There is no config unless you edit the source code and recompile! Notes Inspired by <a>Starship</a> and <a>Pure</a>. <a>MIT License</a> | Copyright © 2025 <a>David Bushell</a>
[]
https://avatars.githubusercontent.com/u/201527030?v=4
MLX.zig
jaco-bro/MLX.zig
2025-03-14T14:47:09Z
MLX.zig: Phi-4, Llama 3.2, and Whisper in Zig
main
1
19
2
19
https://api.github.com/repos/jaco-bro/MLX.zig/tags
Apache-2.0
[ "llama", "llm", "mlx", "pcre2", "regex", "tiktoken", "zig", "zig-package" ]
5,431
false
2025-05-19T00:39:17Z
true
true
unknown
github
[ { "commit": "refs", "name": "pcre2", "tar_url": "https://github.com/PCRE2Project/pcre2/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/PCRE2Project/pcre2" } ]
MLX.zig A <a>Zig</a> binding for <a>MLX</a>, Apple's array framework for machine learning on Apple Silicon. Prerequisites <ul> <li>Apple Silicon Mac</li> <li>Zig v0.13.0</li> <li>CMake</li> </ul> Getting Started <code>fish git clone https://github.com/jaco-bro/MLX.zig.git cd MLX.zig zig build</code> This creates executables in <code>zig-out/bin/</code>: - <code>llm</code> - Unified interface for LLM models (Llama-3.2, Phi-4, Qwen-2.5, ...) - <code>whisper</code> - Speech-to-text using Whisper-Turbo-Large-v3 Whisper Speech-to-Text ```fish zig build run-whisper [-- audio_file.mp3] or zig-out/bin/whisper audio_file.mp3 ``` LLM Interface ```fish zig build run-llm [-- options] or zig-out/bin/llm [options] [input] ``` Options <code>--config=CONFIG Config: llama, phi, qwen, olympic (default: qwen) --format=FORMAT Custom chat format template (defaults based on config) --model-type=TYPE Model type: llama, phi, qwen, ... (defaults based on config) --model-name=NAME Model name (defaults based on config) --max=N Maximum tokens to generate (default: 30) --help Show this help</code> Examples <code>fish zig build -Dconfig=phi -Dformat={s} zig build run-llm -Dmax=100 -- "Write a python function to check if a number is prime" zig-out/bin/llm --config=qwen --format={s} "Write a python function to check if a number is prime"</code> The library supports several model configurations including QwQ, R1-Distill-Qwen, Qwen-2.5-Coder, Llama-3.2, and Phi-4. Acknowledgements Inspired by Erik Kaunismäki's <a>zig-build-mlx</a>. License <a>Apache License 2.0</a>
[]
https://avatars.githubusercontent.com/u/280505?v=4
passcay
uzyn/passcay
2025-05-03T08:26:13Z
🦎🔑 Secure & fast Passkey (WebAuthn) library for Zig
main
0
19
0
19
https://api.github.com/repos/uzyn/passcay/tags
MIT
[ "authentication", "passkey", "relying-party", "security", "webauthn", "zig", "zig-package", "ziglang" ]
144
false
2025-05-15T22:15:52Z
true
true
0.14.0
github
[ { "commit": "refs", "name": "zbor", "tar_url": "https://github.com/r4gus/zbor/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/r4gus/zbor" } ]
Passcay <a></a> <strong>Minimal</strong>, <strong>fast</strong> and <strong>secure</strong> Passkey (WebAuthn) relying party (RP) library for Zig. Supports both Zig stable 0.14+ and nightly (0.15+). Features <ul> <li>Passkey WebAuthn registration</li> <li>Passkey WebAuthn authentication/verification (login)</li> <li>Attestation-less passkey usage (privacy-preserving, does not affect security)</li> <li>Cryptographic signature verification. Supports both ES256 &amp; RS256, covering 100% of all Passkey authenticators today.</li> <li>Secure challenge generation</li> </ul> Dependencies Dynamically linked to operating system's OpenSSL for crypto verification. Works on Linux and macOS. Not on Windows due to OpenSSL dependency. Installation Add <code>passcay</code> to your <code>build.zig.zon</code> dependencies: <code>zig .dependencies = .{ .passcay = .{ .url = "https://github.com/uzyn/passcay/archive/main.tar.gz", // Optionally pin to a specific commit hash }, },</code> And update your <code>build.zig</code> to load <code>passcay</code>: <code>zig const passcay = b.dependency("passcay", .{ .optimize = optimize, .target = target, }); exe.root_module.addImport("passcay", passcay.module("passcay"));</code> Build &amp; Test <code>sh zig build zig build test --summary all</code> Usage Registration ```zig const passcay = @import("passcay"); const input = passcay.register.RegVerifyInput{ .attestation_object = attestation_object, .client_data_json = client_data_json, }; const expectations = passcay.register.RegVerifyExpectations{ .challenge = challenge, .origin = "https://example.com", .rp_id = "example.com", .require_user_verification = true, }; const reg = try passcay.register.verify(allocator, input, expectations); // Save reg.credential_id, reg.public_key, and reg.sign_count // to database for authentication ``` Store the following in database for authentication: - <code>reg.credential_id</code> - <code>reg.public_key</code> - <code>reg.sign_count</code> (usually starts at 0) Authentication ```zig const challenge = try passcay.challenge.generate(allocator); // Pass challenge to client-side for authentication const input = passcay.auth.AuthVerifyInput{ .authenticator_data = authenticator_data, .client_data_json = client_data_json, .signature = signature, }; const expectations = passcay.auth.AuthVerifyExpectations{ .public_key = user_public_key, // Retrieve public_key from database, given credential_id from navigator.credentials.get .challenge = challenge, .origin = "https://example.com", .rp_id = "example.com", .require_user_verification = true, .enable_sign_count_check = true, .known_sign_count = stored_sign_count, }; const auth = try passcay.auth.verify(allocator, input, expectations); ``` Update the stored sign count with <code>auth.recommended_sign_count</code>: Client-Side (JavaScript) ```javascript // Registration const regOptions = { challenge: base64UrlDecode(challenge), rp: { name: "Example", id: "example.com", // Must match your domain without protocol/port }, user: { name: username }, pubKeyCredParams: [ { type: "public-key", alg: -7 }, // ES256 (Most widely supported) { type: "public-key", alg: -257 }, // RS256 ], authenticatorSelection: { authenticatorAttachment: "platform", userVerification: "required", // or "preferred" }, attestation: "none", // Fast &amp; privacy-preserving auth without security compromise }; const credential = await navigator.credentials.create({ publicKey: regOptions }); console.log('Credential details:', credential); // Pass credential to server for verification: passcay.register.verify // Authentication const authOptions = { challenge: base64UrlDecode(challenge), rpId: 'example.com', userVerification: 'preferred', }; const assertion = await navigator.credentials.get({ publicKey: authOptions }); console.log('Assertion details:', assertion); // Retrieve public_key from assertion_id that's returned // Pass assertion to server for verification: passcay.auth.verify ``` JavaScript utils for base64url &lt;-&gt; ArrayBuffer ```javascript // Convert base64url &lt;-&gt; ArrayBuffer function base64UrlToBuffer(b64url) { const pad = '='.repeat((4 - (b64url.length % 4)) % 4); const b64 = (b64url + pad).replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(b64); const arr = new Uint8Array(bin.length); for (let i = 0; i &lt; bin.length; i++) arr[i] = bin.charCodeAt(i); return arr.buffer; } function bufferToBase64Url(buf) { const bytes = new Uint8Array(buf); let bin = ''; for (const b of bytes) bin += String.fromCharCode(b); return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } ``` Docs Reference implementations for integrating Passcay into your application: <ul> <li><code>docs/register.md</code> - Registration flow with challenge generation</li> <li><code>docs/login.md</code> - Authentication flow with verification</li> </ul> See also For passkey authenticator implementations and library for Zig, check out <a>Zig-Sec/keylib</a>. ## Spec references <ul> <li><a>W3C WebAuthn</a></li> <li><a>FIDO2 Client to Authenticator Protocol (CTAP)</a></li> </ul> License This project is licensed under the MIT License. See the <a>LICENSE</a> file for details. Copyright (c) 2025 <a>U-Zyn Chua</a>.
[]
https://avatars.githubusercontent.com/u/81317803?v=4
mini-parser
Operachi061/mini-parser
2025-04-07T12:06:37Z
A very-minimal command-line parser
main
0
18
1
18
https://api.github.com/repos/Operachi061/mini-parser/tags
BSD-3-Clause
[ "argument-parsing", "command-line", "command-line-parser", "minimal", "zig", "zig-package", "ziglang" ]
4
false
2025-04-17T11:03:40Z
true
true
0.15.0-dev.208+8acedfd5b
github
[]
mini-parser mini-parser is a very-minimal parser for <a>Zig</a> language. Example ```zig const std = @import("std"); const mini_parser = @import("mini_parser"); const debug = std.debug; const posix = std.posix; const usage = \Usage: example \ \Options: \ --help -h Display help list. \ --text -t Print the text. \ --bool -b Enable the boolean. \ ; pub fn main() !void { const argv = std.os.argv[0..]; <code>var i: usize = 0; while (argv.len &gt; i) : (i += 1) { const parser = try mini_parser.init(argv[i], &amp;.{ .{ .name = "help", .short_name = 'h', .type = .boolean }, // 1 .{ .name = "text", .short_name = 't', .type = .argument }, // 2 .{ .name = "bool", .short_name = 'b', .type = .boolean }, // 3 }); switch (parser.argument) { 0 =&gt; { debug.print("no argument was given.\n", .{}); posix.exit(0); }, 1 =&gt; { // 1 debug.print("{s}\n", .{usage}); posix.exit(0); }, 2 =&gt; debug.print("Text: {s}\n", .{parser.value}), // 2 3 =&gt; debug.print("Enabled boolean!\n", .{}), // 3 4 =&gt; { debug.print("argument '{s}' does not exist.\n", .{argv[i]}); posix.exit(0); }, else =&gt; {}, } } </code> } ``` Installation Fetch mini-parser package to <code>build.zig.zon</code>: <code>sh zig fetch --save git+https://github.com/Operachi061/mini-parser</code> Then add following to <code>build.zig</code>: <code>zig const mini_parser = b.dependency("mini_parser", .{}); exe.root_module.addImport("mini_parser", mini_parser.module("mini_parser"));</code> After building, test it via: <code>sh ./example --bool --text foo -h</code> License This project is based on the BSD 3-Clause license.
[]
https://avatars.githubusercontent.com/u/8091245?v=4
mzg
uyha/mzg
2025-03-20T19:22:09Z
A MessagePack library for Zig
main
0
14
0
14
https://api.github.com/repos/uyha/mzg/tags
MIT
[ "message-pack", "msgpack", "zig", "zig-package" ]
144
false
2025-05-09T18:18:51Z
true
true
0.14.0
github
[]
mzg <ul> <li><a>mzg</a></li> <li><a>How to use</a></li> <li><a>API</a><ul> <li><a>High level functions</a></li> <li><a>Building block functions</a></li> </ul> </li> <li><a>Examples</a><ul> <li><a>Simple back and forth</a></li> <li><a>Default packing and unpacking for custom types</a></li> <li><a>Adapters for common container types</a></li> </ul> </li> <li><a>Mapping</a><ul> <li><a>Default packing from Zig types to MessagePack</a></li> <li><a>Default unpack from MessagePack to Zig types</a></li> <li><a>Customization</a></li> <li><a>Packing</a></li> <li><a>Unpacking</a></li> </ul> </li> </ul> <code>mzg</code> is a MessagePack library for Zig with no allocations, and the API favors the streaming usage. How to use <ol> <li>Run the following command to add this project as a dependency</li> </ol> <code>sh zig fetch --save git+https://github.com/uyha/mzg.git#v0.1.3</code> <ol> <li>In your <code>build.zig</code>, add the following</li> </ol> <code>zig const mzg = b.dependency("mzg", .{ .target = target, .optimize = optimize, }); // Replace `exe` with your actual library or executable exe.root_module.addImport("mzg", mzg.module("mzg"));</code> API High level functions Packing functions <ol> <li><code>pack</code> is for packing Zig values using a <code>writer</code></li> <li><code>packAdapted</code> is like <code>pack</code> but it accepts a map that defines how certain types should be packed.</li> <li><code>packWithOptions</code> is like <code>pack</code> but it accepts a <code>mzg.PackOptions</code> parameter to control the packing behavior.</li> <li><code>packAdaptedWithOptions</code> is like <code>packWithOptions</code> but it accepts a map that defines how certain types should be packed.</li> </ol> Unpacking functions <ol> <li><code>unpack</code> is for unpacking a MessagePack message into a Zig object and it does not allocate memory.</li> <li><code>unpackAdapted</code> is like <code>unpack</code> but it accepts a map that defines how certain types should be unpacked.</li> <li><code>unpackAllocate</code> is like <code>unpack</code> but it accepts an <code>Allocator</code> that allows the unpacking process to allocate memory.</li> <li><code>unpackAdaptedAllocate</code> is like <code>unpackAllocate</code> but it accepts a map that defines how a particular type should be packed.</li> </ol> Adapters <ol> <li><code>adapter.packArray</code> and <code>adapter.unpackArray</code> pack and unpack structs like <code>std.ArrayListUnmanaged</code></li> <li><code>adapter.packMap</code> and <code>adapter.unpackMap</code> pack and unpack structs like <code>std.ArrayHashMapUnmanaged</code>.</li> <li><code>adapter.packStream</code> and <code>adapter.unpackStream</code> pack and unpack structs in a stream like manner (length is not specified in the beginning).</li> </ol> Building block functions There are a set of <code>pack*</code> and <code>unpack*</code> functions that translate between a precise set of Zig types and MessagePack. These functions can be used when implementing custom packing and unpacking. Examples All examples live in <a>examples</a> directory. Simple back and forth Converting a byte slice to MessagePack and back ```zig pub fn main() !void { const allocator = std.heap.page_allocator; var buffer: std.ArrayListUnmanaged(u8) = .empty; defer buffer.deinit(allocator); <code>try mzg.pack( "a string with some characters for demonstration purpose", buffer.writer(allocator), ); var string: []const u8 = undefined; const size = try mzg.unpack(buffer.items, &amp;string); std.debug.print("Consumed {} bytes\n", .{size}); std.debug.print("string: {s}\n", .{string}); </code> } const std = @import("std"); const mzg = @import("mzg"); ``` Default packing and unpacking for custom types Certain types can be packed and unpacked by default (refer to <a>Mapping</a> for more details) ```zig pub fn main() !void { const allocator = std.heap.page_allocator; var buffer: std.ArrayListUnmanaged(u8) = .empty; defer buffer.deinit(allocator); <code>try mzg.pack( Targets{ .position = .init(2000), .velocity = .init(10) }, buffer.writer(allocator), ); var targets: Targets = undefined; const size = try mzg.unpack(buffer.items, &amp;targets); std.debug.print("Consumed {} bytes\n", .{size}); std.debug.print("Targets: {}\n", .{targets}); </code> } const Position = enum(i32) { <em>, pub fn init(raw: std.meta.Tag(@This())) @This() { return @enumFromInt(raw); } }; const Velocity = enum(i32) { </em>, pub fn init(raw: std.meta.Tag(@This())) @This() { return @enumFromInt(raw); } }; const Targets = struct { position: Position, velocity: Velocity, }; const std = @import("std"); const mzg = @import("mzg"); const adapter = mzg.adapter; ``` Adapters for common container types Many container types in the <code>std</code> library cannot be packed or unpacked by default, but the adapter functions make it easy to work with these types. ```zig pub fn main() !void { const allocator = std.heap.page_allocator; var buffer: std.ArrayListUnmanaged(u8) = .empty; defer buffer.deinit(allocator); <code>var in: std.ArrayListUnmanaged(u32) = .empty; defer in.deinit(allocator); try in.append(allocator, 42); try in.append(allocator, 75); try mzg.pack(adapter.packArray(&amp;in), buffer.writer(allocator)); var out: std.ArrayListUnmanaged(u32) = .empty; defer out.deinit(allocator); const size = try mzg.unpack( buffer.items, adapter.unpackArray(&amp;out, allocator), ); std.debug.print("Consumed {} bytes\n", .{size}); std.debug.print("out: {any}\n", .{out.items}); </code> } const std = @import("std"); const mzg = @import("mzg"); const adapter = mzg.adapter; ``` Mapping Default packing from Zig types to MessagePack | Zig Type | MessagePack | |------------------------------------------|-----------------------------------------------------------| | <code>void</code>, <code>null</code> | <code>nil</code> | | <code>bool</code> | <code>bool</code> | | integers (&lt;=64 bits) | <code>int</code> | | floats (&lt;=64 bits) | <code>float</code> | | <code>?T</code> | <code>nil</code> if value is <code>null</code>, pack according to <code>T</code> otherwise | | enums | <code>int</code> | | enum literals | <code>str</code> | | tagged unions | <code>array</code> of 2 elements: <code>int</code> and the value of the union | | packed structs | <code>int</code> | | structs and tuples | <code>array</code> of fields in the order they are declared | | <code>[N]</code>, <code>[]</code>, <code>[:X]</code>, and <code>@Vec</code> of <code>u8</code> | <code>str</code> | | <code>[N]</code>, <code>[]</code>, <code>[:X]</code>, and <code>@Vec</code> of <code>T</code> | <code>array</code> of <code>T</code> | | <code>Ext</code> | <code>ext</code> | | <code>Timestamp</code> | <code>Timestamp</code> | | <code>*T</code> | <code>T</code> | Default unpack from MessagePack to Zig types | MessagePack | Compatible Zig Type | |-------------|--------------------------------------| | <code>nil</code> | <code>void</code>, <code>?T</code> | | <code>bool</code> | <code>bool</code> | | <code>int</code> | integers, enums | | <code>float</code> | floats | | <code>str</code> | <code>[]const u8</code> | | <code>bin</code> | <code>[]const u8</code> | | <code>array</code> | The length can be read into integers | | <code>map</code> | The length can be read into integers | | <code>ext</code> | <code>Ext</code> | | <code>Timestamp</code> | <code>Timestamp</code> | Customization Packing When an enum/union/struct has an <code>mzgPack</code> function that returns <code>mzg.PackError(@TypeOf(writer))!void</code> can be called with <code>zig // Value cares about the options passed by the caller value.mzgPack(options, map, writer);</code> With the arguments being <ul> <li><code>value</code> is the enum/union/struct being packed.</li> <li><code>options</code> is <code>mzg.PackOptions</code>.</li> <li><code>map</code> is a tuple of 2 element tuples whose 1st element being a type and 2nd element being a packing adapter function.</li> <li><code>writer</code> is <code>anytype</code> that can be called with <code>writer.writeAll(&amp;[_]u8{});</code>.</li> </ul> The function will be called when the <code>mzg.pack</code> function is used. Unpacking When an enum/union/struct has <ul> <li><code>mzgUnpack</code> function that returns <code>UnpackError!usize</code> and can be called with</li> </ul> <code>zig out.mzgUnpack(map, buffer);</code> <ul> <li><code>mzgUnpackAllocate</code> function that returns <code>UnpackError!usize</code> and can be called with</li> </ul> <code>zig out.mzgUnpackAllocate(allocator, map, buffer);</code> With the arguments being <ul> <li><code>out</code> is the enum/union/struct being unpacked.</li> <li><code>allocator</code> is an <code>std.mem.Allocator</code>.</li> <li><code>map</code> is a tuple of 2 element tuples whose 1st element being a type and 2nd element being an unpacking adapter function.</li> <li><code>buffer</code> is <code>[]const u8</code>.</li> </ul> The <code>mzgUnpack</code> function is called when either <code>mzg.unpack</code> or <code>mzg.unpackAdapted</code> is used. The <code>mzgUnpackAllocate</code> function is called when either <code>mzg.unpackAllocate</code> or <code>mzg.unpackAdaptedAllocate</code> is used.
[]
https://avatars.githubusercontent.com/u/49008623?v=4
zargs
kioz-wang/zargs
2025-03-04T03:10:36Z
Another Comptime-argparse for Zig! Let's start to build your command line!
main
4
14
0
14
https://api.github.com/repos/kioz-wang/zargs/tags
MIT
[ "argument-parser", "clap-rs", "cli", "command-line", "positional-arguments", "subcommands", "zig", "zig-package", "ziglang" ]
7,569
false
2025-05-11T10:46:32Z
true
true
0.14.0
github
[]
zargs <blockquote> other language: <a>中文简体</a> </blockquote> Another Comptime-argparse for Zig! Let's start to build your command line! ```zig const std = @import("std"); const zargs = @import("zargs"); const Command = zargs.Command; const Arg = zargs.Arg; const Ranges = zargs.Ranges; pub fn main() !void { // Like Py3 argparse, https://docs.python.org/3.13/library/argparse.html const remove = Command.new("remove") .alias("rm").alias("uninstall").alias("del") .opt("verbose", u32, .{ .short = 'v' }) .optArg("count", u32, .{ .short = 'c', .argName = "CNT", .default = 9 }) .posArg("name", []const u8, .{}); <code>// Like Rust clap, https://docs.rs/clap/latest/clap/ const cmd = Command.new("demo").requireSub("action") .about("This is a demo intended to be showcased in the README.") .author("KiozWang") .homepage("https://github.com/kioz-wang/zargs") .arg(Arg.opt("verbose", u32).short('v').help("help of verbose")) .arg(Arg.optArg("logfile", ?[]const u8).long("log").help("Store log into a file")) .sub(Command.new("install") .arg(Arg.optArg("count", u32).default(10) .short('c').short('n').short('t') .long("count").long("cnt") .ranges(Ranges(u32).new().u(5, 7).u(13, null)).choices(&amp;.{ 10, 11 })) .arg(Arg.posArg("name", []const u8).raw_choices(&amp;.{ "gcc", "clang" })) .arg(Arg.optArg("output", []const u8).short('o').long("out")) .arg(Arg.optArg("vector", ?@Vector(3, i32)).long("vec"))) .sub(remove); var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init; const allocator = gpa.allocator(); const args = cmd.parse(allocator) catch |e| zargs.exitf(e, 1, "\n{s}\n", .{cmd.usage()}); defer cmd.destroy(&amp;args, allocator); if (args.logfile) |logfile| std.debug.print("Store log into {s}\n", .{logfile}); switch (args.action) { .install =&gt; |a| { std.debug.print("Installing {s}\n", .{a.name}); }, .remove =&gt; |a| { std.debug.print("Removing {s}\n", .{a.name}); std.debug.print("{any}\n", .{a}); }, } std.debug.print("Success to do {s}\n", .{@tagName(args.action)}); </code> } ``` Background As a system level programming language, there should be an elegant solution for parsing command line arguments. <code>zargs</code> draws inspiration from the API styles of <a>Py3 argparse</a> and <a>Rust clap</a>. It provides all parameter information during editing, reflects the parameter structure and parser at compile time, along with everything else needed, and supports dynamic memory allocation for parameters at runtime. Installation fetch Get the latest version: <code>bash zig fetch --save git+https://github.com/kioz-wang/zargs</code> To fetch a specific version (e.g., <code>v0.14.3</code>): <code>bash zig fetch --save https://github.com/kioz-wang/zargs/archive/refs/tags/v0.14.3.tar.gz</code> Version Notes <blockquote> See https://github.com/kioz-wang/zargs/releases </blockquote> The version number follows the format <code>vx.y.z</code>: - <strong>x</strong>: Currently fixed at 0. It will increment to 1 when the project stabilizes. Afterward, it will increment by 1 for any breaking changes. - <strong>y</strong>: Represents the supported Zig version. For example, <code>vx.14.z</code> supports <a>Zig 0.14.0</a>. - <strong>z</strong>: Iteration version, where even numbers indicate releases with new features or significant changes (see <a>milestones</a>), and odd numbers indicate releases with fixes or minor changes. import Use <code>addImport</code> in your <code>build.zig</code> (e.g.): ```zig const exe = b.addExecutable(.{ .name = "your_app", .root_source_file = b.path("src/main.zig"), .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{}), }); exe.root_module.addImport("zargs", b.dependency("zargs", .{}).module("zargs")); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&amp;run_cmd.step); ``` After importing the <code>zargs</code>, you will obtain the iterator (<code>TokenIter</code>), command builder (<code>Command</code>), and universal parsing function (<code>parseAny</code>): <code>zig const zargs = @import("zargs");</code> <blockquote> For more information and usage details about these three powerful tools, please refer to the <a>documentation</a>. </blockquote> Features Options, Arguments, Subcommands Terminology <ul> <li>Option (<code>opt</code>)<ul> <li>Single Option (<code>singleOpt</code>)<ul> <li>Boolean Option (<code>boolOpt</code>), <code>T == bool</code></li> <li>Accumulative Option (<code>repeatOpt</code>), <code>@typeInfo(T) == .int</code></li> </ul> </li> <li>Option with Argument (<code>argOpt</code>)<ul> <li>Option with Single Argument (<code>singleArgOpt</code>), T, <code>?T</code></li> <li>Option with Fixed Number of Arguments (<code>arrayArgOpt</code>), <code>[n]T</code></li> <li>Option with Variable Number of Arguments (<code>multiArgOpt</code>), <code>[]T</code></li> </ul> </li> </ul> </li> <li>Argument (<code>arg</code>)<ul> <li>Option Argument (<code>optArg</code>) (equivalent to Option with Argument)</li> <li>Positional Argument (<code>posArg</code>)<ul> <li>Single Positional Argument (<code>singlePosArg</code>), T, <code>?T</code></li> <li>Fixed Number of Positional Arguments (<code>arrayPosArg</code>), <code>[n]T</code></li> </ul> </li> </ul> </li> <li>Subcommand (<code>subCmd</code>)</li> </ul> Matching and Parsing Matching and parsing are driven by an iterator. For options, the option is always matched first, and if it takes an argument, the argument is then parsed. For positional arguments, parsing is attempted directly. For arguments, T must be the smallest parsable unit: <code>[]const u8</code> -&gt; T <ul> <li><code>.int</code></li> <li><code>.float</code></li> <li><code>.bool</code><ul> <li><code>true</code>: 'y', 't', "yes", "true" (case insensitive)</li> <li><code>false</code>: 'n', 'f', "no", "false" (case insensitive)</li> </ul> </li> <li><code>.enum</code>: Uses <code>std.meta.stringToEnum</code> by default, but <code>parse</code> method takes priority</li> <li><code>.struct</code>: Struct with <code>parse</code> method</li> <li><code>.vector</code><ul> <li>Only supports base types of <code>.int</code>, <code>.float</code>, and <code>.bool</code></li> <li><code>@Vector{1,1}</code>: <code>[\(\[\{][ ]*1[ ]*[;:,][ ]*1[ ]*[\)\]\}]</code></li> <li><code>@Vector{true,false}</code>: <code>[\(\[\{][ ]*y[ ]*[;:,][ ]*no[ ]*[\)\]\}]</code></li> </ul> </li> </ul> If type T has no associated default parser or <code>parse</code> method, you can specify a custom parser (<code>.parseFn</code>) for the parameter. Obviously, single-option parameters cannot have parsers as it would be meaningless. Default Values and Optionality Options and arguments can be configured with default values (<code>.default</code>). Once configured, the option or argument becomes optional. <ul> <li>Even if not explicitly configured, single options always have default values: boolean options default to <code>false</code>, and accumulative options default to <code>0</code>.</li> <li>Options or arguments with an optional type <code>?T</code> cannot be explicitly configured: they are forced to default to <code>null</code>.</li> </ul> <blockquote> Single options, options with a single argument of optional type, or single positional arguments of optional type are always optional. </blockquote> Value Ranges Value ranges (<code>.ranges</code>, <code>.choices</code>) can be configured for arguments, which are validated after parsing. <blockquote> Default values are not validated (intentional feature? 😄) </blockquote> If constructing value ranges is cumbersome, <code>.raw_choices</code> can be used to filter values before parsing. Ranges Ranges When <code>T</code> implements compare, value <code>.ranges</code> can be configured for the argument. Choices Choices When <code>T</code> implements equal, value <code>.choices</code> can be configured for the argument. Callbacks A callback (<code>.callBackFn</code>) can be configured, which will be executed after matching and parsing. Subcommands A command cannot have both positional arguments and subcommands simultaneously. Representation For the parser, except for accumulative options and options with a variable number of arguments, no option can appear more than once. Various representations are primarily supported by the iterator. Options are further divided into short options and long options: - <strong>Short Option</strong>: <code>-v</code> - <strong>Long Option</strong>: <code>--verbose</code> Options with a single argument can use a connector to link the option and the argument: - <strong>Short Option</strong>: <code>-o=hello</code>, <code>-o hello</code> - <strong>Long Option</strong>: <code>--output=hello</code>, <code>--output hello</code> <blockquote> Dropping the connector or whitespace for short options is not allowed, as it results in poor readability! </blockquote> For options with a fixed number of arguments, connectors cannot be used, and all arguments must be provided at once. For example, with a long option: <code>bash --files f0 f1 f2 # [3]const T</code> Options with a variable number of arguments are similar to options with a single argument but can appear multiple times, e.g.: <code>bash --file f0 -v --file=f1 --greet # []const T</code> Multiple short options can share a prefix, but if an option takes an argument, it must be placed last, e.g.: <code>bash -Rns -Rnso hello -Rnso=hello</code> Once a positional argument appears, the parser informs the iterator to only return positional arguments, even if the arguments might have an option prefix, e.g.: <code>bash -o hello a b -v # -o is an option with a single argument, so a, b, -v are all positional arguments</code> An option terminator can be used to inform the iterator to only return positional arguments, e.g.: <code>bash --output hello -- a b -v</code> Double quotes can be used to avoid iterator ambiguity, e.g., to pass a negative number <code>-1</code>, double quotes must be used: <code>bash --num \"-1\"</code> <blockquote> Since the shell removes double quotes, escape characters are also required! If a connector is used, escaping is unnecessary: <code>--num="-1"</code>. </blockquote> Compile-Time Command Construction As shown in the example at the beginning of the article, command construction can be completed in a single line of code through chaining. CallBackFn for Command <code>zig const install = Command.new("install"); const _demo = Command.new("demo").requireSub("action") .sub(install.callBack(struct { fn f(_: *install.Result()) void { std.debug.print("CallBack of {s}\n", .{install.name}); } }.f)); const demo = _demo.callBack(struct { fn f(_: *_demo.Result()) void { std.debug.print("CallBack of {s}\n", .{_demo.name}); } }.f);</code> Compile-Time Parser Generation <code>zig const args = try cmd.parse(allocator); defer cmd.destroy(&amp;args, allocator);</code> Simply call <code>parse</code> to generate the parser and argument structure. This method internally creates a system iterator, which is destroyed after use. Additionally, <code>parseFrom</code> supports passing a custom iterator and optionally avoids using a memory allocator. If no allocator is used, there is no need to defer destroy. Retrieving Remaining Command-Line Arguments When the parser has completed its task, if you still need to handle the remaining arguments manually, you can call the iterator's <code>nextAllBase</code> method. If further parsing of the arguments is required, you can use the <code>parseAny</code> function. Versatile iterators Flexible for real and test scenarios <ul> <li>System iterator (<code>init</code>): get real command line arguments.</li> <li>General iterator (<code>initGeneral</code>): splits command line arguments from a one-line string.</li> <li>Line iterator (<code>initLine</code>): same as regular iterator, but you can specify delimiters.</li> <li>List iterator (<code>initList</code>): iterates over a list of strings.</li> </ul> Short option prefixes (<code>-</code>), long option prefixes (<code>--</code>), connectors (<code>=</code>), option terminators (<code>--</code>) can be customized for iterators (see <a>presentation</a> for usage scenarios). Compile-Time Usage and Help Generation <code>zig _ = cmd.usage(); _ = cmd.help();</code> APIs See https://kioz-wang.github.io/zargs/#doc Examples builtin <blockquote> Look at <a>here</a> </blockquote> To build all examples: <code>bash zig build examples</code> To list all examples (all step prefixed <code>ex-</code> are examples): <code>bash zig build -l</code> To execute an example: <code>bash zig build ex-01.add -- -h</code> more <blockquote> Welcome to submit PRs to link your project that use <code>zargs</code>! </blockquote> More real-world examples are coming! <ul> <li><a>filepacker</a></li> <li><a>zterm</a></li> </ul> License <a>MIT</a> © Kioz Wang
[ "https://github.com/kioz-wang/zterm" ]
https://avatars.githubusercontent.com/u/43397328?v=4
openai-proxz
lukeharwood11/openai-proxz
2025-02-14T03:37:54Z
A zig OpenAI API client library
main
5
13
2
13
https://api.github.com/repos/lukeharwood11/openai-proxz/tags
MIT
[ "openai", "zig", "zig-package" ]
111
false
2025-04-30T07:02:25Z
true
true
0.14.0
github
[]
ProxZ An OpenAI API library for the Zig programming language! ⭐️ Features ⭐️ <ul> <li>An easy to use interface, similar to that of <code>openai-python</code></li> <li>Built-in retry logic</li> <li>Environment variable config support for API keys, org. IDs, project IDs, and base urls</li> <li>Response streaming support</li> <li>Integration with the most popular OpenAI endpoints with a generic <code>request</code>/<code>requestStream</code> method for missing endpoints</li> </ul> Installation To install the latest version of <code>proxz</code>, run <code>bash zig fetch --save "git+https://github.com/lukeharwood11/openai-proxz"</code> To install a specific version, run <code>bash zig fetch --save "https://github.com/lukeharwood11/openai-proxz/archive/refs/tags/&lt;version&gt;.tar.gz"</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> To install the latest version compatible with Zig <code>v0.13.0</code>, use <code>bash zig fetch --save "https://github.com/lukeharwood11/openai-proxz/archive/refs/tags/v0.1.0.tar.gz"</code> </blockquote> And add the following to your <code>build.zig</code> ```zig const proxz = b.dependency("proxz", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("proxz", proxz.module("proxz")); ``` Usage |✨ Documentation ✨|| |--|--| |📙 ProxZ Docs |<a>https://proxz.mle.academy</a> | |📗 OpenAI API Docs|<a>https://platform.openai.com/docs/api-reference</a>| Client Configuration <code>zig const proxz = @import("proxz"); const OpenAI = proxz.OpenAI;</code> <code>zig // make sure you have an OPENAI_API_KEY environment variable set, // or pass in a .api_key field to explicitly set! var openai = try OpenAI.init(allocator, .{}); defer openai.deinit();</code> Chat Completions Regular ```zig const ChatMessage = proxz.ChatMessage; var response = try openai.chat.completions.create(.{ .model = "gpt-4o", .messages = &amp;[_]ChatMessage{ .{ .role = "user", .content = "Hello, world!", }, }, }); // This will free all the memory allocated for the response defer response.deinit(); std.log.debug("{s}", .{response.choices[0].message.content}); ``` Streamed Response ```zig var stream = try openai.chat.completions.createStream(.{ .model = "gpt-4o-mini", .messages = &amp;[_]ChatMessage{ .{ .role = "user", .content = "Write me a poem about lizards. Make it a paragraph or two.", }, }, }); defer stream.deinit(); std.debug.print("\n", .{}); while (try stream.next()) |val| { std.debug.print("{s}", .{val.choices[0].delta.content}); } std.debug.print("\n", .{}); ``` Embeddings <code>zig const inputs = [_][]const u8{ "Hello", "Foo", "Bar" }; const response = try openai.embeddings.create(.{ .model = "text-embedding-3-small", .input = &amp;inputs, }); // Don't forget to free resources! defer response.deinit(); std.log.debug("Model: {s}\nNumber of Embeddings: {d}\nDimensions of Embeddings: {d}", .{ response.model, response.data.len, response.data[0].embedding.len, });</code> Models Get model details <code>zig var response = try openai.models.retrieve("gpt-4o"); defer response.deinit(); std.log.debug("Model is owned by '{s}'", .{response.owned_by});</code> List all models <code>zig var response = try openai.models.list(); defer response.deinit(); std.log.debug("The first model you have available is '{s}'", .{response.data[0].id})</code> Configuring Logging By default all logs are enabled for your entire application. To configure your application, and set the log level for <code>proxz</code>, include the following in your <code>main.zig</code>. <code>zig pub const std_options = std.Options{ .log_level = .debug, // this sets your app level log config .log_scope_levels = &amp;[_]std.log.ScopeLevel{ .{ .scope = .proxz, .level = .info, // set to .debug, .warn, .info, or .err }, }, };</code> All logs in <code>proxz</code> use the scope <code>.proxz</code>, so if you don't want to see debug/info logs of the requests being sent, set <code>.level = .err</code>. This will only display when an error occurs that <code>proxz</code> can't recover from. Contributions Contributions are welcome and encouraged! Submit an issue for any bugs/feature requests and open a PR if you tackled one of them! Building Docs <code>bash zig build docs</code>
[]
https://avatars.githubusercontent.com/u/28509323?v=4
tase
Gnyblast/tase
2025-02-24T20:48:36Z
Multi-agent centralized logs control and management tool written in zig.
master
0
12
0
12
https://api.github.com/repos/Gnyblast/tase/tags
MIT
[ "controller", "delete", "devops", "devops-tools", "log", "logging", "management", "multiagent", "rotate", "sysadmin", "sysadmin-tool", "truncate", "zig", "ziglang" ]
3,106
false
2025-05-20T04:09:21Z
true
true
0.14.0
github
[ { "commit": "master", "name": "datetime", "tar_url": "https://github.com/frmdstryr/zig-datetime/archive/master.tar.gz", "type": "remote", "url": "https://github.com/frmdstryr/zig-datetime" }, { "commit": "master", "name": "args", "tar_url": "https://github.com/ikskuh/zig-args/arc...
<a></a> <a></a> <a></a> <a target="_blank"> </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> Tase is on beta version at the moment and missing truncate functionality. <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> Tase is well-tested on limited environments but not battle-tested fully. </blockquote> Tase Table of Contents <ul> <li><a>Tase</a></li> <li><a>Table of Contents</a></li> <li><a>What is Tase?</a></li> <li><a>Features</a></li> <li><a>Installation</a></li> <li><a>CLI Arguments</a></li> <li><a>Configuration Reference</a><ul> <li><a>Configuration File Structure</a></li> <li><a>1. Configs (<code>configs</code>)</a></li> <li><a>2. Action Strategies</a><ul> <li><a>Truncate Strategy</a></li> <li><a>Rotate Strategy</a></li> <li><a>Delete Strategy</a></li> </ul> </li> <li><a>3. Agents Configuration</a></li> <li><a>4. Server Configuration</a></li> </ul> </li> <li><a>Example Configuration</a></li> <li><a>License</a></li> <li><a>Contributing</a></li> <li><a>Roadmap</a></li> <li><a>Author</a></li> </ul> What is Tase? Tase is a lightweight log management system written in Zig. It consists of a daemon running on a master server and lightweight agents deployed across multiple servers. With a single config.yaml, Tase allows centralized control over log file management, including deletion, rotation, and truncation. Features <ol> <li><strong>Master-Agent Architecture</strong>: The master server manages configurations and schedules, while agents execute log management tasks.</li> <li><strong>YAML-Based Configuration</strong>: The master server reads a <code>config.yaml</code> file to determine agent behavior and scheduling.</li> <li><strong>Cron-based Scheduling</strong>: The application uses cron-based scheduling to execute the log management tasks at predefined intervals.</li> <li><strong>Delete Logs</strong>: The application can delete log files that are older than a specified number of days or exceed a certain size.</li> <li><strong>Rotate Logs</strong>: The application can rotate log files, optionally compressing the archived files using the GZip algorithm. It can also delete archived logs older than a specified number of days or size same as delete action.</li> <li><strong>Truncate Logs (Not yet implemented)</strong>: The application can truncate log files that are older than a specified number of days or exceed a certain size.</li> </ol> Installation Tase is written in Zig, and to build and install it, follow these steps: ```sh Clone the repository git clone https://github.com/Gnyblast/tase.git cd tase Build the application zig build Run the master daemon zig-out/bin/tase -m master -c /path/to/config.yml Run the agent daemon on other servers that can communicate with master server zig-out/bin/tase --agent --secret --port 7423 --master-host localhost --master-port 7423 ``` CLI Arguments | Argument | Type | Description | Default | Required | | ---------------- | ------ | ----------------------------------------------------------------- | -------------------- | ----------------------------------- | | <code>--log-dir</code> | string | Directory for tase self logs | <code>/var/log/tase</code> | No | | <code>--log-level</code> | string | Logging level (<code>debug</code>, <code>info</code>, <code>warn</code>, <code>error</code>) | <code>info</code> | No | | <code>--master</code> | bool | For server type master | - | Either --master or --agent required | | <code>--agent</code> | bool | For server type agent | - | Either --master or --agent required | | <code>--config</code> | string | absolute path for configuration file | <code>/etc/tase/app.yaml</code> | No | | <code>--secret</code> | string | Agents only - Secret for master/agent communication (JWT secret) | - | Yes - Only for --agent | | <code>--host</code> | string | Agent Server host address (Only for agents) | <code>127.0.0.1</code> | No | | <code>--port</code> | string | Agent Server port (Only for agents) | <code>7423</code> | No | | <code>--server-type</code> | string | Agent Server type, only <code>tcp</code> atm (Only for agents) | <code>tcp</code> | No | | <code>--master-host</code> | string | Host address of the master for agent to connect (Only for agents) | - | Yes | | <code>--mastger-port</code> | string | Port address of the master for agent to connect (Only for agents) | - | Yes | | <code>--help</code> | bool | Print help menu | - | No | Configuration Reference Configuration File Structure The application uses a YAML configuration file with the following main sections: 1. Configs (<code>configs</code>) Each config defines a log management task with the following properties: | Property | Type | Description | Default | Required | | ------------------ | -------- | ------------------------------------------------------------------------------------------------------ | ------- | -------- | | <code>app_name</code> | string | Name of the application | - | Yes | | <code>logs_dir</code> | string | Directory containing log files | - | Yes | | <code>log_files_regexp</code> | string | Regular expression to match log files. <strong>Always use single quotes <code>'</code> because of Library Limitations</strong> | - | Yes | | <code>cron_expression</code> | string | Cron schedule for the log management task | - | Yes | | <code>run_agent_names</code> | string[] | List of agents to run this task <strong>("local" is a reserved word to run against master server itself)</strong> | - | Yes | | <code>action</code> | object | Log management strategy details | - | Yes | 2. Action Strategies The <code>action</code> object supports three strategies: Truncate Strategy | Property | Type | Description | Default | Required | | -------------------------- | ------ | -------------------------------------------------------------------- | ------- | -------- | | <code>strategy</code> | string | Must be <code>"truncate"</code> | - | Yes | | <code>truncate_settings.from</code> | string | Truncate from top or bottom (<code>"top"</code> or <code>"bottom"</code>) | - | Yes | | <code>truncate_settings.by</code> | string | Truncate by lines or size (<code>"line"</code> or <code>"size"</code>) | - | Yes | | <code>truncate_settings.size</code> | int | Truncate by size, line numbers or size in mb | - | Yes | | <code>truncate_settings.action</code> | string | Keep or Delete matching <code>truncate_settings</code> (<code>"delete"</code> or <code>"keep"</code>) | - | Yes | | <code>if.condition</code> | string | Condition type (<code>"days"</code> or <code>"size" in MB</code>) | - | Yes | | <code>if.operator</code> | string | Comparison operator (<code>"&gt;"</code>, <code>"&lt;"</code>, <code>"="</code>) | - | Yes | | <code>if.operand</code> | number | Threshold value | - | Yes | Rotate Strategy | Property | Type | Description | Default | Required | | ------------------------ | ------ | ------------------------------------------- | ---------------------------- | -------------------------------- | | <code>strategy</code> | string | Must be <code>"rotate"</code> | - | Yes | | <code>rotate_archives_dir</code> | string | Directory for archiving rotated files | same directory with log file | No | | <code>if.condition</code> | string | Condition type (<code>"days"</code> or <code>"size" in MB</code>) | - | Yes | | <code>if.operator</code> | string | Comparison operator (<code>"&gt;"</code>, <code>"&lt;"</code>, <code>"="</code>) | - | Yes | | <code>if.operand</code> | number | Threshold value | - | Yes | | <code>keep_archive.condition</code> | string | Condition type (<code>"days"</code> or <code>"size" in MB</code>) | - | Yes if <code>keep_archive</code> is defined | | <code>keep_archive.operator</code> | string | Comparison operator (<code>"&gt;"</code>, <code>"&lt;"</code>, <code>"="</code>) | - | Yes if <code>keep_archive</code> is defined | | <code>keep_archive.operand</code> | number | Threshold value | - | Yes if <code>keep_archive</code> is defined | | <code>compress</code> | string | Compression algorithm (<code>"gzip"</code>) | - | No | | <code>compression_level</code> | number | Compression level (4-9) | 4 | No | Delete Strategy | Property | Type | Description | Default | Required | | -------------- | ------ | ------------------------------------------- | ------- | -------- | | <code>strategy</code> | string | Must be <code>"delete"</code> | - | Yes | | <code>if.condition</code> | string | Condition type (<code>"days"</code> or <code>"size" in MB</code>) | - | Yes | | <code>if.operator</code> | string | Comparison operator (<code>"&gt;"</code>, <code>"&lt;"</code>, <code>"="</code>) | - | Yes | | <code>if.operand</code> | number | Threshold value | - | Yes | 3. Agents Configuration | Property | Type | Description | Default | Required | | ---------- | ------ | --------------------------------------------------- | ------- | -------- | | <code>name</code> | string | Agent name <strong>("local" is reserved cannot be used)</strong> | - | Yes | | <code>hostname</code> | string | Agent hostname | - | Yes | | <code>port</code> | number | Agent port | - | Yes | | <code>secret</code> | string | Authentication secret | - | Yes | 4. Server Configuration | Property | Type | Description | Default | Required | | ----------- | ------ | ---------------- | ------------- | -------- | | <code>host</code> | string | Server hostname | <code>"127.0.0.1"</code> | No | | <code>port</code> | number | Server port | <code>7423</code> | No | | <code>type</code> | string | Server type | <code>"tcp"</code> | No | | <code>time_zone</code> | string | Server time zone | <code>"UTC"</code> | No | Example Configuration ```yaml server: host: "127.0.0.1" port: 7423 time_zone: "UTC" agents: - name: agent_1 hostname: "192.xxx.xxx.xxx" port: 7423 secret: "your-secret-key" configs: - app_name: "rotate_logs" logs_dir: "/var/log/myapp" log_files_regexp: 'test.log' cron_expression: "0 0 * * *" run_agent_names: - agent_1 action: strategy: rotate if: condition: days operator: "&gt;" operand: 7 compression_type: gzip compression_level: 5 <ul> <li>app_name: "delete_logs" logs_dir: "/var/log/myapp2" log_files_regexp: 'test.log' cron_expression: "30 08 * * 7" run_agent_names:<ul> <li>agent_1</li> <li>local action: strategy: delete if: condition: size operator: "&gt;" operand: 20 ```</li> </ul> </li> </ul> For more example please see: <a>config</a> Contributing Contributions are welcome! Feel free to submit issues and pull requests on <a>GitHub</a>. Please read <a>Contiribution guide</a> Roadmap Version 1.0.0 <ul> <li>Write unit and coverate tests for <code>log_service.zig</code></li> <li>Truncate</li> <li>Write Truncate feature and it's tests to <code>log_service.zig</code></li> <li>Add Truncate container testing to <code>app-test-container</code> with all the requirements</li> <li>Update <a>config</a> to cover truncate for test</li> <li>Create a builder for different CPU architectures and OS and implement a released inside</li> </ul> Version 2.0.0 <ol> <li>Log file monitoring</li> <li>Parse and process monitored log files</li> <li>Save processed log files to a database for future consumption by a UI application</li> </ol> License This project is licensed under the <a>MIT License</a>. Author Developed by <a>Gnyblast</a>.
[]
https://avatars.githubusercontent.com/u/24439787?v=4
Fluid-Simulation
PavelDoGreat/Fluid-Simulation
2025-04-20T04:25:26Z
This project will be a complete rewrite of my mobile app Fluid Simulation. It will be done in an open-source way and hopefully will inspire many people around the world.
main
0
12
1
12
https://api.github.com/repos/PavelDoGreat/Fluid-Simulation/tags
MIT
[ "zig" ]
812
false
2025-05-21T16:39:46Z
true
true
0.14.0
github
[ { "commit": "e3756ae7fb9463ee12004bd3f435c84f73bee7f6", "name": "shdc", "tar_url": "https://github.com/floooh/sokol-tools-bin/archive/e3756ae7fb9463ee12004bd3f435c84f73bee7f6.tar.gz", "type": "remote", "url": "https://github.com/floooh/sokol-tools-bin" } ]
Open-source Fluid Simulation <em>This project will be a complete rewrite of my mobile app Fluid Simulation. It will be done in an open-source way and hopefully will inspire many people around the world.</em> Here are the links to the app: - <strong>Android (Free):</strong> https://play.google.com/store/apps/details?id=games.paveldogreat.fluidsimfree - <strong>Android:</strong> https://play.google.com/store/apps/details?id=games.paveldogreat.fluidsim - <strong>iOS/Mac:</strong> https://itunes.apple.com/app/fluid-simulation/id1443124993 The app is currently developed using Unity Engine, which is the cause of many app's issues, including bugs, high energy consumption, and poor performance. In addition, it has not been the best experience for me as a developer, and I see that it can be much better. I have been developing this app for 7 years and have some experience with coding. The new app will be written in Zig and platforms' native languages like Objective-C, Kotlin, JavaScript. I will try to make it simple, with high performance and fast compile times, low power consumption, and a small executable size. Sounds great, right? At first, it will be developed for web browsers, which makes it easy to distribute for testing and it's just so cool. Then I will develop a new UI interface that will be next-gen. And when I release it as a new version on mobile app stores, the app will be completely free with no money to see. As we are approaching a new golden age with AI, I want this project to be a golden template for development and creative vibe coding. A future where you use AI to adjust the template to your own project and handle all the tedious tasks, so you can focus on the fun and creative parts. It will be a better alternative to big engines, because AI will generate all the editor tools that you need. Projects will be efficient, simple and compact, along with other wonderful things that I will leave for your imagination. I envision it as a beautiful diamond, which, if you apply AI to it, won't lose much of its qualities. There will be new kinds of warriors who use code to fight dark forces. As programmers rise in power, they will have more responsibilities for the order of the world. And this order requires adherence to God's laws. Software that aligns with eternal laws is beautiful and harmonious. It will exist till the end of this Universe. Anything else is a noise that will be forgotten. But don't be sad about it because you are an eternal soul and will never be forgotten. <em>O Lord, may I be your greatest warrior?</em> <strong><em>Rise up, people of order! You have a duty to fight against noise because it wants us to forget the beautiful truth. With great software there will be no place for the unoptimized noise that tries to control minds of the people. And soon there will be new Heaven on Earth and people will see again the glory of God.</em></strong> I will later post a link here describing natural laws in more details. Right now you can go to my X profile and publicly ask me questions https://x.com/PavelDoGreat You can also check my X post about app's price reduction that should be a standard practice among businessmen https://x.com/PavelDoGreat/status/1890253379789812206 How to build To build a project you need Zig. <a>Go to Zig's Getting Started page.</a> Then open project's folder in terminal and type <code>console zig build run</code> License You can use the project in any way you want as long as you don't use it for evil noise generators. The code is available under the <a>MIT license</a>
[]
https://avatars.githubusercontent.com/u/65602967?v=4
mkpr
Sophed/mkpr
2025-04-18T02:51:13Z
⚡ fast Zig CLI tool to create projects from a set of opinionated language templates
main
0
10
0
10
https://api.github.com/repos/Sophed/mkpr/tags
MIT
[ "just", "mkpr", "mkproject", "project-init", "zig" ]
281
false
2025-05-18T05:52:43Z
true
true
0.14.0
github
[]
mkpr — make project Fast Zig CLI tool to create projects from a set of opinionated language templates Usage <code>mkpr &lt;template&gt; &lt;project-name&gt;</code> - Use <code>mkpr ls</code> for a list of templates Motive Originally based on my project <a>golaunch</a>, mkpr is intended to be a comprehensive set of utility scripts and templates for my personal projects. <a>Just</a> was chosen as the command runner of choice for its flexibility and simple shell-like syntax. Simply running <code>just build</code> and having a cohesive toolchain is far easier and less headache than having build scripts with different syntax for each language I use for a project. Installing <ul> <li>I'll add to some package repos eventually</li> <li>Until then, there is binaries available in <a>releases</a></li> </ul> Building <ul> <li>Requires <code>zig</code> version <strong>0.14.0</strong> and <code>just</code> installed <code>git clone https://github.com/Sophed/mkpr cd mkpr just build</code></li> <li>Output binaries can be found in <code>zig-out/bin/</code></li> </ul> Available Templates Go <ul> <li>Requires <code>go</code> installed</li> </ul> Click to view project structure ``` example ├── .gitignore &lt;- language specific ignores ├─ app │ ├─ main.go │ └─ main_test.go ├─ build │ └─ bin &lt;- output binary ├─ go.mod ├─ justfile &lt;- build/run/test scripts ├─ LICENSE &lt;- auto generated MIT license from username/current year └─ README.md &lt;- auto generated with project name ``` Rust <ul> <li>Requires <code>cargo</code> installed</li> <li>The built in <code>cargo init</code> was mostly sufficient, this template just adds meta files</li> </ul> Click to view project structure ``` example ├── .gitignore &lt;- language specific ignores ├── Cargo.lock ├── Cargo.toml ├── justfile &lt;- build/run/test scripts ├── LICENSE &lt;- auto generated MIT license from username/current year ├── README.md &lt;- auto generated with project name ├── src │ └── main.rs ├── target │ └── ... └── tests └── example_test.rs ``` Zig <ul> <li>Requires <code>zig</code> installed (only version 0.14.0 tested, newer versions should still work)</li> </ul> Click to view project structure ``` example ├── .gitignore &lt;- language specific ignores ├── build.zig ├── build.zig.zon ├── justfile &lt;- build/run scripts ├── LICENSE &lt;- auto generated MIT license from username/current year ├── README.md &lt;- auto generated with project name └── src └── main.zig ```
[]
https://avatars.githubusercontent.com/u/124677802?v=4
android-ndk-custom
HomuHomu833/android-ndk-custom
2025-02-22T08:08:25Z
Android NDK with custom LLVM built using musl and Cosmopolitan libc, supporting multiple architectures and platforms.
main
0
10
6
10
https://api.github.com/repos/HomuHomu833/android-ndk-custom/tags
MIT
[ "android", "cosmo", "cosmopolitan", "cosmopolitan-libc", "custom", "musl", "musl-libc", "ndk", "termux", "zig" ]
647
false
2025-05-21T02:23:13Z
false
false
unknown
github
[]
Android NDK Custom A custom-built Android NDK that replaces the default toolchain with a modified LLVM using <strong>musl libc from <a>Zig</a></strong> and <strong><a>Cosmopolitan libc</a></strong>. Inspired by <a>Zongou's build system</a>. Features <ul> <li><strong>Custom LLVM</strong> build, sourced from Google's repositories.</li> <li>Built using Zig as LLVM and Cosmopolitan GCC.</li> <li><strong>Additional Tools Built</strong>:</li> <li><strong>Shaderc</strong></li> <li><strong>Python</strong></li> <li><strong>Make</strong></li> <li><strong>Yasm</strong></li> </ul> Architecture and Platform Support <ul> <li><strong>Zig-based Environment</strong></li> <li><strong>Platforms</strong>:<ul> <li>Linux</li> <li>Android</li> </ul> </li> <li> <strong>Architectures</strong>: <ul> <li><strong>X</strong>: <code>x86</code>, <code>x86_64</code></li> <li><strong>ARM</strong>: <code>arm</code>, <code>armeb</code>, <code>aarch64</code>, <code>aarch64_be</code></li> <li><strong>RISC-V</strong>: <code>riscv32</code>, <code>riscv64</code></li> <li><strong>PowerPC</strong>: <code>powerpc</code>, <code>powerpc64</code>, <code>powerpc64le</code></li> <li><strong>MIPS</strong>: <code>mips</code>, <code>mipsel</code>, <code>mips64</code>, <code>mips64el</code></li> <li><strong>Other</strong>: <code>loongarch64</code>, <code>s390x</code></li> </ul> </li> <li> <strong>Cosmopolitan Environment</strong> </li> <li><strong>Platforms</strong>:<ul> <li>Windows</li> <li>Linux</li> <li>macOS</li> <li>Android</li> <li>NetBSD</li> <li>FreeBSD</li> <li>OpenBSD 7.3</li> </ul> </li> <li><strong>Architectures</strong>:<ul> <li><strong>X</strong>: <code>x86_64</code></li> <li><strong>ARM</strong>: <code>aarch64</code></li> </ul> </li> </ul> Usage This NDK functions like the standard Android NDK. Simply extract the archive and use it as you would with the official version. License This project is licensed under the <strong>MIT License</strong>. See the <a>LICENSE</a> file for more details. Feel free to open pull requests or issues if you have any contributions or feedback!
[]
https://avatars.githubusercontent.com/u/86865279?v=4
zclock
tr1ckydev/zclock
2025-04-19T08:37:24Z
A cross-platform terminal digital clock.
main
1
9
1
9
https://api.github.com/repos/tr1ckydev/zclock/tags
MIT
[ "tty-clock", "zig" ]
78
false
2025-05-21T22:04:58Z
true
true
unknown
github
[]
zclock A minimal customizable cross-platform terminal digital clock. zclock is written from scratch in <a>zig</a> and only uses <code>time.h</code> and pure zig std. <ul> <li>Works on windows, macos and linux</li> <li>Auto center or manual position in terminal</li> <li>Custom date string formatting</li> <li>Toggle seconds display</li> <li>Toggle between 12 or 24 hour (military) mode</li> <li>Change colors to personalize it</li> <li>Change clock render style</li> </ul> Install <ol> <li>Install latest zig master branch.</li> <li>Clone this repository. <code>bash git clone https://github.com/tr1ckydev/zclock cd zclock</code></li> <li>Build the project. <code>bash zig build -Doptimize=ReleaseFast</code></li> <li>Add the binary file from <code>./zig-out/bin/</code> to <code>$PATH</code>.</li> </ol> <blockquote> Press <code>Ctrl + C</code> to exit to clock. </blockquote> Usage Print the help menu to see the available options. <code>bash zclock --help</code> <ul> <li><code>--fmt=&lt;FORMAT&gt;</code>: See <a>strftime manual</a> for available format specifiers.</li> <li><code>--color=&lt;NAME&gt;</code>: See <a>zig docs</a> for valid color names.</li> <li><code>--style=&lt;STYLE&gt;</code>: <code>default</code> | <code>line</code></li> </ul> Notes on windows When using Windows Terminal or Windows Console Host, sometimes flickering of the clock can be observed when it redraws itself on the terminal after each second. Switch to unix-like terminals such as MinGW terminal (e.g. Git Bash), Cygwin terminal for a flicker-free experience. Credits Thanks to <a>peaclock</a> for inspiring this project. License This repository is licensed under the MIT License. Please see <a>LICENSE</a> for full license text.
[]
https://avatars.githubusercontent.com/u/11627921?v=4
zigma
Thomvanoorschot/zigma
2025-03-15T15:53:46Z
Zigma is an algorithmic trading framework built with the Zig programming language, leveraging an actor-based concurrency model. It aims to provide an efficient, low-latency system for algorithmic trading through components handling market data, strategy execution, order management, risk, and data persistence.
main
0
9
0
9
https://api.github.com/repos/Thomvanoorschot/zigma/tags
MIT
[ "actor", "actor-framework", "concurrency", "quantitative-finance", "trading", "wasm", "zig", "ziglang" ]
18,506
false
2025-05-19T16:54:23Z
false
false
unknown
github
[]
Zigma: Actor-Based Algorithmic Trading Framework Overview Zigma is an algorithmic trading framework built with the Zig programming language, leveraging an actor-based concurrency model. This project serves as both a practical trading system and an educational exploration of Zig’s memory management capabilities and concurrency patterns. Goals • Implement a robust actor framework for handling concurrent trading operations \ • Explore Zig’s memory management features in depth \ • Develop efficient, low-latency trading algorithms \ • Create a modular system that can be extended with new strategies and market connectors \ • Serve as a learning resource for Zig programming best practices Architecture Zigma is built around an actor model, where independent components communicate through message passing: \ • Market Data Actors – Connect to exchanges and process incoming market data \ • Strategy Actors – Implement trading algorithms and generate signals \ • Order Management Actors – Handle order creation, modification, and cancellation \ • Risk Management Actors – Monitor positions and enforce trading limits \ • Persistence Actors – Handle data storage and retrieval Features • Non-blocking, concurrent processing of market data \ • Memory-efficient implementation with minimal allocations \ • Type-safe message passing between actors \ • Pluggable strategy system for implementing various trading algorithms \ • Comprehensive logging and monitoring Learning Outcomes This project provides hands-on experience with: \ • Zig’s comptime features and metaprogramming \ • Manual memory management with allocators \ • Error handling patterns in Zig \ • Concurrency without shared state \ • Performance optimization techniques \ • Safe interoperability with C libraries Getting Started (Instructions for building and running the project will be added as development progresses.) Project Status 🚧 Early Development – The actor framework and core components are currently being designed and implemented.
[]
https://avatars.githubusercontent.com/u/196498040?v=4
secsock
tardy-org/secsock
2025-03-09T00:23:02Z
Async TLS (Secure Socket) for the Tardy runtime
main
3
9
1
9
https://api.github.com/repos/tardy-org/secsock/tags
MPL-2.0
[ "async", "tardy", "tls", "zig", "zig-package" ]
62
false
2025-04-27T04:29:43Z
true
true
unknown
github
[ { "commit": "master", "name": "tardy", "tar_url": "https://github.com/tardy-org/tardy/archive/master.tar.gz", "type": "remote", "url": "https://github.com/tardy-org/tardy" }, { "commit": null, "name": "bearssl", "tar_url": null, "type": "relative", "url": "vendor/bearssl"...
secsock This is an implementation of <code>SecureSocket</code>, a wrapper for the Tardy <code>Socket</code> type that provides TLS functionality. Supported TLS Backends <ul> <li><a>BearSSL</a>: An implementation of the SSL/TLS protocol (RFC 5346) written in C.</li> <li><a>s2n-tls</a>: An implementation of SSL/TLS protocols by AWS. (Experimental)</li> </ul> Installing Compatible Zig Version: <code>0.14.0</code> Compatible <a>tardy</a> Version: <code>v0.3.0</code> Latest Release: <code>0.1.0</code> <code>zig fetch --save git+https://github.com/tardy-org/secsock#v0.1.0</code> You can then add the dependency in your <code>build.zig</code> file: ```zig const secsock = b.dependency("secsock", .{ .target = target, .optimize = optimize, }).module("secsock"); exe.root_module.addImport(secsock); ``` Contribution We use Nix Flakes for managing the development environment. Nix Flakes provide a reproducible, declarative approach to managing dependencies and development tools. Prerequisites <ul> <li>Install <a>Nix</a> <code>bash sh &lt;(curl -L https://nixos.org/nix/install) --daemon</code></li> <li>Enable <a>Flake support</a> in your Nix config (<code>~/.config/nix/nix.conf</code>): <code>experimental-features = nix-command flakes</code></li> </ul> Getting Started <ol> <li> Clone this repository: <code>bash git clone https://github.com/tardy-org/secsock.git cd secsock</code> </li> <li> Enter the development environment: <code>bash nix develop</code> </li> </ol> This will provide you with a shell that contains all of the necessary tools and dependencies for development. Once you are inside of the development shell, you can update the development dependencies by: 1. Modifying the <code>flake.nix</code> 2. Running <code>nix flake update</code> 3. Committing both the <code>flake.nix</code> and the <code>flake.lock</code> License Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in secsock by you, shall be licensed as MPL2.0, without any additional terms or conditions.
[ "https://github.com/tardy-org/zzz" ]
https://avatars.githubusercontent.com/u/38849891?v=4
zi
xoltia/zi
2025-05-03T17:51:50Z
A Zig/ZLS installer.
main
0
9
0
9
https://api.github.com/repos/xoltia/zi/tags
MIT
[ "installer", "version-manager", "zig" ]
77
false
2025-05-21T05:34:10Z
true
true
0.15.0-dev.386+2e35fdd03
github
[]
zi: a zig installer zi is a basic tool that helps you install specific versions of Zig from the official index. It can also install ZLS, either from GitHub releases or by building it from source for use with the latest Zig version. Usage ``` Usage: zi [OPTIONS] [SUBCOMMAND] Subcommands: ls List Zig versions install Install a specific Zig version Flags: -h, --help Print help information -V, --version Print version information Flags for <code>ls</code> subcommand: -r, --remote List only remote versions -l, --local List only local versions Flags for <code>install</code> subcommand: -f, --force Remove the existing download if it exists -s, --skip-zls Skip downloading and/or linking the ZLS executable Environment variables: ZI_INSTALL_DIR Directory to install Zig versions (default: $HOME/.zi) ZI_LINK_DIR Directory to create symlinks for the active Zig version (default: $HOME/.local/bin) ```
[]
https://avatars.githubusercontent.com/u/151967?v=4
whats
mrusme/whats
2025-04-14T23:19:32Z
Command line tool for getting answers to everyday questions like `whats 2 meters in feet` or more importantly `whats 1.21 gigawatts in watts`
master
1
8
0
8
https://api.github.com/repos/mrusme/whats/tags
GPL-3.0
[ "calculator", "cli", "command-line", "command-line-tool", "conversion", "converter", "tool", "tools", "zig" ]
215
false
2025-05-14T16:21:04Z
true
true
0.14.0
github
[ { "commit": "master", "name": "bfstree_zig", "tar_url": "https://github.com/mrusme/bfstree.zig//archive/master.tar.gz", "type": "remote", "url": "https://github.com/mrusme/bfstree.zig/" }, { "commit": "master", "name": "xml", "tar_url": "https://github.com/ianprime0509/zig-xml//a...
whats <a></a> Command line tool for getting answers to everyday questions like: <code>sh whats 2 meters in feet</code> ... or more importantly: <code>sh whats 1.21 gigawatts in watts</code> This tool is in its <strong>very</strong> early stages and right now primarily a <em>finger exercise</em> for me while getting into Zig. TODO <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 lazy loading of data based on command (e.g. if no money required don't load) <code>whats --help</code> ```sh Usage: whats [OPTION]... NUMBER [UNIT] [OPERATOR] [NUMBER] [UNIT] A command for basic convertion and calculation. -h, --help display this help and exit -v, --version output version information and exit Units: Symbol Name MONEY: EUR EUR RON RON PLN PLN USD USD ILS ILS KRW KRW MYR MYR MXN MXN NOK NOK JPY JPY ISK ISK SGD SGD BGN BGN DKK DKK TRY TRY ZAR ZAR CZK CZK CNY CNY BRL BRL PHP PHP NZD NZD HKD HKD INR INR AUD AUD IDR IDR GBP GBP SEK SEK THB THB CHF CHF CAD CAD HUF HUF DATA: b bit Kb kilobit Mb megabit Gb gigabit Tb terabit Pb petabit Eb exabit Zb zettabit Yb yottabit B byte KB kilobyte MB megabyte GB gigabyte TB terabyte PB petabyte EB exabyte ZB zettabyte YB yottabyte KiB kibibyte MiB mebibyte GiB gibibyte TiB tebibyte PiB pebibyte EiB exbibyte ZiB zebibyte YiB yobibyte ENERGY: J joule qJ quectojoule rJ rontojoule yJ yoctojoule zJ zeptojoule aJ attojoule fJ femtojoule pJ picojoule nJ nanojoule μJ microjoule mJ millijoule cJ centijoule dJ decijoule daJ decajoule hJ hectojoule kJ kilojoule MJ megajoule GJ gigajoule TJ terajoule PJ petajoule EJ exajoule ZJ zettajoule YJ yottajoule RJ ronnajoule QJ quettajoule Wh watthour kWh kilowatthour MWh megawatthour GWh gigawatthour TWh terawatthour PWh petawatthour eV electronvolt cal calorie LENGTH: m meter am attometer fm femtometer pm picometer nm nanometer µm micrometer mm millimeter cm centimeter dm decimeter dam decameter hm hectometer km kilometer Mm megameter Gm gigameter Tm terameter Pm petameter Em exameter Å angstrom in inch ft foot yd yard mi mile nmi nauticalmile lea league fur furlong MASS: g gram qg quectogram rg rontogram yg yoctogram zg zeptogram ag attogram fg femtogram pg picogram ng nanogram μg microgram mg milligram cg centigram dg decigram dag decagram hg hectogram kg kilogram Mg megagram Gg gigagram Tg teragram Pg petagram Eg exagram Zg zettagram Yg yottagram Rg ronnagram Qg quettagram gr grain dr drachm oz ounce lb pound st stone t ton ___ slug POWER: W watt qW quectowatt rW rontowatt yW yoctowatt zW zeptowatt aW attowatt fW femtowatt pW picowatt nW nanowatt μW microwatt mW milliwatt cW centiwatt dW deciwatt daW decawatt hW hectowatt kW kilowatt MW megawatt GW gigawatt TW terawatt PW petawatt EW exawatt ZW zettawatt YW yottawatt RW ronnawatt QW quettawatt PRESSURE: Pa pascal qPa quectopascal rPa rontopascal yPa yoctopascal zPa zeptopascal aPa attopascal fPa femtopascal pPa picopascal nPa nanopascal μPa micropascal mPa millipascal cPa centipascal dPa decipascal daPa decapascal hPa hectopascal kPa kilopascal MPa megapascal GPa gigapascal TPa terapascal PPa petapascal EPa exapascal ZPa zettapascal YPa yottapascal RPa ronnapascal QPa quettapascal mbar millibar cbar centibar dbar decibar bar bar kbar kilobar Mbar megabar Gbar gigabar at technicalatmosphere atm standardatmosphere Ba barye inH20 inchofwatercolumn mmH20 meterofwatercolumn inHg inchofmercury mmHg meterofmercury N/m² newtonpersquaremeter psi poundforcepersquareinch Torr torr TEMPERATURE: C celsius F fahrenheit K kelvin TIME: s second qs quectosecond rs rontosecond ys yoctosecond zs zeptosecond as attosecond fs femtosecond ps picosecond ns nanosecond μs microsecond ms millisecond cs centisecond ds decisecond das decasecond hs hectosecond ks kilosecond Ms megasecond Gs gigasecond Ts terasecond Ps petasecond Es exasecond Zs zettasecond Ys yottasecond Rs ronnasecond Qs quettasecond min minute hr hour d day ___ month yr year ___ decade ___ century ___ millennium 𝑡ₚ plancktime ___ fortnight ___ score VOLUME: L liter qL quectoliter rL rontoliter yL yoctoliter zL zeptoliter aL attoliter fL femtoliter pL picoliter nL nanoliter μL microliter mL milliliter cL centiliter dL deciliter daL decaliter hL hectoliter kL kiloliter ML megaliter GL gigaliter TL teraliter PL petaliter EL exaliter ZL zettaliter YL yottaliter RL ronnaliter QL quettaliter min minim qt quart pt pint gal gallon floz fluidounce fldr usfluiddram tsp teaspoon tbsp tablespoon uspt uspint usqt usquart pot uspottle usgal usgallon usfloz usfluidounce c uscup jig usshot gi usgill bbl barrel ___ oilbarrel ___ hogshead CALCULATION: % percent Note: Symbols are case-sensitive, names are not. Operators: in: Conversion, e.g. 2m in feet to: Conversion or calculation, e.g. 2m to feet, 10 to 20 of: Calculation, e.g. 20% of 100, 20 of 100 The operator is optional when units are present: whats 2 m ft whats 10% 100 Examples: whats 2 meters in feet whats 1.21 gigawatts in watts whats 8 kg in grams whats 1024 KiB in MiB Spaces are optional: whats 2m ft Report bugs at: https://github.com/mrusme/whats/issues Home page: http://xn--gckvb8fzb.com/projects/whats/ ```
[]
https://avatars.githubusercontent.com/u/4337696?v=4
hparse
nikneym/hparse
2025-02-16T08:30:17Z
Fastest HTTP parser in the west. Utilizes SIMD vectorization, supports streaming and never allocates. Powered by Zig ⚡
main
0
8
0
8
https://api.github.com/repos/nikneym/hparse/tags
MIT
[ "http", "http-parser", "parse", "zig", "ziglang" ]
81
false
2025-04-23T01:58:25Z
true
true
unknown
github
[]
hparse Fast HTTP/1.1 &amp; HTTP/1.0 parser. Powered by Zig ⚡ Features <ul> <li>Cross-platform SIMD vectorization through Zig's <code>@Vector</code>,</li> <li>Streaming first; can be easily integrated to event loops,</li> <li>Handles partial requests,</li> <li>Never allocates and never copies.</li> <li>Similar API to picohttpparser; can be swapped in smoothly.</li> </ul> Benchmarks Benchmarks can be found under <a><code>bench/</code></a> folder, they can either be run with <a>hyperfine</a> or <a>poop</a>. Here are the comparison of 3 parser libraries (hparse, httparse and picohttpparser) via hyperfine, visualized by Claude 3.7 Sonnet. Usage ```zig const buffer: []const u8 = "GET /hello-world HTTP/1.1\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n"; // initialize with default values var method: Method = .unknown; var path: ?[]const u8 = null; var http_version: Version = .@"1.0"; var headers: [32]Header = undefined; var header_count: usize = 0; // parse the request _ = try hparse.parseRequest(buffer[0..], &amp;method, &amp;path, &amp;http_version, &amp;headers, &amp;header_count); ``` 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/hparse/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 hparse_dep = b.dependency("hparse", dep_opts); const hparse_module = hparse_dep.module("hparse"); exe_mod.addImport("hparse", hparse_module); ``` Acknowledgements This project wouldn't be possible without these other projects and posts: <ul> <li><a>h2o/picohttpparser</a></li> <li><a>seanmonstar/httparse</a></li> <li><a>SIMD with Zig by Karl Seguin</a></li> <li><a>SWAR explained: parsing eight digits by Daniel Lemire</a></li> <li><a>Bit Twiddling Hacks by Sean Eron Anderson</a></li> </ul> License MIT.
[]
https://avatars.githubusercontent.com/u/61094301?v=4
zterm
Rowobin/zterm
2025-05-17T22:08:05Z
A terminal manipulation library written in Zig.
main
0
7
0
7
https://api.github.com/repos/Rowobin/zterm/tags
MIT
[ "terminal", "terminal-us", "zig" ]
5
false
2025-05-20T16:34:20Z
true
true
0.14.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> This library is a work in progress, bugs and incomplete feeatures are to be expected. </blockquote> zterm A low-level terminal manipulation library written in Zig. Built as an learning exercise, taking inspiration from <a>mibu</a>. <blockquote> Tested with zig 0.14.0 and 0.15.0-dev.565+8e72a2528 </blockquote> Features <ul> <li>Style (bold, italic, underline, etc).</li> <li>8-16 colors.</li> <li>True Color (24-bit RGB).</li> </ul> How to use Add library as a dependency in <code>build.zig.zon</code> file with the following command: <code>bash zig fetch --save git+https://github.com/Rowobin/zterm</code> Add the following to the<code>build.zig</code> file: ```zig const zterm_dep = b.dependency("zterm", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zterm", zterm_dep.module("zterm")); ``` Now the library can be used: ```zig const std = @import("std"); const zterm = @import("zterm"); pub fn main() void { std.debug.print("{s}Hello World in red!\n", .{ zterm.color.fg(.red) }); } ``` Building examples You can build any example with: ```zig <blockquote> zig build example_name ``` </blockquote> List of examples: - text_effects
[]
https://avatars.githubusercontent.com/u/132705474?v=4
zig-devicetree
CascadeOS/zig-devicetree
2025-03-05T22:11:35Z
A read-only Flattened Device Tree (DTB) API.
main
0
7
1
7
https://api.github.com/repos/CascadeOS/zig-devicetree/tags
BSD-2-Clause
[ "device-tree", "devicetree", "dtb", "fdt", "zig", "zig-library", "zig-package", "ziglang" ]
135
false
2025-05-08T17:53:14Z
true
true
0.14.0
github
[]
zig-devicetree A read-only Flattened Devicetree (DTB) API. None of the API requires allocation except the various list builders in <code>Property.Value</code> which are completely optional. Compatible with <a>Devicetree Specification v0.4</a>. <a>Auto-generated docs</a> This started as a wrapper around <a>libfdt</a> but is now a fresh implementation. Installation Add the dependency to <code>build.zig.zon</code>: <code>sh zig fetch --save git+https://github.com/CascadeOS/zig-devicetree</code> Then add the following to <code>build.zig</code>: <code>zig const devicetree_dep = b.dependency("devicetree", .{}); exe.root_module.addImport("DeviceTree", devicetree_dep.module("DeviceTree"));</code>
[]
https://avatars.githubusercontent.com/u/55424194?v=4
zzon
nurulhudaapon/zzon
2025-04-16T16:05:18Z
A fast, spec compliant, ZON parser and serializer for JavaScript.
main
0
6
0
6
https://api.github.com/repos/nurulhudaapon/zzon/tags
-
[ "javascript", "js", "json", "ts", "typescript", "zig", "zon" ]
1,827
false
2025-04-21T20:04:45Z
false
false
unknown
github
[]
Zig ZON › zzon <a></a> <a></a> A fast, spec-compliant ZON parser and serializer for JavaScript. <a>ZON</a> is a compact, human-readable, and easy-to-parse data format from the Zig programming language that is similar to JSON in JavaScript. The API is similar to the native <a><code>JSON</code> API</a>. <a>Try it in the Playground</a> Installation <code>bash npm install zzon</code> Usage Stringify ```ts id="stringify" import { ZON } from 'zzon'; const zon = ZON.stringify({"a":1,"b":"abc","c":true}); console.log(zon); // .{.a=1,.b="abc",.c=true} ``` Parse ```ts id="parse" import { ZON } from 'zzon'; const json = ZON.parse(<code>.{.a=1,.b="abc",.c=true}</code>); console.log(json); // {"a":1,"b":"abc","c":true} ``` <a>Playground</a> Benchmarks Performance comparison between ZON and JSON (source: <a>test/index.test.ts</a>): | Operation | JSON | ZON | Difference | |-----------|------|-----|------------| | Parse | 254.23ms | 2544.44ms | 2290.21ms (10.01x slower) | | Stringify | 228.45ms | 1033.41ms | 804.95ms (4.52x slower) | Hardware: Apple M1 Pro Platform: darwin 24.4.0 (arm64) <em>Last updated: 2025-04-21T04:58:48.677Z</em> Example Usage <ul> <li><a>Browser</a></li> <li><a>Bun</a></li> </ul> License <a>MIT</a>
[]
https://avatars.githubusercontent.com/u/1084816?v=4
wax
chrisco512/wax
2025-02-14T03:35:13Z
A simple, zero-dependency smart contract framework for Arbitrum Stylus, written in Zig
master
2
6
1
6
https://api.github.com/repos/chrisco512/wax/tags
-
[ "arbitrum", "ethereum", "wasm", "zig" ]
289
false
2025-05-11T04:17:43Z
true
true
unknown
github
[]
Wax A simple, zero-dependency smart contract framework for Arbitrum Stylus, written in Zig Philosophy <ul> <li>Simple router-based app framework</li> <li>Supports middleware</li> <li>Tiny binaries</li> <li>Maximum performance</li> <li>Learn it in an afternoon (even with zero Zig experience)</li> <li>Avoid esoteric language features wherever possible</li> <li>Stick with basic building blocks as much as possible: functions, structs, arrays, enums</li> <li>Easily testable</li> </ul> Dependencies This code is running on a pre-release of Zig 0.14 (which is due in next couple of weeks). Install Zig from master, see: https://ziglang.org/download/. You'll also need Arbitrum Nitro dev node to test, which depends on Docker. See: https://docs.arbitrum.io/run-arbitrum-node/run-nitro-dev-node In addition, you'll need cargo stylus to deploy: https://github.com/OffchainLabs/cargo-stylus Running Examples After all dependencies are installed. Make sure you have Arbitrum Nitro Dev node running locally by following instructions from link above. Navigate to examples/counter and run <code>zig build</code>. It will produce a <code>main.wasm</code> file in <code>examples/counter/zig-out/bin</code>. Navigate to that directory and then run: ```bash <blockquote> RPC=http://localhost:8547 PRIVATE_KEY=0xb6b15c8cb491557369f3c7d2c287b053eb229daa9c22138887752191c9520659 cargo stylus deploy --no-verify --endpoint $RPC --private-key $PRIVATE_KEY --wasm-file=main.wasm ``` </blockquote> It will produce output similar to: <code>bash stripped custom section from user wasm to remove any sensitive data contract size: 1.4 KB deployed code at address: 0x1bac7c33af7313d0ac112a3c7bbc3314fc181ef7 deployment tx hash: 0x9ec6bb6672fe3c6141390b77688290f4202c73a5e2c88fc2acd0f6efc429db64 wasm already activated!</code> Although your contract address and tx hash will be different. Set the contract address to a local variable: ```bash <blockquote> CONTRACT=0x1bac7c33af7313d0ac112a3c7bbc3314fc181ef7 ``` </blockquote> Then, using Foundry's <code>cast</code> (https://getfoundry.sh/), invoke the smart contract's <code>count</code> and <code>increment</code> methods: <code>bash ❯ cast call --rpc-url $RPC --private-key $PRIVATE_KEY $CONTRACT "count()(uint256)" 0 ❯ cast send --rpc-url $RPC --private-key $PRIVATE_KEY $CONTRACT "increment()()" ❯ cast call --rpc-url $RPC --private-key $PRIVATE_KEY $CONTRACT "count()(uint256)" 1</code> Notice This code is still in early-stage development and should not be used in production.
[]
https://avatars.githubusercontent.com/u/1931331?v=4
sentry-native
olksdr/sentry-native
2025-03-12T19:07:01Z
Sentry Native packaged for Zig.
master
0
6
0
6
https://api.github.com/repos/olksdr/sentry-native/tags
MIT
[ "crash-reporting", "error-reporting", "getsentry", "monitoring", "native", "sentry", "zig", "zig-package", "ziglang" ]
5
false
2025-03-31T10:30:56Z
true
true
0.14.0
github
[]
Sentry Native This is the <a>sentry-native</a>, packaged for <a>Zig</a>. This is a build wrapper, which prepars the library which can be linked and exposes the sentry native C API. <em>Note</em>: This will work for simple use-cases, but this still needs more testing. Installation First add the dependencies to your project ```shell <blockquote> zig fetch --save git+https://github.com/olksdr/sentry-native.git ``` </blockquote> And after you can import <code>sentry_native</code> in yout <code>build.zig</code>. <em>Note</em>: the dash ("-") is replaced with underscore ("_") in the name. ```zig const sentry_native = b.dependency("sentry_native", .{ .target = target, .optimize = optimize, // Only if you run on Unix-like system you might want to link with libcurl (deafult is "false"). .curl = true, // Only if you are on Windows (default "false"). .winhttp = true, }); // Link the Sentry library to your exe. exe.linkLibrary(sentry_native.artifact("sentry")); // Add the imports to the root module, so you can use those in your code, e.g.: // const sentry = @import("sentry"); exe.root_module.addImport("sentry", sentry_native.module("sentry")); ``` You might have to install additional dependencies and makes sure the your dev environment is configured and all paths and includes are in-place. Different systems will have different requirements (e.g. on Windows you might have to install WindowsSDK and make sure that <code>PATH</code> is properly set up, etc.). Maintenance When updating <code>sentry-native</code> to the new relase (or commit), make sure to check and update the list of file <code>*.c</code> files, and also make sure that includes are correct. When updating to the new release, make sure to change also the version in the <code>build.zig</code> update fetching new <code>sentry-native</code> commit. Known limitations: Currently only <code>none</code> or <code>inproc</code> (enabled by default) backends are supported. TODO: As part of this build the following items still on the list: <br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Support Crashpad 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> Support Breakpad backend.
[]
https://avatars.githubusercontent.com/u/24578855?v=4
zig-jwt
deatil/zig-jwt
2025-02-20T11:10:53Z
A JWT (JSON Web Token) library for zig.
main
0
6
1
6
https://api.github.com/repos/deatil/zig-jwt/tags
Apache-2.0
[ "jwt", "zig", "zig-jwt" ]
153
false
2025-05-21T03:54:25Z
true
true
0.14.0-dev.3451+d8d2aa9af
github
[]
Zig-jwt A JWT (JSON Web Token) library for zig. Env <ul> <li>Zig &gt;= 0.14.0-dev.3451+d8d2aa9af</li> </ul> What the heck is a JWT? JWT.io has <a>a great introduction</a> to JSON Web Tokens. In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for <code>Bearer</code> tokens in Oauth 2. A token is made of three parts, separated by <code>.</code>'s. The first two parts are JSON objects, that have been <a>base64url</a> encoded. The last part is the signature, encoded the same way. The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to <a>RFC 7519</a> for information about reserved keys and the proper way to add your own. What's in the box? This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. Adding zig-jwt as a dependency Add the dependency to your project: <code>sh zig fetch --save=zig-jwt git+https://github.com/deatil/zig-jwt#main</code> or use local path to add dependency at <code>build.zig.zon</code> file <code>zig .{ .dependencies = .{ .@"zig-jwt" = .{ .path = "./lib/zig-jwt", }, ... } }</code> And the following to your <code>build.zig</code> file: <code>zig const zig_jwt_dep = b.dependency("zig-jwt", .{}); exe.root_module.addImport("zig-jwt", zig_jwt_dep.module("zig-jwt"));</code> The <code>zig-jwt</code> structure can be imported in your application with: <code>zig const zig_jwt = @import("zig-jwt");</code> Get Starting ~~~zig const std = @import("std"); const jwt = @import("zig-jwt"); pub fn main() !void { const alloc = std.heap.page_allocator; <code>const kp = jwt.eddsa.Ed25519.KeyPair.generate(); const claims = .{ .aud = "example.com", .sub = "foo", }; const s = jwt.SigningMethodEdDSA.init(alloc); const token_string = try s.sign(claims, kp.secret_key); // output: // make jwt: eyJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJhdWQiOiJleGFtcGxlLmNvbSIsInN1YiI6ImZvbyJ9.8aYTV-9_Z1RQUPepUlut9gvniX_Cx_z8P60Z5FbnMMgNLPNP29ZtNG3k6pcU2TY_O3DkSsdxbN2HkmgvjDUPBg std.debug.print("make jwt: {s} \n", .{token_string}); const p = jwt.SigningMethodEdDSA.init(alloc); var token = try p.parse(token_string, kp.public_key); // output: // claims aud: example.com const claims2 = try token.getClaims(); std.debug.print("claims aud: {s} \n", .{claims2.object.get("aud").?.string}); </code> } ~~~ Token Validator ~~~zig const std = @import("std"); const jwt = @import("zig-jwt"); pub fn main() !void { const alloc = std.heap.page_allocator; <code>const token_string = "eyJ0eXAiOiJKV0UiLCJhbGciOiJFUzI1NiIsImtpZCI6ImtpZHMifQ.eyJpc3MiOiJpc3MiLCJpYXQiOjE1Njc4NDIzODgsImV4cCI6MTc2Nzg0MjM4OCwiYXVkIjoiZXhhbXBsZS5jb20iLCJzdWIiOiJzdWIiLCJqdGkiOiJqdGkgcnJyIiwibmJmIjoxNTY3ODQyMzg4fQ.dGVzdC1zaWduYXR1cmU"; var token = jwt.Token.init(alloc); try token.parse(token_string); var validator = try jwt.Validator.init(token); defer validator.deinit(); // validator.withLeeway(3); // output: // hasBeenIssuedBy: true std.debug.print("hasBeenIssuedBy: {} \n", .{validator.hasBeenIssuedBy("iss")}); // have functions: // validator.hasBeenIssuedBy("iss") // iss // validator.isRelatedTo("sub") // sub // validator.isIdentifiedBy("jti rrr") // jti // validator.isPermittedFor("example.com") // audience // validator.hasBeenIssuedBefore(now) // iat, now is time timestamp // validator.isMinimumTimeBefore(now) // nbf // validator.isExpired(now) // exp </code> } ~~~ Signing Methods The JWT library have signing methods: <ul> <li><code>RS256</code>: jwt.SigningMethodRS256</li> <li><code>RS384</code>: jwt.SigningMethodRS384</li> <li> <code>RS512</code>: jwt.SigningMethodRS512 </li> <li> <code>PS256</code>: jwt.SigningMethodPS256 </li> <li><code>PS384</code>: jwt.SigningMethodPS384</li> <li> <code>PS512</code>: jwt.SigningMethodPS512 </li> <li> <code>ES256</code>: jwt.SigningMethodES256 </li> <li> <code>ES384</code>: jwt.SigningMethodES384 </li> <li> <code>ES256K</code>: jwt.SigningMethodES256K </li> <li> <code>EdDSA</code>: jwt.SigningMethodEdDSA </li> <li> <code>ED25519</code>: jwt.SigningMethodED25519 </li> <li> <code>HSHA1</code>: jwt.SigningMethodHSHA1 </li> <li><code>HS224</code>: jwt.SigningMethodHS224</li> <li><code>HS256</code>: jwt.SigningMethodHS256</li> <li><code>HS384</code>: jwt.SigningMethodHS384</li> <li> <code>HS512</code>: jwt.SigningMethodHS512 </li> <li> <code>BLAKE2B</code>: jwt.SigningMethodBLAKE2B </li> <li> <code>none</code>: jwt.SigningMethodNone </li> </ul> Sign PublicKey RSA PublicKey: ~~~zig var secret_key: jwt.crypto_rsa.SecretKey = undefined; var public_key: jwt.crypto_rsa.PublicKey = undefined; // rsa no generate // from pkcs1 der bytes const secret_key = try jwt.crypto_rsa.SecretKey.fromDer(prikey_bytes); const public_key = try jwt.crypto_rsa.PublicKey.fromDer(pubkey_bytes); // from pkcs8 der bytes const secret_key = try jwt.crypto_rsa.SecretKey.fromPKCS8Der(prikey_bytes); const public_key = try jwt.crypto_rsa.PublicKey.fromPKCS8Der(pubkey_bytes); ~~~ ECDSA PublicKey: ~~~zig const ecdsa = std.crypto.sign.ecdsa; var p256_secret_key: ecdsa.EcdsaP256Sha256.SecretKey = undefined; var p256_public_key: ecdsa.EcdsaP256Sha256.PublicKey = undefined; var p384_secret_key: ecdsa.EcdsaP384Sha384.SecretKey = undefined; var p384_public_key: ecdsa.EcdsaP384Sha384.PublicKey = undefined; var p256k_secret_key: ecdsa.EcdsaSecp256k1Sha256.SecretKey = undefined; var p256k_public_key: ecdsa.EcdsaSecp256k1Sha256.PublicKey = undefined; // generate p256 public key const p256_kp = ecdsa.EcdsaP256Sha256.KeyPair.generate(); // from plain bytes const p256_secret_key = try ecdsa.EcdsaP256Sha256.SecretKey.fromBytes(pri_key_bytes); const p256_public_key = try ecdsa.EcdsaP256Sha256.PublicKey.fromSec1(pub_key_bytes); // from der bytes const p256_secret_key = try jwt.ecdsa.ParseP256Sha256Der.parseSecretKeyDer(pri_key_bytes); const p256_secret_key = try jwt.ecdsa.ParseP256Sha256Der.parseSecretKeyPKCS8Der(pri_key_bytes); const p256_public_key = try jwt.ecdsa.ParseP256Sha256Der.parsePublicKeyDer(pub_key_bytes); // generate p384 public key const p384_kp = ecdsa.EcdsaP384Sha384.KeyPair.generate(); // from plain bytes const p384_secret_key = try ecdsa.EcdsaP384Sha384.SecretKey.fromBytes(pri_key_bytes); const p384_public_key = try ecdsa.EcdsaP384Sha384.PublicKey.fromSec1(pub_key_bytes); // from der bytes const p384_secret_key = try jwt.ecdsa.ParseP384Sha384Der.parseSecretKeyDer(pri_key_bytes); const p384_secret_key = try jwt.ecdsa.ParseP384Sha384Der.parseSecretKeyPKCS8Der(pri_key_bytes); const p384_public_key = try jwt.ecdsa.ParseP384Sha384Der.parsePublicKeyDer(pub_key_bytes); // generate p256k public key const p256k_kp = ecdsa.EcdsaSecp256k1Sha256.KeyPair.generate(); // from plain bytes const p256k_secret_key = try ecdsa.EcdsaSecp256k1Sha256.SecretKey.fromBytes(pri_key_bytes); const p256k_public_key = try ecdsa.EcdsaSecp256k1Sha256.PublicKey.fromSec1(pub_key_bytes); // from der bytes const p256k_secret_key = try jwt.ecdsa.ParseSecp256k1Sha256Der.parseSecretKeyDer(pri_key_bytes); const p256k_secret_key = try jwt.ecdsa.ParseSecp256k1Sha256Der.parseSecretKeyPKCS8Der(pri_key_bytes); const p256k_public_key = try jwt.ecdsa.ParseSecp256k1Sha256Der.parsePublicKeyDer(pub_key_bytes); ~~~ EdDSA PublicKey: ~~~zig const Ed25519 = std.crypto.sign.Ed25519; var secret_key: Ed25519.SecretKey = undefined; var public_key: Ed25519.PublicKey = undefined; // generate public key const kp = Ed25519.KeyPair.generate(); // from plain bytes const secret_key = try Ed25519.SecretKey.fromBytes(pri_key_bytes); const public_key = try Ed25519.PublicKey.fromBytes(pub_key_bytes); // from der bytes const secret_key = try jwt.eddsa.parseSecretKeyDer(pri_key_bytes); const public_key = try jwt.eddsa.parsePublicKeyDer(pub_key_bytes); ~~~ LICENSE <ul> <li>The library LICENSE is <code>Apache2</code>, using the library need keep the LICENSE.</li> </ul> Copyright <ul> <li>Copyright deatil(https://github.com/deatil).</li> </ul>
[]
https://avatars.githubusercontent.com/u/58077502?v=4
nzfat
GasInfinity/nzfat
2025-02-28T14:24:33Z
A very generic and configurable FAT12/16/32 implementation with VFAT support.
main
0
6
0
6
https://api.github.com/repos/GasInfinity/nzfat/tags
MIT
[ "fat", "filesystem", "zig", "zig-package" ]
154
false
2025-03-27T07:57:53Z
true
true
0.11.0
github
[]
⚡ nzfat (WIP) A very generic and configurable FAT12/16/32 implementation library with VFAT support written in zig. Almost all the features are configurable, from long filename support (and the max number of characters it supports) to the maximum supported FAT type (12/16/32). <a></a> ❓ Usage The library is not mature enough for production usage. Almost everything revolves around the type <code>nzfat.FatFileSystem</code> and the function <code>nzfat.format.make()</code>. Please see <a>a basic example</a> or <a>messy testing code that uses all its features</a> 📝 TODO Small TODO's <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> Searching for 1 free entry in a directory (a.k.a: Short filename only) <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> Searching for a free cluster linearly <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> Deletion of files and directories <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> Short filename alternatives for functions when using a VFAT <code>FatFilesystem</code> <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> Searching for N free clusters for file and directory 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> Allocate new directory entries if no entries found and not in root (FAT12/16 only) <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> Allocate clusters for files <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> Creation of files and directories with short names <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> API to modify dates and times and attributes in entries <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> API for reading and writing file contents <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> Searching for N free entries in a directory and creation of directory entries with LFN entries if needed. <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> Finish cross-section long filename directory 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> Support Windows NT extra reserved short filename case flags <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Create fat formatted media <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> API for renaming files without copying <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> API for moving files without copying <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> Utility to write files given a buffer (a.k.a: writeAllBytes) <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> Proper FAT unmounting <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> Finish FAT32 formatting <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> Proper FAT mirroring and active FAT handling <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> Optimize the filesystem by properly using FSInfo32 or caching the last free sector/free sector count (When do we calculate it in FAT12/16/(32 when there's no fsinfo or an invalid one)?) <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> Utility to check and 'fix' fat filesystem <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> Comptime utility function to create directories and files given a comptime known path (Really useful!) <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> Comptime utility function to search for directories and files given a comptime known path (Really useful!) Big TODO's <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> Reorganize/rename things <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> Rewrite codepage name 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> Rewrite UTF-16 name handling <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> Think about how to handle errors while writing (e.g: currently an error while allocating clusters will leave the FAT table with dangling clusters...) <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> Behaviour tests <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> Implement some sort of I/O cache? Or leave it to the BlockDevice implementation? <br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Some sort of cache strategy for FAT entries if requested. <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> API Freeze
[]
https://avatars.githubusercontent.com/u/55464917?v=4
whatszig
jlucaso1/whatszig
2025-03-24T22:10:27Z
A WhatsApp messaging client written in Zig, powered by the Go WhatsApp library.
main
0
5
0
5
https://api.github.com/repos/jlucaso1/whatszig/tags
MIT
[ "client", "go", "whatsapp", "zig" ]
57
false
2025-03-31T20:17:54Z
true
true
0.14.0
github
[]
WhatsZig A WhatsApp messaging client written in Zig, powered by the Go WhatsApp library. <a></a> Description WhatsZig is a simple WhatsApp messaging application that connects to the WhatsApp network using Zig as the primary language with Go bindings. It allows you to authenticate via QR code and send messages to WhatsApp contacts. Requirements <ul> <li>Zig (0.14.0 or later)</li> <li>Go (1.20 or later)</li> <li>A WhatsApp account</li> </ul> Installation <ol> <li> Clone the repository: <code>git clone https://github.com/jlucaso1/whatszig.git cd whatszig</code> </li> <li> Build the project: <code>zig build</code> </li> </ol> Usage Running the Application Execute the following command: <code>zig build run</code> Authentication Process <ol> <li>On first run, the application will display a QR code in the terminal (in base64 format).</li> <li>Copy the QR code data and convert it to an image using an online tool or local converter.</li> <li>Scan the QR code with your WhatsApp mobile app:</li> <li>Open WhatsApp on your phone</li> <li>Go to Settings &gt; Linked Devices</li> <li>Tap on "Link a Device"</li> <li> Scan the QR code </li> <li> After successful authentication, you'll be prompted to enter a phone number to send a message. </li> </ol> Sending Messages <ol> <li>Enter the recipient's phone number when prompted (e.g., 559999999999).</li> <li>Enter the message you want to send.</li> <li>The message will be sent, and the program will display the result before exiting.</li> </ol> Persistent Authentication After the first authentication, the application creates a local database file (<code>whatsmeow.db</code>) that stores your session. This means you won't need to scan the QR code again on subsequent runs, unless you log out or your session expires. How It Works WhatsZig uses: - Zig for the main application logic and user interface - Go's WhatsApp library (whatsmeow) for WhatsApp protocol implementation - CGO to connect Zig and Go components Credits This project would not be possible without: <ul> <li><a>tulir/whatsmeow</a> - The excellent Go WhatsApp library that powers the core functionality</li> <li><a>WhiskeySockets/Baileys</a> - For inspiration on WhatsApp API implementation</li> </ul> License <a>MIT License</a>
[]
https://avatars.githubusercontent.com/u/124872?v=4
zig-base91
jedisct1/zig-base91
2025-03-13T11:42:42Z
Base91 encoding for Zig.
main
0
5
1
5
https://api.github.com/repos/jedisct1/zig-base91/tags
MIT
[ "base64", "base91", "codec", "zig", "zig-package" ]
7
false
2025-04-05T15:11:42Z
true
true
0.14.0
github
[]
Base91 for Zig An implementation of the Base91 encoding scheme written in Zig. It enables you to convert binary data to a Base91-encoded string and vice versa. Overview <ul> <li><strong>Space Efficiency:</strong> Base91 produces shorter encoded strings compared to Base64, which can be advantageous when minimizing data size is a priority.</li> <li><strong>Performance Trade-Off:</strong> Although Base91 is more space-efficient, its encoding/decoding operations are generally slower than those of Base64. This trade-off should be considered based on your application’s requirements.</li> </ul> Considerations <ul> <li><strong>When to Use:</strong> Opt for Base91 when reducing the size of encoded data is critical, such as in bandwidth-constrained environments or when storing large volumes of encoded data.</li> <li><strong>When to Avoid:</strong> If your application is performance-sensitive and the encoding/decoding speed is paramount, Base64 might be a more suitable alternative.</li> </ul>
[]
https://avatars.githubusercontent.com/u/200407513?v=4
ruthenium
ruthenium-lang/ruthenium
2025-03-03T21:41:48Z
The Ruthenium Programming Language
master
17
5
1
5
https://api.github.com/repos/ruthenium-lang/ruthenium/tags
-
[ "befunge", "brainfuck", "dreamberd", "funny-coding", "funny-program", "go", "golang", "gulfofmexico", "intercal", "java", "malbolge", "nim", "piet", "programming-language", "programming-language-development", "rust", "ruthenium", "satyamshorrf", "zig" ]
406
false
2025-05-16T18:05:22Z
false
false
unknown
github
[]
404
[]
https://avatars.githubusercontent.com/u/124872?v=4
zig-cymric
jedisct1/zig-cymric
2025-04-04T16:05:52Z
Zig implementations of the Cymric authenticated encryption modes.
main
0
4
1
4
https://api.github.com/repos/jedisct1/zig-cymric/tags
-
[ "aead", "cymric", "zig", "zig-package" ]
13
false
2025-04-17T23:52:23Z
true
false
unknown
github
[]
Cymric implementations in Zig Implementations of the Cymric1 and Cymric2 authenticated encryption modes instantiated with AES. Cymric <a>original implementations and overview</a>.
[]
https://avatars.githubusercontent.com/u/207234749?v=4
cli
for-zig/cli
2025-04-11T15:40:44Z
Easy CLI in zig
main
0
4
0
4
https://api.github.com/repos/for-zig/cli/tags
MIT
[ "cli", "cmd", "terminal", "zig" ]
7
false
2025-05-10T15:57:46Z
true
true
0.15.0-dev.64+2a4e06bcb
github
[]
<b> Seamless Command Line Integration with ZIG. </b> <b><i> inspired from <a>SuperZIG/io/terminal</a> module. </i></b> <b><i> 🔥 Built for power. Designed for speed. Ready for production. 🔥 </i></b> <ul> <li> Features 🌟 </li> <li> <strong>📋 Command Management</strong> &gt; Define and handle commands with ease. </li> <li> <strong>🛠️ Option Parsing</strong> &gt; Support for short and long options, with or without values. </li> <li> <strong>❗ Required Options</strong> &gt; Enforce the presence of required options for commands. </li> <li> <strong>⚙️ Optional Options</strong> &gt; Provide flexibility to commands by allowing additional configuration without being mandatory. </li> <li> <strong>🌍 Platform Compatibility</strong> &gt; Supports Windows, Linux and macOS. </li> </ul> <ul> <li> Documentation <blockquote> Comprehensive documentation for this project is available at: <a>rebuild-x.github.io/docs</a> This documentation is maintained by the <a>Rebuild-X</a> organization and provides detailed insights into the implementation and usage of the CLI framework. </blockquote> </li> </ul> <ul> <li> Build and Run <blockquote> To build and run the application, use the following commands: </blockquote> <code>bash zig build ./zig-out/bin/my_cli help</code> </li> </ul> <a> </a>
[]
https://avatars.githubusercontent.com/u/43209783?v=4
quix
wllfaria/quix
2025-03-07T04:05:23Z
Cross platform terminal manipulation library written in zig.
main
0
4
0
4
https://api.github.com/repos/wllfaria/quix/tags
MIT
[ "cross-platform", "terminal", "tui", "zig", "zig-package" ]
141
false
2025-03-31T17:46:40Z
true
true
0.14.0
github
[ { "commit": "5e149c5e67052092b10d199d9bff209107010b52", "name": "quix_winapi", "tar_url": "https://github.com/wllfaria/quix-winapi/archive/5e149c5e67052092b10d199d9bff209107010b52.tar.gz", "type": "remote", "url": "https://github.com/wllfaria/quix-winapi" } ]
Quix Quix is a terminal manipulation library written in zig. Table of Contents <ul> <li><a>Quix</a><ul> <li><a>Table of Contents</a></li> <li><a>Getting Started</a></li> <li><a>License</a></li> </ul> </li> </ul> Getting Started Add quix as a dependency using <code>zig fetch</code>: <code>sh zig fetch --save git+https://github.com/wllfaria/quix.git</code> Update your <code>build.zig</code> to include quix: <code>zig const quix = b.dependency("quix", .{ .target = target, .optimize = optimize, });</code> Example build.zig. ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const quix = b.dependency("quix", .{ .target = target, .optimize = optimize, }); const app_mod = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); app_mod.addImport("quix", quix.module("quix")); const app = b.addExecutable(.{ .name = "my_app", .root_module = app_mod, }); b.installArtifact(app); const run_cmd = b.addRunArtifact(app); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&amp;run_cmd.step); const exe_unit_tests = b.addTest(.{ .root_module = app_mod }); const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&amp;run_exe_unit_tests.step); } ``` Modify your <code>src/main.zig</code> to look like this: ```zig const quix = @import("quix"); pub fn main() !void { const styled = quix.style.new("Hello from quix!\n") .foreground(.White) .background(.DarkRed) .bold(); <code>try quix.style.printStyled(styled); </code> } ``` <em>You can also check the <a>examples</a> directory for different and more advanced examples.</em> License This project, <code>quix</code> and all its sub-libraries are licensed under the MIT license - see the <a>LICENSE</a> file for details.
[]
https://avatars.githubusercontent.com/u/12181586?v=4
ch32_zig
ghostiam/ch32_zig
2025-02-24T22:49:14Z
WCH CH32 HAL in Zig. Compile simply with `zig build`.
master
0
4
0
4
https://api.github.com/repos/ghostiam/ch32_zig/tags
MIT
[ "ch32", "ch32v", "ch32v003", "embedded", "embedded-zig", "wch", "zig", "ziglang" ]
20,684
false
2025-05-08T21:04:06Z
true
true
0.14.0
github
[ { "commit": "ce6022df56143950f04ed42f8c6c25b06b54fd7f.zip", "name": "minichlink", "tar_url": "https://github.com/ghostiam/minichlink-ocd/archive/ce6022df56143950f04ed42f8c6c25b06b54fd7f.zip.tar.gz", "type": "remote", "url": "https://github.com/ghostiam/minichlink-ocd" } ]
WCH CH32 HAL in Zig HAL(Hardware Abstraction Layer) for the WCH CH32 series of microcontrollers written in Zig. Project Goals <ul> <li>Minimizing the size of the firmware output file. After each change, the size of all examples is checked, and if it increases, the cause is investigated and resolved.</li> <li>Providing seamless IDE autocompletion support is a top priority. Whatever you interact with, autocompletion should work seamlessly.</li> </ul> Getting Started See <a>GETTING_STARTED.md</a> for more details. Basic Examples If you want to learn more about how everything works, I recommend checking out the repository with basic examples that are based on the use of registers without abstractions: <a>ch32v003_basic_zig</a> Size benchmark See <a>SIZE_BENCHMARK.md</a> Useful Notes See <a>USEFUL_NOTES.md</a> Build and flash the examples <code>shell cd examples/blink_minimal zig build zig build minichlink -- -w zig-out/firmware/blink_minimal_ch32v003.bin flash -b</code> Build the <code>minichlink</code> <a>Minichlink</a> is a open-source flasher for WCH chips. It is built with Zig and can be compiled using the following command: <code>shell zig build minichlink</code> Output will be in <code>zig-out/bin/minichlink</code>.
[]
https://avatars.githubusercontent.com/u/15731839?v=4
Zorch
SuperKogito/Zorch
2025-03-01T15:42:25Z
Neural networks in Zig
main
0
4
0
4
https://api.github.com/repos/SuperKogito/Zorch/tags
LGPL-3.0
[ "autograd", "automatic-differentiation", "deep-learning", "machine-learning", "neural-network", "tensor", "zig", "zig-library", "zig-package", "ziglang" ]
3,219
false
2025-03-25T10:55:15Z
true
true
unknown
github
[]
Zorch: A Tensor Library with a Pytorch-like API in Zig Zorch is a lightweight, high-performance tensor library written in Zig. It provides a flexible and efficient framework for numerical computations, automatic differentiation, and machine learning. The library is designed to be simple, modular, and easy to extend. <strong><em>NB: The library is still experimental and not stable enough</em></strong> Table of Contents <ul> <li><a>Zorch: A Tensor Library with a Pytorch-like API in Zig</a></li> <li><a>Table of Contents</a></li> <li><a>Features and To-dos</a><ul> <li><a>Tensor, Ndarray</a></li> <li><a>Autograd</a></li> <li><a>Neural Networks</a></li> <li><a>Optimization</a></li> <li><a>Datasets</a></li> <li><a>Utilities</a></li> <li><a>Testing</a></li> <li><a>Documentation</a></li> </ul> </li> <li><a>Project Structure</a></li> <li><a>Getting Started</a><ul> <li><a>Prerequisites</a></li> <li><a>Building the Project</a></li> </ul> </li> <li><a>Documentation</a></li> <li><a>Examples</a><ul> <li><a>Creating a Tensor</a></li> <li><a>Performing Tensor Operations</a></li> <li><a>Using Automatic Differentiation</a></li> </ul> </li> <li><a>Contributing</a></li> <li><a>License</a></li> </ul> Features and To-dos Tensor, Ndarray <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>Tensor, Ndarray</code> struct <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>Tensor, Ndarray</code> creation (<code>from_value</code>, <code>from_data</code>, <code>zeros</code>, <code>ones</code>, <code>random</code>) <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>Tensor, Ndarray</code> addition (<code>add</code>, <code>add_scalar</code>) <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>Tensor, Ndarray</code> subtraction (<code>sub</code>, <code>sub_scalar</code>) <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>Tensor, Ndarray</code> multiplication (<code>mul</code>, <code>mul_scalar</code>) <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>Tensor, Ndarray</code> division (<code>div</code>, <code>div_scalar</code>) <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>Tensor, Ndarray</code> power (<code>pow</code>, <code>pow_scalar</code>) <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>Tensor, Ndarray</code> matrix multiplication (<code>matmul</code>) <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>Tensor, Ndarray</code> reshaping (<code>reshape</code>) <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>Tensor, Ndarray</code> slicing (<code>slice</code>) <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>Tensor, Ndarray</code> broadcasting (<code>broadcast_to</code>) <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>Tensor, Ndarray</code> element-wise operations (<code>equal</code>, <code>greater_than</code>, <code>less_than</code>) <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>Tensor, Ndarray</code> reduction operations (<code>sum</code>, <code>mean</code>, <code>min</code>, <code>max</code>, <code>argmin</code>, <code>argmax</code>) <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>Tensor, Ndarray</code> activation functions (<code>relu</code>, <code>tanh</code>, <code>sigmoid</code>, <code>softmax</code>) <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>Tensor, Ndarray</code> logging and printing (<code>print</code>, <code>info</code>) <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>Tensor, Ndarray</code> broadcasting support (<code>broadcast_to</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> Support for sparse tensors <br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Support for GPU acceleration <br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Support for BLAS acceleration <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> Concatenation and stacking operations Autograd <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> Backpropagation for (<code>addition</code>, <code>multiplication</code>, <code>substraction</code>, <code>division</code>, etc.) <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Backpropagation for matrix multiplication <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> Gradient accumulation <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> Zeroing gradients (<code>zero_grad</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> Support caching between forward and backward functions <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> Backpropagation for more operations (e.g., division, power) <br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Support for higher-order derivatives <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> Memory optimization for computation graphs <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> Memory optimization for computation graphs Neural Networks <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> Linear layer <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> Convolution layers (<code>Conv2D</code>, <code>Conv1D</code>, etc.) <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> Pooling layers (<code>MaxPool</code>, <code>MeanPool</code>, etc.) <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> Recurrent layers (<code>RNN</code>, <code>LSTM</code>, etc.) <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> Loss functions (e.g., CrossEntropy, MSE) Optimization <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> Stochastic Gradient Descent (SGD) <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> Learning rate scheduling <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> Implement more optimizers (e.g., Adam, RMSprop) <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> Learning rate schedulers (e.g., StepLR, ReduceOnPlateau) Datasets <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> Generate XOR training dataset <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> Parse MNIST dataset Utilities <br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Custom error handling (<code>TensorError</code>, <code>NdarrayError</code>) <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> Logging with timestamps and colors <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> Data type conversion (<code>convert_value_to_dtype</code>) Testing <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> Unit tests for most modules <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 unit tests for all modules <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 integration tests for end-to-end workflows 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> Inline docstrings for all functions <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> Generated HTML documentation <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 more examples and tutorials <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> Improve inline documentation Project Structure The project is organized as follows: <code>. ├── build.zig # Build configuration for Zig ├── build.zig.zon # Dependency management for Zig ├── docs/ # Documentation and generated files ├── src/ # Source code │ ├── autograd.zig # Automatic differentiation │ ├── data.zig # Data loading and preprocessing │ ├── dtypes.zig # Data type definitions │ ├── errors.zig # Custom error handling │ ├── functional.zig # Functional programming utilities │ ├── logger.zig # Logging utilities │ ├── main.zig # Entry point for the application │ ├── ndarray.zig # Core tensor operations │ ├── nn.zig # Neural network components │ ├── ops.zig # Tensor operations │ ├── optim.zig # Optimization algorithms │ ├── root.zig # Root module for the library │ ├── tensor.zig # Tensor abstraction │ ├── utils.zig # Utility functions │ └── zorch.zig # Main library module └── zig-out/ # Build output directory ├── bin/ # Compiled binaries │ └── zorch # Executable └── lib/ # Compiled libraries └── libzorch.a # Static library</code> Getting Started Prerequisites <ul> <li><a>Zig</a> (version 0.13.0 or later)</li> </ul> Building the Project <ol> <li> Clone the repository: <code>bash git clone https://github.com/your-username/zorch.git cd zorch</code> </li> <li> Build the project using Zig: <code>bash zig build</code> </li> </ol> This will generate the following outputs: - Executable: <code>zig-out/bin/zorch</code> - Static library: <code>zig-out/lib/libzorch.a</code> <ol> <li>Run the executable: <code>bash ./zig-out/bin/zorch</code> Or use <code>bash zig build run</code></li> </ol> Using the Library To use Zorch in your Zig project, add it as a dependency in your <code>build.zig.zon</code> file: <code>zig .dependencies = .{ .zorch = .{ .url = "https://github.com/your-username/zorch/archive/main.tar.gz", .hash = "your-hash-here", }, },</code> Then, import the library in your Zig code: ```zig const zorch = @import("zorch"); pub fn main() !void { // Example usage const allocator = std.heap.page_allocator; const tensor = try zorch.Tensor.from_value(allocator, &amp;[_]usize{2, 2}, .f32, 7.2); defer tensor.deinit(); <code>try tensor.print(); </code> } ``` Documentation For detailed documentation, refer to the <a>docs</a> directory. You can also generate the documentation locally: <code>bash zig build docs</code> This will generate HTML documentation in the <code>docs/</code> directory. Examples Creating a Tensor <code>zig const allocator = std.heap.page_allocator; const tensor = try zorch.Tensor.from_value(allocator, &amp;[_]usize{2, 2}, .f32, 1.0); defer tensor.deinit();</code> Performing Tensor Operations ```zig const a = try zorch.Tensor.from_value(allocator, &amp;[<em>]usize{2, 2}, .f32, 1.0); const b = try zorch.Tensor.from_value(allocator, &amp;[</em>]usize{2, 2}, .f32, 2.0); defer a.deinit(); defer b.deinit(); const result = try a.add(b, false); defer result.deinit(); ``` Using Automatic Differentiation ```zig const x = try zorch.Tensor.from_value(allocator, &amp;[_]usize{2, 2}, .f32, 1.0); x.requires_grad = true; defer x.deinit(); const y = try x.mul_scalar(2.0, false); defer y.deinit(); try y.backward(null); ``` Contributing <ul> <li>Contributions are welcome! Please open an issue or submit a pull request for any bugs, feature requests, or improvements.</li> <li>Let me know if you need further help!</li> </ul>
[]
https://avatars.githubusercontent.com/u/201527030?v=4
tokenizer
jaco-bro/tokenizer
2025-04-19T04:26:17Z
BPE tokenizer for LLMs in Pure Zig
main
0
4
3
4
https://api.github.com/repos/jaco-bro/tokenizer/tags
Apache-2.0
[ "bpe-tokenizer", "pcre2", "regex", "tokenizer", "zig", "zig-package" ]
305
false
2025-05-16T16:52:45Z
true
true
unknown
github
[ { "commit": "refs", "name": "pcre2", "tar_url": "https://github.com/PCRE2Project/pcre2/archive/refs.tar.gz", "type": "remote", "url": "https://github.com/PCRE2Project/pcre2" } ]
Tokenizer BPE tokenizer implemented entirely in Zig. Example integration with LLMs at <a>nnx-lm</a>. Requirement zig v0.13.0 Install <code>bash git clone https://github.com/jaco-bro/tokenizer cd tokenizer zig build exe --release=fast</code> Usage <ul> <li><code>zig-out/bin/tokenizer_exe [--model MODEL_NAME] COMMAND INPUT</code> </li> <li><code>zig build run -- [--model MODEL_NAME] COMMAND INPUT</code> </li> </ul> <code>bash zig build run -- --encode "hello world" zig build run -- --decode "{14990, 1879}" zig build run -- --model "phi-4-4bit" --encode "hello world" zig build run -- --model "phi-4-4bit" --decode "15339 1917"</code> Python (optional) Tokenizer is also pip-installable for use from Python: <code>bash pip install tokenizerz python</code> Usage: ```python <blockquote> <blockquote> <blockquote> import tokenizerz tokenizer = tokenizerz.Tokenizer() Directory 'Qwen2.5-Coder-0.5B' created successfully. DL% UL% Dled Uled Xfers Live Total Current Left Speed 100 -- 6866k 0 1 0 0:00:01 0:00:01 --:--:-- 4904k Download successful. tokens = tokenizer.encode("Hello, world!") print(tokens) [9707, 11, 1879, 0] tokenizer.decode(tokens) 'Hello, world!' ``` </blockquote> </blockquote> </blockquote> Shell: <code>bash bpe --encode "hello world"</code>
[ "https://github.com/allyourcodebase/boost-libraries-zig" ]
https://avatars.githubusercontent.com/u/146390816?v=4
curl
allyourcodebase/curl
2025-04-10T23:09:33Z
curl ported to the zig build system
master
0
4
0
4
https://api.github.com/repos/allyourcodebase/curl/tags
MIT
[ "zig", "zig-package" ]
17
false
2025-04-23T17:43:59Z
true
true
0.14.0
github
[ { "commit": "master", "name": "curl", "tar_url": "https://github.com/curl/curl/archive/master.tar.gz", "type": "remote", "url": "https://github.com/curl/curl" }, { "commit": "6c72830882690c1eb2567a537525c3f432c1da50", "name": "zlib", "tar_url": "https://github.com/allyourcodebase...
<a></a> curl This is <a>curl</a>, packaged for <a>Zig</a>. Installation <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> Curl depends on https://github.com/allyourcodebase/openssl which currently doesn't work on macOS. Consider using a different ssl implementation. </blockquote> Standalone library (libcurl) and command-line tool (curl) <code>bash git clone https://github.com/allyourcodebase/curl cd curl zig build -Doptimize=ReleaseFast</code> The library and CLI tool can be found in the newly created <code>./zig-out</code> directory. The <code>zig build run</code> build step may be used to directly run curl. Avoid system dependencies By default, curl requires some system dependencies that have not been ported to the zig build system yet. These dependencies may be either manually installed on the host system or disabled with the following build command: ```bash Windows zig build -Doptimize=ReleaseFast -Dlibpsl=false -Dlibssh2=false -Dlibidn2=false -Dnghttp2=false Posix zig build -Doptimize=ReleaseFast -Dlibpsl=false -Dlibssh2=false -Dlibidn2=false -Dnghttp2=false -Ddisable-ldap ``` Zig Build System First, update your <code>build.zig.zon</code>: ``` Initialize a <code>zig build</code> project if you haven't already zig init zig fetch --save git+https://github.com/allyourcodebase/curl.git ``` You can then import curl in your <code>build.zig</code> with: ```zig const curl_dependency = b.dependency("curl", .{ .target = target, .optimize = optimize, }); // A custom <code>artifact</code> function is provided because the build system // provides no way to differentiate between the library (libcurl) and // the command-line tool (curl) since they are both named "curl" in // the build system. // See https://github.com/ziglang/zig/issues/20377 const curlExe = @import("curl").artifact(curl_dependency, .exe); const libCurl = @import("curl").artifact(curl_dependency, .lib); your_exe.root_module.linkLibrary(libCurl); ``` Avoid system dependencies By default, curl requires some system dependencies that have not been ported to the zig build system yet. These dependencies may be either manually installed on the host system or disabled with the following change to the <code>build.zig</code>: <code>zig const curl_dependency = b.dependency("curl", .{ .target = target, .optimize = optimize, .libpsl = false, .libssh2 = false, .libidn2 = false, .nghttp2 = false, .@"disable-ldap" = true, });</code>
[ "https://github.com/allyourcodebase/curl", "https://github.com/allyourcodebase/kcov", "https://github.com/jiacai2050/zigcli", "https://github.com/lishaduck/zig-curl", "https://github.com/thislight/haiya" ]
https://avatars.githubusercontent.com/u/124872?v=4
zig-ipcrypt
jedisct1/zig-ipcrypt
2025-04-17T11:25:00Z
A Zig implementation of the IP address encryption and obfuscation methods specified in the ipcrypt document.
main
0
4
0
4
https://api.github.com/repos/jedisct1/zig-ipcrypt/tags
NOASSERTION
[ "address", "encryption", "ip", "ipcrypt", "ipcrypt2", "obfuscation", "zig", "zig-package" ]
10
false
2025-04-23T22:39:13Z
true
true
0.14.0
github
[]
zig-ipcrypt A Zig implementation of the IP address encryption and obfuscation methods specified in the <a>ipcrypt document</a> ("Methods for IP Address Encryption and Obfuscation"). Overview This library implements three variants of IP address encryption as specified in the ipcrypt draft: <ol> <li><strong>Deterministic</strong> (<code>Deterministic</code>): Format-preserving encryption using AES-128</li> <li><strong>Non-deterministic with KIASU-BC</strong> (<code>DeterministicNd</code>): Uses an 8-byte tweak</li> <li><strong>Non-deterministic with AES-XTS</strong> (<code>DeterministicNdx</code>): Uses a 16-byte tweak</li> </ol> Tradeoffs Each variant offers different tradeoffs between security, performance, and format preservation: Deterministic <ul> <li><strong>Pros</strong>:</li> <li>Format-preserving (output is a valid IP address)</li> <li>Smallest output size (16 bytes)</li> <li>Fastest performance (single AES-128 operation)</li> <li><strong>Cons</strong>:</li> <li>Reveals repeated inputs (same input always produces same output)</li> <li>No protection against correlation attacks</li> </ul> Non-deterministic with KIASU-BC <ul> <li><strong>Pros</strong>:</li> <li>Resists correlation attacks (same input produces different outputs)</li> <li>Moderate output size (24 bytes)</li> <li>Good performance (AES-128 with tweak modification)</li> <li><strong>Cons</strong>:</li> <li>Not format-preserving</li> <li>8-byte tweak has lower collision resistance than 16-byte tweak</li> <li>Birthday bound of 2^32 operations per (key,ip)</li> </ul> Non-deterministic with AES-XTS <ul> <li><strong>Pros</strong>:</li> <li>Resists correlation attacks</li> <li>Highest collision resistance (16-byte tweak)</li> <li>Birthday bound of 2^64 operations per (key,ip)</li> <li><strong>Cons</strong>:</li> <li>Not format-preserving</li> <li>Largest output size (32 bytes)</li> <li>Requires two AES-128 keys</li> <li>Slightly slower performance (two sequential AES operations)</li> </ul> Key and Tweak Sizes | Variant | Key Size | Tweak Size | Output Size | | ---------------- | ------------------------------------- | ------------------- | --------------------------------------------- | | Deterministic | 16 bytes (128 bits) | None | 16 bytes (format-preserving) | | DeterministicNd | 16 bytes (128 bits) | 8 bytes (64 bits) | 24 bytes (8-byte tweak + 16-byte ciphertext) | | DeterministicNdx | 32 bytes (256 bits, two AES-128 keys) | 16 bytes (128 bits) | 32 bytes (16-byte tweak + 16-byte ciphertext) | Usage Deterministic Encryption ```zig const ipcrypt = @import("ipcrypt"); // Initialize with a 16-byte key const key = [_]u8{0x2b} ** 16; const deterministic = ipcrypt.Deterministic.init(key); // Convert IP address to Ip16 format const ip = try ipcrypt.Ip16.fromString("192.0.2.1"); // Encrypt const encrypted = deterministic.encrypt(ip); // Decrypt const decrypted = deterministic.decrypt(encrypted); ``` Non-deterministic Encryption (KIASU-BC) ```zig const ipcrypt = @import("ipcrypt"); // Initialize with a 16-byte key const key = [_]u8{0x2b} ** 16; const nd = ipcrypt.DeterministicNd.init(key); // Convert IP address to Ip16 format const ip = try ipcrypt.Ip16.fromString("2001:db8::1"); // Encrypt with random tweak const encrypted = nd.encrypt(ip); // Encrypt with specific tweak const tweak = [_]u8{0x2b} ** 8; const encrypted_with_tweak = nd.encryptWithTweak(ip, tweak); // Decrypt const decrypted = nd.decrypt(encrypted); ``` Non-deterministic Encryption (AES-XTS) ```zig const ipcrypt = @import("ipcrypt"); // Initialize with a 32-byte key const key = [_]u8{0x2b} ** 32; const ndx = ipcrypt.DeterministicNdx.init(key); // Convert IP address to Ip16 format const ip = try ipcrypt.Ip16.fromString("2001:db8::1"); // Encrypt with random tweak const encrypted = ndx.encrypt(ip); // Encrypt with specific tweak const tweak = [_]u8{0x2b} ** 16; const encrypted_with_tweak = ndx.encryptWithTweak(ip, tweak); // Decrypt const decrypted = ndx.decrypt(encrypted); ``` Building Add this to your <code>build.zig.zon</code>: <code>zig .{ .name = "ipcrypt", .url = "https://github.com/yourusername/zig-ipcrypt/archive/refs/tags/v0.1.0.tar.gz", .hash = "1220...", }</code> Then in your <code>build.zig</code>: <code>zig const ipcrypt = b.dependency("ipcrypt", .{ .target = target, .optimize = optimize, }); exe.addModule("ipcrypt", ipcrypt.module("ipcrypt"));</code> License ISC License References <ul> <li><a>ipcrypt specification</a></li> <li><a>AES-128</a></li> <li><a>KIASU-BC</a></li> <li><a>AES-XTS</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/66087392?v=4
zsdl
mdmrk/zsdl
2025-02-12T18:38:59Z
SDL3 wrapper for Zig
main
1
4
1
4
https://api.github.com/repos/mdmrk/zsdl/tags
Zlib
[ "sdl3", "zig" ]
387
false
2025-04-30T15:53:27Z
true
true
0.14.0
github
[ { "commit": "dbb1b96360658f5845ff6fac380c4f13d7276dc2", "name": "sdl", "tar_url": "https://github.com/castholm/SDL/archive/dbb1b96360658f5845ff6fac380c4f13d7276dc2.tar.gz", "type": "remote", "url": "https://github.com/castholm/SDL" } ]
zsdl - SDL3 wrapper for Zig SDL3 wrapper for Zig 0.14.0 built on top of <a>castholm/SDL</a>'s Zig build system implementation for SDL. Check out the <a>documentation</a> for more info. Usage <code>sh zig fetch --save git+https://github.com/mdmrk/zsdl.git</code> <code>zig const zsdl = b.dependency("zsdl", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zsdl", zsdl.module("zsdl"));</code> Examples Simple event loop ```zig const std = @import("std"); const zsdl = @import("zsdl"); pub fn main() !void { try zsdl.init(.{ .video = true }); defer zsdl.quit(); const window = try zsdl.video.Window.create( "redbed", 1280, 720, .{ .resizable = true }, ); defer window.destroy(); main_loop: while (true) { while (zsdl.events.pollEvent()) |event| { switch (event) { .quit =&gt; { break :main_loop; }, .window_resized =&gt; |wr| { std.debug.print( "window resized: (w: {any}, h: {any})\n", .{ wr.size.width, wr.size.height }, ); }, else =&gt; {}, } } } } ``` GPU Spinning Cube ```zig const zsdl = @import("zsdl"); const std = @import("std"); const gpu = zsdl.gpu; const video = zsdl.video; const math = std.math; pub fn rotateMatrix(angle: f32, x: f32, y: f32, z: f32, result: *[16]f32) void { const radians = angle * math.pi / 180.0; const c = @cos(radians); const s = @sin(radians); const c1 = 1.0 - c; const length = @sqrt(x * x + y * y + z * z); const u = [3]f32{ x / length, y / length, z / length, }; // Zero the matrix first for (result) |*val| { val.* = 0.0; } result[15] = 1.0; // Set up rotation matrix for (0..3) |i| { result[i * 4 + ((i + 1) % 3)] = u[(i + 2) % 3] * s; result[i * 4 + ((i + 2) % 3)] = -u[(i + 1) % 3] * s; } for (0..3) |i| { for (0..3) |j| { result[i * 4 + j] += c1 * u[i] * u[j] + (if (i == j) c else 0.0); } } } pub fn perspectiveMatrix(fovy: f32, aspect: f32, znear: f32, zfar: f32, result: *[16]f32) void { const f = 1.0 / @tan(fovy * 0.5); // Zero the matrix first for (result) |*val| { val.* = 0.0; } result[0] = f / aspect; result[5] = f; result[10] = (znear + zfar) / (znear - zfar); result[11] = -1.0; result[14] = (2.0 * znear * zfar) / (znear - zfar); result[15] = 0.0; } pub fn multiplyMatrix(lhs: *const [16]f32, rhs: *const [16]f32, result: *[16]f32) void { var tmp: [16]f32 = undefined; for (0..4) |i| { for (0..4) |j| { tmp[j * 4 + i] = 0.0; for (0..4) |k| { tmp[j * 4 + i] += lhs[k * 4 + i] * rhs[j * 4 + k]; } } } // Copy result for (0..16) |i| { result[i] = tmp[i]; } } pub fn translateMatrix(matrix: *[16]f32, x: f32, y: f32, z: f32) void { matrix[12] += x; matrix[13] += y; matrix[14] += z; } pub fn main() !void { const Vertex = extern struct { pos: [3]f32, color: [3]f32, }; const vertices = [_]Vertex{ .{ .pos = .{ -0.5, 0.5, -0.5 }, .color = .{ 1.0, 0.0, 0.0 } }, .{ .pos = .{ 0.5, -0.5, -0.5 }, .color = .{ 0.0, 0.0, 1.0 } }, .{ .pos = .{ -0.5, -0.5, -0.5 }, .color = .{ 0.0, 1.0, 0.0 } }, .{ .pos = .{ -0.5, 0.5, -0.5 }, .color = .{ 1.0, 0.0, 0.0 } }, .{ .pos = .{ 0.5, 0.5, -0.5 }, .color = .{ 1.0, 1.0, 0.0 } }, .{ .pos = .{ 0.5, -0.5, -0.5 }, .color = .{ 0.0, 0.0, 1.0 } }, .{ .pos = .{ -0.5, 0.5, 0.5 }, .color = .{ 1.0, 1.0, 1.0 } }, .{ .pos = .{ -0.5, -0.5, -0.5 }, .color = .{ 0.0, 1.0, 0.0 } }, .{ .pos = .{ -0.5, -0.5, 0.5 }, .color = .{ 0.0, 1.0, 1.0 } }, .{ .pos = .{ -0.5, 0.5, 0.5 }, .color = .{ 1.0, 1.0, 1.0 } }, .{ .pos = .{ -0.5, 0.5, -0.5 }, .color = .{ 1.0, 0.0, 0.0 } }, .{ .pos = .{ -0.5, -0.5, -0.5 }, .color = .{ 0.0, 1.0, 0.0 } }, .{ .pos = .{ -0.5, 0.5, 0.5 }, .color = .{ 1.0, 1.0, 1.0 } }, .{ .pos = .{ 0.5, 0.5, -0.5 }, .color = .{ 1.0, 1.0, 0.0 } }, .{ .pos = .{ -0.5, 0.5, -0.5 }, .color = .{ 1.0, 0.0, 0.0 } }, .{ .pos = .{ -0.5, 0.5, 0.5 }, .color = .{ 1.0, 1.0, 1.0 } }, .{ .pos = .{ 0.5, 0.5, 0.5 }, .color = .{ 0.0, 0.0, 0.0 } }, .{ .pos = .{ 0.5, 0.5, -0.5 }, .color = .{ 1.0, 1.0, 0.0 } }, .{ .pos = .{ 0.5, 0.5, -0.5 }, .color = .{ 1.0, 1.0, 0.0 } }, .{ .pos = .{ 0.5, -0.5, 0.5 }, .color = .{ 1.0, 0.0, 1.0 } }, .{ .pos = .{ 0.5, -0.5, -0.5 }, .color = .{ 0.0, 0.0, 1.0 } }, .{ .pos = .{ 0.5, 0.5, -0.5 }, .color = .{ 1.0, 1.0, 0.0 } }, .{ .pos = .{ 0.5, 0.5, 0.5 }, .color = .{ 0.0, 0.0, 0.0 } }, .{ .pos = .{ 0.5, -0.5, 0.5 }, .color = .{ 1.0, 0.0, 1.0 } }, .{ .pos = .{ 0.5, 0.5, 0.5 }, .color = .{ 0.0, 0.0, 0.0 } }, .{ .pos = .{ -0.5, -0.5, 0.5 }, .color = .{ 0.0, 1.0, 1.0 } }, .{ .pos = .{ 0.5, -0.5, 0.5 }, .color = .{ 1.0, 0.0, 1.0 } }, .{ .pos = .{ 0.5, 0.5, 0.5 }, .color = .{ 0.0, 0.0, 0.0 } }, .{ .pos = .{ -0.5, 0.5, 0.5 }, .color = .{ 1.0, 1.0, 1.0 } }, .{ .pos = .{ -0.5, -0.5, 0.5 }, .color = .{ 0.0, 1.0, 1.0 } }, .{ .pos = .{ -0.5, -0.5, -0.5 }, .color = .{ 0.0, 1.0, 0.0 } }, .{ .pos = .{ 0.5, -0.5, 0.5 }, .color = .{ 1.0, 0.0, 1.0 } }, .{ .pos = .{ -0.5, -0.5, 0.5 }, .color = .{ 0.0, 1.0, 1.0 } }, .{ .pos = .{ -0.5, -0.5, -0.5 }, .color = .{ 0.0, 1.0, 0.0 } }, .{ .pos = .{ 0.5, -0.5, -0.5 }, .color = .{ 0.0, 0.0, 1.0 } }, .{ .pos = .{ 0.5, -0.5, 0.5 }, .color = .{ 1.0, 0.0, 1.0 } }, }; const vertex_shader_source = [_]u8{ 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x08, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x6f, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x69, 0x6e, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00, 0x16, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x65, 0x72, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x06, 0x00, 0x07, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x69, 0x6e, 0x74, 0x53, 0x69, 0x7a, 0x65, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x07, 0x00, 0x16, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x43, 0x6c, 0x69, 0x70, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x00, 0x06, 0x00, 0x07, 0x00, 0x16, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x43, 0x75, 0x6c, 0x6c, 0x44, 0x69, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x00, 0x05, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x55, 0x42, 0x4f, 0x00, 0x06, 0x00, 0x07, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x56, 0x69, 0x65, 0x77, 0x50, 0x72, 0x6f, 0x6a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x22, 0x00, 0x00, 0x00, 0x69, 0x6e, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x00, 0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x16, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x16, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x16, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x16, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x48, 0x00, 0x04, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x22, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f, 0x15, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x06, 0x00, 0x16, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x17, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00, 0x19, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x19, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x04, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x51, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x50, 0x00, 0x07, 0x00, 0x07, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x91, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x08, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x29, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 }; const fragment_shader_source = [_]u8{ 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x08, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x07, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0xc2, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x6f, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x69, 0x6e, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 }; try zsdl.init(.{ .video = true }); defer zsdl.quit(); const window = try video.Window.create( "Spinning Cube", 600, 400, .{}, ); defer window.destroy(); const device = try gpu.Device.create( .{ .spirv = true }, true, null, ); defer device.destroy(); try device.claimWindow(window); defer device.releaseWindow(window); const vertex_shader = try device.createShader(.{ .code = &amp;vertex_shader_source, .entrypoint = "main", .format = .{ .spirv = true }, .stage = .vertex, .num_samplers = 0, .num_storage_textures = 0, .num_storage_buffers = 0, .num_uniform_buffers = 1, }); defer device.releaseShader(vertex_shader); const fragment_shader = try device.createShader(.{ .code = &amp;fragment_shader_source, .entrypoint = "main", .format = .{ .spirv = true }, .stage = .fragment, .num_samplers = 0, .num_storage_textures = 0, .num_storage_buffers = 0, .num_uniform_buffers = 0, }); defer device.releaseShader(fragment_shader); const vertex_buffer = try device.createBuffer(.{ .size = @sizeOf(@TypeOf(vertices)), .usage = .{ .vertex = true, }, }); defer device.releaseBuffer(vertex_buffer); const transfer_buffer = try device.createTransferBuffer(.{ .size = @sizeOf(@TypeOf(vertices)), .usage = .upload, }); const map_tb: [*]u8 = @ptrCast(try device.mapTransferBuffer(transfer_buffer, false)); @memcpy(map_tb[0..@sizeOf(@TypeOf(vertices))], std.mem.asBytes(&amp;vertices)); device.unmapTransferBuffer(transfer_buffer); var cmd_buffer = try device.acquireCommandBuffer(); const copy_pass = try cmd_buffer.beginCopyPass(); const buf_location: gpu.TransferBufferLocation = .{ .transfer_buffer = transfer_buffer, .offset = 0, }; copy_pass.uploadToBuffer(&amp;buf_location, &amp;.{ .buffer = vertex_buffer, .offset = 0, .size = @sizeOf(@TypeOf(vertices)), }, false); copy_pass.end(); try cmd_buffer.submit(); device.releaseTransferBuffer(transfer_buffer); const pipeline = try device.createGraphicsPipeline(.{ .vertex_shader = vertex_shader, .fragment_shader = fragment_shader, .vertex_input_state = .{ .vertex_buffer_descriptions = &amp;[_]gpu.VertexBufferDescription{ .{ .slot = 0, .pitch = @sizeOf(Vertex), .input_rate = .vertex, .instance_step_rate = 0, }, }, .vertex_attributes = &amp;[_]gpu.VertexAttribute{ .{ .location = 0, .buffer_slot = 0, .format = .float3, .offset = @offsetOf(Vertex, "pos"), }, .{ .location = 1, .buffer_slot = 0, .format = .float3, .offset = @offsetOf(Vertex, "color"), }, }, }, .primitive_type = .triangle_list, .multisample_state = .{ .sample_count = .@"1", }, .depth_stencil_state = .{ .compare_op = .less_or_equal, .enable_depth_write = true, .enable_depth_test = true, }, .target_info = .{ .color_target_descriptions = &amp;[_]gpu.ColorTargetDescription{ .{ .format = device.getSwapchainTextureFormat(window), }, }, .depth_stencil_format = .d16_unorm, .has_depth_stencil_target = true, }, }); defer device.releaseGraphicsPipeline(pipeline); const window_size = try window.getSizeInPixels(); const depth_texture = try device.createTexture(.{ .type = .@"2d", .format = .d16_unorm, .width = @intCast(window_size.width), .height = @intCast(window_size.height), .layer_count_or_depth = 1, .num_levels = 1, .sample_count = .@"1", .usage = .{ .depth_stencil_target = true }, .props = 0, }); defer device.releaseTexture(depth_texture); const msaa_texture = try device.createTexture(.{ .type = .@"2d", .format = device.getSwapchainTextureFormat(window), .width = @intCast(window_size.width), .height = @intCast(window_size.height), .layer_count_or_depth = 1, .num_levels = 1, .sample_count = .@"1", .usage = .{ .color_target = true }, .props = 0, }); defer device.releaseTexture(msaa_texture); const resolve_texture = try device.createTexture(.{ .type = .@"2d", .format = device.getSwapchainTextureFormat(window), .width = @intCast(window_size.width), .height = @intCast(window_size.height), .layer_count_or_depth = 1, .num_levels = 1, .sample_count = .@"1", .usage = .{ .color_target = true, .sampler = true }, .props = 0, }); defer device.releaseTexture(resolve_texture); var angle_x: f32 = 0.0; var angle_y: f32 = 0.0; var angle_z: f32 = 0.0; main_loop: while (true) { while (zsdl.events.pollEvent()) |event| { switch (event) { .quit =&gt; { break :main_loop; }, else =&gt; {}, } } cmd_buffer = try device.acquireCommandBuffer(); var swapchain_tex_size_w: u32 = undefined; var swapchain_tex_size_h: u32 = undefined; const swapchain_tex = try cmd_buffer.waitAndAcquireSwapchainTexture(window, &amp;swapchain_tex_size_w, &amp;swapchain_tex_size_h); const color_target: gpu.ColorTargetInfo = .{ .texture = swapchain_tex, .load_op = .clear, .store_op = .store, }; const depth_target: gpu.DepthStencilTargetInfo = .{ .clear_depth = 1, .load_op = .clear, .store_op = .dont_care, .stencil_load_op = .dont_care, .stencil_store_op = .dont_care, .texture = depth_texture, .cycle = true, }; const vertex_binding: gpu.BufferBinding = .{ .buffer = vertex_buffer, .offset = 0, }; var matrix_rotate: [16]f32 = undefined; var matrix_modelview: [16]f32 = undefined; var matrix_perspective: [16]f32 = undefined; var matrix_final: [16]f32 = undefined; rotateMatrix(angle_x, 1.0, 0.0, 0.0, &amp;matrix_modelview); // Rotate around Y axis rotateMatrix(angle_y, 0.0, 1.0, 0.0, &amp;matrix_rotate); multiplyMatrix(&amp;matrix_rotate, &amp;matrix_modelview, &amp;matrix_modelview); // Rotate around Z axis rotateMatrix(angle_z, 0.0, 0.0, 1.0, &amp;matrix_rotate); multiplyMatrix(&amp;matrix_rotate, &amp;matrix_modelview, &amp;matrix_modelview); // Pull the camera back from the cube translateMatrix(&amp;matrix_modelview, 0.0, 0.0, -2.5); // Create perspective projection const aspect = @as(f32, @floatFromInt(swapchain_tex_size_w)) / @as(f32, @floatFromInt(swapchain_tex_size_h)); perspectiveMatrix(45.0, aspect, 0.01, 100.0, &amp;matrix_perspective); // Combine modelview and perspective matrices multiplyMatrix(&amp;matrix_perspective, &amp;matrix_modelview, &amp;matrix_final); // Update angles for animation angle_x += 3.0; angle_y += 2.0; angle_z += 1.0; // Keep angles in 0-360 range angle_x = @mod(angle_x, 360.0); angle_y = @mod(angle_y, 360.0); angle_z = @mod(angle_z, 360.0); cmd_buffer.pushVertexUniformData(0, &amp;matrix_final, @sizeOf(@TypeOf(matrix_final))); const render_pass = try cmd_buffer.beginRenderPass(&amp;.{color_target}, &amp;depth_target); render_pass.bindGraphicsPipeline(pipeline); render_pass.bindVertexBuffers(0, &amp;.{vertex_binding}); render_pass.drawPrimitives(vertices.len, 1, 0, 0); render_pass.end(); try cmd_buffer.submit(); } } ``` Support | Category | Status | Category | Status | Category | Status | |:-|:-:|:-|:-:|:-|:-:| | Init | ✅ | Camera | ✅ | Hints | ❌ | | Properties | ❌ | Log | ✅ | Video | ✅ | | Events | ✅ | Keyboard | ✅ | Mouse | ✅ | | Touch | ✅ | Gamepad | ✅ | Joystick | ✅ | | Haptic | ✅ | Audio | ✅ | Gpu | ✅ | | Clipboard | ✅ | Dialog | ✅ | Filesystem | ❌ | | Iostream | ❌ | Atomic | ❌ | Time | ❌ | | Timer | ✅ | Render | ✅ | Pixels | ✅ | | Surface | ✅ | Platform | ❌ | Misc | ❌ | | Main | ❌ | Strings | ❌ | CPU | ❌ | | Intrinsics | ❌ | Locale | ❌ | System | ❌ | | Metal | ❌ | Vulkan | ❌ | Rect | ✅ | Legend: - ✅ Fully implemented - 🧪 Partially implemented/experimental - ❌ Not implemented Supported targets Refer to <a>supported targets</a>.
[ "https://github.com/zig-gamedev/zgui", "https://github.com/zig-gamedev/zig-gamedev" ]
https://avatars.githubusercontent.com/u/60631511?v=4
microwave
edqx/microwave
2025-04-14T18:34:39Z
TOML Parser for Zig.
master
0
4
0
4
https://api.github.com/repos/edqx/microwave/tags
MIT
[ "config", "household-appliance", "toml", "zig", "zig-package" ]
221
false
2025-05-18T23:52:00Z
true
true
unknown
github
[]
Microwave A TOML parser for <a>Zig</a>. This parser should be spec compliant. 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> Parse all spec-compliant TOML documents. - WIP: parses all valid TOML files, but also parses some invalid ones, see <a>Spec Compliancy</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> Use Zig readers and writers <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> Populate structs <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> Populate dynamic values <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> TOML builder/write stream <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> Stringify entire structs and tables TODO These features are yet to be implemented, and are actively being worked on, in order of severity: - Check files for invalid control sequences and characters - Fix parsing issues related to keys and tables being re-defined - Check integer literals against the spec (leading zeroes are currently allowed) Usage Microwave has 5 sets of APIs: - <a>Parser API</a> - for parsing an entire TOML file into a tree-like structure - <a>Populate API</a> - for mapping a TOML file into a given struct - <a>Stringify API</a> - for writing TOML files from a tree or given struct - <a>Write Stream API</a> - for building TOML files safely with debug assertions - <a>Tokeniser/Scanner API</a> - for iterating through a TOML file for each significant token Parser API Microwave allows you to parse an entire TOML file from either a slice or reader into a tree-like structure that can be traversed, inspected or modified manually. From Slice ```zig const document = try microwave.parse.fromSlice(allocator, toml_text); defer document.deinit(); // all pointers will be freed using the created internal arena // use document.root_table ``` From Reader ```zig const document = try microwave.parse.fromReader(allocator, file.reader()); defer document.deinit(); // use document.root_table ``` Owned Allocations API If you would like to personally own all of the pointers without creating an arena for them, use the <code>*Owned</code> variation of the functions. These return a <code>parse.Value.Table</code> directly, representing the root table of the TOML file. The best way to free the resulting root table is to use <code>parse.deinitTable</code>. ```zig var owned_tree = try microwave.parse.fromSliceOwned(allocator, toml_text); // or .fromReaderOwned defer microwave.parse.deinitTable(allocator, &amp;owned_tree); // use owned_tree ``` Value API ```zig pub const Value = union(enum) { pub const Table = std.StringArrayHashMapUnmanaged(Value); pub const Array = std.ArrayListUnmanaged(Value); pub const ArrayOfTables = std.ArrayListUnmanaged(Table); <code>pub const DateTime = struct { date: ?[]const u8 = null, time: ?[]const u8 = null, offset: ?[]const u8 = null, pub fn dupe(self: DateTime, allocator: std.mem.Allocator) !DateTime; pub fn deinit(self: DateTime, allocator: std.mem.Allocator) ; }; none: void, table: Table, array: Array, array_of_tables: ArrayOfTables, string: []const u8, integer: i64, float: f64, boolean: bool, date_time: DateTime, pub fn dupeRecursive(self: Value, allocator: std.mem.Allocator) !Value; pub fn deinitRecursive(self: *Value, allocator: std.mem.Allocator) void; </code> }; ``` Populate API It's often helpful to map a TOML file directly onto a Zig struct, for example for config files. Microwave lets you do this using the <code>Populate(T)</code> API: ```zig const Dog = struct { pub const Friend = struct { name: []const u8, }; <code>name: []const u8, cross_breeds: []const []const u8, age: i64, friends: []Friend, vet_info: microwave.parse.Value.Table, </code> } const dog = try microwave.Populate(Dog).createFromSlice(allocator, toml_text); // or .createFromReader defer dog.deinit(); ``` Struct Shape Since TOML only supports a subset of the types that are available in Zig, your destination struct must consist of the following types: | TOML Type | Zig Type | Examples | |-|-|-| | String | <code>[]const u8</code> | <code>"Barney"</code> | | Float | <code>f64</code> | <code>5.0e+2</code> | | Integer | <code>i64</code>, <code>f64</code> | <code>16</code> | | Boolean | <code>bool</code> | <code>true</code>, <code>false</code> | | Date/Time | <code>parse.Value.DateTime</code> | <code>2025-04-19T00:43:00.500+05:00</code> | | Specific Table | <code>struct { ... }</code> | <code>{ name = "Barney", age = 16 }</code> | | Array of Tables | <code>[]struct {}</code> | <code>[[pet]]</code> | | Inline Array | <code>[]T</code> | <code>["Hello", "Bonjour", "Hola"]</code> | | Any Table | <code>parse.Value.Table</code> | Any TOML table | | Any Value | <code>parse.Value</code> | Any TOML value | You can also specify an option of different types using unions. For example: ```zig const Animal = union(enum) { dog: struct { name: []const u8, breed: []const u8, }, cat: struct { name: []const u8, number_of_colours: usize, }, }; const animal = try microwave.Populate(Animal).createFromSlice(allocator, toml_text); defer animal.deinit(); ``` If the field is entirely optional and may not exist, use the Zig optional indiciator on the type, for example: ```zig const Person = struct { name: []const u8, age: i64, salary: f64, job: ?[]const u8, // can be missing from the TOML file }; const person = try microwave.Populate(Person).createFromSlice(allocator, toml_text); defer person.deinit(); ``` Owned Allocations API Like the parser API, you might want to own the pointers yourself rather than delegate them to an arena. You can use the <code>*Owned</code> variations of the functions. These return the value directly. You can free the data in the returned value however you want, but if you're using an stack-based allocator like arena or fixed buffer allocator, then it's best to use <code>Populate(T).deinitRecursive</code>. <code>zig var dog = try microwave.Populate(Dog).createFromSliceOwned(allocator, toml_text); defer microwave.Populate(Dog).deinitRecursive(allocator, &amp;dog);</code> 'Into' API Instead of making Microwave create the value to populate, you can provide it with a pointer to an existing one to populate using the <code>into*</code> functions: <code>zig var dog: Dog = undefined; try microwave.Populate(Dog).intoFromSliceOwned(allocator, &amp;dog); // or .intoFromReaderOwned defer microwave.Populate(Dog).deinitRecursive(allocator, &amp;dog);</code> Stringify API Microwave can try its best to serialise a given struct value or <code>parse.Value.Table</code> into a writer: <code>zig try microwave.stringify.write(allocator, dog, file.writer());</code> <code>zig try microwave.stringify.writeTable(allocator, root_table, file.writer());</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> There's no need to de-init anything, the allocator is for temporary allocations. </blockquote> Write Stream API You can build a TOML file manually, with safety assertions that the file is well-formed, using the write stream API: <code>zig var stream: microwave.write_stream.Stream(@TypeOf(file.writer()), .{ .newlines = .lf, unicode_full_escape_strings = false, format_float_options = .{ .mode = .scientific, .precision = null, }, date_time_separator = .t, }) = .{ .underlying_writer = file.writer(), .allocator = allocator, }; defer stream.deinit();</code> You can use the following functions on the <code>write_stream.Stream</code> struct to build your TOML file: ```zig pub fn beginDeepKeyPair(self: <em>Stream, key_parts: []const []const u8) !void; pub fn beginKeyPair(self: </em>Stream, key_name: []const u8) !void; pub fn writeString(self: <em>Stream, string: []const u8) !void; pub fn writeInteger(self: </em>Stream, integer: i64) !void; pub fn writeFloat(self: <em>Stream, float: f64) !void; pub fn writeBoolean(self: </em>Stream, boolean: bool) !void; pub fn writeDateTime(self: *Stream, date_time: parse.Value.DateTime) !void; pub fn beginArray(self: <em>Stream) !void; pub fn arrayLine(self: </em>Stream) !void; pub fn endArray(self: *Stream) !void; pub fn beginInlineTable(self: <em>Stream) !void; pub fn endInlineTable(self: </em>Stream) !void; pub fn writeDeepTable(self: <em>Stream, key_parts: []const []const u8) !void; pub fn writeTable(self: </em>Stream, key_name: []const u8) !void; pub fn writeDeepManyTable(self: <em>Stream, key_parts: []const []const u8) !void; pub fn writeManyTable(self: </em>Stream, key_name: []const u8) !void; ``` Scanner API As a low level API, Microwave also provides the ability to scan through a file and iterate through individual tokens. Only basic state checks are done at this stage, and that state you have to manage yourself. It doesn't guarantee a well-formed TOML file. Most of those checks are done in the <a>parsing stage</a>. Whole Slice Scanner If you have access to the entire slice of the TOML file, you can initialise the scanner directly: ```zig var scanner: microwave.Scanner = .{ .buffer = slice }; while (try scanner.next()) |token| { // token.kind, token.range.start, token.range.end <code>// modify state with scanner.setState(state) </code> } ``` The default scanner may return any of the following errors: <code>zig pub const Error = error{ UnexpectedEndOfBuffer, UnexpectedByte };</code> Buffered Reader Scanner You can also tokenise the TOML file using a reader: ```zig var scanner = microwave.Scanner.bufferedReaderScanner(file.reader()); // use scanner.next() in the same way ``` The buffered reader scanner may return any of the following errors: <code>zig pub const Error = error{ UnexpectedEndOfBuffer, UnexpectedByte, BufferTooSmall };</code> Managing State A TOML file can be tokenised differently depending on what kind of entities need to be read. The scanner API doesn't manage this for you, but with your own reading logic you can update the state of the scanner using the <code>scanner.setState</code> function: <code>zig while (try scanner.next()) |token| { if (token.kind == .table_start) { scanner.setState(.table_key); } if (token.kind == .table_end) { scanner.setState(.root); } }</code> The valid states are listed below: | State Name | Enum Value | Description | |-|-|-| | Root | <code>.root</code> | Either ordinary newline-separated keys, or [table] and [[many table]] structures | | Table Key | <code>.table_key</code> | The keys inside [ .. ] and [[ ... ]] | | Inline Key | <code>.inline_key</code> | Delimeter-separated inline table keys | | Value | <code>.value</code> | An ordinary value literal, array or inline table opening token | | Array Container | <code>.array_container</code> | Same as <code>.value</code>, but can process array close tokens and value delimeters | The default state is <code>.root</code>. Handling Errors When encountering an error, you can use <code>scanner.cursor()</code> to get the file offset that it occurred at. If you encounter <code>error.BufferTooSmall</code> while using the buffered reader scanner, you can increase the size of the buffer for your project by instantiating <code>Scanner.BufferedReaderScanner</code> directly: <code>zig var scanner = microwave.Scanner.BufferedReaderScanner(8192, @TypeOf(file.reader())) = .{ .reader = file.reader(), };</code> Token Contents To access the contents of a token, you can use the <code>scanner.tokenContents</code> function: <code>zig while (try scanner.next()) |token| { if (token.kind == .string) { std.log.info("Found string! {s}", .{ scanner.tokenContents(token) }); } }</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> For the buffered reader scanner, previous token contents may be invalidated at any point while iterating. </blockquote> Related Projects Check out my other project, <a>dishwasher</a> for parsing XML files. Why 'Microwave'? Not sure. Spec Compliancy See the <a>tests</a> folder to check Microwave against the various official TOML test cases. All failed tests are false positives, which means Microwave can read all valid TOML files, but can also read many invalid ones too. <code>- fail: invalid/control/bare-cr.toml - fail: invalid/control/comment-cr.toml - fail: invalid/control/comment-del.toml - fail: invalid/control/comment-ff.toml - fail: invalid/control/comment-lf.toml - fail: invalid/control/comment-null.toml - fail: invalid/control/comment-us.toml - fail: invalid/control/multi-cr.toml - fail: invalid/control/multi-del.toml - fail: invalid/control/multi-lf.toml - fail: invalid/control/multi-null.toml - fail: invalid/control/multi-us.toml - fail: invalid/control/rawmulti-cr.toml - fail: invalid/control/rawmulti-del.toml - fail: invalid/control/rawmulti-lf.toml - fail: invalid/control/rawmulti-null.toml - fail: invalid/control/rawmulti-us.toml - fail: invalid/encoding/bad-codepoint.toml - fail: invalid/encoding/bad-utf8-in-comment.toml - fail: invalid/encoding/bad-utf8-in-multiline-literal.toml - fail: invalid/encoding/bad-utf8-in-string-literal.toml - fail: invalid/float/leading-zero.toml - fail: invalid/float/leading-zero-neg.toml - fail: invalid/float/leading-zero-plus.toml - fail: invalid/inline-table/duplicate-key-3.toml - fail: invalid/inline-table/overwrite-02.toml - fail: invalid/inline-table/overwrite-05.toml - fail: invalid/inline-table/overwrite-08.toml - fail: invalid/integer/leading-zero-1.toml - fail: invalid/integer/leading-zero-2.toml - fail: invalid/integer/leading-zero-3.toml - fail: invalid/integer/leading-zero-sign-1.toml - fail: invalid/integer/leading-zero-sign-2.toml - fail: invalid/integer/leading-zero-sign-3.toml - fail: invalid/spec/inline-table-2-0.toml - fail: invalid/spec/table-9-0.toml - fail: invalid/spec/table-9-1.toml - fail: invalid/table/append-with-dotted-keys-1.toml - fail: invalid/table/append-with-dotted-keys-2.toml - fail: invalid/table/duplicate.toml - fail: invalid/table/duplicate-key-dotted-table.toml - fail: invalid/table/duplicate-key-dotted-table2.toml - fail: invalid/table/redefine-2.toml - fail: invalid/table/redefine-3.toml - fail: invalid/table/super-twice.toml passing: 512/557</code> License All microwave code is under the MIT license.
[ "https://github.com/GasFurr/B3T" ]
https://avatars.githubusercontent.com/u/35976402?v=4
fancy-cat-nix
freref/fancy-cat-nix
2025-02-20T09:51:24Z
Nix package for fancy-cat
master
0
3
1
3
https://api.github.com/repos/freref/fancy-cat-nix/tags
-
[ "zig", "zig-package" ]
10
false
2025-05-05T18:12:05Z
false
false
unknown
github
[]
fancy-cat-nix <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 fork, you can find the original repo by @AaronVerDow <a>here</a>. This nix flake is community-maintained and provided as-is without warranty or official support. </blockquote> Package <a>fancy-cat</a> for use in Nix. This directory can be included in a Nix config as a package using <code>callPackage</code>. The flake is used for building the package in a local shell and can be tested with <code>nix shell</code>. <code>build.zig.zon.nix</code> is created by running <code>nix run github:Cloudef/zig2nix#zon2nix -- build.zig.zon</code> in the source repo.
[]
https://avatars.githubusercontent.com/u/6756180?v=4
zcc-d
kassane/zcc-d
2025-05-13T17:32:29Z
D library for build scripts to compile C/C++ code using zig toolchain
main
1
3
0
3
https://api.github.com/repos/kassane/zcc-d/tags
MIT
[ "cross-compile", "d", "dlang", "zig" ]
24
false
2025-05-20T17:05:46Z
false
false
unknown
github
[]
zcc-d <a></a> <a></a> <a></a> A D library for building C/C++ code using Zig as a cross-compilation toolchain, inspired by <a>cc-rs</a> and <a>cargo-zigbuild</a>. Features <ul> <li>Cross-compilation support via Zig's C/C++ compiler</li> <li>Target triple and CPU architecture configuration</li> <li>Automatic C++ mode detection based on file extensions</li> <li>Flag transformation and filtering</li> <li>Build output logging</li> <li>Exception handling for build failures</li> </ul> Requirements <ul> <li><a>D compiler</a></li> <li><a>Zig compiler</a></li> <li><a>dub</a> or <a>redub</a> package manager</li> </ul> Installation <code>bash dub add zcc</code> Usage <strong>library</strong> ```d // Compile C/C++ code auto b = new Builder(); // Use <code>zig cc</code> or <code>zig c++</code> b.file("source.cpp") // Auto-detects C++ mode .setTargetTriple("aarch64-linux-gnu") .setCpu("generic") .addArg("-Wall") .execute(); // Build library auto lb = new Builder(); // use <code>zig build-lib -lc</code> or <code>zig build-lib -lc++</code> lb.files(["source.cpp", "resource.cc"]) // Auto-detects C++ mode .setTargetTriple("riscv64-linux-gnu") .setCpu("baseline") .addArg("-Wall") .buildLibrary("libname"); ``` See more in <a>samples</a>. <strong>executable</strong> <code>console dub run zcc:cc -- &lt;clang-flags&gt; &lt;source-files&gt;</code> Contributing Contributions are welcome! Please open an issue or submit a pull request.
[]
https://avatars.githubusercontent.com/u/60502183?v=4
chdb-zig
s0und0fs1lence/chdb-zig
2025-03-26T22:40:21Z
Zig wrapper for chdb
main
0
3
0
3
https://api.github.com/repos/s0und0fs1lence/chdb-zig/tags
Apache-2.0
[ "chdb", "clickhouse", "sql", "zig" ]
3,401
false
2025-04-14T13:30:12Z
true
true
0.14.0
github
[]
chdb-zig A Zig wrapper for <a>chdb</a> - the embedded ClickHouse database. This library provides a safe, efficient, and ergonomic way to interact with chdb using Zig's powerful type system and memory safety features. Features <ul> <li>🛡️ Base sql interpolation function to be able to pass arguments to query</li> <li>🚀 Zero-allocation query building where possible</li> <li>🎯 Type-safe query parameter interpolation</li> <li>📦 Native Zig implementation</li> <li>⚡ Direct chdb integration</li> </ul> Usage ```zig const std = @import("std"); const chdb = @import("chdb"); pub fn main() !void { const allocator = std.heap.page_allocator; <code>const conn = chdb.ChConn.init(alloc, ":memory:") catch |err| { std.debug.print("Error: {}\n", .{err}); return err; }; defer conn.deinit(); var result = try conn.exec(@constCast("CREATE TABLE test (id Int32) engine=MergeTree() order by id;"), .{}); std.debug.print("{d}\n", .{result.affectedRows()}); result = try conn.exec(@constCast("INSERT INTO test values ({i}),({i}),({i})"), .{1,2,3}); std.debug.print("{d}\n", .{result.affectedRows()}); const res = try conn.query(@constCast("select * from test"), .{}); while (res.next()) |row| { const columns = row.columns(); for (columns) |column| { std.debug.print("{s}\n", .{column}); } const val: ?i64 = row.get(i64, "id"); std.debug.print("{d}\n", .{val.?}); } </code> } ``` Installation Coming soon! Features SQL Interpolation <ul> <li>Type-safe parameter binding</li> <li>Protection against SQL injection (very basic and not a replacement for proper sanitization)</li> <li>Support for:</li> <li>Strings (escaped)</li> <li>Integers (signed/unsigned)</li> <li>Floats</li> <li>Dates and DateTimes</li> <li>Arrays</li> <li>Boolean values</li> <li>NULL values</li> </ul> Contributing Contributions are welcome! Please feel free to submit a Pull Request. License This project is licensed under the Apache License, Version 2.0 - see the <a>LICENSE</a> file for details.
[]
https://avatars.githubusercontent.com/u/71296243?v=4
SysInput
PeterM45/SysInput
2025-03-22T22:18:00Z
A system-wide autocomplete and spell-checking utility for Windows written in Zig.
main
0
3
0
3
https://api.github.com/repos/PeterM45/SysInput/tags
MIT
[ "accessibility", "autocomplete", "keyboard-hook", "open-source", "productivity", "spellcheck", "text-completion", "text-editor", "text-suggestions", "utility", "win32-api", "windows", "zig" ]
3,430
false
2025-05-21T02:10:50Z
true
true
0.14.0
github
[]
SysInput <strong>SysInput</strong> is a lightweight Windows utility written in <a>Zig</a>. It provides system-wide autocomplete and spell checking across all applications by capturing keystrokes and displaying suggestions near your cursor. Demo Features <ul> <li><strong>System-wide suggestions:</strong> Works in any standard text field.</li> <li><strong>Intelligent autocomplete:</strong> Learns from your typing.</li> <li><strong>Low resource usage:</strong> Efficiently built in Zig ⚡</li> <li><strong>Adaptive learning:</strong> Optimizes insertion methods per application</li> </ul> Installation Prerequisites <ul> <li>Windows 10 or 11</li> <li><a>Zig 0.14.0</a> (or later)</li> </ul> Building from Source <code>bash git clone https://github.com/PeterM45/SysInput.git cd SysInput zig build zig build run</code> The application runs in the background. Type in any text field and press <strong>Tab</strong> to see suggestions. Usage <ol> <li>Start typing in any text field (at least 2 characters).</li> <li>Suggestions appear near your cursor.</li> <li>Press <strong>Tab</strong> or <strong>Enter</strong> to accept a suggestion.</li> <li>Use <strong>Up/Down arrows</strong> to navigate suggestions.</li> </ol> Keyboard Shortcuts | Key | Action | | ----------- | ------------------- | | <strong>Tab</strong> | Accept suggestion | | <strong>Enter</strong> | Accept suggestion | | <strong>↓ Arrow</strong> | Next suggestion | | <strong>↑ Arrow</strong> | Previous suggestion | | <strong>Esc</strong> | Exit SysInput | Architecture <ul> <li><strong>Core:</strong> Text buffer, configuration, and debugging.</li> <li><strong>Input:</strong> Keyboard hooks and text field detection.</li> <li><strong>Text:</strong> Autocomplete engine, dictionary management, and spell checking.</li> <li><strong>UI:</strong> Suggestion overlay and window management.</li> <li><strong>Win32:</strong> Windows API bindings and hook implementations.</li> </ul> Project Structure <code>SysInput/ ├── build.zig - Build configuration ├── resources/ │ └── dictionary.txt - Word dictionary for suggestions └── src/ ├── buffer_controller.zig - Text buffer management ├── core/ - Core functionality │ ├── buffer.zig - Text buffer implementation │ ├── config.zig - Configuration │ └── debug.zig - Debugging utilities ├── input/ - Input handling │ ├── keyboard.zig - Keyboard hook and processing │ ├── text_field.zig - Text field detection │ └── window_detection.zig - Window detection ├── main.zig - Application entry point ├── module_exports.zig - Main module imports ├── suggestion/ - Suggestion handling │ ├── manager.zig - Suggestion manager │ └── stats.zig - Statistics tracking ├── text/ - Text processing │ ├── autocomplete.zig - Autocomplete engine │ ├── dictionary.zig - Dictionary loading/management │ ├── edit_distance.zig - Text similarity algorithms │ ├── insertion.zig - Text insertion methods │ └── spellcheck.zig - Spell checking ├── ui/ - User interface │ ├── position.zig - UI positioning logic │ ├── suggestion_ui.zig - Suggestion UI │ └── window.zig - Window management └── win32/ - Windows API bindings ├── api.zig - Windows API definitions ├── hook.zig - Hook implementation └── text_inject.zig - Text injection utilities</code> Contributing Contributions are welcome! To get started: <ol> <li>Fork the repository.</li> <li>Clone your fork.</li> <li>Create a branch for your changes.</li> <li>Submit a pull request.</li> </ol> Check out our contribution guidelines for more details. Troubleshooting <strong>No suggestions?</strong> <ul> <li>Ensure SysInput is running.</li> <li>Type in a standard text field (minimum 2 characters).</li> </ul> <strong>Text insertion issues?</strong> <ul> <li>Try a different insertion method; some applications may have restrictions.</li> </ul> License This project is licensed under the MIT License – see the <a>LICENSE</a> file for details. Feel free to tweak as needed. Happy coding! 👍
[]
https://avatars.githubusercontent.com/u/10281587?v=4
libqt6zig-examples
rcalixte/libqt6zig-examples
2025-03-07T13:14:24Z
Qt 6 examples for Zig
master
0
3
0
3
https://api.github.com/repos/rcalixte/libqt6zig-examples/tags
MIT
[ "qt", "qt6", "zig", "zig-program", "ziglang" ]
539
false
2025-05-22T00:22:49Z
true
true
unknown
github
[ { "commit": "360593c0e3f67da6b7d5bb6bcb33afab36f85f15", "name": "libqt6zig", "tar_url": "https://github.com/rcalixte/libqt6zig/archive/360593c0e3f67da6b7d5bb6bcb33afab36f85f15.tar.gz", "type": "remote", "url": "https://github.com/rcalixte/libqt6zig" } ]
![MIT License](https://img.shields.io/badge/License-MIT-green) [![Static Badge](https://img.shields.io/badge/v0.14%20(stable)-f7a41d?logo=zig&amp;logoColor=f7a41d&amp;label=Zig)](https://ziglang.org/download/) Example applications using the MIT-licensed Qt 6 bindings for Zig These examples can be thought of as instructive templates for using the main library. Though some of the examples have some complexity to them, the intention is to aim for simplicity while demonstrating valid uses of the library. All of source code for the examples are a single file by design. Any auxiliary files are placed in the same directory for either compilation or execution purposes. Please try out the sample applications and start a <a>discussion</a> if you have any questions or issues relevant to these examples. TABLE OF CONTENTS <ul> <li><a>License</a></li> <li><a>Building</a></li> <li><a>FAQ</a></li> <li><a>Special Thanks</a></li> </ul> License The sample applications within <code>libqt6zig-examples</code> are licensed under the MIT license. Building The dependencies for building the sample applications are the same as the main library. Refer to the main library's <a>Building</a> section for more information. It is recommended to execute an initial build to generate a clean build cache before making any changes. This allows the build process to use the cached build artifacts to speed up subsequent builds. Once the required packages are installed, the library can be built from the root of the repository: <code>bash zig build</code> Users of Arch-based distributions need to <strong>make sure that all packages are up-to-date</strong> first and will need to add the following option to support successful compilation: <code>bash zig build -Denable-workaround</code> To skip the restricted extras: <code>bash zig build -Dskip-restricted</code> Example applications can also be built and run independently: <code>bash zig build helloworld events</code> Applications can be installed to the system in a non-default location by adding the <code>--prefix-exe-dir</code> option to the build command: <code>bash sudo zig build --prefix-exe-dir /usr/local/bin # creates /usr/local/bin/{examples}</code> To see the full list of examples available: <code>bash zig build -l</code> To see the full list of examples and build options available: <code>bash zig build --help</code> The source code for the examples can be found in the <code>src</code> directory of the repository. FAQ Q1. How long does it take to compile the examples? The examples compile a subset of the entire main library and then build the sample applications from the source code. The first compilation should take less than 3 minutes, assuming the hardware in use is at or above the level of that of a consumer-grade mid-tier machine released in the past decade. Once the build cache is warmed up for the examples, subsequent compilations should be very fast, on the order of seconds. For client applications that use and configure a specific subset of the main library, the expected compilation time should be similar to the examples. Q2. What build modes are supported by the examples? Currently, only <code>ReleaseFast</code>, <code>ReleaseSafe</code>, and <code>ReleaseSmall</code> are supported. The <code>Debug</code> build mode is not supported. This may change in the future. The default build mode is <code>ReleaseFast</code>. To change the build mode: <code>bash zig build -Doptimize=ReleaseSafe</code> or <code>bash zig build --release=safe</code> Q3. Are translations supported? Several options are available to implement translations ranging from functions available in the main library to well-supported systems such as <a>GNU gettext</a> to <a>Qt's internationalization options</a>. Developers are free to use any of the available options or implement their own solution. Q4. Do the applications built with this library support theming? | ![debian_cinnamon_helloworld](assets/debian_cinnamon_helloworld.png) | ![endeavour_kde_helloworld](assets/endeavour_kde_helloworld.png) | | :------------------------------------------------------------------: | :--------------------------------------------------------------: | | Debian + Cinnamon + Qt 6.8 (custom theme) | EndeavourOS + KDE + Qt 6.8 | | ![fedora_kde_helloworld](assets/fedora_kde_helloworld.png) | ![freebsd_xfce_helloworld](assets/freebsd_xfce_helloworld.png) | | Fedora + KDE + Qt 6.8 | FreeBSD + Xfce + Qt 6.8 | | ![mint_cinnamon_helloworld](assets/mint_cinnamon_helloworld.png) | ![ubuntu_helloworld](assets/ubuntu_helloworld.png) | | Linux Mint + Cinnamon + Qt 6.4 | Ubuntu + Qt 6.4 | Special Thanks <ul> <li> <a>@mappu</a> for the <a>MIQT</a> bindings that provided the phenomenal foundation for this project </li> <li> <a>@arnetheduck</a> for proving the value of collaboration on the back-end of the library while working across different target languages </li> </ul>
[]
https://avatars.githubusercontent.com/u/10899984?v=4
nix-microzig-devenv
clementpoiret/nix-microzig-devenv
2025-04-12T16:13:55Z
A template to simplify starting microcontroller projects using Zig
main
0
3
0
3
https://api.github.com/repos/clementpoiret/nix-microzig-devenv/tags
MIT
[ "embedded", "mcu", "zig", "ziglang" ]
5
false
2025-04-13T08:40:46Z
true
true
0.14.0
github
[]
Microcontroller Project Template using MicroZig and Devenv This repository serves as a GitHub template to simplify starting microcontroller projects using <a>MicroZig</a>, a framework for developing firmware in Zig. The template is designed to work with various MicroZig-supported boards, with the Raspberry Pi Pico 2 provided as the default example. It leverages <a>Devenv</a> to manage the development environment using Nix, ensuring a consistent and reproducible setup. Prerequisites To use this template, ensure you have the following installed: <ul> <li>Zig version 0.14 or later</li> <li>Nix package manager</li> <li>Git for cloning the repository</li> <li>Board-specific tools (e.g., picotool for Raspberry Pi Pico 2, included in the Devenv environment)</li> </ul> The template is configured for the Raspberry Pi Pico 2 by default but can be adapted for other MicroZig-supported boards. Refer to the MicroZig documentation for a list of supported boards. Getting Started Follow these steps to set up and run the example firmware for the Raspberry Pi Pico 2: <ol> <li>Clone the repository:</li> </ol> <code>sh git clone https://github.com/clement-poiret/nix-microzig-devenv.git cd nix-microzig-devenv</code> <ol> <li>Enter the development environment:</li> </ol> <code>sh devenv shell</code> Note that if you have direnv, <code>direnv allow</code> will make you automatically enter the development environment when entering it. This command sets up a shell with all required tools and dependencies, managed by Nix and Devenv. <ol> <li>Build the example firmware:</li> </ol> <code>sh zig build</code> This compiles the firmware, producing a <code>template.uf2</code> file in the <code>zig-out/firmware</code> directory. <ol> <li>Flash the firmware to the Pico 2:</li> </ol> Put your Raspberry Pi Pico 2 into bootloader mode by holding the BOOTSEL button while plugging it into your computer via USB. Then run: <code>sh picotool load -f zig-out/firmware/template.uf2</code> This flashes the compiled firmware onto the microcontroller. You should see the LED connected to GPIO15 blinking if everything is set up correctly. <strong>Note</strong>: If you are using a different board, refer to the Adapting for Other Boards section for guidance on modifying the template. Project Structure The template includes the following files, each serving a specific purpose: <ul> <li><code>build.zig</code>: The Zig build script that configures the firmware compilation process using MicroZig.</li> <li><code>build.zig.zon</code>: Specifies dependencies (e.g., MicroZig) and metadata for the Zig project.</li> <li><code>devenv.lock</code>, <code>devenv.nix</code>, <code>devenv.yaml</code>: Configuration files for Devenv, defining the Nix-based development environment, including tools like picotool and Zig.</li> <li><code>src/main.zig</code>: The entry point for your firmware code. This file contains a simple example that blinks an LED on GPIO15 for the Pico 2.</li> <li><code>src/root.zig</code>: A supporting Zig module, potentially for root-level configurations or imports (currently minimal in this template).</li> </ul> Adapting for Other Boards To use this template with a different MicroZig-supported board, follow these steps: <ol> <li>Update the target in <code>build.zig</code>: Modify the <code>target</code> field in the <code>mb.add_firmware</code> call to match your board. For example, to use the Raspberry Pi Pico:</li> </ol> <code>zig .target = mb.ports.rp2xxx.boards.raspberrypi.pico,</code> Refer to the MicroZig documentation for the list of supported boards under ports. <ol> <li> Adjust dependencies in <code>build.zig.zon</code>: Ensure that the MicroZig version and any additional dependencies are compatible with your target hardware. You may need to update the MicroZig commit or add specific dependencies for your board. </li> <li> Modify Devenv configurations: Update <code>devenv.nix</code> to include any board-specific tools or utilities required for flashing or debugging. For example, if your board uses a different flashing tool, replace picotool with the appropriate package. </li> <li> Update firmware code in <code>src/main.zig</code>: Change the pin configurations and any board-specific code to match your board's hardware. Consult your board's documentation for details on GPIO pins, peripherals, and other features. </li> <li> Update flashing instructions: Modify the flashing commands in the Building and Flashing section to match your board's requirements. You may need to use different tools or procedures. </li> </ol> License This template is released under the MIT License (LICENSE). Feel free to use, modify, and distribute it as needed.
[]
https://avatars.githubusercontent.com/u/12181586?v=4
ch32v003_basic_zig
ghostiam/ch32v003_basic_zig
2025-03-26T19:54:50Z
Basic examples for ch32v003 from scratch in Zig. Just using `zig build` 🚀
master
0
3
0
3
https://api.github.com/repos/ghostiam/ch32v003_basic_zig/tags
MIT
[ "ch32v", "ch32v003", "embedded", "embedded-zig", "wch", "zig", "ziglang" ]
27
false
2025-04-18T11:10:13Z
false
false
unknown
github
[]
CH32V003 basic examples Basic examples are based on the use of registers, without abstractions. \ All examples have been tested for functionality on <code>ch32v003</code>, but since the pin to which the LED is connected may differ for you, you will need to change the port and pin in the code. \ In these examples, the LED is connected to the <code>PC0</code> pin. <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> If you are looking for more production-ready solutions, you should check out the repository <a>ch32_zig</a>, which contains <code>HAL</code> and utilities for working with <code>WCH CH32</code> chips. </blockquote> <a>001_blink_minimal</a> Blinking LED with minimal code in <code>ZIG</code>. \ No linker script, no startup code, no standard library, only read/write registers! <a>002_blink_ld_zig</a> This example uses a global variable that needs to be placed in memory. \ For this, a linker script and a function that initializes the registers and copies data from <code>FLASH</code> to <code>RAM</code> are required. \ The data copying function will be implemented in pure <code>ZIG</code>. <a>003_blink_ld_asm</a> The difference from the previous example is that the data copying function will be implemented in assembly, which will greatly reduce the firmware size when compiled in a mode other than <code>ReleaseSmall</code>. \ This function will be used in all subsequent examples. <a>004_blink_systick_interrupt</a> Now we get to interrupts. \ In this example, we will blink the LED using a system timer interrupt. <a>005_blink_uart</a> We will do a small code refactoring by moving the startup code to a separate file. \ We will add <code>UART</code> initialization and output a counter that increments with each LED blink. <a>006_blink_uart_logger</a> We raise the stakes and connect <code>std.log</code> to <code>UART</code>! \ Now we can use string formatting and output panic messages to <code>UART</code>! \ To demonstrate this, the code will panic when the counter reaches <code>10</code>. <a>007_spi_master</a> As an additional example, we will add an <code>SPI</code> master that will send <code>Test</code>.
[]
https://avatars.githubusercontent.com/u/37661824?v=4
ztunnel
LvMalware/ztunnel
2025-03-22T13:30:09Z
Secure End-To-End Encrypted tunnels using zig
master
0
3
0
3
https://api.github.com/repos/LvMalware/ztunnel/tags
-
[ "cryptography", "e2ee", "tunnel", "zig", "zig-package" ]
19
false
2025-03-27T16:06:34Z
true
true
0.14.0
github
[]
ZTunnel This library provides a simple protocol based on SSH's Binary Packet Protocol (BPP), that can be used to establish a secure end-to-end encrypted tunnel between a client and a server. Key-exchange is performed using <code>X25519Kyber768</code>, that is Ellipitic Curve Diffe-Hellman (ECDH) using curve X25519 + the post-quantum Key-Encapsulation Mechanism (KEM) called Kyber. This way, the communication remains secure as long as at least one of the two algorithms is unbroken. All data is then transmitted using <code>AES-256-GCM</code>. <blockquote> Note: This protocol is useful to protect against eavesdropping, but currently it <strong>can't</strong> protect against active man-in-the-middle attacks. Future versions might include a method to validate each peer's public keys during key-exchange, invalidating such attacks. </blockquote>
[]
https://avatars.githubusercontent.com/u/2773256?v=4
zig-devserver
dasimmet/zig-devserver
2025-05-01T17:11:12Z
a reloading static http server for `zig build --watch`
main
0
3
0
3
https://api.github.com/repos/dasimmet/zig-devserver/tags
MIT
[ "zig", "zig-package" ]
74
false
2025-05-04T14:08:05Z
true
true
0.14.0
github
[ { "commit": "master", "name": "mime", "tar_url": "https://github.com/andrewrk/mime/archive/master.tar.gz", "type": "remote", "url": "https://github.com/andrewrk/mime" } ]
Zig Dev Http Webserver a webserver that reloads the page when <code>zig build dev --watch</code> rebuilds your content try it with: <code>zig build dev --watch -Dopen-browser=index.html</code> and then edit <code>src/index.html</code> and have the browser tab reload. Only POSIX is supported, since reloading requires <code>fork()</code> ing the server to the background at the moment. The next launch of the server will send a request to the old instance to kill it. On html pages a small javascript is injected to check when the server was started. When the page receives a newer timestamp, a reload is triggered. To stop the forked server when <code>zig build dev --watch</code> is stopped, it sends <code>kill(ppid, 0)</code> signals back to it's parent process on request and end itself if needed. Naturally, DO NOT USE THIS IN PRODUCTION. This is a development tool only. <code>build.zig</code> usage ```zig // zig fetch --save git+https://github.com/dasimmet/zig-devserver.git pub fn build(b: *std.Build) void { const devserver = @import("devserver"); const run_devserver = devserver.serveDir(b, .{ // optionally provide a host ip. this is the default: .host = "127.0.0.1", <code> // provide a port to listen on .port = b.option(u16, "port", "dev server port") orelse 8080, // optionally provide a path to open .open_browser = b.option( []const u8, "open-browser", "open the os default webbbrowser on first server launch", ) orelse "/", // either `serveInstall` =&gt; path in `zig-out`. // makes the run step depend on the install step. // alternatively, use `serveLazyPath` on sources or generated files .directory = .serveInstall("www"), }); // setup a `dev` top level step to run the server b.step("dev", "run dev webserver").dependOn(&amp;run_devserver.step); </code> } ``` References <ul> <li><a>https://cookbook.ziglang.cc/05-02-http-post.html</a></li> <li><a>https://github.com/andrewrk/mime.git</a></li> <li><a>https://github.com/scottredig/zig-demo-webserver</a></li> <li><a>https://stackoverflow.com/questions/3043978/how-to-check-if-a-process-id-pid-exists</a></li> <li><a>https://ziggit.dev/t/build-zig-webserver/7078/4</a></li> </ul>
[]
https://avatars.githubusercontent.com/u/142879640?v=4
VimZ
MohamadCS/VimZ
2025-02-18T17:25:14Z
A vim like text editor written in zig.
main
0
3
0
3
https://api.github.com/repos/MohamadCS/VimZ/tags
MIT
[ "terminal", "vim", "zig" ]
230
false
2025-04-09T02:30:47Z
true
true
0.14.0
github
[ { "commit": "master", "name": "vaxis", "tar_url": "https://github.com/rockorager/libvaxis/archive/master.tar.gz", "type": "remote", "url": "https://github.com/rockorager/libvaxis" } ]
VimZig A vim like text editor written in zig ... The purpose of this project is to imporve my knowlege in Zig. Build <code>bash zig build --release=fast</code> Usage <code>bash ./zig-out/bin/vimz &lt;path_to_file&gt;</code>
[]
https://avatars.githubusercontent.com/u/104195271?v=4
zig-wol
rktr1998/zig-wol
2025-02-25T21:39:06Z
Wake-on-lan CLI written in Zig.
main
4
3
0
3
https://api.github.com/repos/rktr1998/zig-wol/tags
MIT
[ "cli", "command-line", "wake-on-lan", "wol", "zig", "ziglang" ]
53
false
2025-04-25T22:16:11Z
true
true
0.14.0
github
[ { "commit": "8db1aa2f5efdf1e2ff6dd5f5f8efe1b4f44ff978", "name": "network", "tar_url": "https://github.com/ikskuh/zig-network/archive/8db1aa2f5efdf1e2ff6dd5f5f8efe1b4f44ff978.tar.gz", "type": "remote", "url": "https://github.com/ikskuh/zig-network" }, { "commit": "a39ab2595d685526a6fb13f9...
Zig-wol Written in the <a>Zig</a> programming language, <a>zig-wol</a> is a CLI utility for sending wake-on-lan magic packets to wake up a computer in a LAN given its MAC address. Features <ul> <li>Send WOL magic packets to wake up devices on the LAN.</li> <li>Cross-platform support for Windows and Linux.</li> </ul> Usage Wake a machine on your LAN by broadcasting the magic packet: replace <code>&lt;MAC&gt;</code> with the target MAC address (e.g. <code>9A-63-A1-FF-8B-4C</code>). <code>sh zig-wol wake &lt;MAC&gt;</code> Create an alias for a MAC address. <code>sh zig-wol list # display all aliases zig-wol alias &lt;NAME&gt; &lt;MAC&gt; # create an alias zig-wol wake &lt;NAME&gt; # wake a machine by alias</code> Run <code>zig-wol help</code> to display all subcommands and <code>zig-wol &lt;subcommand&gt; --help</code> to display specific options. Installation Pre-compiled binaries of <a>zig-wol</a> are distributed with <a>releases</a>: download the binary for your architecture and operating system and you are good to go! Install latest on Windows using PowerShell <code>pwsh Invoke-RestMethod "https://raw.githubusercontent.com/rktr1998/zig-wol/refs/heads/main/install/install-latest-on-windows.ps1" | Invoke-Expression</code> This command downloads the latest release for your processor architecture and <strong>installs</strong> the program at <code>C:\Users\%username%\.zig-wol</code>. To <strong>uninstall</strong> zig-wol, simply delete this folder. Install latest on Linux <code>sh bash &lt;(curl -sSL https://raw.githubusercontent.com/rktr1998/zig-wol/refs/heads/main/install/install-latest-on-linux.sh)</code> This command downloads the latest release for your processor architecture and <strong>installs</strong> the program at <code>/home/$USER/.zig-wol</code>. To <strong>uninstall</strong> zig-wol, simply delete this folder. Build Prerequisites <ul> <li><a>Zig (v0.14.0)</a> installed on your system.</li> </ul> 1. Clone the Repository <code>sh git clone https://github.com/rktr1998/zig-wol.git cd zig-wol</code> 2. Build the Application <code>sh zig build</code> This command compiles the source code and places the executable in the <code>zig-out/bin/</code> directory. License This project is licensed under the MIT License. See the <a>LICENSE</a> file for details.
[]
https://avatars.githubusercontent.com/u/108661125?v=4
BytePusher
Frost-Phoenix/BytePusher
2025-05-04T21:14:21Z
BytePusher VM
main
0
2
0
2
https://api.github.com/repos/Frost-Phoenix/BytePusher/tags
-
[ "bytepusher", "vm", "zig" ]
747
false
2025-05-18T12:09:11Z
true
true
0.14.0
github
[ { "commit": "master", "name": "raylib_zig", "tar_url": "https://github.com/Not-Nik/raylib-zig/archive/master.tar.gz", "type": "remote", "url": "https://github.com/Not-Nik/raylib-zig" } ]
BytePusher A <a>Bytepusher</a> virtual machine made with Zig and Raylib. | | | | |:-------------------------:|:-------------------------:|:-------------------------:| | | | | Usage <code>./bytepusher &lt;rom-path&gt;</code> Keyboard KeyboardBytePusher VM | | | | | |:-:|:-:|:-:|:-:| | 1 | 2 | 3 | 4 | | Q | W | E | R | | A | S | D | F | | Z | X | C | V | | | | | | |:-:|:-:|:-:|:-:| | 1 | 2 | 3 | C | | 4 | 5 | 6 | D | | 7 | 8 | 9 | E | | A | 0 | B | F |
[]
https://avatars.githubusercontent.com/u/124677802?v=4
android-sdk-custom
HomuHomu833/android-sdk-custom
2025-05-08T12:40:47Z
Android SDK built using musl libc, supporting multiple architectures.
main
0
2
1
2
https://api.github.com/repos/HomuHomu833/android-sdk-custom/tags
MIT
[ "android", "custom", "musl", "musl-libc", "sdk", "termux", "zig" ]
866
false
2025-05-19T00:48:28Z
false
false
unknown
github
[]
Android SDK Custom A custom-built Android SDK that replaces the default binaries with versions built using <strong>musl libc from <a>Zig</a></strong>. Inspired by <a>lzhiyong's Android SDK Tools</a>. Features <ul> <li><strong>Custom-built binaries</strong>, sourced from Google's Android SDK repositories.</li> <li>Uses <strong>Zig</strong> as a build environment for musl-based toolchains.</li> </ul> Architecture and Platform Support <ul> <li><strong>Zig-based Environment</strong></li> <li><strong>Supported Platforms</strong>:<ul> <li>Linux</li> <li>Android</li> </ul> </li> <li><strong>Supported Architectures</strong>:<ul> <li><strong>x86</strong>: <code>x86</code>, <code>x86_64</code></li> <li><strong>ARM</strong>: <code>arm</code>, <code>armeb</code>, <code>aarch64</code>, <code>aarch64_be</code></li> <li><strong>RISC-V</strong>: <code>riscv32</code>, <code>riscv64</code></li> <li><strong>Other</strong>: <code>loongarch64</code>, <code>powerpc64le</code>, <code>s390x</code></li> </ul> </li> </ul> Usage This SDK functions like the standard Android SDK. Simply extract the archive and use it as you would the official version. License This project is licensed under the <strong>MIT License</strong>. See the <a>LICENSE</a> file for more details. Feel free to open pull requests or issues if you have any contributions or feedback!
[]
https://avatars.githubusercontent.com/u/44242534?v=4
chipz-8
diicellman/chipz-8
2025-03-26T12:39:05Z
CHIP-8 emulator written in zig + raylib
main
0
2
0
2
https://api.github.com/repos/diicellman/chipz-8/tags
-
[ "chip8-emulator", "raylib", "zig" ]
7
false
2025-04-12T12:53:06Z
true
true
0.14.0
github
[ { "commit": "master", "name": "raylib_zig", "tar_url": "https://github.com/Not-Nik/raylib-zig/archive/master.tar.gz", "type": "remote", "url": "https://github.com/Not-Nik/raylib-zig" } ]
CHIPZ-8 <em><strong>ELECTROCHEMISTRY [Medium]</strong>: The phosphor glow of forgotten technology burns in your mind. These primitive pixels, this rudimentary sound—they call to something primal in you. The machines may be simple, but the experience was pure.</em> A minimal Chip-8 emulator implemented in Zig using raylib. Features <ul> <li>Complete Chip-8 instruction set implementation</li> <li>64×32 pixel display at 16× scaling (1024×512 window)</li> <li>Customizable execution speed</li> </ul> Prerequisites <ul> <li>Zig 0.14.0</li> <li>raylib-zig</li> </ul> Usage <code>bash zig build run -- path/to/rom.ch8</code> Controls The original Chip-8 had a 16-key hexadecimal keypad. This emulator maps them to modern keyboards as follows: <code>Chip-8 Keypad Keyboard Mapping +-+-+-+-+ +-+-+-+-+ |1|2|3|C| |1|2|3|4| +-+-+-+-+ +-+-+-+-+ |4|5|6|D| |Q|W|E|R| +-+-+-+-+ =&gt; +-+-+-+-+ |7|8|9|E| |A|S|D|F| +-+-+-+-+ +-+-+-+-+ |A|0|B|F| |Z|X|C|V| +-+-+-+-+ +-+-+-+-+</code> Included ROMs The <code>test-roms</code> directory contains several ROMs to test your emulator: <ul> <li><code>tetris.ch8</code> - Classic Tetris game</li> <li><code>space_invaders.ch8</code> - Space Invaders clone</li> <li><code>IBM_logo.ch8</code> - Displays the IBM logo</li> <li><code>BMP_viewer.ch8</code> - Simple image viewer</li> <li><code>keypad_test.ch8</code> - Tests keyboard input</li> <li><code>test_opcode.ch8</code> - Tests Chip-8 opcodes</li> </ul> Building from Source <code>bash git clone https://github.com/yourusername/CHIPZ-8.git cd CHIPZ-8 zig build</code> Additional Resources <ul> <li><a>Chip-8 Emulator Tutorial</a> - Disco blog post by Austin Morlan</li> <li><a>Chip-8 ROM Collection</a> - Additional ROMs to play with</li> </ul>
[]
https://avatars.githubusercontent.com/u/87213748?v=4
pvz-bloomiverse
JamzOJamz/pvz-bloomiverse
2025-04-04T04:36:55Z
A Plants vs. Zombies fangame
main
0
2
0
2
https://api.github.com/repos/JamzOJamz/pvz-bloomiverse/tags
-
[ "game", "plants-vs-zombies", "plantsvszombies", "pvz", "pvz2", "raylib-zig", "zig", "ziglang" ]
14,790
false
2025-04-17T06:26:05Z
true
true
0.14.0
github
[ { "commit": "master", "name": "raylib_zig", "tar_url": "https://github.com/Not-Nik/raylib-zig/archive/master.tar.gz", "type": "remote", "url": "https://github.com/Not-Nik/raylib-zig" }, { "commit": null, "name": "zrres", "tar_url": null, "type": "relative", "url": "lib/zr...
Plants vs. Zombies: Bloomiverse <strong>PvZ: Bloomiverse</strong> is a fan-made reimagining of <em>Plants vs. Zombies</em>, built in <a>Zig</a> and utilizing <a>raylib</a> for rendering. This project aims to recreate the charm of the original game while introducing new mechanics and enhancements. 🚧 Project Status This is a work-in-progress fangame. Contributions, feedback, and suggestions are welcome! 🛠️ Features Coming soon! 📁 Project Structure <ul> <li><code>src/</code>: Contains the main source code.</li> <li><code>lib/</code>: Includes external libraries and dependencies.</li> <li><code>resources/</code>: Game assets such as images and sounds.</li> <li><code>build.zig</code>: Build script for compiling the project.</li> </ul> 🧱 Building the Project Prerequisites <ul> <li><a>Zig</a> (latest stable version)</li> </ul> Build Instructions <ol> <li>Clone the repository:</li> </ol> <code>bash git clone https://github.com/JamzOJamz/pvz-bloomiverse.git cd pvz-bloomiverse</code> <ol> <li>Build the project using Zig:</li> </ol> <code>bash zig build</code> <ol> <li>Run the executable:</li> </ol> <code>bash zig-out/bin/bloomiverse</code> 🎮 Controls <ul> <li><strong>Mouse</strong>: Collect sun.</li> </ul> 📌 Roadmap Coming soon... 🤝 Contributing Contributions are welcome! Please fork the repository and submit a pull request with your changes. 📄 Legal This project is a fan-made creation and is not affiliated with or endorsed by the official <em>Plants vs. Zombies</em> franchise. All rights to the original game are owned by their respective holders.
[]
https://avatars.githubusercontent.com/u/177400051?v=4
zuws
harmony-co/zuws
2025-03-28T08:32:16Z
Opinionated Zig bindings for uWebSockets
main
1
2
1
2
https://api.github.com/repos/harmony-co/zuws/tags
Apache-2.0
[ "bindings", "uwebsockets", "zig" ]
30
false
2025-04-05T20:21:36Z
true
true
unknown
github
[]
zuws Opinionated zig bindings for <a><code>uWebsockets</code></a>. Installation <code>zuws</code> is available using the <code>zig fetch</code> command. <code>sh zig fetch --save git+https://github.com/harmony-co/zuws</code> To add it to your project, after running the command above add the following to your <code>build.zig</code> file: ```zig const zuws = b.dependency("zuws", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zuws", zuws.module("zuws")); ``` <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> You can disable the default debug logs by passing <code>.debug_logs = false</code> as an option. </blockquote> Using the C bindings You can import the C bindings directly instead of the <code>zuws</code> wrapper by using the following: <code>zig exe.root_module.addImport("uws", zuws.module("uws"));</code> Usage ```zig const uws = @import("zuws"); const App = uws.App; const Request = uws.Request; const Response = uws.Response; pub fn main() !void { const app: App = try .init(); defer app.deinit(); <code>try app.get("/hello", hello) .listen(3000, null); </code> } fn hello(res: <em>Response, req: </em>Request) void { _ = req; const str = "Hello World!\n"; res.end(str, false); } ``` Grouping Grouping is not something provided by uws itself and instead is an abstraction we provide to aid developers. The grouping API has a <code>comptime</code> and a <code>runtime</code> variant, most of the time you will want to use the <code>comptime</code> variant, but for the rare cases where adding routes at runtime dynamically is needed the functionality is there. Creating groups at <code>comptime</code> ```zig const app: App = try .init(); defer app.deinit(); const my_group = App.Group.initComptime("/v1") .get("/example", someHandler); // This will create the following route: // /v1/example app.comptimeGroup(my_group); ``` Creating groups at <code>runtime</code> ```zig const app: App = try .init(); defer app.deinit(); var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init; const allocator = gpa.allocator(); var my_group = App.Group.init(allocator, "/v1"); try my_group.get("/example", someHandler); // This will create the following route: // /v1/example try app.group(my_group); // We highly recommend you deinit the group // after you don't need it anymore my_group.deinit(); ``` Combining groups together We provide 2 different ways of combining groups together. Grouping ```zig const app: App = try .init(); defer app.deinit(); const api = App.Group.initComptime("/api"); const v1 = App.Group.initComptime("/v1") .get("/example", someHandler); _ = api.group(v1); // This will create the following route: // /api/v1/example app.comptimeGroup(api); ``` Merging ```zig const app: App = try .init(); defer app.deinit(); const v1 = App.Group.initComptime("/v1") .get("/example", someHandler); const v2 = App.Group.initComptime("/v2"); _ = v2.merge(v1); // This will create the following route: // /v2/example app.comptimeGroup(v2); ``` Running the Examples To run the provided examples in <code>zuws</code> you can clone the repository (don't forget to initialize the submodules), and run the following command: <code>zsh zig build example -- &lt;example-name&gt;</code> You can also generate the assembly of a specific example using the following: <code>zsh zig build example-asm -- &lt;example-name&gt;</code>
[]