avatar_url
stringlengths
46
53
name
stringlengths
1
40
full_name
stringlengths
7
48
created_at
stringdate
2013-01-20 00:03:40
2025-04-10 12:35:22
description
stringlengths
1
387
default_branch
stringclasses
42 values
open_issues
int64
0
4.64k
stargazers_count
int64
0
77.4k
forks_count
int64
0
3.02k
watchers_count
int64
0
77.4k
tags_url
stringlengths
41
82
license
stringclasses
27 values
topics
sequencelengths
0
20
size
int64
0
4.75M
fork
bool
2 classes
updated_at
stringdate
2018-11-13 14:41:18
2025-04-10 23:10:50
has_build_zig
bool
2 classes
has_build_zig_zon
bool
2 classes
readme_content
stringlengths
3
468k
https://avatars.githubusercontent.com/u/643384?v=4
z_impact
scemino/z_impact
2024-08-18T14:24:14Z
A 2d game engine written in ZIG
main
0
21
0
21
https://api.github.com/repos/scemino/z_impact/tags
MIT
[ "gamedev", "zig-package" ]
980
false
2025-03-18T19:52:11Z
true
true
[![build](https://github.com/scemino/z_impact/actions/workflows/main.yml/badge.svg)](https://github.com/scemino/z_impact/actions/workflows/main.yml) β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•—β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ•— β•šβ•β•β–“β–“β–“β•”β• β–“β–“β•‘β–“β–“β–“β–“β•— β–“β–“β–“β–“β•‘β–“β–“β•”β•β•β–“β–“β•—β–“β–“β•”β•β•β–“β–“β•—β–“β–“β•”β•β•β•β•β•β•šβ•β•β–“β–“β•”β•β•β• ▒▒▒╔╝ ▒▒║▒▒╔▒▒▒▒╔▒▒║▒▒▒▒▒▒╔╝▒▒▒▒▒▒▒║▒▒║ β–’β–’β•‘ ░░░╔╝ β–‘β–‘β•‘β–‘β–‘β•‘β•šβ–‘β–‘β•”β•β–‘β–‘β•‘β–‘β–‘β•”β•β•β•β• ░░╔══░░║░░║ β–‘β–‘β•‘ β–‘β–‘β–‘β–‘β–‘β–‘β–‘β•— β–‘β–‘β•‘β–‘β–‘β•‘ β•šβ•β• β–‘β–‘β•‘β–‘β–‘β•‘ β–‘β–‘β•‘ β–‘β–‘β•‘β•šβ–‘β–‘β–‘β–‘β–‘β–‘β•— β–‘β–‘β•‘ β•šβ•β•β•β•β•β•β• β•šβ•β•β•šβ•β• β•šβ•β•β•šβ•β• β•šβ•β• β•šβ•β• β•šβ•β•β•β•β•β• β•šβ•β• β–‘β–‘β–‘β–‘β–’β–’β–’β–’β–’β–’β–’β–“β–“β–“β–“β–“β–“β–“β–“β–“β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–“β–“β–“β–“β–“β–“β–“β–“β–“β–“β–’β–’β–’β–’β–’β–’β–’β–’β–’β–’β–‘β–‘β–‘β–‘β•— β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• Z impact is a ZIG game engine for creating 2d action games. It's well suited for jump'n'runs, twin stick shooters, top-down dungeon crawlers and others with a focus on pixel art. This is NOT a general purpose game engine akin to Godot, Unreal or Unity. At this stage, it is also quite experimental and lacking documentation. Expect problems. Z impact is more a framework than it is a library, meaning that you have to adhere to a structure, in code and file layout, that is prescribed by the engine. You do not call Z impact, Z impact _calls you_. Games made with Z impact can be compiled for Linux, macOS, Windows (through the usual hoops) and for the web with WASM. There are currently two "platform backends": SDL2 & Sokol and different renderers: for SDL2 platform: OpenGL and for sokol: one renderer by OS: OpenGL (Linux), Metal (mac OS), Direct-X (Windows). Z impact is a port of the orginal game engine [high_impact](https://github.com/phoboslab/high_impact/tree/master) made by phoboslab. ## Examples - [Biolab Disaster](https://github.com/scemino/z_biolab): A jump'n'gun platformer, displaying many of Z impacts capabilities. - [Drop](https://github.com/scemino/z_impact/tree/main/samples/zdrop): A minimal arcade game with randomly generated levels ## Compiling To compile and run the sample game Drop ### Linux - Windows - macOS SDL2 platform + OpenGL renderer ```shell zig build run ``` SDL2 platform + software renderer ```shell zig build -Dplatform=sdl_soft run ``` sokol platform ```shell zig build -Dplatform=sokol run ``` ### WEB ```shell zig build -Dtarget=wasm32-emscripten run ``` ## Documentation There's not much at the moment. Most of Z impact's functionality is documented in the header files with this README giving a general overview. It's best to read [the blog post](https://phoboslab.org/log/2024/08/high_impact) for an overview and the source for all the details. ## Assets At this time, Z impact can only load images in QOI format and sounds & music in QOA format. The tools to convert PNG to QOI and WAV to QOA are bundled in this repository and can be integrated in your build step. Game levels can be loaded from .json files. A tile editor to create these levels is part of Z impact: `weltmeister.html` which can be launched with a simple double click from your local copy. ## Libraries used - Sokol App, Audio and Time: https://github.com/floooh/sokol-zig - stb_image.h and stb_image_write.h https://github.com/nothings/stb - QOI Image Format: https://github.com/phoboslab/qoi - QOA Audio Format: https://github.com/phoboslab/qoa - SDL.zig: https://github.com/ikskuh/SDL.zig ## License All Z impact code is MIT Licensed, though some of the libraries come with their own (permissive) license. Check the header files.
https://avatars.githubusercontent.com/u/5464072?v=4
zig-ansi
nektro/zig-ansi
2020-12-09T19:24:11Z
ANSI utilities for CLI usage in Zig.
master
2
21
1
21
https://api.github.com/repos/nektro/zig-ansi/tags
MIT
[ "zig", "zig-package" ]
18
false
2025-02-16T06:11:16Z
true
false
# zig-ansi ![loc](https://sloc.xyz/github/nektro/zig-ansi) [![license](https://img.shields.io/github/license/nektro/zig-ansi.svg)](https://github.com/nektro/zig-ansi/blob/master/LICENSE) [![discord](https://img.shields.io/discord/551971034593755159.svg?logo=discord)](https://discord.gg/P6Y4zQC) ANSI utilities for CLI usage in Zig. ## Zig - https://ziglang.org/ - https://github.com/ziglang/zig - https://github.com/ziglang/zig/wiki/Community ## Getting Started Using https://github.com/nektro/zigmod, add a `git` type with a path of `https://github.com/nektro/zig-ansi`. ## Usage See `src/main.zig` or do `zig build run` to see examples. See `src/lib.zig` for source code. ## Built With - Zig 0.7.0 ## Contact - [email protected] - https://twitter.com/nektro ## License MIT
https://avatars.githubusercontent.com/u/95168615?v=4
clay-zig
raugl/clay-zig
2024-12-31T04:11:58Z
Zig bindings for the library clay: A high performance UI layout library in C.
master
1
21
2
21
https://api.github.com/repos/raugl/clay-zig/tags
MIT
[ "layout", "ui", "zig", "zig-binding", "zig-package" ]
161
false
2025-03-19T12:08:42Z
true
true
### Zig Language Bindings > [!IMPORTANT] > Zig 0.14.0 or higher is required. > [!NOTE] > This project currently is in beta. This directory contains bindings for the [Zig](odin-lang.org) programming language, as well as an example implementation of the [clay website](https://nicbarker.com/clay) in Zig. Special thanks to [johan0A](githubusercontent.com/johan0A) for the reference implementation. If you haven't taken a look at the [full documentation for clay](https://github.com/nicbarker/clay/blob/main/README.md), it's recommended that you take a look there first to familiarise yourself with the general concepts. This README is abbreviated and applies to using clay in Zig specifically. The **most notable difference** between the C API and the Zig bindings is the use of if statements to open the scope for declaring child elements and then having to close it "manually" with a deferred function call. Other changes include: - minor naming changes - ability to initialize a parameter by calling a function that is part of its type's namespace for example `.fixed()` or `.all()` - ability to initialize a parameter by using a public constant that is part of its type's namespace for example `.grow` TODO: - Talk about integrations with raylib - Talk about special `getOpenElementId()`, `element()`, and `hovered()` functions ```c // C macro for creating a scope CLAY( CLAY_ID("SideBar"), CLAY_LAYOUT({ .layoutDirection = CLAY_TOP_TO_BOTTOM, .childAlignment = { .x = CLAY_ALIGN_X_CENTER, .y = CLAY_ALIGN_Y_TOP }, .sizing = { .width = CLAY_SIZING_FIXED(300), .height = CLAY_SIZING_GROW() }, .padding = {16, 16}, .childGap = 16, }), CLAY_RECTANGLE({ .color = COLOR_LIGHT }) ) { // Child elements here } ``` ```zig // Zig form of element macros if (clay.open(.{ .id = clay.Id("SideBar"), .layout = .{ .direction = .top_to_bottom, .alignment = .center_top, .sizing = .{ .w = .fixed(300), .h = .grow }, .padding = .all(16), .child_gap = 16, }, .rectangle = .{ .color = COLOR_LIGHT }, })) { defer clay.close(); // Child elements here } ``` ### Install Download and add `clay-zig` as a dependency by running the following command in your project root: ```sh zig fetch --save https://github.com/raugl/clay-zig/archive/<commit sha>.tar.gz ``` Then add `clay-zig` as a dependency and import its modules and artifact in your build.zig: ```zig const clay_dep = b.dependency("clay-zig", .{ .target = target, .optimize = optimize, }); exe.linkLibrary(clay_dep.artifact("clay")); exe.root_module.addImport("clay", clay_dep.module("clay")); ``` To enable a builtin renderer you should first add its third party library to your project separately (eg: raylib, sdl2), then tell clay-zig about it. In this example we are using [raylib-zig](https://github.com/Not-Nik/raylib-zig): ```zig const cl = @import("clay-zig"); const raylib_dep = b.dependency("raylib-zig", .{ ... }); cl.enableRenderer(exe.root_module, clay_dep, .{ .raylib = raylib_dep.module("raylib") }); ``` ### Quick Start 1. Ask clay for how much static memory it needs using [clay.minMemorySize()](https://github.com/nicbarker/clay/blob/main/README.md#clay_minmemorysize), create an Arena for it to use with [clay.createArenaWithCapacityAndMemory(min_memory_size, memory)](https://github.com/nicbarker/clay/blob/main/README.md#clay_createarenawithcapacityandmemory), and initialize it with [clay.initialize(arena, layout_size, error_handler)](https://github.com/nicbarker/clay/blob/main/README.md#clay_initialize). ```zig const memory = try allocator.alloc(u8, clay.minMemorySize()); defer allocator.free(memory); const arena = clay.createArenaWithCapacityAndMemory(@intCast(memory.len), @ptrCast(memory)); clay.initialize(arena, .{}, .{}); ``` 2. Provide a `measureText(text, config)` function with [clay.setMeasureTextFunction(function)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setmeasuretextfunction) so that clay can measure and wrap text. ```zig // Example measure text function pub fn measureText(text: []const u8, config: *clay.TextConfig) clay.Dimensions { // clay.TextConfig contains members such as font_id, font_size, letter_spacing etc } // Tell clay how to measure text clay.setMeasureTextFunction(measureText) ``` 3. **Optional** - Call [clay.setPointerPosition(pointerPosition)](https://github.com/nicbarker/clay/blob/main/README.md#clay_setpointerposition) if you want to use mouse interactions. ```zig clay.setPointerState(.{ .x = mouse_position_x, .y = mouse_position_y }, is_left_mouse_button_down); ``` 4. Call [clay.beginLayout()](https://github.com/nicbarker/clay/blob/main/README.md#clay_beginlayout) and declare your layout using the provided functions. ```zig const COLOR_LIGHT = clay.Color.init(224, 215, 210, 255); const COLOR_RED = clay.Color.init(168, 66, 28, 255); const COLOR_ORANGE = clay.Color.init(225, 138, 50, 255); // Layout config is just a struct that can be declared statically, or inline const sidebar_item_layout = clay.LayoutConfig{ .sizing = .{ .w = .grow, .h = .fixed(50) }, }; // Re-useable components are just normal functions fn sidebarItemComponent(index: usize) void { clay.element(.{ .id = clay.IdWithIndex("SidebarBlob", index), .layout = sidebar_item_layout, .rectangle = .{ .color = COLOR_ORANGE }, }); } // An example function to begin the "root" of your layout tree fn createLayout() clay.RenderCommandArray { clay.beginLayout(); // An example of laying out a UI with a fixed width sidebar and flexible width main content if (clay.open(.{ .id = clay.Id("OuterContainer"), .layout = .{ .sizing = .grow, .padding = .all(16), .child_gap = 16 }, .rectangle = .{ .color = .init(250, 250, 250, 255) }, })) { defer clay.close(); if (clay.open(.{ .id = clay.Id("SideBar"), .layout = .{ .direction = .top_to_bottom, .sizing = .{ .w = .fixed(300), .h = .grow }, .padding = .all(16), .child_gap = 16 }, .rectangle = .{ .color = COLOR_LIGHT }, })) { defer clay.close(); if (clay.open(.{ .id = clay.Id("ProfilePictureOuter"), .layout = .{ .sizing = .{ .w = .grow }, .padding = .all(16), .child_gap = 16, .alignment = .left_center }, .rectangle = .{ .color = COLOR_RED }, })) { defer clay.close(); clay.element(.{ .id = clay.Id("ProfilePicture"), .layout = .{ .sizing = .fixed(60) }, .image = .{ .image_data = &profile_picture, size = .all(60) }, }); clay.text("Clay - UI Library", .{ .font_size = 24, .text_color = .init(255, 255, 255, 255) }); } // Standard Zig code like loops etc. work inside components for (0..10) |i| sidebarItemComponent(i) } if (clay.open(.{ .id = clay.Id("MainContent"), .layout = .{ .sizing = .grow }, .rectangle = .{ .color = COLOR_LIGHT }, })) { defer clay.close(); // ... } } return clay.endLayout(); } ``` 5. Call [clay.endLayout()](https://github.com/nicbarker/clay/blob/main/README.md#clay_endlayout) and process the resulting [clay.RenderCommandArray](https://github.com/nicbarker/clay/blob/main/README.md#clay_rendercommandarray) in your choice of renderer. ```zig const render_commands = clay.endLayout(); for (render_commands.slice()) |render_command| { switch (render_command.type) { .rectangle => { drawRectangle(render_command.bounding_box, render_command.config.rectangle.color); }, // ... Implement handling of other command types } } ``` Please see the [full C documentation for clay](https://github.com/nicbarker/clay/blob/main/README.md) for API details. All public C functions and Macros have Zig binding equivalents, generally of the form `Clay_BeginLayoup` (C) -> `clay.beginLayout` (Zig)
https://avatars.githubusercontent.com/u/10281587?v=4
libqt6c
rcalixte/libqt6c
2025-03-07T13:05:39Z
Qt 6 for C
master
0
20
1
20
https://api.github.com/repos/rcalixte/libqt6c/tags
MIT
[ "bindings", "c", "gui-library", "qt", "qt6", "zig-package" ]
10,117
false
2025-04-01T09:08:35Z
true
true
<div align="center"> <img alt="libqt6c" src="assets/libqt6c.png" height="128px;" /> ![MIT License](https://img.shields.io/badge/License-MIT-green) [![Go Report Card](https://goreportcard.com/badge/github.com/rcalixte/libqt6c)](https://goreportcard.com/report/github.com/rcalixte/libqt6c) [![Static Badge](https://img.shields.io/badge/v0.14%20(stable)-f7a41d?logo=zig&logoColor=f7a41d&label=Zig)](https://ziglang.org/download/) </div> --- MIT-licensed Qt 6 bindings for C 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 [Building](#building) 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 [MIQT bindings for Go](https://github.com/mappu/miqt) 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 [FAQ](#faq) is a decent entry point for newcomers. Please try out the library and start a [discussion](https://github.com/rcalixte/libqt6c/discussions) if you have any questions or issues relevant to this library. --- TABLE OF CONTENTS ----------------- - [Supported Platforms](#supported-platforms) - [License](#license) - [Examples](#examples) - [Building](#building) - [Usage](#usage) - [FAQ](#faq) - [Special Thanks](#special-thanks) Supported platforms ------------------- | OS | Arch | Linkage (Bindings) | Status | | ------- | ------ | ------------------ | ------- | | FreeBSD | x86_64 | Static | βœ… Works | | Linux | arm64 | Static | βœ… Works | | Linux | x86_64 | Static | βœ… Works | License ------- The `libqt6c` bindings are licensed under the MIT license. You must also meet your Qt license obligations. Examples -------- The [`helloworld`](https://github.com/rcalixte/libqt6c-examples/tree/master/src/helloworld/main.c) example follows: ```c #include <libqt6c.h> #include <stdint.h> #include <stdio.h> #define BUFFER_SIZE 64 static long counter = 0; void button_callback(void* self) { counter++; char buffer[BUFFER_SIZE]; snprintf(buffer, BUFFER_SIZE, "You have clicked the button %ld time(s)", counter); q_pushbutton_set_text(self, buffer); } int main(int argc, char* argv[]) { // Initialize Qt application q_application_new(&argc, argv); QWidget* widget = q_widget_new2(); if (!widget) { // we can use assert or check for null to simulate exception handling // assert(widget != NULL); fprintf(stderr, "Failed to create widget\n"); return 1; } // We don't need to free the button, it's a child of the widget QPushButton* button = q_pushbutton_new5("Hello world!", widget); if (!button) { fprintf(stderr, "Failed to create button\n"); return 1; } q_pushbutton_set_fixed_width(button, 320); q_pushbutton_on_clicked(button, button_callback); q_widget_show(widget); int result = q_application_exec(); q_widget_delete(widget); printf("OK!\n"); return result; } ``` Full examples are available in the [`libqt6c-examples`](https://github.com/rcalixte/libqt6c-examples) repository. Building -------- FreeBSD (native) ---------------- - *Tested with FreeBSD 14 / Qt 6.8 / GCC 13* For dynamic linking with the Qt 6 system libraries: ```bash sudo pkg install qt6-base qt6-charts qt6-multimedia qt6-svg qt6-webchannel qt6-webengine qscintilla2-qt6 zig ``` > [!NOTE] > The `zig` package may need to be downloaded or compiled and installed separately if the latest stable version is not available in the default repositories. Linux (native) -------------- - *Tested with Debian 12 + 13 / Qt 6.4 + 6.8 / GCC 12 + 14* - *Tested with Linux Mint 22 / Qt 6.4 / GCC 13* - *Tested with Ubuntu 24.04 / Qt 6.4 / GCC 13* - *Tested with Fedora 41 / Qt 6.8 / GCC 14* - *Tested with EndeavourOS Mercury / Qt 6.8 / GCC 14* For dynamic linking with the Qt 6 system libraries: - __Debian-based distributions__: ```bash sudo apt install qt6-base-dev libqscintilla2-qt6-dev qt6-base-private-dev qt6-charts-dev qt6-multimedia-dev qt6-svg-dev qt6-webchannel-dev qt6-webengine-dev ``` > [!NOTE] > The `zig` package must be downloaded and installed separately. - __Fedora-based distributions__: ```bash sudo dnf install qt6-qtbase-devel qscintilla-qt6-devel qt6-qtcharts-devel qt6-qtmultimedia-devel qt6-qtsvg-devel qt6-qtwebchannel-devel qt6-qtwebengine-devel zig ``` > [!NOTE] > The `zig` package will need to be downloaded and installed separately if the latest stable version is not available in the default repositories. - __Arch-based distributions__: ```bash sudo pacman -S qt6-base qscintilla-qt6 qt6-charts qt6-multimedia qt6-svg qt6-webchannel qt6-webengine zig ``` Once the required packages are installed, the library can be built from the root of the repository: ```bash zig build ``` Users of Arch-based distributions need to __make sure that all packages are up-to-date__ first and will need to add the following option to support successful compilation: ```bash zig build -Denable-workaround=true ``` The compiled libraries can be installed to the system in a non-default location by adding the `--prefix-lib-dir` option to the build command: ```bash sudo zig build --prefix-lib-dir /usr/local/lib/libqt6c # creates /usr/local/lib/libqt6c/{libraries} ``` To skip the restricted extras: ```bash zig build -Dskip-restricted=true ``` To see the full list of build options available: ```bash zig build --help ``` Usage ----- - If using Zig's build system, import the library into your project: ```bash zig fetch --save git+https://github.com/rcalixte/libqt6c ``` Append `#<tag>`, `#<commit>`, or `#<branch>` to the end of the URL to pin to a specific version of the library. - Add the library to your `build.zig` file: ```zig const qt6c = b.dependency("libqt6c", .{ .target = target, .optimize = .ReleaseFast, }); // After defining the executable, add the include path from the library exe.root_module.addIncludePath(qt6c.path("include")); // Link the compiled libqt6c 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(qt6c.artifact(qt_lib_name)); ``` __Extra options are required for building on Arch-based distributions. Refer to the build system at the examples link below for more details.__ - Use the library in your code: ```c // the main qt6 header to import (C ABI Qt typedefs are included) #include <libqt6c.h> ``` Full examples of the build system and sample applications can be found in the [`libqt6c-examples`](https://github.com/rcalixte/libqt6c-examples) 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 `helloworld` example, only linking the libraries needed and without a warm cache, should take under 30 seconds. This assumes the Zig build system is being used. ### Q3. How does the `libqt6c` API differ from the official Qt C++ API? Supported Qt C++ class methods are implemented 1:1 as C functions where the function names in C correspond to the snake_case equivalent of the combined Qt C++ class and method names, with the `Q` prefix altered to `q_`. [The official Qt documentation](https://doc.qt.io/qt-6/classes.html) should be used for reference and is included in the library wrapper header code (though not all links are guaranteed to work perfectly, nor is this functionality in scope for this project). - `QWidget::show()` is projected as `q_widget_show(void*)` - `QPushButton::setText(QString)` is projected as `q_pushbutton_set_text(void*, const char*)` 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 C side. The C side is managed by the developer and the C++ side has variant ownership semantics. Ownership semantics are documented throughout the [C++ documentation](https://doc.qt.io/qt-6/topics-core.html). The library tries to adhere to idiomatic C where possible but is still bound by 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: - [Qt object ownership](https://doc.qt.io/qt-6/objecttrees.html) - [Qt signals and slots](https://doc.qt.io/qt-6/signalsandslots.html) - [Qt's property system](https://doc.qt.io/qt-6/properties.html) - [Qt's Meta-Object system](https://doc.qt.io/qt-6/metaobjects.html) - [Qt widgets](https://doc.qt.io/qt-6/examples-widgets.html) The `QByteArray` and `QString` types are projected as plain C types available within the standard library: `char*` and `const char*`. The `QList<T>` and `QVector<T>` types are projected as `T**` or `T*[]` when used as an input parameter and supported by the helper library as `libqt_list<T*>` when used as a return type. The `QMap<K,V>` and `QHash<K,V>` types are supported by the helper library as `libqt_map<K,V>` but are limited beyond basic capacities with no goal of feature expansion beyond the functionality required for adequate operation in the library. Consumers of this library are free to use types from other libraries as well, especially for hash types. The included helper library is not meant to be robust but merely to provide containers and functions for porting the Qt C++ API to a consumable C ABI. By default, this library does not expose the raw C ABI bindings and instead only makes the wrapper constructs available. Therefore, it is not possible call any of the Qt type's methods or the raw C ABI and some C equivalent method must be used instead. This library was constructed with the goal of enabling single-language application development. Anything beyond that boundary is up to the developer to implement. - C string types are internally converted to `QString` using `QString::fromUtf8`. Therefore, the C string input must be UTF-8 to avoid [mojibake](https://en.wikipedia.org/wiki/Mojibake). If the C input string contains binary data, the conversion would corrupt such bytes into U+FFFD (οΏ½). On return to C space, this becomes `\xEF\xBF\xBD`. - The `libqt6c` library does not extend the C standard library and therefore it is up to the developer to provide their own functions for complex types like `QMap` and `QHash` beyond the scope of the helper library's containers. Where Qt returns a C++ object by value (e.g. `QSize`), the binding may have moved it to the heap, and in C, this may be represented as a pointer type. In such cases, the caller is the owner and must free the object (using either `_delete` methods for the type or deallocation with `free`, `libqt_string_free`, etc.). This means code using `libqt6c` can look similar to the Qt C++ equivalent code but with the addition of proper memory management. The `connect(targetObject, targetSlot)` methods are projected as `_on_(targetObject, void (*)())`. While the parameters in the methods themselves are more convenient to use, the documentation comments in the C header 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. - You can also override virtual methods like `paint_event` in the same way. Where supported, there are additional `_on_` and `_qbase_` variants: - `on_paint_event`: Set an override callback function to be called when `paint_event` 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. - `qbase_paint_event`: Invoke the base class implementation of `paint_event`. This is useful for when the custom implementation requires the base class implementation. (When there is no override set, the `qbase_paint_event` implementation is equivalent to `paint_event`.) Qt class inherited types are projected via void pointers and type casting in C. For example, to pass a `QLabel* myLabel` to a function taking only the `QWidget*` base class, it should be sufficient to pass `myLabel` and the library will automatically cast it to the correct type and Qt vtable reference. - When a Qt subclass adds a method overload (e.g. `QMenu::sizeHint(QMenu*)` vs `QWidget::sizeHint(QWidget*)`), the base class version is shadowed and can only be called via `q_widget_size_hint(void*)` while the subclass implementation can be called directly, e.g. `q_menu_size_hint(void*)`. Inherited methods are shadowed for convenience as well, e.g. `q_menu_show(void*)` is equivalent to `q_widget_show(void*)`. 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. Qt expects fixed OS threads to be used for each QObject. When you first call `q_application_new`, that will be considered the [Qt main thread](https://doc.qt.io/qt-6/thread-basics.html#gui-thread-and-worker-thread). - When accessing Qt objects from inside another thread, it's safest to use `q_threading_async` to access the Qt objects from Qt's main thread. The [Threading library](https://github.com/rcalixte/libqt6c/tree/master/src/threading/libqt6cthreading.c) documents additional available strategies within the header code. Qt C++ enums are projected as PascalCase C typedef enums, replacing namespace indicators from C++ (`::`) with underscores and where enum values are represented by the uppercase equivalent of the Qt C++ class name, enum name, and enum value. For example, `Qt::AlignmentFlag` is projected as a C enum typedef of `Qt__AlignmentFlag` with values prefixed by `QT_ALIGNMENTFLAG`. Enums are not strongly typed in their definitions but are currently typed as `int64_t` parameters or return types by the C 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's build system? Currently, only `ReleaseFast`, `ReleaseSafe`, and `ReleaseSmall` are supported. The `Debug` build mode is not supported. This may change in the future. The default build mode is `ReleaseFast`. To change the build mode: ```bash zig build -Doptimize=ReleaseSafe ``` ### Q5. Can I use another build system? In theory, any build system that supports both C and C++ should work. However, this has only been lightly tested and is therefore unsupported and left as an exercise for the interested reader. ### Q6. Can I use Qt Designer and the Qt Resource system? MIQT (the upstream Qt bindings for Go) has a custom implementation of Qt `uic` and `rcc` tools, to allow using [Qt Designer](https://doc.qt.io/qt-6/qtdesigner-manual.html) for form design and resource management. There is work in progress to support Qt Designer with this library in the future. ### Q7. How can I add bindings for another Qt library? Fork this repository and add your library to the `genbindings/config-libraries` file. [Read more Β»](cmd/genbindings/README.md) Special Thanks -------------- - [@mappu](https://github.com/mappu) for the [MIQT](https://github.com/mappu/miqt) bindings that provided the phenomenal foundation for this project - [@arnetheduck](https://github.com/arnetheduck) for proving the value of collaboration on the back-end of this project while working across different target languages
https://avatars.githubusercontent.com/u/5464072?v=4
zig-tracer
nektro/zig-tracer
2023-09-20T23:00:09Z
Generic tracing library for Zig, supports multiple backends.
master
4
20
7
20
https://api.github.com/repos/nektro/zig-tracer/tags
MIT
[ "zig", "zig-package" ]
30
false
2025-03-04T21:29:16Z
true
false
# zig-tracer Generic tracing library for Zig, supports multiple backends. ## Install - Supports Zigmod - Supports Zig package manager ## Usage in your program: ```zig const std = @import("std"); const tracer = @import("tracer"); pub const build_options = @import("build_options"); pub const tracer_impl = tracer.spall; // see 'Backends' section below pub fn main() !void { try tracer.init(); defer tracer.deinit(); // main loop while (true) { try tracer.init_thread(); defer tracer.deinit_thread(); handler(); } } fn handler() void { const t = tracer.trace(@src()); defer t.end(); } ``` `@src()` values are sometimes absolute paths so backends may use this value to trim it to only log relative paths ```zig exe_options.addOption(usize, "src_file_trimlen", std.fs.path.dirname(std.fs.path.dirname(@src().file).?).?.len); ``` ## Backends - `none` this is the default and causes tracing calls to become a no-op so that `tracer` can be added to libraries transparently - `log` uses `std.log` to print on function entrance. - `chrome` writes a json file in the `chrome://tracing` format described [here](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview) and [here](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool/). - `spall` writes a binary file compatible with the [Spall](https://gravitymoth.com/spall/) profiler. - more? feel free to open an issue with requests! Any custom backend may also be used that defines the following functions: - `pub fn init() !void` - `pub fn deinit() void` - `pub fn init_thread(dir: std.fs.Dir) !void` - `pub fn deinit_thread() void` - `pub inline fn trace_begin(ctx: tracer.Ctx, comptime ifmt: []const u8, iargs: anytype) void` - `pub inline fn trace_end(ctx: tracer.Ctx) void` ## License MIT
https://avatars.githubusercontent.com/u/6756180?v=4
libvlc-zig
kassane/libvlc-zig
2022-12-08T17:13:15Z
Zig bindings for libVLC media framework.
main
7
20
0
20
https://api.github.com/repos/kassane/libvlc-zig/tags
BSD-2-Clause
[ "bindings", "libvlc", "libvlc-zig", "zig", "zig-library", "zig-package" ]
449
false
2025-03-06T14:00:03Z
true
true
<h1 align="center"> <div> <img src=".github/logo.png" alt="libvlc-zig logo"/> </div> </h1> <p align="center"> <a href="https://github.com/kassane/libvlc-zig/actions/workflows/Linux.yml"> <img alt="Build Linux status" src="https://github.com/kassane/libvlc-zig/actions/workflows/Linux.yml/badge.svg"> </a> <a href="https://github.com/kassane/libvlc-zig/actions/workflows/Darwin.yml"> <img alt="Build MacOS status" src="https://github.com/kassane/libvlc-zig/actions/workflows/Darwin.yml/badge.svg"> </a> <a href="https://github.com/kassane/libvlc-zig/actions/workflows/MinGW.yml"> <img alt="Build MinGW status" src="https://github.com/kassane/libvlc-zig/actions/workflows/MinGW.yml/badge.svg"> </a> <a href="https://opensource.org/licenses/BSD-2-Clause" rel="nofollow"> <img alt="BSD 2 Clause license" src="https://img.shields.io/github/license/kassane/libvlc-zig"/> </a> <a href="https://github.com/kassane/libvlc-zig/graphs/contributors"> <img alt="GitHub contributors" src="https://img.shields.io/github/contributors/kassane/libvlc-zig" /> </a> </p> # libvlc-zig Zig bindings for libVLC media framework. Some of the features provided by libVLC include the ability to play local files and network streams, as well as to transcode media content into different formats. It also provides support for a wide range of codecs, including popular formats like H.264, MPEG-4, and AAC. ## Requirements - [zig v0.11.0 or higher](https://ziglang.org/download) - [vlc](https://code.videolan.org/videolan/vlc) ## How to use ### Example ```bash $> zig build run -Doptimize=ReleaseSafe # print-version (default) $> zig build run -DExample="cliPlayer-{c,cpp,zig}" -Doptimize=ReleaseSafe -- -i /path/multimedia_file ``` ## How to contribute to the libvlc-zig project? Read [Contributing](CONTRIBUTING.md). ## FAQ ### Q: Why isn't libvlc-zig licensed under **LGPLv2.1**? A: The decision to license `libvlc-zig` under the **BSD-2 clause** was made by the author of the project. This license was chosen because it allows for more permissive use and distribution of the code, while still ensuring that the original author receives credit for their work. `libvlc-zig` respects the original **LGPLv2.1** (Lesser General Public License) license of the VLC project. ### Q: Are you connected to the developers of the original project? A: No, the author of `libvlc-zig` is not part of the **VideoLAN development team**. They are simply interested in being part of the VLC community and contributing to its development. ### Q: What is the main goal of this project? A: The main goal of `libvlc-zig` is to provide a set of bindings for the **VLC media player's** libvlc library that are written in the **Zig programming language**. The project aims to provide a more modern and safe way to interface with the library, while maintaining compatibility with existing code written in **C** and **C++**. ### Q: Does libvlc-zig aim to replace libvlc? A: No, `libvlc-zig` does not aim to replace libvlc. Instead, it provides an alternative way to interface with the library that may be more suitable for Zig developers. ### Q: Can I use libvlc-zig in my project? A: Yes, you can use `libvlc-zig` in your project as long as you comply with the terms of the **BSD-2 clause** license. This includes giving credit to the original author of the code. ### Q: Does libvlc-zig support all of the features of libvlc? A: `libvlc-zig` aims to provide bindings for all of the features of libvlc, but it may not be complete or up-to-date with the latest version of the library. If you encounter any missing features or bugs, please report them to the project's GitHub issues page. ### Q: What programming languages are compatible with libvlc-zig? A: `libvlc-zig` provides bindings for the **Zig programming language**, but it can also be used with **C** and **C++** projects that use the libvlc library. ## License ``` BSD 2-Clause License Copyright (c) 2022, Matheus Catarino França Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. ```
https://avatars.githubusercontent.com/u/188725936?v=4
discord.zig
discord-zig/discord.zig
2024-11-10T03:06:27Z
Mirror of Discord.zig
master
2
20
4
20
https://api.github.com/repos/discord-zig/discord.zig/tags
None
[ "discord", "zig", "zig-library", "zig-package", "ziglang" ]
232
false
2025-04-10T19:23:54Z
true
true
# Discord.zig A high-performance bleeding edge Discord library in Zig, featuring full API coverage, sharding support, and fine-tuned parsing * Sharding Support: Ideal for large bots, enabling distributed load handling. * 100% API Coverage & Fully Typed: Offers complete access to Discord's API with strict typing for reliable and safe code. * High Performance: Faster than whichever library you can name (WIP) * Flexible Payload Parsing: Supports payload parsing through both zlib and zstd*. * Proper error handling ```zig const std = @import("std"); const Discord = @import("discord"); const Shard = Discord.Shard; fn ready(_: *Shard, payload: Discord.Ready) !void { std.debug.print("logged in as {s}\n", .{payload.user.username}); } fn message_create(session: *Shard, message: Discord.Message) !void { if (std.ascii.eqlIgnoreCase(message.content.?, "!hi")) { var result = try session.sendMessage(message.channel_id, .{ .content = "hello world from discord.zig", }); defer result.deinit(); const m = result.value.unwrap(); std.debug.print("sent: {?s}\n", .{m.content}); } } pub fn main() !void { var gpa: std.heap.GeneralPurposeAllocator(.{}) = .init; const allocator = gpa.allocator(); var handler = Discord.init(allocator); defer handler.deinit(); try handler.start(.{ .intents = Discord.Intents.fromRaw(53608447), .token = std.posix.getenv("DISCORD_TOKEN").?, .run = .{ .message_create = &message_create, .ready = &ready }, }); } ``` ## Installation ```zig // In your build.zig file const exe = b.addExecutable(.{ .name = "marin", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const dzig = b.dependency("discord.zig", .{}); exe.root_module.addImport("discord.zig", dzig.module("discord.zig")); ``` **Warning**: the library is intended to be used with the latest dev version of Zig. ## contributing Contributions are welcome! Please open an issue or pull request if you'd like to help improve the library. * Support server: https://discord.gg/RBHkBt7nP5 * The original repo: https://codeberg.org/yuzu/discord.zig ## general roadmap | Task | Status | |-------------------------------------------------------------|--------| | stablish good sharding support with buckets | βœ… | | finish the event coverage roadmap | βœ… | | proper error handling | βœ… | | use the priority queues for handling ratelimits (half done) | ❌ | | make the library scalable with a gateway proxy | ❌ | | get a cool logo | ❌ | ## missing events right now | Event | Support | |----------------------------------------|---------| | voice_channel_effect_send | ❌ | | voice_state_update | ❌ | | voice_server_update | ❌ | ## http methods missing | Endpoint | Support | |----------------------------------------|---------| | Audit log | ❌ | | Automod | ❌ | | Guild Scheduled Event related | ❌ | | Guild template related | ❌ | | Soundboard related | ❌ | | Stage Instance related | ❌ | | Subscription related | ❌ | | Voice related | ❌ | | Webhook related | ❌ |
https://avatars.githubusercontent.com/u/53349189?v=4
zentig_ecs
freakmangd/zentig_ecs
2023-04-18T21:48:53Z
Zig ECS library
main
0
20
2
20
https://api.github.com/repos/freakmangd/zentig_ecs/tags
MIT
[ "ecs", "game-development", "gamedev", "zig", "zig-package" ]
6,384
false
2025-03-18T12:41:13Z
true
true
# zentig_ecs A Zig ECS library. Zentig is designed for scalability and ease of use, while staying out of your way. It's heavily inspired by everything that makes [bevy_ecs](https://github.com/bevyengine/bevy) so great and [Unity](https://unity.com/) so approachable. ##### WARNING: It is not recommended to use zentig for anything major in it's current state. While it is functional and I use it frequently, it is far from battle tested. That being said, if you encounter any problems please feel free to open an issue! ## Installation Fetching for zig master: ``` zig fetch --save git+https://github.com/freakmangd/zentig_ecs ``` Fetching for zig 0.13.0: ``` zig fetch --save https://github.com/freakmangd/zentig_ecs/archive/refs/tags/0.13.0.tar.gz ``` In both cases, place this in your `build.zig`: ```zig const zentig = b.dependency("zentig-ecs", .{}); exe.root_module.addImport("ztg", zentig.module("zentig")); ``` And import it in your project: ```zig const ztg = @import("ztg"); ``` ## Overview An entity is just a `usize`: ```zig pub const Entity = usize; ``` A basic component: ```zig pub const Player = struct { name: []const u8, }; ``` A basic system: ```zig pub fn playerSpeak(q: ztg.Query(.{Player})) !void { for (q.items(Player)) |plr| { std.debug.print("My name is {s}\n", .{self.name}); } } ``` Registering systems/components into a world: ```zig const MyWorld = blk: { var wb = ztg.WorldBuilder.init(&.{}); wb.addComponents(&.{Player}); wb.addSystemsToStage(.update, playerSpeak); break :blk wb.Build(); }; ``` Calling systems is easily integratable into your game framework: ```zig test "running systems" { var world = MyWorld.init(testing.allocator); defer world.deinit(); try world.runStage(.load); try world.runUpdateStages(); try world.runStage(.draw); // Support for user defined stages try world.runStageList(&.{ .post_process, .pre_reset, .post_mortem }); } ``` ## Scalability The `.include()` function in `WorldBuilder` makes it easy to compartmentalize your game systems. As well as integrate third party libraries with only one extra line! `main.zig`: ```zig // .include() looks for a `pub fn include(comptime *WorldBuilder) (!)void` def // in each struct. If the function errors it's a compile error, // but the signature can return either `!void` or `void` wb.include(&.{ ztg.base, @import("player.zig"), @import("my_library"), }); ``` `player.zig`: ```zig pub fn include(comptime wb: *ztg.WorldBuilder) void { wb.addComponents(.{ Player, PlayerGun, PlayerHUD }); wb.addSystemsToStage(.update, .{ update_player, update_gun, update_hud }); } ``` `my_library/init.zig`: ```zig pub fn include(comptime wb: *ztg.WorldBuilder) void { wb.include(&.{ // Namespaces can be included more than once to "ensure" // they are included if you depend on them ztg.base, //... }); } ``` ## Getting Started See this short tutorial on creating systems and components [here](https://github.com/freakmangd/zentig_ecs/tree/main/docs/hello_world.md) ## Full Examples See full examples in the [examples folder](https://github.com/freakmangd/zentig_ecs/tree/main/examples) ## Framework Support zentig is framework agnostic, it doesn't include any drawing capabilities. For that you need something like Raylib, I've created a library that wraps common Raylib components and provides systems that act on those components [here](https://github.com/freakmangd/zentig_raylib). That page provides installation instructions and usage examples.
https://avatars.githubusercontent.com/u/4678790?v=4
zubench
dweiller/zubench
2022-05-18T11:14:14Z
Micro benchmarking in zig
main
0
20
3
20
https://api.github.com/repos/dweiller/zubench/tags
MIT
[ "zig-package" ]
55
false
2025-03-18T05:12:59Z
true
true
# zubench A micro-benchmarking package for [Zig](https://ziglang.org). ## goals The primary goals of **zubench** are to: - be simple to use - there should be no need to wrap a function just to benchmark it - provide standard machine-readable output for archiving or post-processing - given the user the choice of which system clock(s) to use - provide statistically relevant and accurate results - integrate with the Zig build system Not all these goals are currently met, and its always possible to debate how well they are met; feel free to open an issue (if one doesn't exist) or pull request if you would like to see improvement in one of these areas. ## features - [x] human-readable terminal-style output - [x] machine-readable JSON output - [x] wall, process, and thread time - [ ] kernel/user mode times - [x] declarative `zig test` style benchmark runner - [x] option to define benchmarks as Zig tests - [ ] adaptive sample sizes - [x] [MAD](https://en.wikipedia.org/wiki/Median_absolute_deviation)-based outlier rejection ## platforms Some attempt has been made to work on the below platforms; those with a '️️️️️⚠️' in the table below haven't been tested, but _should_ work for all implemented clocks. Windows currently only has the wall time clock implemented. If you find a non-Linux platform either works or has issues please raise an issue. | Platform | Status | | :------: | :----: | | Linux | βœ… | | Windows | ❗ | | Darwin | ⚠️ | | BSD | ⚠️ | | WASI | ⚠️ | ## usage The *main* branch follows Zig's master branch, for Zig 0.12 use the *zig-0.12* branch. The simplest way to create and run benchmarks is using one of the Zig build system integrations. There are currently two integrations, one utilising the Zig test system, and one utilising public declarations. Both integrations will compile an executable that takes a collection of functions to benchmark, runs them repeatedly and reports timing statistics. The differences between the two integrations are how you define benchmarks in your source files, and how benchmarking options are determined. ### test integration The simplest way to define and run benchmarks is utilising the Zig test system. **zubench** will use a custom test runner to run the benchmarks. This means that benchmarks are simply Zig tests, i.e. `test { // code to benchmark }`. In order to avoid benchmarking regular tests when using this system, you should consider the way that Zig analyses test declarations and either give the names of benchmark tests a unique substring that can be used as a test filter or organise your tests so that when the compiller analyses the root file for benchmark tests, it will not analyse regular tests. The following snippets show how you can use this integration. ```zig const addTestBench = @import("zubench/build.zig").addTestBench; pub fn build(b: *std.build.Builder) void { // existing build function // ... // benchmark all tests analysed by the compiler rooted in "src/file.zig", compiled in ReleaseSafe mode const benchmark_exe = zubench.addTestBench(b, "src/file.zig", .ReleaseSafe); // use a test filter to only benchmark tests whose name include the substring "bench" // note that this is not required if the compiler will not analyse tests that you don't want to benchmark benchmark_exe.setTestFilter("bench"); const bench_step = b.step("bench", "Run the benchmarks"); bench_step.dependOn(&benchmark_exe.run().step); } ``` This will make `zig build bench` benchmark tests the compiler analyses by starting at `src/file.zig`. `addTestBench()` returns a `*LibExeObjStep` for an executable that runs the benchmarks; you can integrate it into your `build.zig` however you wish. Benchmarks are `test` declarations the compiler analyses staring from `src/file.zig`: ```zig // src/file.zig test "bench 1" { // this will be benchmarked // ... } test "also a benchmark" { // this will be benchmarked // ... } test { // this will be benchmarked // the test filter is ignored for unnamed tests // ... } test "regular test" { // this will not be benchmarked return error.NotABenchmark; } ``` ### public decl integration This integration allows for fine-grained control over the execution of benchmarks, allowing you to specify various options as well as benchmark functions that take parameters. The following snippets shows how you can use this integration. ```zig // build.zig const addBench = @import("zubench/build.zig").addBench; pub fn build(b: *std.build.Builder) void { // existing build function // ... // benchmarks in "src/file.zig", compiled in ReleaseSafe mode const benchmark_exe = addBench(b, "src/file.zig", .ReleaseSafe); const bench_step = b.step("bench", "Run the benchmarks"); bench_step.dependOn(&benchmark_exe.run().step); } ``` This will make `zig build bench` run the benchmarks in `src/file.zig`, and print the results. `addBench()` returns a `*LibExeObjStep` for an executable that runs the benchmarks; you can integrate it into your `build.zig` however you wish. Benchmarks are specified in `src/file.zig` by creating a `pub const benchmarks` declaration: ```zig // add to src/file.zig // the zubench package const bench = @import("src/bench.zig"); pub const benchmarks = .{ .@"benchmark func1" = bench.Spec(func1){ .args = .{ arg1, arg2 }, .max_samples = 100 }, .@"benchmark func2" = bench.Spec(func2){ .args = .{ arg1, arg2, arg3 }, .max_samples = 1000, .opts = .{ .outlier_detection = .none }}, // disable outlier detection } ``` The above snippet would cause two benchmarks to be run called "benchmark func1" and "benchmark func2" for functions `func1` and `func2` respectively. The `.args` field of a `Spec` is a `std.meta.ArgsTuple` for the corresponding function, and `.max_samples` determines the maximum number of times the function is run during benchmarking. A complete example can be found in `examples/fib_build.zig`. It is also relatively straightforward to write a standalone executable to perform benchmarks without using the build system integration. To create a benchmark for a function `func`, run it (measuring process and wall time) and obtain a report, all that is needed is ```zig var progress = std.Progress.start(.{}); var bm = try Benchmark(func).init(allocator, "benchmark name", .{ func_arg_1, … }, .{}, max_samples, progress); const report = bm.run(); bm.deinit(); ``` The `report` then holds a statistical summary of the benchmark and can used with `std.io.Writer.print` (for terminal-style readable output) or `std.json.stringify` (for JSON output). See `examples/` for complete examples. ### Custom exectuable It is also possible to write a custom benchmarking executable using **zubench** as a dependency. There is a simple example of this in `examples/fib2.zig` or, you can examine `src/bench_runner.zig`. ## examples Examples showing some ways of producing and running benchmarks can be found the `examples/` directory. Each of these files are built using the root `build.zig` file. All examples can be built using `zig build examples` and they can be run using `zig build run`. ## status **zubench** is in early developmentβ€”the API is not stable at the moment and experiments with the API are planned, so feel free to make suggestions for the API or features you would find useful.
https://avatars.githubusercontent.com/u/3932972?v=4
zig-assimp
ikskuh/zig-assimp
2021-09-03T08:25:20Z
Open Asset Importer Library built with Zig
master
3
20
11
20
https://api.github.com/repos/ikskuh/zig-assimp/tags
BSD-3-Clause
[ "3d-formats", "assimp", "assimp-port", "zig", "zig-package", "ziglang" ]
81
false
2025-03-18T14:00:15Z
true
true
# OpenAssetImporter Library Binding for Zig This repo is a build sdk for [Assimp](https://github.com/assimp/assimp) to be used with the Zig build system: ```zig const std = @import("std"); // Import the SDK const Assimp = @import("Sdk.zig"); pub fn build(b: *std.build.Builder) void { const mode = b.standardReleaseOptions(); const exe = b.addExecutable("static-example", null); exe.setBuildMode(mode); exe.addCSourceFile("src/example.cpp", &[_][]const u8{"-std=c++17"}); exe.linkLibC(); exe.linkLibCpp(); exe.install(); // Create a new instance var sdk = Assimp.init(b); // And link Assimp statically to our exe and enable a default set of // formats. sdk.addTo(exe, .static, Assimp.FormatSet.default); } ```
https://avatars.githubusercontent.com/u/146390816?v=4
openssl
allyourcodebase/openssl
2024-04-13T01:43:54Z
openssl zig package
main
2
19
5
19
https://api.github.com/repos/allyourcodebase/openssl/tags
MIT
[ "zig-package" ]
750
false
2025-03-24T08:04:43Z
true
true
# openssl zig package This is openssl ported to the Zig Build System. ## Status I was able to use this to build [CPython](https://github.com/thejoshwolfe/cpython) for x86_64-linux. Adding support for other operating systems and CPU architectures is straightforward and will require fiddling with the build script to take into account the target. ## Anti-Endorsement I do not endorse openssl. I think it is a pile of trash. My motivation for this project is because it is a dependency of CPython, which is a dependency of the most active YouTube downloader, [ytdlp](https://github.com/yt-dlp/yt-dlp).
https://avatars.githubusercontent.com/u/20110944?v=4
zigtris
ringtailsoftware/zigtris
2024-11-17T19:50:13Z
A minimal terminal Tetris written in Zig
main
0
19
2
19
https://api.github.com/repos/ringtailsoftware/zigtris/tags
MIT
[ "zig-package" ]
613
false
2025-02-06T07:46:02Z
true
true
# Zigtris A minimal terminal Tetris written in Zig. Tested with Zig 0.14.0 `zig build run` Cursor keys to move, space to drop, `q` to quit. ![](demo.gif) # I just want to play! don't make me install Zig docker run --rm -it -v `pwd`:/app -w /app kassany/alpine-ziglang:0.13.0 zig build run # Run as a service via ssh ./run-as-service.sh ssh zigtris@localhost -p 2022 # Notes Some notes for anyone looking at the code: - `Display` is a thin wrapper on top of the `mibu` terminal library, it provides a double buffered one pixel per character interface where it only redraws changed pixels on the buffer flip - `Stage` is the game stage and provides a square pixel interface on top of `Display` (by printing two chars for each pixel) - `Player` holds the `Tetronimo` shapes and movement logic - `Debris` holds the list of fallen blocks for hitchecking and completed line detection # License MIT
https://avatars.githubusercontent.com/u/41784264?v=4
znvim
jinzhongjia/znvim
2024-02-13T17:11:29Z
neovim remote rpc client implementation with zig
main
2
19
2
19
https://api.github.com/repos/jinzhongjia/znvim/tags
MIT
[ "neovim", "neovim-remote", "zig", "zig-package" ]
154
false
2025-03-03T02:26:56Z
true
true
# znvim _znvim_ is a [neovim remote rpc](https://neovim.io/doc/user/api.html#rpc-connecting) client implementation with [`zig`](https://ziglang.org/). > This package is under developing! ## Document [https://jinzhongjia.github.io/znvim/](https://jinzhongjia.github.io/znvim/) ## Features - Implementation of multiple remote calling methods - Support all neovim rpc [channels](https://neovim.io/doc/user/channel.html#channel-intro) - Completely thread safe - Asynchronous ## Getting Started ### `0.12.0` / `0.13.0` / `master` 1. Add to `build.zig.zon` ```sh zig fetch --save https://github.com/jinzhongjia/znvim/archive/{commit or branch}.tar.gz ``` 2. Config `build.zig` ```zig const znvim = b.dependency("znvim", .{ .target = target, .optimize = optimize, }); // add module exe.root_module.addImport("znvim", znvim.module("znvim")); ``` ## To use this lib You can find example on `test` fold! Recommend to learn about what [msgpack](https://github.com/msgpack/msgpack/blob/master/spec.md) is (this lib uses [zig-msgpack](https://github.com/zigcc/zig-msgpack)) and read neovim's API [documentation](https://neovim.io/doc/user/api.html).
https://avatars.githubusercontent.com/u/12820359?v=4
astroz
ATTron/astroz
2024-06-25T00:35:54Z
Astrodynamics and Spacecraft Toolkit Written in Zig! Features orbit prop, celestial precession, CCSDS parsing, RF parsing, fits image parsing, and more!
main
0
19
1
19
https://api.github.com/repos/ATTron/astroz/tags
GPL-3.0
[ "astro", "astronomy", "astrophysics", "ccsds", "celestial-bodies", "fits-files", "fits-image", "orbital-simulation", "radio-frequency", "rf", "space", "spacecraft", "tle", "toolkit", "vita", "zig", "zig-library", "zig-package" ]
107,268
false
2025-03-24T07:08:34Z
true
true
# ASTROZ [![CI][ci-shd]][ci-url] [![CD][cd-shd]][cd-url] [![DC][dc-shd]][dc-url] <img src="https://repository-images.githubusercontent.com/819657891/291c28ef-4c03-4d0e-bb0c-41d4662867c3" width="100" height="100"/> ## Astronomical and Spacecraft Toolkit Written in Zig for Zig! ### Features / Plans #### Spacecraft - [x] CCSDS Packets - [x] CCSDS Stream Parser - [x] VITA49 Packets - [x] Vita49 Stream Parser - [x] TLE Support - [x] Orbital Propagation - [x] RK4 - [x] Orbital Maneuvers - [x] Impulse Maneuvers - [x] Phase Maneuvers - [x] Plane Change Maneuvers - [x] Orientation Determination #### Astronomical - [x] Astronomical References - [x] J2000 and JD - [x] Celestial Bodies - [x] Mass - [x] Radius - [x] Orbital Details - [x] Astronomical Coordinates - [x] Equatorial Coordinate System - [x] World Coordinate System - [x] Astronomical Computation - [x] Precession - [x] Celestial Bodies - [ ] Orbital Mechanics - [ ] Interplanetary Maneuvers - [ ] FITS File Parsing - BROKEN DUE TO ZIGIMG DEPENDENCY BREAKING ON MAIN - [x] Image Generation - [ ] Multi Image Parsing/Generation - [x] Table Parsing ### Feature not listed ? To request a feature, please create an issue for this project and I will try my best to be responsive. ### Usage - Add `astroz` as a dependency in your `build.zig.zon`. ```sh zig fetch --save https://github.com/ATTron/astroz/archive/<git_tag_or_commit_hash>.tar.gz ``` - Use `astroz` as a module in your `build.zig`. ```zig const astroz_dep = b.dependency("astroz", .{ .target = target, .optimize = optimize, }); const astroz_mod = astroz_dep.module("astroz"); exe.root_module.addImport("astroz", astroz_mod); ``` ### Examples - #### [Parse TLE](examples/parse_tle.zig) - #### [Orbit Prop for Next 3 Days](examples/orbit_prop.zig) <img src="assets/orbit_prop.gif" width="450" height="400" alt="visualization of orbit prop"/> - #### [Orbit Prop for Next 3 Days with Impulse Maneuvers](examples/orbit_prop_impulse_manuevers.zig) <img src="assets/orbit_prop_impulse.gif" width="450" height="400" alt="visualization of orbit prop with impulse"/> - #### [Orbit Plane Change](examples/orbit_plane_change.zig) - #### [Orbit Phase Change](examples/orbit_phase_change.zig) - #### [Orbit Orientation Determination](examples/simple_spacecraft_orientation.zig) - #### [Parse Vita49](examples/parse_vita49.zig) - #### [Parse Vita49 with Callback](examples/parse_vita49_callback.zig) - #### [Parse CCSDS from File](examples/parse_ccsds.zig) - #### [Parse CCSDS from File with File Sync](examples/parse_ccsds_file_sync.zig) - #### [Create CCSDS Packet](examples/create_ccsds_packet.zig) - #### [Create CCSDS Packet with Config](examples/create_ccsds_packet_config.zig) **NOTE THIS IS CURRENTLY BROKEN DUE TO ZIGIMG DEPENDENCY BREAKING ON THE MAIN BRANCH** - #### [Generate Image from FITS File](examples/parse_fits_file.zig) <img src="test/test.png" width="450" height="400" alt="sample fits image as png"/> - #### [Precess star to July 30, 2005](examples/precess_star.zig) - #### [Calculate WCS values from a TLE](examples/wcs.zig) <!-- MARKDOWN LINKS --> [ci-shd]: https://img.shields.io/github/actions/workflow/status/ATTron/astroz/ci.yaml?branch=main&style=for-the-badge&logo=github&label=CI&labelColor=black [ci-url]: https://github.com/ATTron/astroz/blob/main/.github/workflows/ci.yaml [cd-shd]: https://img.shields.io/github/actions/workflow/status/ATTron/astroz/cd.yaml?branch=main&style=for-the-badge&logo=github&label=CD&labelColor=black [cd-url]: https://github.com/ATTron/astroz/blob/main/.github/workflows/cd.yaml [dc-shd]: https://img.shields.io/badge/click-F6A516?style=for-the-badge&logo=zig&logoColor=F6A516&label=doc&labelColor=black [dc-url]: https://attron.github.io/astroz
https://avatars.githubusercontent.com/u/124872?v=4
zig-rocca-s
jedisct1/zig-rocca-s
2021-10-19T23:02:17Z
An implementation of the ROCCA-S encryption scheme.
master
0
19
0
19
https://api.github.com/repos/jedisct1/zig-rocca-s/tags
MIT
[ "aead", "cipher", "rocca", "rocca-s", "zig", "zig-package" ]
24
false
2024-10-25T11:52:51Z
true
false
# ROCCA-S: an efficient AES-based encryption scheme This is an implementation of [ROCCA-S: an efficient AES-based encryption scheme for beyond 5G](https://www.ietf.org/archive/id/draft-nakano-rocca-s-05.html), a very fast authenticated encryption scheme optimized for platforms with AES-NI or ARM crypto extensions. ROCCA-S has a 256 bit key size, a 128 bit nonce, processes 256 bit message blocks and outputs a 256 bit authentication tag. **Warning:** this implementation is for benchmarking and testing purposes only.
https://avatars.githubusercontent.com/u/15014128?v=4
zbgfx
cyberegoorg/zbgfx
2024-04-10T12:00:23Z
When zig meets bgfx.
main
1
19
3
19
https://api.github.com/repos/cyberegoorg/zbgfx/tags
WTFPL
[ "bgfx", "bgfx-graphics-library", "gamedev", "zig", "zig-package" ]
9,686
false
2025-04-02T14:27:20Z
true
true
# ZBgfx [![GitHub Actions](https://github.com/cyberegoorg/zbgfx/actions/workflows/test.yaml/badge.svg)](https://github.com/cyberegoorg/zbgfx/actions/workflows/test.yaml) When [zig](https://github.com/ziglang/zig) meets [bgfx](https://github.com/bkaradzic/bgfx). ## Features - [x] Zig api. - [x] Compile as standard zig library. - [x] `shaderc` as build artifact. - [x] Shader compile in `build.zig` to `*.bin.h`. - [x] Shader compile in `build.zig` and embed as zig module. (this is zig equivalent of `*.bin.h`) - [x] Shader compile from runtime via `shaderc` as child process. - [x] Binding for [DebugDraw API](https://github.com/bkaradzic/bgfx/tree/master/examples/common/debugdraw) - [x] `imgui` render backend. Use build option `imgui_include` to enable. ex. for zgui: `.imgui_include = zgui.path("libs").getPath(b),` - [ ] Zig based allocator. > [!IMPORTANT] > This is only zig binding. For BGFX stuff goto [bgfx](https://github.com/bkaradzic/bgfx). > [!WARNING] > - `shaderc` need some time to compile. > [!NOTE] > - If you build shaders/app and see something like `run shaderc (shader.bin.h) stderr`. This is not "true" error (build success), but only in debug build shader print some stuff to stderr and zig build catch it. ## License Folders `libs`, `shaders` is copy&paste from [bgfx](https://github.com/bkaradzic/bgfx) for more sell-contained experience and is licensed by [LICENSEE](https://github.com/bkaradzic/bgfx/blob/master/LICENSE) Zig binding is licensed by [WTFPL](LICENSE) ## Zig version Minimal is `0.14.0`. But you know try your version and believe. ## Bgfx version - [BX](https://github.com/bkaradzic/bx//compare/01c99ddd0912c5ecf56d9522f287c6c67aa3ad14...master) - [BImg](https://github.com/bkaradzic/bimg/compare/c5c7b6e1874cf60caa18b643391f5122f89a4ca8...master) - [BGFX](https://github.com/bkaradzic/bgfx/compare/de56398919b875b27b629c0b62f119c338c081d8...master) ## Getting started Copy `zbgfx` to a subdirectory of your project and then add the following to your `build.zig.zon` .dependencies: ```zig .zbgfx = .{ .path = "path/to/zbgfx" }, ``` or use `zig fetch --save ...` way. Then in your `build.zig` add: ```zig pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ ... }); const zbgfx = b.dependency("zbgfx", .{}); exe.root_module.addImport("zbgfx", zbgfx.module("zbgfx")); exe.linkLibrary(zbgfx.artifact("bgfx")); // This install shaderc to install dir // For shader build in build =D check examples // b.installArtifact(zbgfx.artifact("shaderc")); } ``` ## Usage See examples for binding usage and [bgfx](https://github.com/bkaradzic/bgfx) for bgfx stuff. ## Build options | Build option | Default | Description | |-----------------|---------|------------------------------------------------------| | `imgui_include` | `null` | Path to ImGui includes (need for imgui bgfx backend) | | `multithread` | `true` | Compile with `BGFX_CONFIG_MULTITHREADED` | | `with_shaderc` | `true` | Compile with `shaderc` | ## Examples Run this for build all examples: ```sh cd examples zig build ``` ### [00-Minimal](examples/00-minimal/) Minimal setup with GLFW for window and input. ```sh examples/zig-out/bin/00-minimal ``` | Key | Description | |-----|--------------| | `v` | Vsync on/off | | `d` | Debug on/off | ### [01-ZGui](examples/01-zgui/) Minimal setup for zgui/ImGui. ```sh examples/zig-out/bin/01-zgui ``` | Key | Description | |-----|--------------| | `v` | Vsync on/off | | `d` | Debug on/off | ### [02-Runtime shaderc](examples/02-runtime-shaderc/) Basic usage of shader compile in runtime. Try edit shaders in `zig-out/bin/shaders` and hit `r` to recompile. ```sh examples/zig-out/bin/02-runtime-shaderc ``` | Key | Description | |-----|-----------------------------| | `v` | Vsync on/off | | `d` | Debug on/off | | `r` | Recompile shaders form file | ### [03-debugdraw](examples/03-debugdraw/) DebugDraw api usage example. ```sh examples/zig-out/bin/03-debugdraw ``` | Key | Description | |-----|--------------| | `v` | Vsync on/off | | `d` | Debug on/off |
https://avatars.githubusercontent.com/u/146390816?v=4
pipewire
allyourcodebase/pipewire
2024-06-08T05:57:45Z
pipewire ported to the zig build system
main
0
18
0
18
https://api.github.com/repos/allyourcodebase/pipewire/tags
MIT
[ "zig-package" ]
3
false
2025-03-19T01:05:04Z
true
true
# pipewire Pipewire client library, ported to the Zig build system. ## Motivation I want a static executable that can play audio. I have this working already with libsoundio, however, it is via the pulseaudio client library. I thought it would be nice to use pipewire directly on systems that use it. ## Status I got the audio-src example compiling and running, however, it turns out the pipewire protocol only works via `dlopen`, making it a non-starter for static executables. Therefore, I will not be pursuing this project any further.
https://avatars.githubusercontent.com/u/20110944?v=4
misshod
ringtailsoftware/misshod
2024-12-28T02:56:39Z
MiSSHod is a minimal, experimental SSH client and server implemented as a library
main
0
18
1
18
https://api.github.com/repos/ringtailsoftware/misshod/tags
MIT
[ "ssh", "ssh-client", "ssh-server", "zig", "zig-package", "ziglang" ]
398
false
2025-01-14T08:11:47Z
true
true
# MiSSHod *misshod. (ˌmΙͺsΛˆΚƒΙ’d). adj. badly shod* # About MiSSHod is a minimal, experimental SSH client and server implemented as a library. It has been tested with both [OpenSSH](https://github.com/openssh/openssh-portable) and [Dropbear](https://github.com/mkj/dropbear). **MiSSHod is not secure, it should not be used in real world systems** It aims to be: - Transport and I/O agnostic - TCP would be normal, but MiSShod can be run over any reliable stream protocol - Asynchronous - MiSShod never blocks execution for I/O, it enters a wait state and can be resumed when data arrives - Callback free - asynchronous message passing prevents the caller needing callbacks and context structs - Very lightweight, opening up the possibility of running on small embedded devices **Features** - Public key auth - Password auth - Supports exactly one of each of the required protocols - hmac-sha2-256 (hmac) - curve25519-sha256 (key exchange) - ssh-ed25519 (key) - aes256-ctr (cipher) # Building MiSSHod requires [Zig 0.14.0](https://ziglang.org/download/). ## Client To build `mssh`, a command line SSH client for Mac/Linux ```bash zig build test ``` ```bash cd mssh zig build ./zig-out/bin/mssh ./zig-out/bin/mssh <username@host> <port> [idfile] ``` To run a test SSH server (dropbear) in docker ```bash cd testserver ./sshserver ``` Login with password auth, ("password") ```bash ./zig-out/bin/mssh [email protected] 2022 # Same as: ssh -p 2022 [email protected] ``` Login with pubkey auth using a passwordless private key ```bash ./zig-out/bin/mssh [email protected] 2022 ../testserver/id_ed25519_passwordless # Same as: ssh -p 2022 [email protected] -i ../testserver/id_ed25519_passwordless ``` Login with pubkey auth using a password protected private key ("secretpassword") ```bash ./zig-out/bin/mssh [email protected] 2022 ../testserver/id_ed25519_passworded # Same as: ssh -p 2022 [email protected] -i ../testserver/id_ed25519_passworded ``` ## Server `msshd` is a toy ssh server. It handles one connection at a time and echoes back received data with "You said X". To build `msshd` ```bash cd msshd zig build ./zig-out/bin/msshd ./zig-out/bin/msshd <port> <hostkey> ``` To run the server ```bash ./zig-out/bin/msshd 2022 ../testserver/id_ed25519_passwordless Server listening on port 2022 ``` Connect using OpenSSH ```bash ssh -p 2022 [email protected] ``` By default the server will accept any public key offered. Typically, OpenSSH offers all available keys, so it will be able to login immediately. This can be changed in `msshd/src/main.zig`. Typically, a real server would check the user's `authorized_keys` file. Connect using `mssh` using pubkey auth (key password is "secretpassword") ```bash cd mssh zig build run -- [email protected] 2022 ../testserver/id_ed25519_passworded ``` Connect using `mssh` using password auth (any password matching username will be accepted, so "foo" here) ```bash cd mssh zig build run -- [email protected] 2022 ``` # Tiny client example As a proof of concept, the `tiny` example logs into the test server but contains no socket code. Instead, it uses stdout and stdin. To run it via `socat`: ```bash zig build && socat TCP4:127.0.0.1:2022 EXEC:./zig-out/bin/tiny ``` Tiny uses a weaker PRNG, a fixed buffer allocator and does no file I/O. # Security **MiSSHod is not secure, it should not be used in real world systems** - Very little testing has been done and not all code paths have been exercised - No efforts have been made to prevent timing attacks - Sensitive data is held in RAM for longer than is strictly necessary - MiSSHod relies on Zig's standard library for all crypto algorithms, which is still relatively young - Most importantly, I am not a cryptographer and I have no idea what I'm doing # Status MiSSHod was developed rapidly. The main aim was to get it working and learn something along the way. I don't know what's next, but hopefully you can learn something too by looking at a small SSH implementation. It's entirely undocumented and there aren't enough tests. The IO systems are a bit arcane, as I've tried wherever possible to avoid using excess RAM.
https://avatars.githubusercontent.com/u/41784264?v=4
zig-lamp
jinzhongjia/zig-lamp
2025-02-06T05:05:07Z
Improve the zig experience in neovim
main
1
18
1
18
https://api.github.com/repos/jinzhongjia/zig-lamp/tags
None
[ "neovim", "neovim-lua-plugin", "neovim-plugin", "zig", "zig-library", "zig-package", "ziglang" ]
84
false
2025-03-26T16:47:46Z
true
true
404
https://avatars.githubusercontent.com/u/124872?v=4
zig-eddsa-key-blinding
jedisct1/zig-eddsa-key-blinding
2022-01-20T21:42:36Z
A Zig implementation of EdDSA signatures with blind keys.
main
0
17
1
17
https://api.github.com/repos/jedisct1/zig-eddsa-key-blinding/tags
MIT
[ "blinding", "ed25519", "eddsa", "zig", "zig-package" ]
5
false
2025-01-18T04:18:25Z
true
false
# EdDSA signatures with blind keys A Zig implementation of the [EdDSA key blinding](https://chris-wood.github.io/draft-wood-cfrg-eddsa-blinding/draft-wood-cfrg-eddsa-blinding.html) proposal. ```zig // Create a standard Ed25519 key pair const kp = try Ed25519.KeyPair.create(null); // Create a random blinding seed var blind: [32]u8 = undefined; crypto.random.bytes(&blind); // Blind the key pair const blind_kp = try BlindEd25519.blind(kp, blind); // Sign a message and check that it can be verified with the blind public key const msg = "test"; const sig = try BlindEd25519.sign(msg, blind_kp, null); try Ed25519.verify(sig, msg, blind_kp.blind_public_key); // Unblind the public key const pk = try BlindEd25519.unblind_public_key(blind_kp.blind_public_key, blind); try std.testing.expectEqualSlices(u8, &pk, &kp.public_key); ```
https://avatars.githubusercontent.com/u/1338?v=4
uuid6-zig
jdknezek/uuid6-zig
2021-05-08T05:46:25Z
UUIDv6 implemented in Zig
master
1
17
3
17
https://api.github.com/repos/jdknezek/uuid6-zig/tags
MIT
[ "zig-package" ]
34
false
2023-09-02T23:16:03Z
true
false
# uuid6-zig This is a prototype [UUIDv6](https://github.com/uuid6/uuid6-ietf-draft) draft 03 implementation in [Zig](https://github.com/ziglang/zig). It also includes versions 1 & 3-5 for comparison. ## Installation The library is contained entirely in `src/Uuid.zig`. Feel free to copy and customize or clone it as a submodule. It targets Zig `master` and may not work on the latest release. ### Adding to your build.zig ```zig libOrExe.addPackagePath("uuid6", "path/to/uuid6-zig/src/Uuid.zig"); ``` ## Usage There are namespaces for the various UUID versions, `v1`, `v3` - `v7`. Each has a `create(...)` method to create a single UUID, or a `Source` that can be used to create many with shared parameters and/or state. Sources are not thread-safe and should be protected with a mutex. ### Example ```zig const std = @import("std"); const Uuid = @import("uuid6"); pub fn main() anyerror!void { var rng = std.rand.DefaultPrng.init(0); const source = Uuid.v4.Source.init(&rng.random); var i: usize = 0; while (i < 10) : (i += 1) { const uuid = source.create(); std.debug.print("{}\n", .{uuid}); } } ``` See also `examples/bench`. ## Performance The following tables were generated by [hyperfine](https://github.com/sharkdp/hyperfine) running `examples/bench`. Note that the times are for 1e7 UUIDs, so for example each v4 takes ~12ns, and each v3 takes ~99ns. ### Thread-safe | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |:---|---:|---:|---:|---:| | `bench -n 10000000 -v 1` | 232.4 Β± 1.5 | 230.6 | 235.7 | 1.83 Β± 0.02 | | `bench -n 10000000 -v 3` | 998.9 Β± 2.9 | 995.7 | 1004.7 | 7.88 Β± 0.09 | | `bench -n 10000000 -v 4` | 126.8 Β± 1.3 | 123.7 | 129.7 | 1.00 | | `bench -n 10000000 -v 5` | 740.7 Β± 2.6 | 736.6 | 743.9 | 5.84 Β± 0.06 | | `bench -n 10000000 -v 6` | 189.1 Β± 1.1 | 187.3 | 191.6 | 1.49 Β± 0.02 | | `bench -n 10000000 -v 7` | 206.7 Β± 1.6 | 204.3 | 209.7 | 1.63 Β± 0.02 | ### Single-threaded | Command | Mean [ms] | Min [ms] | Max [ms] | Relative | |:---|---:|---:|---:|---:| | `bench -n 10000000 -v 1` | 229.7 Β± 0.9 | 228.3 | 231.3 | 1.89 Β± 0.02 | | `bench -n 10000000 -v 3` | 1005.7 Β± 17.4 | 998.5 | 1054.9 | 8.27 Β± 0.17 | | `bench -n 10000000 -v 4` | 121.7 Β± 1.3 | 119.8 | 125.7 | 1.00 | | `bench -n 10000000 -v 5` | 747.8 Β± 8.9 | 737.0 | 760.2 | 6.15 Β± 0.10 | | `bench -n 10000000 -v 6` | 151.6 Β± 1.0 | 150.0 | 153.9 | 1.25 Β± 0.02 | | `bench -n 10000000 -v 7` | 203.4 Β± 1.4 | 201.4 | 206.4 | 1.67 Β± 0.02 | Environment: - OS: Windows 10 - CPU: AMD Ryzen 5 5600X - Build mode: `release-fast`
https://avatars.githubusercontent.com/u/2364380?v=4
tempus
jnordwick/tempus
2024-05-26T05:25:42Z
fast, minimal clocks, TSC, dates, and timestamps for zig
main
2
17
0
17
https://api.github.com/repos/jnordwick/tempus/tags
AGPL-3.0
[ "zig-package" ]
28
false
2024-12-16T16:58:25Z
true
true
404
https://avatars.githubusercontent.com/u/4424467?v=4
zensor
ethanthoma/zensor
2024-07-08T06:59:30Z
Zig tensor library
main
1
17
0
17
https://api.github.com/repos/ethanthoma/zensor/tags
MIT
[ "machine-learning", "tensor", "zig", "zig-package" ]
196
false
2025-03-19T20:14:02Z
true
true
<h3 align="center"> Zensor, a zig tensor library </h3> A zig tensor library. Correctness first, speed second. This library promises compile-time type and shape checking. **Very WIP** ## Example Usage: ```zig const std = @import("std"); const T = u32; const Tensor = @import("zensor").Tensor(T); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); var compiler = zensor.Compiler.init(allocator); defer compiler.deinit(); const filename = "./examples/numpy.npy"; const a = try zensor.Tensor(.Int64, .{3}).from_numpy(&compiler, filename); const b = try zensor.Tensor(.Int64, .{3}).full(&compiler, 4); const c = try a.mul(b); const d = try c.sum(0); std.debug.print("{}\n", .{d}); } ``` Results in: ``` ❯ zig build run Tensor( type: dtypes.Int64, shape: [1], length: 1, data: [56, ] ) ``` ## Install Fetch the library: ```bash zig fetch --save git+https://github.com/ethanthoma/zensor.git#main ``` Add to your `build.zig`: ```zig const zensor = b.dependency("zensor", .{ .target = target, .optimize = optimize, }).module("zensor"); exe.root_module.addImport("zensor", zensor); ``` ## Examples Examples can be found in `./examples`. You can run these via: ```bash zig build NAME_OF_EXAMPLE ``` Assuming you have cloned the source. ## Tests If you want to run the tests after cloning the source. Simply run: ```bash zig build test ``` ## Design This library conversts all your tensor operations into an AST: ``` 0 Store RuntimeBuffer(ptr=@140052063859008, dtype=dtypes.Int64, shape={ 3 }) 1 ┗━Mul 2 ┣━Load RuntimeBuffer(ptr=@140052063858688, dtype=dtypes.Int64, shape={ 3 }) 3 ┗━Const 4 ``` When you want to execute your operations, it first gets split into schedules: ``` Schedule{ status: NotRun topological sort: [4]ast.Nodes{Load, Const, Mul, Store}, global buffers: [(0, true), (1, false)], dependencies count: 0, AST: 0 Store RuntimeBuffer(ptr=@140052063859008, dtype=dtypes.Int64, shape={ 3 }) 1 ┗━Mul 2 ┣━Load RuntimeBuffer(ptr=@140052063858688, dtype=dtypes.Int64, shape={ 3 }) 3 ┗━Const 4 } ``` And then IR code: ``` step op name type input arg 0 DEFINE_GLOBAL Pointer [] (0, true) 1 DEFINE_GLOBAL Pointer [] (1, false) 2 CONST Int [] 0 3 CONST Int [] 3 4 DEFINE_ACC Int [5] 0 5 LOOP Int [2, 3] None 6 LOAD Int [1, 5] None 7 ALU Int [4, 6] ALU.Add 8 UPDATE Int [4, 7] None 9 ENDLOOP [5] None 10 CONST Int [] 0 11 STORE [0, 10, 4] None ``` And finally, executed: ``` PC: 0 PC: 1 PC: 2 CONST: 0 PC: 3 CONST: 3 PC: 4 ACC: 0 PC: 5 LOOP: from 0 to 3 PC: 6 LOAD: 4 from buffer 1 at 0 PC: 7 ALU: Add(0, 4) = 4e0 PC: 8 UPDATE: value stored in step 4 to 4e0 PC: 6 LOAD: 16 from buffer 1 at 1 PC: 7 ALU: Add(4e0, 16) = 2e1 PC: 8 UPDATE: value stored in step 4 to 2e1 PC: 6 LOAD: 36 from buffer 1 at 2 PC: 7 ALU: Add(2e1, 36) = 5.6e1 PC: 8 UPDATE: value stored in step 4 to 5.6e1 PC: 9 PC: 10 CONST: 0 PC: 11 STORE: 5.6e1 into 0 at 0 ```
https://avatars.githubusercontent.com/u/124872?v=4
zig-hpke
jedisct1/zig-hpke
2021-03-30T19:36:34Z
HPKE implementation for Zig.
master
1
17
4
17
https://api.github.com/repos/jedisct1/zig-hpke/tags
MIT
[ "crypto", "hpke", "zig", "zig-package" ]
36
false
2025-03-25T05:56:13Z
true
true
# HPKE for Zig `zig-hpke` is an implementation of the [Hybrid Public Key Encryption](https://www.rfc-editor.org/rfc/rfc9180.html) (HPKE) scheme. ## Usage ### Bounded arrays This code heavily relies on the `std.BoundedArray` type: a type to store small, variable-sized slices whose maximum size is known. Keys are typically represented using that type, whose raw slice can be accessed with the `constSlice()` function (for a constant slice), or `slice()` (for a mutable slice). ### Suite instantiation ```zig const suite = try Suite.init( primitives.Kem.X25519HkdfSha256.id, primitives.Kdf.HkdfSha256.id, primitives.Aead.Aes128Gcm.id, ); ``` ### Key pair creation ```zig const kp = try suite.generateKeyPair(); ``` ### Client: creation and encapsulation of the shared secret A _client_ initiates a connexion by sending an encrypted secret; a _server_ accepts an encrypted secret from a client, and decrypts it, so that both parties can eventually agree on a shared secret. ```zig var client_ctx_and_encapsulated_secret = try suite.createClientContext(server_kp.public_key.slice(), "info", null, null); var client_ctx = client_ctx_and_encapsulated_secret.client_ctx; var encapsulated_secret = client_ctx_and_encapsulated_secret.encapsulated_secret; ``` * `encapsulated_secret.encapsulated` needs to be sent to the server. `encapsulated_secret.encapsulated.secret` must remain secret. * `client_ctx` can be used to encrypt/decrypt messages exchanged with the server. To improve misuse resistance, this implementation uses distinct types for the client and the server context: `ClientContext` for the client, and `ServerContext` for the server. ### Server: decapsulation of the shared secret ```zig var server_ctx = try suite.createServerContext(encapsulated_secret.encapsulated.constSlice(), server_kp, "info", null); ``` * `server_ctx` can be used to encrypt/decrypt messages exchanged with the client * The last parameter is an optional pre-shared key. ### Encryption of a message from the client to the server A message can be encrypted by the client for the server: ```zig client_ctx.encryptToServer(&ciphertext, message, ad); ``` Nonces are automatically incremented, so it is safe to call this function multiple times within the same context. Last parameter is optional associated data. The ciphertext is `client_ctx.tagLength()` bytes larger than the message. ### Decryption of a ciphertext received by the server The server can decrypt a ciphertext sent by the client: ```zig var message2: [message.len]u8 = undefined; try server_ctx.decryptFromClient(&message2, &ciphertext, ad); ``` Last parameter is optional associated data. The message length is `server_ctx.tagLength()` bytes shorter than the ciphertext. ### Encryption of a message from the server to the client A message can also be encrypted by the server for the client: ```zig server_ctx.encryptToClient(&ciphertext, message, ad); ``` Nonces are automatically incremented, so it is safe to call this function multiple times within the same context. Last parameter is optional associated data. ### Decryption of a ciphertext received by the client The client can decrypt an encrypted response from the server: ```zig try client_ctx.decryptFromServer(&message2, &ciphertext, ad); ``` Last parameter is optional associated data. ## Authenticated modes Authenticated modes, with or without a PSK are supported. See `createAuthenticatedClientContext` and `createAuthenticatedServerContext`. ### Exporter secret The exporter secret can be obtained with the `exportedSecret()` function available both in the `ServerContext` and `ClientContext` structures: ```zig const exporter = client_ctx.exporterSecret().constSlice(); ``` ### Key derivation ```zig const secret1 = try client_ctx.exportSecret("description 1") const secret2 = try server_ctx.exportSecret("description 2"); ``` ### Access the raw cipher interface ```zig const aead = suite.aead; ``` ## That's it!
https://avatars.githubusercontent.com/u/2286349?v=4
zig-x86_64
leecannon/zig-x86_64
2020-07-25T14:44:59Z
Support for x86_64 specific instructions (e.g. TLB flush), registers (e.g. control registers), and structures (e.g. page tables)
master
0
17
2
17
https://api.github.com/repos/leecannon/zig-x86_64/tags
MIT
[ "osdev", "x86", "x86-64", "zig", "zig-library", "zig-package", "ziglang" ]
307
false
2025-03-26T01:57:10Z
true
false
# zig-x86_64 [![CI](https://github.com/leecannon/zig-x86_64/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/leecannon/zig-x86_64/actions/workflows/main.yml) **I don't use this library anymore. I made this as a port of the rust crate but over time I have come to dislike the API.** **As written it does not support self-hosted so will probably be deleted with the release of zig 0.11** This repo contains various functionality required to make an x86_64 kernel (following [Writing an OS in Rust](https://os.phil-opp.com/)) It is mainly a zig reimplementation of the rust crate [x86_64](https://github.com/rust-osdev/x86_64). It includes a few additonal types in the `x86_64.additional` namespace: - `SerialPort` - Serial port type, mainly for debug output - `SimplePic` - Reimplementation of [pic8259_simple](https://docs.rs/pic8259_simple) ## How to get ### Gyro `gyro add leecannon/x86_64` ### Zigmod `zigmod aq add 1/leecannon/x86_64` ### Git #### Submodule `git submodule add https://github.com/leecannon/zig-x86_64 zig-x86_64` #### Clone `git clone https://github.com/leecannon/zig-x86_64`
https://avatars.githubusercontent.com/u/124872?v=4
zig-blind-rsa-signatures
jedisct1/zig-blind-rsa-signatures
2021-02-23T21:52:31Z
Blind RSA signatures implementation for Zig.
main
0
16
1
16
https://api.github.com/repos/jedisct1/zig-blind-rsa-signatures/tags
Apache-2.0
[ "blind", "blind-signatures", "rsa", "rsa-blind-signatures", "rsa-blinded-signatures", "signatures", "zig", "zig-package" ]
287
false
2025-04-09T10:17:54Z
true
false
# Blind RSA signatures Author-blinded RSASSA-PSS RSAE signatures. This is an implementation of the [RSA Blind Signatures](https://www.rfc-editor.org/rfc/rfc9474.html) RFC. Also includes a preliminary implementation of the [Partially Blind RSA Signatures](https://datatracker.ietf.org/doc/draft-amjad-cfrg-partially-blind-rsa/) draft. ## Protocol overview A client asks a server to sign a message. The server receives the message, and returns the signature. Using that `(message, signature)` pair, the client can locally compute a second, valid `(message', signature')` pair. Anyone can verify that `(message', signature')` is valid for the server's public key, even though the server didn't see that pair before. But no one besides the client can link `(message', signature')` to `(message, signature)`. Using that scheme, a server can issue a token and verify that a client has a valid token, without being able to link both actions to the same client. 1. The client creates a random message, optionally prefixes it with noise, and blinds it with a random, secret factor. 2. The server receives the blind message, signs it and returns a blind signature. 3. From the blind signature, and knowing the secret factor, the client can locally compute a `(message, signature)` pair that can be verified using the server's public key. 4. Anyone, including the server, can thus later verify that `(message, signature)` is valid, without knowing when step 2 occurred. The scheme was designed by David Chaum, and was originally implemented for anonymizing DigiCash transactions. ## Dependencies This implementation requires OpenSSL or BoringSSL. ## Usage ```zig // [SERVER]: Generate a RSA-2048 key pair const kp = try BlindRsa(2048).KeyPair.generate(); defer kp.deinit(); const pk = kp.pk; const sk = kp.sk; // [CLIENT]: create a random message and blind it for the server whose public key is `pk`. // The second parameter determines whether noise should be added to the message. // `true` adds noise, and returns it as `blinding_result.msg_randomizer` // `false` doesn't prefix the message with noise. // The client must store the message, the optional noise, and the secret. const msg = "msg"; var blinding_result = try pk.blind(msg, true); // [SERVER]: compute a signature for a blind message, to be sent to the client. // The client secret should not be sent to the server. const blind_sig = try sk.blindSign(blinding_result.blind_message); // [CLIENT]: later, when the client wants to redeem a signed blind message, // using the blinding secret, it can locally compute the signature of the // original message. // The client then owns a new valid (message, signature) pair, and the // server cannot link it to a previous(blinded message, blind signature) pair. // Note that the finalization function also verifies that the new signature // is correct for the server public key. // The noise parameter can be set to `null` if the message wasn't prefixed with noise. const sig = try pk.finalize(blind_sig, blinding_result.secret, blinding_result.msg_randomizer, msg); // [SERVER]: a non-blind signature can be verified using the server's public key. try pk.verify(sig, blinding_result.msg_randomizer, msg); ``` Deterministic padding is also supported with the `BlindRsaDeterministic` type: ```zig const BRsa = BlindRsaDeterministic(2048); const kp = BRSA.KeyPair.generate(); ... ``` For specific use cases, custom hash functions and salt lengths are also accessible via the `BlindRsaCustom` type. ```zig const BRsa = BlindRsaCustom(2048, .sha256, 48); const kp = BRSA.KeyPair.generate(); ... ``` Some helper functions are also included for key serialization and deserialization. ## For other languages * [Rust](https://github.com/jedisct1/rust-blind-rsa-signatures) * [C](https://github.com/jedisct1/blind-rsa-signatures) * [Go](https://github.com/cloudflare/circl/tree/master/blindsign)
https://avatars.githubusercontent.com/u/8823448?v=4
zig-enumerable
lawrence-laz/zig-enumerable
2023-12-19T20:10:14Z
Iterator tools for functional data processing.
main
0
16
0
16
https://api.github.com/repos/lawrence-laz/zig-enumerable/tags
MIT
[ "enumerable", "functional", "iterators", "itertools", "linq", "zig", "zig-package" ]
127
false
2024-08-18T18:01:34Z
true
true
# Zig Enumerable ⚑ Functional vibes for data processing as sequences. ```zig const std = @import("std"); const enumerable = @import("enumerable"); test "example" { try expectEqualIter( "(1,2,3)", enumerable.from(std.mem.tokenizeAny(u8, "foo=1;bar=2;baz=3", "=;").buffer) .where(std.ascii.isDigit) .intersperse(',') .prepend('(') .append(')'), ); } ``` ## πŸ“¦ Get started ```bash zig fetch --save https://github.com/lawrence-laz/zig-enumerable/archive/master.tar.gz ``` ```zig // build.zig const enumerable = b.dependency("enumerable", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("enumerable", enumerable.module("enumerable")); ```
https://avatars.githubusercontent.com/u/42583079?v=4
zig-prompter
GabrieleInvernizzi/zig-prompter
2024-12-11T20:13:44Z
zig-prompter is a lightweight and flexible library for building and managing interactive text-based prompts.
main
0
16
1
16
https://api.github.com/repos/GabrieleInvernizzi/zig-prompter/tags
MIT
[ "cli", "prompt", "terminal", "zig", "zig-package" ]
54
false
2025-03-29T13:51:17Z
true
true
# zig-prompter **zig-prompter** is a lightweight and flexible library for building and managing interactive text-based prompts in the [Zig programming language](https://ziglang.org/). Whether you're creating command-line tools, text-based games, or utilities requiring user input, **zig-prompter** simplifies the process with intuitive APIs and a robust feature set. ## Installation First, add zig-prompter to your `build.zig.zon` file: ```bash zig fetch --save git+https://github.com/GabrieleInvernizzi/zig-prompter/ ``` Update your `build.zig` file to include the dependency: ```zig const prompter_dep = b.dependency("prompter", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("prompter", prompter_dep.module("prompter")); ``` Here’s an example of using **zig-prompter** to create a simple selection prompt: ```zig const std = @import("std"); const Prompter = @import("prompter"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const stdout = std.io.getStdOut(); const theme = Prompter.Themes.SimpleTheme{}; var p = Prompter.Prompt.init(allocator, theme.theme()); const opts = [_][]const u8{ "Option 1", "Option 2", "Option 3" }; const sel_opt = try p.option("Select an option", &opts, 1); if (sel_opt) |o| { try stdout.writer().print("The selected option was: {s} (idx: {d})\n", .{ opts[o], o }); } else { try stdout.writer().writeAll("The selection was aborted.\n"); } } ``` For a more exhaustive example, take a look at the [example](https://github.com/GabrieleInvernizzi/zig-prompter/tree/main/example) directory. ## Features - [x] String prompt - [x] Interactive option selection prompt - [x] Confirmation prompt - [x] Password prompt - [x] Input validation - [x] Advanced support for themes and personalization - [ ] Include more themes - [ ] Windows support ## Contributions Contributions are always welcome and greatly appreciated! Whether it's fixing bugs, adding features, improving documentation, or enhancing examples, your input helps make **zig-prompter** even better. Feel free to open issues to discuss potential improvements or submit pull requests directly. Thank you for your support! ## Acknowledgments This library was inspired by the fantastic **Rust** library [Dialoguer](https://github.com/mitsuhiko/dialoguer).
https://avatars.githubusercontent.com/u/35976402?v=4
fzwatch
freref/fzwatch
2024-11-03T22:33:03Z
A lightweight and cross-platform file watcher for your Zig projects
master
1
16
3
16
https://api.github.com/repos/freref/fzwatch/tags
MIT
[ "zig", "zig-package" ]
22
false
2025-04-09T13:35:22Z
true
true
# fzwatch A lightweight and cross-platform file watcher for your Zig projects. > [!NOTE] > This project exists to support [fancy-cat](https://github.com/freref/fancy-cat) and has limited features. ## Instructions ### Run example You can run the [examples](./examples/) like so: ```sh zig build run-<filename> ``` ### Usage A basic example can be found under [examples](./examples/basic.zig). The API is defined as follows: ```zig pub const Event = enum { modified }; pub const Callback = fn (context: *anyopaque, event: Event) void; pub const Opts = struct { latency: f16 = 1.0 }; pub fn init(allocator: std.mem.Allocator) !Watcher; pub fn deinit(self: *Watcher) void; pub fn addFile(self: *Watcher, path: []const u8) !void; pub fn removeFile(self: *Watcher, path: []const u8) !void; pub fn setCallback(self: *Watcher, callback: Callback) void; pub fn start(self: *Watcher, opts: Opts) !void; pub fn stop(self: *Watcher) !void; ``` ### Testing Run the test suite: ```sh zig build test ```
https://avatars.githubusercontent.com/u/34311583?v=4
osdialog-zig
ttytm/osdialog-zig
2024-10-18T13:35:04Z
Cross-platform utility module for Zig to open native dialogs for the filesystem, message boxes, color-picking.
main
0
16
1
16
https://api.github.com/repos/ttytm/osdialog-zig/tags
ISC
[ "bindings", "color-picker", "dialog", "filesystem", "library", "linux", "macos", "module", "native", "windows", "zig", "zig-package", "ziglang" ]
11
false
2025-03-29T14:30:50Z
true
true
# osdialog-zig [badge__build-status]: https://img.shields.io/github/actions/workflow/status/ttytm/osdialog-zig/ci.yml?branch=main&logo=github&logoColor=C0CAF5&labelColor=333 [badge__version-lib]: https://img.shields.io/github/v/tag/ttytm/osdialog-zig?logo=task&logoColor=C0CAF5&labelColor=333&color= [badge__version-zig]: https://img.shields.io/badge/Zig-0.13.0-cc742f?logo=zig&logoColor=C0CAF5&labelColor=333 [![][badge__build-status]](https://github.com/ttytm/osdialog-zig/actions?query=branch%3Amain) [![][badge__version-lib]](https://github.com/ttytm/osdialog-zig/releases/latest) [![][badge__version-zig]](https://github.com/ttytm/osdialog-zig/releases/latest) Cross-platform utility module for Zig to open native dialogs for the filesystem, message boxes, color-picking. ## Quickstart - [Installation](#installation) - [Usage](#usage) - [Example](#example) - [Credits](#credits) ## Showcase <table align="center"> <tr> <th>Linux</th> <th>Windows</th> <th>macOS</th> </tr> <tr> <td width="400"> <img alt="Linux File Dialog" src="https://github.com/ttytm/dialog/assets/34311583/6ba6e96b-3581-4382-8074-79918a99dcbd"> </td> <td width="400"> <img alt="Windows File Dialog" src="https://github.com/ttytm/dialog/assets/34311583/911e8c71-0cc1-4426-a62c-04714b6b071f"> </td> <td width="400"> <img alt="macOS File Dialog" src="https://github.com/ttytm/dialog/assets/34311583/f7c4375e-d2e4-4121-ad34-db0473d8fabe"> </td> </tr> </table> <details open> <summary><b>More Examples</b> <sub><sup>Toggle visibility...</sup></sub></summary><br> <table align="center"> <tr> <th>Linux</th> <th>Windows</th> <th>macOS</th> </tr> <tr> <td width="400"> <img alt="Linux Color Picker GTK3" src="https://github.com/ttytm/dialog/assets/34311583/8e587c8c-2f12-41ee-9a10-4c3f92e72885"> <img alt="Linux Message" src="https://github.com/ttytm/dialog/assets/34311583/42e1081b-ee52-4286-abfd-ad9eda63d282"> <img alt="Linux Message with Yes and No Buttons" src="https://github.com/ttytm/dialog/assets/34311583/07aa26bd-f887-417b-9c1a-56724ceb2589"> <img alt="Linux Input Prompt" src="https://github.com/ttytm/dialog/assets/34311583/bc5e3ec1-88b5-4e1a-b46e-381b322b8a6c"> <img alt="Linux Color Picker GTK2" src="https://github.com/ttytm/dialog/assets/34311583/37619ed0-8fe2-4e5c-af11-70d7f2304b2b"> </td> <td width="400"> <img alt="Windows Color Picker" src="https://github.com/ttytm/dialog/assets/34311583/966b1395-55ac-45b8-aa1b-516f673b64e8"> <img alt="Windows Message" src="https://github.com/ttytm/dialog/assets/34311583/a73e0eaf-e56b-44e6-bcc5-31bb381c6e37"> <img alt="Windows Message with Yes and No Buttons" src="https://github.com/ttytm/dialog/assets/34311583/16a1ad65-571e-4183-8c0b-119cbf126aec"> <img alt="Windows Input Prompt" src="https://github.com/ttytm/dialog/assets/34311583/54e4a708-de38-44ea-ae61-be39c1bdbff9"> </td> <td width="400"> <img alt="macOS Color Picker" src="https://github.com/user-attachments/assets/551ac8d6-406d-4b01-9095-d0a357cc8250"> <!-- <img alt="macOS Message" src="https://github.com/ttytm/dialog/assets/34311583/15920c46-e529-405f-9731-3ac57ce46449"> --> <img alt="macOS Message with Yes and No Buttons" src="https://github.com/ttytm/dialog/assets/34311583/11cba10b-3190-4114-b1ad-e49e56d4498c"> <img alt="macOS Input Prompt" src="https://github.com/ttytm/dialog/assets/34311583/e6d496b4-3c20-4ece-8808-0eba99a59a45"> </td> </tr> </table> </details> ## Installation ```sh # ~/<ProjectsPath>/your-awesome-projct zig fetch --save https://github.com/ttytm/osdialog-zig/archive/main.tar.gz ``` ```zig // your-awesome-projct/build.zig const std = @import("std"); pub fn build(b: *std.Build) void { // .. const osdialog_dep = b.dependency("osdialog", .{}); const exe = b.addExecutable(.{ .name = "your-awesome-projct", // .. }); exe.root_module.addImport("osdialog", osdialog_dep.module("osdialog")); // ... } ``` ## Usage Ref.: [`osdialog-zig/src/lib.zig`](https://github.com/ttytm/osdialog-zig/blob/main/src/lib.zig) ```zig /// Opens a message box and returns `true` if `OK` or `Yes` was pressed. pub fn message(text: [*:0]const u8, opts: MessageOptions) bool /// Opens an input prompt with an "OK" and "Cancel" button. pub fn prompt(allocator: std.mem.Allocator, text: [*:0]const u8, opts: PromptOptions) ?[:0]u8 /// Opens an RGBA color picker and returns the selected `Color` or `null` if the selection was canceled. pub fn color(options: ColorPickerOptions) ?Color /// Opens a file dialog and returns the selected path or `null` if the selection was canceled. pub fn path(allocator: std.mem.Allocator, action: PathAction, options: PathOptions) ?[:0]u8 ``` ### Example Ref.: [`osdialog-zig/examples/src/main.zig`](https://github.com/ttytm/osdialog-zig/blob/main/examples/src/main.zig) ```zig const std = @import("std"); const osd = @import("osdialog"); pub fn main() void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer _ = gpa.deinit(); _ = osd.message("Hello, World!", .{}); if (!osd.message("Do you want to continue?", .{ .buttons = .yes_no })) { std.process.exit(0); } if (osd.prompt(allocator, "Give me some input", .{})) |input| { defer allocator.free(input); std.debug.print("Input: {s}\n", .{input}); } if (osd.color(.{ .color = .{ .r = 247, .g = 163, .b = 29, .a = 255 } })) |selected| { std.debug.print("Color RRR,GGG,BBB,AAA: {d},{d},{d},{d}\n", .{ selected.r, selected.g, selected.b, selected.a }); } if (osd.path(allocator, .open, .{})) |path| { defer allocator.free(path); std.debug.print("Selected file: {s}\n", .{path}); } if (osd.path(allocator, .open_dir, .{})) |path| { defer allocator.free(path); } if (osd.path(allocator, .save, .{ .path = ".", .filename = "myfile.txt" })) |path| { defer allocator.free(path); std.debug.print("Save location: {s}\n", .{path}); } } ``` ```sh # osdialog/examples zig build run ``` ## Credits - [AndrewBelt/osdialog](https://github.com/AndrewBelt/osdialog) - The C project this library is leveraging
https://avatars.githubusercontent.com/u/65570835?v=4
lscolors
ziglibs/lscolors
2019-11-03T15:47:57Z
A zig library for colorizing paths according to LS_COLORS
master
0
16
1
16
https://api.github.com/repos/ziglibs/lscolors/tags
MIT
[ "ls-colors", "zig", "zig-package", "ziglang" ]
97
false
2025-04-09T10:14:59Z
true
true
# lscolors ![CI](https://github.com/ziglibs/zig-lscolors/workflows/CI/badge.svg) A zig library for colorizing paths according to the `LS_COLORS` environment variable. Designed to work with Zig 0.14.0. ## Quick Example ```zig const std = @import("std"); const LsColors = @import("lscolors").LsColors; pub fn main() !void { var gpa: std.heap.DebugAllocator(.{}) = .init; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var lsc = try LsColors.fromEnv(allocator); defer lsc.deinit(); var dir = try std.fs.cwd().openDir(".", .{ .iterate = true }); defer dir.close(); var iterator = dir.iterate(); while (try iterator.next()) |itm| { std.log.info("{}", .{try lsc.styled(itm.name)}); } } ```
https://avatars.githubusercontent.com/u/5332688?v=4
zig-getopt
dmgk/zig-getopt
2021-05-20T14:17:44Z
POSIX-compatible getopt(3) implementation in Zig
master
2
16
5
16
https://api.github.com/repos/dmgk/zig-getopt/tags
0BSD
[ "option-parser", "option-parsing", "zig", "zig-package", "ziglang" ]
10
false
2025-03-19T21:08:32Z
true
false
# Minimal POSIX getopt(3) implementation in Zig This is a minimal, allocation-free getopt(3) implementation with [POSIX-conforming](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html) argument parsing semantics. ## Example ```zig const std = @import("std"); const debug = std.debug; const getopt = @import("getopt.zig"); pub fn main() void { var arg: []const u8 = undefined; var verbose: bool = false; var opts = getopt.getopt("a:vh"); while (opts.next()) |maybe_opt| { if (maybe_opt) |opt| { switch (opt.opt) { 'a' => { arg = opt.arg.?; debug.print("arg = {s}\n", .{arg}); }, 'v' => { verbose = true; debug.print("verbose = {}\n", .{verbose}); }, 'h' => debug.print( \\usage: example [-a arg] [-hv] \\ , .{}), else => unreachable, } } else break; } else |err| { switch (err) { getopt.Error.InvalidOption => debug.print("invalid option: {c}\n", .{opts.optopt}), getopt.Error.MissingArgument => debug.print("option requires an argument: {c}\n", .{opts.optopt}), } } debug.print("remaining args: {?s}\n", .{opts.args()}); } ``` ``` $ zig run example.zig -- -hv -a42 foo bar usage: example [-a arg] [-hv] verbose = true arg = 42 remaining args: { foo, bar } ```
https://avatars.githubusercontent.com/u/20910163?v=4
zai
AdjectiveAllison/zai
2024-02-14T23:13:19Z
Zig AI!
main
0
16
0
16
https://api.github.com/repos/AdjectiveAllison/zai/tags
MIT
[ "zig-package" ]
300
false
2025-04-04T19:18:48Z
true
true
# zai - a Zig AI Library zai is a flexible Zig library for interacting with various AI providers' APIs, offering a unified interface for chat completions, embeddings, and more. ## Requirements - Zig 0.14.0 ## Features - Multi-provider support: - OpenAI-compatible APIs (OpenAI, Together.ai, OpenRouter) - Amazon Bedrock - Anthropic - Support coming soon for Google Vertex AI and local models via zml - Unified interface across providers - Streaming support for real-time responses - Provider and model registry for easy configuration - System prompt management and reuse across models - Command-line interface (CLI) for quick interactions: - Stdin piping support for integrating with other Unix tools - Combined prompt and context handling - Supports chat completions, standard completions, and embeddings ## Installation 1. Add zai as a dependency using `zig fetch`: ```sh # Latest version zig fetch --save git+https://github.com/AdjectiveAllison/zai.git#main ``` 2. Add zai as a module in your `build.zig`: ```zig const zai_dep = b.dependency("zai", .{ .target = target, .optimize = optimize, }); const zai_mod = zai_dep.module("zai"); // Add to your executable exe.root_module.addImport("zai", zai_mod); ``` ## CLI Installation To install the zai CLI tool: ```sh zig build cli install -Doptimize=ReleaseFast --prefix ~/.local ``` ## Usage ### Provider Configuration First, create a provider configuration. You can do this programmatically or via the CLI: ```zig const zai = @import("zai"); // OpenAI-compatible configuration const provider_config = zai.ProviderConfig{ .OpenAI = .{ .api_key = "your-api-key", .base_url = "https://api.together.xyz/v1", // Together.ai example }}; // Amazon Bedrock configuration const bedrock_config = zai.ProviderConfig{ .AmazonBedrock = .{ .access_key_id = "your-access-key", .secret_access_key = "your-secret-key", .region = "us-west-2", }}; // Anthropic configuration const anthropic_config = zai.ProviderConfig{ .Anthropic = .{ .api_key = "your-anthropic-api-key", .default_max_tokens = 8000, // Default max tokens limit }}; ``` ### Chat Example ```zig const std = @import("std"); const zai = @import("zai"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // Initialize provider var provider = try zai.init(allocator, provider_config); defer provider.deinit(); // Set up chat messages const messages = [_]zai.Message{ .{ .role = "system", .content = "You are a helpful assistant.", }, .{ .role = "user", .content = "Tell me a short joke.", }, }; // Configure chat options const chat_options = zai.ChatRequestOptions{ .model = "mistralai/Mixtral-8x7B-v0.1", .messages = &messages, .temperature = 0.7, .stream = true, }; // Stream the response try provider.chatStream(chat_options, std.io.getStdOut().writer()); } ``` ### Provider Feature Matrix | Provider | Chat | Chat Stream | Completion | Completion Stream | Embeddings | |---------------|------|-------------|------------|-------------------|------------| | OpenAI-compatible | βœ… | βœ… | βœ… | βœ… | βœ… | | Amazon Bedrock | βœ… | βœ… | ❌ | ❌ | ❌ | | Anthropic | βœ… | βœ… | ❌ | ❌ | ❌ | | Google Vertex* | ❌ | ❌ | ❌ | ❌ | ❌ | | Local (zml)* | ❌ | ❌ | ❌ | ❌ | ❌ | \* Coming soon ## CLI Usage The zai CLI provides commands for managing providers, models, and making API calls: ```sh # Add a provider zai provider add openai --api-key "your-key" --base-url "https://api.openai.com/v1" # Add a model to a provider zai models add openai gpt-4 --id gpt-4-turbo-preview --chat # Manage system prompts zai prompt add my-system-prompt --type system --content "You are a helpful assistant." zai prompt list zai prompt import another-prompt --type system --file ./prompts/my-prompt.txt # Assign a default prompt to a model zai models set-prompt openai gpt-4 my-system-prompt # Chat with a model (will use first provider and first model of provider by default) zai chat --provider openai --model gpt-4 "Tell me a joke" # same as this if openai and gpt-4 are your first provider and chat model in config. zai chat "tell me a joke" # The model will automatically use its default system prompt if available # Override the default system prompt for a single session zai chat --system-message "You are a pirate." "Tell me about sailing." # Pipe content from other commands or files cat document.txt | zai chat "Summarize this:" git diff | zai chat "Explain these changes:" # Generate shell completions zai completions fish > ~/.config/fish/completions/zai.fish zai completions bash > ~/.bash_completion.d/zai zai completions zsh > ~/.zsh/completions/_zai # Install completions directly zai completions fish --install ``` See more CLI examples and documentation by running: ```sh zai --help zai <command> --help ``` ## Examples Check out the `examples/` directory for more detailed examples: - Chat using OpenAI-compatible APIs (`examples/chat_openai.zig`) - Chat using Amazon Bedrock (`examples/chat_bedrock.zig`) - Chat using Anthropic (`examples/chat_anthropic.zig`) - Embeddings generation (`examples/embeddings.zig`) - Provider registry management (`examples/registry.zig`) - And more! ## Contributing Contributions are welcome! Some areas that need work: - Adding tests - Improving CLI provider configuration workflow - Implementing additional providers (Google Vertex AI) - Local model support via zml integration - Documentation improvements ## License zai is released under the MIT License. See the [LICENSE](LICENSE) file for details.
https://avatars.githubusercontent.com/u/5332688?v=4
zig-uuid
dmgk/zig-uuid
2021-05-22T22:24:06Z
Fast, allocation-free v4 UUIDs in Zig
master
7
16
11
16
https://api.github.com/repos/dmgk/zig-uuid/tags
0BSD
[ "uuid", "uuid-generator", "uuidv4", "zig", "zig-package", "ziglang" ]
8
false
2024-10-08T02:43:54Z
true
false
# Fast, allocation-free v4 UUIDs in Zig ## Example ```zig const std = @import("std"); const UUID = @import("uuid.zig").UUID; pub fn main() !void { // generate const uuid1 = UUID.init(); std.debug.print("{}\n", .{uuid1}); // parse const uuid2 = try UUID.parse("3df6f0e4-f9b1-4e34-ad70-33206069b995"); std.debug.print("{}\n", .{uuid2}); } ``` ``` $ zig run example.zig 78c33481-4c67-4202-ba8d-11ee1dfaad24 3df6f0e4-f9b1-4e34-ad70-33206069b995 ``` ### Tests ```bash zig test uuid.zig ``` ```bash Test [3/3] test.check to_string works... First call to_string 851d0256-c62c-43b0-bf15-71da00bafb30 Second call to_string 851d0256-c62c-43b0-bf15-71da00bafb30 All 3 tests passed. ```
https://avatars.githubusercontent.com/u/106511?v=4
pulseaudio
andrewrk/pulseaudio
2023-01-17T06:46:23Z
pulseaudio with the build system replaced by zig
master
0
16
2
16
https://api.github.com/repos/andrewrk/pulseaudio/tags
NOASSERTION
[ "zig-package" ]
15,876
false
2025-03-26T04:22:10Z
true
true
# PulseAudio Zig Package This is a fork of [PulseAudio](https://www.freedesktop.org/wiki/Software/PulseAudio/), packaged for Zig. Unnecessary files have been deleted, and the build system has been replaced with `build.zig`. ## License Original LICENSE file is unchanged. The Zig files that have been added to this repository are MIT (Expat) licensed. The MIT License (Expat) Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
https://avatars.githubusercontent.com/u/22335998?v=4
zig-clay
Gota7/zig-clay
2024-12-29T00:50:11Z
Bindings for Clay UI library in Zig.
main
11
16
2
16
https://api.github.com/repos/Gota7/zig-clay/tags
MIT
[ "zig-package" ]
134
false
2025-03-29T13:43:49Z
true
true
# zig-clay Tweaked bindings for the [clay](https://github.com/nicbarker/clay) C UI library. ## Features * Zig 0.13.0 compatibility. * Naming conventions follow zig standards. * Callbacks are more zig-like. * Config structures have default initializations. * Code is very similar to how it looks in C. ## Usage The main difference between this and the C API is the lack of macros. To get around this, a different approach was taken to emulate the feel of the C API: ```zig const layout = clay.beginLayout(); if (clay.child(&.{ clay.id("OuterContainer"), clay.rectangle(.{ .color = .{ .r = 43, .g = 41, .b = 51, .a = 255 } }), clay.layout(.{ .layout_direction = .top_to_bottom, .sizing = .{ .width = clay.sizingGrow(.{}), .height = clay.sizingGrow(.{}), }, .padding = .{ .x = 16, .y = 16 }, .child_gap = 16, }), // More config here. })) |outer_container| { defer outer_container.end(); clay.text("Hello World!", .{ .font_id = 0, .font_size = 24, .text_color = .{ .r = 255, .g = 255, .b = 255, .a = 255 }, }); // More child elements here. } // ... const commands = layout.end(); ``` C version for comparison: ```c Clay_BeginLayout(); CLAY( CLAY_ID("OuterContainer"), CLAY_RECTANGLE({ .color = { 43, 41, 51, 255 } }), CLAY_LAYOUT({ .layoutDirection = CLAY_TOP_TO_BOTTOM, .sizing = { .width = CLAY_SIZING_GROW(), .height = CLAY_SIZING_GROW() }, .padding = { 16, 16 }, .childGap = 16 }) // More config here. ) { CLAY_TEXT("Hello World!", CLAY_TEXT_CONFIG({ .fontId = 0, .fontSize = 24, .textColor = { 255, 255, 255, 255 } })); // More child elements here. } // ... Clay_RenderCommandArray renderCommands = Clay_EndLayout(); ``` While not as frequent, sometimes control flow is required during element configuration. In this scenario, manual configuration should be done: ```zig if (clay.childManualControlFlow()) |sidebar_button| { defer sidebar_button.end(); sidebar_button.config(clay.layout(sidebar_button_layout)); clay.onHover(handle_sidebar_interaction, @ptrFromInt(i)); if (clay.hovered()) sidebar_button.config(clay.rectangle(.{ .color = .{ .r = 120, .g = 120, .b = 120, .a = 255 }, .corner_radius = clay.cornerRadius(8), })); // More config here. sidebar_button.endConfig(); // Children. clay.text(document.title, .{ .font_id = font_id_body_16, .font_size = 20, .text_color = color_white, }); // More child elements here. } ``` In this scenario, care should be taken that the order is: 1. Call `childManualControlFlow()` 2. Config (calls to `.config()`) 3. Call `.endConfig()` 4. Child elements 5. Call `.end()` ## Getting Started The `example` folder has an example of a working project. Other than the syntatical differences seen above, usage of the zig API should be fairly 1-to-1 with the C library.
https://avatars.githubusercontent.com/u/14295318?v=4
ollama-zig
dravenk/ollama-zig
2025-01-07T11:18:13Z
Ollama Zig library
main
0
16
1
16
https://api.github.com/repos/dravenk/ollama-zig/tags
MIT
[ "deepseek", "llama", "llm", "llms", "ollama", "ollama-api", "ollama-client", "zig", "zig-library", "zig-package" ]
75
false
2025-04-08T03:33:43Z
true
true
# Ollama Zig Library The Ollama Zig library provides the easiest way to integrate Zig 0.13+ projects with [Ollama](https://github.com/ollama/ollama). ## Prerequisites - [Ollama](https://ollama.com/download) should be installed and running - Pull a model to use with the library: `ollama pull <model>` e.g. `ollama pull llama3.2` - See [Ollama.com](https://ollama.com/search) for more information on the models available. ## Install ```sh zig fetch --save git+https://github.com/dravenk/ollama-zig.git ``` ## Usage Adding to build.zig ```zig const ollama = b.dependency("ollama-zig", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("ollama", ollama.module("ollama")); ``` Import it in your code: ```zig const ollama = @import("ollama"); ``` See [types.zig](src/types.zig) for more information on the response types. ## Streaming responses Response streaming can be enabled by setting `.stream = true`. ```zig try ollama.chat(.{ .model = "llama3.2", .stream = true, .messages = &.{ .{ .role = .user, .content = "Why is the sky blue?" }, } }); ``` ## API The Ollama Zig library's API is designed around the [Ollama REST API](https://github.com/ollama/ollama/blob/main/docs/api.md) ### Chat ```zig var responses = try ollama.chat(.{ .model = "llama3.2", .stream = false, .messages = &.{ .{ .role = .user, .content = "Why is the sky blue?" }, } }); while (try responses.next()) |chat| { const content = chat.message.content; std.debug.print("{s}", .{content}); } ``` ### Generate ```zig var responses = try ollama.generate(.{ .model = "llama3.2", .prompt = "Why is the sky blue?" }); while (try responses.next()) |response| { const content = response.response; std.debug.print("{s}", .{content}); } ``` ### Show ```zig try ollama.show("llama3.2"); ``` ### Create ```zig try ollama.create(.{ .model = "mario", .from = "llama3.2", .system = "You are Mario from Super Mario Bros." }); ``` ### Copy ```zig try ollama.copy("llama3.2", "user/llama3.2"); ``` ### Delete (In plan)Wait for the upstream update. see https://github.com/ollama/ollama/issues/8753 ```zig try ollama.delete("llama3.2") ``` ### Pull ```zig try ollama.pull("llama3.2") ``` ### Push ```zig try ollama.push(.{ .model = "dravenk/llama3.2"}); ``` ### Embed or Embed (batch) ```zig var input = std.ArrayList([]const u8).init(allocator); try input.append("The sky is blue because of rayleigh scattering"); try input.append("Grass is green because of chlorophyll"); var responses = try ollama.embed(.{ .model = "dravenk/llama3.2", .input = try input.toOwnedSlice(), }); while (try responses.next()) |response| { std.debug.print("total_duration: {d}\n", .{response.total_duration.?}); std.debug.print("prompt_eval_count: {d}\n", .{response.prompt_eval_count.?}); } ``` ### Ps ```zig try ollama.ps() ``` ### Version ```zig try ollama.version() ``` ## Errors Errors are raised if requests return an error status or if an error is detected while streaming. ```zig ```
https://avatars.githubusercontent.com/u/60146383?v=4
zetaframe
zetaframe/zetaframe
2020-04-19T19:50:11Z
lightweight zig game framework.
master
0
15
0
15
https://api.github.com/repos/zetaframe/zetaframe/tags
Apache-2.0
[ "game-engine", "game-framework", "game-framework-engine", "gamedev", "zig-library", "zig-package", "ziglang" ]
1,023
false
2024-07-19T03:24:04Z
true
false
# zetaframe ![GitHub Workflow Status](https://img.shields.io/github/workflow/status/zetaframe/zetaframe/Tests?style=for-the-badge) A `wip` lightweight zig game framework. ## Modules ### core The core of all zetaframe applications. zetaframe is based around a Entity Component System (ECS). ### math A glsl compatible linear algebra library. `wip` ### render An powerful vulkan render api. `wip`. Will later include a system that can be added directly into `core`. --- ## Building Use zig master. --- ## License See [LICENSE.md](../master/LICENSE.md)
https://avatars.githubusercontent.com/u/265903?v=4
PeerType
alexnask/PeerType
2020-11-19T12:57:04Z
Zig peer type resolution at comptime, ported from the compiler source code
master
0
15
3
15
https://api.github.com/repos/alexnask/PeerType/tags
MIT
[ "metaprogramming", "zig", "zig-library", "zig-package" ]
31
false
2023-03-15T18:05:08Z
false
false
# PeerType ## API ```zig /// types must be an iterable of types (tuple, slice, ptr to array) pub fn PeerType(comptime types: anytype) ?type; pub fn coercesTo(comptime dst: type, comptime src: type) bool; pub fn requiresComptime(comptime T: type) bool; ``` ## License MIT
https://avatars.githubusercontent.com/u/1327032?v=4
zig-windows-process
GoNZooo/zig-windows-process
2020-06-21T13:08:51Z
Toolset for interacting with Windows processes in Zig
main
0
15
1
15
https://api.github.com/repos/GoNZooo/zig-windows-process/tags
None
[ "processes", "win32", "windows", "zig", "zig-package", "ziglang" ]
1,071
false
2025-02-09T14:56:22Z
true
false
# zig-windows-process This repo is meant to hold tools for tinkering with Windows processes (though I might extend it in the future) to allow for a higher-level interface for injecting DLLs and such. The primary motivation is that I'd like to have a basic toolkit for dealing with things that usually come up in game hacking and exploration. ## The library code The library code is primarily in `main.zig` so if you were to add the package it would be from that file, as follows: ```zig exe.addPackagePath("windows-process", "dependencies/windows-process/src/main.zig"); ``` ## Example usage ### DLL injection `inject_dll.zig` contains a main file for a program that will take a DLL path and inject it into a given process. One needs to make sure that the process has the same bitness as the DLL. ### Finding/enumerating processes `find_process.zig` uses the process enumeration API to find processes matching a given executable name. ## More stuff and more ways to do these things I'm not an expert on any of these things and there are way more things to add here. I'd love suggestions for tools to add, techniques to facilitate through this package. Having a general module that allows interaction with Windows processes in general is the point, after all.
https://avatars.githubusercontent.com/u/20110944?v=4
zig-embshell
ringtailsoftware/zig-embshell
2023-01-31T00:09:50Z
Small embeddable command line shell in zig
main
0
15
0
15
https://api.github.com/repos/ringtailsoftware/zig-embshell/tags
MIT
[ "cli", "embedded", "shell", "zig", "zig-package", "ziglang" ]
40
false
2025-04-05T15:02:37Z
true
true
# EmbShell A very small interactive command shell for (embedded) Zig programs. EmbShell makes an ideal system monitor for debugging and interacting with a small embedded system. It interactively takes lines of text, parses commands and makes callbacks into handler functions. Compared with Readline, Linenoise and Editline - EmbShell is tiny. It lacks most of their features, but it does have: - Tab completion for command names - Backspace for line editing - No reliance on libc and very little use of Zig's `std` (ie. no fancy print formatting) - Very little RAM use (just a configurable buffer for the incoming command line) In EmbShell: - All commands and configuration are set at `comptime` to optimise footprint - All arguments are separated by whitespace, there is no support for quoted strings, multiline commands or escaped data - All handler arguments are strings, leaving it to the app to decide how to parse them - No runtime memory allocations ## Using Developed with `zig 0.14.0` ### Run the sample cd example-posix zig build run ``` myshell> help echo led myshell> echo hello world You said: { echo, hello, world } OK myshell> led 1 If we had an LED it would be set to true OK ``` ## Using in your own project First add the library as a dependency in your `build.zig.zon` file. `zig fetch --save git+https://github.com/ringtailsoftware/zig-embshell.git` And add it to `build.zig` file. ```zig const embshell_dep = b.dependency("embshell", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("embshell", embshell_dep.module("embshell")); ``` `@import` the module and provide a configuration. - `.prompt` is the string shown to the user before each command is entered - `.maxargs` is the maximum number of arguments EmbShell will process (e.g. "mycmd foo bar" is 3 arguments) - `.maxlinelen` is the maximum length of a line to be handled, a buffer of this size will be created - `.cmdtable` an array of names and handler function for commands ```zig const UserdataT = u32; const EmbShellT = @import("embshell").EmbShellFixedParams(UserdataT); const EmbShell = @import("embshell").EmbShellFixed(.{ .prompt = "myshell> ", .maxargs = 16, .maxlinelen = 128, .cmdtable = &.{ .{ .name = "echo", .handler = echoHandler }, .{ .name = "led", .handler = ledHandler }, }, .userdataT = UserdataT, }); ``` Each handler function is in the following form. EmbShell prints "OK" after successfully executing each function and "Failed" if an error is returned. ```zig fn myHandler(userdata: UserdataT, args:[][]const u8) anyerror!void { // process args // optionally return error } ``` Next, call `.init()` and provide a write callback to allow EmbShell to emit data ```zig fn write(data:[]const u8) void { // emit data to terminal } var shell = try EmbShell.init(write, userdata); ``` Finally, feed EmbShell with incoming data from the terminal to be processed ```zig const buf = readFromMyTerminal(); shell.feed(buf) ```
https://avatars.githubusercontent.com/u/1552770?v=4
thespian
neurocyte/thespian
2024-02-08T22:09:11Z
thespian: an actor library for Zig, C & C++ applications
master
0
14
1
14
https://api.github.com/repos/neurocyte/thespian/tags
MIT
[ "actor-model", "cpp", "zig", "zig-package" ]
203
false
2025-03-26T19:39:23Z
true
true
# Thespian Fast & flexible actors for Zig, C & C++ applications To build: ``` ./zig build ``` See `tests/*` for many interesting examples.
https://avatars.githubusercontent.com/u/2364380?v=4
anycast
jnordwick/anycast
2024-11-29T19:06:20Z
One cast to rule them all
trunk
0
14
0
14
https://api.github.com/repos/jnordwick/anycast/tags
BSD-2-Clause
[ "zig-package" ]
9
false
2025-04-09T00:44:50Z
true
true
404
https://avatars.githubusercontent.com/u/5464072?v=4
zig-json
nektro/zig-json
2021-04-30T05:34:08Z
A JSON library for inspecting arbitrary values
master
0
14
3
14
https://api.github.com/repos/nektro/zig-json/tags
MIT
[ "zig", "zig-package" ]
117
false
2025-04-09T23:04:43Z
true
false
# zig-json ![loc](https://sloc.xyz/github/nektro/zig-json) [![license](https://img.shields.io/github/license/nektro/zig-json.svg)](https://github.com/nektro/zig-json/blob/master/LICENSE) A JSON library for inspecting arbitrary values. Optionally accepts trailing commas. Fully passes https://github.com/nst/JSONTestSuite. ## Usage See `test.zig` for examples. ## Building Example Program ``` $ zigmod fetch $ zig build test ``` ## License MIT
https://avatars.githubusercontent.com/u/2286349?v=4
zig-bitjuggle
leecannon/zig-bitjuggle
2021-06-27T18:01:20Z
Various "bit juggling" helpers and functionality
master
0
14
1
14
https://api.github.com/repos/leecannon/zig-bitjuggle/tags
MIT
[ "zig", "zig-library", "zig-package", "ziglang" ]
68
false
2025-03-02T17:55:19Z
true
true
# zig-bitjuggle This package contains various "bit juggling" helpers and functionality: - `isBitSet` - Check if a bit is set - `getBit` - Get the value of a bit - `getBits` - Get a range of bits - `setBit` - Set a specific bit - `setBits` - Set a range of bits - `Bitfield` - Used along with `extern union` to represent arbitrary bit fields - `Bit` - Used along with `extern union` to represent bit fields - `Boolean` - Used along with `extern union` to represent boolean bit fields ## Installation Add the dependency to `build.zig.zon`: ```sh zig fetch --save git+https://github.com/leecannon/zig-bitjuggle ``` Then add the following to `build.zig`: ```zig const bitjuggle = b.dependency("bitjuggle", .{}); exe.root_module.addImport("bitjuggle", bitjuggle.module("bitjuggle")); ```
https://avatars.githubusercontent.com/u/5464072?v=4
zig-unicode-ucd
nektro/zig-unicode-ucd
2021-05-31T02:33:29Z
Zig bindings for the Unicode Character Database
master
7
14
0
14
https://api.github.com/repos/nektro/zig-unicode-ucd/tags
MIT
[ "zig", "zig-package" ]
1,859
false
2025-02-16T06:11:27Z
true
false
# zig-unicode-ucd Zig bindings for the Unicode Character Database Last updated as of Unicode 16.0.0 http://www.unicode.org/reports/tr44/ https://www.unicode.org/versions/latest/ ## Development ``` zig build run -Dstep=generate zig build run -Dstep=run ``` ## License Code here is MIT Source data files are https://www.unicode.org/license.html
https://avatars.githubusercontent.com/u/124872?v=4
zig-hiae
jedisct1/zig-hiae
2025-02-06T00:31:55Z
HiAE - A High-Throughput Authenticated Encryption Algorithm for Cross-Platform Efficiency.
master
0
14
0
14
https://api.github.com/repos/jedisct1/zig-hiae/tags
None
[ "aead", "aes", "encryption", "hiae", "zig-package" ]
1,706
false
2025-03-07T05:42:39Z
true
true
# HiAE: A High-Throughput Authenticated Encryption Algorithm for Cross-Platform Efficiency A Zig implementation of HiAE, along with support for parallel variants. ## Benchmarks ### Encryption #### Zen4 | Variant | Throughput | | :------ | ---------: | | HiAE | 252.0 Gb/s | | HiAEX2 | 449.9 Gb/s | | HiAEX4 | 472.8 Gb/s | #### Apple M1 | Variant | Throughput | | :------ | ---------: | | HiAE | 169.5 Gb/s | | HiAEX2 | 133.9 Gb/s | | HiAEX4 | 98.3 Gb/s | #### WebAssembly (lime1+simd128) | Variant | Throughput | | :------ | ---------: | | HiAE | 9.2 Gb/s | | HiAEX2 | 11.0 Gb/s | | HiAEX4 | 7.7 Gb/s | #### MAC #### Zen4 (likely limited by the memory bandwidth) | Variant | Throughput | | :--------- | ---------: | | HiAE-MAC | 315.8 Gb/s | | HiAEX2-MAC | 530.4 Gb/s | | HiAEX4-MAC | 522.2 Gb/s | | LeMAC | 345.0 Gb/s | #### Apple M1 | Variant | Throughput | | :--------- | ---------: | | HiAE-MAC | 163.1 Gb/s | | HiAEX2-MAC | 182.9 Gb/s | | HiAEX4-MAC | 138.8 Gb/s | | LeMAC | 219.2 Gb/s | #### WebAssembly (lime1+simd128) | Variant | Throughput | | :------ | ---------: | | HiAE | 9.8 Gb/s | | HiAEX2 | 12.0 Gb/s | | HiAEX4 | 7.7 Gb/s | | LeMAC | 10.0 Gb/s | ## Circuits ### Absorption ![Absorption in HiAE](.media/s1.png) ### Encryption ![Encryption in HiAE](.media/s2.png) ### Inversion ![Inversion in HiAE](.media/s3.png)
https://avatars.githubusercontent.com/u/3932972?v=4
zig-gemtext
ikskuh/zig-gemtext
2021-03-05T00:07:29Z
A zig library to manipulate gemini text files
master
0
14
3
14
https://api.github.com/repos/ikskuh/zig-gemtext/tags
MIT
[ "gemini", "gemini-language", "gemini-protocol", "markup", "markup-converter", "parser", "zig", "zig-package", "ziglang" ]
163
false
2025-01-30T09:38:05Z
true
false
# Gemini Text Processor This is a library and a tool to manipulate [gemini text files](https://gemini.circumlunar.space/docs/specification.html). It provides both an easy-to-use API as well as a streaming parser with minimal allocation requirements and a proper separation between temporary allocations required for parsing and allocations for returned text fragments. The library is thoroughly tested with a lot of gemini text edge cases and all (tested) cases are handled reasonably. ## Features - Fully spec-compliant gemini text parsing - Non-blocking streaming parser - Provides both a convenient [Zig](src/gemtext.zig) and [C](include/gemtext.h) API - Rendering to several formats - Gemini text - HTML - Markdown - RTF ## Example This is a simple example that parses a gemini file and converts it into a HTML file. ```zig pub fn main() !void { var document = try gemtext.Document.parse( std.heap.page_allocator, std.io.getStdIn().reader(), ); defer document.deinit(); try gemtext.renderer.html( document.fragments.items, std.io.getStdOut().writer(), ); } ``` More examples can be found the the examples folder: - `gem2html` ([C](examples/gem2html.c), [Zig](examples/gem2html.zig)) - `gem2md` ([C](examples/gem2md.c), [Zig](examples/gem2md.zig)) - `streaming-parser` ([C](examples/streaming-parser.c), [Zig](examples/streaming-parser.zig))
https://avatars.githubusercontent.com/u/2286349?v=4
zig-sbi
leecannon/zig-sbi
2022-03-03T23:01:23Z
Zig wrapper around the RISC-V SBI specification
master
0
14
4
14
https://api.github.com/repos/leecannon/zig-sbi/tags
MIT
[ "osdev", "risc-v", "riscv", "riscv32", "riscv64", "sbi", "zig", "zig-package", "ziglang" ]
138
false
2025-03-24T06:56:06Z
true
true
# zig-sbi Zig wrapper around the [RISC-V SBI specification](https://github.com/riscv-non-isa/riscv-sbi-doc). Compatible with SBI Specification v3.0-rc1. ## Installation Add the dependency to `build.zig.zon`: ```sh zig fetch --save git+https://github.com/leecannon/zig-sbi ``` Then add the following to `build.zig`: ```zig const sbi = b.dependency("sbi", .{}); exe.root_module.addImport("sbi", sbi.module("sbi")); ```
https://avatars.githubusercontent.com/u/5464072?v=4
zig-range
nektro/zig-range
2021-05-01T09:16:54Z
A range function to loop over an index without an extra variable.
master
0
14
1
14
https://api.github.com/repos/nektro/zig-range/tags
MIT
[ "zig", "zig-package" ]
4
false
2024-07-28T01:58:50Z
true
false
# zig-range ![loc](https://sloc.xyz/github/nektro/zig-range) [![license](https://img.shields.io/github/license/nektro/zig-range.svg)](https://github.com/nektro/zig-range/blob/master/LICENSE) [![discord](https://img.shields.io/discord/551971034593755159.svg?logo=discord)](https://discord.gg/P6Y4zQC) A range function to loop over an index without an extra variable ## Usage ```zig for (range(10)) |_, i| { // 'i' will increment from 0 -> 9 } ``` ## Building Example Program ``` $ zigmod fetch $ zig build ``` ## Built With - Zig Master & [Zigmod Package Manager](https://github.com/nektro/zigmod) ## License MIT
https://avatars.githubusercontent.com/u/5464072?v=4
zig-oauth2
nektro/zig-oauth2
2021-09-11T02:28:04Z
HTTP handler functions to allow you to easily add OAuth2 login support to your Zig application
master
0
13
1
13
https://api.github.com/repos/nektro/zig-oauth2/tags
MIT
[ "zig", "zig-package" ]
43
false
2025-03-24T09:54:58Z
true
false
# zig-oauth2 HTTP handler functions to allow you to easily add OAuth2 login support to your Zig application. ## Built With - Zig master - https://github.com/ziglang/zig - Zigmod package manager - https://github.com/nektro/zigmod ## Install ``` zigmod aq add 1/nektro/oauth2 ``` ## License MIT
https://avatars.githubusercontent.com/u/146390816?v=4
boost-libraries-zig
allyourcodebase/boost-libraries-zig
2024-08-30T17:29:41Z
Boost Libraries using build.zig
main
0
13
1
13
https://api.github.com/repos/allyourcodebase/boost-libraries-zig/tags
BSL-1.0
[ "boost-libraries", "cpp", "cpp-libraries", "zig-package" ]
129
false
2025-04-06T13:19:35Z
true
true
# Boost Libraries using Zig build-system [Boost Libraries](https://boost.io) using `build.zig`. Replacing the [CMake](https://cmake.org/) and [B2](https://www.bfgroup.xyz/b2/) build system. > [!IMPORTANT] > For C++ projects, `zig c++` uses llvm-libunwind + llvm-libc++ (static-linking) by default. > Except, for MSVC target (`-nostdlib++`). ### Requirements - [zig](https://ziglang.org/download) v0.14.0 or master ## How to use Build libraries ```bash # Build no-header-only libraries $ zig build -Doptimize=<Debug|ReleaseSafe|ReleaseFast|ReleaseSmall> \ -Dtarget=<triple-target> \ --summary <all|new> \ -Dcontext \ -Djson \ -Dsystem \ -Dcontainer \ -Dcobalt \ -Dfilesystem ``` #### Helper ```bash Project-Specific Options: -Dtarget=[string] The CPU architecture, OS, and ABI to build for -Dcpu=[string] Target CPU features to add or subtract -Ddynamic-linker=[string] Path to interpreter on the target system -Doptimize=[enum] Prioritize performance, safety, or binary size Supported Values: Debug ReleaseSafe ReleaseFast ReleaseSmall -Datomic=[bool] Build boost.atomic library (default: false) -Dcharconv=[bool] Build boost.charconv library (default: false) -Dcobalt=[bool] Build boost.cobalt library (default: false) -Dcontainer=[bool] Build boost.container library (default: false) -Dcontext=[bool] Build boost.context library (default: false) -Dexception=[bool] Build boost.exception library (default: false) -Dfiber=[bool] Build boost.fiber library (default: false) -Dfilesystem=[bool] Build boost.filesystem library (default: false) -Diostreams=[bool] Build boost.iostreams library (default: false) -Djson=[bool] Build boost.json library (default: false) -Dlog=[bool] Build boost.log library (default: false) -Dnowide=[bool] Build boost.nowide library (default: false) -Dprocess=[bool] Build boost.process library (default: false) -Dpython=[bool] Build boost.python library (default: false) -Drandom=[bool] Build boost.random library (default: false) -Dregex=[bool] Build boost.regex library (default: false) -Dserialization=[bool] Build boost.serialization library (default: false) -Dstacktrace=[bool] Build boost.stacktrace library (default: false) -Dsystem=[bool] Build boost.system library (default: false) -Durl=[bool] Build boost.url library (default: false) -Dwave=[bool] Build boost.wave library (default: false) -Dshared=[bool] Build as shared library (default: false) ``` ### or use in new zig project Make directory and init ```bash $ zig init ## add in 'build.zig.zon' boost-libraries-zig package $ zig fetch --save=boost git+https://github.com/allyourcodebase/boost-libraries-zig ``` Add in **build.zig** ```zig const std = @import("std"); pub fn build(b: *std.Build) !void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const boost_dep = b.dependency("boost", .{ .target = target, .optimize = optimize, }); const boost_artifact = boost_dep.artifact("boost"); for(boost_artifact.root_module.include_dirs.items) |include_dir| { try exe.root_module.include_dirs.append(b.allocator, include_dir); } // if not header-only, link library exe.linkLibrary(boost_artifact); } ``` ## How update zon dependencies Open [`update_zon.zig`](update_zon.zig) and change `const boost_version = "boost-version-tagged";` or add/sub url in `git_urls` list. ```bash zig run -fsingle-threaded update_zon.zig ``` ## License see: [LICENSE](LICENSE)
https://avatars.githubusercontent.com/u/71455761?v=4
ziglang-caches
Jeevananthan-23/ziglang-caches
2024-03-05T11:10:44Z
In-memory cache implementation with commonly used LRU, W-LFU and S3-FIFO as the eviction policy
master
3
13
0
13
https://api.github.com/repos/Jeevananthan-23/ziglang-caches/tags
MIT
[ "cache", "lfu-cache", "lru-cache", "s3fifo", "sieve", "zig", "zig-package", "ziglang" ]
50
false
2025-01-22T14:26:29Z
true
true
# ziglang-caches This is a modern cache implementation, inspired by the following papers, provides high efficiency. - SIEVE | [SIEVE is Simpler than LRU: an Efficient Turn-Key Eviction Algorithm for Web Caches (NSDI'24)](https://junchengyang.com/publication/nsdi24-SIEVE.pdf) - S3-FIFO | [FIFO queues are all you need for cache eviction (SOSP'23)](https://dl.acm.org/doi/10.1145/3600006.3613147) - W-TinyLFU | [TinyLFU: A Highly Efficient Cache Admission Policy](https://arxiv.org/abs/1512.00727) This offers state-of-the-art efficiency and scalability compared to other LRU-based cache algorithms. ## Basic usage > [!LRU_Cache] > Least recents used cache eviction policy for cache your data in-memory for fast access. ```zig const std = @import("std"); const lru = @import("lru"); const cache = lru.LruCache(.locking, u8, []const u8); pub fn main() !void { // Create a cache backed by DRAM var lrucache = try cache.init(std.heap.page_allocator, 4); defer lrucache.deinit(); // Add an object to the cache try lrucache.insert(1, "one"); try lrucache.insert(2, "two"); try lrucache.insert(3, "three"); try lrucache.insert(4, "four"); // Most recently used cache std.debug.print("mru: {s} \n", .{lrucache.mru().?.value}); // least recently used cache std.debug.print("lru: {s} \n", .{lrucache.lru().?.value}); // remove from cache _ = lrucache.remove(1); // Check if an object is in the cache O/P: false std.debug.print("key: 1 exists: {} \n", .{lrucache.contains(1)}); } ``` ### :rocket: Usage 1. Add `ziglang-caches` as a dependency in your `build.zig.zon`. <details> <summary><code>build.zig.zon</code> example</summary> ```zig .{ .name = "<name_of_your_package>", .version = "<version_of_your_package>", .dependencies = .{ .caches = .{ .url = "https://github.com/jeevananthan-23/ziglang-caches/archive/<git_tag_or_commit_hash>.tar.gz", .hash = "<package_hash>", }, }, } ``` Set `<package_hash>` to `12200000000000000000000000000000000000000000000000000000000000000000`, and Zig will provide the correct found value in an error message. </details> 2. Add `lrucache` as a module in your `build.zig`. <details> <summary><code>build.zig</code> example</summary> ```zig const lrucache = b.dependency("caches", .{}); exe.addModule("lrucache", lrucache.module("lrucache")); ``` </details>
https://avatars.githubusercontent.com/u/565124?v=4
typ
peterhellberg/typ
2024-09-11T17:48:48Z
A small Zig ⚑ module, as a convenience for me when writing WebAssembly plugins for Typst
main
0
13
0
13
https://api.github.com/repos/peterhellberg/typ/tags
MIT
[ "module", "typesetting", "typst", "zig-package" ]
28
false
2025-03-05T16:20:36Z
true
true
# typ :printer: A small [Zig](https://ziglang.org/) ⚑ module, as a convenience for me when writing WebAssembly [plugins](https://typst.app/docs/reference/foundations/plugin/) for [Typst](https://typst.app/) > [!NOTE] > Initially based on the [hello.zig](https://github.com/astrale-sharp/wasm-minimal-protocol/blob/master/examples/hello_zig/hello.zig) > example in [wasm-minimal-protocol](https://github.com/astrale-sharp/wasm-minimal-protocol/) ## Requirements You will want to have a fairly recent [Zig](https://ziglang.org/download/#release-master) as well as the [Typst CLI](https://github.com/typst/typst?tab=readme-ov-file#installation) > [!IMPORTANT] > I had to `rustup default 1.79.0` when compiling the latest `typst` > as there were some breaking change in `1.80.0` > [!TIP] > Some of the software that I have installed for a pretty > nice **Typst** workflow in [Neovim](https://neovim.io/): > > - https://github.com/nvarner/typst-lsp > - https://github.com/kaarmu/typst.vim > - https://github.com/chomosuke/typst-preview.nvim ## Usage Use `zig fetch` to add a `.typ` to the `.dependencies` in your `build.zig.zon` ```console zig fetch --save https://github.com/peterhellberg/typ/archive/refs/tags/v0.1.0.tar.gz ``` > [!NOTE] > You should now be able to update your `build.zig` as described below. #### `build.zig` ```zig const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.resolveTargetQuery(.{ .cpu_arch = .wasm32, .os_tag = .freestanding, }); const hello = b.addExecutable(.{ .name = "hello", .root_source_file = b.path("hello.zig"), .strip = true, .target = target, .optimize = .ReleaseSmall, }); const typ = b.dependency("typ", .{}).module("typ"); hello.root_module.addImport("typ", typ); hello.entry = .disabled; hello.rdynamic = true; b.installArtifact(hello); } ``` #### `hello.zig` ```zig const typ = @import("typ"); export fn hello() i32 { const msg = "*Hello* from `hello.wasm` written in Zig!"; return typ.str(msg); } export fn echo(len: usize) i32 { var res = typ.alloc(u8, len * 2) catch return 1; defer typ.free(res); typ.in(res.ptr); for (0..len) |i| { res[i + len] = res[i]; } return typ.ok(res); } ``` #### `hello.typ` ```typst #set page(width: 10cm, height: 10cm) #set text(font: "Inter") == A WebAssembly plugin for Typst #line(length: 100%) #emph[Typst is capable of interfacing with plugins compiled to WebAssembly.] #line(length: 100%) #let p = plugin("zig-out/bin/hello.wasm") #eval(str(p.hello()), mode: "markup") #eval(str(p.echo(bytes("1+2"))), mode: "code") ``` #### Expected output ![hello.png](https://github.com/user-attachments/assets/a1cd9c86-ef94-4d1f-a44c-b958475f79b0)
https://avatars.githubusercontent.com/u/5464072?v=4
zig-tls
nektro/zig-tls
2022-10-28T21:49:40Z
[WIP] A pure-Zig TLS 1.3 client implementation.
master
0
13
0
13
https://api.github.com/repos/nektro/zig-tls/tags
MIT
[ "tls", "tls13", "zig", "zig-package" ]
40
false
2024-06-22T18:27:40Z
true
false
# zig-tls A pure-Zig [RFC8446 TLS 1.3](https://tools.ietf.org/html/rfc8446) client implementation. Crypto is hard, please feel free to view the source and open issues for any improvements. Indebted to https://tls13.xargs.org/ and multiple readings of the RFC. ## License MIT
https://avatars.githubusercontent.com/u/109542784?v=4
aws-sdk-zig
by-nir/aws-sdk-zig
2024-02-26T22:48:38Z
🟧 AWS SDK for the Zig programming language
main
0
13
0
13
https://api.github.com/repos/by-nir/aws-sdk-zig/tags
MIT
[ "aws", "aws-sdk", "cloud", "sdk", "zig", "zig-package" ]
1,354
false
2025-02-24T18:03:42Z
true
true
# AWS SDK for Zig ![Zig v0.14 (dev)](https://img.shields.io/badge/Zig-v0.14_(dev)_-black?logo=zig&logoColor=F7A41D "Zig v0.14 – master branch") [![MIT License](https://img.shields.io/github/license/by-nir/aws-sdk-zig)](/LICENSE) **The _AWS SDK for Zig_ provides an interface for _Amazon Web Services (AWS)_.** > [!CAUTION] > This project is in early development, DO NOT USE IT IN PRODUCTION! > > Support for the remaining services and features will be added as the project > matures and stabilize. **Breaking changes are imminent!** _Pure Zig implementation,_ from code generation to runtime SDKs. Building upon the language’s strong foundation, this project provides a **performant** and fully functioning SDKs, while **minimizing dependencies** and increased **platform portability**. > [!TIP] > Use the [AWS Lambda Runtime for Zig](https://github.com/by-nir/aws-lambda-zig) > to deploy Lambda functions written in Zig. ## Supported Features ### Authentication | Status | Method | Runs locally | |:------:|:-------|:------------:| | | [IAM Identity Center authentication](https://docs.aws.amazon.com/sdkref/latest/guide/access-sso.html) | βœ“ | | | [IAM Roles Anywhere](https://docs.aws.amazon.com/sdkref/latest/guide/access-rolesanywhere.html) | βœ“ | | | [Assume a role](https://docs.aws.amazon.com/sdkref/latest/guide/access-assume-role.html) | βœ“ | | βœ“ | [AWS access keys](https://docs.aws.amazon.com/sdkref/latest/guide/access-users.html) | βœ“ | | | [IAM roles for EC2 instances](https://docs.aws.amazon.com/sdkref/latest/guide/access-iam-roles-for-ec2.html) | | ### Settings | Status | Feature | Notes | |:------:|:--------|:------| | | [Application ID](https://docs.aws.amazon.com/sdkref/latest/guide/feature-appid.html) | | | | [Amazon EC2 instance metadata](https://docs.aws.amazon.com/sdkref/latest/guide/feature-ec2-instance-metadata.html) | | | | [Amazon S3 access points](https://docs.aws.amazon.com/sdkref/latest/guide/feature-s3-access-point.html) | | | | [Amazon S3 Multi-Region Access Points](https://docs.aws.amazon.com/sdkref/latest/guide/feature-s3-mrap.html) | | | βœ“ | [AWS Region](https://docs.aws.amazon.com/sdkref/latest/guide/feature-region.html) | | | | [AWS STS Regionalized endpoints](https://docs.aws.amazon.com/sdkref/latest/guide/feature-sts-regionalized-endpoints.html) | | | βœ“ | [Dual-stack and FIPS endpoints](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoints.html) | | | | [Endpoint discovery](https://docs.aws.amazon.com/sdkref/latest/guide/feature-endpoint-discovery.html) | | | | [General configuration](https://docs.aws.amazon.com/sdkref/latest/guide/feature-gen-config.html) | | | | [IMDS client](https://docs.aws.amazon.com/sdkref/latest/guide/feature-imds-client.html) | | | | [Retry behavior](https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html) | | | | [Request compression](https://docs.aws.amazon.com/sdkref/latest/guide/feature-compression.html) | | | | [Service-specific endpoints](https://docs.aws.amazon.com/sdkref/latest/guide/feature-ss-endpoints.html) | | | | [Smart configuration defaults](https://docs.aws.amazon.com/sdkref/latest/guide/feature-smart-config-defaults.html) | | ## Contributing > [!IMPORTANT] > At this point, the project serves as environment for developing other experimental sub-projects. > This initiative is in an exploratory phase and is **not yet ready for contributions**. | πŸ“ | Description | |:----------------------------------|:----------------------------------------------------------------| | [sdk](sdk/) | AWS SDKs for Zig<br />_Auto-generated, do not modify manually!_ | | [aws/runtime](aws/runtime/) | SDK runtime shared by all the services | | [aws/codegen](aws/codegen/) | AWS-specific source generation pipeline | | [smithy/runtime](smithy/runtime/) | [Smithy 2.0](https://smithy.io/2.0) client runtime | | [smithy/codegen](smithy/codegen/) | [Smithy 2.0](https://smithy.io/2.0) source generation pipeline | ### CLI Commands - `zig build --build-file build.codegen.zig` Generate the AWS SDKs source code. - Optionally specify one or more `-Dfilter=sdk_codename` to select specific services. - `zig build test:<service>` Run generated SDK service’s unit tests. ## License The author and contributors are not responsible for any issues or damages caused by the use of this software, part of it, or its derivatives. See [LICENSE](/LICENSE) for the complete terms of use. > [!NOTE] > _AWS SDK for Zig_ is not an official _Amazon Web Services_ software, nor is it > affiliated with _Amazon Web Services, Inc_. The SDKs code is generated based on a dataset of _Smithy models_ created by _Amazon Web Services_. The models are extracted from the official [AWS SDK for Rust](https://github.com/awslabs/aws-sdk-rust) and [licensed](https://github.com/awslabs/aws-sdk-rust/blob/main/LICENSE) as declared by Amazon Web Services, Inc. at the source repository. This codebase, including the generated code, are covered by a [standalone license](/LICENSE). ## References ### Smithy - [Smithy Spec](https://smithy.io/2.0/index.html) - [Smithy Reference Implementation](https://github.com/smithy-lang/smithy) - [Smithy Rust](https://github.com/smithy-lang/smithy-rs) ### AWS SDKs - [AWS SDKs and Tools Reference Guide](https://docs.aws.amazon.com/sdkref/latest/guide/overview.html) - [AWS Common Runtime (CRT) libraries](https://docs.aws.amazon.com/sdkref/latest/guide/common-runtime.html) - [AWS SDK for C++](https://github.com/aws/aws-sdk-cpp) - [AWS SDK for Rust](https://github.com/awslabs/aws-sdk-rust)
https://avatars.githubusercontent.com/u/8091245?v=4
mzg
uyha/mzg
2025-03-20T19:22:09Z
A MessagePack library for Zig
main
0
13
0
13
https://api.github.com/repos/uyha/mzg/tags
MIT
[ "message-pack", "msgpack", "zig", "zig-package" ]
134
false
2025-04-08T10:34:54Z
true
true
<!-- markdownlint-disable no-inline-html --> # mzg <!--toc:start--> - [mzg](#mzg) - [How to use](#how-to-use) - [API](#api) - [High level functions](#high-level-functions) - [Building block functions](#building-block-functions) - [Examples](#examples) - [Simple back and forth](#simple-back-and-forth) - [Default packing and unpacking for custom types](#default-packing-and-unpacking-for-custom-types) - [Adapters for common container types](#adapters-for-common-container-types) - [Mapping](#mapping) - [Default packing from Zig types to MessagePack](#default-packing-from-zig-types-to-messagepack) - [Default unpack from MessagePack to Zig types](#default-unpack-from-messagepack-to-zig-types) - [Customization](#customization) - [Packing](#packing) - [Unpacking](#unpacking) <!--toc:end--> `mzg` is a MessagePack library for Zig with no allocations, and the API favors the streaming usage. ## How to use 1. Run the following command to add this project as a dependency ```sh zig fetch --save git+https://github.com/uyha/mzg.git#v0.0.3 ``` 1. In your `build.zig`, add the following ```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")); ``` ## API ### High level functions 1. `pack` for packing Zig values using a `writer` 1. `packWithOptions` is like `pack` but accepts a `mzg.PackOptions` parameter to control the packing behavior. 1. `unpack` for unpacking a MessagePack message into a Zig object 1. A set of adapters living in the `mzg.adapter` namespace to help with packing and unpacking common container types. ### Building block functions There are a set of `pack*` and `unpack*` 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 [examples](examples) 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); 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, &string); std.debug.print("Consumed {} bytes\n", .{size}); std.debug.print("string: {s}\n", .{string}); } 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 [Mapping](#mapping) for more details) ```zig pub fn main() !void { const allocator = std.heap.page_allocator; var buffer: std.ArrayListUnmanaged(u8) = .empty; defer buffer.deinit(allocator); try mzg.pack( Targets{ .position = .init(2000), .velocity = .init(10) }, buffer.writer(allocator), ); var targets: Targets = undefined; const size = try mzg.unpack(buffer.items, &targets); std.debug.print("Consumed {} bytes\n", .{size}); std.debug.print("Targets: {}\n", .{targets}); } const Position = enum(i32) { _, pub fn init(raw: std.meta.Tag(@This())) @This() { return @enumFromInt(raw); } }; const Velocity = enum(i32) { _, 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 `std` 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); 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(&in), buffer.writer(allocator)); var out: std.ArrayListUnmanaged(u32) = .empty; defer out.deinit(allocator); const size = try mzg.unpack( buffer.items, adapter.unpackArray(&out, allocator), ); std.debug.print("Consumed {} bytes\n", .{size}); std.debug.print("out: {any}\n", .{out.items}); } const std = @import("std"); const mzg = @import("mzg"); const adapter = mzg.adapter; ``` ## Mapping ### Default packing from Zig types to MessagePack <!-- markdownlint-disable line-length --> | Zig Type | MessagePack | |------------------------------------------|-----------------------------------------------------------| | `void`, `null` | `nil` | | `bool` | `bool` | | integers (<=64 bits) | `int` | | floats (<=64 bits) | `float` | | `?T` | `nil` if value is `null`, pack according to `T` otherwise | | enums | `int` | | enum literals | `str` | | tagged unions | `array` of 2 elements: `int` and the value of the union | | packed structs | `int` | | structs and tuples | `array` of fields in the order they are declared | | `[N]`, `[]`, `[:X]`, and `@Vec` of `u8` | `str` | | `[N]`, `[]`, `[:X]`, and `@Vec` of `T` | `array` of `T` | | `Ext` | `ext` | | `Timestamp` | `Timestamp` | | `*T` | `T` | <!-- markdownlint-enable line-length --> ### Default unpack from MessagePack to Zig types | MessagePack | Compatible Zig Type | |-------------|--------------------------------------| | `nil` | `void`, `?T` | | `bool` | `bool` | | `int` | integers, enums | | `float` | floats | | `str` | `[]const u8` | | `bin` | `[]const u8` | | `array` | The length can be read into integers | | `map` | The length can be read into integers | | `ext` | `Ext` | | `Timestamp` | `Timestamp` | ### Customization #### Packing When an enum/union/struct has an `mzgPack` function with the signature being one of ```zig pub fn mzgPack(self: *@This(), writer: anytype) !void ``` ```zig pub fn mzgPack(self: *@This(), options: mzg.PackOptions, writer: anytype) !void ``` The function will be called when the `mzg.pack` function is used. #### Unpacking When an enum/union/struct has an `mzgUnpack` function with the signature being ```zig pub fn mzgUnpack(self: @This(), buffer: []const u8) UnpackError!usize ``` The function will be called when the `mzg.unpack` function is used.
https://avatars.githubusercontent.com/u/124872?v=4
zig-aes-gem
jedisct1/zig-aes-gem
2024-07-13T23:19:08Z
AES-GEM (AES Galois Extended Mode) implementation.
main
0
13
1
13
https://api.github.com/repos/jedisct1/zig-aes-gem/tags
MIT
[ "aes", "aes-gem", "gem", "zig", "zig-package" ]
4
false
2025-03-07T05:42:44Z
true
true
404
https://avatars.githubusercontent.com/u/80392719?v=4
zfat
ZigEmbeddedGroup/zfat
2022-05-07T08:35:40Z
Generic purpose platform-independent FAT driver for Zig
main
0
13
5
13
https://api.github.com/repos/ZigEmbeddedGroup/zfat/tags
MIT
[ "fat", "fat32", "filesystem", "zig", "zig-package" ]
2,332
false
2025-03-13T23:12:12Z
true
true
# zfat Bindings for the [FatFs](http://elm-chan.org/fsw/ff/00index_e.html) library
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
13
1
13
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-10T11:36:03Z
true
true
# mini-parser mini-parser is a very-minimal parser for [Zig](https://ziglang.org) 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 <opts> \\ \\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..]; var i: usize = 0; while (argv.len > i) : (i += 1) { const parser = try mini_parser.init(argv[i], &.{ .{ .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 => { debug.print("no argument was given.\n", .{}); posix.exit(0); }, 1 => { // 1 debug.print("{s}\n", .{usage}); posix.exit(0); }, 2 => debug.print("Text: {s}\n", .{parser.value}), // 2 3 => debug.print("Enabled boolean!\n", .{}), // 3 4 => { debug.print("argument '{s}' does not exist.\n", .{argv[i]}); posix.exit(0); }, else => {}, } } } ``` ## Installation Fetch mini-parser package to `build.zig.zon`: ```sh zig fetch --save git+https://github.com/Operachi061/mini-parser ``` Then add following to `build.zig`: ```zig const mini_parser = b.dependency("mini_parser", .{}); exe.root_module.addImport("mini_parser", mini_parser.module("mini_parser")); ``` After building, test it via: ```sh ./example --bool --text foo -h ``` ## License This project is based on the BSD 3-Clause license.
https://avatars.githubusercontent.com/u/51416554?v=4
http2.zig
hendriknielaender/http2.zig
2024-01-30T17:22:10Z
🌐 HTTP/2 server for zig
main
15
13
1
13
https://api.github.com/repos/hendriknielaender/http2.zig/tags
MIT
[ "http-server", "http2", "zig", "zig-library", "zig-package" ]
373
false
2024-12-09T09:57:20Z
true
true
> [!WARNING] > Still work in progress. <h1 align="center"> <img src="docs/images/logo.png" width="40%" height="40%" alt="http2.zig logo" title="http2.zig logo"> </h1> <div align="center">A HTTP/2 Zig library according to the HTTP/2 RFCs.</div> <div align="center"> [![MIT license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/hendriknielaender/http2.zig/blob/HEAD/LICENSE) ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/hendriknielaender/http2.zig) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](https://github.com/hendriknielaender/http2.zig/blob/HEAD/CONTRIBUTING.md) ![h2spec Conformance](https://img.shields.io/badge/h2spec-71%2F74%20tests%20passing-red) </div> ## Features - Connection management - Stream handling - Frame parsing and serialization - Compliance with HTTP/2 specifications ## Installation You can use `zig fetch` to conveniently set the hash in the `build.zig.zon` file and update an existing dependency. Run the following command to fetch the http2.zig package: ```shell zig fetch https://github.com/hendriknielaender/http2.zig/archive/<COMMIT>.tar.gz --save ``` Using `zig fetch` simplifies managing dependencies by automatically handling the package hash, ensuring your `build.zig.zon` file is up to date. ### Option 1 (build.zig.zon) 1. Declare http2.zig as a dependency in `build.zig.zon`: ```diff .{ .name = "my-project", .version = "1.0.0", .paths = .{""}, .dependencies = .{ + .http2 = .{ + .url = "https://github.com/hendriknielaender/http2.zig/archive/<COMMIT>.tar.gz", + }, }, } ``` 2. Add the module in `build.zig`: ```diff const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + const opts = .{ .target = target, .optimize = optimize }; + const http2_module = b.dependency("http2", opts).module("http2"); const exe = b.addExecutable(.{ .name = "test", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); + exe.root_module.addImport("http2", http2_module); exe.install(); ... } ``` 3. Get the package hash: ```shell $ zig build my-project/build.zig.zon:6:20: error: url field is missing corresponding hash field .url = "https://github.com/hendriknielaender/http2.zig/archive/<COMMIT>.tar.gz", ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ note: expected .hash = "<HASH>", ``` 4. Update `build.zig.zon` package hash value: ```diff .{ .name = "my-project", .version = "1.0.0", .paths = .{""}, .dependencies = .{ .http2 = .{ .url = "https://github.com/hendriknielaender/http2.zig/archive/<COMMIT>.tar.gz", + .hash = "<HASH>", }, }, } ``` ## Usage ### Connection To create an HTTP/2 connection, use the `Connection` struct. This struct handles the initialization, sending of the HTTP/2 preface, settings, and managing streams. ```zig const std = @import("std"); const http2 = @import("http2"); const Connection = http2.Connection(std.io.AnyReader, std.io.AnyWriter); pub fn main() !void { const address = try std.net.Address.resolveIp("0.0.0.0", 8081); var listener = try address.listen(.{ .reuse_address = true }); defer listener.deinit(); std.debug.print("Listening on 127.0.0.1:8081...\n", .{}); while (true) { var conn = try listener.accept(); defer conn.stream.close(); std.debug.print("Accepted connection from: {any}\n", .{conn.address}); var server_conn = Connection.init(@constCast(&std.heap.page_allocator), conn.stream.reader().any(), conn.stream.writer().any(), true) catch |err| { std.debug.print("Failed to initialize connection: {}\n", .{err}); continue; }; defer server_conn.deinit(); // Handle connection and errors during the process server_conn.handleConnection() catch |err| { std.debug.print("Error handling connection: {}\n", .{err}); }; std.debug.print("Connection from {any} closed\n", .{conn.address}); } } ```
https://avatars.githubusercontent.com/u/4718156?v=4
boltdb-zig
laohanlinux/boltdb-zig
2023-05-13T17:12:55Z
No Description
main
1
12
0
12
https://api.github.com/repos/laohanlinux/boltdb-zig/tags
Apache-2.0
[ "zig-package" ]
27,898
false
2025-01-23T02:41:46Z
true
true
# boltdb-zig A pure Zig implementation of BoltDB, an embedded key/value database. ## Overview boltdb-zig is a Zig port of the original [BoltDB](https://github.com/boltdb/bolt), which is a simple yet powerful embedded key/value database written in Go. It provides a consistent and ACID-compliant data store with the following features: - Pure Zig implementation - Single file backend - ACID transactions - Lock-free MVCC - Nested buckets ## Status 🚧 This project is currently under development. ## Usage ```zig # zig fetch --save git+https://github.com/laohanlinux/boltdb-zig.git ``` import the library in your build.zig.zon file: [link](example/build.zig.zon) ``` const boltdbDep = b.dependency("boltdb-zig", .{ .target = target, .optimize = optimize, }); const exe = b.addExecutable(.{ .name = "example", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); exe.root_module.addImport("boltdb", boltdbDep.module("boltdb")); ``` How use? [link](example/src/main.zig) ## License This project is licensed under the MIT License - see the LICENSE file for details. ## Acknowledgments - Original [BoltDB](https://github.com/boltdb/bolt)
https://avatars.githubusercontent.com/u/46653655?v=4
zinger
BitlyTwiser/zinger
2024-12-01T01:18:42Z
Simple HTTP request library for Zig applications
main
0
12
1
12
https://api.github.com/repos/BitlyTwiser/zinger/tags
Apache-2.0
[ "http", "http-requests", "zig", "zig-package", "ziglang" ]
231
false
2025-03-07T20:11:16Z
true
true
<div align="center"> <img src="/assets/zinger.jpg" width="450" height="500"> # Zinger A Simple HTTP request library # Contents [Usage](#usage) | [Make Requests](#make-requests) | [GET](#get) | [POST](#post) | [PUT and DELETE](#put-and-delete) | [Supported Requests](#supports) | </div> ## Usage Add Zinger to your Zig project with Zon: ```sh zig fetch --save https://github.com/BitlyTwiser/zinger/archive/refs/tags/v0.1.1.tar.gz ``` Add the following to build.zig file: ```zig const zinger = b.dependency("zinger", .{}); exe.root_module.addImport("zinger", zinger.module("zinger")); ``` Import Zinger and you should be set! ```zig const zinger = @import("zinger").Zinger; ``` Please see the examples in the main.zig file or below to view using the package ## Make requests Any of the requsts can be made with a body utilizing the optional values. Additionally, any body can be converted to JSON by utilizing the anytype passed into the `json` function call. The example in main shows how to make a request and check for errors in the query ### max_append_size Note: The std.http.Client.FetchOptions, by default, sets a max body size (if not defined) to: ``` 2 * 1024 * 1024```. If this is enough for your use cases (most general HTTP requests with a smaller JSON body would fit within this allotment), then everything is fine. Overwise, you will need to pass in the alloted/desired amount into Zinger init. Example: ```zig var z = zinger.Zinger.init(allocator, null); // OR // The numerical value here should be carefully considered to avoid over allocation. var z = zinger.Zinger.init(allocator, 1024 * 10); ``` ```zig const allocator = std.heap.page_allocator; var z = zinger.Zinger.init(allocator, null); defer z.deinit(); var headers = [_]std.http.Header{}; const resp = try z.get("<some api>", null, &headers); if (resp.err()) |err_data| { std.debug.print("{s}", .{err_data.phrase}); } if (resp.err() != null) { try resp.printErr(); } ``` This is the most *basic* example there is for curating requests. A simple get request, but otherwiese does not display anything as we pass in a null body. (Perhaps useful if all you want to check is the status of the response which is done in the resp.err() check) ## GET ```zig const allocator = std.heap.page_allocator; var z = zinger.Zinger.init(allocator, 1024 * 2 * 2); defer z.deinit(); var headers = [_]std.http.Header{}; const resp = try z.get("<some api>", null, &headers); if (resp.err()) |err_data| { std.debug.print("{s}", .{err_data.phrase}); } if (resp.err() != null) { try resp.printErr(); } // Serialize the JSON data from the body using the json(anytype) method. // Pass any struct type here to marshal the body into the struct. // Obviously, ensure that the struct attributes match the returned JSON data from the endpoint const json_resp = try resp.json(test_resp_type); std.debug.print("{any}", .{json_resp}); ``` ## POST You can denote whatever type you want for the JSON data in a custom struct ```zig const test_resp_type = struct { test_data: []const u8, }; ``` ```zig fn post(allocator: std.mem.Allocator) !void { // Create Zinger instance for POST var z = zinger.Zinger.init(allocator, null); const test_data = struct { example_string: []const u8, }{ .example_string = "testing", }; const json_body = std.json.stringifyAlloc(allocator, test_data, .{}); defer allocator.free(json_body); var headers = [_]std.http.Header{.{ .name = "content-type", .value = "application/json" }}; const resp = try z.get("<api endpoint>", test_data, &headers); if (resp.err()) |err_data| { std.debug.print("{s}", .{err_data.phrase}); } if (resp.err() != null) { try resp.printErr(); } // Serialize the JSON data from the body using the json(anytype) method using the custom struct above const resp_data = struct { example_string: []const u8, }{}; const json_resp = try resp.json(resp_data); std.debug.print("{any}", .{json_resp}); } ``` ## PUT and DELETE Following the same pattern above, you *can* unclude a body as part of the DELETE/PUT requests. The library is really designed around however the user wants to present the data, attempting to make it as simple as possible to make all the general requests you need. For PUT/DELETE, simply change the HTTP verb in the above examples and you are set! PUT/DELETE: ```zig fn delete(allocator: std.mem.Allocator) !void { // Create Zinger instance for POST // The value for the max_override here is just symbolic for reference, // this would generally be null unless you *need* to override this value var z = zinger.Zinger.init(allocator, 2048 * 10); const test_data = struct { example_string: []const u8, }{ .example_string = "testing", }; const json_body = try std.json.stringifyAlloc(allocator, test_data, .{}); defer allocator.free(json_body); var headers = [_]std.http.Header{.{ .name = "content-type", .value = "application/json" }}; var resp = try z.delete("<api endpoint>", json_body, &headers); if (resp.err() != null) { try resp.printErr(); return; } // Serialize the JSON data from the body using the json(anytype) method. const json_resp = try resp.json(test_resp_type); std.debug.print("{any}", .{json_resp}); } fn put(allocator: std.mem.Allocator) !void { // Create Zinger instance for POST var z = zinger.Zinger.init(allocator, null); const test_data = struct { example_string: []const u8, }{ .example_string = "testing", }; const json_body = try std.json.stringifyAlloc(allocator, test_data, .{}); defer allocator.free(json_body); var headers = [_]std.http.Header{.{ .name = "content-type", .value = "application/json" }}; var resp = try z.put("<api endpoint>", json_body, &headers); if (resp.err()) |err_data| { std.debug.print("{s}", .{err_data.phrase}); return; } // Serialize the JSON data from the body using the json(anytype) method. const json_resp = try resp.json(test_resp_type); std.debug.print("{any}", .{json_resp}); } ``` # Supports GET, POST, PUT, and DELETE requests
https://avatars.githubusercontent.com/u/22280250?v=4
zon_get_fields
Durobot/zon_get_fields
2023-12-27T18:10:39Z
Utility functions to get field values from the abstract syntax tree generated from ZON (Zig Object Notation) text using Zig stdlib
main
0
12
3
12
https://api.github.com/repos/Durobot/zon_get_fields/tags
MIT
[ "zig", "zig-package", "ziglang", "zon" ]
192
false
2025-03-03T07:45:01Z
true
true
# zon_get_fields Several functions to facilitate the process of walking Abstract Syntax Trees (ASTs) generated from [ZON](https://github.com/ziglang/zig/issues/14290) text, and fetch the values of the fields from the AST. But first you have to call `std.zig.Ast.parse` to tokenize and parse your ZON, creating the AST. Updated to work with and tested with Zig **0.14.0-dev.3046+08d661fcf**. The latest commit is not going to work with earlier versions of Zig 0.14.0-dev, because of the breaking changes in lib/std/builtin.zig (change of names of struct fields, like `Array.sentinel` to `sentinel_ptr` or `StructField.default_value` to `default_value_ptr`). Support for older versions, like Zig **0.12.0**, **0.12.1**, **0.13.0**, and **0.14.0-dev.91+a154d8da8** was dropped because of [this breaking change in the standard library](https://github.com/ziglang/zig/commit/0fe3fd01ddc2cd49c6a2b939577d16b9d2c65ea9). If you need a version of zon_get_fields that works with older Zig versions, [get this release](https://github.com/Durobot/zon_get_fields/releases/tag/v0.1-beta). It still probably won't work with Zig 0.11, but you're welcome to try it and report back, although I'm not too keen on backporting. **zon_get_fields** is licensed under the [the MIT License](https://en.wikipedia.org/w/index.php?title=MIT_License&useskin=vector). You are more than welcome to drop `zon_get_fields.zig` into your project (don't forget to `const zgf = @import("zon_get_fields.zig");`), or you can use the Zig package manager: 1. In your project's `build.zig.zon`, in `.dependencies`, add ```zig .zon_get_fields = .{ .url = "https://github.com/Durobot/zon_get_fields/archive/<GIT COMMIT HASH, 40 HEX DIGITS>.tar.gz", .hash = "<ZIG PACKAGE HASH, 68 HEX DIGITS>" // Use arbitrary hash, get correct hash from the error } ``` 2. In your project's `build.zig`, in `pub fn build`, before `b.installArtifact(exe);`, add ```zig const zgf = b.dependency("zon_get_fields", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zon_get_fields", zgf.module("zon_get_fields")); ``` 3. Add `const zgf = @import("zon_get_fields");`in your source file(s). 3. Build your project with `zig build`, as you normally do. Things I like: 1. Hey, it works! At least it looks like it does, and since nothing like this exists in the standard library, I consider it a success; 2. You can throw your struct and an AST at a function (`pub fn zonToStruct`), and have your struct filled with data. The fields that have matching values in the provided AST, that is, and you get to know what was filled and what was not - look and the returned struct; 3. Or you can fetch the values of the fields you need using string paths to indicate them, calling `pub fn getFieldVal`. It's fine if all you need is a couple of fields; 3. All the basics are covered - signed and unsigned integers and floats, strings, single characters, booleans, nested structs, arrays, arrays of arrays, arrays of structs (in fact, any combination of structs and arrays should work). Things I don't really like: 1. No AST validity verification. Thinking about ZON schemas or similar in the future, maybe? 2. If you use the second approach, `pub fn getFieldVal`, for every field you want to read you've got to specify the path. The path is split, the AST is walked, and if you have rather large structures to fetch, a lot of this work is repeated for each field. Not the best approach performance-wise. But you can switch to `pub fn zonToStruct`, which fills all the fields it can it one go; 3. An ugly hack that I had to use in order to get negative values from the fields, both integers and floating point. See `fn fulllTokenSlice`. I can't be sure my approach works correctly in all situations, or will continue to work in the future, so I feel really uneasy about using it; For examples of how to use them, turn to the test sections in `zon_parse.zig`: 1. Find `zonToStruct Tests` [comment](https://github.com/Durobot/zon_get_fields/blob/cd1524a1e30b1375524a48b491d845f27a3b4594/src/zon_get_fields.zig#L1490) for `pub fn zonToStruct` approach - filling your struct all at once; 2. Find `getFieldVal Tests` [comment](https://github.com/Durobot/zon_get_fields/blob/cd1524a1e30b1375524a48b491d845f27a3b4594/src/zon_get_fields.zig#L428) for `pub fn getFieldVal`approach - fetching field values one by one, as you provide string paths to each field. Or check out the short examples below (you can compile and run them with `zig build example_zon_to_struct` and `zig build example_get_field_val` commands). Say you've got this ZON file (`my.zon`): ```zon .{ .database = .{ .host = "127.0.0.1", .port = 5432, .user = "superadmin", .password = "supersecret", }, .decimal_separator = '.', .months_in_year = 12, .newline_char = '\n', .pi = 3.14159265359, .hello = "こんにけは", .unicode_char = '⚑', .primes = .{ 2, 3, 5, 7, 11 }, .factorials = .{ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800 }, .slc_of_structs = .{ .{ .ham = 10, .eggs = 2 }, .{ .ham = 5 } }, .slc_of_arrays = .{ .{ 10, 20, 30 }, .{ 40, 50, }, }, .slc_of_slices = .{ .{ 1, 2, 3 }, .{ 4, 5 }, .{ 6 } } } ``` Then you can either: 1. Define a struct, pass a pointer to it together with AST built from `my.zon` to pub `fn zonToStruct`, get your struct filled, and get a report struct which mirrors the fields of your struct, indicating whether they were filled or not (see [this table](#Report-struct-field-types) for report struct field types): ```zig const std = @import("std"); const zgf = @import("zon_get_fields.zig"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocr = gpa.allocator(); // `Ast.parse` requires a sentinel (0) terminated slice, so we pass 0 as the sentinel value (last arg) const zon_txt = try std.fs.cwd().readFileAllocOptions(allocr, "my.zon", std.math.maxInt(usize), null, @alignOf(u8), 0); defer allocr.free(zon_txt); var ast = try std.zig.Ast.parse(allocr, zon_txt, .zon); defer ast.deinit(allocr); const MyStruct = struct // Field order is not important { const DatabaseSettings = struct { host: []const u8 = &.{}, // Since this is a slice of _const_ u8, // it will be addressing the string in ast.source port: u16 = 0, user: []u8 = &.{}, // Having a slice field requires passing a non-null allocator // to zonToStruct, and freeing `user` when we're done password: [20]u8 = [_]u8 {33} ** 20, // This array is filled with string/array elements up // to this field's capacity, or padded with 0 bytes, // if ZON string/array hasn't got enough elements }; const MyStruct = struct { ham: u32 = 0, eggs: u32 = 0 }; database: DatabaseSettings = .{}, decimal_separator: u8 = 0, months_in_year: u8 = 0, newline_char: u8 = 0, pi: f64 = 0.0, hello: []const u8 = &.{}, // Same as hello: []const u8 = undefined; hello.len = 0; unicode_char: u21 = 0, primes: [10]u8 = [_]u8 { 0 } ** 10, factorials: [10]u32 = [_]u32 { 0 } ** 10, slc_of_structs: []MyStruct = &.{}, slc_of_arrays: [][3]u32 = &.{}, slc_of_slices: [][]u32 = &.{}, }; var ms = MyStruct {}; // We MUST provide `allocr` if there are slices in ms, otherwise a null is fine. const report = try zgf.zonToStruct(&ms, ast, allocr); defer allocr.free(ms.database.user); // Must free `user` since it's a slice of non-const u8's. defer allocr.free(ms.slc_of_structs); defer allocr.free(report.slc_of_structs); // Must also free the slice of structs in `report` defer allocr.free(ms.slc_of_arrays); defer allocr.free(report.slc_of_arrays); defer { for (ms.slc_of_slices) |s| allocr.free(s); // Deallocate nested slices first allocr.free(ms.slc_of_slices); // THEN deallocate the outer slice allocr.free(report.slc_of_slices); // `report` contains a slice of `ZonFieldResult` enums } std.debug.print("Field = database.host value = {s}\n", .{ ms.database.host }); std.debug.print("Field = database.port value = {d}\n", .{ ms.database.port }); std.debug.print("Field = database.user value = {s}\n", .{ ms.database.user }); std.debug.print("Field = database.password value = {s}\n", .{ ms.database.password }); std.debug.print("Field = decimal_separator value = {c}\n", .{ ms.decimal_separator }); std.debug.print("Field = months_in_year value = {d}\n", .{ ms.months_in_year }); std.debug.print("Field = newline_char value = 0x{X:0>2}\n", .{ ms.newline_char }); std.debug.print("Field = pi value = {d}\n", .{ ms.pi }); std.debug.print("Field = hello value = {s}\n", .{ ms.hello }); std.debug.print("Field = unicode_char value = {u}\n", .{ ms.unicode_char }); std.debug.print("Field = primes value = [ ", .{}); for (ms.primes) |p| std.debug.print("{}, ", .{ p }); std.debug.print("]\n", .{}); std.debug.print("Field = factorials value = [ ", .{}); for (ms.factorials) |f| std.debug.print("{}, ", .{ f }); std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_structs value = [ ", .{}); for (ms.slc_of_structs) |s| std.debug.print("{{ ham = {}, eggs = {} }}, ", .{ s.ham, s.eggs }); std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_arrays value = [ ", .{}); for (ms.slc_of_arrays) |a| { std.debug.print("[ ", .{}); for (a) |e| std.debug.print("{}, ", .{ e }); std.debug.print("], ", .{}); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_slices value = [ ", .{}); for (ms.slc_of_slices) |s| { std.debug.print("[ ", .{}); for (s) |e| std.debug.print("{}, ", .{ e }); std.debug.print("], ", .{}); } std.debug.print("]\n\n", .{}); // `report` describes the state of corresponding fields in `ms` std.debug.print("Report =\n{s}\n", .{ std.json.fmt(report, .{ .whitespace = .indent_4 }) }); } ``` 2. Or you can fetch the values one by one using `pub fn getFieldVal`: ```zig const std = @import("std"); const zgf = @import("zon_get_fields.zig"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocr = gpa.allocator(); // `Ast.parse` requires a sentinel (0) terminated slice, so we pass 0 as the sentinel value (last arg) const zon_txt = try std.fs.cwd().readFileAllocOptions(allocr, "my.zon", std.math.maxInt(usize), null, @alignOf(u8), 0); defer allocr.free(zon_txt); var ast = try std.zig.Ast.parse(allocr, zon_txt, .zon); defer ast.deinit(allocr); var fld_name: []const u8 = "database.host"; const dbhost_str = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, dbhost_str }); fld_name = "database.port"; const dbport_u16 = try zgf.getFieldVal(u16, ast, fld_name); std.debug.print("Field = {s} value = {d}\n", .{ fld_name, dbport_u16 }); fld_name = "database.user"; const dbhost_user = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, dbhost_user }); fld_name = "database.password"; const dbhost_password = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, dbhost_password }); fld_name = "decimal_separator"; const dec_separ_u8 = try zgf.getFieldVal(u8, ast, fld_name); std.debug.print("Field = {s} value = {c}\n", .{ fld_name, dec_separ_u8 }); fld_name = "months_in_year"; const months_in_year_u8 = try zgf.getFieldVal(u8, ast, fld_name); std.debug.print("Field = {s} value = {d}\n", .{ fld_name, months_in_year_u8 }); fld_name = "newline_char"; const newline_char_u8 = try zgf.getFieldVal(u8, ast, fld_name); std.debug.print("Field = {s} value = 0x{X:0>2}\n", .{ fld_name, newline_char_u8 }); fld_name = "pi"; const pi_f64 = try zgf.getFieldVal(f64, ast, fld_name); std.debug.print("Field = {s} value = {d}\n", .{ fld_name, pi_f64 }); fld_name = "hello"; const hello_unicode_str = try zgf.getFieldVal([]const u8, ast, fld_name); std.debug.print("Field = {s} value = {s}\n", .{ fld_name, hello_unicode_str }); fld_name = "unicode_char"; const unicode_char_u21 = try zgf.getFieldVal(u21, ast, fld_name); std.debug.print("Field = {s} value = {u}\n", .{ fld_name, unicode_char_u21 }); std.debug.print("Field = primes value = [ ", .{}); var buf = [_]u8 { 0 } ** 22; for (0..5) |i| { const buf_slice = try std.fmt.bufPrint(&buf, "primes[{d}]", .{i}); const int_u8 = try zgf.getFieldVal(u8, ast, buf_slice); std.debug.print("{d}, ", .{ int_u8 }); } std.debug.print("]\n", .{}); std.debug.print("Field = factorials value = [ ", .{}); for (0..12) |i| { const buf_slice = try std.fmt.bufPrint(&buf, "factorials[{d}]", .{i}); const int_u32 = try zgf.getFieldVal(u32, ast, buf_slice); std.debug.print("{d}, ", .{ int_u32 }); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_structs value = [ ", .{}); for (0..2) |i| { const ham_buf_slice = try std.fmt.bufPrint(&buf, "slc_of_structs[{d}].ham", .{i}); const ham_int_u32 = try zgf.getFieldVal(u32, ast, ham_buf_slice); const eggs_buf_slice = try std.fmt.bufPrint(&buf, "slc_of_structs[{d}].eggs", .{i}); const eggs_int_u32 = zgf.getFieldVal(u32, ast, eggs_buf_slice) catch |err| { // We actually must check these things for all fields std.debug.print("{{ ham = {d}, eggs = {} }}, ", .{ ham_int_u32, err }); continue; }; std.debug.print("{{ ham = {d}, eggs = {d} }}, ", .{ ham_int_u32, eggs_int_u32 }); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_arrays value = [ ", .{}); for (0..2) |i| { std.debug.print("[ ", .{}); for (0..(3 - i)) |j| { const buf_slice = try std.fmt.bufPrint(&buf, "slc_of_arrays[{d}].[{d}]", .{i, j}); const int_u32 = try zgf.getFieldVal(u32, ast, buf_slice); std.debug.print("{d}, ", .{ int_u32 }); } std.debug.print("], ", .{}); } std.debug.print("]\n", .{}); std.debug.print("Field = slc_of_slices value = [ ", .{}); for (0..3) |i| { std.debug.print("[ ", .{}); for (0..(3 - i)) |j| { const buf_slice = try std.fmt.bufPrint(&buf, "slc_of_slices[{d}].[{d}]", .{i, j}); const int_u32 = try zgf.getFieldVal(u32, ast, buf_slice); std.debug.print("{d}, ", .{ int_u32 }); } std.debug.print("], ", .{}); } std.debug.print("]\n", .{}); } ``` ##### Report struct field types | Target struct field | Report struct field | | ---------------------------------------- | ------------------------------------------------------------ | | Primitive types (integers, floats, etc.) | ZonFieldResult enum. | | Array of elements of a primitive type | Array of ZonFieldResult enum elements. | | Array of arrays, structs or slices | Array of arrays, structs, slices, or ZonFieldResult enums (for target array of slices of primitive elements).<br />The type of report array element depends on the type of target array elements. | | Struct | Struct. Field types depend on target struct field types. | | Slice of elements of a primitive type | ZonFieldResult enum. | | Slice of arrays | Slice of arrays. Report array element type depends on the target array element type.<br />**Note**: (1) allocator must be provided (not null), since report slice has to be allocated; (2) caller owns the report struct and must deallocate this report slice. | | Slice of structs | Slice of structs. Report struct field types depend on the target struct field types.<br />**Note**: (1) allocator must be provided (not null), since report slice has to be allocated; (2) caller owns the report struct and must deallocate this report slice. | | Slice of slices | If target nested slices contain primitive type elements (integers, floats, etc.), then the report will contain a slice of ZonFieldResult enum elements.<br />If target nested slices contain structs, arrays or slices, then the report will contain a slice of matching structs, arrays or slices. See target struct field types 'struct', 'array' or 'slice' above.<br />**Note**: (1) allocator must be provided (not null), since report slice has to be allocated; (2) caller owns the report struct and must deallocate this report slice. |
https://avatars.githubusercontent.com/u/30970706?v=4
mpack-zig
theseyan/mpack-zig
2024-12-07T06:34:07Z
MessagePack bindings for Zig / msgpack.org[Zig]
main
0
12
0
12
https://api.github.com/repos/theseyan/mpack-zig/tags
MIT
[ "messagepack", "mpack", "zig", "zig-package" ]
132
false
2025-02-15T12:00:00Z
true
true
# MessagePack for Zig High-level APIs for [MPack](https://github.com/ludocode/mpack), a fast compliant encoder/decoder for the [MessagePack](https://msgpack.org/) binary format. Built and tested with Zig version `0.13.0`. > * Simple and easy to use > * Secure against untrusted data > * Lightweight, suitable for embedded > * [Extremely fast](https://github.com/ludocode/schemaless-benchmarks#speed---desktop-pc) ## Table of Contents - [Installation](#installation) - [Usage](#usage) - [API](#api) - [`Writer`](#writer) - [`Tree`](#tree) - [`TreeCursor`](#treecursor) - [`Reader`](#reader) - [`Cursor`](#cursor) - [Testing](#testing) - [Benchmarks](#benchmarks) ## Installation ```bash # replace {VERSION} with the latest release eg: v0.1.0 zig fetch https://github.com/theseyan/mpack-zig/archive/refs/tags/{VERSION}.tar.gz ``` Copy the hash generated and add mpack-zig to `build.zig.zon`: ```zig .{ .dependencies = .{ .mpack = .{ .url = "https://github.com/theseyan/mpack-zig/archive/refs/tags/{VERSION}.tar.gz", .hash = "{HASH}", }, }, } ``` ## API As there is currently no proper documentation, I recommend checking out the [tests](https://github.com/theseyan/mpack-zig/tree/main/test) to refer for examples. The source code is also well-commented. ### `Writer` > [!NOTE] > Zero-allocating API, all writes are flushed to user-provided buffer. The simplest way to incrementally write a MessagePack encoded message to a buffer. Writing should always start with `startMap` and end with `finishMap`. Values should always be written immediately after respective keys. After writing is done, call `deinit` to flush the written bytes to the underlying buffer. For pure-Zig code, it can be useful to directly encode a struct (or any supported type) using the `writeAny`/`writeAnyExplicit` methods. If you already have a parsed tree of nodes (using `Tree` API), and need to serialize a nested child `Map` node to it's own MessagePack buffer, use the `writeMapNode` method which accepts a `Tree.Node` (internally, it uses the `Writer` and `TreeCursor` APIs). It is also possible to write pre-encoded MessagePack object bytes as value to a larger object via `writeEncodedObject`. This is particularly useful when creating a larger structure that embeds smaller encoded structures, wihout having to decode and re-encode everything. ```zig const Writer = mpack.Writer; var buffer: [1024]u8 = undefined; var writer = Writer.init(&buffer); try writer.startMap(3); try writer.writeString("name"); // Key try writer.writeString("Sayan"); // Value try writer.writeString("age"); // Key try writer.writeUint32(100); // Value try writer.writeString("location"); // and so on... try writer.startMap(2); try writer.writeString("x"); try writer.writeDouble(123.535); try writer.writeString("y"); try writer.writeDouble(1234.1234); try writer.finishMap(); try writer.finishMap(); // Flush buffered writes to stream try writer.deinit(); ``` Results in an encoded message equivalent to the following JSON: ```json { "name": "Sayan", "age": 100, "location": { "x": 123.535, "y": 1234.1234 } } ``` The following `Writer` methods are available: - `writeAny` - Serialize any supported data type, including structs, value must be known at comptime. - `writeHashMap` - Write a `StringArrayHashMap` as a `Map` value. - `writeNumber` - Infer the type of number at comptime. - `writeNull` - `writeBool` - `writeInt8`, `writeInt16`, `writeInt32`, `writeInt64` - `writeUint8`, `writeUint16`, `writeUint32`, `writeUint64` - `writeFloat`, `writeDouble` - `writeNumberExplicit` - Infer the type of number at comptime, but value is runtime-known. - `writeString` - `writeBytes` - `writeExtension` - Read more on [MessagePack Extensions](https://github.com/msgpack/msgpack/blob/master/spec.md#extension-types). - `startArray` - Start writing an array. `count` must be known upfront. - `startMap` - Start writing a map. `length` must be known upfront. - `finishArray`, `finishMap` - Close the last opened array/map. - `writeAnyExplicit` - When value is unknown at comptime, but type is known. - `writeMapNode` - Encode a parsed `NodeType.Map` node back to binary. - `writeEncodedObject` - Write a pre-encoded MessagePack object as value. - `stat` - Returns information about underlying buffer. ### `Tree` > [!NOTE] > By default, nodes of the parsed tree are allocated on the heap as required automatically. > To avoid dynamic allocations, you can create a re-useable `Pool` with pre-allocated nodes. > Strings/Binary/Extension values are zero-copy and point to the original buffer, hence are only valid as long as the buffer lives. Tree-based reader, can be used to read data explicitly and with random access, get a item by path (eg. `parents.mother.children[0].name`), de-serialize a message to a Zig struct, or traverse the tree using `TreeCursor`. ```zig pub const Tree = struct { pub fn init(allocator: std.mem.Allocator, data: []const u8, pool: ?Pool) !Tree pub fn deinit(self: *Tree) !void pub fn getByPath(self: *Tree, path: []const u8) !Node pub fn readAny(self: *Tree, comptime T: type) !struct { value: T, arena: std.heap.ArenaAllocator } pub fn cursor(self: *Tree) !Cursor /// A pre-allocated pool of nodes to avoid dynamic allocations in hot paths. pub const Pool = struct { /// Creates a pool of pre-allocated nodes for use with `init`. /// This helps avoid slow dynamic allocations in hot paths. pub fn init(allocator: std.mem.Allocator, size: usize) !Pool /// Destroys the pool and frees the underlying memory. pub fn deinit(self: *Pool) void }; }; pub const Node = { pub const NodeType = enum { Null, Bool, Int, Uint, Float, Double, String, Bytes, Array, Map, Extension, Missing }; pub fn getType(self: Node) NodeType pub fn isValid(self: Node) bool pub fn isNull(self: Node) bool pub fn getBool(self: Node) !bool pub fn getInt(self: Node) !i64 pub fn getUint(self: Node) !u64 pub fn getFloat(self: Node) !f32 pub fn getDouble(self: Node) !f64 pub fn getString(self: Node) ![]const u8 pub fn getBytes(self: Node) ![]const u8 pub fn getExtensionType(self: Node) !i8 pub fn getExtensionBytes(self: Node) ![]const u8 pub fn getArrayLength(self: Node) !u32 pub fn getArrayItem(self: Node, index: u32) !Node pub fn getMapLength(self: Node) !u32 pub fn getMapKeyAt(self: Node, index: u32) !Node pub fn getMapValueAt(self: Node, index: u32) !Node pub fn getMapKey(self: Node, key: []const u8) !Node }; ``` ### `TreeCursor` A `TreeCursor` can be used to traverse through a tree's nodes in order. ```zig var cursor = try tree.cursor(); // ... or a cursor starting from any nested Map node var cursor = try TreeCursor.init(nested_map_node); ``` It is non-allocating, and returns items one-by-one via the `next` method. When all items are exhausted, `null` is returned. ```zig pub const TreeCursor = struct { pub const MAX_STACK_DEPTH = 512; pub const Event = union(enum) { // Value events null, bool: bool, int: i64, uint: u64, float: f32, double: f64, string: []const u8, bytes: []const u8, // Container events mapStart: u32, // Count of map mapEnd, arrayStart: u32, // Length of array arrayEnd, // Extensions extension: struct { type: i8, data: []const u8, }, }; pub fn init(root: Node) TreeCursor pub fn next(self: *TreeCursor) !?Event }; ``` ### `Reader` > [!NOTE] > Simple, zero-allocating, single-pass reader. > Strings/Binary/Extension values are "views" into the original buffer, and hence only valid as long as the buffer lives. Simple primitive reader API that reads tags from the encoded buffer one-by-one. This is the fastest way to traverse through the message but cannot go backwards nor provide random-access. Each read tag advances the reader automatically. Use the `Tree` API if elements are to be accessed multiple times or random-access is required. Otherwise, it is recommended to use the traversing `Cursor` API instead of using this directly. ```zig pub const Reader = struct { pub const TagType = enum { Null, Bool, Int, Uint, Float, Double, String, Bytes, Array, Map, }; pub const Tag = struct { pub fn getType(self: *Tag) TagType, pub fn isNull(self: *Tag) bool, pub fn getBool(self: *Tag) bool, pub fn getInt(self: *Tag) i64, pub fn getUint(self: *Tag) u64, pub fn getFloat(self: *Tag) f32, pub fn getDouble(self: *Tag) f64, pub fn getStringValue(self: *Tag, reader: *Reader) ![]const u8, pub fn getBinaryBytes(self: *Tag, reader: *Reader) ![]const u8, pub fn getExtensionBytes(self: *Tag, reader: *Reader) ![]const u8 pub fn getStringLength(self: *Tag) u32, pub fn getArrayLength(self: *Tag) u32, pub fn getMapLength(self: *Tag) u32, pub fn getBinLength(self: *Tag) u32, pub fn getExtensionLength(self: *Tag) u32, pub fn getExtensionType(self: *Tag) i8 } pub fn init(data: []const u8) Reader pub fn readTag(self: *Reader) !Tag pub fn finishArray(self: *Reader) void pub fn finishMap(self: *Reader) void pub fn cursor(self: *Reader) Cursor pub fn deinit(self: *Reader) !void }; ``` ### `Cursor` Cursor based on the `Reader` API. Faster than `TreeCursor` but subject to the same limitations as `Reader`. The API is very similar to `TreeCursor`. ```zig pub const Cursor = struct { pub const MAX_STACK_DEPTH = 512; pub const Event = union(enum) { // Value events null, bool: bool, int: i64, uint: u64, float: f32, double: f64, string: []const u8, bytes: []const u8, // Container events mapStart: u32, // Count of map mapEnd, arrayStart: u32, // Length of array arrayEnd, // Extensions extension: struct { type: i8, data: []const u8, }, }; pub fn init(reader: *Reader) Cursor pub fn next(self: *Cursor) !?Event }; ``` ## Testing Unit tests are present in the `test/` directory. Currently, the tests are limited and do not cover everything. PRs to improve the quality of these tests are welcome. ```bash zig build test ``` ## Benchmarks Benchmarks are present in `benchmark/` and use the [zBench](https://github.com/hendriknielaender/zBench) library. Run the benchmarks: ```bash zig build bench ``` Results on my personal PC (Intel i5-11400H, Debian, 32 GiB RAM): ``` benchmark runs total time time/run (avg Β± Οƒ) (min ... max) p75 p99 p995 ----------------------------------------------------------------------------------------------------------------------------- explicit write x 100 65535 625.421ms 9.543us Β± 1.091us (8.976us ... 82.607us) 9.808us 13.675us 15.594us serialize struct x 100 65535 585.208ms 8.929us Β± 1.517us (7.551us ... 52.956us) 9.685us 12.922us 13.962us tree: parse 65535 10.195ms 155ns Β± 93ns (136ns ... 19.05us) 158ns 186ns 188ns tree: parse w/ pool 65535 10.901ms 166ns Β± 1.222us (129ns ... 211.649us) 166ns 247ns 248ns tree: read by path 65535 23.742ms 362ns Β± 183ns (324ns ... 31.989us) 367ns 413ns 526ns tree: cursor iterate 65535 23.694ms 361ns Β± 234ns (328ns ... 35.133us) 363ns 410ns 421ns reader: cursor iterate 65535 11.166ms 170ns Β± 41ns (158ns ... 5.897us) 175ns 187ns 190ns ```
https://avatars.githubusercontent.com/u/6881800?v=4
zig-recover
dimdin/zig-recover
2024-02-05T15:36:56Z
zig panic recover
main
0
12
0
12
https://api.github.com/repos/dimdin/zig-recover/tags
MIT
[ "zig", "zig-library", "zig-package", "ziglang" ]
18
false
2025-03-14T08:40:13Z
true
true
Zig Panic Recover ================= Recover calls a function and regains control of the calling thread when the function panics or behaves undefined. Recover is licensed under the terms of the [MIT License](LICENSE). How to use ---------- Recover `call`, calls `function` with `args`, if the function does not panic, will return the called function's return value. If the function panics, will return `error.Panic`. ``` const recover = @import("recover"); try recover.call(function, args); ``` Prerequisites ------------- 1. Enabled runtime safety checks, such as unreachable, index out of bounds, overflow, division by zero, incorrect pointer alignment, etc. 2. In the root source file define panic as recover.panic or override the default panic handler and call recover `panicked`. ``` pub const panic = recover.panic; ``` 3. Excluding Windows, linking to C standard library is required. Example ------- Returns error.Panic because function division panics with runtime error "division by zero". ``` fn division(num: u32, den: u32) u32 { return num / den; } try recover.call(division, .{1, 0}); ``` Testing ------- For recover to work for testing, you need a custom test runner with a panic handler: ``` pub const panic = @import("recover").panic; ``` To test that `foo(0)` panics: ``` test "foo(0) panics" { const err = recover.call(foo, .{0}); std.testing.expectError(error.Panic, err). } ``` Proper Usage ------------ - Recover is useful for testing panic and undefined behavior runtime safety checks. - It is **not** recommended to use recover as a general exception mechanism.
https://avatars.githubusercontent.com/u/24609692?v=4
webgpu-wasm-zig
seyhajin/webgpu-wasm-zig
2024-01-19T17:42:44Z
πŸš€ A minimal WebGPU example written in Zig, compiled to WebAssembly (wasm). πŸ› οΈ Ideal for experimenting and preparing for native development without install dependencies (dawn, wgpu-rs).
master
0
12
1
12
https://api.github.com/repos/seyhajin/webgpu-wasm-zig/tags
MIT
[ "3d-graphics", "emscripten", "wasm", "webassembly", "webgpu", "zig", "zig-package" ]
205
false
2025-03-04T14:32:27Z
true
false
<div align="center"> <h1>webgpu-wasm-zig</h1> <p>A minimal WebGPU example written in Zig, compiled to WebAssembly (wasm).</p> <img src="screen.png"/> ![πŸ‘οΈ](https://views.whatilearened.today/views/github/seyhajin/webgpu-wasm-zig.svg) </div> ## Getting started ### Clone ```bash git clone https://github.com/seyhajin/webgpu-wasm-zig.git ``` Alternatively, download [zip](https://github.com/seyhajin/webgpu-wasm-zig/archive/refs/heads/master.zip) from Github repository and extract wherever you want. ### Build Build the example with `zig build` command, which will generate 3 new files (`.html`, `.js`, `.wasm`). #### Command ``` zig build --sysroot [path/to/emsdk]/upstream/emscripten/cache/sysroot ``` Example with Emscripten installed with Homebrew (`brew install emscripten`, v3.1.51) on macOS : ``` zig build --sysroot /usr/local/Cellar/emscripten/3.1.51/libexec/cache/sysroot ``` > [!NOTE] > `build.zig` is preconfigured to build to `wasm32-emscripten` target only. > [!CAUTION] > Must provide Emscripten sysroot via `--sysroot` argument. ### Run Launch a web server to run example before open it to WebGPU compatible web browser (Chrome Canary, Brave Nightly, etc.). e.g. : launch `python3 -m http.server` and open web browser to `localhost:8000`. > [!TIP] > Use [Live Server](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) extension in Visual Studio Code to open the HTML file. This extension will update automatically page in real-time when you rebuild the example. ## Prerequisites * [zig](https://www.zig.org/download), works with Zig 0.12+dev version * [emscripten](https://emscripten.org), version 3.1+ * git (optional) * python3 (optional)
https://avatars.githubusercontent.com/u/192897928?v=4
zig-luajit-build
sackosoft/zig-luajit-build
2025-01-12T21:13:06Z
A package to compile LuaJIT using the Zig toolchain. Install to access the LuaJIT C API. For Zig API see https://github.com/sackosoft/zig-luajit
main
1
12
2
12
https://api.github.com/repos/sackosoft/zig-luajit-build/tags
MIT
[ "luajit", "zig", "zig-package" ]
51
false
2025-03-12T00:54:23Z
true
true
<div align="center"> # zig-luajit-build Used to compile and link the native [LuaJIT][LUAJIT] C API into Zig ⚑ applications. ![Ubuntu Build Status Badge](https://img.shields.io/github/actions/workflow/status/sackosoft/zig-luajit-build/build-ubuntu.yml?label=Linux%20Build) ![Windows Build Status Badge](https://img.shields.io/github/actions/workflow/status/sackosoft/zig-luajit-build/build-windows.yml?label=Windows%20Build) ![GitHub License](https://img.shields.io/github/license/sackosoft/zig-luajit-build) <!-- TODO: Capture attention with a visualization, diagram, demo or other visual placeholder here. ![Placeholder]() --> </div> LuaJIT is a fork from the [Lua][LUA] project -- "Lua is a powerful, efficient, lightweight, embeddable scripting language." [LUAJIT]: https://luajit.org/index.html [LUA]: https://www.lua.org/about.html ## Are you looking for a Zig interface to the LuaJIT C API? This package does not contain Zig language bindings to the C API. This package only handles building and linking the LuaJIT library into a Zig application. If you're looking to run Lua on LuaJIT in your Zig application, you're probably looking for one of these projects: 1. [sackosoft/zig-luajit](https://github.com/sackosoft/zig-luajit) **- Zig language bindings LuaJIT.** - Preferred solution when only one Lua runtime (LuaJIT) is required; built on top of `zig-luajit-build`. 2. [natecraddock/ziglua](https://github.com/natecraddock/ziglua) - Zig language bindings for Lua 5.x and Luau and LuaJIT. - More mature project, maintained by Nathan Craddock. Has some quirks as a result of supporting all Lua runtimes with the same Zig API. ## Zig Version The `main` branch targets Zig's `master` (nightly) deployment (last tested with `0.14.0-dev.3460+6d29ef0ba`). ## Installation & Usage Install using `zig fetch`. This will add a `luajit_build` dependency to your `build.zig.zon` file. ```bash zig fetch --save=luajit_build git+https://github.com/sackosoft/zig-luajit-build ``` Next, in order for your code to import the LuaJIT C API, you'll need to update your `build.zig` to: 1. get a reference to the `luajit-build` dependency which was added by zig fetch. 2. get a reference to the `luajit-build` module, containing the native LuaJIT C API. 3. attach that module as an import to your library or executable, so that your code can reference the C API. ```zig // (1) Reference the dependency const luajit_build_dep = b.dependency("luajit_build", .{ .target = target, .optimize = optimize, .link_as = .static // Or .dynamic to link as a shared library }); // (2) Reference the module containing the LuaJIT C API. const luajit_build = luajit_build_dep.module("luajit-build"); // Set up your library or executable const lib = // ... const exe = // ... // (3) Add the module as an import, available via `@import("c")`, or any other name you choose here. lib.root_module.addImport("c", luajit_build); // Or exe.root_module.addImport("c", luajit_build); ``` Now the code in your library or executable can import and access the LuaJIT C API! ```zig const c = @import("c"); // Access LuaJIT functions via 'c' pub fn main() !void { const state: ?*c.lua_State = c.luaL_newstate(); if (state) |L| { c.luaL_openlibs(L); c.luaL_dostring( L, \\ print("Hello, world!") ); } } ``` ## Configuration This package supports one configuration option, shown in the example above. - `link_as`: Controls how LuaJIT is linked - `.static`: Build and link LuaJIT as a static library (default). - `.dynamic`: Build and link LuaJIT as a shared library. ## License Some files in this repository were copied or adapted from the [natecraddock/ziglua](https://github.com/natecraddock/ziglua) project. Any files copied or adapted from that project have a comment describing the attribution at the top. Such files are shared by Nathan Craddock under the MIT License in [ziglua/license](https://github.com/natecraddock/ziglua/blob/90dab7e72173709353dcaaa6d911bed7655c030d/license). All other files are released under the MIT License in [zig-luajit-build/LICENSE](./LICENSE).
https://avatars.githubusercontent.com/u/766758?v=4
libgeos.zig
guidorice/libgeos.zig
2022-01-13T00:20:50Z
Zig bindings for the GEOS C library; compile libgeos in your build.zig.
main
1
12
0
12
https://api.github.com/repos/guidorice/libgeos.zig/tags
NOASSERTION
[ "c", "computational-geometry", "geojson", "geospatial", "gis", "libgeos", "zig", "zig-package", "zig-programming-language", "ziglang" ]
73
false
2025-03-13T04:54:24Z
true
false
# libgeos.zig [Zig](https://ziglang.org) bindings for the [GEOS C library (libgeos)](https://libgeos.org/) > GEOS (Geometry Engine, Open Source) is a C/C++ library for spatial computational geometry of the sort generally used by β€œgeographic information systems” software. GEOS is a core dependency of PostGIS, QGIS, GDAL, and Shapely. ## GEOS version `3.10.2-CAPI-1.16.0` ## Zig version * `0.9.1`, `0.10.0-dev` ## Build Requires only `zig`. Don't forget to clone/init the submodule! ```shell git clone --recurse-submodules https://github.com/guidorice/libgeos.zig.git cd libgeos.zig/ zig build ``` ## Tests ```shell zig build test ``` ## Examples ```shell $ zig build --help $ zig build run-ex1 Geometry A: POLYGON((0 0, 10 0, 10 10, 0 10, 0 0)) Geometry B: POLYGON((5 5, 15 5, 15 15, 5 15, 5 5)) Intersection(A, B): POLYGON ((10 10, 10 5, 5 5, 5 10, 10 10)) ``` ## Known Issues * blocker: The libgeos library uses C++ `std::runtime_error`, which is not currently captured by the Zig wrapper code. As a result, there is no way to recover from some error conditions, for example, failing to parse some WKT formatted string. [see issue #9](https://github.com/guidorice/libgeos.zig/issues/9) ## Roadmap * [x] Minimal build.zig. Builds libgeos entirely using Zig compiler and build system. * [x] Create example exe using this package as a Zig library. * [x] Port libgeos C examples to Zig (from src/geos/examples) * [x] [Ex 1](src/examples/ex1.zig) Reads two WKT representations and calculates the intersection, prints it out, and cleans up. * [x] [Ex 1 (threadsafe)](src/examples/ex1_threadsafe.zig) * [x] [Ex 2](src/examples/ex2.zig) Reads one geometry and does high-performance prepared geometry operations to place "random" points inside it. * [x] [Ex 3](src/examples/ex3.zig) Build a spatial index and search it for a nearest pair. * [ ] Solution for `std:runtime_error` conditions (see known issues) * [ ] New Zig idiomatic wrapper for libgeos C API? Alternatively: port to Zig-native. * [ ] New GeoJSON reader/writer which speaks libgeos types and full support for Feature properties. Reference: [GEOS GeoJSON support notes here.](https://libgeos.org/specifications/geojson/) * [ ] New Zig projects which utilize these Geospatial or Geometric primitives. ## Notes See also [vendor/geos/README](src/vendor/geos/README.md) for how libgeos is updated within this repo.
https://avatars.githubusercontent.com/u/107519028?v=4
learn-zig
better-zig/learn-zig
2022-06-15T00:09:56Z
zig quick learn
main
0
12
1
12
https://api.github.com/repos/better-zig/learn-zig/tags
Apache-2.0
[ "ffi", "ffi-bindings", "zig", "zig-package", "ziglang" ]
49
false
2025-01-01T02:47:27Z
false
false
# learn-zig - learning zig language > related: - βœ… https://github.com/better-zig/ziglings-solutions - zig 语法练习 ## Features: - [basic](./packages/basic/): zig basic example - [toolbox](./packages/toolbox/) : zig toolbox - [zig-utils](./packages/zig-utils/) : zig utils > 与 C θ―­θ¨€δΊ’ζ“δ½œζ€§: - βœ… [c](./packages/c/src/main.c): 使用 zig 作为 C 编译器, η›΄ζŽ₯ηΌ–θ―‘ C 代码 - `cd packages/c; task run` - or `task c:run` - βœ… [zig-use-c](./packages/zig-use-c/src/main.zig): zig 调用 C 代码 - βœ… [zig-to-c](./packages/zig-to-c/readme.md): zig ηΌ–θ―‘ζˆ C Lib(C ABI), 基于 `FFI`, 蒫兢他语言(如 dart)调用 ## QuickStart: > requirements: - zig: `0.10.0-dev.2617+47c4d4450` - zigmod: `zigmod r80 macos aarch64 none` > install: ```ruby # install zig: task install:zig:dev -> % zig version 0.10.0-dev.2617+47c4d4450 # macos + m1 cpu: task install:zigmod:m1 # or macos + intel cpu task install:zigmod:intel ``` > run: ```ruby task basic:run ``` > test: ```ruby task basic:test ``` ## Structure: ```ruby -> % tree ./packages/ -L 2 ./packages/ β”œβ”€β”€ basic β”‚ β”œβ”€β”€ Taskfile.yml β”‚ β”œβ”€β”€ build.zig β”‚ β”œβ”€β”€ src β”‚ β”œβ”€β”€ zig-cache β”‚ β”œβ”€β”€ zig-out β”‚ └── zigmod.yml β”œβ”€β”€ toolbox β”‚ β”œβ”€β”€ Taskfile.yml β”‚ β”œβ”€β”€ build.zig β”‚ β”œβ”€β”€ src β”‚ └── zigmod.yml └── zig-utils β”œβ”€β”€ Taskfile.yml β”œβ”€β”€ build.zig β”œβ”€β”€ src β”œβ”€β”€ zig-cache └── zigmod.yml ```
https://avatars.githubusercontent.com/u/37453713?v=4
zigvale
ominitay/zigvale
2021-08-22T12:15:04Z
A Zig implementation of the stivale2 boot protocol
main
1
12
0
12
https://api.github.com/repos/ominitay/zigvale/tags
MIT
[ "boot", "bootloader", "hacktoberfest", "kernel", "osdev", "stivale", "stivale2", "zig", "zig-package", "ziglang", "zigvale" ]
86
false
2023-10-28T13:51:54Z
true
false
# Zigvale Zigvale is a Zig implementation of the stivale2 boot protocol to be used both in kernels and bootloaders. The specification, along with C header files, may be found [here](https://github.com/stivale/stivale). ## Example Visit [zigvale-barebones](https://github.com/ominitay/zigvale-barebones) for a bare-bones kernel demonstrating how to use Zigvale. ## Add to your project Zigvale is available on [aquila](https://aquila.red/1/Ominitay/zigvale), [zpm](https://zig.pm/#/package/zigvale), and [astrolabe](https://astrolabe.pm/#/package/ominitay/zigvale/0.7.3). ### Gyro `gyro add ominitay/zigvale` ### Zigmod ###### Aquila `zigmod aq add 1/Ominitay/zigvale` ###### ZPM `zigmod zpm add zigvale` ### ZKG `zkg add zigvale` ### Git ###### Submodule `git submodule add https://github.com/ominitay/zigvale zigvale` ###### Clone `git clone https://github.com/ominitay/zigvale` ## Documentation To generate documentation, run `zig build docs` Zig's documentation generator is experimental and incomplete. When documentation generation has improved somewhat, I will host the documentation. In the meantime, you may both read the comments made manually, and read the documentation in the [stivale repository](https://github.com/stivale/stivale).
https://avatars.githubusercontent.com/u/206480?v=4
otp.zig
karlseguin/otp.zig
2024-11-08T01:47:11Z
An TOTP library for Zig
master
0
12
0
12
https://api.github.com/repos/karlseguin/otp.zig/tags
MIT
[ "zig", "zig-library", "zig-package" ]
13
false
2025-03-05T04:35:05Z
true
false
# OTP for Zig Currently only supports TOTP with SHA1 or SHA256. ```zig const std = @import("std"); const otp = @import("otp"); pub fn main() !void { // You would store secret in the DB with the user var secret: [20]u8 = undefined; otp.generateSecret(&secret); // base32 encode the secret // (for a 20-byte secret, you need a 32 byte buffer) var code_buf: [32]u8 = undefined; std.debug.print("{s}\n", .{otp.bufEncodeSecret(&code_buf, &secret)}); // verify a user-supplied totp const user_topt = "123456"; if (otp.totp.verify(user_topt, &secret, .{})) { std.debug.print("GOOD!\n", .{}); } } ``` ## Install 1) Add otp.zig as a dependency in your `build.zig.zon`: ```bash zig fetch --save git+https://github.com/karlseguin/otp.zig#master ``` 2) In your `build.zig`, add the `otp` module as a dependency you your program: ```zig const otp = b.dependency("otp", .{ .target = target, .optimize = optimize, }); // the executable from your call to b.addExecutable(...) exe.root_module.addImport("otp", otp.module("otp")); ``` ## Secrets The first thing to do is to generate a secret: ```zig var secret: [20]u8 = undefined; otp.generateSecret(&secret); ``` You can pick any size, but 20 bytes, as above, is recommended. You should store the secret along with a user. `generateSecret` fills the supplied slice with raw bytes. You can base32 encode the secret using: ```zig // write the base32 encoded secret to the writer try otp.encodeSecret(writer, secret); // OR // write the base32 encoded secret into "encoded_buf" var encoded_buf: [32]u8 = undefined; const encoded = otp.bufEncodeSecret(&encoded_buf, secret); ``` When using `bufEncodedSecret`, the supplied buffer *must* be large enough to hold the encoded value. You can use `const len = otp.encodeSecretLen(secret.len)` to get the required length. ### TOTP #### Config Passed to various totp functions: * `interval: u32` - How long a code should be valid for in seconds. Defaults to 30 * `digits: u8` - Number of digits. Defaults to 6. * `algorithm: otp.totp.Algorithm` - The hash algorithm to use. Defaults to `.sha1` (other supported value is `.sha256`) #### otp.totp.generate(buf: []u8, secret: []const u8, config: Config) []u8 Generate a new TOTP code for the current time. `buf` must be at least `config.digits`. A slice of `buf[0..config.digits]` is returned. #### otp.totp.generateAt(buf: []u8, secret: []const u8, timestamp: i64, config: Config) []u8 Generate a new TOTP code for the specified time. `buf` must be at least `config.digits`. A slice of `buf[0..config.digits]` is returned. #### otp.totp.verify(code: []const u8, secret: []const u8, config: Config) bool Verifies that the given code is valid for the current time. #### otp.totp.verifyAt(code: []const u8, secret: []const u8, timestamp: i64, config: Config) bool Verifies that the given code is valid for the given time. #### Example ```zig var code_buf: [6]u8 = undefined; const code = otp.totp.generate(&code, &secret, .{}); std.debug.assert(otp.totp.verify(code, &secret, .{}) == true); ``` Which is a shorthand for: ```zig var code_buf: [6]u8 = undefined; const now = std.time.timestamp() const config = otp.TOTP.Config{ .digits = 6, .interval = 30, .algorithm = .sha1, }; const code = otp.totp.generateAt(&code, &secret, now, config); std.debug.assert(otp.totp.verifyAt(code, &secret, now config) == true); ``` When generating a code, the buffer, `code_buf` above, must be at least `config.digits` long. #### URL You can generate a URL (which is what would be put in a QR code) using either the `url` or `bufUrl` functions. These functions take their own type of config object: * `account: []const u8` - The account name. Required * `issuer: ?[]const u8` - Optional issuer name. Defaults to `null` * `config: Config` - The TOTP configuration. Default to `.{}` ##### bufUrl(buf: []u8, secret: []const u8, uc: URLConfig) ![]u8 Writes the URL into `buf`. Returns an error if `buf` isn't large enough. Returns the URL on success. ##### url(writer: anytype, secret: []const u8, uc: URLConfig) !void Writes the URL using the writer. ```zig // min length of buf will largely depend on the account name, issuer name and length of secret. var buf: [200]u8 = undefined; const url = try bufUrl(&buf, secret, .{.account = "Leto", .issuer = "spice.gov", .config = .{.digits = 8} }); ```
https://avatars.githubusercontent.com/u/499599?v=4
zcmd.zig
liyu1981/zcmd.zig
2024-01-14T08:57:24Z
zcmd is a single file lib to replace zig's std.childProcess.run with the ability of running pipeline like bash..
main
1
12
1
12
https://api.github.com/repos/liyu1981/zcmd.zig/tags
MIT
[ "zig", "zig-package" ]
10,022
false
2025-01-09T14:45:10Z
true
true
# zcmd.zig `zcmd` is a single file lib (`zcmd.zig`) to replace zig's `std.childProcess.run`. It has almost identical API like `std.childProcess.run`, but with the ability of running pipeline like `bash`. Example like execution of single command (replacement of zig's `std.childProcess.run`) ```zig const result = try Zcmd.run(.{ .allocator = allocator, .commands = &[_][]const []const u8{ &.{ "uname", "-a" }, }, }); ``` the differences to `std.childProcess.run` is it will take `commands` instead of single `command`. It can run a `bash` like pipeline like follows (_to recursively find and list the latest modified files in a directory with subdirectories and times_) ```zig const result = try Zcmd.run(.{ .allocator = allocator, .commands = &[_][]const []const u8{ &.{ "find", ".", "-type", "f", "-exec", "stat", "-f", "'%m %N'", "{}", ";" }, &.{ "sort", "-nr" }, &.{ "head", "-1" }, }, }); ``` It can also accept an input from outside as stdin to command or command pipeline, like follows ```zig const f = try std.fs.cwd().openFile("tests/big_input.txt", .{}); defer f.close(); const content = try f.readToEndAlloc(allocator, MAX_OUTPUT); defer allocator.free(content); const result = try Zcmd.run(.{ .allocator = allocator, .commands = &[_][]const []const u8{ &.{"cat"}, &.{ "wc", "-lw" }, }, .stdin_input = content, }); ``` When there is something failed inside pipeline, we will report back `stdout` and `stderr` just like `bash`, like below example ```zig const result = try Zcmd.run(.{ .allocator = allocator, .commands = &[_][]const []const u8{ &.{ "find", "nonexist" }, &.{ "wc", "-lw" }, }, }); defer result.deinit(); try testing.expectEqualSlices( u8, result.stdout.?, " 0 0\n", ); try testing.expectEqualSlices( u8, result.stderr.?, "find: nonexist: No such file or directory\n", ); ``` Please check [example/zcmd_app](https://github.com/liyu1981/zcmd.zig/tree/main/example/zcmd_app) for an example on how to use `zcmd.zig`. ### use `zcmd.zig` in `build.zig` Originally `zcmd.zig` is functions I wrote in `build.zig` to auto generating files with commands, so it is important that can use this in `build.zig`. So `zcmd.zig` exposed itself for `build.zig` too. To use that we will need to normally introduce `zcmd.zig` to `build.zig.zon` (see Usage below). Then in your `build.zig`, do following to use it ```zig // when import in build.zig, the zcmd is exposed in nested const zcmd const zcmd = @import("zcmd").zcmd; // then next can use zcmd.run as above ``` Please check [example/zcmd_build_app](https://github.com/liyu1981/zcmd.zig/tree/main/example/zcmd_build_app) for detail version how to use in this way. ## Usage ### through Zig Package Manager use following bash in your project folder (with `build.zig.zon`) ``` zig fetch --save https://github.com/liyu1981/zcmd.zig/archive/refs/tags/v0.2.2.tar.gz ``` you can change the version `v0.1.0` to other version if there are in [release](https://github.com/liyu1981/zcmd.zig/releases) page. ### or simply just copy `zcmd.zig` file to your project It is a single file lib with no dependencies! ## Zig Docs Zig docs is hosted in github pages at: [https://liyu1981.github.io/zcmd.zig/](https://liyu1981.github.io/zcmd.zig/), please go there to find what apis `zcmd.zig` provides. ## Coverage `zcmd.zig` is rigorously tested. Run unit tests at repo checkout root folder with `zig test src/zcmd.zig`. For coverage test, as `kcov` is working in a way of 'debug every line and record', it can not work with `zcmd` tests. `zcmd` tests will fork many sub processes and if one of them be stopped the whole pipeline hangs. I am still in searching of what's the best method to cover.
https://avatars.githubusercontent.com/u/6756180?v=4
winpthreads-zigbuild
kassane/winpthreads-zigbuild
2023-03-28T13:48:04Z
The Winpthreads Library for Zig toolchain
main
0
12
4
12
https://api.github.com/repos/kassane/winpthreads-zigbuild/tags
NOASSERTION
[ "mingw", "mingw-w64", "windows", "zig-package" ]
725
false
2025-03-17T18:59:48Z
true
true
The Winpthreads Library for Zig ----------------------- [![build](https://github.com/kassane/winpthreads-zigbuild/actions/workflows/build.yml/badge.svg)](https://github.com/kassane/winpthreads-zigbuild/actions/workflows/build.yml) Based on: https://github.com/ziglang/zig/issues/10989 solved: https://github.com/ziglang/zig/pull/22156 (Zig v0.14.0) Zig v0.6 ~ v0.13.0 toolchain/MinGW don't includes `winpthreads`. This library provides POSIX threading APIs for mingw-w64. For maximum compatibility, winpthreads headers expose APIs without the `dllimport` attribute by default. If your program is linked against the DLL, you may define the `WINPTHREADS_USE_DLLIMPORT` macro to add the `dllimport` attribute to all APIs, which makes function calls to them a bit more efficient. How to use --------- **Requires:** zig v0.12.0 or v0.13.0 * Make a project: ```bash mkdir your-project-folder cd your-project-folder # generate both (exe and lib template w/ build.zig & build.zig.zon) zig init # get latest version (commit-tag or branch) zig fetch git+https://github.com/kassane/winpthreads-zigbuild#main ``` * Add on current project: ```bash # (w/ build.zig & build.zig.zon) cd your-project-folder # get latest version zig fetch git+https://github.com/kassane/winpthreads-zigbuild#main # or #commit-tag ``` **Warn:** `main` branch changes commit hashes.
https://avatars.githubusercontent.com/u/22038970?v=4
bit-string
paoda/bit-string
2023-08-17T03:16:24Z
No Description
main
0
12
0
12
https://api.github.com/repos/paoda/bit-string/tags
MIT
[ "zig-library", "zig-package" ]
17
false
2024-07-03T23:06:13Z
true
true
# Bit String A library to check and extract values from integers based on a "bit string". Primarily intended for (my) emulator instruction decoding, but maybe someone else can find a use for it? ## Example ```zig const std = @import("std"); test "doc test" { const value: u8 = 0b10001011; try std.testing.expectEqual(true, match("1000_1011", value)); try std.testing.expectEqual(false, match("11111011", value)); try std.testing.expectEqual(true, match("1---1011", value)); { const ret = extract("1000aaaa", value); try std.testing.expectEqual(@as(u4, 0b1011), ret.a); } { const ret = extract("1aaa1aaa", value); try std.testing.expectEqual(@as(u6, 0b000011), ret.a); } { const ret = extract("1---abcd", value); try std.testing.expectEqual(@as(u3, 0b1), ret.a); try std.testing.expectEqual(@as(u3, 0b0), ret.b); try std.testing.expectEqual(@as(u3, 0b1), ret.c); try std.testing.expectEqual(@as(u3, 0b1), ret.d); } } ``` ## Syntax | Token | Meaning | Description | ------- | --------- | ----------- | `0` | Clear bit | In the equivalent position, the value's bit must be cleared. | `1` | Set bit | In the equivalent position, the value's bit must be set. | `a..=z` | Variable | Given the 4-bit bit string, `"1aa0"`, the value `0b1010` would produce the variable `a` with the value `0b01` | `-` | Ignored | In the equivalent position, the value's bit does not matter. | `_` | Ignored* | Underscores are completely ignored during parsing, use to make bit strings easier to read e.g. `1111_1111` ## Notes - This library does the majority of it's work at `comptime`. Due to this, you cannot create strings to match against at runtime. - Variables do not have to be "sequential". This means the 5-bit bit string `"1aa0a"` with the value `0b10101` will produce the variable `a` with the value `0b011`.
https://avatars.githubusercontent.com/u/20110944?v=4
zeptolibc
ringtailsoftware/zeptolibc
2024-12-05T11:55:40Z
Some basic libc functions for working with C code in Zig
main
0
11
0
11
https://api.github.com/repos/ringtailsoftware/zeptolibc/tags
None
[ "libc", "zig", "zig-package" ]
54
false
2025-03-24T06:56:35Z
true
true
# ZeptoLibC A few of the most essential libc functions needed when working with C code in Zig. Much of the code is taken from [ziglibc](https://github.com/marler8997/ziglibc). ZeptoLibC provides, among others: - `malloc()`, `calloc()`, `realloc()`, `free()` - `printf()`, `fprintf()`, `snprintf()` - `strncmp()`, `strchr()`, `strncpy()` - `abs()`, `fabs()`, `sin()`, `cos()`, `sqrt()`, `pow()`, `floor()`, `ceil()` - `memset()`, `memmove()` ZeptoLibC is not intended to implement the full C library and does the bare minimum to support I/O operations (just `printf()`). The aim is to allow simple porting of existing C code to freestanding/baremetal environments such as WASM and embedded systems. All ZeptoLibC functions start with the prefix `zepto_`, eg. `zepto_malloc()` so as to not clash with any existing C functions. The file `zeptolibc.h` provides `#define`s for mapping `malloc()` -> `zepto_malloc()`. # How to use For a complete example, see https://github.com/ringtailsoftware/zeptolibc-example First we add the library as a dependency in our `build.zig.zon` file. `zig fetch --save git+https://github.com/ringtailsoftware/zeptolibc.git` And we add it to `build.zig` file. ```zig const zeptolibc_dep = b.dependency("zeptolibc", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("zeptolibc", zeptolibc_dep.module("zeptolibc")); exe.addIncludePath(zeptolibc_dep.path("src/")); ``` # Usage: Add `#include "zeptolibc.h"` to your C code. ```c #include "zeptolibc.h" void my_greeting(void) { printf("Hello world\n"); } ``` Setup ZeptoLibC from Zig and call the C code. `zeptolibc.init()` may be passed `null` for both write function and allocator. A `null` allocator will cause `malloc()` to always return `NULL`. A `null` write function will silently drop written data. ```zig const std = @import("std"); const zeptolibc = @import("zeptolibc"); const c = @cImport({ @cInclude("greeting.c"); }); fn writeFn(data:[]const u8) void { _ = std.io.getStdOut().writer().write(data) catch 0; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); // init zepto with a memory allocator and a write function (used for stdout and stderr) zeptolibc.init(allocator, writeFn); c.my_greeting(); } ```
https://avatars.githubusercontent.com/u/124872?v=4
zig-morus
jedisct1/zig-morus
2021-10-28T22:42:35Z
MORUS-1280-128 implementation in Zig.
master
0
11
0
11
https://api.github.com/repos/jedisct1/zig-morus/tags
MIT
[ "morus", "morus-1280-128", "webassembly", "zig", "zig-package" ]
16
false
2024-05-09T20:00:03Z
true
false
# MORUS cipher for Zig This is a Zig implementation of [MORUS](https://competitions.cr.yp.to/round3/morusv2.pdf) (MORUS-1280-128) MORUS is a fast authenticated cipher for platforms without hardware AES acceleration. It performs especially well on WebAssembly compared to alternatives. Its performance is comparable to AES-OCB, without using AES instructions. Benchmark results on x86_64 (Macbook Pro, 2,4 GHz Core i9, single core): ```text morus: 5890 MiB/s aes128-ocb: 5824 MiB/s ``` Benchmark results for WebAssembly (WAVM) ```text aes128-gcm: 176 MiB/s aes128-ocb: 300 MiB/s xchacha8Poly1305: 319 MiB/s aegis-128l: 807 MiB/s rocca: 854 MiB/s morus: 3505 MiB/s ``` MORUS is the fastest cipher on Raspberry Pi 4, and possibly other ARM devices without crypto extensions: ```text aes128-gcm: 41 MiB/s aes128-ocb: 81 MiB/s xchacha8Poly1305: 159 MiB/s aegis-128l: 168 MiB/s rocca: 221 MiB/s morus: 713 MiB/s ``` On platforms with AES acceleration, [AEGIS](https://jedisct1.github.io/draft-aegis-aead/draft-irtf-cfrg-aegis-aead.html)(available in the standard library as `std.crypto.aead.aegis.Aegis128L`) and [ROCCA](https://github.com/jedisct1/zig-rocca) have higher performance. Benchmark on Rocket Lake (Xeon E-2386G): ```text aes128-ocb: 10173 MiB/s aes256-ocb: 7792 MiB/s morus: 11069 MiB/s rocca: 16274 MiB/s aegis-128l: 21206 MiB/s (170 Gb/s) ``` Warning: MORUS doesn't provide 128-bit confidentiality even though [the best know attacks](https://eprint.iacr.org/2019/172.pdf) are impractical.
https://avatars.githubusercontent.com/u/60631511?v=4
dishwasher
edqx/dishwasher
2024-06-09T23:50:43Z
A non-spec-compliant, but probably pretty fast, XML parser for Zig.
master
0
11
0
11
https://api.github.com/repos/edqx/dishwasher/tags
MIT
[ "household-appliance", "xml", "zig", "zig-package" ]
344
false
2025-03-16T12:52:40Z
true
true
# Dishwasher A fairly fast XML parser for [Zig](https://ziglang.org). Note that this parser isn't strictly spec-compliant, however it will probably work with most well-formed xml documents. ## Features - [x] Pretty speedy - [x] Reader API-friendly - [x] Can populate structs - [x] Can populate dynamic values - [x] Compile-time parsing - [x] Diagnostics for malformed documents - [ ] Stringification (coming soon) ### Benchmarks Here are the results from the given benchmarks on my pc (i9-14900kf) in different optimisation modes, when parsing the [OpenGL XML Spec document](https://github.com/KhronosGroup/OpenGL-Registry/blob/main/xml/gl.xml) fully. | Mode | Min | Max | Avg | |------|-----|-----|-----| | `Debug` | `100ms` | `280ms` | `131ms` | | `ReleaseSafe` | `13ms` | `25ms` | `15ms` | | `ReleaseSmall` | `18ms` | `50ms` | `30ms` | | `ReleaseFast` | `7ms` | `27ms` | `13ms` | _All times are averaged over 100 runs, rounded to the nearest 2sf._ ## Usage Dishwasher has 4 APIs, 3 of which will be most useful. - [Parsing API](#parsing-api) - for parsing an entire XML document at runtime. - [Populate API](#populate-api) - for mapping an XML document to a given struct. - [Comptime Parsing and Populate API](#comptime-parsing-and-populate-api) - for parsing an entire XML document at compile time. - [Scanner API](#scanner-api) - for iterating through XML symbols from a slice or reader. ### Parsing API Dishwasher lets you parse an XML document from either an entire slice or a reader into a tree-like structure that represents all nodes. All of the parse methods create an arena which is returned back to you so that you can deinitialise it when you no longer need the data. #### Parse from a slice ```zig const owned_tree = dishwasher.parse.fromSlice(allocator, xml_text); defer owned_tree.deinit(); // all strings and lists will be free'd std.debug.assert(owned_tree.tree.children[0] == .elem); ``` #### Parse from a reader ```zig const owned_tree = dishwasher.parse.fromReader(allocator, file.reader()); defer owned_tree.deinit(); std.debug.assert(owned_tree.tree.children[0] == .elem); ``` #### Diagnostics You can also get basic information about invalid documents using the parse diagnostics struct, and passing it into either `parse.fromSliceDiagnostics` or `parse.fromReaderDiagnostics`. ```zig var diagnostics = dishwasher.parse.Diagnostics.init(allocator); defer diagnostics.deinit(); const parsed = try dishwasher.parse.fromReaderDiagnostics(allocator, file.reader(), &diagnostics); defer parsed.deinit(); for (diagnostics.defects.items) |defect| { std.debug.print("{} from {}..{}", .{ defect.kind, defect.range.start, defect.range.end }); } ``` #### Tree API The returned tree has the following signature: ```zig const Tree = struct { pub const Node = union(enum) { pub const Elem = struct { pub const Attr = struct { name: []const u8, value: ?[]const u8, }; tag_name: []const u8, attributes: []const Attr, tree: ?Tree, // Get an attribute given its name. pub fn attributeByName(self: Elem, needle: []const u8) ?Attr; pub fn attr(self: Elem, needle: []const u8) ?Attr; // Get the value of an attribute given its name. Note that if the // attribute has no value, e.g., <button disabled> this will // still return null. Use attr or attributeByName in those // cases. pub fn attributeValueByName(self: Elem, needle: []const u8) ?[]const u8; pub fn attrValue(self: Elem, needle: []const u8) ?[]const u8; }; pub const Text = struct { contents: []const u8, // Return the text without any whitespace at the beginning or end. pub fn trimmed(self: Text) []const u8; } pub const Comment = struct { contents: []const u8, }; elem: Elem, text: text, comment: Comment, }; children: []const Node, // Find an element child by its tag name pub fn elementByTagName(self: Tree, needle: []const u8) ?Node.Elem; pub fn elem(self: Tree, needle: []const u8) ?Node.Elem; // Allocate a slice for all of the element children of a given tag name // To free the returned slice, you can just call allocator.free(elements) // where 'elements' is the returned slice. pub fn elementsByTagNameAlloc(self: Tree, allocator: std.mem.Allocator, needle: []const u8) ![]Node.Elem; pub fn elemsAlloc(self: Tree, allocator: std.mem.Allocator, needle: []const u8) ![]Node.Elem; // Get an element by the value of one of its attributes pub fn elementByAttributeValue(self: Tree, needle_name: []const u8, needle_value: []const u8) ?Node.Elem; pub fn elemByAttr(self: Tree, needle_name: []const u8, needle_value: []const u8) ?Node.Elem; // Return the inner text (not including the elements) of the tree. Note that the // result will be entirely unformatted. pub fn concatTextAlloc(self: Tree, allocator: std.mem.Allocator) ![]const u8; // Return the inner text (not including the elements) of the tree but without // any whitespace at the start or end. pub fn concatTextTrimmedAlloc(self: Tree, allocator: std.mem.Allocator) ![]const u8; } ``` ### Populate API Often, it's useful to be able to populate a given struct with values from an XML document. That is, 'reading' the document into the struct. Dishwasher comes with a shaping API so you can dictate how the document should be read into the struct. Simply declare an `xml_shape` on the struct: ```zig const Job = struct { title: []const u8, start_date: []const u8, end_date: []const u8, } const Person = struct { pub const xml_shape = .{ .name = .content_trimmed, .age = .{ .attribute, "age" }, .jobs = .{ .elements, "job", .{ .start_date = .{ .attribute, "start_date" }, .end_date = .{ .attribute, "end_date" }, .title = .content_trimmed, .fired = .attribute_exists, } }, .location = .{ .one_of, .{ .element, "house", .content }, .{ .element, "work", .content }, .none, }, .apprentice = .{ .maybe, .{ .element, "apprentice", Person } }, .children = .{ .elements, "child", Person }, }; name: []const u8, age: []const u8, jobs: []struct { start_date: []const u8, end_date: []const u8, title: []const u8, fired: bool, }, location: union(enum) { house: []const u8, work: []const u8, none: void, }, apprentice: ?*Person, children: []Person, }; pub const Register = struct { pub const xml_shape = .{ .people = .{ .elements, "person", Person }, }; people: []Person, }; const register = try diswasher.Populate(Register).initFromSlice(allocator, xml_text); defer register.deinit(); // register.value: Register ``` Alternatively, you can populate an existing struct: ```zig var register: Register = undefined; const arena = try dishwasher.Populate(Register).fromSlice(allocator, xml_text, &register); defer arena.deinit(); ``` If you want to own all of your values yourself, use: ```zig const owned_tree = dishwasher.parse.fromReader(allocator, file.reader()); defer owned_tree.deinit(); const register = try dishwasher.Populate(Register).initFromTreeOwned(allocator, owned_tree.tree); // free 'register' values yourself.. ``` #### Dynamic values If some field accepts any sort of XML document shape, you can instruct it to accept a `parse.Tree`: ```zig const Register = struct { pub const xml_shape = .{ .people = .{ .elements, "person", dishwasher.parse.Tree }, }; people: []dishwasher.parse.Tree, }; ``` > [!NOTE] > Note that the tree is not duplicated for you, so if you use the `initFromTreeOwned` method, the values in the tree > will still belong to the arena that was initialised for the tree. #### Free struct If you use the `initFromTreeOwned` population method, you can free all of the values in an arena-friendly way with: ```zig dishwasher.Populate(Register).deinit(allocator, register); ``` ### Comptime Parsing and Populate API It could be useful to parse an XML document at compile time, for example for some inline code generation. While comptime doesn't have allocators, there's a custom API for this: ```zig const tree = dishwasher.parse.fromSliceComptime(xml_text); ``` Check out the [Tree API](#tree-api) to know what to do with the returned value. #### Comptime Populate API If you want to populate a struct at compile time, you can use the `*Comptime` methods on the `Populate` struct: ```zig const register = dishwasher.Populate(Register).initFromSliceComptime(xml_text); ``` > [!NOTE] > Remember that for the target struct, all pointers need to be `*const T` or > `[]const T`. ### Scanner API If you want low-level access to the iterator for lexing an XML document, you can use the Scanner API, which accepts a slice buffer: ```zig var xmlScanner = Scanner.fromSlice(xml_text); while (try xmlScanner.next()) |token| { std.debug.print("token kind: ", .{ token.kind }); } ``` If you have a reader and no access to the entire slice, the Reader API can connect any reader to the Scanner API so you can lex from a reader: ```zig var xmlReader = Scanner.staticBufferReader(file.reader()); while (try xmlScanner.next()) |token| { std.debug.print("token kind: ", .{ token.kind }); } ``` > [!NOTE] > If you're given an error about running out of buffer space, try increase > the reader buffer size with > ```zig > const buffer_size = 4096; > const XmlFileReader = zigScanner.StaticBufferReader(@TypeOf(file.reader()), buffer_size); > const xmlReader = XmlFileReader.init(file.reader()); > ``` #### Comptime Scanner The scanner works during compile time without any modification. ## License All dishwasher code is under the MIT license.
https://avatars.githubusercontent.com/u/8823448?v=4
jaysan
lawrence-laz/jaysan
2024-09-18T23:20:56Z
A fast json serializer
main
0
11
1
11
https://api.github.com/repos/lawrence-laz/jaysan/tags
MIT
[ "json", "json-serializer", "zig", "zig-package" ]
26
false
2025-01-02T16:43:37Z
true
true
<h1 align="center"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c9/JSON_vector_logo.svg/160px-JSON_vector_logo.svg.png" width="64"><br> Jayさん <br> </h1> Jaysan is a fast json library written in Zig. Currently supports serialization only. ```zig var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const Foo = struct { foo: i32, bar: []const u8, }; const string = try json.stringifyAlloc( gpa.allocator(), Foo{ .foo = 123, .bar = "Hello, world!", }, ); // {"foo":123,"bar":"Hello, world!"} ``` ```md Benchmark 1: zig-stdjson Time (mean Β± Οƒ): 141.9 ms Β± 1.1 ms [User: 140.4 ms, System: 1.0 ms] Range (min … max): 140.1 ms … 144.1 ms 20 runs Benchmark 2: zig-jaysan Time (mean Β± Οƒ): 46.8 ms Β± 1.3 ms [User: 46.2 ms, System: 0.4 ms] Range (min … max): 43.1 ms … 49.2 ms 61 runs Benchmark 3: rust-serde Time (mean Β± Οƒ): 46.9 ms Β± 0.9 ms [User: 45.8 ms, System: 0.9 ms] Range (min … max): 45.9 ms … 50.9 ms 62 runs Summary zig-jaysan 1.00 Β± 0.03 times faster than rust-serde 3.03 Β± 0.09 times faster than zig-stdjson ```
https://avatars.githubusercontent.com/u/547147?v=4
zig-releaser
knadh/zig-releaser
2021-10-23T16:26:44Z
A simple hack to use GoReleaser to build, release, and publish Zig projects.
master
1
11
2
11
https://api.github.com/repos/knadh/zig-releaser/tags
MIT
[ "build-release", "build-tool", "goreleaser", "package", "release", "release-automation", "zig", "zig-package" ]
7
false
2025-03-08T04:30:30Z
false
false
# GoReleaser v2 Official Support πŸŽ‰ See <https://goreleaser.com/quick-start/>. # zig-releaser (old, GoReleaser v1) zig-releaser is a hack that allows Zig programs to be built, packaged, and released with [GoReleaser](https://goreleaser.com), a tool for publishing Go programs. [Here is an example](https://github.com/knadh/csv2json/releases) for a Zig program published to GitHub with GoReleaser. The changelog and artefacts are all automatically generated by GoReleaser. This hack has only been tested with GitHub but should work with other release targets GoReleaser supports. ### How to use - Install [GoReleaser](https://goreleaser.com/install/). - Setup the [GitHub token](https://github.com/settings/tokens/new) with `repo` perms. - Copy `.goreleaser/`, and `.goreleaser.yml` from this repo to the root of the Zig project. - Edit `.goreleaser.yml` for the project (generally the `binary`, `goos`, `files` fields). - Edit `build.sh` script to tweak the zig build flags. Once the project is ready for release, add a semver tag (`git tag -a v0.1.0 -m v0.1.0`) ### Dry run ```sh goreleaser --snapshot --skip=publish --clean ``` The releases will appear in the `dist` directory. ### Publish ```sh goreleaser --snapshot --skip=publish --clean ```
https://avatars.githubusercontent.com/u/5464072?v=4
zig-zorm
nektro/zig-zorm
2021-08-09T08:41:46Z
An ORM-ish library for Zig.
master
1
11
0
11
https://api.github.com/repos/nektro/zig-zorm/tags
AGPL-3.0
[ "sqlite", "zig", "zig-package" ]
30
false
2025-03-13T15:49:29Z
true
false
# Zorm The ORM library for Zig. WIP ## Example Usage [src/main.zig](src/main.zig) ## Built With - [Zig](https://github.com/ziglang/zig) master - [Zigmod](https://github.com/nektro/zigmod) package manager - https://github.com/vrischmann/zig-sqlite ## Add me ``` $ zigmod aq add 1/nektro/zorm ``` ## License AGPL-3.0
https://avatars.githubusercontent.com/u/3932972?v=4
zig-uri
ikskuh/zig-uri
2020-05-15T16:00:29Z
A small URI parser that parses URIs after RFC3986
master
1
11
2
11
https://api.github.com/repos/ikskuh/zig-uri/tags
MIT
[ "uri-parser", "zig", "zig-package", "ziglang" ]
21
false
2024-03-25T21:15:01Z
false
false
# Zig URI Parser A small URI parser that parses URIs after [RFC3986](https://tools.ietf.org/html/rfc3986). > **NOTICE: THIS LIBRARY IS DEPRECATED!** > This library is now part of zig `std` library, available as `std.Uri` since [87b2234](https://github.com/ziglang/zig/commit/87b223428a8953b6af9bea61ff4cc905821c0557). > ## Usage Example ```zig var link = try uri.parse("https://github.com/MasterQ32/zig-uri"); // link.scheme == "https" // link.host == "github.com" // link.path == "/MasterQ32/zig-uri" ```
https://avatars.githubusercontent.com/u/48649707?v=4
zig-sieve
tensorush/zig-sieve
2024-01-21T14:38:57Z
Zig implementation of SIEVE cache eviction algorithm.
main
0
10
0
10
https://api.github.com/repos/tensorush/zig-sieve/tags
MIT
[ "sieve-cache", "zig-package" ]
18
false
2025-03-18T06:56:57Z
true
true
# zig-sieve ## Zig implementation of [SIEVE cache eviction algorithm](https://cachemon.github.io/SIEVE-website/). ### Usage - Add `sieve` dependency to `build.zig.zon`. ```sh zig fetch --save git+https://github.com/tensorush/zig-sieve ``` - Use `sieve` dependency in `build.zig`. ```zig const sieve_dep = b.dependency("sieve", .{ .target = target, .optimize = optimize, }); const sieve_mod = sieve_dep.module("sieve"); <compile>.root_module.addImport("sieve", sieve_mod); ``` ### Benchmarks (MacBook M1 Pro) - Sequence: the time to cache and retrieve integer values. ```sh $ zig build bench -- -s Sequence: 23.042us ``` - Composite: the time to cache and retrieve composite values. ```sh $ zig build bench -- -c Composite: 33.417us ``` - Composite (normal): the time to cache and retrieve normally-distributed composite values. ```sh $ zig build bench -- -n Composite Normal: 99.708us ```
https://avatars.githubusercontent.com/u/2242?v=4
zig-termsize
softprops/zig-termsize
2024-02-29T04:54:41Z
terminal size matters
main
1
10
2
10
https://api.github.com/repos/softprops/zig-termsize/tags
MIT
[ "zig-library", "zig-package", "zigdex-lib" ]
23
false
2025-03-19T17:20:19Z
true
true
<h1 align="center"> termsize </h1> <div align="center"> terminal size matters </div> --- [![CI](https://github.com/softprops/zig-termsize/actions/workflows/ci.yml/badge.svg)](https://github.com/softprops/zig-termsize/actions/workflows/ci.yml) ![License Info](https://img.shields.io/github/license/softprops/zig-termsize) ![Release](https://img.shields.io/github/v/release/softprops/zig-termsize) ![Zig Support](https://img.shields.io/badge/zig-0.12.0%2F0.13.0-black?logo=zig) ## 🍬 features Termsize is a zig library providing a multi-platform interface for resolving your terminal's current size in rows and columns. On most unix systems, this is similar invoking the stty(1) program, requesting the terminal size. ## examples ```zig const std = @import("std"); const termsize = @import("termsize"); pub fn main() !void { std.debug.print( "{any}", .{termsize.termSize(std.io.getStdOut())}, ); } ``` ## πŸ“Ό installing Create a new exec project with `zig init-exe`. Copy the echo handler example above into `src/main.zig` Create a `build.zig.zon` file to declare a dependency > .zon short for "zig object notation" files are essentially zig structs. `build.zig.zon` is zigs native package manager convention for where to declare dependencies Starting in zig 0.12.0, you can use and should prefer ```sh zig fetch --save "git+https://github.com/softprops/zig-termsize#v0.1.0" ``` otherwise, to manually add it, do so as follows ```diff .{ .name = "my-app", .version = "0.1.0", .dependencies = .{ + // πŸ‘‡ declare dep properties + .termsize = .{ + // πŸ‘‡ uri to download + .url = "https://github.com/softprops/zig-termsize/archive/refs/tags/v0.1.0.tar.gz", + // πŸ‘‡ hash verification + .hash = "{current-hash}", + }, }, } ``` > the hash below may vary. you can also depend any tag with `https://github.com/softprops/zig-termsize/archive/refs/tags/v{version}.tar.gz` or current main with `https://github.com/softprops/zig-termsize/archive/refs/heads/main/main.tar.gz`. to resolve a hash omit it and let zig tell you the expected value. Add the following in your `build.zig` file ```diff const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); + // πŸ‘‡ de-reference termsize dep from build.zig.zon + const termsize = b.dependency("termsize", .{ + .target = target, + .optimize = optimize, + }).module("termsize"); var exe = b.addExecutable(.{ .name = "your-exe", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); + // πŸ‘‡ add the termsize module to executable + exe.root_module.addImport("termsize", termsize); b.installArtifact(exe); } ``` ## πŸ₯Ή for budding ziglings Does this look interesting but you're new to zig and feel left out? No problem, zig is young so most us of our new are as well. Here are some resources to help get you up to speed on zig - [the official zig website](https://ziglang.org/) - [zig's one-page language documentation](https://ziglang.org/documentation/0.13.0/) - [ziglearn](https://ziglearn.org/) - [ziglings exercises](https://github.com/ratfactor/ziglings) \- softprops 2024
https://avatars.githubusercontent.com/u/56497124?v=4
lizpack
kj4tmp/lizpack
2024-12-19T07:19:26Z
A MessagePack Library for Zig
main
0
10
0
10
https://api.github.com/repos/kj4tmp/lizpack/tags
MIT
[ "zig", "zig-package" ]
102
false
2025-03-06T04:55:45Z
true
true
# lizpack ![Tests](https://github.com/kj4tmp/lizpack/actions/workflows/main.yml/badge.svg) A MessagePack Library for Zig 1. Zero allocations. 1. Zero encoding errors. 1. Simple control flow. 1. All messages validated for you. A simple API: ```zig lizpack.encode(...) lizpack.encodeBounded(...) lizpack.encodeAlloc(...) lizpack.decode(...) lizpack.decodeAlloc(...) ``` Combines with your definition of your message structure: ```zig const CustomerComplaint = struct { user_id: u64, status: enum(u8) { received, reviewed, awaiting_response, finished, }, }; ``` ## Default Formats | Zig Type | MessagePack Type | | ---------------------------------- | ----------------------------------- | | `bool` | bool | | `null` | nil | | `u3`,`u45`, `i6` | integer | | `?T` | nil or T | | `enum` | integer | | `[N]T` | N length array of T | | `[N:x]T` | N+1 length array of T ending in x | | `[N]u8` | str | | `@Vector(N, T)` | N length array of T | | `struct` | map, str: field value | | `union (enum)` | map (single key-value pair) | | `[]T` | N length array of T | | `[:x]T` | N + 1 length array of T ending in x | | `[]u8` | str | | `[:x]u8` | str ending in x | | `*T` | T | > `str` is the default MessagePack type for `[]u8` because it is the smallest for short slices. Unsupported types: | Zig Type | Reason | | ------------------ | ------------------------------------------------------------ | | `union` (untagged) | Decoding cannot determine active field, and neither can you. | | `error` | I can add this, if someone asks. Perhaps as `str`? | Note: pointer types require allocation to decode. ## Customizing Formats You can customize how types are formatted in message pack: | Zig Type | Available Encodings | | ----------------------------------- | ----------------------------------------- | | `enum` | string, int | | `[]u8`,`[N]u8`, `@Vector(N, u8)` | string, int, array | | `struct` | map, array | | `union (enum)` | map (single key-value pair), active field | | `[] struct {key: ..., value: ...}` | map, array | | `[N] struct {key: ..., value: ...}` | map, array | See [examples](examples/examples.zig) for how to do it. ## Manual Encoding / Decoding If you require the finest level of control over how data is encoded and decoded, the `lizpack.manual` API may suit your use case. See [examples](examples/examples.zig) for how to do it. ## Examples ```zig const std = @import("std"); const lizpack = @import("lizpack"); test { const CustomerComplaint = struct { user_id: u64, status: enum(u8) { received, reviewed, awaiting_response, finished, }, }; var out: [1000]u8 = undefined; const expected: CustomerComplaint = .{ .user_id = 2345, .status = .reviewed }; const slice: []u8 = try lizpack.encode(expected, &out, .{}); try std.testing.expectEqual(expected, lizpack.decode(@TypeOf(expected), slice, .{})); } ``` More examples can be found in [examples/](/examples/). ## Installation To add lizpack to your project as a dependency, run: ```sh zig fetch --save git+https://github.com/kj4tmp/lizpack ``` Then add the following to your build.zig: ```zig // assuming you have an existing executable called `exe` const lizpack = b.dependency("lizpack", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("lizpack", lizpack.module("lizpack")); ``` And import the library to begin using it: ```zig const lizpack = @import("lizpack"); ``` ## Zig Version Please refer to the `minimum_zig_version` field of the [`build.zig.zon`](/build.zig.zon). ## TODO - [ ] refactor: use of has_sentinel - [ ] refactor: use of std.builtin.Type.Pointer.Sentinel
https://avatars.githubusercontent.com/u/146390816?v=4
wayland
allyourcodebase/wayland
2024-12-18T19:07:19Z
wayland ported to the zig build system
master
0
10
1
10
https://api.github.com/repos/allyourcodebase/wayland/tags
MIT
[ "zig", "zig-package" ]
16
false
2025-03-25T21:53:01Z
true
true
[![CI](https://github.com/allyourcodebase/wayland/actions/workflows/ci.yaml/badge.svg)](https://github.com/allyourcodebase/wayland/actions) # Wayland This is [Wayland](https://gitlab.freedesktop.org/wayland/wayland), packaged for [Zig](https://ziglang.org/). ## Installation First, update your `build.zig.zon`: ``` # Initialize a `zig build` project if you haven't already zig init zig fetch --save git+https://github.com/allyourcodebase/wayland.git#1.23.1-2 ``` You can then import `wayland` in your `build.zig` with: ```zig const wayland = b.dependency("wayland", .{ .target = target, .optimize = optimize, }); const wayland_server = wayland.artifact("wayland-server"); const wayland_client = wayland.artifact("wayland-client"); const wayland_egl = wayland.artifact("wayland-egl"); const wayland_cursor = wayland.artifact("wayland-cursor"); // Makes sure we get `wayland-scanner` for the host platform even when cross-compiling const wayland_host = b.dependency("wayland", .{ .target = b.host, .optimize = std.builtin.OptimizeMode.Debug, }); const wayland_scanner = wayland_host.artifact("wayland-scanner"); ```
https://avatars.githubusercontent.com/u/5008987?v=4
zig-fractions
Chriscbr/zig-fractions
2024-07-06T06:39:45Z
Simplify, convert, and do math with fractions in Zig
main
0
10
0
10
https://api.github.com/repos/Chriscbr/zig-fractions/tags
MIT
[ "fractions", "zig", "zig-library", "zig-package" ]
22
false
2024-12-29T13:16:59Z
true
true
# zig-fractions A Zig library for performing math with fractions, where each fraction is represented by a pair of integers. Compatible with Zig 0.13 stable. Supported APIs: - convertion from floats, or numerator/denominator pairs (`fromFloat()`, `init()`) - convertion to floats and integers (`to(T)`) - formatting (`toString()`, `toStringAlloc()`, `format()`) - negation, absolute value (`negate()`, `abs()`) - addition, subtraction, multiplication, division (`add()`, `sub()`, `mul()`, `div()`) - comparison (`eql()`, `eqlAbs()`, `eqlZero()`, `order()`, `orderAbs()`) - simplifying (`simplify()`) ## Installation First, run the following: ``` zig fetch --save git+https://github.com/Chriscbr/zig-fractions ``` Then add the following to build.zig: ```zig const zig_fractions = b.dependency("zig-fractions", .{}); exe.root_module.addImport("zig-fractions", zig_fractions.module("zig-fractions")); ``` Then you can use the library in your Zig project: ```zig const Fraction = @import("zig-fractions").Fraction; var f1 = try Fraction.fromFloat(@as(f32, 2.5)); const f2 = try Fraction.init(1, 5, false); try f1.mul(&f2); // 2.5 * 1/5 = 1/2 std.debug.print("{}\n", .{f1}); // "1/2" ``` ## Contributing Pull requests are welcome.
https://avatars.githubusercontent.com/u/499599?v=4
jstring.zig
liyu1981/jstring.zig
2024-01-19T10:58:50Z
a reusable string lib for myself with all familiar methods methods can find in javascript string
main
4
10
1
10
https://api.github.com/repos/liyu1981/jstring.zig/tags
None
[ "jstring", "zig", "zig-package" ]
6,092
false
2025-03-17T17:39:42Z
true
true
# `jstring.zig` ## Target: create a reusable string lib for myself with all familiar methods methods can find in javascript string. ## Reason: 1. string is important we all know, so a good string lib will be very useful. 2. javascript string is (in my opinion) the most battle tested string library out there, strike a good balance between features and complexity. The javascript string specs and methods this file use as reference can be found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String All methods except those marked as deprecated (such as anchor, big, blink etc) are implemented, in zig way. # integration with PCRE2 regex One highlight of `jstring.zig` is that it integrates with [PCRE2](https://www.pcre.org/) to provide `match`, `match_all` and more just like the familar feeling of javascript string. here are some examples of how regex can be used ```zig var str1 = try JStringUnmanaged.newFromSlice(arena.allocator(), "hello,hello,world"); var results = try str1.splitByRegex(arena.allocator(), "l+", 0, 0); try testing.expectEqual(results.len, 1); try testing.expect(results[0].eqlSlice("hello,hello,world")); results = try str1.splitByRegex(arena.allocator(), "l+", 0, -1); try testing.expectEqual(results.len, 4); try testing.expect(results[0].eqlSlice("he")); try testing.expect(results[1].eqlSlice("o,he")); try testing.expect(results[2].eqlSlice("o,wor")); try testing.expect(results[3].eqlSlice("d")); ``` # usage ```bash zig fetch --save https://github.com/liyu1981/jstring.zig/archive/refs/tags/0.1.1.tar.gz ``` check `example` folder for a sample project ```zig const std = @import("std"); const jstring = @import("jstring"); pub fn main() !u8 { var your_name = brk: { var jstr = try jstring.JString.newFromSlice(std.heap.page_allocator, "name is: zig"); defer jstr.deinit(); const m = try jstr.match("name is: (?<name>.+)", 0, true, 0, 0); if (m.matchSucceed()) { const r = m.getGroupResultByName("name"); break :brk try jstr.slice( @as(isize, @intCast(r.?.start)), @as(isize, @intCast(r.?.start + r.?.len)), ); } unreachable; }; defer your_name.deinit(); try std.io.getStdOut().writer().print("\nhello, {s}\n", .{your_name}); return 0; } ``` in order to run this example from the `git clone` repo, you will need ```bash cd <jstirng_repo>/examples zig fetch --save ../ # to update your local zig cache about jstring zig build run ``` # `build.zig` when use `jstring.zig` in your project, as it integrates with `PCRE2`, will need to link your project to `libpcre-8`. `jstring.zig` provide a build time function to easy this process. ```zig // in your build.zig const jstring_build = @import("jstring"); ... const jstring_dep = b.dependency("jstring", .{}); exe.addModule("jstring", jstring_dep.module("jstring")); jstring_build.linkPCRE(exe, jstring_dep); ``` again, check `example` folder for the usage # performance `jstring.zig` is built with performance in mind. Though `benchmark` is still in developing, but the initial result of allocate/free 1M random size of strings shows a _~70%_ advantage comparing to c++/20's `std::string`. ```bash benchmark % ./zig-out/bin/benchmark |zig create/release: | [ooooo] | avg= 16464000ns | min= 14400000ns | max= 20975000ns | |cpp create/release: | [ooooo] | avg= 56735400ns | min= 56137000ns | max= 57090000ns | ``` (`jstring.zig` is built with `-Doptimize=ReleaseFast`, and `cpp` is built with `-std=c++20 -O2`) check current benchmark method [here](https://github.com/liyu1981/jstring.zig/blob/main/tools/benchmark/main.zig) # docs check the auto generated zig docs [here](https://liyu1981.github.io/jstring.zig) # tests `jstring` is rigorously tested. ```bash ./script/pcre_test.sh src/jstring.zig ``` to run all tests. or check kcov report [here](https://liyu1981.github.io/jstring.zig/cov/index.html): the current level is 100%. # license MIT License :)
https://avatars.githubusercontent.com/u/116048347?v=4
localasm
InspectorBoat/localasm
2025-01-17T03:04:16Z
Local assembly viewer for zig
master
0
10
0
10
https://api.github.com/repos/InspectorBoat/localasm/tags
None
[ "zig-package" ]
254
false
2025-01-31T13:43:54Z
true
true
# localasm We have godbolt at home - a local assembly output viewer, integrated with the zig build system # Installation and usage localasm currently only supports 0.14.0-dev. 1\. Run `zig fetch` to add the localasm package to your `build.zig.zon` manifest: ```sh zig fetch --save git+https://github.com/inspectorboat/localasm ``` 2\. (Optional) Add a special declaration to the root file of the module you would like to analyze: ```zig pub const functions_to_analyze = .{ square, fib }; ``` If this declaration is not present, localasm will instead emit assembly for all functions in the root source file. 3\. Use localasm to add build steps in your `build.zig` script: ```zig pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const module = b.createModule(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); localasm.addAssemblyOutput(b, module, .{ .target = target }); // Optional: Analyze multiple modules const other_module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, }); localasm.addAssemblyOutput(b, other_module, .{ // Defaults to .ReleaseFast if left out .optimize = .ReleaseSafe, .target = b.graph.host, // Enable a step to output raw assembly without cleaning - extremely noisy, off by default .enable_raw_asm_step = true, // Renames the step - defaults to rawasm. Useful if you want to analyze multiple modules (hence multiple addAssemblyOutput calls) .raw_asm_step_name = "lib_rawasm", .raw_asm_file_name = "lib_rawasm.s", // Enable a step to output clean assembly - on by default .enable_clean_asm_step = true, .clean_asm_step_name = "lib_asm", .clean_asm_file_name = "lib_asm.s", // Enable a step that sends cleaned assembly to llvm-mca for analysis - on by default .enable_mca_step = true, .mca_step_name = "lib_mca", .mca_file_name = "lib_mca.txt", }); } ``` 4\. Run `zig build asm` to get your assembly output: ```sh cat zig-out\asm\asm.s main.square: push rbp mov rbp, rsp mov eax, ecx imul eax, ecx pop rbp ret ``` 5\. (Optional) Run `zig build mca` to feed the assembly output into llvm-mca: ```sh cat zig-out\asm\mca.txt Iterations: 100 Instructions: 2900 Total Cycles: 3484 Total uOps: 4800 Dispatch Width: 6 uOps Per Cycle: 1.38 IPC: 0.83 Block RThroughput: 8.0 ``` Any arguments passed to `zig build mca` will be forwarded to llvm-mca. For example, use `zig build mca -- --timeline` to enable a timeline view of program execution. This step requires llvm-mca to be installed, which can be acquired at [releases.llvm.org](https://releases.llvm.org/). # Why not just use godbolt? - Due to zig's lazy analysis, getting non-`export` functions to get emitted is a pain - you have to use a hack like `const foo: *const anyopaque = @ptrCast(&function);`, which gets irritating to type every time. localasm does this for you automatically by wrapping the module you pass into `addAssemblyOutput`, and also filters out the dummy constants emitted. - If any code is split into multiple files, has library dependencies, or is part of a larger project, getting it into godbolt can difficult. Integrating with the zig build system solves this. - Running locally means you get to use your personal editor setup, which I personally find to be a large improvement to godbolt's rather cramped UI. # Known limitations - Currently, only x86 assembly cleanup is suppported. Compiler-explorer has a [repository](https://github.com/compiler-explorer/asm-parser/blob/main/setup.sh) that already handles assembly parsing, but it is written in C++. If anybody would feels inclined to port it to [allyourcodebase](https://github.com/allyourcodebase), please let me know and I will integrate it into this package.
https://avatars.githubusercontent.com/u/45130910?v=4
axe
Ratakor/axe
2024-10-30T22:11:54Z
A logging library
master
0
10
0
10
https://api.github.com/repos/Ratakor/axe/tags
MIT
[ "log", "logging", "zig-package" ]
638
false
2025-03-24T14:41:03Z
true
true
# Axe πŸͺ“ A fully customizable, drop-in replacement for `std.Options.LogFn` with support for multiple file logging (custom writer supported), buffering, JSON, time, custom format, colors (automatic tty detection, windows support, NO\_COLOR support, CLICOLOR\_FORCE support), source location, and thread safety (multiple mutex interface available)! ![](screenshot.png) ## Usage Add it to an existing project with this command: ```sh zig fetch --save git+https://github.com/Ratakor/axe ``` Then add the module your build.zig. ```zig const axe = b.dependency("axe", .{}).module("axe"); exe.root_module.addImport("axe", axe); ``` Check [example.zig](example/example.zig) for how to use it! [API Documentation](https://ratakor.github.io/axe) <!-- ## TODO - Add a way to combine multiple loggers into one. -->
https://avatars.githubusercontent.com/u/193787365?v=4
zindexer
openSVM/zindexer
2025-01-28T01:25:04Z
solana indexer for clickhouse in zig
main
4
10
1
10
https://api.github.com/repos/openSVM/zindexer/tags
NOASSERTION
[ "zig", "zig-package", "ziglana", "ziglang" ]
156
false
2025-04-03T23:28:14Z
true
true
# ZIndexer - Multi-Network SVM Indexer ZIndexer is a high-performance indexer for Solana Virtual Machine (SVM) networks, capable of subscribing to and indexing data from multiple networks simultaneously. ## Features - **Multi-Network Support**: Index multiple SVM networks (mainnet, devnet, testnet, localnet) simultaneously - **Comprehensive Indexing**: - Automated Market Makers (AMMs) - Metaplex NFTs and marketplaces - Token transfers and balances - Account balance changes - Transactions and instructions - Blocks and slots - Account activity - **Real-time and Historical Modes**: Choose between real-time indexing or historical backfilling - **Database Integration**: High-performance storage and querying of indexed data with support for ClickHouse and QuestDB - **Interactive TUI**: Monitor indexing progress across all networks in real-time ## Requirements - Zig 0.14.0 or later - ClickHouse server or QuestDB server - Internet connection to access SVM networks ## Building ```bash zig build ``` ## Configuration The indexer uses two configuration files: - `src/rpc_nodes.json`: HTTP RPC endpoints for each network - `src/ws_nodes.json`: WebSocket endpoints for each network You can customize these files to add or remove networks, or to use different RPC providers. ## Usage ```bash # Run in real-time mode (default) ./zig-out/bin/zindexer # Run in historical mode ./zig-out/bin/zindexer --mode historical # Customize ClickHouse connection ./zig-out/bin/zindexer --database-type clickhouse --database-url localhost:9000 --database-user default --database-password "" --database-name solana # Use QuestDB instead ./zig-out/bin/zindexer --database-type questdb --database-url localhost:9000 --database-user admin --database-password "quest" --database-name solana # Show help ./zig-out/bin/zindexer --help ``` ### Command Line Options - `-m, --mode <mode>`: Indexer mode (historical or realtime) - `-r, --rpc-nodes <file>`: RPC nodes configuration file - `-w, --ws-nodes <file>`: WebSocket nodes configuration file - `-t, --database-type <type>`: Database type (clickhouse or questdb) - `-c, --database-url <url>`: Database server URL - `-u, --database-user <user>`: Database username - `-p, --database-password <pass>`: Database password - `-d, --database-name <db>`: Database name - `-b, --batch-size <size>`: Batch size for historical indexing - `--max-retries <count>`: Maximum retry attempts - `--retry-delay <ms>`: Delay between retries in milliseconds #### Legacy ClickHouse Options (for backward compatibility) - `--clickhouse-url <url>`: ClickHouse server URL - `--clickhouse-user <user>`: ClickHouse username - `--clickhouse-password <pass>`: ClickHouse password - `--clickhouse-database <db>`: ClickHouse database name #### QuestDB Options - `--questdb-url <url>`: QuestDB server URL - `--questdb-user <user>`: QuestDB username - `--questdb-password <pass>`: QuestDB password - `--questdb-database <db>`: QuestDB database name - `-h, --help`: Show help message ## Schema Setup The schema can be automatically applied to your database instance using the included script: ### For ClickHouse ```bash DB_TYPE=clickhouse CLICKHOUSE_URL="http://localhost:8123" ./scripts/apply_schema.sh ``` ### For QuestDB ```bash DB_TYPE=questdb QUESTDB_URL="http://localhost:9000" ./scripts/apply_schema.sh ``` ## Architecture ZIndexer is built with a modular architecture: - **Core Indexer**: Manages connections to multiple networks and coordinates indexing - **RPC Client**: Handles communication with SVM networks via HTTP and WebSocket - **Database Abstraction Layer**: Provides a common interface for different database backends - **ClickHouse Client**: Manages data storage and retrieval in ClickHouse - **QuestDB Client**: Manages data storage and retrieval in QuestDB - **Indexing Modules**: - Transaction Indexer: Processes transaction data - Instruction Indexer: Processes instruction data - Account Indexer: Tracks account changes - Token Indexer: Tracks token transfers and balances - DeFi Indexer: Tracks AMM and DeFi protocol activity - NFT Indexer: Tracks NFT mints, sales, and marketplace activity - Security Indexer: Monitors for suspicious activity ## Database Schema ZIndexer creates several tables in ClickHouse: - `transactions`: Basic transaction data - `instructions`: Instruction data with program IDs - `accounts`: Account state changes - `account_activity`: Account usage statistics - `token_transfers`: Token transfer events - `token_accounts`: Token account balances - `token_holders`: Token holder information - `nft_mints`: NFT mint events - `nft_sales`: NFT sale events - `pool_swaps`: AMM swap events - `liquidity_pools`: AMM pool information ## Continuous Integration & Deployment ZIndexer uses GitHub Actions for CI/CD: - **CI Workflow**: Automatically builds and tests the code on Ubuntu and macOS - **Lint Workflow**: Checks code formatting using `zig fmt` - **Release Workflow**: Creates binary releases when a new tag is pushed Status badges: ![Build Status](https://github.com/openSVM/zindexer/workflows/ZIndexer%20CI/badge.svg) ![Lint Status](https://github.com/openSVM/zindexer/workflows/ZIndexer%20Lint/badge.svg) ![Release Status](https://github.com/openSVM/zindexer/workflows/ZIndexer%20Release/badge.svg) ## License [MIT License](LICENSE)
https://avatars.githubusercontent.com/u/34946442?v=4
stitch
cryptocode/stitch
2023-03-26T17:04:23Z
Append resources to your executables
main
0
10
0
10
https://api.github.com/repos/cryptocode/stitch/tags
MIT
[ "zig", "zig-library", "zig-package" ]
35
false
2025-03-04T11:13:41Z
true
true
<img align="right" height="120" src="https://user-images.githubusercontent.com/34946442/232327201-294224c2-8502-423b-b2cb-663ca88ccfc1.png"> <img src="https://user-images.githubusercontent.com/34946442/230613201-60de5adc-6304-4f18-84d9-d36bb46fdc1f.svg" width="24" height="24">&nbsp; <img src="https://user-images.githubusercontent.com/34946442/230613198-ca5c938a-613b-412f-8d97-8ce8f19aeb1f.svg" width="24" height="24">&nbsp; <img src="https://user-images.githubusercontent.com/34946442/230613203-858cb471-2859-4e6e-8ef9-61b03c36c085.svg" width="24" height="24"> Stitch is a tool and library for Zig and C for adding and retrieving resources to and from executables. Why not just use `@embedFile` / `#embed`? Stitch serves a different purpose, namely to let build systems, and *users* of your software, create self-contained executables. For example, instead of requiring users to install an interpreter and execute `mylisp fib.lisp`, they can simply run `./fib` or `fib.exe` Resoures can be anything, such as scripts, images, text, templates config files and other executables. ## Some use cases * Self extracting tools, like an installer * Create executables for scripts written in your interpreted programming language * Include a sample config file, which is extracted on first run. The user can then edit this. * An image in your own format that's able to display itself when executed ## Building the project To build with Zig 0.13, use the `zig-<version>` tag/release. To build with Zig 0.14 or master, use the main branch (last tested with Zig version `0.14.0-dev.3470+711b0fef5`) `zig build` will put a `bin` and `lib` directory in your output folder (e.g. zig-out) * bin/stitch is a standalone tool for attaching resources to executables. This can also be done programmatically using the library * lib/libstitch is a library for reading attached resources from the current executable, and for adding resources to executables (like the standalone tool) ## Using the tool This example adds two scripts to a Lisp interpreter that supports, through the stitch library, reading embedded scripts: ```bash stitch ./mylisp std.lisp fib.lisp --output fib ./fib 8 21 ``` Resources can be named explicitly ```bash stitch ./mylisp std=std.lisp fibonacci=fib.lisp --output fib ``` If a name is not given, the filename (without path) is used. The stitch library supports finding resources by name or index. The `--output` flag is optional. By default, resources are added to the original executable (first argument) ## Stitching programmatically Let's say you want your interpreted programming language to support producing binaries. An easy way to do this is to create an interpreter executable that reads scripts attached to itself using stitch. You can provide interpreter binaries for all the OS'es you wanna support, or have the Zig build file do this if your user is building the interpreter. In the example below, a Lisp interpreter uses the stitch library to support creating self-contained executables: ```bash ./mylisp --create-exe sql-client.lisp --output sql-client ``` The resulting binary can now be executed: ``` ./sql-client ``` You can make the `mylisp` binary understand stitch attachments and then make a copy of it and stitch it with the scripts. Alternatively, you can have separate interpreter binaries specifically for reading stitched scripts. ## Using the library from C Include the `stitch.h` header and link to the library. Here's an example, using the included C test program: ```bash zig build-exe c-api/test/c-test.c -Lzig-out/lib -lstitch -Ic-api/include ./c-test ``` ## Binary layout The binary layout specification can be used by other tools that wants to parse files produced by Stitch, without using the Stitch library. [Specification](spec/README.md)
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
10
2
10
https://api.github.com/repos/lukeharwood11/openai-proxz/tags
MIT
[ "openai", "zig", "zig-package" ]
111
false
2025-04-05T16:01:42Z
true
true
<div align="center"> <h1>ProxZ</h1> <img src="https://img.shields.io/badge/zig-0.14.0-%23F7A41D?logo=zig&logoColor=%23F7A41D" /> <img src="https://img.shields.io/badge/zig-0.13.0-white?logo=zig&logoColor=white" /> <img src="https://img.shields.io/badge/License-MIT-blue" /> <br /> <br /> An OpenAI API library for the Zig programming language! </div> ## ⭐️ Features ⭐️ - An easy to use interface, similar to that of `openai-python` - Built-in retry logic - Environment variable config support for API keys, org. IDs, project IDs, and base urls - Response streaming support - Integration with the most popular OpenAI endpoints with a generic `request`/`requestStream` method for missing endpoints ## Installation To install the latest version of `proxz`, run ```bash zig fetch --save "git+https://github.com/lukeharwood11/openai-proxz" ``` To install a specific version, run ```bash zig fetch --save "https://github.com/lukeharwood11/openai-proxz/archive/refs/tags/<version>.tar.gz" ``` > [!NOTE] > To install the latest version compatible with Zig `v0.13.0`, use > > ```bash > zig fetch --save "https://github.com/lukeharwood11/openai-proxz/archive/refs/tags/v0.1.0.tar.gz" > ``` And add the following to your `build.zig` ```zig const proxz = b.dependency("proxz", .{ .target = target, .optimize = optimize, }); exe.root_module.addImport("proxz", proxz.module("proxz")); ``` ## Usage |✨ Documentation ✨|| |--|--| |πŸ“™ ProxZ Docs |<https://proxz.mle.academy> | |πŸ“— OpenAI API Docs|<https://platform.openai.com/docs/api-reference>| ### Client Configuration ```zig const proxz = @import("proxz"); const OpenAI = proxz.OpenAI; ``` ```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(); ``` ### Chat Completions #### Regular ```zig const ChatMessage = proxz.ChatMessage; var response = try openai.chat.completions.create(.{ .model = "gpt-4o", .messages = &[_]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 = &[_]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 ```zig const inputs = [_][]const u8{ "Hello", "Foo", "Bar" }; const response = try openai.embeddings.create(.{ .model = "text-embedding-3-small", .input = &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, }); ``` ### Models #### Get model details ```zig var response = try openai.models.retrieve("gpt-4o"); defer response.deinit(); std.log.debug("Model is owned by '{s}'", .{response.owned_by}); ``` #### List all models ```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}) ``` ## Configuring Logging By default all logs are enabled for your entire application. To configure your application, and set the log level for `proxz`, include the following in your `main.zig`. ```zig pub const std_options = std.Options{ .log_level = .debug, // this sets your app level log config .log_scope_levels = &[_]std.log.ScopeLevel{ .{ .scope = .proxz, .level = .info, // set to .debug, .warn, .info, or .err }, }, }; ``` All logs in `proxz` use the scope `.proxz`, so if you don't want to see debug/info logs of the requests being sent, set `.level = .err`. This will only display when an error occurs that `proxz` 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 ```bash zig build docs ```
https://avatars.githubusercontent.com/u/379570?v=4
iter-zig
eldesh/iter-zig
2022-08-06T11:43:58Z
A basic iterator library written in Zig
master
1
10
3
10
https://api.github.com/repos/eldesh/iter-zig/tags
BSD-2-Clause
[ "zig-package" ]
332
false
2024-08-02T22:56:00Z
true
false
# iter-zig **iter-zig** is a lazy style generic iterator combinator library written in Zig. Where the *iterator* means that the types enumrating all element of a set of values. ## Support This library is developped with: - Debian (x86_64) 10.4 - Zig 0.10.0 and Zigmod r80 - Zig 0.9.1 and Zigmod r79 ## Build ```sh zig build ``` ## Unit Test To performs unit tests of iter-zig: ```sh zig build test ``` ## Example An example program using iter-zig is provided. The program can be performed with: ```sh zig build example ``` Source code of this program is `src/main.zig`. ## Generate docs To generate documentations: ```sh zig build doc ``` A html documents would be generated under the `./docs` directory. ## Iterator Concept **Iterator** is a generic concept that objects that enumrating a set of values. Especially, in this library, Iterator is a value of a kind of types that satisfies follow constraints. The constraints are: - Have `Self` type - Have `Item` type - Have `next` method takes `*Self` and returns `?Item`. Where the `Self` type specifies the type itself (equals to `@This()`), the `Item` type represents the type of elements returns from the iterator, and the `next` method returns a 'next' value of the container. If the next value is not exists, 'null' must be returned. The order of occurence of values are implementation defined. However, all values must occur exactly once before 'null' is returned. ## Features ### Meta function [The type constraints required as an Iterator](#iterator-concept) is able to be checked by `isIterator` function statically. ```zig comptime assert(isIterator(SliceIter(u32))); comptime assert(!isIterator(u32)); ``` When you implement a new type to be an iterator, it must ensure that `isIterator` returns `true`. ### Container Iterators **iter-zig** provides several basic iterators that wraps standard containers. - ArrayIter - SliceIter - ArrayListIter - SinglyLinkedListIter - BoundedArrayIter - TailQueueIter For example, an iterator on a slice is able to be used as follows: ```zig var arr = [_]u32{ 1, 2, 3 }; var iter = SliceIter(u32).new(arr[0..]); try expectEqual(@as(u32, 1), iter.next().?.*); try expectEqual(@as(u32, 2), iter.next().?.*); try expectEqual(@as(u32, 3), iter.next().?.*); try expectEqual(@as(?*u32, null), iter.next()); ``` Further, `Const` variations are defined for each containers. These iterators behaves as same to non-const variations except for returns const pointers. - ArrayConstIter - SliceConstIter - ArrayListConstIter - SinglyLinkedListConstIter - BoundedArrayConstIter - TailQueueConstIter ```zig var arr = [_]u32{ 1, 2, 3 }; var iter = SliceConstIter(u32).new(arr[0..]); iter.next().?.* += 1; // error: cannot assign to constant ``` Note that, these iterators not own container values into it. The user must release the memory holding the container if necessary. ### Iterators to Containers Iterator to container converters are defined for some std containers. - slice_from_iter - array_list_from_iter - bounded_array_from_iter - singly_linked_list_from_iter These converters consume the input iterator and build a container. The constructed container contains all the elements of the iterator and no other elements. ### Range Iterator `range` creates a Range value such that it represents a range of numbers. For example, `range(0, 10)` means that the numbers from `0` to `10`, which is mathematics is denoted as `[0,10)`. In particular, Range instantiated with integral type to be iterator. ```zig var rng = range(@as(u32, 0), 3); try expectEqual(@as(u32, 0), rng.next().?); try expectEqual(@as(u32, 1), rng.next().?); try expectEqual(@as(u32, 2), rng.next().?); try expectEqual(@as(?u32, null), rng.next()); ``` Similarly, `range_from` creates an instance of `RangeFrom` to represents an endless sequence of numbers. e.g. `range_from(@as(u32, 0))` creates an endless sequence of natural numbers `0,1,2,...`. ```zig var rng = range_from(@as(u32, 0)); try expectEqual(@as(u32, 0), rng.next().?); try expectEqual(@as(u32, 1), rng.next().?); try expectEqual(@as(u32, 2), rng.next().?); .. ``` When `Range` or `RangeFrom` is instantiated with a type of floating numbers, it would not be an Iterator. It is just a range of values. ```zig comptime assert(!concept.isIterator(range.Range(f64))); comptime assert(!concept.isIterator(range.RangeFrom(f64))); comptime assert( range.range(@as(f64, 2.0), 3.0).contains(2.5)) comptime assert(!range.range(@as(f64, 2.0), 3.0).contains(1.5)) ``` ### Iterator Operators All iterators defined in this library provide iterator functions below. - peekable - position - cycle - copied - cloned - nth - last - flat_map - flatten - partial_cmp - cmp - le - ge - lt - gt - sum - product - eq - ne - max - max_by - max_by_key - min - min_by - min_by_key - reduce - skip - scan - step_by - fold - try_fold - try_foreach - for_each - take_while - skip_while - map - map_while - filter - filter_map - chain - enumerate - all - any - take - count - find - find_map - inspect - fuse - zip These functions are almost same to [functions on Iterator trait of Rust](https://doc.rust-lang.org/std/iter/trait.Iterator.html) except for experimental api. #### Adaptor style iterator Some functions above return an iterator from the iterator itself. For that case, the functions are implemented in adaptor style. For example, the `map` function returns a new iterator object `Map` rather than apply a function to each elements from the iterator. ```zig var arr = [_]u32{ 1, 2, 3 }; var iter = SliceIter(u32).new(arr[0..]); fn incr(x:u32) u32 { return x+1; } // Calculations have not yet been performed. var map: Map(SliceIter(u32), fn (u32) u32) = iter.map(incr); try expectEqual(@as(u32, 2), map.next().?.*); // incr is performed try expectEqual(@as(u32, 3), map.next().?.*); // incr is performed try expectEqual(@as(u32, 4), map.next().?.*); // incr is performed try expectEqual(@as(?*u32, null), map.next()); ``` ### Implementing Iterator **iter-zig** allows library users to implement a new iterator type by their self. Further, it is easy to implement all functions showed in [Iterator Operators](#iterator-operators) to your new iterator type using `DeriveIterator`. For example, let's make an iterator `Counter` which counts from `1` to `5`. ```zig const Counter = struct { pub const Self = @This(); pub const Item = u32; count: u32, pub fn new() Self { return .{ .count = 0 }; } pub fn next(self: *Self) ?Item { self.count += 1; if (self.count < 6) return self.count; return null; } }; ``` Now we can use it as an iterator. ```zig comptime assert(isIterator(Counter)); var counter = Counter.new(); try expectEqual(@as(u32, 1), counter.next().?); try expectEqual(@as(u32, 2), counter.next().?); try expectEqual(@as(u32, 3), counter.next().?); try expectEqual(@as(u32, 4), counter.next().?); try expectEqual(@as(u32, 5), counter.next().?); try expectEqual(@as(?u32, null), counter.next()); ``` However, `Counter` not implement utility functions like `map` or `count` etc ... To implement these functions, use `DeriveIterator` meta function like below. ```zig const CounterExt = struct { pub const Self = @This(); pub const Item = u32; pub usingnamespace DeriveIterator(@This()); // Add count: u32, pub fn new() Self { return .{ .count = 0 }; } pub fn next(self: *Self) ?Item { self.count += 1; if (self.count < 6) return self.count; return null; } }; ``` In above code, `CounterExt` difference from `Counter` is only the `DeriveIterator(@This())` line. Now, you can use all functions showed in [Iterator Operators](#iterator-operators). ```zig fn incr(x:u32) u32 { return x+1; } fn even(x:u32) bool { return x % 2 == 0; } fn sum(st:*u32, v:u32) ?u32 { st.* += v; return st.*; } var counter = CounterExt.new(); var iter = counter .map(incr) // 2,3,4,5,6 .filter(even) // 2,4,6 .scan(@as(u32, 0), sum); // 2,6,12 try expectEqual(@as(u32, 2), iter.next().?); try expectEqual(@as(u32, 6), iter.next().?); try expectEqual(@as(u32, 12), iter.next().?); try expectEqual(@as(?u32, null), iter.next()); ``` If you can implement some method efficiently rather than using `next` method, just implement that method (in `CounterExt` in the above). `DeriveIterator` suppresses the generation of that function. #### Convention **iter-zig** adopts naming conventions for implementing iterators. First, when defining a new iterator type, the type constructor must be named `MakeT` where type `T` is a name of the type. And the constructor should take a `Derive` function like below. ```zig pub fn MakeCounter(comptime Derive: fn (type) type) type { return struct { pub const Self = @This(); pub const Item = u32; pub usingnamespace Derive(@This()); count: u32, pub fn next(self: *Self) ?Item { ... } }; } ``` This allows users to switch the function used for deriving. Second, a type constructor should be named `T`. And the constructor should forward `DeriveIterator` to `MakeT`. ```zig pub fn Counter() type { return MakeCounter(DeriveIterator); } ```
https://avatars.githubusercontent.com/u/20110944?v=4
zoridor
ringtailsoftware/zoridor
2024-11-24T08:30:36Z
A Quoridor game for terminal and web
main
0
10
1
10
https://api.github.com/repos/ringtailsoftware/zoridor/tags
MIT
[ "game", "quoridor", "zig", "zig-package" ]
1,709
false
2025-02-15T10:35:46Z
true
true
# Zoridor A terminal and web version of the [Quoridor](https://en.wikipedia.org/wiki/Quoridor) board game [WASM4](https://wasm4.org/) version on [wasm4 branch](https://github.com/ringtailsoftware/zoridor/tree/wasm4). Play on the web at https://ringtailsoftware.github.io/zoridor/ Or play the WASM4 cart at https://ringtailsoftware.github.io/zoridor/cart.html ![](doc/demo.gif) Quoridor tutorials: - https://www.youtube.com/watch?v=39T3L6hNfmg - https://www.youtube.com/watch?v=FDdm-EgRy9g - https://www.youtube.com/watch?v=6ISruhN0Hc0 # Running Get [Zig](https://ziglang.org/download/) Terminal version: zig build run Web version: zig build -Dweb=true && zig build serve -- zig-out -p 8000 Browse to http://localhost:8000 # Development Auto-rebuild and reload on change watchexec -r --stop-signal SIGKILL -e zig,html,css,js,zon -w src 'zig build -Dweb=true && zig build serve -- zig-out -p 8000' # Terminal mode controls - You are Player 1. Your objective is to move your red pawn from the top of the board to the bottom of the board - Player 2 starts at the bottom and is attempting to reach the top of the board - On each turn you can either move your pawn or add one fence piece to the board (you have 10 to start with) ## Moving a pawn - Use the cursor keys to choose where to move to. Your pawn may only move one square on each turn and cannot move diagonally - The "[ ]" mark where your pawn will move and is coloured green for a valid move and red for invalid - Once you have selected a move, press enter to move the pawn ## Adding a fence - Press tab to switch from pawn to fence mode - Use the cursor keys to choose where to add the fence - Fences must not cross other fences, or completely block either player from reaching their goal. An invalid fence position will be shown in red - To rotate the fence, press space - Once you have positioned the fence, press enter to place it # Command line options Help zig build run -- -h To watch machine vs machine matches forever: zig build run -- -1 machine -2 machine -f On exit, a record of all moves is printed in both Glendenning format and base64. The base64 format can be reloaded with `zig build run -- -l jcNJujqxKRY2sA==` # Theory For a comprehensive examination of playing Quoridor, see [Lisa Glendenning's Thesis](https://www.labri.fr/perso/renault/working/teaching/projets/files/glendenning_ugrad_thesis.pdf)
https://avatars.githubusercontent.com/u/231785?v=4
runeset
mnemnion/runeset
2024-05-27T17:25:59Z
Fast UTF-8 codepoint sets for Zig.
trunk
0
10
0
10
https://api.github.com/repos/mnemnion/runeset/tags
MIT
[ "parsing", "sets", "utf-8", "zig", "zig-package" ]
48,630
false
2025-03-17T16:57:42Z
true
true
# Runeset: Sets of UTF-8 Characters This library offers a compact data structure for "generalized"[^1] UTF-8 encoded codepoints. The design is based on an [implicit data structure](https://en.wikipedia.org/wiki/Implicit_data_structure)[^2], which uses `@popCount` and bit masking to check membership quickly, with minimal branching, and without having to decode the UTF-8 into another format (for instance, a codepoint). This design is original, in the sense that I invented it. There may be prior art, it's remarkably difficult to search for "UTF-8 character sets" and find papers on set data structures, so I can't say with high confidence that it's truly novel; in a sense, it's an obvious extension of the widespread practice of using a pair of `u64` bitmasks to detect a set of ASCII values. What I can say is: it's effective. The `RuneSet` struct is just a slice of `u64`, offering a few variations on set membership tests, depending on how confident you are that the string it's testing is valid UTF-8, and what you would like the test to do in the event that it isn't. Also supported are the fundamental set operations: equality, subset, union, intersection, and difference. All of the three combining forms produce a new `RuneSet`, and must be given an `Allocator`. The `RuneSet` is immutable by design, and as such, doesn't support adding or removing codepoints to an already-created set. This would be possible to implement in principle, but I don't happen to have a use for mutable adds and removes, and therefore didn't write them. You can create a `RuneSet` containing a single character, and via union or difference, either add or subtract that character, if you would like: this would create a new `RuneSet` with just that character added or removed. The data structure is very fast. The test suite, with extensions, contains 5MB of sample data, with a 20MB extra collection, and performs a multitude of operations on that data, on the order of a dozen per string. In ReleaseFast mode, the main suite of 5MB concludes in roughly a second on an M1. With the annex, including fuzzing the creation function 2^24 times, a complete run is over in six seconds, give or take a few milli. About 2/3rds of that is the fuzzing. While I have yet to set up definitive benchmarks, it's clear that membership testing using `RuneSet` has a throughput over 100 MB/sec on modern machines, potentially substantially higher than this. I'll update this with better numbers when I get around to benchmarking it; the focus has been on implementing the library, and assuring good test coverage. For real character sets, it is also quite sparing of memory. The CJK Ideographs block of Unicode, consisting of 22,992 codepoints, is represented as a `RuneSet` in 338 words. Dense ranges such as that block can of course be tested by decoding the tested sequence into a codepoint and checking if it's in that range, but the combination of generality, compactness, and speed, offered by the `RuneSet`, is unique. Speaking of test coverage, the library has 100% line coverage, which you may verify by running `zig build cov`, provided you have [kcov](https://github.com/SimonKagstrom/kcov) installed. To run the extended suite, including the fuzzer, use `zig build -Dtest-more test`. This will take an appreciable amount of time in the default debug-mode builds, as it will trigger the 244 assertions which gird the library. ## Roadmap I intend to add some ability to write out the data structure, whether as binary data, Zig source code, or potentially both. As an allocating data structure, it isn't currently possible to generate a RuneSet at comptime, and many applications of them will use character sets known in advance, which may as well be built into the `.rodata` of programs, rather than constructed at runtime from strings. I also plan to wrap all of the major functionality in C-compatible data structures and functions, for use wherever the C ABI is spoken. Other than that, I consider the library fully implemented and feature-complete. Odds are good, however, that more open-source code, which makes use of the RuneSet as a foundation, will be forthcoming. [^1]: Generalized, here, has a similar meaning to its use in [WTF-8](https://simonsapin.github.io/wtf-8/), except that `RuneSet` can also encode so-called "overlong" encodings, as well as surrogates (paired vs. unpaired is a meaningless distinction for a codepoint set). This falls out of the design: it's capable of encoding those sequences, and I saw no reason to impose a performance burden in order to prevent it. On the contrary, should you want to represent the set of all overlong encodings, perhaps to detect them and raise an error, a `RuneSet` is a fine way to do it. A set which does not contain overlong encodings or surrogates will never match against them, so this seeming laxity comes with no disadvantages. The five- and six-byte sequences from Pike and Thompson's original FSS UTF-8 of 1993 are not supported. As such, what would constitute lead bytes for those sequences are rejected as invalid. It would be possible to extend the `RuneSet` data structure to include these, if there were ever any point in so doing. [^2]: That the `RuneSet` is 'implicit' doesn't make it the smallest possible encoding for every subset of UTF-8. For example, the CJK Unified Ideographs block could be represented as two numbers, and for some crafted inputs, such as one in 64 characters throughout the Unicode range, a bitmask of one bit per character would be smaller as well. It means that the structure is implicit to the data, without indirection, and that in full generality it isn't possible to represent UTF-8 sequences more compactly, compared to the information theoretic lower-bound. Our overhead is limited to one word, used to store one of the offsets as an important optimization.
https://avatars.githubusercontent.com/u/1552770?v=4
notcurses-zig
neurocyte/notcurses-zig
2023-03-25T14:23:35Z
Zig bindings and packaging for notcurses
master
0
10
1
10
https://api.github.com/repos/neurocyte/notcurses-zig/tags
MIT
[ "tui", "zig", "zig-package" ]
29
false
2025-03-20T12:52:26Z
true
true
# Zig bindings and package for notcurses This package provides build scripts and basic (WIP) bindings for building notcurses applications in Zig. See `src/ncinputtest.zig` for a basic example application. Should generally build with zig nightly.
https://avatars.githubusercontent.com/u/231785?v=4
ztap
mnemnion/ztap
2024-09-12T01:42:44Z
ZTAP: TAP producer for zig build test
trunk
0
10
1
10
https://api.github.com/repos/mnemnion/ztap/tags
MIT
[ "tap", "testing", "zig", "zig-package" ]
30
false
2025-04-01T02:30:20Z
true
true
# ZTAP The [Test Anything Protocol](https://testanything.org/) is a simple, venerable, and widely-used format for reporting the output of tests. ZTAP is a Zig library for running and reporting tests in the TAP 14 format. ## Compatibility ZTAP requires Zig 0.14. ## Use This can be used as the main unit testing step, or as a custom step. Instructions will assume the latter, but are easily adapted for the former case. Add to `build.zig.zon` in the usual fashion: ```sh zig fetch --save "https://github.com/mnemnion/ztap/archive/refs/tags/v0.9.0.tar.gz" ``` You'll need a test runner Γ  la `src/ztap-runner.zig`: ```zig const std = @import("std"); const builtin = @import("builtin"); const ztap = @import("ztap"); // This gives TAP-compatible panic handling pub const panic = std.debug.FullPanic(ztap.ztap_panic); pub fn main() !void { ztap.ztap_test(builtin); std.process.exit(0); } ``` Do be sure to exit with `0`, since the protocol interprets non-zero as a test failure. Add something of this nature to `build.zig`: ```zig // ZTAP test runner step. const ztap_unit_tests = b.addTest(.{ .name = "ztap-run", .root_source_file = b.path("src/test-root-file.zig"), .target = target, .optimize = optimize, .test_runner = .{ .path = b.path("src/ztap-runner.zig"), .mode = .simple }, }); // To put the runner in zig-out etc. b.installArtifact(ztap_unit_tests); const run_ztap_tests = b.addRunArtifact(ztap_unit_tests); // To unilaterally run tests, add this: run_ztap_tests.has_side_effects = true; if (b.lazyDependency("ztap", .{ .target = target, .optimize = optimize, })) |ztap_dep| { ztap_unit_tests.root_module.addImport("ztap", ztap_dep.module("ztap")); } const ztap_step = b.step("ztap", "Run tests with ZTAP"); ztap_step.dependOn(&run_ztap_tests.step); ``` That should do the trick. See the first link for an example of what to expect in the way of output. ## Use Notes ZTAP is simply an output format for Zig's test system, and no changes should be necessary to use it as such. If `error.SkipZigTest` is returned, ZTAP will issue the `# Skip` directive. Zig doesn't support a TODO for tests (not that it should necessarily), but TAP does, so if `error.ZTapTodo` is returned, ZTAP will issue `# Todo`. Zig's test runner will treat the latter as any other error. In the event that Zig adds a TODO error to the test system, ZTAP will support that also. The `ztap_panic` function will add a comment to the TAP output naming the test, and issue the `Bail out!` directive which is proper for a fatal error. It then calls the default panic handler, which does the accustomed things using `stderr`. ## Roadmap ZTAP does what it needs to. My intention is to use it (use by others is encouraged as well) until I'm fairly convinced it does nothing weird or untoward, or until six months have passed, whichever is longer. It will then be declared 1.0 and will not change further unless TAP, or Zig, require it to. No changes to the interface at any of these points are likely. ### Why Though? Everything speaks TAP. CI speaks TAP, distros speak TAP, your editor speaks TAP. If you find yourself wanting to integrate with some or all of these things, ZTAP will TAP your Zig. Also, if you print to `stdout`, ZTAP will not hang your unit tests. That doesn't make it a good idea, TAP harnesses ignore what they don't grok, but it can't help things, and it can screw them up. It does mean that tests will complete in the event that `stdout` is printed to.
https://avatars.githubusercontent.com/u/5464072?v=4
zig-mime
nektro/zig-mime
2023-02-28T04:18:01Z
No Description
main
0
10
1
10
https://api.github.com/repos/nektro/zig-mime/tags
None
[ "zig", "zig-package" ]
18
false
2025-02-16T06:11:12Z
true
false
# zig-mime
https://avatars.githubusercontent.com/u/124872?v=4
zig-bounded-array
jedisct1/zig-bounded-array
2023-11-22T17:18:28Z
BoundedArray module for Zig.
main
0
9
0
9
https://api.github.com/repos/jedisct1/zig-bounded-array/tags
MIT
[ "array", "arrayvec", "bounded", "boundedarray", "tinyvec", "zig", "zig-lib", "zig-package", "ziglang" ]
10
false
2025-02-22T18:59:02Z
true
true
# BoundedArray for Zig A `BoundedArray` is a structure containing a fixed-size array, as well as the length currently being used. It can be used as a variable-length array that can be freely resized up to the size of the backing array. If you're looking for a Zig equivalent to Rust's super useful `ArrayVec`, this is it. It is useful to pass around small arrays whose exact size is only known at runtime, but whose maximum size is known at comptime, without requiring an `Allocator`. Bounded arrays are easier and safer to use than maintaining buffers and active lengths separately, or involving structures that include pointers. They can also be safely copied like any value, as they don't use any internal pointers. ```zig var actual_size = 32; var a = try BoundedArray(u8, 64).init(actual_size); var slice = a.slice(); // a slice of the 64-byte array var a_clone = a; // creates a copy - the structure doesn't use any internal pointers ``` # Update: archived. The main point of that fork was to keep the length being a `usize`, because returning a different type was a footgun (adding lengths, in particular, could easily trigger an overflow). However, that change was eventually [reverted](https://github.com/ziglang/zig/commit/85747b266aac8a2ff7fea4a4b18f722133544ad7), so applications should just go back to using the type from the standard library.