avatar_url
stringlengths 46
116
⌀ | name
stringlengths 1
46
| full_name
stringlengths 7
60
| created_at
stringdate 2016-04-01 08:17:56
2025-05-20 11:38:17
| description
stringlengths 0
387
⌀ | default_branch
stringclasses 45
values | open_issues
int64 0
4.93k
| stargazers_count
int64 0
78.2k
| forks_count
int64 0
3.09k
| watchers_count
int64 0
78.2k
| tags_url
stringlengths 0
94
| license
stringclasses 27
values | topics
listlengths 0
20
| size
int64 0
4.82M
| fork
bool 2
classes | updated_at
stringdate 2018-11-13 14:41:18
2025-05-22 08:23:54
| has_build_zig
bool 2
classes | has_build_zig_zon
bool 2
classes | zig_minimum_version
stringclasses 60
values | repo_from
stringclasses 3
values | dependencies
listlengths 0
121
| readme_content
stringlengths 0
437k
| dependents
listlengths 0
21
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://avatars.githubusercontent.com/u/107726195?v=4 | zig-nds | zig-homebrew/zig-nds | 2022-06-18T18:57:30Z | Starter pack for developing NDS games/applications with Zig | master | 1 | 8 | 0 | 8 | https://api.github.com/repos/zig-homebrew/zig-nds/tags | - | [
"devkitpro",
"nds",
"zig"
]
| 8 | false | 2025-01-08T23:39:48Z | true | false | unknown | github | []
| zig-nds
Getting started
<ul>
<li><a>zig</a></li>
<li><a>devkitPro</a></li>
</ul>
<code>pacman -S nds-dev
git clone https://github.com/zig-homebrew/zig-nds
cd zig-nds/
zig build # then run zig-out/zig-nds.nds with desmume</code>
Resources
<ul>
<li><a>nds-examples</a></li>
<li><a>libnds repository</a></li>
<li><a>libnds documentation</a></li>
<li><a>GBATEK</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/7449346?v=4 | zwm | zuranthus/zwm | 2022-06-25T16:22:17Z | A minimal tiling window manager for Linux written in Zig | main | 0 | 8 | 2 | 8 | https://api.github.com/repos/zuranthus/zwm/tags | MIT | [
"linux",
"tiling-window-manager",
"window-manager",
"x11",
"zig"
]
| 147 | false | 2025-05-09T07:49:37Z | true | false | unknown | github | []
| <code>███████╗██╗ ██╗███╗ ███╗
╚══███╔╝██║ ██║████╗ ████║
███╔╝ ██║ █╗ ██║██╔████╔██║
███╔╝ ██║███╗██║██║╚██╔╝██║
███████╗╚███╔███╔╝██║ ╚═╝ ██║
╚══════╝ ╚══╝╚══╝ ╚═╝ ╚═╝</code>
Zwm is a dwm-inspired minimal tiling window manager for X implemented in Zig programming language.
My main goals for creating Zwm are learning Zig and implementing a minimal window manager for personal use
that is easier to hack than dwm. Both goals are work in progress :)
Current state
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Basic tiling layout
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Workspaces (tags)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Focus and window management commands
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Spawn process command
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Customizable config file
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Hot reloading with persisted state (requires a <a>script</a>)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Support for external status bar, like <a>Polybar</a>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Floating windows
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Fullscreen windows
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> ICCCM and EWMH support
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> "Urgency"/"Demands attention" window state
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Multi-monitor support
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Support for adding new layouts
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> More built-in layouts: fullscreen, 3-column, ...
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Iron out issues with focus, window management, and general UX
Installation
You will need at least git and zig installed.
<code>bash
git clone https://github.com/zuranthus/zwm.git
cd zwm
sudo zig build install -p /usr/local</code>
Configuration
Modify <code>src/config.zig</code> before building and installing.
Usage
The easiest way is to start zwm with <code>startx</code> by adding <code>exec zwm</code> to <code>~/.xinitrc</code>.
Hot Reloading
It is possible to restart zwm while keeping windows and their workspace distribution intact. This makes updating zwm binary a quick and painless process.
Enabling hot reloading is easy: use the following script in <code>~/.xinitrc</code> instead of a simple <code>exec zwm</code>
<code>bash
while :
do
zwm
[[ $? == 42 ]] || break;
done</code>
Now if you build and install a new zwm build, restart zwm with <code>Mod + Shift + Q</code> (configurable in <code>src/config.zig</code>). Voilà: you are running the new build and all windows are alive and in their workspaces. | []
|
https://avatars.githubusercontent.com/u/9960133?v=4 | visual-zig-nuttx | lupyuen/visual-zig-nuttx | 2022-07-17T06:04:11Z | Visual Programming for Zig with NuttX Sensors | main | 0 | 8 | 1 | 8 | https://api.github.com/repos/lupyuen/visual-zig-nuttx/tags | Apache-2.0 | [
"bl602",
"bl604",
"blockly",
"bme280",
"nuttx",
"pinecone",
"pinedio",
"riscv32",
"sensor",
"zig"
]
| 386 | false | 2023-08-10T22:37:04Z | false | false | unknown | github | []
|
Visual Programming for Zig with NuttX Sensors
Read the articles...
<ul>
<li>
<a>"Visual Programming with Zig and NuttX Sensors"</a>
</li>
<li>
<a>"Zig Visual Programming with Blockly"</a>
</li>
<li>
<a>"Read NuttX Sensor Data with Zig"</a>
</li>
</ul>
Can we use Scratch / <a>Blockly</a> to code Zig programs, the drag-n-drop way?
Let's create a Visual Programming Tool for Zig that will generate IoT Sensor Apps with Apache NuttX RTOS.
<em>Why limit to IoT Sensor Apps?</em>
<ul>
<li>
Types are simpler: Only floating-point numbers will be supported, no strings needed
</li>
<li>
Blockly is Typeless. With Zig we can use Type Inference to deduce the missing Struct Types
</li>
<li>
Make it easier to experiment with various IoT Sensors: Temperature, Humidity, Air Pressure, ...
</li>
</ul>
<a>Blockly Source Code: lupyuen3/blockly-zig-nuttx</a>
Sensor Test App in C
We start with the Sensor Test App (in C) from Apache NuttX RTOS: <a>sensortest.c</a>
Here are the steps for reading a NuttX Sensor...
```c
// From https://lupyuen.github.io/articles/bme280#sensor-test-app
// Open the Sensor Device.
// devname looks like "/dev/uorb/sensor_baro0" or "/dev/uorb/sensor_humi0"
fd = open(devname, O_RDONLY | O_NONBLOCK);
// Set Standby Interval
ioctl(fd, SNIOC_SET_INTERVAL, interval);
// Set Batch Latency
ioctl(fd, SNIOC_BATCH, latency);
// If Sensor Data is available...
if (poll(&fds, 1, -1) > 0) {
// Read the Sensor Data
if (read(fd, buffer, len) >= len) {
<code>// Cast buffer as Barometer Sensor Data
struct sensor_event_baro *event =
(struct sensor_event_baro *) buffer;
// Handle Pressure and Temperature
printf(
"%s: timestamp:%d value1:%.2f value2:%.2f\n",
name,
event.timestamp,
event.pressure,
event.temperature
);
</code>
}
}
// Close the Sensor Device and free the buffer
close(fd);
free(buffer);
```
<a>(Source)</a>
NuttX compiles the Sensor Test App <a>sensortest.c</a> with this GCC command...
```bash
App Source Directory
cd $HOME/nuttx/apps/testing/sensortest
Compile sensortest.c with GCC
riscv64-unknown-elf-gcc \
-c \
-fno-common \
-Wall \
-Wstrict-prototypes \
-Wshadow \
-Wundef \
-Os \
-fno-strict-aliasing \
-fomit-frame-pointer \
-fstack-protector-all \
-ffunction-sections \
-fdata-sections \
-g \
-march=rv32imafc \
-mabi=ilp32f \
-mno-relax \
-isystem "$HOME/nuttx/nuttx/include" \
-D__NuttX__ \
-DNDEBUG \
-DARCH_RISCV \
-pipe \
-I "$HOME/nuttx/apps/include" \
-Dmain=sensortest_main \
sensortest.c \
-o sensortest.c.home.user.nuttx.apps.testing.sensortest.o
```
(Observed from <code>make --trace</code>)
Let's convert the Sensor Test App from C to Zig...
Auto-Translate Sensor App to Zig
The Zig Compiler can auto-translate C code to Zig. <a>(See this)</a>
Here's how we auto-translate our Sensor App <a>sensortest.c</a> from C to Zig...
<ul>
<li>
Take the GCC command from above
</li>
<li>
Change <code>riscv64-unknown-elf-gcc</code> to <code>zig translate-c</code>
</li>
<li>
Add the target <code>-target riscv32-freestanding-none -mcpu=baseline_rv32-d</code>
</li>
<li>
Remove <code>-march=rv32imafc</code>
</li>
<li>
Surround the C Flags by <code>-cflags</code> ... <code>--</code>
</li>
</ul>
Like this...
```bash
App Source Directory
cd $HOME/nuttx/apps/testing/sensortest
Auto-translate sensortest.c from C to Zig
zig translate-c \
-target riscv32-freestanding-none \
-mcpu=baseline_rv32-d \
-cflags \
-fno-common \
-Wall \
-Wstrict-prototypes \
-Wshadow \
-Wundef \
-Os \
-fno-strict-aliasing \
-fomit-frame-pointer \
-fstack-protector-all \
-ffunction-sections \
-fdata-sections \
-g \
-mabi=ilp32f \
-mno-relax \
-- \
-isystem "$HOME/nuttx/nuttx/include" \
-D__NuttX__ \
-DNDEBUG \
-DARCH_RISCV \
-I "$HOME/nuttx/apps/include" \
-Dmain=sensortest_main \
sensortest.c \
<blockquote>
sensortest.zig
```
</blockquote>
To fix the translation (Zig Translate doesn't support <code>goto</code>) we need to insert this...
```c
ifdef <strong>clang</strong> // Workaround for zig cc
include
include "../../nuttx/include/limits.h"
define goto return ret;
define name_err
define open_err
define ctl_err
endif // <strong>clang</strong>
```
<a>(Source)</a>
And change this...
```c
ifndef <strong>clang</strong> // Workaround for NuttX with zig cc
ctl_err:
endif // !<strong>clang</strong>
close(fd);
ifndef <strong>clang</strong> // Workaround for NuttX with zig cc
open_err:
endif // !<strong>clang</strong>
free(buffer);
ifndef <strong>clang</strong> // Workaround for NuttX with zig cc
name_err:
endif // !<strong>clang</strong>
```
<a>(Source)</a>
<a>(See the changes)</a>
Here's the original C code: <a>sensortest.c</a>
And the auto-translation from C to Zig: <a>translated/sensortest.zig</a>
Sensor App in Zig
We copy the relevant snippets from the Auto-Translation to create our Zig Sensor App: <a>sensortest.zig</a>
https://github.com/lupyuen/visual-zig-nuttx/blob/0d3617dbcae5ae9836b5a70ba2026c75e12a00ce/sensortest.zig#L32-L417
Then we compile our Zig Sensor App...
```bash
Download our Zig Sensor App for NuttX
git clone --recursive https://github.com/lupyuen/visual-zig-nuttx
cd visual-zig-nuttx
Compile the Zig App for BL602 (RV32IMACF with Hardware Floating-Point)
zig build-obj \
--verbose-cimport \
-target riscv32-freestanding-none \
-mcpu=baseline_rv32-d \
-isystem "$HOME/nuttx/nuttx/include" \
-I "$HOME/nuttx/apps/include" \
sensortest.zig
Patch the ELF Header of <code>sensortest.o</code> from Soft-Float ABI to Hard-Float ABI
xxd -c 1 sensortest.o \
| sed 's/00000024: 01/00000024: 03/' \
| xxd -r -c 1 - sensortest2.o
cp sensortest2.o sensortest.o
Copy the compiled app to NuttX and overwrite <code>sensortest.o</code>
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cp sensortest.o $HOME/nuttx/apps/testing/sensortest/sensortest*.o
Build NuttX to link the Zig Object from <code>sensortest.o</code>
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cd $HOME/nuttx/nuttx
make
```
Connect BME280 Sensor
For testing the Zig Sensor App, we connect the BME280 Sensor (Temperature / Humidity / Air Pressure) to Pine64's <a><strong>PineCone BL602 Board</strong></a>...
| BL602 Pin | BME280 Pin | Wire Colour
|:---:|:---:|:---|
| <strong><code>GPIO 1</code></strong> | <code>SDA</code> | Green
| <strong><code>GPIO 2</code></strong> | <code>SCL</code> | Blue
| <strong><code>3V3</code></strong> | <code>3.3V</code> | Red
| <strong><code>GND</code></strong> | <code>GND</code> | Black
Run Zig Sensor App
To read the BME280 Sensor, let's run the Zig Sensor App: <a>sensortest.zig</a>
First we read the Humidity with our Zig Sensor App...
<code>bash
NuttShell (NSH) NuttX-10.3.0
nsh> sensortest -n 1 humi0
Zig Sensor Test
bme280_fetch: temperature=30.520000 °C, pressure=1027.211548 mbar, humidity=72.229492 %
humi0: timestamp:109080000 value:72.23</code>
<a>(See the complete log)</a>
Our Zig App returns the correct Humidity (<code>value</code>): 72 %.
Next we read the Temperature and Air Pressure with our Zig Sensor App...
<code>bash
nsh> sensortest -n 1 baro0
Zig Sensor Test
bme280_fetch: temperature=30.520000 °C, pressure=1029.177490 mbar, humidity=72.184570 %
baro0: timestamp:78490000 value1:72.18 value2:72.18</code>
<a>(See the complete log)</a>
This shows that the BME280 Driver has fetched the correct Temperature (30 °C), Pressure (1,029 mbar) and Humidity (72 %).
But our Zig App returns both Pressure (<code>value1</code>) and Temperature (<code>value2</code>) as 72. Which is incorrect.
Compare the above output with the original C Version of the Sensor App: <a>sensortest.c</a>
```bash
nsh> sensortest -n 1 humi0
bme280_fetch: temperature=30.690001 °C, pressure=1027.283447 mbar, humidity=72.280273 %
humi0: timestamp:26000000 value:72.28
nsh> sensortest -n 1 baro0
bme280_fetch: temperature=30.690001 °C, pressure=1029.177368 mbar, humidity=72.257813 %
baro0: timestamp:14280000 value1:1029.18 value2:30.69
```
<a>(See the complete log)</a>
We see that Humidity (<code>value</code>), Pressure (<code>value1</code>) and Temperature (<code>value2</code>) are returned correctly by the C Version of the Sensor App.
Something got messed up in the Auto-Translation from C <a>(sensortest.c)</a> to Zig <a>(sensortest.zig)</a>. Let's find out why...
Fix Floating-Point Values
<em>(Note: We observed this issue with Zig Compiler version 0.10.0, it might have been fixed in later versions of the compiler)</em>
Earlier we saw that our Zig Sensor App printed the incorrect Sensor Values for Pressure (<code>value1</code>) and Temperature (<code>value2</code>)...
<code>bash
nsh> sensortest -n 1 baro0
Zig Sensor Test
bme280_fetch: temperature=30.520000 °C, pressure=1029.177490 mbar, humidity=72.184570 %
baro0: timestamp:78490000 value1:72.18 value2:72.18</code>
Zig seems to have a problem passing the Pressure and Temperature values (both <code>f32</code>) to <code>printf</code>, based on this Auto-Translated Zig Code...
<code>c
fn print_valf2(buffer: [*c]const u8, name: [*c]const u8) void {
const event = @intToPtr([*c]c.struct_sensor_baro, @ptrToInt(buffer));
_ = printf("%s: timestamp:%llu value1:%.2f value2:%.2f\n",
name,
event.*.timestamp,
@floatCast(f64, event.*.pressure),
@floatCast(f64, event.*.temperature)
);
}</code>
<a>(Source)</a>
The workaround is to convert the Float values to Integer AND split into two calls to <code>printf</code>...
<code>c
fn print_valf2(buffer: [*c]const u8, name: [*c]const u8) void {
const event = @intToPtr([*c]c.struct_sensor_baro, @ptrToInt(buffer));
_ = printf("%s: timestamp:%llu ",
name,
event.*.timestamp,
);
_ = printf("value1:%d value2:%d\n",
@floatToInt(i32, event.*.pressure),
@floatToInt(i32, event.*.temperature)
);
}</code>
<a>(Source)</a>
Now our Zig Sensor App prints the correct values, but truncated as Integers...
```text
nsh> sensortest -n 1 baro0
Zig Sensor Test
SensorTest: Test /dev/uorb/sensor_baro0 with interval(1000000us), latency(0us)
baro0: timestamp:42610000 value1:1003 value2:31
SensorTest: Received message: baro0, number:1/1
nsh> sensortest -n 1 humi0
Zig Sensor Test
SensorTest: Test /dev/uorb/sensor_humi0 with interval(1000000us), latency(0us)
humi0: timestamp:32420000 value:68
SensorTest: Received message: humi0, number:1/1
```
Since <code>printf</code> works OK with Integers, let's print the Floats as Integers with 2 decimal places...
<code>zig
/// Print the float with 2 decimal places.
/// We print as integers because `printf` has a problem with floats.
fn print_float(f: f32) void {
const scaled = @floatToInt(i32, f * 100);
const f1 = @divTrunc(scaled, 100);
const f2 = @mod(scaled, 100);
_ = printf("%d.%02d", f1, f2);
}</code>
<a>(Source)</a>
Then we pass the Floats to <code>print_float</code> for printing...
<code>zig
fn print_valf2(buffer: [*c]const u8, name: [*c]const u8) void {
const event = @intToPtr([*c]c.struct_sensor_baro, @ptrToInt(buffer));
_ = printf("%s: timestamp:%llu ",
name,
event.*.timestamp,
);
_ = printf("value1:"); print_float(event.*.pressure);
_ = printf(" value2:"); print_float(event.*.temperature);
_ = printf("\n");
}</code>
<a>(Source)</a>
Finally we see the Pressure (<code>value1</code>), Temperature (<code>value2</code>) and Humidity (<code>value</code>) printed correctly with 2 decimal places!
```text
nsh> sensortest -n 1 baro0
Zig Sensor Test
SensorTest: Test /dev/uorb/sensor_baro0 with interval(1000000us), latency(0us)
baro0: timestamp:17780000 value1:1006.12 value2:29.65
SensorTest: Received message: baro0, number:1/1
nsh> sensortest -n 1 humi0
Zig Sensor Test
SensorTest: Test /dev/uorb/sensor_humi0 with interval(1000000us), latency(0us)
humi0: timestamp:28580000 value:77.44
SensorTest: Received message: humi0, number:1/1
```
<em>Have we tried other options for <code>@floatCast</code>?</em>
Yes we tested these options for <code>@floatCast</code>...
<code>zig
_ = printf("value1 no floatCast: %f\n", event.*.pressure);
_ = printf("value1 floatCast f32: %f\n", @floatCast(f32, event.*.pressure));
_ = printf("value1 floatCast f64: %f\n", @floatCast(f64, event.*.pressure));</code>
But the result is incorrect...
<code>text
nsh> sensortest -n 1 baro0
Zig Sensor Test
baro0: timestamp:60280000 value1:1006.90 value2:30.79
value1 no floatCast: 0.000000
value1 floatCast f32: 0.000000
value1 floatCast f64: 30.790001</code>
Because <code>value1</code> (Pressure) is supposed to be 1006, not 30.
Robert Lipe suggests that we might have a problem with the RISC-V Calling Conventions for Floats and Doubles...
<blockquote>
The calling conventions for RISC-V on small computers for floats/doubles is weird and the software/emulators/ libs are confusing. Verify that floats get promoted to doubles in the call and that they go to F0, F2, F4, etc. in the frame, properly aligned. Double check complr flags
</blockquote>
<a>(Source)</a>
<blockquote>
See, e.g., https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/master/riscv-cc.adoc and related. This is <em>totally</em> the kind of thing that small parts (enable FP on BL602; disable s/w libs) and x-language can get wrong.
</blockquote>
<a>(Source)</a>
<em>Instead of <code>printf</code>, why not call the Zig Debug Logger <code>debug</code>?</em>
<code>zig
debug("pressure: {}", .{ event.*.pressure });
debug("temperature: {}", .{ event.*.temperature });</code>
This causes a Linker Error, as explained below...
Floating-Point Link Error
<em>(Note: We observed this issue with Zig Compiler version 0.10.0, it might have been fixed in later versions of the compiler)</em>
When we call the Zig Debug Logger <code>debug</code> to print Floating-Point Numbers (32-bit)...
<code>zig
var event = @intToPtr([*c]c.struct_sensor_baro, @ptrToInt(buffer));
debug("pressure: {}", .{ event.*.pressure });
debug("temperature: {}", .{ event.*.temperature });</code>
It fails to link...
<code>text
riscv64-unknown-elf-ld: nuttx/nuttx/staging/libapps.a(sensortest.c.home.user.nuttx.apps.testing.sensortest.o): in function `std.fmt.errol.errolInt':
zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:305:
undefined reference to `__fixunsdfti'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:305:
undefined reference to `__floatuntidf'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:315:
undefined reference to `__umodti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:316: undefined reference to `__udivti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:316:
undefined reference to `__umodti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:318:
undefined reference to `__umodti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:319:
undefined reference to `__udivti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:319:
undefined reference to `__umodti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:324:
undefined reference to `__udivti3'
riscv64-unknown-elf-ld: zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:335:
undefined reference to `__udivti3'
riscv64-unknown-elf-ld: nuttx/nuttx/staging/libapps.a(sensortest.c.home.user.nuttx.apps.testing.sensortest.o): in function `std.fmt.errol.fpeint':
zig-linux-x86_64-0.10.0-dev.2351+b64a1d5ab/lib/std/fmt/errol.zig:677:
undefined reference to `__ashlti3'</code>
But printing as Integers with <code>debug</code> works OK...
<code>zig
debug("pressure: {}",
.{ @floatToInt(i32, event.*.pressure) });
debug("temperature: {}",
.{ @floatToInt(i32, event.*.temperature) });</code>
So we print Floats as Integers with the Debug Logger...
Fixed-Point Printing
Earlier we saw that Zig Debug Logger <code>debug</code> won't print Floating-Point Numbers. (Due to a Linker Error)
Let's convert Floating-Point Numbers to Fixed-Point Numbers (2 decimal places) and print as Integers instead...
<code>zig
/// Convert the float to a fixed-point number (`int`.`frac`) with 2 decimal places.
/// We do this because `debug` has a problem with floats.
pub fn floatToFixed(f: f32) struct { int: i32, frac: u8 } {
const scaled = @floatToInt(i32, f * 100.0);
const rem = @rem(scaled, 100);
const rem_abs = if (rem < 0) -rem else rem;
return .{
.int = @divTrunc(scaled, 100),
.frac = @intCast(u8, rem_abs),
};
}</code>
<a>(Source)</a>
This is how we print Floating-Point Numbers as Fixed-Point Numbers...
<code>zig
/// Print 2 floats
fn print_valf2(buffer: []const align(8) u8, name: []const u8) void {
_ = name;
const event = @ptrCast(*const c.struct_sensor_baro, &buffer[0]);
const pressure = floatToFixed(event.*.pressure);
const temperature = floatToFixed(event.*.temperature);
debug("value1:{}.{:0>2}", .{ pressure.int, pressure.frac });
debug("value2:{}.{:0>2}", .{ temperature.int, temperature.frac });
}</code>
<a>(Source)</a>
Change to Static Buffer
Originally we allocated the Sensor Data Buffer from the Heap via <code>calloc</code>...
<code>zig
// Allocate buffer from heap
len = @bitCast(c_int, @as(c_uint, g_sensor_info[@intCast(c_uint, idx)].esize));
buffer = @ptrCast([*c]u8, @alignCast(std.meta.alignment(u8),
c.calloc(@bitCast(usize, @as(c_int, 1)), @bitCast(usize, len))));
...
// Read into heap buffer
if (c.read(fd, @ptrCast(?*anyopaque, buffer), @bitCast(usize, len)) >= len) {
g_sensor_info[@intCast(c_uint, idx)].print.?(buffer, name);
}
...
// Deallocate heap buffer
c.free(@ptrCast(?*anyopaque, buffer));</code>
To make this a little safer, we switched to a Static Buffer...
<code>zig
/// Sensor Data Buffer
/// (Aligned to 8 bytes because it's passed to C)
var sensor_data align(8) = std.mem.zeroes([256]u8);</code>
<a>(Source)</a>
So that we no longer worry about deallocating the buffer...
<code>zig
// Use static buffer
len = @bitCast(c_int, @as(c_uint, g_sensor_info[@intCast(c_uint, idx)].esize));
assert(sensor_data.len >= len);
...
// Read into static buffer
if (c.read(fd, @ptrCast(?*anyopaque, &sensor_data), @bitCast(usize, len)) >= len) {
g_sensor_info[@intCast(c_uint, idx)].print.?(&sensor_data, name);
}
...
// No need to deallocate buffer</code>
<a>(Source)</a>
We also moved the Device Name from the Stack...
<code>zig
/// Main Function that will be called by NuttX. We read the Sensor Data from a Sensor.
pub export fn sensortest_main(...) {
var devname: [c.PATH_MAX]u8 = undefined;</code>
<a>(Source)</a>
To a Static Buffer...
<code>zig
/// Device Name, like "/dev/uorb/sensor_baro0" or "/dev/uorb/sensor_humi0"
/// (Aligned to 8 bytes because it's passed to C)
var devname align(8) = std.mem.zeroes([c.PATH_MAX]u8);</code>
<a>(Source)</a>
And we removed the Alignment from Device Name...
<code>zig
fd = c.open(
@ptrCast([*c]u8, @alignCast(std.meta.alignment(u8), &devname)),
c.O_RDONLY | c.O_NONBLOCK
);</code>
<a>(Source)</a>
So it looks like this...
<code>zig
fd = c.open(
&devname[0],
c.O_RDONLY | c.O_NONBLOCK
);</code>
<a>(Source)</a>
Incorrect Alignment
When we align the Sensor Data Buffer to 4 bytes...
<code>zig
/// Sensor Data Buffer
/// (Aligned to 4 bytes because it's passed to C)
var sensor_data align(4) = std.mem.zeroes([256]u8);</code>
It triggers a Zig Panic due to Incorrect Aligment...
```text
nsh> sensortest -n 1 baro0
Zig Sensor Test
SensorTest: Test /dev/uorb/sensor_baro0 with interval(1000000us), latency(0us)
!ZIG PANIC!
incorrect alignment
Stack Trace:
0x23014f4c
0x230161e2
```
RISC-V Disassembly shows that it's checking <code>andi a0,a0,7</code>...
<code>text
nuttx/visual-zig-nuttx/sensortest.zig:196
const event = @intToPtr([*c]c.struct_sensor_baro, @ptrToInt(buffer));
23014f2a: 85aa mv a1,a0
23014f2c: fcb42e23 sw a1,-36(s0)
23014f30: 891d andi a0,a0,7
23014f32: 4581 li a1,0
23014f34: 00b50c63 beq a0,a1,23014f4c <print_valf2+0x32>
23014f38: a009 j 23014f3a <print_valf2+0x20>
23014f3a: 23068537 lui a0,0x23068
23014f3e: 3c850513 addi a0,a0,968 # 230683c8 <__unnamed_6>
23014f42: 4581 li a1,0
23014f44: 00000097 auipc ra,0x0
23014f48: dd4080e7 jalr -556(ra) # 23014d18 <panic>
23014f4c: fdc42503 lw a0,-36(s0)
23014f50: fea42a23 sw a0,-12(s0)</code>
(Last 3 bits of address must be 0)
Which means that the buffer address must be aligned to 8 bytes...
<code>zig
/// Sensor Data Buffer
/// (Aligned to 8 bytes because it's passed to C)
var sensor_data align(8) = std.mem.zeroes([256]u8);</code>
<a>(Source)</a>
Probably because <code>struct_sensor_baro</code> contains a <code>timestamp</code> field that's a 64-bit Integer.
Clean Up
The Auto-Translation from C to Zig looks super verbose and strips away the Macro Constants...
<code>zig
// Parse the Command-Line Options
g_should_exit = @as(c_int, 0) != 0;
while ((blk: {
const tmp = c.getopt(argc, argv, "i:b:n:h");
ret = tmp;
break :blk tmp;
}) != -@as(c_int, 1)) {
while (true) {
switch (ret) {
@as(c_int, 105) => {
interval = @bitCast(c_uint, @truncate(c_uint, c.strtoul(c.getoptargp().*, null, @as(c_int, 0))));
break;
},
@as(c_int, 98) => {
latency = @bitCast(c_uint, @truncate(c_uint, c.strtoul(c.getoptargp().*, null, @as(c_int, 0))));
break;
},
@as(c_int, 110) => {
count = @bitCast(c_uint, @truncate(c_uint, c.strtoul(c.getoptargp().*, null, @as(c_int, 0))));
break;
},
else => {
usage();
return ret;
},
}
break;
}
}</code>
<a>(Source)</a>
We clean up the Zig code like this...
<code>zig
// Parse the Command-Line Options
g_should_exit = false;
while (true) {
ret = c.getopt(argc, argv, "i:b:n:h");
if (ret == c.EOF) { break; }
switch (ret) {
'i' => { interval = c.strtoul(c.getoptargp().*, null, 0); },
'b' => { latency = c.strtoul(c.getoptargp().*, null, 0); },
'n' => { count = c.strtoul(c.getoptargp().*, null, 0); },
else => { usage(); return ret; },
}
}</code>
<a>(Source)</a>
So that it resembles the original C code...
```c
g_should_exit = false;
while ((ret = getopt(argc, argv, "i:b:n:h")) != EOF)
{
switch (ret)
{
case 'i':
interval = strtoul(optarg, NULL, 0);
break;
<code> case 'b':
latency = strtoul(optarg, NULL, 0);
break;
case 'n':
count = strtoul(optarg, NULL, 0);
break;
case 'h':
default:
usage();
goto name_err;
}
</code>
}
```
<a>(Source)</a>
Our Zig Sensor App was originally this...
https://github.com/lupyuen/visual-zig-nuttx/blob/4ccb0cd9b2a55464b76b8a0fcbcf9f106d608f2f/sensortest.zig#L35-L170
After cleanup becomes this...
https://github.com/lupyuen/visual-zig-nuttx/blob/692b5e5f6b67d04815f975dff77380a164c98247/multisensor.zig#L15-L150
We test again to be sure that the Zig Sensor App is still working OK...
```text
NuttShell (NSH) NuttX-10.3.0
nsh> uname -a
NuttX 10.3.0 32c8fdf272 Jul 18 2022 16:38:47 risc-v bl602evb
nsh> sensortest -n 1 baro0
Zig Sensor Test
test_multisensor
SensorTest: Test /dev/uorb/sensor_baro0 with interval(1000000), latency(0)
value1:1007.65
value2:27.68
SensorTest: Received message: baro0, number:1/1
nsh> sensortest -n 1 humi0
Zig Sensor Test
test_multisensor
SensorTest: Test /dev/uorb/sensor_humi0 with interval(1000000), latency(0)
value:78.91
SensorTest: Received message: humi0, number:1/1
```
We also check that errors are handled correctly...
```text
nsh> sensortest -n 1 baro
Zig Sensor Test
test_multisensor
Failed to open device:/dev/uorb/sensor_baro , ret:No such file or directory
nsh> sensortest -n 1 invalid
Zig Sensor Test
test_multisensor
The sensor node name:invalid is invalid
sensortest test
Test barometer sensor (/dev/uorb/sensor_baro0)
sensortest test2
Test humidity sensor (/dev/uorb/sensor_humi0)
sensortest [arguments...]
[-h ] sensortest commands help
[-i ] The output data period of sensor in us
default: 1000000
[-b ] The maximum report latency of sensor in us
default: 0
[-n ] The number of output data
default: 0
Commands:
ex, accel0(/dev/uorb/sensor_accel0)
nsh> sensortest
Zig Sensor Test
sensortest test
Test barometer sensor (/dev/uorb/sensor_baro0)
sensortest test2
Test humidity sensor (/dev/uorb/sensor_humi0)
sensortest [arguments...]
[-h ] sensortest commands help
[-i ] The output data period of sensor in us
default: 1000000
[-b ] The maximum report latency of sensor in us
default: 0
[-n ] The number of output data
default: 0
Commands:
ex, accel0(/dev/uorb/sensor_accel0)
```
Read Barometer Sensor
Reading Sensor Data from a single sensor looks a lot simpler (because we don't need to cast the Sensor Data)...
```zig
// Omitted: Open the Sensor Device, enable the Sensor and poll for Sensor Data
...
// Define the Sensor Data Type
var sensor_data = std.mem.zeroes(c.struct_sensor_baro);
const len = @sizeOf(@TypeOf(sensor_data));
// Read the Sensor Data
if (c.read(fd, &sensor_data, len) >= len) {
<code>// Convert the Sensor Data to Fixed-Point Numbers
const pressure = floatToFixed(sensor_data.pressure);
const temperature = floatToFixed(sensor_data.temperature);
// Print the Sensor Data
debug("pressure:{}.{:0>2}", .{
pressure.int,
pressure.frac
});
debug("temperature:{}.{:0>2}", .{
temperature.int,
temperature.frac
});
</code>
}
```
<a>(Source)</a>
Here's the Air Pressure and Temperature read from the BME280 Barometer Sensor...
<code>text
nsh> sensortest test
Zig Sensor Test
test_sensor
pressure:1007.66
temperature:27.70</code>
Read Humidity Sensor
To read a Humidity Sensor (like BME280), the code looks highly similar...
```zig
// Define the Sensor Data Type
var sensor_data = std.mem.zeroes(c.struct_sensor_humi);
const len = @sizeOf(@TypeOf(sensor_data));
// Read the Sensor Data
if (c.read(fd, &sensor_data, len) >= len) {
<code>// Convert the Sensor Data to Fixed-Point Numbers
const humidity = floatToFixed(sensor_data.humidity);
// Print the Sensor Data
debug("humidity:{}.{:0>2}", .{
humidity.int,
humidity.frac
});
</code>
}
```
<a>(Source)</a>
Here's the Humidity read from the BME280 Humidity Sensor...
<code>text
nsh> sensortest test2
Zig Sensor Test
test_sensor2
humidity:78.81</code>
Zig Generics
With Zig Generics and <code>comptime</code>, we can greatly simplify the reading of Sensor Data...
```zig
// Read the Temperature
const temperature: f32 = try sen.readSensor(
c.struct_sensor_baro, // Sensor Data Struct to be read
"temperature", // Sensor Data Field to be returned
"/dev/uorb/sensor_baro0" // Path of Sensor Device
);
// Print the Temperature
debug("temperature={}", .{ floatToFixed(temperature) });
```
<a>(Source)</a>
Here's the implementation of <code>readSensor</code>...
https://github.com/lupyuen/visual-zig-nuttx/blob/1bb1c69ea4a9310e42b149e04ac26a7e4a1f4b58/sensor.zig#L34-L108
Note that the Sensor Data Struct Type and the Sensor Data Field are declared as <code>comptime</code>...
<code>zig
/// Read a Sensor and return the Sensor Data
pub fn readSensor(
comptime SensorType: type, // Sensor Data Struct to be read, like c.struct_sensor_baro
comptime field_name: []const u8, // Sensor Data Field to be returned, like "temperature"
device_path: []const u8 // Path of Sensor Device, like "/dev/uorb/sensor_baro0"
) !f32 { ...</code>
Which means that the values will be substituted at Compile-Time. (Works like a C Macro)
We can then refer to the Sensor Data Struct <code>sensor_baro</code> like this...
<code>zig
// Define the Sensor Data Type
var sensor_data = std.mem.zeroes(
SensorType
);</code>
And return a field <code>temperature</code> like this...
<code>zig
// Return the Sensor Data Field
return @field(sensor_data, field_name);</code>
Thus this program...
https://github.com/lupyuen/visual-zig-nuttx/blob/a7404eae71dc37850e323848180414aa6ef7e0f7/visual.zig#L27-L61
Produces this output...
<code>text
NuttShell (NSH) NuttX-10.3.0
nsh> sensortest visual
Zig Sensor Test
Start main
...
temperature=30.18
pressure=1007.69
humidity=68.67
End main</code>
CBOR Encoding
Blockly will emit the Zig code below for a typical IoT Sensor App: <a>visual.zig</a>
```zig
// Read Temperature from BME280 Sensor
const temperature = try sen.readSensor( // Read BME280 Sensor
c.struct_sensor_baro, // Sensor Data Struct
"temperature", // Sensor Data Field
"/dev/uorb/sensor_baro0" // Path of Sensor Device
);
// Read Pressure from BME280 Sensor
const pressure = try sen.readSensor( // Read BME280 Sensor
c.struct_sensor_baro, // Sensor Data Struct
"pressure", // Sensor Data Field
"/dev/uorb/sensor_baro0" // Path of Sensor Device
);
// Read Humidity from BME280 Sensor
const humidity = try sen.readSensor( // Read BME280 Sensor
c.struct_sensor_humi, // Sensor Data Struct
"humidity", // Sensor Data Field
"/dev/uorb/sensor_humi0" // Path of Sensor Device
);
// Compose CBOR Message with Temperature, Pressure and Humidity
const msg = try composeCbor(.{
"t", temperature,
"p", pressure,
"h", humidity,
});
// Transmit message to LoRaWAN
try transmitLorawan(msg);
```
This reads the Temperature, Pressure and Humidity from BME280 Sensor, composes a CBOR Message that's encoded with the Sensor Data, and transmits the CBOR Message to LoRaWAN.
<em><code>composeCbor</code> will work for a variable number of arguments? Strings as well as numbers?</em>
Yep, here's the implementation of <code>composeCbor</code>: <a>visual.zig</a>
```zig
/// TODO: Compose CBOR Message with Key-Value Pairs
/// https://lupyuen.github.io/articles/cbor2
fn composeCbor(args: anytype) !CborMessage {
debug("composeCbor", .{});
comptime {
assert(args.len % 2 == 0); // Missing Key or Value
}
<code>// Process each field...
comptime var i: usize = 0;
var msg = CborMessage{};
inline while (i < args.len) : (i += 2) {
// Get the key and value
const key = args[i];
const value = args[i + 1];
// Print the key and value
debug(" {s}: {}", .{
@as([]const u8, key),
floatToFixed(value)
});
// Format the message for testing
var slice = std.fmt.bufPrint(
msg.buf[msg.len..],
"{s}:{},",
.{
@as([]const u8, key),
floatToFixed(value)
}
) catch { _ = std.log.err("Error: buf too small", .{}); return error.Overflow; };
msg.len += slice.len;
}
debug(" msg={s}", .{ msg.buf[0..msg.len] });
return msg;
</code>
}
/// TODO: CBOR Message
/// https://lupyuen.github.io/articles/cbor2
const CborMessage = struct {
buf: [256]u8 = undefined, // Limit to 256 chars
len: usize = 0,
};
```
Note that <code>composeCbor</code> is declared as <code>anytype</code>...
<code>zig
fn composeCbor(args: anytype) { ...</code>
That's why <code>composeCbor</code> accepts a variable number of arguments with different types.
To handle each argument, this <code>inline</code> / <code>comptime</code> loop is unrolled at Compile-Time...
```zig
// Process each field...
comptime var i: usize = 0;
inline while (i < args.len) : (i += 2) {
<code> // Get the key and value
const key = args[i];
const value = args[i + 1];
// Print the key and value
debug(" {s}: {}", .{
@as([]const u8, key),
floatToFixed(value)
});
...
}
</code>
```
<em>What happens if we omit a Key or a Value when calling <code>composeCbor</code>?</em>
This <code>comptime</code> assertion check will fail at Compile-Time...
<code>zig
comptime {
assert(args.len % 2 == 0); // Missing Key or Value
}</code>
Customise Blockly
Next we customise <a>Blockly</a> to generate the Zig Sensor App.
Read the article...
<ul>
<li><a>"Visual Programming with Zig and NuttX Sensors"</a></li>
</ul>
Test Visual Zig Sensor App
To test the Zig Sensor App generated by Blockly, let's build an IoT Sensor App that will read Temperature, Pressure and Humidity from BME280 Sensor, and transmit the values to LoRaWAN...
<a>lupyuen3.github.io/blockly-zig-nuttx/demos/code</a>
The Blocks above will emit this Zig program...
```zig
/// Main Function
pub fn main() !void {
// Every 10 seconds...
while (true) {
const temperature = try sen.readSensor( // Read BME280 Sensor
c.struct_sensor_baro, // Sensor Data Struct
"temperature", // Sensor Data Field
"/dev/uorb/sensor_baro0" // Path of Sensor Device
);
debug("temperature={}", .{ temperature });
<code>const pressure = try sen.readSensor( // Read BME280 Sensor
c.struct_sensor_baro, // Sensor Data Struct
"pressure", // Sensor Data Field
"/dev/uorb/sensor_baro0" // Path of Sensor Device
);
debug("pressure={}", .{ pressure });
const humidity = try sen.readSensor( // Read BME280 Sensor
c.struct_sensor_humi, // Sensor Data Struct
"humidity", // Sensor Data Field
"/dev/uorb/sensor_humi0" // Path of Sensor Device
);
debug("humidity={}", .{ humidity });
const msg = try composeCbor(.{ // Compose CBOR Message
"t", temperature,
"p", pressure,
"h", humidity,
});
// Transmit message to LoRaWAN
try transmitLorawan(msg);
// Wait 10 seconds
_ = c.sleep(10);
</code>
}
}
```
<a>(<code>composeCbor</code> is explained here)</a>
Copy the contents of the Main Function and paste here...
<a>visual-zig-nuttx/visual.zig</a>
The generated Zig code should correctly read the Temperature, Pressure and Humidity from BME280 Sensor, and transmit the values to LoRaWAN...
```text
NuttShell (NSH) NuttX-10.3.0
nsh> sensortest visual
Zig Sensor Test
Start main
temperature=31.05
pressure=1007.44
humidity=71.49
composeCbor
t: 31.05
p: 1007.44
h: 71.49
msg=t:31.05,p:1007.44,h:71.49,
transmitLorawan
msg=t:31.05,p:1007.44,h:71.49,
temperature=31.15
pressure=1007.40
humidity=70.86
composeCbor
t: 31.15
p: 1007.40
h: 70.86
msg=t:31.15,p:1007.40,h:70.86,
transmitLorawan
msg=t:31.15,p:1007.40,h:70.86,
temperature=31.16
pressure=1007.45
humidity=70.42
composeCbor
t: 31.16
p: 1007.45
h: 70.42
msg=t:31.16,p:1007.45,h:70.42,
transmitLorawan
msg=t:31.16,p:1007.45,h:70.42,
temperature=31.16
pressure=1007.47
humidity=70.39
composeCbor
t: 31.16
p: 1007.47
h: 70.39
msg=t:31.16,p:1007.47,h:70.39,
transmitLorawan
msg=t:31.16,p:1007.47,h:70.39,
temperature=31.19
pressure=1007.45
humidity=70.35
composeCbor
t: 31.19
p: 1007.45
h: 70.35
msg=t:31.19,p:1007.45,h:70.35,
transmitLorawan
msg=t:31.19,p:1007.45,h:70.35,
temperature=31.20
pressure=1007.42
humidity=70.65
composeCbor
t: 31.20
p: 1007.42
h: 70.65
msg=t:31.20,p:1007.42,h:70.65,
transmitLorawan
msg=t:31.20,p:1007.42,h:70.65,
```
(Tested with NuttX and BME280 on BL602)
Test Stubs
To test the Zig program above on Linux / macOS / Windows (instead of NuttX), add the stubs below to simulate a NuttX Sensor...
```zig
/// Import Standard Library
const std = @import("std");
/// Main Function
pub fn main() !void {
// TODO: Paste here the contents of Zig Main Function generated by Blockly
...
}
/// Aliases for Standard Library
const assert = std.debug.assert;
const debug = std.log.debug;
///////////////////////////////////////////////////////////////////////////////
// CBOR Encoding
/// TODO: Compose CBOR Message with Key-Value Pairs
/// https://lupyuen.github.io/articles/cbor2
fn composeCbor(args: anytype) !CborMessage {
debug("composeCbor", .{});
comptime {
assert(args.len % 2 == 0); // Missing Key or Value
}
<code>// Process each field...
comptime var i: usize = 0;
var msg = CborMessage{};
inline while (i < args.len) : (i += 2) {
// Get the key and value
const key = args[i];
const value = args[i + 1];
// Print the key and value
debug(" {s}: {}", .{
@as([]const u8, key),
floatToFixed(value)
});
// Format the message for testing
var slice = std.fmt.bufPrint(
msg.buf[msg.len..],
"{s}:{},",
.{
@as([]const u8, key),
floatToFixed(value)
}
) catch { _ = std.log.err("Error: buf too small", .{}); return error.Overflow; };
msg.len += slice.len;
}
debug(" msg={s}", .{ msg.buf[0..msg.len] });
return msg;
</code>
}
/// TODO: CBOR Message
/// https://lupyuen.github.io/articles/cbor2
const CborMessage = struct {
buf: [256]u8 = undefined, // Limit to 256 chars
len: usize = 0,
};
///////////////////////////////////////////////////////////////////////////////
// Transmit To LoRaWAN
/// TODO: Transmit message to LoRaWAN
fn transmitLorawan(msg: CborMessage) !void {
debug("transmitLorawan", .{});
debug(" msg={s}", .{ msg.buf[0..msg.len] });
}
///////////////////////////////////////////////////////////////////////////////
// Stubs
const c = struct {
const struct_sensor_baro = struct{};
const struct_sensor_humi = struct{};
fn sleep(seconds: c_uint) c_int {
std.time.sleep(@as(u64, seconds) * std.time.ns_per_s);
return 0;
}
};
const sen = struct {
fn readSensor(comptime SensorType: type, comptime field_name: []const u8, device_path: []const u8) !f32
{ _ = SensorType; _ = field_name; _ = device_path; return 23.45; }
};
fn floatToFixed(f: f32) f32 { return f; }
```
<a>(<code>composeCbor</code> is explained here)</a>
Debug Logger Crashes
<strong>UPDATE:</strong> This crashing seems to be caused by our Zig Sensor App running out of Stack Space. We fixed iy by increasing <a>"Sensor Driver Test Stack Size"</a> from 2048 to 4096.
Calling the <code>debug</code> logger inside <code>print_valf2</code> causes weird crashes...
<code>zig
debug("timestamp: {}", .{ event.*.timestamp });</code>
Possibly due to Memory Corruption inside our Zig Debug Logger...
<code>``zig
/// Called by Zig for</code>std.log.debug<code>,</code>std.log.info<code>,</code>std.log.err`, ...
/// TODO: Support multiple threads
/// https://gist.github.com/leecannon/d6f5d7e5af5881c466161270347ce84d
pub fn log(...) void {
<code>// Possible memory corruption here: Format the message
var slice = std.fmt.bufPrint(&log_buf, format, args)
catch { _ = puts("*** Error: log_buf too small"); return; };
...
</code>
```
Here's a crash log...
<code>text
bme280_fetch: temperature=31.570000 °C, pressure=1025.396118 mbar, humidity=64.624023 %
name: baro0
timestamp: 27270000
value1: 1025
value2: 31
size: 16
SensorTest: Received message: , number:1/1
decode_insn_compressed: Compressed: a783
riscv_exception: EXCEPTION: Load access fault. MCAUSE: 00000005
riscv_exception: PANIC!!! Exception = 00000005
up_assert: Assertion failed at file:common/riscv_exception.c line: 89 task: sensortest
backtrace| 3: 0x2300c698
riscv_registerdump: EPC: 2300c698
riscv_registerdump: A0: 4201b9a0 A1: 0000a80 A2: 4201bf48 A3: 00000000
riscv_registerdump: A4: 2307a5e8 A5: 00583000 A6: 2307a000 A7: 00000000
riscv_registerdump: T0: 000001ff T1: 23005830 T2: 0000002d T3: 00000068
riscv_registerdump: T4: 00000009 T5: 0000002a T6: 0000002e
riscv_registerdump: S0: 4201b9a0 S1: 2307a000 S2: 00000a80 S3: 4201bdef
riscv_registerdump: S4: 00000000 S5: 00000000 S6: 00000000 S7: 00000000
riscv_registerdump: S8: 00000000 S9: 00000000 S10: 00000000 S11: 00000000
riscv_registerdump: SP: 4201bef0 FP: 4201b9a0 TP: 00000000 RA: 2300c78e</code>
Another crash...
<code>text
up_assert: Assertion failed at file:common/riscv_doirq.c line: 78 task: sensortest
backtrace| 3: 0x2300bd9a
riscv_registerdump: EPC: 2300bd9a
riscv_registerdump: A0: 00000000 A1: 4201bc38 A2: 00000013 A3: 00000000
riscv_registerdump: A4: 00000000 A5: 0000000b A6: a0000000 A7: 2306a1b2
riscv_registerdump: T0: f0000000 T1: 80000000 T2: 00000000 T3: 00000000
riscv_registerdump: T4: 00000008 T5: 00010000 T6: 6d0cb600
riscv_registerdump: S0: 0000001b S1: 00000000 S2: 23079000 S3: 4201b8c8
riscv_registerdump: S4: 4201bc38 S5: 00000006 S6: 00000000 S7: 00000000
riscv_registerdump: S8: 00000000 S9: 00000000 S10: 00000000 S11: 00000000
riscv_registerdump: SP: 4201bbf0 FP: 0000001b TP: 00000000 RA: 2300bd78</code>
Which happens when closing a file (console?)...
<code>text
/home/user/nuttx/nuttx/fs/inode/fs_files.c:380
/* if f_inode is NULL, fd was closed */
if (!(*filep)->f_inode)
2300bd98: 441c lw a5,8(s0)
2300bd9a: c39d beqz a5,2300bdc0 <fs_getfilep+0xaa>
2300bd9c: 87a2 mv a5,s0
2300bd9e: 00fa2023 sw a5,0(s4)</code>
And another crash...
<code>text
up_assert: Assertion failed at file:mm_heap/mm_free.c line: 154 task: sensortest
riscv_registerdump: EPC: 230086b0
riscv_registerdump: A0: 00000000 A1: 4201bc38 A2: 00000000 A3: 00000000
riscv_registerdump: A4: 23078460 A5: 23078000 A6: 4201bdbc A7: 23078000
riscv_registerdump: T0: 000001ff T1: 23078460 T2: 0000002d T3: 00000068
riscv_registerdump: T4: 00000009 T5: 0000002a T6: 0000002e
riscv_registerdump: S0: 4201c1f0 S1: 23078000 S2: 4201b800 S3: 4201bed0
riscv_registerdump: S4: 42013000 S5: 23078000 S6: 00000000 S7: 00000000
riscv_registerdump: S8: 00000081 S9: 00000025 S10: 23068e25 S11: 4201bec4
riscv_registerdump: SP: 4201beb0 FP: 00000000 TP: 23001478 RA: 230080c2</code>
This crashes inside <code>free</code> when deallocating the Sensor Data Buffer, might be due to a Heap Problem.
For safety, we converted the Heap Buffer to a Static Buffer. | []
|
https://avatars.githubusercontent.com/u/11590808?v=4 | zig-socks | mllken/zig-socks | 2022-10-22T05:31:59Z | A SOCKS 5/4/4a client library for Zig | main | 0 | 8 | 2 | 8 | https://api.github.com/repos/mllken/zig-socks/tags | MIT | [
"proxy",
"zig"
]
| 59 | false | 2025-03-16T15:52:02Z | true | true | 0.13.0 | github | []
| zig-socks
A simple, non-allocating SOCKS 5/4/4a client library for Zig
<em>Tested against Zig 0.13.x</em>
Features
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Protocol version 5
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> CONNECT command
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> BIND command
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> UDP ASSOCIATE command
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Password authentication
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> IPv4 address
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> IPv6 address
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> hostname address
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Protocol version 4 and 4a
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> CONNECT command
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> BIND command
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> IPv4 address
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> hostname address
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Remote DNS lookups
Usage
```zig
const std = @import("std");
const Socksv5 = @import("socks.zig").Socksv5;
pub fn main() !void {
const proxy = try std.net.Address.parseIp4("127.0.0.1", 1080);
const stream = try Socksv5.connect(proxy, null, "www.google.com", 80);
defer stream.close();
<code>// read/write to stream...
</code>
}
<code>or</code>zig
var gpa = GeneralPurposeAllocator(.{})();
const allocator = gpa.allocator();
const stream = try std.net.tcpConnectToHost(allocator, "localhost", 1080);
defer stream.close();
// use the generic interface - should work with any std.io.Reader and std.io.Writer
try Socksv5.client(stream.reader(), stream.writer(), null, "www.google.com", 80);
// read/write to stream...
``` | []
|
https://avatars.githubusercontent.com/u/11590808?v=4 | zig-pcapfile | mllken/zig-pcapfile | 2022-10-30T08:52:08Z | A pure Zig library for reading and writing PCAP files | main | 0 | 8 | 4 | 8 | https://api.github.com/repos/mllken/zig-pcapfile/tags | MIT | [
"pcap",
"zig",
"ziglang"
]
| 20 | false | 2025-04-05T16:30:18Z | true | true | 0.13.0 | github | []
| zig-pcapfile
A pure Zig library for reading and writing PCAP files
<em>Releases target Zig releases (e.g. 0.10.x). Master follows the Zig master branch</em>
Status
Full support for reading and writing PCAP version 2.4 files (.pcap extension)
No support for PCAPNG files (.pcapng extension)
Usage
```zig
// PCAP reading
var in_file = try std.fs.cwd().openFile("test.pcap", .{});
var it = try pcap.iterator(allocator, .{}, in_file.reader());
defer it.deinit(allocator);
while (try it.next()) |rec| {
try std.debug.print("packet with len = {d}\n", .{rec.data.len});
}
``` | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | mount.ufs | nektro/mount.ufs | 2022-08-12T23:55:28Z | [WIP] A FUSE filesystem client for mounting UFS partitions, mainly used by FreeBSD and its derivatives. | master | 0 | 7 | 0 | 7 | https://api.github.com/repos/nektro/mount.ufs/tags | GPL-2.0 | [
"freebsd",
"fuse",
"linux",
"netbsd",
"openbsd",
"ufs",
"zig"
]
| 59 | false | 2025-02-02T11:47:42Z | true | false | unknown | github | []
| mount.ufs
<a></a>
A FUSE filesystem client for mounting UFS partitions, mainly used by FreeBSD and its derivatives.
Entirely WIP and experimental until further notice. Any research notes or PRs welcome through any of my contact avenues.
Current Status
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Get libfuse passthrough example building with Zig
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Port passthrough code to be pure Zig
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Read access UFS
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Write access UFS
License
GPL-2.0 | []
|
https://avatars.githubusercontent.com/u/41548458?v=4 | jhex | jonpalmisc/jhex | 2022-07-20T02:55:19Z | Hex dumping tool & Zig library | master | 0 | 7 | 0 | 7 | https://api.github.com/repos/jonpalmisc/jhex/tags | BSD-3-Clause | [
"cli",
"hex-dump",
"xxd",
"zig"
]
| 11 | false | 2024-05-29T09:00:18Z | true | false | unknown | github | []
| Jhex
Jhex is a simple CLI tool and Zig library for creating and formatting hex dumps.
<code>0007:be20 30 e8 79 28 e0 36 1d c5 81 6e 1b 9c dc 7e a2 64 0.y(.6...n...~.d
0007:be30 43 0d b3 03 05 fb 6d 11 f9 31 83 e8 07 54 0a ae C.....m..1...T..
0007:be40 39 d4 aa 4c fe 6f 26 02 44 ce 41 6d f8 27 6e 4b 9..L.o&.D.Am.'nK
0007:be50 7f e2 9b fd d7 13 fe b4 03 22 8c 03 53 49 78 f3 ........."..SIx.
0007:be60 10 38 ca 8a 94 ce ac 79 45 bd 53 93 94 ed 37 92 .8.....yE.S...7.
0007:be70 fc cd 67 77 f1 2b dd 54 16 49 b5 c4 20 88 c5 70 ..gw.+.T.I.. ..p
0007:be80 ea a2 c2 4f a6 54 0d 35 2d ba 27 6d c9 56 69 b1 ...O.T.5-.'m.Vi.
0007:be90 dc 40 9d 4d ce c7 36 7b aa 25 fc c4 55 35 e2 32 [email protected]{.%..U5.2
0007:bea0 3f 99 d2 09 b6 52 74 66 1c 24 a2 af d2 82 22 3e ?....Rtf.$....">
0007:beb0 c5 1b 34 4a ef 16 8b b7 46 09 0b 55 b2 45 5c 06 ..4J....F..U.E\.
0007:bec0 77 f5 7d 7f 17 28 bc a7 3d a3 88 42 52 ff 89 f3 w.}..(..=..BR...
0007:bed0 97 d1 0f 9a 06 b0 e7 57 fb f7 10 e1 8c 87 d3 81 .......W........
0007:bee0 87 9e 76 5b 10 d5 94 7e 56 03 84 57 95 f6 52 3d ..v[...~V..W..R=
0007:bef0 e5 19 ef 7a af 85 0d 26 d4 2a f0 50 fc 97 a1 d8 ...z...&.*.P....
0007:bf00 4b 01 9b 0d b3 8f 79 c2 63 31 c8 c6 4a 6e 33 4a K.....y.c1..Jn3J
0007:bf10 6f f0 3e 64 d5 e0 74 fd 03 75 d2 06 bb 31 81 48 o.>d..t..u...1.H
0007:bf20 bf c8 ce c0 3d aa d5 be 00 0b 2f c0 e8 9e 15 1b ....=...../.....
0007:bf30 c4 fe 3c 9c 9e bb 6b 5c 8f 90 21 04 b4 94 49 33 ..<...k\..!...I3
0007:bf40 3b c9 36 9d 2a 9c 8d 3e f4 95 35 d3 fe 94 fc 95 ;.6.*..>..5.....
0007:bf50 f3 a2 03 07 16 16 a0 aa a8 6f 18 97 8d 47 77 90 .........o...Gw.
0007:bf60 36 64 50 de 9a 3e 52 65 72 00 c5 69 eb 22 66 8a 6dP..>Rer..i."f.
0007:bf70 55 bd 9a 22 16 91 66 ce 8d 74 94 db 62 d9 86 cf U.."..f..t..b...
0007:bf80 28 f7 9e c1 58 7c 87 a9 1e b5 0a 2f e9 9e 3c e7 (...X|...../..<.
0007:bf90 47 b0 3b a2 00 00 00 00 G.;.....</code>
<blockquote>
A portion of the output of Jhex dumping itself.
</blockquote>
Usage
CLI Tool
Running <code>zig build</code> will produce the <code>jhex</code> CLI tool. It works similarly to the
classic <code>xxd</code> program.
Zig Library
All of the code for creating hex dumps is contained in <code>src/hexdump.zig</code>. Easy
integration with other Zig programs has been a design goal from the start. To
use, simply build <code>src/hexdump.zig</code> with your project and use the <code>HexDumper</code>
interface. See <code>src/main.zig</code> for a usage example.
License
Copyright © 2022 Jon Palmisciano; licensed under the BSD-3-Clause license. | []
|
https://avatars.githubusercontent.com/u/57440386?v=4 | zp | karitham/zp | 2022-03-16T17:10:49Z | a simple, fast shell prompt | master | 1 | 7 | 0 | 7 | https://api.github.com/repos/karitham/zp/tags | MIT | [
"shell-prompt",
"zig",
"zsh"
]
| 4,892 | false | 2022-12-24T06:32:46Z | true | false | unknown | github | []
| zp
A blazing fast prompt. Written in zig.
Looks like this.
```bash
./karitham/zp ⚡️ 0.10.0-dev master >>
./../. on $(git branch --show-current) >>
```
In zsh, you can then set it like <code>eval "$(zp hook)"</code>
It's dependant on libgit2 for git stuff. | []
|
https://avatars.githubusercontent.com/u/2614101?v=4 | shadowsocks-zig | RobinKa/shadowsocks-zig | 2022-12-25T18:09:53Z | Implementations of Shadowsocks 2022 written in Zig | master | 1 | 7 | 3 | 7 | https://api.github.com/repos/RobinKa/shadowsocks-zig/tags | MIT | [
"native",
"proxy",
"shadowsocks",
"shadowsocks-2022",
"shadowsocks-client",
"shadowsocks-server",
"vpn",
"zig"
]
| 111 | false | 2024-07-29T03:09:54Z | true | false | unknown | github | []
| Shadowsocks written in Zig
Client and server implementation of <a>Shadowsocks 2022</a> written in <a>Zig</a>.
Shadowsocks 2022 is an encrypted proxy protocol utilizing a pre-shared key and was designed to be hard to detect to avoid government censorship.
Features
The main function will run a server. The first argument will be used for the path to the json config (see the <a>configs directory</a> for examples). If no argument is passed, the environment variables <code>SHADOWSOCKS_PORT</code>, <code>SHADOWSOCKS_KEY</code> and <code>SHADOWSOCKS_METHOD</code> will be used and all need to be set.
The client is currently just a struct with an interface similar to sockets, see the <a>tests</a> for how to use it.
The following encryption methods are currently supported:
<ul>
<li>Blake3Aes128Gcm</li>
<li>Blake3Aes256Gcm</li>
<li>Blake3ChaCha8Poly1305</li>
<li>Blake3ChaCha12Poly1305</li>
<li>Blake3ChaCha20Poly1305</li>
</ul>
UDP is not yet supported. | []
|
https://avatars.githubusercontent.com/u/22038970?v=4 | bp-jit | paoda/bp-jit | 2022-11-08T05:14:15Z | A BytePusher Virtual Machine featuring a basic Dynamic Recompiler | main | 0 | 7 | 0 | 7 | https://api.github.com/repos/paoda/bp-jit/tags | - | [
"bytepusher",
"dynarec",
"emudev",
"jit",
"virtual-machine",
"x86-64",
"zig"
]
| 154 | false | 2025-05-04T00:41:55Z | true | true | unknown | github | [
{
"commit": "6aa5180eeadde1475359dea355ce3df534e4ab4b.tar.gz",
"name": "zig-clap",
"tar_url": "https://github.com/Hejsil/zig-clap/archive/6aa5180eeadde1475359dea355ce3df534e4ab4b.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/Hejsil/zig-clap"
},
{
"commit": "0ea4948b8b4a470284b8b72780e680321d7ffd29.tar.gz",
"name": "mach-glfw",
"tar_url": "https://github.com/hexops/mach-glfw/archive/0ea4948b8b4a470284b8b72780e680321d7ffd29.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/hexops/mach-glfw"
},
{
"commit": "8e4d73150af291d63a5390b157552ce0bbcd4a1d.tar.gz",
"name": "mach-sysaudio",
"tar_url": "https://github.com/hexops/mach-sysaudio/archive/8e4d73150af291d63a5390b157552ce0bbcd4a1d.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/hexops/mach-sysaudio"
},
{
"commit": null,
"name": "glfw",
"tar_url": null,
"type": "remote",
"url": "https://pkg.machengine.org/glfw/7b1a45feeacf876428bfbd924d4aca9a9a158cd9.tar.gz"
},
{
"commit": null,
"name": "zgui",
"tar_url": null,
"type": "remote",
"url": "https://git.musuka.dev/paoda/zgui/archive/9099f4b05c18ec0dbd90be90c75b1f8cc36210fd.tar.gz"
}
]
| Byte Pusher Virtual Machine
A <a>BytePusher</a> virtual machine that translates the one <a>ByteByteJump</a> instruction to x86-64 assembly.
Scope
I wanted to explore Just-In-Time compilers with the hope of maybe writing one for a more complicated instruction set sometimes in the future. This was my "first step" towards that goal. This project's compiler is non-optimizing and so it's not actually any faster than the interpreter from what I could see (note: didn't do any serious benchmarking)
TODO
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Audio
Usage
This application is run from the terminal. A typical command might look like: <code>./bp-jit ./bin/demo/nyan.bp</code>
Building
Most recently built on Zig <a>v2024.1.0-mach</a>
Dependencies
Dependency | Source
--- | ---
mach-glfw | <a>https://github.com/hexops/mach-glfw</a>
zgui | <a>https://github.com/michal-z/zig-gamedev</a>
zig-clap | <a>https://github.com/Hejsil/zig-clap</a>
<code>gl.zig</code> | <a>https://github.com/MasterQ32/zig-opengl</a>
<code>gl.zig</code> is an auto-generated file providing bindings for <a>OpenGL</a>
Controls
The BytePusher inherits the <a>CHIP-8</a> set of controls. In this project, they're defined as:
<code>+---+---+---+---+
| 1 | 2 | 3 | 4 |
+---+---+---+---+
| Q | W | E | R |
+---+---+---+---+
| A | S | D | F |
+---+---+---+---+
| Z | X | C | V |
+---+---+---+---+
</code> | []
|
https://avatars.githubusercontent.com/u/115832001?v=4 | romforth | romforth/romforth | 2022-10-14T18:46:20Z | Ultra Portable, Small, Baremetal Forth for various processors | main | 0 | 7 | 0 | 7 | https://api.github.com/repos/romforth/romforth/tags | AGPL-3.0 | [
"6502",
"arm64",
"forth",
"m68k",
"msp430",
"padauk",
"pdk14",
"pdp11",
"risc-v64",
"sparc",
"wasm",
"x86",
"x86-16",
"x86-32",
"x86-64",
"x86-nasm",
"z180",
"z80",
"z80n",
"zig"
]
| 3,192 | false | 2025-05-12T16:17:00Z | false | false | unknown | github | []
| romforth is a small, portable, baremetal version of Forth which has been ported
to various 8/16/32/64-bit microcontrollers with support for both big and little
endian architectures. So far, it has been ported to the following instruction
sets: x86 (16-bit, 32-bit and 64-bit), PDP11, 68000, SPARC, Z80, MSP430, ARM64,
RISC-V(rv32, rv64), WASM, Padauk, 6502.
So, at a superficial level, romforth is just yet another Forth which has been
ported to a wide variety of CPUs and is meant to be runnable directly from the
Flash/ROM of the microcontroller.
Dig deeper though, and you might see that romforth can also be considered a
"porting toolkit" which enables a "stepwise porting framework" that allows you
to port Forth "relatively easily" to any of your favorite CPU architectures.
The various ports that have been done already can be then be considered as
proof of concept of this approach to porting Forth.
At this point you might reasonably ask: Why use Forth for microcontrollers?
I'll go ahead and claim that Forth is a perfect fit for small, resource
constrained systems. Perhaps elsewhere too, but opinions widely differ on that.
Here's some sample code that might be used to blink an LED every second:
<code>loop{
green led_on
500 millisec sleep
green led_off
500 millisec sleep
}loop
</code>
romforth is yet another Forth-like implementation meant to (eventually)
run on most "low end" (ie ROM and RAM constrained) microcontrollers.
See PORTING for a list of architectures to which romforth has been ported
as well as all the steps that are required for porting to a new architecture.
Unlike many Forth implementations which require a large number of "words" to
be implemented before you can do anything with it, romforth is meant to be a
"shrink to fit" implementation where the user decides how much of the Forth
functionality they really need and only implement what they really require.
There are four "levels" of Forth that could be implemented in this way.
For lack of better names, I'll refer to these "levels" as:
1/4 : "oneforth" (pun intended), which has only primitives and a data stack
ROM : ~256 bytes, RAM : in the single digit byte range?
2/4 : "twoforth" which has definitions and a return stack (in addition to
the primitives and data stack that "oneforth" has)
ROM : ~256 bytes, RAM : 16 bytes (or thereabouts in two digit byte range)
3/4 : "threeforth" which has a static dictionary (in addition to the primitives
and definitions and the two stacks that "twoforth" has)
ROM : ~512 bytes, RAM : 16 bytes (or thereabouts in two digit byte range)
4/4 : a full fledged "fourforth"/full/regular Forth with a dynamic dictionary
in addition to the rest of the bells and whistles from "threeforth".
ROM : ~1024 bytes, RAM : 512 bytes or more - to hold the dictionary
These levels are further broken down into a total of ~73 individual steps which
implement incremental pieces of Forth functionality. Each of these steps comes
with tests that can be run to verify each additional piece of functionality as
it is added, one at a time, which helps in having a working implementation at
each and every step along the way.
By design, the most compact implementation is limited to use just a little over
~256 bytes of native code with the rest of the functionality implemented in
machine independent code. Currently, ~100 bytes of machine independent Forth
related functionality is used in the x86 implementation. So the overall
Flash/ROM requirement on x86 is currently about ~350 bytes.
As mentioned earlier, there is also a regression test suite which is called at
boot as part of init (which can be optionally #ifdef'ed out) and that currently
takes an additional ~500 bytes of machine independent code.
romforth is meant to be extended using new "purpose built" Forth words which
can be defined in terms of existing Forth words. The new definitions can be
added in the machine independent "defs.4th".
The new words that have been defined can then be called directly as part of
the CPU boot code/initialization by adding them to "rom.4th".
Running "make" will generate a "forth" binary which can be flashed into ROM
(although in all of the implementations that have been completed so far, the
testing is done using emulation, not actual hardware). I hope to run this on
actual hardware real soon now.
The following (mostly) traditional Forth runtime words are available:
Data Stack operators : dup drop nip dip swap over rot 2drop third fourth
Data Stack get/set ops : pick stick
Arithmetic : + - inc(1+) dec(1-) neg
Memory access : ! @ c! c@
Comparison operators : > < >= <= 0= ~
I/O : key emit p@ p!
Memory allocation : here alloc
Return stack operators : >r r>
Call/return : enter exit call exec
Loop index : i
Literals : lit
Bit operators : & | ^ << >> inv
Control flow : j(branch) jz(branch0) jnz(branchnz)
Stack switch operators : sp@! rp@!
Halt : bye
Conditionals : if{ ... }else{ ... }if
unconditional loop : loop{ ... }loop
while loop : loop{ ... }while{ ... }loop
until loop : loop{ ... }until{ ... }loop
for loop : for{ ... }for
At the "oneforth" and "twoforth" levels of the implementation, compared to
regular Forth, what is not available is the dictionary. We make up for that by
providing an "umbilical host"ed solution using a set of scripts, which runs on
the host, and will turn the Forth code into byte code which can be run on top
of the ~350 byte "runtime". This "umbilical host" provides control flow
structures such as conditionals and loop structures which are identical to
the ones available at runtime in the dictionary at the "threeforth"/"fourforth"
levels of the implementation.
So, using about ~350 bytes of "runtime", we can write architecture independent
loops (while, until, for), conditionals (if, else), allocate memory, and even
run threads or invoke semi/full-coroutines (if your proclivities tend that way)
It is reasonable to ask what distinguishes this Forth implementation from
the zillion other implementations that already exist. I think the main
distinguishing features are that it is portable, small and runs baremetal:
1. Portable : romforth currently runs on 8/16/32/64 bit architectures as well
as little and big endian CPUs. It was designed with portability in mind
so as to eventually be able to run on "most" microcontrollers. The
primitives implemented in native code are only a few instructions
each. For a compact implementation, only ~256 bytes of native code
will need to be ported to a new architecture.
2. Small : Designed for low end microcontrollers
On x86, a minimal init needs ~350 bytes of code and 7 bytes of RAM
As a proof of concept, for even smaller systems, I've coded up an
x86 bootloader which needs just a dozen bytes of x86 native code
to load the additional bytes in via any available serial interface
- either from an "umbilical host" during testing or from, say, an
external SPI flash part.
3. Baremetal : Can run directly on the hardware, doesn't require any other
underlying runtime or OS support.
License
All of the code here is licensed under the Affero GPL 3.0 open source license.
For exact details about the license please see the LICENSE file. For the
thinking/intent behind the choice of AGPL, see LICENSE.README
Rationale
For a long winded explanation of why this project exists, see RATIONALE
Installation
To make a local copy:
git clone https://github.com/romforth/romforth
To build/test, the following dependencies need to be installed:
(Note 1: the version number in parentheses is the "known to work" version used
in testing, older/newer versions may or may not work)
(Note 2: If you are only doing a partial build for a specific processor by
running <code>make</code> within a subdirectory, a subset of these dependencies is
sufficient. For example, for the x86 port, a C compiler and the <code>nasm</code>
x86 assembler might be more than sufficient.)
<code>- perl (v5.22.1)
- nasm (version 2.15.05 compiled on Aug 28 2020)
- gcc (version 5.3.1 20160413 (Ubuntu 5.3.1-14ubuntu2))
- binutils ((GNU Binutils) 2.38)
- pdp11
- m68k
- sparc
- msp430
- aarch64
- riscv64
- riscv32
- simh (open-simh V4.0-0 Current git commit id: 33aad325)
- zig (0.11.0)
- qemu (7.1.0, via nix)
- sdcc(ucsim) (4.2.0 #13081 (Linux), ucsim: 0.6.4)
- m4 ((GNU M4) 1.4.17)
- msp430-gcc ((GCC) 4.6.3 20120301 (mspgcc LTS 20120406 unpatched))
- mspdebug(from github.com/romforth/mspdebug, until my changes
are upstreamed)
- wasmtime (wasmtime-cli 9.0.4)
- perl6 (version 2015.11 built on MoarVM version 2015.11)
</code>
After installing all the above dependencies, running <code>make</code> will build each of
the ports and run each of them in an emulator and should complete successfully.
To do a partial build, you can go into any individual processor specific
directory and run <code>make</code> within that subdirectory.
ROM/RAM Requirements
The table below lists the current ROM usage (in bytes) of the various ports:
.--------------.------------.-----------------.-----------------.
| CPU | Primitives | Forth bytecodes | Forth bytecodes |
| | | (total) | TESTROM (total) |
+--------------+------------+-----------------+-----------------+
| x86 | 264 | 1619 (1883) | 3047 (3311) |
| x86-as | 264 | 1619 (1883) | 3047 (3311) |
| PDP11 | 276 | 2140 (2416) | 4272 (4548) |
| x86-user | 445 | 3245 (3690) | 6548 (6993) |
| C/x86 | 445 | 3928 (5848) | 6985 (7430) |
| x86-32 | 385 | 2229 (2614) | 4288 (4673) |
| x86-sys | 518 | 3245 (3763) | 6548 (7066) |
| m68k | 378 | 2280 (2658) | 4348 (4726) |
| sparc | 956 | 2208 (3164) | 4315 (5271) |
| z80 | 491 | 1735 (2231) | 3178 (3674) |
| z80-c | 1588 | 1563 (3151) | 2927 (4515) |
| z180-sdcc | 1590 | 1563 (3153) | 2927 (4517) |
| z80n-sdcc | 1584 | 1563 (3147) | 2927 (4511) |
| msp430-as | 270 | 2540 (2810) | 4672 (4942) |
| arm-zigcc | 1272+.. | 3036 (4308) | 5762 (7034) |
| arm64-sys | 1060 | 3336 (4396) | 6664 (7724) |
| riscv-zigcc | 1124+.. | 3036 (4160) | 5762 (6886) |
| rv64-sys | 692 | 3336 (4028) | 6664 (7356) |
| rv32-sys | 692 | 2302 (2994) | 4374 (5066) |
| msp430-stc | 0 | 4328 (4328) | 10060 (10060) |
| z80-stc | 0 | 3456 (3456) | 7090 (7090) |
| msp430-fcode | 344 | 2064 (2408) | 3308 (3652) |
| msp430-f | 344 | 602 (946) | 1408 (1752) |
| nqh-zig | 9387 | 341 (9728) | 1009 (10396) |
| wasm32-c | 1735 | 2840 (4575) | 5552 (7287) |
| pdk14-stc<em> | 0 | 15 (125) | 503 (613) |
| pdk14-thr1</em> | 264 | 40 (304) | 609 (873) |
| 6502-sdcc | 2624 | 2060 (4684) | 3495 (6119) |
| 6502-stc | 0 | 859 (859) | 3386 (3386) |
'--------------'------------'-----------------'-----------------'
*Note: The units for pdk14-stc and pdk14-thr1 are in "words" which can be
13/14/15/... bits long depending on the processor family. | []
|
https://avatars.githubusercontent.com/u/3759175?v=4 | cache | Hejsil/cache | 2022-07-29T20:56:40Z | Provides caching for any command line tool that does not have it | master | 1 | 7 | 0 | 7 | https://api.github.com/repos/Hejsil/cache/tags | MIT | [
"cache",
"cli",
"zig"
]
| 48 | false | 2025-05-07T13:48:33Z | true | true | 0.14.0 | github | [
{
"commit": "13c0daa5276fba9ae4f81a0e839733b068126dc8",
"name": "clap",
"tar_url": "https://github.com/Hejsil/zig-clap/archive/13c0daa5276fba9ae4f81a0e839733b068126dc8.tar.gz",
"type": "remote",
"url": "https://github.com/Hejsil/zig-clap"
}
]
| cache
Can wrap any command line tool to provide caching for the output of that tool.
Example
```sh
$ # We can use curl to get the weather data from wttr.in
$ curl -s 'https://wttr.in/'
...
$ # Caching this command is simple. It only depends on the arguments of the command,
$ # and outputs to stdout
$ cache -- curl -s 'https://wttr.in/'
...
$ # Now, this is cached and will never be invalidated (unless you delete
$ # ~/.cache/cache). We can specify that the command depends on external data. Let's
$ # have it depend on the output of <code>date</code>, so the cache is invalidated each day
$ cache -s "$(date +%Y-%m-%d)" -- curl -s 'https://wttr.in/'
...
$ # You can mark a command to depend on different things like environment variables
$ # (-e), files (-f) or even stdin (--stdin).
$ # cache can also handle if a command outputs to one or more files. You need to
$ # manually list the files the command will output
$ cache -o test -f test.c -- gcc -o test test.c
``` | [
"https://github.com/karlseguin/aolium-api"
]
|
https://avatars.githubusercontent.com/u/25674682?v=4 | zofi | spazzylemons/zofi | 2022-07-01T04:14:20Z | Wayland application launcher written in Zig | master | 0 | 7 | 0 | 7 | https://api.github.com/repos/spazzylemons/zofi/tags | MIT | [
"wayland",
"zig"
]
| 109 | false | 2025-04-21T07:36:17Z | true | false | unknown | github | []
| zofi
A straightforward Wayland application launcher similar to rofi and dmenu.
Building
<ul>
<li>GTK 3</li>
<li>gtk-layer-shell</li>
<li>pkg-config</li>
<li>The latest version of Zig</li>
</ul>
Run <code>zig build</code> to build zofi. The executable is placed at <code>zig-out/bin/zofi</code>.
See <a>this link</a> for
building an optimized binary. To see all available options, run
<code>zig build --help</code>.
Usage
zofi runs in Wayland compositors that support the layer shell protocol. You can
use <code>wayland-info</code> within a compositor to check for support.
To use zofi, enter a command and press enter to run it. If your command matches
an executable on the PATH, you can select it from a list of suggestions by
pressing up and down, and pressing enter to run the highlighted program. Press
tab with an executable selected to insert the full executable name into the
command bar, allowing you to add command-line parameters. Press escape to close
zofi without running anything.
Configuration
zofi uses GTK 3, so most graphical elements of zofi are configured directly by
your GTK 3 theme. The size of the window can be specified using command-line
arguments. Run <code>zofi -h</code> for more information.
License
zofi is licensed under the MIT License. | []
|
https://avatars.githubusercontent.com/u/14948182?v=4 | zlru | v0idpwn/zlru | 2022-09-04T02:16:58Z | LRU cache implementation in Zig | master | 0 | 6 | 0 | 6 | https://api.github.com/repos/v0idpwn/zlru/tags | - | [
"lru",
"zig"
]
| 6 | false | 2023-05-21T16:27:15Z | true | false | unknown | github | []
| ZLRU
Zig implementation of a LRU cache. | []
|
https://avatars.githubusercontent.com/u/1193542?v=4 | zig-sdl-playground | remyroez/zig-sdl-playground | 2022-07-23T06:24:55Z | ⚡ my zig playground with SDL2 | main | 0 | 6 | 1 | 6 | https://api.github.com/repos/remyroez/zig-sdl-playground/tags | MIT | [
"practice",
"sdl",
"sdl2",
"zig"
]
| 55 | false | 2024-06-02T07:29:38Z | true | false | unknown | github | []
| zig-sdl-playground
⚡ my zig playground with SDL2
Dependencies
<ul>
<li><a>zig</a> 0.10.0</li>
<li><a>vcpkg</a><ul>
<li>sdl2</li>
<li>sdl2-image</li>
<li>sdl2-mixer[libvorbis]</li>
<li>sdl2-ttf</li>
</ul>
</li>
</ul>
Assets
<ul>
<li>texture: <a>ziglang/logo - Zero the Ziguana</a></li>
<li>sound: <a>Sci-Fi Sounds</a></li>
<li>font: <a>Kenney Fonts - Kenney Future</a></li>
</ul>
Build and Run
<code>zig build run</code> | []
|
https://avatars.githubusercontent.com/u/11492844?v=4 | zigode | fjebaker/zigode | 2022-09-18T01:31:54Z | ⚡️ Ordinary differential equations in Zig. | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/fjebaker/zigode/tags | MIT | [
"differential-equations",
"ode",
"ode-solver",
"ordinary-differential-equations",
"solvers",
"tsit5",
"zig"
]
| 196 | false | 2024-10-14T04:57:41Z | true | false | unknown | github | []
| Zigode
Ordinary differential equation solving in pure Zig and almost entirely on the stack! Tiny weekend project, will probably not be actively maintained.
Usage
```zig
const std = @import("std");
const zigode = @import("zigode");
// define problem
fn lorenz(du: <em>[3]f64, u: </em>const [3]f64, _: f64, p: *LorenzParams) void {
du[0] = p.sigma * (u[1] - u[0]);
du[1] = u[0] * (28.0 - u[2]) - u[1];
du[2] = u[0] * u[1] - (p.beta) * u[2];
}
// problem parameters
const LorenzParams = struct{
sigma: f64 = 10.0,
beta: f64 = 8.0 / 3.0
};
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
pub fn main() !void {
defer _ = gpa.deinit();
// need to tell the solver the function and parameter type
// so that everything can be comptime resolved and stack allocated
var prob = zigode.Tsit5(lorenz, LorenzParams).init(.{});
<code>// get common solver interface
var solver = prob.solver(gpa.allocator());
const u: [3]f64 = .{1.0, 0.0, 0.0};
var sol = try solver.solve(
u, 0.0, 100.0, .{.save = true, .dt = 1e-2, .max_iters = 10_000}
);
defer sol.deinit();
// print solution overview to stdout
const stdout = std.io.getStdIn();
try sol.printInfo(stdout);
// then write it to a file and plot it with your plotting package of choice
</code>
}
```
Solvers
Currently implemented is only the basic fixed step-size Newton method, and Tsitouras 5/4 Runge Kutta.
Plan
The scope of this project is just so I can write a quick weekend relativistic ray tracer in Zig, and so the plan is extremely limited:
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Callback functions
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Adaptive step size algorithms
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Serialise and export solution to known format
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Multi-threaded solving
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> (stretch) Interpolations
Citations
This work is heavily inspired by the Julia <a>DifferentialEquations.jl</a> library and SciML ecosystem. The Tsitouras 5/4 coefficients are taken directly from their implementation. | []
|
https://avatars.githubusercontent.com/u/41510086?v=4 | zig-http-client | ddddddO/zig-http-client | 2022-07-29T12:29:37Z | [WIP] 🎈HTTP client lib for Zig. Inspired by go-resty! | main | 2 | 6 | 0 | 6 | https://api.github.com/repos/ddddddO/zig-http-client/tags | MIT | [
"http-client",
"zig"
]
| 52 | false | 2023-09-22T13:19:22Z | true | false | unknown | github | []
| <strong>WIP</strong> zig-http-client
HTTP client lib for Zig. Inspired by <strong><a>go-resty</a></strong>!
Todo
HTTP method
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> GET
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> POST
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> DELETE
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> PUT
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> HEAD
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> PATCH
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> OPTIONS
etc
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> HTTPS support
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> query parameter set func
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> retry support
Usage
GET method
```zig
const std = @import("std");
const HttpClient = @import("zig-http-client").HttpClient;
pub fn main() anyerror!void {
const allocator = std.heap.page_allocator;
const host = "www.google.com";
<code>const client = HttpClient.init(allocator);
const res = try client.req()
.setHeader("Accept: text/html")
.get(host);
defer res.deinit();
const writer = std.io.getStdOut().writer();
try writer.print("Status Line: {s}\n", .{res.statusLine()});
try writer.print("Status Code: {s}\n", .{res.statusCode()});
try writer.print("Status: {s}\n", .{res.status()});
// Output:
// Status Line: HTTP/1.1 200 OK
// Status Code: 200
// Status: OK
</code>
}
```
POST and GET method (with Cookie)
```zig
const std = @import("std");
const HttpClient = @import("zig-http-client").HttpClient;
pub fn main() anyerror!void {
const allocator = std.heap.page_allocator;
const client = HttpClient.init(allocator);
<code>const user_name = std.os.getenv("NAME");
const password = std.os.getenv("PASSWORD");
var body = try std.fmt.allocPrint(allocator, "name={s}&passwd={s}", .{ user_name, password });
defer allocator.free(body);
var content_length_header = try std.fmt.allocPrint(allocator, "Content-Length: {d}", .{body.len});
defer allocator.free(content_length_header);
const host = "http://localhost:8082/auth";
const res = try client.req()
.setHeader("Content-Type: application/x-www-form-urlencoded")
.setHeader(content_length_header)
.setBody(body)
.post(host);
defer res.deinit();
var cookie_header = try std.fmt.allocPrint(allocator, "Cookie: {s}", .{res.cookie()});
defer allocator.free(cookie_header);
const host_2 = "http://localhost:8082/memos?userId=1";
const res_2 = try client.req()
.setHeader(cookie_header)
.get(host_2);
defer res_2.deinit();
const writer = std.io.getStdOut().writer();
try writer.print("Status Line: {s}\n", .{res_2.statusLine()});
// Output:
// Status Line: HTTP/1.1 200 OK
</code>
}
``` | []
|
https://avatars.githubusercontent.com/u/40190339?v=4 | spacewasm | daneelsan/spacewasm | 2022-08-25T03:48:51Z | Original 1962 game code running on a PDP-1 emulator in Zig + Wasm + JS + HTML5 Canvas | master | 0 | 6 | 0 | 6 | https://api.github.com/repos/daneelsan/spacewasm/tags | - | [
"html5-canvas",
"js",
"wasm",
"zig"
]
| 125 | false | 2025-04-16T02:32:53Z | true | false | unknown | github | []
| Spacewasm
Original 1962 game code running on a PDP-1 emulator in Zig + Wasm + JS + HTML5 Canvas
See it live at: https://daneelsan.github.io/spacewasm/
"a", "d", "s", "w" to control the first spaceship, the <em>"Needle"</em>.
"j", "l", "k", "i" to control the second spaceship, the <em>"Wedge"</em>.
The controls are spin one way, spin the other, thrust, and fire.
Keep away from the central star that pulls the ships with gravity.
The game ends when any of the ships explode into pixel dust.
Build
To build the .wasm file (and put it in the appropriate place), run:
```shell
$ zig build && cp zig-out/bin/space.wasm docs/space.wasm
$ ls docs/*.wasm
docs/space.wasm
```
<code>shell
$ zig version
0.14.0</code>
TODO
[ ] Fix a bug that occurs when a ship crashes with the central star and launches it in an erratic pattern
[ ] Implement a fully featured Type 30 CRT display (phosphor decay, intensity levels, etc.)
[ ] Improve the "game loop" by using <code>requestAnimationFrame</code> instead of <code>setInterval</code>
[ ] Abstract the IO devices away from the PDP1.zig file
[ ] Abstract the platform away (the only target right now is Wasm + JS)
Resources
<ul>
<li>https://spacewar.oversigma.com</li>
<li>https://www.masswerk.at/spacewar/</li>
<li>http://www.bitsavers.org/pdf/dec/pdp1/F15D_PDP1_Handbook_Oct63.pdf</li>
<li>http://www.bitsavers.org/pdf/dec/pdp1/F25_PDP1_IO.pdf</li>
<li>http://bitsavers.org/pdf/dec/_Books/Bell-ComputerEngineering.pdf</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/88548934?v=4 | ZMC | lbirkert/ZMC | 2023-02-05T20:33:59Z | asynchronous minecraft reverse proxy written in zig | main | 0 | 6 | 1 | 6 | https://api.github.com/repos/lbirkert/ZMC/tags | MIT | [
"async",
"minecraft",
"proxy",
"zig"
]
| 40 | false | 2024-08-19T19:35:56Z | true | true | unknown | github | [
{
"commit": "4ad3002e9d6abc160a66c21cff4e99e47d220bc3.tar.gz",
"name": "zig_network",
"tar_url": "https://github.com/MasterQ32/zig-network/archive/4ad3002e9d6abc160a66c21cff4e99e47d220bc3.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/MasterQ32/zig-network"
}
]
| <code>$$$$$$$$\ $$\ $$\ $$$$$$\
\____$$ | $$$\ $$$ |$$ __$$\
$$ / $$$$\ $$$$ |$$ / \__|
$$ / $$\$$\$$ $$ |$$ |
$$ / $$ \$$$ $$ |$$ |
$$ / $$ |\$ /$$ |$$ | $$\
$$$$$$$$\ $$ | \_/ $$ |\$$$$$$ |
\________|\__| \__| \______/</code>
<a></a>
<code>ZMC</code> is an asynchronous reverse proxy for <a>Minecraft</a> written in <a>ZIG</a>.
It allows you to host multiple Minecraft servers reachable over different domains via a single IP address.
<strong>NOTE</strong> <code>ZMC</code> requires the latest ZIG version from the <code>master</code> branch.
Cloning
<code>git clone --recursive https://github.com/KekOnTheWorld/ZMC</code>
Configuration
The file path can be passed as a commandline argument to <code>ZMC</code>: <code>zig build run -- yourconfig.zon</code>
The configuration itself is in the <code>ZON</code> (<strong>Z</strong>ig <strong>O</strong>bject <strong>N</strong>otation) file format.
An example configuration can be found at <code>config.zon</code>.
address
The address the server will listen on. Recommended is <code>0.0.0.0</code> for IPv4 and <code>::1</code> for IPv6.
port
The port the server will listen on. Minecraft uses <code>25565</code> as its default port.
gateways
An array of gateways. A gateway contains a hostname (the domain this gateway will be accessible from, which
should have an A/AAAA record pointing to the server <code>ZMC</code> is running on), an address (the address to your
local Minecraft server; probably <code>localhost</code>/<code>127.0.0.1</code>/<code>::1</code>), and a port (the port of your local
Minecraft server).
Building
<code>zig build -Doptimize=ReleaseSafe</code>
<code>zig build -Doptimize=ReleaseSmall</code>
<code>zig build -Doptimize=ReleaseFast</code>
The executable will be located in the <code>zig-out</code> directory.
License
<code>ZMC</code> is licensed under the <a>MIT License</a>.
Special Thanks To
<ul>
<li>The ZIG team and foundation for making such an amazing language. <a>Sponsor</a></li>
<li>MasterQ32 for the <code>zig-network</code> library providing async I/O. <a>Sponsor</a></li>
<li>Everyone willing to contribute</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/54106488?v=4 | scafetch | iddev5/scafetch | 2022-02-22T12:44:18Z | A command line tool to display information about remote repositories | master | 0 | 6 | 1 | 6 | https://api.github.com/repos/iddev5/scafetch/tags | MIT | [
"cli-app",
"git",
"zig",
"ziglang"
]
| 81 | false | 2024-07-11T15:16:17Z | true | true | unknown | github | [
{
"commit": "80c1df8b85214bd8d3bd61458cd9e6533880dc1f.tar.gz",
"name": "ay-arg",
"tar_url": "https://github.com/iddev5/ay-arg/archive/80c1df8b85214bd8d3bd61458cd9e6533880dc1f.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/iddev5/ay-arg"
}
]
| scafetch
<a></a>
<a></a>
<a></a>
Scafetch is a command-line tool to display information about your remote Git repositories in an aesthetic and visually pleasing way.
It currently supports fetching repository information from Github, Gitlab and Codeberg (Gitea).
Installation
Releases
You can get the latest stable <a>release</a> from Github.
Arch Linux (AUR)
Install the community maintained <a>scafetch</a> package.
Usage
You only need Zig master to compile.
Use zig to build:
<code>zig build -Doptimize=ReleaseSafe</code>
(You can optionally install it in a system or user wide directory for easier access, use the <code>-p <prefix></code> flag for convenience)
Then, run the application:
<code>./zig-out/bin/scafetch ziglang/zig</code>
where <code>ziglang/zig</code> is taken as an example repository address, and the host defaults to Github
It is also possible to explicitly state the host service name using <code>-o <hostname></code> flag. See <code>--help</code> for more information.
Scafetch can additionally infer the host service from hints present in the given URL:
Host name | 1 | 2 | 3
----------|------------------------|------------------------------|---------------------------------
Github | <code>gh/<author>/<repo></code> | <code>github/<author>/<repo></code> | <code>github.com/<author>/<repo></code>
Gitlab | <code>gl/<author>/<repo></code> | <code>gitlab/<author>/<repo></code> | <code>gitlab.com/<author>/<repo></code>
Codeberg | <code>cb/<author>/<repo></code> | <code>codeberg/<author>/<repo></code> | <code>codeberg.org/<author>/<repo></code>
Todo
<ul>
<li>More CLI flags, like opt out of coloring, what info to display etc.</li>
<li>Authentication support</li>
<li>Show an ASCII art of the primary language(?) of the repository</li>
</ul>
License
scafetch is licensed under <a>MIT License</a> | []
|
https://avatars.githubusercontent.com/u/60808802?v=4 | zigshot | Shinyzenith/zigshot | 2022-05-17T17:20:58Z | Screenshot tool written in zig for wayland compositors implementing zwlr_screencopy_unstable_v1 protocol. | master | 1 | 6 | 1 | 6 | https://api.github.com/repos/Shinyzenith/zigshot/tags | - | [
"screenshot",
"wayland",
"wayland-client",
"zig",
"ziglang"
]
| 23 | false | 2025-02-16T06:03:44Z | true | false | unknown | github | []
| Zigshot
Screenshot tool written in zig for <em>wayland compositors</em> implementing <strong>zwlr_screencopy_unstable_v1 protocol.</strong>
Dependencies:
<ol>
<li><code>zig</code> 0.9.1</li>
<li><code>wayland</code></li>
<li><code>wayland-protocols</code></li>
</ol>
Building
```console
$ git clone https://github.com/shinyzenith/zigshot;cd zigshot
zig build --prefix /usr/local -Drelease-fast
``` | []
|
https://avatars.githubusercontent.com/u/8573972?v=4 | simple-zig-wasm-synthesizer | gaycodegal/simple-zig-wasm-synthesizer | 2022-12-18T21:23:22Z | building a wasm web audio api synthesizer using zig | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/gaycodegal/simple-zig-wasm-synthesizer/tags | MIT | [
"javascript",
"synthesizer",
"wasm",
"webassembly",
"zig"
]
| 101 | false | 2025-05-14T18:32:49Z | false | false | unknown | github | []
| Simple Wave Synthesizer
The intention of this project is to create a small (in code size) synthesizer
to make bit tune sound effect / music for online games. This project is demonstrating compiling a polyphonic synthesizer in Zig and playing it from the web.
It is currently monophonic, but mostly usable.
Read the <a>Write Up</a> to learn how this was made.
Rationale
<ul>
<li>Games can easily use megabytes for music even if the rest of the game is very small due to pixel art or being text based.</li>
<li>mod / xm would be great, but its not a format suited for sound effects, only for music</li>
<li>mod / xm don't allow instruments to use multiple samples</li>
</ul>
Could I have used wave files for sfx and xm for music? Definitely, but I didn't want to, as I had already seen what Tic80 could do.
Progress
In its current state, it could be used to play short sound effects for
online games. The code size is at last check ~19.2kb in js + wasm (without shortening variable names etc), or 8.5kb zipped. The audio it generates is 45kb/s 8bit audio.
The wasm binary itself is only 3kb.
<ul>
<li>Play different notes from a note bank</li>
<li>Play different waveforms from a waveform bank</li>
<li>Music player which doesn't suffer the length limitations of audiobuffer, instead using AudioWorklet</li>
<li>Message passing setup for the music player to allow for dynamic choice of song</li>
<li>Volume control via volume list<ul>
<li>technically, because volume now allows you to play less than at maximum amplitude, you can now do polyphony by just playing multiple things at once with low volume.</li>
</ul>
</li>
<li>can interrupt / resume at any point, meaning support for using a sfx as an instrument in a music track can be worked on now</li>
</ul>
Soon
<ul>
<li>4 track polyphony / maybe 8 track 4 volume, 4 sfx</li>
</ul>
Later
<ul>
<li>Waveform editing</li>
<li>Make music be able to use notes and sfx alike to play music (sfx as instruments)</li>
<li>Make an optional file format for the music</li>
</ul>
Licenses
This project is MIT licensed, the only outside code it uses is the NoteHz taken from Tic80 (which is also MIT Licensed). There is a license file for a file called wavefile.js but that code is not included in this github, and I only use it for testing to verify the waveforms are correct, but if you choose to download that file yourself, you have the license. | []
|
https://avatars.githubusercontent.com/u/587972?v=4 | barn | tw4452852/barn | 2022-06-18T03:28:40Z | :milky_way: A mirror root of your local directory | main | 0 | 6 | 1 | 6 | https://api.github.com/repos/tw4452852/barn/tags | Apache-2.0 | [
"fuse",
"linux",
"zig"
]
| 19 | false | 2025-03-20T02:23:37Z | true | false | unknown | github | []
| Barn
Barn is a tool to mirror your local directory on a remote machine.
demo
<a></a>
Prerequisite
Make sure the remote machine's kernel has enabled <code>CONFIG_FUSE_FS</code>.
This is the only dependency, no others!
Usage
<ol>
<li>Start server on the remote machine:</li>
</ol>
```
barn server
```
By default, it will select a unused port to listen on. Of course you could specify the port with <code>--port</code> option:
```
barn server --port=xxx
```
<ol>
<li>Connect to the server from your local machine:</li>
</ol>
```
barn client --remote= --port=
```
<ol>
<li>Once the initialization is done between server and client,
you should see the mirror directory like this on server's output:</li>
</ol>
<code>serving from <ip>:<port>, the mirror root directory: /tmp/barn_xxx</code>
However, you could also find the location through mount point:
```
mount
...
/dev/fuse on /tmp/barn_xxx type fuse (rw,nosuid,nodev,relatime,user_id=0,group_id=0)
```
<ol>
<li>Now, everything is set successfully, you could do whatever you want in the mirror directory,
everything there is a mirror of your local root directory.
You could even <code>chroot</code> into that directory:</li>
</ol>
```
chroot /tmp/barn_xxx /bin/bash
```
Have fun!
Installation
You could either download the <a>prebuilt binary</a> or build from source.
How to build
<strong>Zig version:</strong> 0.11.0
<code>git clone https://github.com/tw4452852/barn
cd barn
zig build -Dtarget=x86_64-linux-musl</code>
If everything is ok, the binary will be located in <code>./zig-out/bin/barn</code>.
Inspiration
This tool is heavily inspired by the <a>u-root's cpu</a>
which is an implementation of <a>plan9's cpu</a>.
There is <a>an excellant article</a> to talk about it. | []
|
https://avatars.githubusercontent.com/u/18194808?v=4 | zig-template | Inve1951/zig-template | 2022-07-02T21:07:41Z | Base setup for zig projects with IDE glue. | master | 0 | 6 | 1 | 6 | https://api.github.com/repos/Inve1951/zig-template/tags | - | [
"boilerplate",
"template",
"vscode",
"vscode-snippets",
"zig",
"ziglang",
"zls"
]
| 6 | false | 2025-03-26T06:26:46Z | true | false | unknown | github | []
| Zig project template - v1.1
Base setup for zig projects with IDE glue.
Features
<ul>
<li>
vscode integration
<ul>
<li>
IDE "tasks" to build and run the app and tests
</li>
<li>
IDE "launch configurations" to debug the app, all tests, or just the tests in the currently focused zig file
</li>
<li>
format-on-safe via <code>zig fmt</code>
</li>
<li>
<code>zls</code> integration
</li>
<li>
zig file templates (see below)
</li>
</ul>
</li>
<li>
TODO: cover other IDEs when their zig support gets good enough.
</li>
</ul>
Zig File Template Setup
To make use of the included templates do the follow:
<ul>
<li>
install vscode extension <code>Gruntfuggly.auto-snippet</code>
</li>
<li>
apply machine-local settings (see <code>.vscode/user/settings.json</code>) (also needed for format-on-safe and breakpoints)
</li>
<li>
install the templates (see <code>.vscode/user/snippets/zig.json</code>)
</li>
</ul>
These get automatically applied when creating new <code>.zig</code> files. They provide typical boilerplate with smart TAB key navigation.
Usage Notes
Set the executable name in <code>build.zig</code>.
The debugger "launch configurations" depend on the executable name matching the project's folder name.
The <em>debug current file's tests</em> launch configuration does not use <code>build.zig</code>.
Tested on Linux;
<em>should</em> work on Mac OS;
<em>should</em> work on Windows.
<code>zls</code> is expected to be on $PATH. Same goes for <code>zig</code>.
Got any notes? Ping me in the zig discord. | []
|
https://avatars.githubusercontent.com/u/1337349?v=4 | zig-jvm | DomWilliams0/zig-jvm | 2022-09-25T05:44:23Z | Hotspot-compatible JVM in Zig | master | 1 | 6 | 0 | 6 | https://api.github.com/repos/DomWilliams0/zig-jvm/tags | GPL-3.0 | [
"hotspot",
"jvm",
"zig"
]
| 855 | false | 2025-03-04T07:45:22Z | true | false | unknown | github | []
| zig-jvm
A Java Virtual Machine implementation in Zig.
Goals
<ul>
<li>Run Minecraft with <strong>playable</strong> performance<ul>
<li>Ideally the opcode interpreter will be fast enough, but a JIT isn't out of the question.</li>
</ul>
</li>
<li>Provide an API to <strong>create and destroy multiple JVMs within the same process</strong><ul>
<li>Every existing JVM I've looked at uses globals, doesn't clean up after shutdown, and can't be
coexist with other instances in the same process.</li>
</ul>
</li>
</ul>
This makes use of the system Java class files from <code>OpenJDK 18</code>, and reimplements all native code.
Linux only for now.
Features
<ul>
<li>✅ Class parsing and loading</li>
<li>🚧 Module support</li>
<li>🚧 Implement all opcodes<ul>
<li>✅ Implement most important (field access, method calling, conditionals, arithmetic)</li>
<li>🚧 Implement the rest of them</li>
</ul>
</li>
<li>✅ Exceptions (see test case <a>src/test/Throw.java</a>)</li>
<li>✅ Native function resolving and invoking (via <code>libffi</code>)</li>
<li>🚧 Java Native Interface (JNI)<ul>
<li>✅ <code>JNIEnv*</code> passed to native functions</li>
<li>🚧 Actually implement these native functions</li>
</ul>
</li>
<li>🚧 Multiple threads, monitors, <code>synchronized</code> methods</li>
</ul>
(🚧 = in progress or planned)
Example logfile
A snippet from the logs to show the current capabilities:
<code>...
debug: executing java/lang/Throwable.fillInStackTrace
debug: call stack:
* 0) java/lang/Throwable.fillInStackTrace (pc=0)
* 1) java/lang/Throwable.<init> (pc=24)
* 2) java/lang/Exception.<init> (pc=2)
* 3) java/io/IOException.<init> (pc=2)
* 4) java/io/FileNotFoundException.<init> (pc=2)
* 5) Throw.vmTest (pc=6)
debug: operand stack: {}
debug: local vars: [#0: reference, java/io/FileNotFoundException@7f4ab77b7f00]
debug: pc=0: aload_0
debug: operand stack: pushed #1 (reference): java/io/FileNotFoundException@7f4ab77b7f00
debug: operand stack: {#0: reference, java/io/FileNotFoundException@7f4ab77b7f00}
debug: local vars: [#0: reference, java/io/FileNotFoundException@7f4ab77b7f00]
debug: pc=1: getfield
debug: resolving class java/lang/Throwable
debug: operand stack: popped #0 (reference): java/io/FileNotFoundException@7f4ab77b7f00
debug: operand stack: pushed #1 (reference): [java/lang/StackTraceElement@7f4ab780ce00
debug: getfield(java/io/FileNotFoundException@7f4ab77b7f00, stackTrace) = [java/lang/StackTraceElement@7f4ab780ce00
debug: operand stack: {#0: reference, [java/lang/StackTraceElement@7f4ab780ce00}
debug: local vars: [#0: reference, java/io/FileNotFoundException@7f4ab77b7f00]
debug: pc=4: ifnonnull
debug: operand stack: popped #0 (reference): [java/lang/StackTraceElement@7f4ab780ce00
debug: operand stack: {}
debug: local vars: [#0: reference, java/io/FileNotFoundException@7f4ab77b7f00]
debug: pc=14: aload_0
debug: operand stack: pushed #1 (reference): java/io/FileNotFoundException@7f4ab77b7f00
debug: operand stack: {#0: reference, java/io/FileNotFoundException@7f4ab77b7f00}
debug: local vars: [#0: reference, java/io/FileNotFoundException@7f4ab77b7f00]
debug: pc=15: iconst_0
debug: operand stack: pushed #2 (int): 0
debug: operand stack: {#0: reference, java/io/FileNotFoundException@7f4ab77b7f00, #1: int, 0}
debug: local vars: [#0: reference, java/io/FileNotFoundException@7f4ab77b7f00]
debug: pc=16: invokevirtual
debug: resolving class java/lang/Throwable
debug: resolved method to java/io/FileNotFoundException.fillInStackTrace
debug: executing java/io/FileNotFoundException.fillInStackTrace
debug: binding native method
debug: looking for 'Java_java_lang_Throwable_fillInStackTrace'
debug: call stack:
* 0) java/io/FileNotFoundException.fillInStackTrace (native)
* 1) java/lang/Throwable.fillInStackTrace (pc=16)
* 2) java/lang/Throwable.<init> (pc=24)
* 3) java/lang/Exception.<init> (pc=2)
* 4) java/io/IOException.<init> (pc=2)
* 5) java/io/FileNotFoundException.<init> (pc=2)
* 6) Throw.vmTest (pc=6)</code>
Usage
Please note that this is:
* very much WIP
* built with the Zig master branch, and is randomly updated to the latest
(currently <code>0.13.0-dev.365+332fbb4b0</code>).
* will be very unlikely to run arbitrary Java programs any time soon
The way I am progressing through the massive amount of functionality expected from a JVM is to build
up a supply of small programs that exercise different parts of the JVM. These programs are in
<code>src/test</code>, and can be run as follows:
<ul>
<li>Extract the JDK modules file to a directory (until modules are supported)<ul>
<li><code>jimage extract --dir $EXTRACT_DIR /usr/lib/jvm/java-18-openjdk/lib/modules</code></li>
<li>This should give a directory structure where <code>java.base/java/lang/Object.class</code> exists</li>
</ul>
</li>
<li><code>zig build run-testrunner -- -Xbootclasspath $EXTRACT_DIR/java.base</code></li>
</ul>
If you're feeling brave, you can run a given class file, just like the normal <code>java</code> command. Don't
expect it to work though.
If <code>Test.class</code> is in <code>$CLASS_DIR</code>, then run
<code>zig build run-java -- -Xbootclasspath $EXTRACT_DIR:$CLASS_DIR Test</code>
Why?
First of all, why not? This is a great technical project that constantly stretches me.
Also this is my second iteration of implementing a JVM, the <a>first is in Rust</a> and is still pretty incomplete, but suffers from some over-the-top type safety that I wanted to reduce in a second iteration, which would also help with performance. | []
|
https://avatars.githubusercontent.com/u/43641633?v=4 | apscript-zig-archive | sno2/apscript-zig-archive | 2022-11-10T05:02:26Z | An interpreter for the AP© Computer Science Principles pseudocode language written in Zig. | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/sno2/apscript-zig-archive/tags | MIT | [
"zig"
]
| 63 | false | 2024-11-19T06:09:04Z | true | false | unknown | github | []
| APScript (WIP)
An interpreter for the AP© Computer Science Principles pseudocode language
written in <a>Zig</a>.
<blockquote>
Warning: Heavily WIP as this is only on GitHub for me to work on while at
school.
</blockquote>
Examples
Printing to the console
<code>sql
age <- 23
DISPLAY("You are", age, "years old.")</code>
<code>bash
You are 23 years old.</code>
Mutating variables
```sql
age <- 0
REPEAT UNTIL (age > 105) {
age <- age + 1
DISPLAY("You are", age, "years old.")
}
DISPLAY("RIP")
```
<code>bash
You are 1 years old.
You are 2 years old.
You are 3 years old.
You are 4 years old.
...
You are 102 years old.
You are 103 years old.
You are 104 years old.
You are 105 years old.
RIP</code>
Accessing input from the console
<blockquote>
Note: The interpreter always tries to coerce results from <code>INPUT()</code> into numbers first.
If that fails, then it returns a string.
</blockquote>
<code>sql
age <- INPUT("What is your age?")
DISPLAY("You are", age, "years old and will be", age + 1, "next year!")</code>
<code>bash
What is your age? 23 [Enter]
You are 23 years old and will be 24 next year!</code>
License
<a>MIT</a> | []
|
https://avatars.githubusercontent.com/u/12129065?v=4 | zig-protobuf | shailpatels/zig-protobuf | 2023-01-20T00:12:22Z | Protobuf implementation for the Zig programming language | main | 0 | 6 | 0 | 6 | https://api.github.com/repos/shailpatels/zig-protobuf/tags | MIT | [
"protobuf",
"zig"
]
| 60 | false | 2025-04-17T14:28:37Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "protobuf",
"tar_url": "https://github.com/shailpatels/protobuf/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/shailpatels/protobuf"
}
]
| Zig-Protobuf
About
Zig-Protobuf is an implementation of <a>Google's Protocal Buffers (Protobuf)</a>. The project
is currently in development and incomplete. It has two parts, <code>protoc-zig</code>, a protoc plugin that parses <code>.proto</code> files
and generates zig code, and a Protobuf interface that is currently focused on serializing the protobuf wire format.
The goal is to take <code>.proto</code> files and produce readable zig code with an easy to use encoding and decoding API that
can be used in zig programs. Here is an example of the output of parsing a <code>.proto</code> message <em>(imports are not shown, using proto3
syntax)</em>
message.proto
message.pb.zig
```proto
message SearchRequest {
string query = 1;
int32 page_number = 2;
int32 result_per_page = 3;
}
```
```zig
pub const SearchRequest = struct{
query: []const u8 = "",
page_number: i32 = 0,
result_per_page: i32 = 0,
pub const descriptor_pool = enum(u32){page_number = 2,query = 1,result_per_page = 3};
pub fn ParseFromString(string: []const u8, allocator: Allocator) DecodeError!SearchRequest{
return ProtobufMessage(SearchRequest).ParseFromString(string, allocator);
}
pub fn SerializeToString(message: SearchRequest, allocator: Allocator) []const u8 {
return ProtobufMessage(SearchRequest).SerializeToString(message, allocator);
}
};
```
Usage
You will need <code>protoc</code> installed, see the installation on the <a>protobuf GitHub Repo</a>.
<code>protoc --plugin=protoc-gen-zigpb=<path to zigpb> --zigpb_out=../generated --proto_path=<path to your proto files> <proto files to compile></code>
You can also place the <code>zigpb</code> under <code>/usr/bin</code> to avoid passing a path to the plugin each time
Development
You will need the full <code>libprotobuf</code> installed, see <a>here</a>
<em>Note:</em> Make sure you use the same compiler you plan on using to build the <code>protoc-zig</code> code, for example, if you plan on using zig as your c++ compiler for <code>protoc-zig</code> you must also build <code>libprotobuf</code> with zig's c++ toolchain.
Once built, see <code>tools/prepare_env.py</code>, this will copy over the protobuf implementation into a header file for the plugin to generate when
parsing <code>.proto</code> files. Once done you can either use <code>cmake</code> or <code>zig build</code> to build the plugin.
Zig Build
<code>zig build</code>
Cmake
<code>cd protoc-zig
mkdir build
cd build
CC="zig cc" CXX="zig c++" cmake ..
make</code>
Testing
The script <code>generate_zig_protobuf.py</code> will take the files in <code>test-protos</code> and generate the zig structs from them in <code>generated</code>
The script <code>generate_encoded.py</code> will generate some binary data to test decoding with, it takes an optional parameter to the path of <code>zigpb</code>, by
default it assumes you built with <code>cmake</code>
Once set up you can then run <code>zig test src/main.zig</code> or <code>zig test src/main.zig --test-filter <test-name></code>
Notes
<ul>
<li>So far the zig file generation works only with the proto3 syntax currently and is probably incomplete and will most likely change</li>
<li>Haven't done too much on encoding yet</li>
<li>In the future would like to support additional features like converting to JSON, gRPC, and proto2 syntax</li>
<li>Built with zig version 0.12.0-dev.146+020105d0d</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/1566759?v=4 | update-zig | snail23/update-zig | 2022-11-26T04:54:57Z | Fetch the latest Zig master branch build | main | 0 | 5 | 1 | 5 | https://api.github.com/repos/snail23/update-zig/tags | MIT | [
"binaries",
"binary",
"branch",
"build",
"builds",
"download",
"fetch",
"master",
"script",
"scripts",
"shell",
"shell-script",
"shell-scripts",
"simple",
"update",
"zig",
"zig-lang",
"ziglang"
]
| 17 | false | 2023-10-14T06:03:03Z | false | false | unknown | github | []
| Zig Updater
Fetch the latest Zig master branch build easily with one command. <code>update-zig</code> will automatically parse https://ziglang.org/download/index.json, download the latest <code>x86_64-linux</code> archive, and unpack the contents to <code>$HOME/.zig</code>.
You can run the command again and nothing will happen if a new build is not available so feel free to spam it however you like.
Note: <code>dialog</code> colors may be different on your machine.
Running
<code>update-zig</code>
Prerequisites
Make sure the following packages are installed if any issues arise on your system:
- <code>gawk</code>
- <code>dialog</code>
- <code>jq</code>
- <code>pv</code>
- <code>wget</code>
- <code>xz-utils</code>
Installing
```
git clone https://github.com/snail23/update-zig $HOME/.zig
chmod +x $HOME/.zig/update-zig
````
Optionally, run <code>update-zig</code> on login as well as add <code>$HOME/.zig</code> to <code>PATH</code>:
<code>echo 'PATH="$PATH:$HOME/.zig"' >> $HOME/.profile
echo update-zig >> $HOME/.profile</code>
License
```
MIT License
Copyright (c) 2023 Snail
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/11492844?v=4 | zigularity | fjebaker/zigularity | 2022-09-19T00:58:00Z | Itsy-bitsy-teeny-weeny-black-hole-visualisation-machiney. | main | 0 | 5 | 0 | 5 | https://api.github.com/repos/fjebaker/zigularity/tags | MIT | [
"black-holes",
"general-relativity",
"ray-tracing",
"relativity",
"zig"
]
| 979 | false | 2024-05-29T09:00:38Z | true | false | unknown | github | []
| Zigularity
<i>Itsy-bitsy-teeny-weeny-black-hole-visualisation-machiney</i>
A little long weekend project: relativistic ray tracing in Zig, visualizing thin accretion discs around a Kerr black hole with a handful of configurable parameters:
<ul>
<li>observer position</li>
<li>disc inner and outer radius</li>
<li>black hole mass and spin</li>
</ul>
<code>bash
git clone https://github.com/fjebaker/zigularity
cd zigularity
zigmod fetch
zig build -Drelease-fast</code>
Default is to try and calculate the coordinate-time of each traced photon (pixel) -- darker colours indicate things further away to give a slight semblance of three-dimensionality. The program should output something similar to this:
The program will write the output to a plain-text file <code>"disc.data"</code>, which may be plotted with your plotting package of choice. As an example, here is a little bit of Python:
```py
import matplotlib.pyplot as plt
import numpy as np
with open("disc.data") as f:
data = f.read()
image = []
for line in data.split("\n"):
row = line.split(",")[:-1]
if row:
image.append(row)
img = np.array(image, dtype=float)
plt.imshow(
img.transpose(),
# only want to color close to the black hole
vmin = 900,
vmax = 1100,
cmap = "Greys"
)
plt.show()
```
It can also be used to calculate the so-called <em>shadow</em> of a black hole, which traces the apparent shape of the event horizon:
Or for a non-spinning black hole:
Todo
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> fix bad pixels bugs
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <em>severely</em> clean and refactor the code
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> interpolate on integrator callback to smoothen the disc
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> ~~(stretch) multi-threading cus it's a wee bit slow~~ Not available on self-hosted Zig compiler yet.
Dependencies
Requires <a>nektro/zigmod</a> to install dependencies:
<ul>
<li><a>fjebaker/zigode</a></li>
</ul>
About
I write relativistic ray tracing codes as part of my research, feel free to <a>take a look</a> (~:
Relativistic ray-tracing is similar to regular ray-tracing, except that the trajectory of light may be altered due to the locally curved spacetime under strong gravity (see <a>gravitional lensing</a>). The trajectories may be traced by solving the <a>geodesic equation</a> -- a 2nd order ODE system which can be quite stiff -- however certain formulations of curved space permit a 1st order set of equations.
One such spacetime is the spacetime of the <a>Kerr metric</a>, describing a black hole with angular momentum. This metric is parameterised by a black hole mass $M$ and spin $a$, and is axis-symmetric about the spin axis and unchanging with time.
This code implements equations from <a>Bardeen et al. (1972)</a> and <a>Fanton et al. (1997)</a> to construct the 1st order equations, and integrates them using a simple adaptive Runge-Kutta algorithm. | []
|
https://avatars.githubusercontent.com/u/2549434?v=4 | rebar3_zig | shiguredo/rebar3_zig | 2022-07-20T05:53:21Z | Rebar3 plugin to call Zig functions from Erlang using NIF | develop | 0 | 5 | 1 | 5 | https://api.github.com/repos/shiguredo/rebar3_zig/tags | Apache-2.0 | [
"erlang",
"zig"
]
| 949 | false | 2023-10-30T06:19:51Z | false | false | unknown | github | []
| rebar3_zig
<a></a>
<a></a>
<a>Erlang</a> から <a>Zig</a> で書かれたコードを利用可能にするための <a>Rebar3</a> プラグインです。
内部では Erlang の <a>NIF</a> (Native Implemented Functions) という機能を利用しています。
About Shiguredo's open source software
We will not respond to PRs or issues that have not been discussed on Discord. Also, Discord is only available in Japanese.
Please read https://github.com/shiguredo/oss/blob/master/README.en.md before use.
時雨堂のオープンソースソフトウェアについて
利用前 https://github.com/shiguredo/oss をお読みください。
使い方
基本的な使い方は以下の通りです:
```console
////////
// 1) 適当な rebar3 プロジェクトを作成
$ rebar3 new lib zig_sample
$ cd zig_sample/
////////
// 2) rebar3_zig をプロジェクトプラグインとして追加
$ echo "\n{project_plugins, [rebar3_zig]}." >> rebar.config
////////
// 3) rebar3 のテンプレート機能を使って Zig 用のファイル群を生成
// 自分の環境での NIF 用ヘッダのインクルードパスを指定
// (ここでは省略して後で C_INCLUDE_PATH 環境変数に指定するのでも可)
$ INCLUDE_PATH=/path/to/erlang/erts-${ ERTS_VERSION }/include/
// NIF 関数呼び出し用に生成される Erlang のモジュール名を指定
$ NIF_MODULE_NAME=sample
// ファイル生成
$ rebar3 new zig name=$NIF_MODULE_NAME include_path=$INCLUDE_PATH
===> Analyzing applications...
===> Compiling rebar3_zig
===> Writing zig_src/build.zig
===> Writing zig_src/nif.zig
===> Writing zig_src/main.zig
===> Writing src/sample.erl
$ cat zig_src/main.zig
const std = @import("std");
pub fn add(x: c_int, y: c_int) c_int {
return x + y;
}
test "add" {
try std.testing.expectEqual(add(1, 2), 3);
}
////////
// 4) コンパイルとテスト
$ rebar3 zig compile
===> Analyzing applications...
===> Compiling rebar3_zig
===> Verifying dependencies...
===> Analyzing applications...
===> Compiling zig_sample
===> Running zig compile...
===> Moving artifacts...
===> Moved: "zig_src/zig-out/lib/libsample.0.0.0.dylib" => "priv/libsample.so"
$ rebar3 zig test
===> Analyzing applications...
===> Compiling rebar3_zig
===> Running zig test...
All 1 tests passed.
////////
// 5) Erlang シェルからの NIF 関数呼び出し
$ rebar3 shell
<blockquote>
sample:add(1, 2).
3
```
</blockquote>
また rebar.config ファイルに以下のフックを追加することで、
<code>$ rebar3 compile</code> や <code>$ rebar3 eunit</code> 実行時に自動で Zig のコードのコンパイルやテストが実行可能になります。
<code>erlang
{provider_hooks, [{post, [{compile, {zig, compile}},
{eunit, {zig, test}},
{clean, {zig, clean}}]}]}.</code>
ライセンス
<a>Apache License 2.0</a>
```
Copyright 2022-2022, Takeru Ohta (Original Author)
Copyright 2022-2022, Shiguredo Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
<code>http://www.apache.org/licenses/LICENSE-2.0
</code>
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
``` | []
|
https://avatars.githubusercontent.com/u/107726195?v=4 | zig-gamecube | zig-homebrew/zig-gamecube | 2022-06-19T11:24:54Z | Starter pack for developing Gamecube games/applications with Zig | master | 0 | 5 | 0 | 5 | https://api.github.com/repos/zig-homebrew/zig-gamecube/tags | - | [
"devkitpro",
"wii",
"zig"
]
| 9 | false | 2024-05-19T18:01:36Z | true | false | unknown | github | []
| zig-gamecube
Getting started
<ul>
<li><a>zig</a></li>
<li><a>devkitPro</a></li>
</ul>
<code>pacman -S gamecube-dev
git clone https://github.com/zig-homebrew/zig-gamecube
cd zig-gamecube/
zig build # then run zig-out/zig-gamecube.dol with dolphin-emu</code>
Resources
<ul>
<li><a>gamecube-examples</a></li>
<li><a>libogc repository</a></li>
<li><a>libogc documentation</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/3976625?v=4 | pre-commit-zig | batmac/pre-commit-zig | 2022-07-16T00:12:23Z | Zig hooks for pre-commit | main | 2 | 5 | 2 | 5 | https://api.github.com/repos/batmac/pre-commit-zig/tags | MIT | [
"fmt",
"pre-commit",
"pre-commit-hook",
"pre-commit-hooks",
"zig",
"ziglang"
]
| 7 | false | 2024-09-08T05:07:54Z | false | false | unknown | github | []
| pre-commit-zig
Zig pre-commit hooks for <a>http://pre-commit.com/</a>
install
you need first to install <a>pre-commit</a>:
<code>brew install pre-commit</code> or <code>pipx install pre-commit</code> or <code>pip install pre-commit</code>
install pre-commit into your git repo:
<code>pre-commit install</code>
Usage
Add a file named <code>.pre-commit-config.yaml</code> into the root directory of your repository:
<code>yaml
repos:
- repo: https://github.com/batmac/pre-commit-zig
rev: master
hooks:
- id: zig-fmt
- id: zig-build
- id: zig-build-test</code>
Available hooks
<ul>
<li><code>zig-fmt</code> - runs <code>zig fmt</code> on the changed files.</li>
<li><code>zig-fmt-check</code> - runs <code>zig fmt --check</code> (doesn't modify files).</li>
<li><code>zig-build</code> - ensure <code>zig build</code> passes in your repository.</li>
<li><code>zig-build-test</code> - ensure <code>zig build test</code> passes in your repository.</li>
</ul>
Credits
<ul>
<li><a>dnephin/pre-commit-golang</a></li>
<li><a>Bahjat/pre-commit-golang</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/61017?v=4 | c_call_zig | ssteinbach/c_call_zig | 2022-10-13T06:00:14Z | Small example of calling a static zig library from C code. | main | 0 | 5 | 0 | 5 | https://api.github.com/repos/ssteinbach/c_call_zig/tags | - | [
"c",
"ffi",
"linking",
"zig",
"ziglang"
]
| 22 | false | 2025-04-08T05:18:37Z | true | true | 0.14.0 | github | []
| Calling Zig from C
Overview
Example repository for calling zig functions from C. Zig has some nice
reflection based JSON parsing ability, this exposes a c function that uses that
to parse a C-struct out of JSON and return it.
Requirements
<ul>
<li>Zig (built against 0.13.0)</li>
<li>C toolchain (clang)</li>
</ul>
Building
```bash
<blockquote>
make
./c_to_zig_json_reader
```
</blockquote>
Testing
There is a (small) unit test in <code>src/json_reader.zig</code>.
```bash
<blockquote>
make test
```
</blockquote>
Build.zig Note
When building the static library to wrap in C, make sure the build.zig
includes:
<code>zig
const lib = b.addStaticLibrary("zigJsonReader", "json_reader.zig");
lib.bundle_compiler_rt = true;</code>
Additionally, the header file is written by hand. | []
|
https://avatars.githubusercontent.com/u/85593302?v=4 | zogc | svelterust/zogc | 2022-04-08T10:04:54Z | Game engine for the Wii | master | 0 | 5 | 0 | 5 | https://api.github.com/repos/svelterust/zogc/tags | - | [
"wii",
"zig"
]
| 6,418 | false | 2023-01-28T00:04:07Z | true | false | unknown | github | []
| zogc
Game engine for the Wii in Zig with zero-fuss installation.
<code>bash
git clone https://github.com/knarkzel/zogc
cd zogc/
zig build</code>
Commands
<ul>
<li>To build and run with Dolphin, do <code>zig build run</code></li>
<li>To build and deploy to Wii over network (must be in Homebrew menu), do <code>zig build deploy</code></li>
<li>To build and debug crash addresses, do <code>zig build line -- <addresses></code></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/791710?v=4 | NovaZig | flyx/NovaZig | 2022-10-30T12:27:22Z | Zig support for the Nova editor | master | 2 | 5 | 1 | 5 | https://api.github.com/repos/flyx/NovaZig/tags | MIT | [
"editor-plugin",
"zig"
]
| 21 | false | 2024-09-25T12:58:27Z | false | false | unknown | github | []
| 404 | []
|
https://avatars.githubusercontent.com/u/2567177?v=4 | clerk | malcolmstill/clerk | 2022-11-02T22:00:01Z | Todos in your CLI | master | 5 | 5 | 0 | 5 | https://api.github.com/repos/malcolmstill/clerk/tags | MIT | [
"sqlite",
"todo",
"zig"
]
| 2,454 | false | 2025-04-15T01:13:13Z | true | true | unknown | github | [
{
"commit": "878f8cf92b308dabe2dce9e24bd7849e005f7ab5.tar.gz",
"name": "sqlite",
"tar_url": "https://github.com/vrischmann/zig-sqlite/archive/878f8cf92b308dabe2dce9e24bd7849e005f7ab5.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/vrischmann/zig-sqlite"
},
{
"commit": null,
"name": "ansi-term",
"tar_url": null,
"type": "relative",
"url": "lib/ansi-term"
}
]
| clerk
Installation
<ul>
<li>Download a binary for your platform from <a>the release page</a></li>
<li>linux / macos: <code>chmod u+x clerk</code></li>
<li>Ideally stick <code>clerk</code> somewhere in your <code>PATH</code></li>
</ul>
Dependencies
<code>clerk</code> depends on these fantastic libraries (vendored in <code>lib/</code>):
- <a><code>zig-sqlite</code></a>
- <a><code>ansi-colors</code></a>
FAQ
Where are the todos stored?
<ul>
<li>In <code>~/.clerk.db</code></li>
</ul>
I'd rather compile from source than download the binaries. How do I do that?
<ul>
<li>To build from source only requires zig 0.10.0.</li>
<li>Download the source and run <code>zig build</code></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/2828351?v=4 | re4k | bcrist/re4k | 2022-11-19T04:33:08Z | Fusemaps for Lattice ispMach4000 CPLDs | main | 0 | 5 | 2 | 5 | https://api.github.com/repos/bcrist/re4k/tags | MIT | [
"cpld",
"cplds",
"lattice",
"reverse-engineering",
"zig",
"ziglang"
]
| 8,655 | false | 2025-04-06T18:16:44Z | true | true | unknown | github | []
| Fusemaps for Lattice ispMach4000 CPLDs
This repo contains reverse-engineered fusemaps for most of the commonly available LC4k CPLDs from Lattice.
Data is provided in text files containing machine and human readable S-Expressions describing the fuse locations that control each feature.
These are intended to be used to generate libraries so that CPLD configurations can be created using whatever programming language is desired.
Existing libraries include:
<ul>
<li><a>Zig-LC4k</a></li>
</ul>
If you build a library/bindings for another language, let me know so I can list it here!
Device List
| |TQFP44|TQFP48|TQFP100|TQFP128|TQFP144|csBGA56|csBGA64|csBGA132|csBGA144|ucBGA64|ucBGA132|
|:-----------|:----:|:----:|:-----:|:-----:|:-----:|:-----:|:-----:|:------:|:------:|:-----:|:------:|
|LC4032V/B/C | ✔️ | ✔️ | | | | | | | | | |
|LC4032ZC | | ✔️ | | | | ✔️ | | | | | |
|LC4032ZE | | ✔️ | | | | | ✔️ | | | | |
|LC4064V/B/C | ✔️ | ✔️ | ✔️ | | | | | | | | |
|LC4064ZC | | ✔️ | ✔️ | | | ✔️ | | ✔️ | | | |
|LC4064ZE | | ✔️ | ✔️ | | | | ✔️ | | ✔️ | ✔️ | |
|LC4128V | | | ✔️ | ✔️ | ✔️ | | | | | | |
|LC4128B/C | | | ✔️ | ✔️ | | | | | | | |
|LC4128ZC | | | ✔️ | | | | | ✔️ | | | |
|LC4128ZE | | | ✔️ | | ✔️ | | | | ✔️ | | ✔️ |
LC4256 and larger devices are not supported at this time.
Automotive (LA4xxx) variants likely use the same fusemaps as their LC counterparts, but that's just conjecture.
Please don't use this project for any automotive or other safety-critical application.
Introduction
Please read through the Lattice datasheet for your device if you have not.
Generally I have tried to use the same terminology for things as is used there.
You can also reference the glossary at the end of this document if you are unsure of what an acronym or term means.
You can find PDF and KiCAD format schematics showing the structure of each type of device in the <code>schematics</code> directory.
General Fusemap Layout
All LC4k devices have a logical layout of fuses into a 2D grid with either 100 or 95 rows,
and a variable number of columns, depending on the number of GLBs in the device.
The JEDEC files list these fuses one row after another,
and when programming the device via JTAG each row is delivered in a separate SDR transaction.
Each GLB uses a chunk of at least 86 columns,
and the GLBs are laid out side-by-side,
however they are not generally ordered from left to right
(the block for GLB "A" is not necessarily to the left of the block for GLB "B").
The first 72 rows contain PT and GI routing fuses.
This part of the fusemap is densely packed;
every single logical fuse corresponds to a bit of FLASH memory and controls the behavior of the device.
The remaining rows have a variety of uses, and are sparsely packed;
most bits don't actually correspond to FLASH memory cells, and always read as a <code>1</code>, even after attempting to program them to <code>0</code>.
Generally there is a single column corresponding to each macrocell slice, containing fuses that configure that macrocell slice.
These columns are arranged in groups of two, usually with 8 mostly-unused columns separating each pair.
Devices that only have 95 rows only have a single I/O cell per pair of macrocells.
Instead of placing all the I/O cell configuration fuses in the same column,
half of the fuses are shifted over to the adjacent macrocell's column,
reducing the total number of rows needed.
Each GLB has a few bits of block configuration which are placed in the "borders" to the left and right of the macrocell slice columns.
This includes fuses for configuring block clock source/polarity, shared PT polarity, routing of the shared PT enable to the GOE bus, etc.
Finally, global configuration is typically placed in a small, vaguely ring-shaped structure at the right edge of one of the GLB regions.
This includes configuration of input-only pins, GOE polarity, and oscillator/timer (in ZE devices).
S-Expression Files
The reverse-engineered fusemap for each device consists of a set of s-expression files in <code>LC4xxx/LC4xxx*_*/.sx</code>.
There is also a combined file <code>LC4xxx/LC4xxx*_*.sx</code> which contains the data from all of the individual files.
The meaning of the data in each particular file is explained below.
If the syntax of any of the files is confusing to you after reading its corresponding section,
please open an issue so I can try to document it better.
<code>grp.sx</code> <code>(global_routing_pool)</code>
Each GLB has 36 GI "slots" which (along with their complements) are used as inputs to the product terms in that GLB.
Each GI can be selected from a fixed set of signals in the global routing pool.
The options are different for each GI "slot" in the GLB,
but every GLB in the device uses the same options for the same GI slot.
The number of options for each slot depends on the device type
(devices with more GLBs have more GRP signals,
therefore in order to have multiple possible routings for each signal,
each GLB must have more possible options).
For devices that have an even number of GI options,
the option fuses are stored at the very left side of the GLB block,
using <code>N/2</code> columns (where <code>N</code> is the number of options).
A "one-cold" encoding is used here; i.e. there is one fuse for each option,
and only one fuse should be programmed to 0 for each GI.
For devices that have an odd number of GI options, the GLBs are organized into pairs,
and each pair shares the same columns of GI routing fuses. The first row contains fuses
for one of the GLBs, and the second row contains fuses for the other.
<code>pterms.sx</code> <code>(product_terms)</code>
Within the first 72 rows, each column
(with the exception of the columns used for GI routing above)
represents a single product term.
Every pair of rows corresponds to a single GI slot,
with the first row representing the non-inverted GI signal,
and the second row representing the inverted version of the same signal.
Programming a fuse within a product term to 0 means the corresponding signal must be asserted
in order for the product term to output <code>true</code>.
Another way to think of this is that the fuse value is OR-ed with the signal, and the result is
passed into the product term's AND gate.
Therefore if no PT fuses are set to 0, the PT will always yield <code>true</code>.
If both fuses are set to 0 for any GI, the PT will always yield <code>false</code>.
When the lpf4k fitter wants to make a PT <code>false</code>,
it sets all the fuses for the first dozen or so rowss to 0.
It's not clear why they chose to set just those.
It may be that setting just one pair to 0 might create static hazards
if the GI mapped to that slot changes.
But in that case wouldn't it be best to set all GI pairs to zeroes?
In testing, that does seem to work as expected,
so that's what I'd recommend doing.
My best guess is that this could be a holdover from older device families
that used sense amplifiers instead of fully CMOS logic.
Setting all fuses to 0 might cause higher power usage in such devices.
Product terms are grouped into clusters of 5,
with one cluster associated with each macrocell.
Additionally, there are 3 extra product terms per GLB,
which may be used for specific purposes,
but are shared amongst all macrocells in the GLB.
These PTs are always in the last 3 columns of the GLB's block.
<code>cluster_routing.sx</code> <code>(cluster_routing)</code>
Each product term can optionally be used for a special purpose related to that macrocell (see below),
or they can be summed (OR-ed) together and fed into the macrocell's logic input.
Since a logic equation simplified to a sum-of-products often requires more than 5 product terms,
a cluster can either keep it's sum for itself,
or it can "donate" it to one of up to three nearby macrocells.
Each cluster then creates a second sum from any intermediate sums that were routed to that cluster.
A cluster can receive a "donation" (or multiple) even if it is not "keeping" it's own original sum.
Therefore this second sum can represent up to 20 product terms, all with a constant propagation delay.
Some specific clusters have a maximum of < 20 PTs:
<ul>
<li>The cluster for MC 0 can only receive a sum from cluster 1 or cluster 2, so including itself it has a maximum of 15 PTs.</li>
<li>The cluster for MC 14 can only receive a sum from cluster 13 or cluster 15, so including itself it has a maximum of 15 PTs.</li>
<li>The cluster for MC 15 can only receive a sum from cluster 14, so including itself it has a maximum of 10 PTs.</li>
</ul>
A cluster sum can only be routed to one other cluster;
it can't be duplicated and sent to multiple neighboring clusters.
<code>wide_routing.sx</code> <code>(wide_routing)</code>
In cases where a very large number of product terms are needed,
but very few outputs are needed,
the output of the second sum above can be redirected to the cluster at index <code>(N+4)%16</code>
(where <code>N</code> is the current cluster index).
This is referred to in the datasheets as "SuperWIDE(tm)" steering logic.
Note that this differs from <code>cluster_routing</code> in several ways:
<ul>
<li>It "wraps around", so cluster 15 can be routed to cluster 3.</li>
<li>It can be "chained" such that any macrocell in the GLB can potentially use every PT cluster, if no other MCs in the GLB need a cluster.</li>
<li>Using this feature increases the maximum propagation delay (but not equally; PTs that go through the wide routing will be slower than those in the final cluster's 20-PT group).</li>
</ul>
When a macrocell's cluster is routed away to another cluster,
the macrocell sees a constant low (false) value as its logic input.
<code>input_bypass.sx</code> <code>(macrocell_data)</code>
A macrocell register's data/toggle input may be configured to come directly from the macrocell's input pad,
instead of having to travel through the GRP, PTs, cluster routing, etc.
This provides a reduced minimum setup time.
Technically this feature can also be used when the macrocell is configured for combinational logic,
but there's not much point in doing so,
since that just makes the macrocell feedback signal the same as the input buffer signal.
You could use an ORM offset to create a tri-state line driver where the input and output are both pins,
and the OE signal is controlled by the CPLD logic.
This would yield the fastest possible propagation delay across the line driver,
but if propagation delay is that critical,
you'd probably be better off just outputting the OE signal and using an external tri-state buffer or bus switch.
<code>zerohold.sx</code> <code>(zero_hold_time)</code>
When a macrocell is configured as an input register,
an extra delay can be added to bring the minimum hold time down to 0.
This also means the setup time is increased.
This is controlled by a single fuse that affects the entire chip.
Registers whose data comes from product term logic are not affected by this fuse,
because the internal propagation delays mean that no hold time is required anyway.
<code>pt0_xor.sx</code> <code>(pt0_xor)</code>
Each macrocell contains an XOR gate.
The output of the XOR gate goes to the data/toggle input of the macrocell's register,
and optionally to the macrocell feedback/ORM input (when the MC is in combinational mode).
One of the inputs to the XOR gate is always the logic input from the PT cluster router.
The second input of the XOR gate can be either a constant value,
or the result of the macrocell's first product term, PT0.
When it is sourced from PT0, that product term is removed from its cluster sum.
When PT0 is not redirected, a logic 0 is fed to the XOR (optionally inverted; see below).
Note that the datasheets' macrocell schematic (fig. 5)
depicts the input register mux feeding into one of the XOR inputs,
however when testing real devices,
we see that the XOR gate is bypassed completely when the <code>input_register</code> fuse is cleared.
This implies that the input register mux is actually located after the XOR output.
This makes sense, since the idea of the input register is to make the setup time as short as possible.
<code>invert.sx</code> <code>(invert)</code>
The second input of the XOR gate can be inverted using this fuse.
When sourced from PT0, this means PT0 can be thought as a 36-input OR gate
instead of a 36-input AND gate (via a De Morgan transformation;
you must also use the complement of each PT0 input of course).
When the inverter is enabled, but the XOR is not sourced from PT0,
the second XOR input becomes a constant high,
so the logic sum from the PT cluster router is inverted.
Again, one way to think of this is that you can use the macrocell as a product-of-sums
instead of a sum-of-products.
<code>mc_func.sx</code> <code>(macrocell_function)</code>
Each macrocell can implement one of four fundamental circuits:
<ul>
<li>Purely combinational logic</li>
<li>Transparent latch</li>
<li>D flip-flop</li>
<li>T flip-flop</li>
</ul>
The latter 3 all act as single bit storage elements,
and thus have some extra configuration that is irrelevant for combinational macrocells:
<ul>
<li>Clock source</li>
<li>Clock enable source</li>
<li>Power-up initialization</li>
<li>Asynchronous set/reset</li>
</ul>
These features are described below.
<code>clock_source.sx</code> <code>(clock_source)</code>
When a macrocell is used as a register,
it needs a clock signal, which can be one of eight options:
<ul>
<li>Four block clock signals (see below)</li>
<li>The GLB's shared clock PT</li>
<li>The macrocell's PT1</li>
<li>The macrocell's PT1, inverted</li>
<li>A constant low/false</li>
</ul>
When it is sourced from PT1, that product term is removed from its cluster sum.
When the macrocell is configured as a D or T flip flop, the clock triggers on the rising edge.
If if the source can be inverted, it effectively flips it to trigger on the falling edge.
When configured as a latch, it will be transparent when the clock signal is high,
and latched when the clock signal is low.
<code>bclk_polarity.sx</code> <code>(bclk_polarity)</code>
The four BCLK clock selection options come from dedicated input pins
(usually four, but some devices only have two).
Using these avoids the need to use macrocell PTs or the GLB's shared clock PT for the clock.
The polarity of these clocks can be configured independently for each GLB.
It is configured in fixed pairs,
where each BCLK can be either the non-inverted version of one of the clocks,
or the inverted version of the <em>other</em> clock.
So you can have both clocks non-inverted, both clocks inverted,
or a complementary pair of either clock.
<code>ce_source.sx</code> <code>(clock_enable_source)</code>
The clock enable inhibits the updating of the register contents when it is high.
It has no effect when the macrocell is configured for combinational logic.
For transparent latches, it works effectively as if the clock were ANDed with the CE;
as long as both are high, the latch is in transparent mode;
if either goes low, it latches the current value.
For D and T flip flops, this means as long as the CE is low during the triggering edge,
there will be no change that cycle.
This is not the same as simply ANDing the CE with the clock signal;
the CE does not need to remain low for the entire duration that the clock is high.
There are four possible sources for the CE signal:
<ul>
<li>The macrocell's PT2</li>
<li>The macrocell's PT2, inverted</li>
<li>The GLB's shared clock PT</li>
<li>A constant high/true</li>
</ul>
The shared clock PT is the same one that's used as an option for the clock,
and within a GLB, the same PT can be used as a clock for some MCs and a CE for others.
When it is sourced from PT2, that product term is removed from its cluster sum.
Note that PT2 can also be used for an async set/reset signal (see below).
<code>shared_pt_clk_polarity.sx</code> <code>(shared_pt_clk_polarity)</code>
Each GLB's shared clock PT can optionally be inverted.
This affects all usages within the GLB, both as a clock and a clock enable.
<code>init_state.sx</code> <code>(init_state)</code>
When a macrocell is configured as a register,
its initial state at power-up can be configured.
This configuration can be selected independently for each macrocell.
<code>init_source.sx</code> <code>(init_source)</code>
When a macrocell is configured as a register,
an signal can be used to asynchronously set or reset the register to its power-up state.
While this signal remains high, the macrocell is forced into its power-up state.
There are only two options for the source of this signal:
<ul>
<li>The macrocell's PT3</li>
<li>The GLB's shared init PT</li>
</ul>
This means that if the GLB's shared init PT is not a constant false,
any registers in that GLB that <em>don't</em> want to use a reset signal must use PT3 as a constant false instead.
It PT3 is used as the source, that product term is removed from its cluster sum.
<code>shared_pt_init_polarity.sx</code> <code>(shared_pt_init_polarity)</code>
Each GLB's shared initialization PT can optionally be inverted.
<code>async_source.sx</code> <code>(async_source)</code>
An optional second asynchronous set/reset signal can be sourced from PT2.
While the signal remains high, the macrocell is forced into the complement of its power-up state.
Note also that PT2 can also be used as a source for the CE signal,
and while it is possible to simultaneously use it for both,
generally you wouldn't be able to use the same PT logic for both,
so this generally you'd use it for one or the other.
When PT2 is used as an async set/reset, that product term is removed from its cluster sum.
<code>pt4_oe.sx</code> <code>(pt4_output_enable)</code>
When this fuse is programmed,
PT4 is removed from the macrocell's cluster sum,
and instead routed to the ORM.
From there it can be selected as an output enable signal for this macrocell's output,
or certain nearby macrocells (see below).
When not used, the OE signal presented to the ORM is a constant false.
<code>output_routing.sx</code> <code>(output_routing)</code>
Normally a macrocell slice's I/O cell will output the signal produced by it's corresponding macrocell,
however there is a built-in "output routing multiplexer" (ORM)
that allows limited redirection to take the output signal
from a macrocell offset of up to +7 instead.
Note that this offset wraps around as well, so the I/O for MC 15 can be selected from MC 0-6 as well.
The PT4 OE signal (if used) is also routed from the same MC.
<code>output_routing_mode.sx</code> <code>(output_routing_mode)</code>
For non-ZE family devices, the ORM can be bypassed, which slightly decreases the output delay.
Additionally, the entire macrocell logic block can be bypassed if only a combinational logic output is needed,
with a maximum of 5 PTs.
There are several options available:
<ul>
<li>Output the normal signal selected by the ORM</li>
<li>Bypass the ORM and always output the feedback signal from this macrocell, regardless of the ORM configuration</li>
<li>Output this cluster's 5-PT sum</li>
<li>Output this cluster's 5-PT sum, inverted</li>
</ul>
None of these options affect the routing of the PT4 OE signal;
it always goes through the ORM routing.
When one of the 5-PT sum options is used,
the PT cluster is still routed using the normal cluster routing rules as well,
unlike when individual PTs are redirected for a special use.
It's possible to still use the buried macrocell,
but you have to be careful to isolate the original 5-PT cluster sum, e.g.
<ul>
<li>Route it to another cluster</li>
<li>Route another always true cluster in and use PT0 for a single PT macrocell</li>
<li>Use the buried macrocell as an input register</li>
</ul>
<code>oe_source.sx</code> <code>(output_enable_source)</code>
Each I/O cell's output driver is active when its output enable signal is high.
The OE signal can be selected from one of 8 sources:
<ul>
<li>One of 4 global output enables</li>
<li>The PT4 output enable signal from the ORM</li>
<li>The PT4 output enable signal from the ORM, inverted</li>
<li>A constant high (output only)</li>
<li>A constant low (input only)</li>
</ul>
<code>goes.sx</code> <code>(goe_polarity)</code>
All devices have 4 global OE signals.
The polarity of these signals can be configured globally,
and their source depends on the device.
Sources for LC4032 devices:
<ul>
<li>GOE0: Shared PT OE bus bit 0</li>
<li>GOE1: Shared PT OE bus bit 1</li>
<li>GOE2: A0 input buffer</li>
<li>GOE3: B15 input buffer</li>
</ul>
Sources for other devices:
<ul>
<li>GOE0: Selectable; either shared PT OE bus bit 0, or specific input buffer noted in datasheet</li>
<li>GOE1: Selectable; either shared PT OE bus bit 1, or specific input buffer noted in datasheet</li>
<li>GOE2: Shared PT OE bus bit 2</li>
<li>GOE3: Shared PT OE bus bit 3</li>
</ul>
<code>goes.sx</code> <code>(shared_pt_oe_bus)</code>
The shared PT OE bus is a set of 2 or 4 (depending on the device type, as above) global signals
where each bit can be connected to any of the GLBs' shared enable PT
(note this is shared with the power guard feature on ZE devices).
If multiple GLBs are configured to drive the same PT OE bus line,
it will behave as if only the first (lowest numbered) GLB were used.
It might have been convenient if they had summed the PTs in this case,
but alas, for some reason they didn't.
If no GLBs are configured to drive a PT OE bus line,
it is pulled high (if the polarity fuse is 1) or low (if the polarity fuse is 0).
There's really no reason to utilize this though, since each output cell can be
configured for "always output" or "always high impedance" without using any GOE signal.
<code>drive.sx</code> <code>(drive_type)</code>
One fuse per output controls whether the output is open-drain or push-pull.
Open-drain can also be emulated by outputing a constant low and using OE to enable or disable it,
but that places a lot of limitation on how much logic can be done in the macrocell;
only a single PT can be routed to the OE signal.
<code>slew.sx</code> <code>(slew_rate)</code>
One fuse per output controls the slew rate for that driver.
According to the datasheet,
using the slow slew rate adds approximately 1ns to the output buffer propagation delay,
which means rise and fall times are likely about twice as long as normal.
<code>threshold.sx</code> <code>(input_threshold)</code>
The Lattice fitter allows each input signal's voltage standard to be selected from around a half dozen choices, including:
* 1.8V LVCMOS
* 2.5V LVCMOS
* 3.3V LVCMOS
* 3.3V LVTTL (5V-tolerant)
* 3.3V PCI (5V-tolerant)
The datasheets and IBIS models are quite vague about the actual input structure used in the devices,
but it turns out this configuration only affects one fuse per input,
so it seems that this fuse selects either a high or low input transition threshold.
Generally speaking, the high threshold is suitable for either 2.5V or 3.3V signals,
and the low threshold is for 1.8V or 1.5V signals.
Additionally, the datasheet mentions that inputs are only 5V-tolerant when VCCO is 3.3V,
so the protection diodes probably clamp relative to that rail rather than VCC.
The following are mostly guesses for the actual Vth based on the published limits in the datasheet,
and assuming that the threshold is always referenced to VCC,
as opposed to using VCCO or an internal fixed voltage reference.
| Vth | <code>-V</code> | <code>-B</code> | <code>-C</code>/<code>-ZC</code> | <code>-ZE</code> |
|:---------------|:-------------------------:|:-------------------------:|:---------------------------:|:------------------------:|
| low | 0.28×VCC | 0.36×VCC | 0.5×VCC | 0.5×VCC |
| high | 0.4×VCC | 0.5×VCC | 0.73×VCC | 0.68×VCC (falling edge)0.79×VCC (rising edge) |
<code>bus_maintenance.sx</code> <code>(bus_maintenance)</code>
2 fuses allow selection of one of four input termination options:
* pull up
* pull down
* bus-hold
* floating/high-Z
In ZE family devices, this can be configured separately for each input pin.
In other families, there is only a single set of fuses which apply to the entire device.
<code>bus_maintenance.sx</code> <code>(bus_maintenance_extra)</code>
On certain non-ZE devices,
setting bus maintenance to floating causes the fitter to toggle additional fuses
beyond the two global bus maintenance fuses.
This only happens on devices where the die has I/O cells that aren't bonded to any package pin. (e.g. TQFP-44 packages)
Normally, these extra I/O cells are left as inputs,
but if inputs are allowed to float, this could cause excessive power usage,
so the fitter turns them into outputs by setting the appropriate OE mux fuses.
<code>power_guard.sx</code> <code>(power_guard)</code>
In ZE-family devices, input signals can be "masked"
so that high frequency signals don't propagate very far through the chip when not needed.
This can reduce dynamic power consumption.
Normally, power guard is disabled when the GLB's shared enable PT is high.
Power guard can also be permanently disabled for individual inputs using a fuse defined here.
That may be necessary if you need to use the shared enable PT for a GOE.
<code>osctimer.sx</code> <code>(osctimer)</code>
ZE-family devices contain a low-accuracy 5 MHz oscillator,
and a divider that can drop it down to lower frequencies.
When enabled, these signals replace the macrocell feedback signals for specific macrocells.
Fitter Bugs & Uncertainties
In the process of trying to get the LPF4k fitter to do what I want,
I've encountered a handful of bugs,
as well as some limitations which make it impossible to exercise certain hardware features.
In these cases, I've done my best to manually reverse engineer with real hardware,
but I don't have access to every device variant,
so I've also had to make some assumptions.
I'll try to document those here.
Fitter won't route all GOEs
Even though there are four GOEs in every device,
the fitter will never route more than two of them in any particular design.
If you add more unique equations than that,
it'll start using PT4 as individual OE for the extra ones.
I tried adding a bunch of dummy logic product terms so that there isn't a free PT available,
but that doesn't convince it to do otherwise;
it'll just shout about failing to allocate everything.
It's also impossible to force the fitter to place a shared PT OE in a specific GLB.
This means I've had to make some assumptions about the locations of the shared PT OE bus fuses,
but based on testing with LC4032ZE and LC4064ZC devices,
I would be surprised if they don't hold for all devices.
Negated GOE signals
When attempting to use a suffix of <code>.OE-</code> to create an active-low GOE,
the fitter report lists the correct equations,
but the JEDEC file that results is identical to one that just used <code>.OE</code>.
In order to coerce it to actually program the GOE polarity fuse,
you can invert the source signal instead,
but that only works when it's coming directly from an OE pin.
Otherwise it will just use the complemented signal in the shared PT OE.
This means it's really only possible to locate two of the GOE polarity fuses per device.
We have to infer the locations of the others by assuming that they're all in a contiguous block.
Fitter won't set shared PT init polarity
Somewhat similar to the bug above,
the fitter will refuse to route a design that uses <code>.AR-</code> or <code>.AS-</code>.
Presumably this is because it's not able to invert the output of PT3 when that's used for initialization.
But when coming from the shared PT, there <em>is</em> a configurable polarity;
it's just impossible to get the fitter to use it.
As above, if you invert a single signal, it will just encode that in the shared PT itself.
So again, we have to infer the location of this fuse based on where we know the shared PT clock polarity fuse is,
with hardware testing for verification.
LC4128ZE_TQFP100 Missing Power Guard fuse for CLK0
Enabling a power guard instance for this pin on this particular device does not cause any fuse to be written.
The fitter does not give any warnings however,
and the dedicated clock power guard fuses for other package variants match this one,
except for this one fuse.
This leads me to assume that one line in the fitter source code probably got deleted or something,
causing it to skip this fuse.
I added a special case to force this to the fuse it (very likely) should be.
LC4064ZC_csBGA56 Dedicated Inputs
The datasheet lists that this device has 32 I/Os and 12 input-only pins (4 clocks and 8 dedicated inputs).
I believe that two of the 8 dedicated inputs are actually just connected to regular macrocells.
There is quite a bit of evidence supporting this assumption:
* No other LC4064 or LC4128 packages have more than 6 dedicated inputs, even though some devices (e.g. <code>LC4064ZC_csBGA132</code>) have unconnected pins. One would think if the die actually had 8 dedicated inputs, they would connect them to pins when possible.
* The LC4064s in TQFP-44 use a trick where only half the macrocells have corresponding I/O cells, resulting in a reduced JEDEC height of 95, but this device has a JEDEC height of 100, so internally it likely has the full complement of 64 I/O cells, with half of them unconnected.
* The GI routing fuses used for ball F8 are exactly the same as the fuses for macrocell C12's I/O in packages that expose it.
* The GI routing fuses used for ball E3 are exactly the same as the fuses for macrocell A15's I/O in packages that expose it.
Therefore, in the <code>pins.csv</code> file, I've listed balls E3 and F8 as I/Os corresponding to macrocells A15 and C12, respectively.
Attempting to assign these pins as outputs causes the fitter to spit out a warning,
so there are some fuses that I can't reverse engineer using the fitter.
In these cases I'm just copying the fuse locations from the corresponding macrocell in the <code>LC4064ZC_TQFP100</code> package,
under the assumption that it uses the same die.
Additionally, there appears to be a fitter bug relating to the input threshold fuse for balls F8 and E1.
The fitter toggles two input threshold fuses for the input on ball E1,
and no fuses for the input on ball F8.
Since F8 is one of the "weird" dedicated inputs,
I'm using the C12 macrocell's input threshold fuse from the TQFP100 package for that one,
just like I do for the output configuration fuses.
Then I can just exclude that fuse from the fuses the fitter toggled for ball E1,
which yields only one remaining correct fuse for that ball.
I don't have any of these devices to test physically, so to be safe,
you may just want to avoid using balls E1, E3, and F8 entirely for this particular device.
Fitter Report missing GI data
For <code>LC4064ZC_csBGA56</code>, the second column (GIs 18-35) doesn't always show up in the fitter GI summary.
For some other devices, "input only" pins are incorrectly listed as sourced from a macrocell feedback signal.
e.g. for <code>LC4128ZC_TQFP100</code>, pin 12's source is listed as "mc B-11",
but the GI mux fuse that's set is one of the ones corresponding to pin 16 in <code>LC4128V_TQFP144</code>;
which is MC B14 and ORP B^11 in that device.
So it seems the fitter is writing the I/O cell's ID in this case, rather than the actual pin number.
Glossary
GLB
Generic Logic Block: A group of 36 GIs, 83 PTs, 16 MCs, and the other logic associated with them. Each device contains two or more GLBs.
GRP
Global Routing Pool: the set of all signals that can be used as inputs to a GLB. This includes all I/O cell pins, feedback from all MCs, dedicated clock pins, and (in some devices) dedicated input pins.
GI
Generic Input: One of 36 signals per GLB which can be used in that GLB's product terms.
PT
Product Term: Up to 36 signals (or their complements) ANDed together.
MC
Macrocell: A single flip-flop or combinational logic "output".
MC Slice
Macrocell Slice: A 5-PT cluster, macrocell, routing logic, and I/O cell. Each GLB contains 16 MC Slices, along with the 3 shared PTs, BCLK and GI configuration.
ORM
Output Routing Multiplexer: Allows macrocells and their associated OE product term to be shunted to a different nearby pin.
BCLK
Block Clock: Each GLB ("Block") can independently configure the polarity of the dedicated clock inputs.
BIE
Block Input Enable: For ZE-family devices, inputs can be dynamically masked to reduce dynamic power consumption.
GOE
Global Output Enable: Up to four signals which can come from specific input pins, or from the BIE shared PTs.
CE
Clock Enable
LE
Latch Enable
AS
Asynchronous (pre)Set
AR
Asynchronous Reset/clear
Reproduction Steps
In case you want to try to add other devices, or just want to reproduce the .sx files that are committed here, you can follow these build steps:
<ol>
<li>Make sure ispLEVER Classic 2.1 is installed at <code>C:\ispLEVER_Classic2_1</code> and that you have a valid license. In particular, <code>C:\ispLEVER_Classic2_1\ispcpld\bin\lpf4k.exe</code> needs to work, but nothing else is used.</li>
<li>Make sure Zig is installed and run <code>zig build -Doptimize=ReleaseSafe</code> from the <code>generate/</code> directory.</li>
<li>(optional) Make sure LIMP is installed and run <code>limp -R .</code> from the root of the repo. This will regenerate the Ninja makefiles.</li>
<li>Make sure Ninja is installed and run <code>ninja</code> from the root of the repo.</li>
</ol>
Note: a large number of temporary files are created (and then deleted) in the <code>temp/</code> directory. I found that adding a Windows Defender exclusion for the repo and the <code>ispLEVER_Classic2_1</code> directory significantly speeds up the process.
TODO
<ul>
<li>Hardware experiments<ul>
<li>Why are there two fuses to enable the OSCTIMER? what happens if only one is enabled? (or none, but divider/outputs are enabled)</li>
<li>Do OSCTIMER outputs only replace the GRP feedback signals when enabled, or also the signal that goes to the ORM?</li>
<li>Can you use input register feedback on MCs that aren't connected to pins? (e.g. LC4064x TQFP48)</li>
<li>What happens if you violate the one-cold rule for GI fuses?</li>
</ul>
</li>
</ul> | [
"https://github.com/bcrist/Zig-LC4k"
]
|
https://avatars.githubusercontent.com/u/107519028?v=4 | ziglings-solutions | better-zig/ziglings-solutions | 2022-07-22T10:28:41Z | Learn the Zig programming language by fixing tiny broken programs. | solutions | 0 | 5 | 0 | 5 | https://api.github.com/repos/better-zig/ziglings-solutions/tags | MIT | [
"zig",
"ziglang"
]
| 405 | true | 2025-04-11T16:03:09Z | true | false | unknown | github | []
| Ziglings Solutions
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Ziglings 解题报告, 已完成.
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> 持续更新
related:
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> <a>zig 中文教程</a>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> <a>better-zig/learn-zig</a>: zig 学习练习代码
说明:
<blockquote>
Zig 当前版本:
</blockquote>
<ul>
<li>zig 社区项目, 基本都是基于 <code>zig dev</code> 版本(不维护稳定版本).</li>
<li>so, 请使用 <code>dev 版本</code>, 更快追踪最新特性变更</li>
</ul>
```ruby
➤ zig version
0.10.0-dev.2617+47c4d4450
```
<blockquote>
解题方式:
</blockquote>
```ruby
方式1: 逐一按照顺序解题
zig build
方式2: 传入指定题目编号, 可以忽略其他题目
zig build 1
zig build 83
zig build 84
```
<ul>
<li>本 repo fork 原项目, 会持续同步更新.</li>
<li>解题报告在 <code>solutions</code> 分支.</li>
</ul>
<blockquote>
solutions 分支:
</blockquote>
<ul>
<li>对每个语法练习题, 都补充了注释和错误点.</li>
<li>补充官方文档对各语法点的详细介绍(数据类型/基本操作等)</li>
</ul>
<blockquote>
<a>解题进度</a>
</blockquote>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> <a>ex001</a> - <a>ex091</a>
- 已完成
<blockquote>
补充说明:
</blockquote>
<ul>
<li><a>ex001</a> - <a>ex008</a> : 简单数据类型(数组, 字符串基本操作)</li>
<li><a>ex009</a> - <a>ex017</a> : 控制逻辑语句(if/else, while, for 语法)</li>
<li><a>ex018</a> - <a>ex020</a> : 函数定义(参数/返回值)</li>
<li><a>ex021</a> - <a>ex025</a> : 错误处理</li>
<li>⭐⭐⭐⭐⭐</li>
<li><a>ex022</a> : zig 的自定义错误+类型 union 并集写法, 非常风骚.</li>
<li>zig 的错误处理, catch 语义, 融合了 go panic 机制+ 赋默认值, 很特别的设计</li>
<li>try 语言, 实现了 常规语言的 try...catch 机制, 手动管理(忽略) panic.</li>
<li><a>ex027</a> - <a>ex027</a> : defer/errdefer 机制, 类似 go defer</li>
<li>⭐⭐⭐</li>
<li><a>ex030</a> - <a>ex032</a> : switch + else, 类似 rust match</li>
<li><a>ex033</a> : if/err 语义</li>
<li><a>ex34</a> : try catch</li>
<li><a>ex35</a> - <a>ex36</a> : enum 枚举类型</li>
<li><a>ex37</a> - <a>ex38</a> : struct 结构体类型</li>
<li><a>ex39</a> - <a>ex44</a> : pointer 指针类型, 取地址操作(类似 C 语言), 指针参数, 传引用类型</li>
<li>⭐⭐⭐⭐⭐</li>
<li><a>ex045</a> - <a>ex046</a> : optional 语义, 类似 <code>dart Null Safety 语义</code>.</li>
<li>⭐⭐</li>
<li><a>ex047</a> - <a>ex049</a> : struct method 语义, 类似 <code>python class + self 语义</code>, 区分 类函数(静态) vs 类方法.</li>
<li><a>ex050</a> - <a>ex051</a> : value 类型: <code>undefined vs null vs errors vs void</code> 语义区别</li>
<li>⭐⭐⭐</li>
<li><a>ex052</a> - <a>ex053</a> : 数组切片 + 指针</li>
<li>⭐⭐</li>
<li><a>ex054</a> : 数组指针, 指向一片元素. (难理解, 类 C 语言)</li>
<li>⭐⭐⭐⭐⭐</li>
<li><a>ex055</a> - <a>ex058</a> : union 联合体类型(类 c 语言), 联合体+枚举 混合类型.</li>
<li>⭐⭐</li>
<li><a>ex059</a> - <a>ex060</a> : 数值计算: 整型(2 进制, 8 进制, 16 进制) vs 浮点型</li>
<li>⭐⭐</li>
<li><a>ex061</a> : 定长数组指针</li>
<li>⭐</li>
<li><a>ex062</a> - <a>ex063</a> : for + break label + else 语义</li>
<li>⭐⭐⭐</li>
<li><a>ex064</a> - <a>ex065</a> : builtin functions 编译器内建函数, 实现类似 <code>go reflect 反射</code>等语义</li>
<li>⭐⭐⭐⭐</li>
<li><a>ex066</a> - <a>ex075</a> : builtin functions 编译期阶段的高阶用法</li>
<li>⭐⭐⭐⭐⭐</li>
<li><a>ex066</a> - <a>ex067</a> : 变量定义, 加 <code>comptime</code> 前缀, 强制指定编译期检查. (类似 rust 生命周期标记, 改变变量生命周期)</li>
<li><a>ex068</a> - <a>ex069</a> : 函数参数, 加 <code>comptime</code> 前缀, 强制指定编译期检查.</li>
<li><a>ex070</a> : 函数参数, 指定为 <code>anytype</code> 类型, 配合 <code>@TypeOf() + @hasDecl()</code>实现多态(鸭子类型). 类似 go + reflect 反射效果.(用法也类似)</li>
<li><a>ex071</a> : 内联优化, <code>inline for</code>, 类似 <code>C/C++</code> 内联概念.</li>
<li><a>ex072</a> : 内联优化, <code>inline while</code>.</li>
<li><a>ex073</a> : 任意表达式, 加 <code>comptime</code> 前缀, 强制指定编译期阶段检测(分配).</li>
<li><a>ex074</a> - <a>ex075</a> : 默认省略 <code>comptime</code> 前缀的场景.</li>
<li><a>ex076</a> - <a>ex078</a> : 字符串类型, <code>sentinel</code> 尾哨兵机制. 兼容 <code>C 字符串</code> 语义, <code>@ptrCast()</code> 强制类型转换.</li>
<li>⭐⭐⭐</li>
<li><a>ex079</a> : 命名规则扩展, <code>@"x-y-z"</code> 作为命名字段. 比较无聊的<code>语法糖</code>.</li>
<li><a>ex080</a> - <a>ex083</a>: 泛型数据结构 + 鸭子类型(多态/反射) - <code>匿名结构体 + @typeName(@TypeOf()) + @as() + @field()</code>,</li>
<li>⭐⭐⭐</li>
<li><a>ex084</a> - <a>ex091</a> : 异步并发编程, <code>suspend + resume + async + await + nosuspend + panic UB error</code>.</li>
<li>⭐⭐⭐⭐⭐</li>
<li><a>ex084</a> - <a>ex086</a>: 异步编程, <code>suspend + resume + async</code>, 简单用法</li>
<li><a>ex087</a> : 异步编程, 使用<code>async + suspend + resume + global var</code> 全局变量, 实现协程间同步通信.</li>
<li><a>ex088</a> - <a>ex089</a>: 异步编程, 使用<code>async + await + return</code> 基于 await 实现协程同步.</li>
<li><a>ex090</a> : 异步编程, <code>nosuspend + suspend + panic UB(未定义)错误</code></li>
<li><a>ex091</a> : 异步编程, <code>suspend + async + resume</code>, 完整理解每条语句的执行顺序.(控制流切换)</li>
</ul>
快速开始:
<blockquote>
准备:
</blockquote>
<ul>
<li><a>配置 zig 开发环境(vscode 设置)</a></li>
<li>安装 go-task</li>
</ul>
<blockquote>
开始:
</blockquote>
```ruby
拉取本 repo 代码:
git clone [email protected]:better-zig/ziglings-solutions.git
切换分支:
git checkout solutions
```
<blockquote>
验证:
</blockquote>
```ruby
切换本项目根目录
cd this-repo-root/
编译+运行, 交互式逐个修复有问题的测试题
zig build
or:
task dev
```
Ziglings
Welcome to Ziglings! This project contains a series of tiny broken programs.
By fixing them, you'll learn how to read and write
<a>Zig</a>
code.
Those tiny broken programs need your help! (You'll also save the planet from
evil aliens and help some friendly elephants stick together, which is very
sweet of you.)
This project was directly inspired by the brilliant and fun
<a>rustlings</a>
project for the <a>Rust</a> language.
Indirect inspiration comes from <a>Ruby Koans</a>
and the Little LISPer/Little Schemer series of books.
Intended Audience
This will probably be difficult if you've <em>never</em> programmed before.
But no specific programming experience is required. And in particular,
you are <em>not</em> expected to have any prior experience with "systems programming"
or a "systems" level language such as C.
Each exercise is self-contained and self-explained. However, you're encouraged
to also check out these Zig language resources for more detail:
<ul>
<li>https://ziglearn.org/</li>
<li>https://ziglang.org/documentation/master/</li>
</ul>
Also, the <a>Zig community</a> is incredibly friendly and helpful!
Getting Started
Install a <a>development build</a> of the Zig compiler.
(See the "master" section of the downloads page.)
Verify the installation and build number of <code>zig</code> like so:
<code>bash
$ zig version
0.10.0-dev.1427+xxxxxxxxx</code>
Clone this repository with Git:
<code>bash
$ git clone https://github.com/ratfactor/ziglings
$ cd ziglings</code>
Then run <code>zig build</code> and follow the instructions to begin!
<code>bash
$ zig build</code>
A Note About Versions
The Zig language is under very active development. In order to be current,
Ziglings tracks <strong>development</strong> builds of the Zig compiler rather than
versioned <strong>release</strong> builds. The last stable release was <code>0.9.1</code>, but Ziglings
needs a dev build with pre-release version "0.10.0" and a build number at least
as high as that shown in the example version check above.
It is likely that you'll download a build which is <em>greater</em> than the minimum.
<em>(For those who cannot easily update Zig, there are also community-supported
branches in this repo. At the moment, there's one for v0.8.1. Older version
branches may or may not have all exercises and/or bugfixes.)</em>
Once you have a build of the Zig compiler that works with Ziglings, they'll
continue to work together. But keep in mind that if you update one, you may
need to also update the other.
Also note that the current "stage 1" Zig compiler is very strict
about input:
<a>no tab characters or Windows CR/LF newlines are allowed</a>.
Version Changes
<ul>
<li><em>2022-03-19</em> zig 0.10.0-dev.1427 - method for getting sentinel of type changed</li>
<li><em>2021-12-20</em> zig 0.9.0-dev.2025 - <code>c_void</code> is now <code>anyopaque</code></li>
<li><em>2021-06-14</em> zig 0.9.0-dev.137 - std.build.Id <code>.Custom</code> is now <code>.custom</code></li>
<li><em>2021-04-21</em> zig 0.8.0-dev.1983 - std.fmt.format() <code>any</code> format string required</li>
<li><em>2021-02-12</em> zig 0.8.0-dev.1065 - std.fmt.format() <code>s</code> (string) format string required</li>
</ul>
Advanced Usage
It can be handy to check just a single exercise or <em>start</em> from a single
exercise:
<code>bash
zig build 19
zig build 19_start</code>
You can also run without checking for correctness:
<code>bash
zig build 19_test</code>
Or skip the build system entirely and interact directly with the compiler
if you're into that sort of thing:
<code>bash
zig run exercises/001_hello.zig</code>
Calling all wizards: To prepare an executable for debugging, install it
to zig-cache/bin with:
<code>bash
zig build 19_install</code>
What's Covered
I've decide to limit Ziglings to the core language and not
attempt coverage of the Standard Library. Perhaps you can change
my mind?
Core Language
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Hello world (main needs to be public)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Importing standard library
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Assignment
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Arrays
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Strings
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> If
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> While
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> For
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Functions
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Errors (error/try/catch/if-else-err)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Defer (and errdefer)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Switch
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Unreachable
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Enums
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Structs
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Pointers
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Optionals
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Struct methods
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Slices
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Many-item pointers
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Unions
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Numeric types (integers, floats)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Labelled blocks and loops
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Loops as expressions
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Builtins
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Inline loops
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Comptime
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Sentinel termination
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Quoted identifiers @""
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Anonymous structs/tuples/lists
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Async <--- IN PROGRESS!
Contributing
Contributions are very welcome! I'm writing this to teach myself and to create
the learning resource I wished for. There will be tons of room for improvement:
<ul>
<li>Wording of explanations</li>
<li>Idiomatic usage of Zig</li>
<li>Maybe additional exercises?</li>
</ul>
Please see CONTRIBUTING.md in this repo for the full details. | []
|
https://avatars.githubusercontent.com/u/107234593?v=4 | ogc | zig-wii/ogc | 2022-06-10T12:14:05Z | Zig game engine and bindings for libogc | master | 0 | 5 | 1 | 5 | https://api.github.com/repos/zig-wii/ogc/tags | - | [
"devkitpro",
"wii",
"zig"
]
| 34 | false | 2024-05-09T19:09:12Z | true | false | unknown | github | []
| ogc
Zig game engine and bindings for the Wii in Zig with zero-fuss installation.
To see how this library is used, see <a>example</a>
and <a>rogue</a>.
Commands
<ul>
<li>To build and run with Dolphin, do <code>zig build run</code></li>
<li>To build and deploy to Wii over network (must be in Homebrew menu), do <code>zig build deploy</code></li>
<li>To build and debug crash addresses, do <code>zig build line -- <addresses></code></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/2828351?v=4 | Zig-TempAllocator | bcrist/Zig-TempAllocator | 2022-07-26T05:46:09Z | Arena allocator for interactive programs and simulations | main | 0 | 5 | 0 | 5 | https://api.github.com/repos/bcrist/Zig-TempAllocator/tags | MIT | [
"allocator",
"utilities",
"utility-library",
"zig",
"zig-library",
"zig-package",
"ziglang"
]
| 41 | false | 2025-04-28T20:12:04Z | true | true | 0.14.0 | github | []
| Zig-TempAllocator
A stack allocator similar to std.heap.ArenaAllocator, except:
<ul>
<li>You can reset the whole allocator without releasing the underlying memory back to the OS.</li>
<li>You can take a snapshot at any time and later invalidate/free all allocations after that point, but preserving allocations before it.</li>
<li>It will track how much memory is usually used before being reset, and release some if it remains significantly lower than the current committed capacity.</li>
<li>The inner "child allocator" is not configurable; internally it uses OS memory management facilities directly.</li>
</ul>
The primary use-cases for TempAllocator are real-time interactive programs and simulations (games, GUIs, etc.), but it can be useful for anything where work is done sequentially in a main loop, and it's easy to guarantee that memory allocated from it won't be held across resets.
Usage Example
```zig
const std = @import("std");
const TempAllocator = @import("temp_allocator.zig");
const app = @import("myApp.zig");
pub fn main() void {
var tempalloc = TempAllocator.init(1024<em>1024</em>1024); // 1GB of virtual address space
defer tempalloc.deinit();
<code>var n: usize = 0;
while (!app.shouldExit()) {
tempalloc.reset();
n += 1;
var temp: []u8 = std.fmt.allocPrint(tempalloc.allocator(), "number {} is {s}", .{ n, "Something" });
app.doSomethingWithAString(temp);
}
</code>
}
```
Zig Version
Last updated for <code>zig 0.12.0-dev.1591+3fc6a2f11</code>; use with significantly older or newer versions may require adjustments
Implementation Notes
TempAllocator utilizes a fixed chunk of virtual address space to allocate from. The size of this chunk must be specified when initializing the allocator, and can't be changed while the allocator is in use. But the maximum size may be enormous (up to several terabytes on windows, and possibly even more on other systems). This is because the full virtual address chunk won't be "committed" to physical memory and/or swap pages until it's actually used.
Windows
The full virtual address chunk is allocated with:
<code>VirtualAlloc(null, capacity, MEM_RESERVE, PAGE_NOACCESS)
</code>
Then when regions need to be used, they're committed with:
<code>VirtualAlloc(ptr, len, MEM_COMMIT, PAGE_READWRITE)
</code>
Later, those regions may be decommitted with:
<code>VirtualFree(ptr, len, MEM_DECOMMIT)
</code>
Linux/MacOS
The full virtual address chunk is allocated with:
<code>mmap(null, capacity, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE)
</code>
The use of <code>MAP_NORESERVE</code> means we open up the possibility of getting segfaults later when the allocator's memory is written to, if the system runs out of physical memory. But linux's default <code>vm.overcommit_memory</code> sysctl means that can already happen for pretty much any allocation anyway. Zig's use of errors to try to handle allocation failures is more or less useless on linux.
The full virtual address range is <code>mmap</code>ed as writable, but real pages won't be assigned until they're written to. But we still keep track of "committed" pages so that later we can mark them unused when we would normally decommit them on Windows:
<code>madvise(ptr, len, MADV_DONTNEED)
</code> | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | ox | nektro/ox | 2022-04-17T18:39:26Z | Opinionated web framework for Zig | master | 0 | 5 | 1 | 5 | https://api.github.com/repos/nektro/ox/tags | AGPL-3.0 | [
"web-framework",
"zig"
]
| 28 | false | 2025-02-02T20:52:07Z | false | false | unknown | github | []
| 404 | []
|
https://avatars.githubusercontent.com/u/85593302?v=4 | utils | svelterust/utils | 2022-06-12T17:19:50Z | Nice helper functions for build.zig | master | 0 | 4 | 0 | 4 | https://api.github.com/repos/svelterust/utils/tags | - | [
"utils",
"zig"
]
| 5 | false | 2022-06-21T19:19:29Z | true | false | unknown | github | []
| utils
Collection of useful functions for <code>build.zig</code>.
Examples are listed in the source code.
Getting started
<code>bash
curl https://raw.githubusercontent.com/knarkzel/utils/master/src/main.zig -o utils.zig</code>
Documentation
```zig
pub const Options = struct {
enable_stdout: bool = false,
enable_stderr: bool = false,
};
/// Looks for build.zig by traversing from current directory and upwards,
/// ideal for setting builder.build_root starting from builder.build_root
pub fn root(cwd: []const u8) UtilsError![]const u8
/// Run shell command
pub fn exec(allocator: std.mem.Allocator, cwd: []const u8, argv: []const []const u8, opts: Options) !void
/// Ensure repository exists, if not clone it with git. cwd is absolute path
pub fn ensure_repository(allocator: std.mem.Allocator, cwd: []const u8, path: []const u8, url: []const u8) !void
/// Ensure submodules are initialized. cwd is absolute path
pub fn ensure_submodules(allocator: std.mem.Allocator, cwd: []const u8) !void
/// Ensure zigmod has done initial fetch. cwd is absolute path
pub fn ensure_zigmod(allocator: std.mem.Allocator, cwd: []const u8) !void
/// Ensure file exists, otherwise wget it. cwd is absolute path
pub fn ensure_file(allocator: std.mem.Allocator, cwd: []const u8, path: []const u8, url: []const u8) !void
/// Ensure path exists, otherwise wget and extract it with tar. cwd is absolute path
pub fn ensure_tar(allocator: std.mem.Allocator, cwd: []const u8, path: []const u8, url: []const u8) !void
``` | []
|
https://avatars.githubusercontent.com/u/1560508?v=4 | cpp-zig-build-system-demo | ryoppippi/cpp-zig-build-system-demo | 2022-08-04T11:22:25Z | null | main | 1 | 4 | 0 | 4 | https://api.github.com/repos/ryoppippi/cpp-zig-build-system-demo/tags | MIT | [
"zig",
"ziglang"
]
| 33 | false | 2024-05-17T12:54:03Z | true | false | unknown | github | []
| cpp-zig-build-system-demo
Compare Cmake and zig toolchain to build a C++ project.
<code>sh
make build_zig
make build_cmake_make
make build_cmake_ninja</code>
Japanese Article
https://zenn.dev/ryoppippi/articles/9efc7b621ec853
License
MIT
Author
Ryotaro "Justin" Kimura (a.k.a. ryoppippi) | []
|
https://avatars.githubusercontent.com/u/17478576?v=4 | sqlite3.zig | riyaz-ali/sqlite3.zig | 2022-08-17T11:21:44Z | sqlite3 database driver for ziglang | main | 1 | 4 | 0 | 4 | https://api.github.com/repos/riyaz-ali/sqlite3.zig/tags | MIT | [
"sqlite3",
"sqlite3-extension",
"zig"
]
| 17 | false | 2023-10-29T08:16:39Z | false | false | unknown | github | []
| sqlite3.zig
<a></a>
<a></a>
<strong><code>sqlite3.zig</code></strong> is a minimal, non-opinionated <a><code>sqlite3</code></a> driver for <a><code>ziglang</code></a>.
Overview
<code>sqlite3.zig</code> provides an easy interface to <code>sqlite3</code> that allows you to build both applications and <a><code>sqlite3</code> runtime extensions</a>.
Setup
<ul>
<li>You need to download the <a><code>sqlite3</code> amalgamation file</a> and extract it inside your project
(say under <code>$PROJECT/sqlite3</code> directory). </li>
</ul>
The library follows a <em>Bring-Your-Own</em> model when it comes to bundling <code>sqlite3</code>. You are expected
to provide necessary configuration by setting up appropriate include paths etc. This may sound difficult but is extremely easy and allows
you to better manage <code>sqlite3</code> version (rather than depend on us to update it 😉).
<ul>
<li>Update your <code>build.zig</code> file to add <code>$PROJECT/sqlite3</code> to your include path, and also add a dependency on <code>sqlite3.c</code> source file.</li>
</ul>
<code>zig
exe.addIncludeDir("sqlite3/");
exe.addCSourceFile("sqlite3/sqlite3.c", &[_][]const u8 {
// any compile-time flags that you might want to add
// see: https://www.sqlite.org/compile.html
});</code>
This would allow <code>#include <sqlite3.h></code> to resolve to <code>$PROJECT/sqlite3/sqlite3.h</code> and also include <code>sqlite3.c</code> source along with your application.
<ul>
<li>To add <code>sqlite3.zig</code> to your project add it as a git submodule (say at <code>$PROJECT/libs/sqlite3</code>)</li>
</ul>
<code>zig
exe.addPackagePath("sqlite3.zig", "libs/sqlite3/sqlite3.zig");</code>
You can now do <code>@import('sqlite3.zig')</code> and start enjoying <code>sqlite3</code> 😁
## License
MIT License Copyright (c) 2022 Riyaz Ali
Refer to <a>LICENSE</a> for full text. | []
|
https://avatars.githubusercontent.com/u/139?v=4 | adventofcode2022 | leahneukirchen/adventofcode2022 | 2022-11-30T12:44:43Z | Advent of Code 2022 in Racket and Zig. | master | 0 | 4 | 0 | 4 | https://api.github.com/repos/leahneukirchen/adventofcode2022/tags | - | [
"advent-of-code",
"advent-of-code-2022",
"racket",
"zig"
]
| 138 | false | 2024-09-15T15:09:22Z | false | false | unknown | github | []
| Advent of Code 2022 (adventofcode.com) in Racket and Zig.
I'm using Racket 8.7 and Zig 0.10.0.
Solutions appear the day after---no spoilers.
To the extent possible under law, Leah Neukirchen has waived
all copyright and related or neighboring rights to this work.
http://creativecommons.org/publicdomain/zero/1.0/ | []
|
https://avatars.githubusercontent.com/u/4645331?v=4 | rvz | chaoyangnz/rvz | 2022-08-30T03:49:22Z | xv6 port on RISC-V VisionFive2 / Nezha in Zig | master | 0 | 4 | 0 | 4 | https://api.github.com/repos/chaoyangnz/rvz/tags | - | [
"d1-h",
"jh7110",
"risc-v",
"xv6",
"zig"
]
| 32,354 | false | 2025-02-03T04:53:31Z | true | false | unknown | github | []
| RVZ
A xv6 port on JH7110 / D1-H using Zig.
<blockquote>
Currently I run on VisionFive2. In <a>rvx</a>, I managed to port on Nezha D1 in C.
</blockquote>
Development (Ubuntu)
Prerequisite
<ul>
<li><a>VisionFive2</a></li>
<li><a>Nezha</a></li>
</ul>
Unbuntu:
- USB-UART driver: <code>sudo apt install libusb-1.0-0-dev</code>
- packages:
- Zig: <code>snap install zig --classic --edge</code>
- toolchain: <code>npm i xpm & xpm i</code>
- (optional): <code>sudo apt-get install -y gcc-riscv64-linux-gnu</code>
Validation
<ul>
<li><code>lsusb</code></li>
</ul>
Bus 001 Device 004: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
<code>sudo adduser <user> dialout</code>
Tools
These tools may be needed during build, so better to put them in <code>$PATH</code>.
<ul>
<li><a>vf2flash</a></li>
</ul>
A utility to help load your kernel into DRAM and run and also flash your kernel into SPI Flash sector. It also can act as a Serial terminal.
<ul>
<li>
<a>vf2-uboot-fit-imager</a>
</li>
<li>
<a>xfel</a>
</li>
</ul>
A CLI tool to build U-boot FIT image with visionfive ITS.
Build (test bare metal)
<code>./dev</code>
The above will load the binary to DRAM 0x40000000 and run.
You should be able to see UART output at the end. | []
|
https://avatars.githubusercontent.com/u/40190339?v=4 | Dodgeballz | daneelsan/Dodgeballz | 2022-04-19T07:13:46Z | A mini game using Zig, WASM and JS | master | 0 | 4 | 0 | 4 | https://api.github.com/repos/daneelsan/Dodgeballz/tags | - | [
"html5-canvas",
"webassembly",
"zig"
]
| 1,054 | false | 2025-03-10T03:38:17Z | true | false | unknown | github | []
| DodgeBallz
Play the game at: https://daneelsan.github.io/Dodgeballz/
<a>DodgeBalls</a> implemented in zig (compiled to wasm-freestanding).
This mini game shows how Zig, WASM, Javascript and HTML5 canvas can interact.
In particular, there are lots of back and forth between imported and exported wasm functions.
Among those imported functions are functions that draw things on a canvas, e.g. <code>arc</code> or <code>strokeRect</code>.
Build
Tested in version:
<code>shell
$ zig version
0.14.0</code>
To build the wasm module, run:
```shell
$ zig build
$ ls zig-out/lib/
DodgeBallz.wasm
```
Run
Start up the server in this repository's directory:
<code>shell
python3 -m http.server</code>
Go to your favorite browser and type to the URL <code>localhost:8000</code>. You should see the checkboard changing colors.
TODOs
<ul>
<li>
Find a better way to debug from the wasm module. I used a lot of <code>console.log</code> to debug, but given that we can only pass a limited set of types between JS and WASM (e.g. <code>i32</code> or <code>f32</code>), this was tedious. Perhaps there is a way to write a zig <code>Writer</code> that writes into the console.
</li>
<li>
Of course, there are many improvements to the game. The score could be made to depend on the size of the enemy, the number of enemies could increase depending on the score achieved, etc.
</li>
</ul>
Resources
<ul>
<li>https://github.com/daneelsan/DodgeBalls</li>
<li>https://github.com/daneelsan/minimal-zig-wasm-canvas</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/59705845?v=4 | multiring.zig | ok-ryoko/multiring.zig | 2022-12-16T03:57:08Z | Hierarchical, forwardly linked and circularly linked abstract data type in Zig | main | 2 | 4 | 0 | 4 | https://api.github.com/repos/ok-ryoko/multiring.zig/tags | MIT | [
"abstract-data-type",
"zig"
]
| 634 | false | 2024-10-27T11:41:50Z | true | true | unknown | github | []
|
<source
media="(prefers-color-scheme: dark)"
srcset="./docs/img/multiring-github-dark.png"
<blockquote>
<source
media="(prefers-color-scheme: light)"
srcset="./docs/img/multiring-github-light.png"
<img
src="./docs/img/multiring-github-light.png"
title="multiring"
alt="Multiring comprising 18 data nodes arranged in 5 rings at 3 levels"
align="left"
height="61"
</blockquote>
multiring.zig
The <em>multiring</em> is a <a>hierarchical</a>, <a>forwardly linked</a> and circularly linked <a>abstract data type</a>. multiring.zig implements the multiring in the <a>Zig programming language</a>.
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
The multiring, as implemented in this repository, hasn’t been specified and verified formally.
</blockquote>
Here’s how a multiring is traversed:
The counter-clockwise orientation of traversal in the animation above is arbitrary—we obtain it by having the normal to the plane of each ring point up and applying the <a>right-hand rule</a>. We chose a 3D representation to better visualize the depth of the traversal.
Properties of this module
<ul>
<li>Linked list-like interface</li>
<li>No recursive method implementations</li>
<li>No dependencies</li>
<li>No memory management</li>
</ul>
Adding multiring.zig to a Zig v0.13.0 project
In your project’s <em>build.zig.zon</em> file, add the following dependency:
<code>zig
.{
.dependencies = .{
.multiring = .{
.url = "https://github.com/ok-ryoko/multiring.zig/archive/refs/heads/main.tar.gz",
},
},
}</code>
When you first run <code>zig build</code>, it will complain about a missing hash for the <code>multiring</code> dependency and echo the computed hash. You can use this value to populate the dependency’s <code>hash</code> field.
Next, declare this module as a dependency in your <em>build.zig</em> file, e.g.,
<code>zig
const multiring = b.dependency(
"multiring",
.{ .target = target, .optimize = optimize },
);</code>
Finally, add the module to your target, e.g.,
<code>zig
exe.root_module.addImport("multiring", multiring.module("multiring"));</code>
… where <code>exe</code> in this example is a <code>*std.Build.Step.Compile</code> that represents an executable to be compiled. You should now be able to import the <code>MultiRing</code> ADT like so:
<code>zig
const MultiRing = @import("multiring").MultiRing;</code>
This module has not yet had any versioned releases, so dependents that favor reproducibility should reference a particular commit on <code>main</code> as in the following example:
<code>zig
.{
.dependencies = .{
.multiring = .{
.url = "https://github.com/ok-ryoko/multiring.zig/archive/4d241318e1aa6cec7c0bb9b50dda4fae11720839.tar.gz",
.hash = "12202e4b8b3ea04e5397225ab2ee83a9e002946488b07da78b4da09f88519a7d459d",
},
},
}</code>
Using multiring.zig
Please see the tests in <a><em>multiring_test.zig</em></a> as well as the <a>examples</a>.
The <code>MultiRing</code> API is still unstable; <a>Ryoko</a> doesn’t recommend using this library in production.
Applications
multiring.zig has no known applications. Ryoko wrote it to practice Zig, have fun and show linked lists some love. If you have used multiring.zig successfully in your project(s), please let us know by <a>starting a discussion</a>.
Community
Understanding our code of conduct
Please take time to read <a>our code of conduct</a> before reaching out for support or making a contribution.
Getting support
If you’re encountering unexpected or undesirable program behavior, check the <a>issue tracker</a> to see whether your problem has already been reported. If not, please consider taking time to create a bug report.
If you have questions about using the program or participating in the community around the program, consider <a>starting a discussion</a>.
Please allow up to 1 week for a maintainer to reply to an issue or a discussion.
Contributing to multiring.zig
If you’re interested in contributing, then please read <a>our contributing guidelines</a>.
License
multiring.zig is free and open source software <a>licensed under the MIT license</a>.
Acknowledgements
The multiring.zig logos and traversal animations were made in <a>Inkscape</a> and <a>Blender</a>, respectively.
The initial implementation was inspired by Zig 0.9.1’s <a><code>std.SinglyLinkedList</code></a>.
The following resources have been instrumental in preparing this repository for community contributions:
<ul>
<li><a>Open Source Guides</a></li>
<li><a>the GitHub documentation</a> and <a>the github/docs repository</a></li>
<li><a>the tokio contributing guidelines</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/25912761?v=4 | candy-stick | r4gus/candy-stick | 2022-09-27T20:50:58Z | CTAP2 authenticator implementation in Zig | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/r4gus/candy-stick/tags | MIT | [
"authentication",
"authenticator",
"ctap",
"ctap2",
"fido",
"fido2",
"zig",
"ziglang"
]
| 8,227 | false | 2023-02-21T16:08:26Z | false | false | unknown | github | []
| Candy Stick
There have been some API changes to the fido2 library, i.e., this project will currently not compile. Please see <a>candy-stick-nrf</a> for a working example.
CTAP2 firmware
<code>src/
|-ctaphid/
| |-response.zig (for generating CTAPHID response packets)
| |-misc.zig (helper functions and constants)
| |-commands.zig (CTAPHID commands)
|-zigusb.zig (entry point and USB callbacks)</code>
Build
To build the project you must have installed the <a>Zig</a> compiler on your system.
You also need the <code>arm-none-eabi</code> build tools.
Arch
<code>sudo pacman -S arm-none-eabi-gcc arm-none-eabi-newlib</code>
Ubuntu
<code>sudo apt install gcc-arm-none-eabi</code>
<blockquote>
<strong>NOTE</strong>: Without <code>*-newlib</code> (Arch) you'll get the <code>fatal error: stdint.h: No such file or directory
# include_next <stdint.h></code> error.
</blockquote>
Also make sure that you've <code>git</code> installed. Then just run <code>./build</code> from the root directory.
Flash
To flash the firmware install <a>edbg</a> and then just run <code>./flash</code> from the
root directory.
<blockquote>
Note: This project targets the SAM E51 Curiosity Nano, i.e. the
ATSAME51J20A (ARM Cortex-M4F) chip.
</blockquote>
Tools
To use the tools you need to install <code>libfido2</code>.
Arch
<code>sudo pacman -S libfido2</code>
Ubuntu
<code>$ sudo apt install libfido2-1 libfido2-dev libfido2-doc fido2-tools</code>
Build from source
<code>git clone https://github.com/Yubico/libfido2.git
cd libfido2
cmake -B build
make -C build
sudo make -C build install</code>
Important Notes
<ul>
<li>The <code>ztap</code> library doesn't sort keys automatically (due to a bug when calling the Zig sort function - program hangs). One must make sure that the returned CBOR is in CTAP canonical CBOR encoding form, e.g. the keys have to be sorted in a specific way. Otherwise libraries like libfido2 will complain.</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/66876057?v=4 | box2d-lite-zig | jakubtomsu/box2d-lite-zig | 2022-06-17T16:49:09Z | Box2D-Lite rewritten in Zig. Box2D is a small physics engine for 2D games. | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/jakubtomsu/box2d-lite-zig/tags | - | [
"game-development",
"physics",
"physics-2d",
"physics-engine",
"physics-simulation",
"zig",
"zig-library"
]
| 2,448 | false | 2024-12-20T17:25:32Z | false | false | unknown | github | []
| Box2D-Lite Zig
Version of <a>Box2D-Lite</a> rewritten in
the <a>Zig programming language</a>
<blockquote>
Box2D-Lite is a small 2D physics engine. It was developed for the 2006 GDC Physics Tutorial. This is the original version of the larger Box2D library. The Lite version is more suitable for learning about game physics.
</blockquote>
Note: it's still work-in-progress!
Tested Zig compiler version: <strong>0.10.0-dev.2585+fcfeafe99</strong>
<a>box2d_raylib_debugdraw.zig</a>: Debug drawing with raylib.
Basic Example
Shows how to set-up a physics world and run simulation. Prints body positions to console.
```zig
const std = @import("std");
const b2 = @import("box2d.zig");
pub fn main() anyerror!void {
// Initialize Box2D World
var b2World: b2.World = b2.World{
.gravity = b2.Vec2{ .x = 0, .y = -9.81 },
.iterations = 6,
.accumulateImpulses = true, // Enable accumulating impulsed over many frames
.warmStarting = true, // Reuse impulses from last frame to start the physics solver
.positionCorrection = true, // Also correct position, not just velocity
.bodies = b2.World.BodyMap.init(std.heap.page_allocator),
.arbiters = b2.World.ArbiterMap.init(std.heap.page_allocator),
};
<code>// Add ground
// Body.init arguments: position, scale, mass
b2World.addBody(b2.Body.init(.{ .x = 0, .y = 0 }, .{ .x = 20, .y = 1 }, std.math.inf(f32)));
// Add dynamic body
b2World.addBody(b2.Body.init(.{ .x = 0, .y = 5 }, .{ .x = 2, .y = 2 }, 2.0));
while(true) {
// Simulate physics
b2World.step(deltatime);
// Print positions of bodies
for (b2World.bodies.items) |b, i| std.debug.print("Body #{} position={}\n", .{i, b.position});
}
</code>
}
```
TODO
<ul>
<li>joints</li>
<li>proper example app</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/153000?v=4 | zig-mark-sweep-gc | justinethier/zig-mark-sweep-gc | 2022-05-16T00:49:48Z | :broom: Zig port of Bob Nystrom's simple mark-sweep GC | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/justinethier/zig-mark-sweep-gc/tags | MIT | [
"garbage-collection",
"memory-management",
"zig",
"ziglang"
]
| 135 | false | 2023-12-31T18:08:48Z | false | false | unknown | github | []
| Porting a simple Mark-Sweep Garbage Collector to Zig
This project is a port of Bob Nystrom's simple mark-sweep garbage collector - a modern classic! - from C to Zig.
Since Zig is a relatively new language I thought it would be helpful to give an overview of the experience and talk about the tooling.
This post explains a few parts of the program but I can't do justice to <a>Bob's original article</a> which I highly recommend reading. His C implementation is included as <code>main.c</code> in this repo and is available <a>on GitHub</a>.
Anyway, off we go...
Installing Zig
The installation process is very simple. Just download the latest version from the <a>Releases page</a>, extract to a folder, and add to your path.
For example here is how Zig is installed for this project's continuous integration:
<code>bash
wget https://ziglang.org/download/0.9.1/zig-linux-x86_64-0.9.1.tar.xz
tar xf zig-linux*.tar.xz
echo "`pwd`/zig-linux-x86_64-0.9.1" >> $GITHUB_PATH</code>
A real installation would put the files somewhere more appropriate but this works just fine for our CI.
<code>zig</code> comes as a large statically-linked executable. No dependencies required :thumbsup:.
Vim Plugin
Out of the box Vim works well enough as an editor for Zig but the experience is a bit underwhelming. So I installed the <a>Vim configuration for Zig</a> plugin get syntax highlighting.
As an unexpected bonus:
<blockquote>
This plugin enables automatic code formatting on save by default using <code>zig fmt</code>.
</blockquote>
Much like with Go its super handy to be able to just <em>not worry</em> about code formatting. On top of that <code>zig fmt</code> also catches basic syntax errors:
I tend to save frequently when coding so this provides constant feedback on the state of the code.
Printing
I just used debug printing to write output:
<code>zig
const print = @import("std").debug.print;
print("Collected {} objects, {} remaining.\n", .{ numObjects - self.numObjects, self.numObjects });</code>
An interesting observation is that instead of C varargs Zig uses an <a>anonymous struct</a>.
While Loops, If's, Optionals, and More
Zig has many improvements over standard C syntax.
Increment as part of the loop:
<code>zig
while (i < self.stack_size) : (i += 1) {</code>
Unbox <a>optionals</a>:
<code>zig
while (object.*) |obj| {
if (object.data.pair.head) |head| {</code>
Handle <a>error unions</a>:
<code>zig
var a = vm.pushPair() catch unreachable;</code>
Other miscellaneous improvements over C include standard naming conventions (underscores in names for non-callable variables) and a cleaner boolean type.
It is also helpful to define functions as part of a <code>struct</code> type, allowing a more natural organization of code. Though this has been a standard feature in most languages for a long time now. <a>Including C++</a>.
Pointers
The <code>sweep</code> function uses a pointer-to-pointer to walk the linked list of all objects and unlink unused objects:
```c
void sweep(VM<em> vm)
{
Object</em><em> object = &vm->firstObject;
while (</em>object) {
if (!(<em>object)->marked) {
/</em> This object wasn't reached, so remove it from the list and free it. <em>/
Object</em> unreached = *object;
<code> *object = unreached->next;
free(unreached);
vm->numObjects--;
} else {
/* This object was reached, so unmark it (for the next GC) and move on to
the next. */
(*object)->marked = 0;
object = &(*object)->next;
}
</code>
}
}
```
Perhaps surprisingly, this function can be expressed line for line in Zig, just with a fresh new syntax.
```zig
fn sweep(self: <em>VM) void {
var object = &(self.first_object);
while (object.</em>) |obj| {
if (!obj.marked) {
// This object wasn't reached, so remove it from the list and free it.
var unreached = obj;
<code> object.* = obj.next;
self.allocator.destroy(unreached);
self.num_objects -= 1;
} else {
// This object was reached, so unmark it (for the next GC) and move on to
// the next.
obj.marked = false;
object = &(obj.next);
}
}
</code>
}
```
Testing
All of the tests were ported over to <a>test declarations</a>. These can be invoked via <code>zig test mark-sweep.zig</code>:
```zig
test "test 1" {
const allocator = std.testing.allocator;
print("Test 1: Objects on stack are preserved.\n", .{});
<code>var _vm = try VM.init(allocator);
var vm = &_vm;
try vm.pushInt(1);
try vm.pushInt(2);
vm.gc();
try std.testing.expect(vm.num_objects == 2);
vm.deinit();
</code>
}
```
Another important point! In Zig one does not call <code>malloc</code> to allocate memory. Instead one of many allocators is used to allocate memory in the way that is most appropriate for the situation at hand. Our code is organized like a typical library where any allocator may be passed in and retained for memory allocations over the life of a VM instance.
For testing we use <code>testing.allocator</code> which fails the test case if any memory is leaked. This enhances our test as <code>vm.deinit()</code> removes all of the <a>root objects</a> and performs a collection. If our code is working properly all allocated memory will be freed.
Debugging with gdb
Having debugged C extensively <code>gdb</code> I was shocked that it <em>Just Works</em> for debugging Zig code:
```shell
justin@ubuntu:~/Documents/zig-mark-sweep-gc$ make
zig build-exe mark-sweep.zig
justin@ubuntu:~/Documents/zig-mark-sweep-gc$ ./mark-sweep
Performance Test.
Collected 20000 objects, 0 remaining.
justin@ubuntu:~/Documents/zig-mark-sweep-gc$ gdb mark-sweep
GNU gdb (Ubuntu 9.1-0ubuntu1) 9.1
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <a>http://gnu.org/licenses/gpl.html</a>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<a>http://www.gnu.org/software/gdb/bugs/</a>.
Find the GDB manual and other documentation resources online at:
<a>http://www.gnu.org/software/gdb/documentation/</a>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from mark-sweep...
(gdb) break VM.sweep
Breakpoint 1 at 0x23091c: file /home/justin/Documents/zig-mark-sweep-gc/mark-sweep.zig, line 91.
(gdb) run
Starting program: /home/justin/Documents/zig-mark-sweep-gc/mark-sweep
Performance Test.
Breakpoint 1, VM.sweep (self=0x7fffffffd938) at /home/justin/Documents/zig-mark-sweep-gc/mark-sweep.zig:91
91 var object = &(self.first_object);
(gdb) n
92 while (object.*) |obj| {
(gdb)
```
Conclusion
That's it for now. All in all this was a great first experience with Zig and I look forward to writing more Zig in the near future.
Useful links:
<ul>
<li><a>Zig Language Reference</a></li>
<li><a>How to read the standard library source code</a></li>
<li><a>Zig Standard Library Documentation</a></li>
<li><a>Zig Tutorial</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/37453713?v=4 | zigfuck | ominitay/zigfuck | 2022-10-02T19:59:23Z | A brainfuck compiler written in Zig! | main | 0 | 4 | 1 | 4 | https://api.github.com/repos/ominitay/zigfuck/tags | EUPL-1.2 | [
"brainfuck",
"compiler",
"hacktoberfest",
"zig",
"ziglang"
]
| 43 | false | 2023-02-16T07:38:12Z | true | false | unknown | github | []
| Zigfuck
Zigfuck is a compiler for the famous esolang "brainfuck", written in Zig.
Backends
Currently, there is only a native backend which outputs executables targetting Linux x64.
Targets
The only supported target is Linux x64.
Roadmap
Zigfuck is intended to implement more sophisticated optimisations, and more backends, for broader target support (and further optimisation).
License
Copyright © ominitay 2022
Licensed under the EUPL, Version 1.2 or later.
You may not use this work except in compliance with the Licence.
You may obtain a copy of the Licence at: <a>https://joinup.ec.europa.eu/software/page/eupl</a> | []
|
https://avatars.githubusercontent.com/u/12962448?v=4 | migrator | star-tek-mb/migrator | 2023-01-25T17:56:41Z | migrator - database migration tool written in zig | master | 0 | 4 | 0 | 4 | https://api.github.com/repos/star-tek-mb/migrator/tags | - | [
"database",
"migration",
"sql",
"zig"
]
| 15 | false | 2024-11-26T15:13:33Z | true | true | unknown | github | [
{
"commit": "897a93129ecf56ef1521a5908ee4602636b18cea.tar.gz",
"name": "sqlite3",
"tar_url": "https://github.com/star-tek-mb/sqlite3-zig/archive/897a93129ecf56ef1521a5908ee4602636b18cea.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/star-tek-mb/sqlite3-zig"
},
{
"commit": "231714be7f220a9eb67cdde25b141fbcd37721dc.tar.gz",
"name": "pgz",
"tar_url": "https://github.com/star-tek-mb/pgz/archive/231714be7f220a9eb67cdde25b141fbcd37721dc.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/star-tek-mb/pgz"
}
]
| Overview
migrator - database migration tool written in zig
Features
Currently supported database drivers:
<ul>
<li>sqlite3</li>
<li>postgres</li>
</ul>
Build
<code>zig build</code>
Usage
Create migration file
<code>bash
migrator create</code>
Write some SQL into created file
<code>sql
CREATE TABLE users(name text not null);</code>
Then migrate
<code>bash
migrator migrate sqlite://hello.db</code> | []
|
https://avatars.githubusercontent.com/u/1291012?v=4 | video-player | charles-l/video-player | 2022-12-20T02:31:42Z | an ffmpeg-based video player written in zig | master | 1 | 4 | 0 | 4 | https://api.github.com/repos/charles-l/video-player/tags | MIT | [
"ffmpeg",
"raylib",
"video-player",
"zig"
]
| 20 | false | 2024-08-21T14:28:08Z | true | false | unknown | github | []
| video-player
an ffmpeg-based video player written in zig | []
|
https://avatars.githubusercontent.com/u/2828351?v=4 | microbe | bcrist/microbe | 2022-11-06T01:23:04Z | Embedded Zig framework for ARM microcontrollers | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/bcrist/microbe/tags | NOASSERTION | [
"cortex-m",
"embedded",
"rpi-pico",
"stm32",
"zig",
"zig-library",
"zig-package",
"ziglang"
]
| 733 | false | 2025-03-15T01:35:32Z | true | true | 0.14.0-dev.1694+3b465ebec | github | []
| Microbe
Microbe is a framework for developing embedded firmware in Zig, primarily targeting small 32-bit architectures like ARM Cortex-M0. It is similar in many ways to <a>microzig</a> and in fact some parts were forked directly from that project. But there are a few things about microzig that I didn't like:
<ul>
<li>Microzig caters heavily to the use of development boards, which is great for beginners, but just adds a lot of unnecessary complexity if you're using a microcontroller directly on your project/product board.</li>
<li>It forces a complex project structure on you. You can't define the root source file yourself, instead it only exists in an "app" module. There's a HAL (hardware abstraction layer) module that doesn't make sense; the entire project is a hardware abstraction layer, so why is there a HAL within the HAL?</li>
<li>The use of anonymous types to represent pins is weird. It seems the only reason is to ensure they're used at comptime, but you can do that just as easily with an enum passed as a <code>comptime</code> parameter. The conflation of chip pins names and board pin names is annoying.</li>
<li>The UART interface doesn't provide a non-blocking interface, or an easy way to support buffered implementations using interrupts or DMA.</li>
<li>There's no facility to easily work with multiple GPIOs simultaneously as a parallel bus.</li>
<li>The SVD-generated register types can be difficult to use, especially where a field would ideally be represented by an enum.</li>
</ul>
I don't bring these up to criticize the microzig project, but rather to highlight the areas where Microbe takes a different path. If you haven't tried microzig yet but you're looking to do embedded programming with Zig, start there first. If you have tried microzig but share some of the feelings I listed above, then this project may be useful to you. And if you're a microzig contributor and think something you see here should be ported, let me know and I'll see if I can help.
Building
Add this package to your <code>build.zig.zon</code> file and import it in your <code>build.zig</code> script as <code>microbe</code>. Then just call <code>microbe.addExecutable(...)</code> instead of <code>std.Build.addExecutable(...)</code>, providing the chip and section information for your desired target.
You can find example applications and <code>build.zig</code> scripts here:
* <a>STM32</a>
* <a>RP2040</a>
Conventions
There are a few API conventions that should be followed in order for chip-specific code to interact well with application code and the common code in this repo, as well as to make porting between architectures as easy as possible.
Most of the symbols that chip implementations are expected to expose can be found in <code>src/chip_interface.zig</code>.
Interrupt Configuration
Chip implementations should provide an enum <code>chip.interrupts.Interrupt</code> which lists all the "external" (i.e. NVIC-controlled) interrupts supported by the chip. The integer values associated with this enum indicate their offset in the NVIC registers. Additionally <code>chip.interrupts.Exception</code> should be an enum which includes all the interrupts, but also may contain synchronous exceptions & fault conditions. The integer values associated with this enum indicate the exception number. An interrupts exception number is generally different from its interrupt number.
Chip implementations should look for an <code>interrupts</code> struct in the root source file and automatically populate the vector table with the addresses of the handlers provided within it. The handler names must match the names from <code>chip.interrupts.Exception</code> exactly.
Clock & Power Configuration
Chip implementations should provide a struct <code>chip.clocks.Config</code> which allows configuration of all the major clock domains on the chip. The exact format will depend on the details of the architecture, but for every major clock domain in the chip, the clock config should have a field:
<code>xxx_frequency_hz: comptime_int
</code>
Where <code>xxx</code> is the name of the clock domain. A frequency of 0 Hz should be considered to mean "clock disabled". If a clock domain is sourced from another clock, it should additionally have a field:
<code>xxx_source: E
</code>
Where <code>E</code> is an enum type, or optional-wrapped enum type, giving the options that can be used as a source.
On reset, chip implementations should initialize the chip's clocks based on a <code>clocks</code> constant (of type <code>chip.clocks.Config</code>) declared in the root source file. If no such declaration exists, the chip's default clock configuration should be used.
Chip implementations should also provide <code>chip.clocks.apply_config(...)</code> to allow dynamic clock changes. Peripherals that are sensitive to clock frequencies (UARTs, PWMs etc.) will generally assume the clocks they use do not change, so care must be taken when using this.
Chip implementations may also provide <code>chip.clocks.get_config()</code> to provide a version of the configuration with additional details and defaults filled in. This should be comptime callable. If it does not return a <code>chip.clocks.Config</code> struct, it should return a <code>chip.clocks.Parsed_Config</code> struct.
The clock config struct may also contain fields for configuring low-power modes or other power-related features.
UARTs
Chip implementations may provide one or more UART implementations that allow <code>std.io</code> streams to be used. If there is only one implementation, <code>chip.uart.UART</code> should be a function that takes a comptime configuration struct and returns an implementation struct. If multiple implementations are provided via separate constructor functions.
The recommended names and types for some common configuration options are:
<ul>
<li><code>baud_rate_hz: comptime_int</code></li>
<li><code>data_bits: enum</code><ul>
<li>Generally <code>.seven</code> or <code>.eight</code>, sometimes maybe other values</li>
<li>Should not include parity bit</li>
</ul>
</li>
<li><code>parity: enum</code><ul>
<li><code>.even</code>, <code>.odd</code>, or <code>.none</code></li>
</ul>
</li>
<li><code>stop_bits: enum</code><ul>
<li>Usually <code>.one</code> or <code>.two</code>, sometimes <code>.one_and_half</code> or <code>.half</code></li>
</ul>
</li>
<li><code>which: ?enum</code><ul>
<li>If the chip has multiple UART peripherals, allows selection of which one to use</li>
<li>If set to null, select automatically based on rx/tx pins specified</li>
</ul>
</li>
<li><code>rx: ?Pad_ID</code><ul>
<li>The input pin to use for receiving, or null to disable receiving</li>
</ul>
</li>
<li><code>tx: ?Pad_ID</code><ul>
<li>The output pin to use for transmitting, or null to disable transmitting</li>
</ul>
</li>
<li><code>cts: ?Pad_ID</code><ul>
<li>The input pin to use for RTS/CTS bidirectional flow control</li>
</ul>
</li>
<li><code>rts: ?Pad_ID</code><ul>
<li>The output pin to use for RTS/CTS bidirectional flow control</li>
</ul>
</li>
<li><code>tx_buffer_size: comptime_int</code><ul>
<li>The size of the internal software transmit FIFO buffer</li>
<li>Set to 0 to disable interrupt/DMA driven I/O</li>
</ul>
</li>
<li><code>rx_buffer_size: comptime_int</code><ul>
<li>The size of the internal software receive FIFO buffer</li>
<li>Set to 0 to disable interrupt/DMA driven I/O</li>
</ul>
</li>
<li><code>tx_dma_channel: ?enum</code><ul>
<li>If multiple DMA channels are available, select one to use for transmission</li>
<li>Set to null to not use DMA for transmitted data</li>
</ul>
</li>
<li><code>rx_dma_channel: ?enum</code><ul>
<li>If multiple DMA channels are available, select one to use for reception</li>
<li>Set to null to not use DMA for received data</li>
</ul>
</li>
</ul>
All UART implementations should expose at least these declarations:
<code>const Data_Type // usually u8
fn init() Self
fn start(*Self) void
fn stop(*Self) void
</code>
Implementations that have reception capability should provide:
<code>fn is_rx_idle(*Self) bool // optional; some hardware may not be capable of reporting this
fn get_rx_available_count(*Self) usize
fn can_read(*Self) bool
fn peek(*Self, []Data_Type) Read_Error![]const Data_Type
fn peek_one(*Self) Read_Error!?Data_Type
const Read_Error
const Reader // usually std.io.Reader(..., Read_Error, ...)
fn reader(*Self) Reader
const Read_Error_Nonblocking
const Reader_Nonblocking
fn reader_nonblocking(*Self) Reader_Nonblocking
</code>
<code>Read_Error</code> usually consists of some subset of:
<ul>
<li><code>error.Overrun</code><ul>
<li>Indicates some received data was lost because older data was not read fast enough</li>
<li>Attempting to read again should return at least one word before another Overrun can occur</li>
</ul>
</li>
<li><code>error.Parity_Error</code><ul>
<li>Indicates potential data corruption due to parity mismatch</li>
<li>The character received should still be provided if another read is performed</li>
</ul>
</li>
<li><code>error.Framing_Error</code><ul>
<li>Indicates an incorrect line state during the stop bit, which may indicate data corruption, configuration mismatch, or severe clock drift</li>
<li>The character received should still be provided if another read is performed</li>
</ul>
</li>
<li><code>error.Break_Interrupt</code><ul>
<li>Indicates an entire frame of 0 bits was received, including stop bits</li>
<li>May be used as a data separator in some protocols, or may indicate a broken cable or other physical issue</li>
<li>Note some implementations may not be capable of differentiating a break character from a framing error</li>
</ul>
</li>
<li><code>error.Noise_Error</code><ul>
<li>Indicates that a signal transition was detected too close to the "center" of a bit period</li>
<li>May indicate borderline baud rate mismatch or significant noise on the line</li>
<li>The received noisy character should still be readable after this error is seen</li>
</ul>
</li>
</ul>
Implementations that have transmission capability should provide:
<code>fn is_tx_idle(*Self) bool // optional; some hardware may not be capable of reporting this
fn get_tx_available_count(*Self) usize
fn can_write(*Self) bool
const Write_Error
const Writer // usually std.io.Writer(..., Write_Error, ...)
fn writer(*Self) Writer
const Write_Error_Nonblocking
const Writer_Nonblocking
fn writer_nonblocking(*Self) Writer_Nonblocking
</code>
The <code>Read_Error_Nonblocking</code> and <code>Write_Error_Nonblocking</code> should generally match include everything from the blocking variants, as well as <code>error.Would_Block</code>, which is returned when the buffer is empty/full and no more data can be read or written. Ideally, when reading or writing multiple words, either the entire operation succeeds, or it has no effect if <code>Would_Block</code> is returned, except for functions that give feedback on how much work they accomplished (e.g. <code>Writer.write</code>). This precludes the use of <code>std.io.Reader</code>/<code>Writer</code> for the non-blocking variants.
Some implementations may require additional functions, e.g. to handle interrupts. | [
"https://github.com/bcrist/Amosis"
]
|
https://avatars.githubusercontent.com/u/1266011?v=4 | zigrl | danprince/zigrl | 2022-12-15T22:16:55Z | 🧌 A Zig + WebAssembly roguelike. | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/danprince/zigrl/tags | - | [
"roguelike",
"roguelike-tutorial",
"wasm",
"zig"
]
| 204 | false | 2024-12-03T15:01:58Z | true | false | unknown | github | []
| ZigRL
A Zig + WebAssembly implementation of the game from <a>rogueliketutorials.com</a>. | []
|
https://avatars.githubusercontent.com/u/65067357?v=4 | pacman.tracy.zig | abhirag/pacman.tracy.zig | 2022-03-27T10:52:58Z | Demonstrating client setup and client markup for Tracy in Zig by profiling floooh's pacman.zig | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/abhirag/pacman.tracy.zig/tags | MIT | [
"observability",
"profiling",
"tracy",
"zig"
]
| 5,173 | false | 2024-10-25T07:01:32Z | true | false | unknown | github | []
| pacman.tracy.zig
Demonstrating client setup and client markup for <a>Tracy Profiler</a> in Zig by profiling <a>floooh's pacman.zig</a>. Find more details <a>here</a>.
Build
<code>$ zig build -Dtracy=./tracy -Dtracy-allocation -Dtracy-callstack</code>
Disable Tracy
Building without the options specified above will disable Tracy | []
|
https://avatars.githubusercontent.com/u/1638331?v=4 | beschi | sjml/beschi | 2022-02-22T07:47:33Z | bit-packing and unpacking code generator for C, C#, Go, Rust, Swift, TypeScript, AssemblyScript, and Zig | main | 0 | 4 | 2 | 4 | https://api.github.com/repos/sjml/beschi/tags | MIT | [
"assemblyscript",
"binary",
"c",
"code-generation",
"csharp",
"deserialization",
"go",
"golang",
"messages",
"rust",
"serialization",
"swift",
"typescript",
"zig"
]
| 666 | false | 2025-01-21T03:06:12Z | false | false | unknown | github | []
|
Beschi
<a></a> <a></a>
This is a custom bit-packing and unpacking code generator for C, C#, Go, Rust, Swift, TypeScript, AssemblyScript, and Zig. You feed it a data description and it generates source files for writing/reading buffers of that data, along the lines of <a>FlatBuffers</a> or <a>Cap'n Proto</a>, but with much less functionality for much simpler use cases. It was initially written for a larger project that was passing data back and forth between a Unity game, a Go server, and a web client, but I extracted it into its own thing. If all you need is a simple way to pack a data structure into a compact, portable binary form, this might be useful for you.
I go into more explanation for why this exists <a>in the documentation</a>, but I'll be honest, too: it <strong>was</strong> kind of fun to write a code generator. 😝
Documentation
<ul>
<li><a>Introduction</a></li>
<li><a>Protocols</a></li>
</ul>
Language-Specific Documentation:
| <a>C</a> | <a>C#</a> | <a>Go</a> | <a>Rust</a> | <a>Swift</a> | <a>TypeScript</a> | <a>AssemblyScript</a> | <a>Zig</a>
|-|-|-|-|-|-|-|-|
<ul>
<li><a>Dev Notes</a></li>
</ul>
Installation
If you use <a>Homebrew</a>, you can install it directly and simply:
<code>brew install sjml/sjml/beschi</code>
Otherwise, you need a Python setup and can then install from <a>PyPI</a>:
<code>pip install beschi</code>
It installs an executable that you can run directly, so long as however you invoked <code>pip</code> put it on your path. (This will work in an activated virtual environment, for instance.)
Example:
<code>beschi --lang csharp --protocol ./messages.toml</code>
Basic Usage
By default, it prints to standard output, but you can also write to a file with an output flag like <code>--output ./Messages.cs</code>.
From the input protocol file (detailed below), you get a code file that you can integrate to a project allowing you encode messages as compact and portable binary buffers.
Protocols
The protocol files are written in <a>TOML</a>. There's <a>a fuller example in the test suite</a> and a <a>more through explanation in the documentation</a>, but here's an annotated sample.
```toml
[meta]
The namespace is optional; not all languages
do something useful with it, but it's handy
to have to help avoid clashes
namespace = "AppMessages"
The size types specify what kind of number to
use when recording the length of lists and
strings. If not specified, they both default
to uint32 (four bytes).
list_size_type = "uint16"
string_size_type = "byte"
Messages are defined by a name and their data
members. This will become a class or struct in
the target languages with these pieces of data
as accessible members.
[[messages]]
_name = "Vector3Message"
x = "float"
y = "float"
z = "float"
There are a variety of different data member
types that can be defined.
[[messages]]
_name = "NewCharacterMessage"
id = "uint64"
characterName = "string"
job = "CharacterClass" # an enum! (see below)
strength = "uint16"
intelligence = "uint16"
dexterity = "uint16"
wisdom = "uint16"
goldInWallet = "uint32"
nicknames = "[string]" # brackets indicate a list/array
You can also define enumerated values which will be
translated into the target language's enum / integer
types as appropriate.
[[enums]]
_name = "CharacterClass"
_values = [
"Fighter",
"Wizard",
"Rogue",
"Cleric"
]
There are also structs, collections of data that go
together, but are not themselves a message.
[[structs]]
_name = "Color"
red = "float"
green = "float"
blue = "float"
alpha = "float"
Structs can contain other structs, and even lists of them.
[[structs]]
_name = "Spectrum"
defaultColor = "Color"
colors = "[Color]"
Structs and enums can then be used in messages
(which can also have lists of structs, of course).
[[messages]]
_name = "CharacterJoinedTeam"
characterID = "uint64"
teamName = "string"
teamColors = "[Color]"
role = "TeamRole"
Enums can also be non-sequential if you need
[[enums]]
_name = "TeamRole"
_values = [
# in a non-sequential enum, the first
# listed value will be used as the default
{ _name = "Minion", _value = 256 },
{ _name = "Ally", _value = 512 },
{ _name = "Leader", _value = 1024 },
# values can even be negative
{ _name = "Traitor", _value = -1 }
]
```
Note that while <a>the TOML spec</a> does not guarantee the order of table entries, <a>the Python library which Beschi uses</a> uses order-preserving dictionaries, so if you care about the order of elements in the resulting struct (for memory alignment issues or something), you can re-order them and have that change reflected in the generated code.
Data Members
These are the base types from which you can build up whatever structures and messages you need to, along with what they correspond to in the various languages.
| Protocol Type | C | C# | Go | Rust | Swift | TypeScript | AssemblyScript | Zig |
|---------------|------------|----------|-----------|----------|-----------|------------|----------------|---------------|
| <strong><code>byte</code></strong> | <code>uint8_t</code> | <code>byte</code> | <code>byte</code> | <code>u8</code> | <code>UInt8</code> | <code>number</code> | <code>u8</code> | <code>u8</code> |
| <strong><code>bool</code></strong> | <code>bool</code> | <code>bool</code> | <code>bool</code> | <code>bool</code> | <code>Bool</code> | <code>boolean</code> | <code>bool</code> | <code>bool</code> |
| <strong><code>int16</code></strong> | <code>uint16_t</code> | <code>short</code> | <code>int16</code> | <code>i16</code> | <code>Int16</code> | <code>number</code> | <code>i16</code> | <code>i16</code> |
| <strong><code>uint16</code></strong> | <code>int16_t</code> | <code>ushort</code> | <code>uint16</code> | <code>u16</code> | <code>UInt16</code> | <code>number</code> | <code>u16</code> | <code>u16</code> |
| <strong><code>int32</code></strong> | <code>uint32_t</code> | <code>int</code> | <code>int32</code> | <code>i32</code> | <code>Int32</code> | <code>number</code> | <code>i32</code> | <code>i32</code> |
| <strong><code>uint32</code></strong> | <code>int32_t</code> | <code>uint</code> | <code>uint32</code> | <code>u32</code> | <code>UInt32</code> | <code>number</code> | <code>u32</code> | <code>u32</code> |
| <strong><code>int64</code></strong> | <code>uint64_t</code> | <code>long</code> | <code>int64</code> | <code>i64</code> | <code>Int64</code> | <code>bigint</code> | <code>i64</code> | <code>i64</code> |
| <strong><code>uint64</code></strong> | <code>int64_t</code> | <code>ulong</code> | <code>uint64</code> | <code>u64</code> | <code>UInt64</code> | <code>bigint</code> | <code>u64</code> | <code>u64</code> |
| <strong><code>float</code></strong> | <code>float</code> | <code>float</code> | <code>float32</code> | <code>f32</code> | <code>Float32</code> | <code>number</code> | <code>f32</code> | <code>f32</code> |
| <strong><code>double</code></strong> | <code>double</code> | <code>double</code> | <code>float64</code> | <code>f64</code> | <code>Float64</code> | <code>number</code> | <code>f64</code> | <code>f64</code> |
| <strong><code>string</code></strong> | <code>char*</code> | <code>string</code> | <code>string</code> | <code>String</code> | <code>String</code> | <code>string</code> | <code>string</code> | <code>[]const u8</code> |
All the numbers are stored as little-endian in the buffer, if that matters for you.
Usage in code
Beschi does not generate any code to handle writing or reading from disk, pushing data across a network, or anything like that — it will turn a message into bytes and read that same message back from the bytes, but you are responsible for what you do with them otherwise.
With the given protocol, though, you could create a message in C# and write it to a file:
<code>csharp
var msg = new AppMessages.Vector3Message();
msg.x = 1.0f;
msg.y = 4096.1234f;
msg.z = -42.56f;
var fs = new FileStream("./vec3.msg", FileMode.Create);
var bw = new BinaryWriter(fs);
msg.WriteBytes(bw, false);</code>
And then read it back in Go:
<code>golang
dat, _ := os.Open("./vec3.msg")
defer dat.Close()
msg := AppMessages.Vector3MessageFromBytes(dat)
if msg.X == 1.0 && msg.Y == 4096.1234 && msg.Z < 0.0 {
print("Ready to go!\n")
}</code>
Or TypeScript:
<code>typescript
const data = fs.readFileSync("./vec3.msg");
const dv = new DataView(new Uint8Array(data).buffer);
const msg = AppMessages.Vector3Message.fromBytes(dv, 0).val;
if (msg.y == Math.fround(4096.1234)) {
console.log("Ready to... typescript?");
}</code>
For the most part, Beschi tries to keep behavior and structures consistent across the languages, but there are a few points of difference <a>outlined on the various language pages</a>. Notice in the example above, for instance, that in TypeScript you have to make a call to <code>Math.fround</code> if you want to do a straight comparison of float values because of how the underlying JavaScript engine treats all numbers as double-width floats. (Doing equality comparisons on floats is usually a bad idea, but in this instance we <em>want</em> to check that they are actually bitwise identical.) Similarly, see how the data members are upper-cased in Go to match that language's export conventions, and the byte reading function is part of the namespace because Go doesn't have static functions for data types. The goal is to make working across languages feel seamless, but there are some differences that we adapt to as much as possible.
There are more extensive examples in <a>the test harnesses</a>.
Future
Beschi makes code that I use "in production" on personal projects. It could probably stand to be better optimized, there are probably edge cases and bugs, etc. But for the most part, this is mature enough that I stopped thinking of it as a project in itself and now it's just a tool that I use.
I will admit that part of me wants to make new writers, but that's not likely to get done until I have a specific project motivating it. If someone loves this system, though, and really wants to see a generator for Haskell or Lua or whatever, go for it. The existing writers should be decent starting points — they aren't terribly clever (no AST or interesting data structures), just iterating over the protocol and writing out serialization/deserialization code.
Beschi?
<a>Constanzo Giuseppe Beschi</a> was an Italian Jesuit who worked in southern India during the early 18th century. He was noted as a talented linguist, able to tie concepts from multiple languages into a single form. At the same time, he was adept at the Jesuit principle of "inculturation," where foreign concepts are adapted for a new culture and the foreigner attempting the adaptation also respectfully adopts habits and ways of proceeding from the host culture. | []
|
https://avatars.githubusercontent.com/u/1531031?v=4 | crafting-interpreters-deno-zig | jpaquim/crafting-interpreters-deno-zig | 2022-05-25T13:12:43Z | Crafting Interpreters in Deno and Zig | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/jpaquim/crafting-interpreters-deno-zig/tags | MIT | [
"crafting-interpreters",
"deno",
"lox",
"typescript",
"zig"
]
| 257 | false | 2024-09-25T10:34:06Z | false | false | unknown | github | []
| crafting-interpreters-deno-zig
<a>Crafting Interpreters</a> in Deno and Zig.
Original Java and C code: https://github.com/munificent/craftinginterpreters
License
The code is available under the <a>MIT license</a> | []
|
https://avatars.githubusercontent.com/u/72643694?v=4 | squashfuse-zig | mgord9518/squashfuse-zig | 2022-12-20T06:59:13Z | Read and mount SquashFS archives | main | 0 | 4 | 0 | 4 | https://api.github.com/repos/mgord9518/squashfuse-zig/tags | MIT | [
"fuse",
"fuse-filesystem",
"squashfs",
"squashfs-image",
"zig"
]
| 807 | false | 2025-02-20T06:27:20Z | true | true | unknown | github | [
{
"commit": "0.9.1",
"name": "clap",
"tar_url": "https://github.com/Hejsil/zig-clap/archive/0.9.1.tar.gz",
"type": "remote",
"url": "https://github.com/Hejsil/zig-clap"
},
{
"commit": "067741f27b6ba46c3950eb0aeedac3f9ca2b3240",
"name": "fuse",
"tar_url": "https://github.com/mgord9518/libfuse-zig/archive/067741f27b6ba46c3950eb0aeedac3f9ca2b3240.tar.gz",
"type": "remote",
"url": "https://github.com/mgord9518/libfuse-zig"
},
{
"commit": "bdf473d2ecfcc13719ad2946dc1b29cbff847f79",
"name": "lz4",
"tar_url": "https://github.com/mgord9518/lz4-zig/archive/bdf473d2ecfcc13719ad2946dc1b29cbff847f79.tar.gz",
"type": "remote",
"url": "https://github.com/mgord9518/lz4-zig"
},
{
"commit": "v1.19",
"name": "libdeflate",
"tar_url": "https://github.com/ebiggers/libdeflate/archive/v1.19.tar.gz",
"type": "remote",
"url": "https://github.com/ebiggers/libdeflate"
},
{
"commit": "v1.5.7",
"name": "libzstd",
"tar_url": "https://github.com/facebook/zstd/archive/v1.5.7.tar.gz",
"type": "remote",
"url": "https://github.com/facebook/zstd"
},
{
"commit": "v1.10.0",
"name": "liblz4",
"tar_url": "https://github.com/lz4/lz4/archive/v1.10.0.tar.gz",
"type": "remote",
"url": "https://github.com/lz4/lz4"
},
{
"commit": "v5.6.4",
"name": "libxz",
"tar_url": "https://github.com/tukaani-project/xz/archive/v5.6.4.tar.gz",
"type": "remote",
"url": "https://github.com/tukaani-project/xz"
}
]
| squashfuse-zig
SquashFS implementation in Zig, modeled after squashfuse
Active/ complete goals:
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Library usage in line with Zig stdlib
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> (Partial) Dir implementation
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Move Inode methods into Dir and File structs
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> File struct
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Performance; choose the fastest decompression libraries by default
(being done for the CLI tool by default via libdeflate)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> (Partial) Compatibility with existing squashfuse tools
Future goals:
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Writing?
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Multithreading
Importing example:
<a>build.zig.zon</a>
```zig
.{
.name = "import_example",
.version = "0.0.0",
.minimum_zig_version = "0.13.0",
<code>.dependencies = .{
.squashfuse = .{
//.url = "https://github.com/mgord9518/squashfuse-zig/archive/refs/tags/continuous.tar.gz",
//.hash = "1220e675672f86be446965d5b779a384c81c7648e385428ed5a8858842cfa38a4e22",
.path = "../",
},
},
.paths = .{
"build.zig",
"build.zig.zon",
"src",
"README.md",
},
</code>
}
```
<a>build.zig</a>
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
<code>const squashfuse_dep = b.dependency("squashfuse", .{
.target = target,
.optimize = optimize,
.zlib_decompressor = .libz_dynamic,
.zstd_decompressor = .libzstd_static,
});
const exe = b.addExecutable(.{
.name = "squashfs_inspector",
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
});
// libc must be explicitly linked unless all compression libraries are
// using Zig implementations
exe.linkLibC();
exe.root_module.addImport(
"squashfuse",
squashfuse_dep.module("squashfuse"),
);
// If a C-ABI compression library is used and isn't linked at runtime,
// the libraries must be linked in the build script as well
exe.linkLibrary(squashfuse_dep.artifact("zstd"));
exe.linkSystemLibrary("z");
b.installArtifact(exe);
</code>
}
``` | []
|
https://avatars.githubusercontent.com/u/11012803?v=4 | zig-htn-demo | j-helland/zig-htn-demo | 2022-12-21T06:17:08Z | AI demo with searching and flanking written in Zig. Hierarchical Task Network (HTN) implementation of the AI. | master | 0 | 3 | 0 | 3 | https://api.github.com/repos/j-helland/zig-htn-demo/tags | - | [
"ecs",
"htn",
"sdl2",
"zig"
]
| 769 | false | 2024-12-31T09:25:13Z | true | true | unknown | github | []
| Hierarchical Task Network (HTN) AI Demo
This is a demo of a Hierarchical Task Network (HTN) AI implementation in Zig.
The only dependency is SDL2.
The AI has searching and flanking behavior.
My goals with this project were:
- To learn Zig.
- To learn about HTNs.
- To have as much fun as possible.
The project has a couple of features that I think are neat:
- <a>HTN implementation</a> that makes defining domains straightforward.
- A flexible <a>Entity Component System (ECS) implementation</a>.
- Easy cross-compilation thanks to Zig.
Video demos (clickable images)
Check out the core AI behaviors in the videos below (click on an image to open a youtube video).
Flanking behavior
<a></a>
When navigating to the player, the AI will try to flank the player.
This behavior is implemented using A* routing with a distance metric biased away from the player's line of sight.
The visibility bias is intuitively very simple: consider visible locations further away by a constant factor.
This approach works fairly well to avoid moving into player view when near the player while smoothly transitioning to normal movement far away from the player.
When the AI spots the player, it records a snapshot of the player's view, finds a nearby hiding place, and then routes to the player using A* with respect to the snapshot of the player's view.
Searching behavior
<a></a>
The AI will default to searching for the player when
1. The player hasn't been spotted yet.
2. The AI has lost track of the player.
More details on the second case: when the AI spots the player, it will hide and then navigate to the last known player location for an attack.
This can fail when the player has moved behind cover while out of the enemy's line of sight.
This is what is meant by losing track of the player.
Running the demo
<em>NOTE: this project has only been tested on macOS Monetery 12.4 with an M1 chip. While other platforms / architectures have not been tested, any changes to <a><code>build.zig</code></a> should be minimal.</em>
<strong>INSTALLATION</strong>
You need to install the following dependencies before building:
- <code>SDL2</code>
- <code>SDL2_Image</code>
On macOS, you can install these via <code>brew install sdl2 sdl2_image</code>.
Then,
- <code>git clone https://github.com/j-helland/zig-htn-demo.git</code>
- <code>cd zig-htn-demo</code>
- <code>zig build run</code>
This should launch the program automatically.
<strong>CONTROLS</strong>
<ul>
<li>Move using <code>WASD</code></li>
<li>Quit using <code>Esc</code></li>
<li>Right-click to spawn a wall at the mouse position.</li>
<li><code>Spacebar</code> to spawn an enemy at the mouse position.</li>
<li>Use the mouse to control the line-of-sight.</li>
</ul>
Project Organization
<ul>
<li><a><code>src/game.zig</code></a> contains the core game loop and <code>GameState</code> definition. Additionally:<ul>
<li>ECS systems are defined here e.g. <code>handlePlayer</code></li>
<li>The HTN planner is defined here as an ECS system <code>handleEnemyAI</code>.</li>
</ul>
</li>
<li><a><code>src/ai.zig</code></a> Defined the HTN domain, as well as the conditions, operators, and sensors needed by the HTN planner to run the AI.</li>
<li><a><code>src/htn/</code></a> Contains the HTN planner, domain builder, and world state definition. Currently, the world state is specialized to this demo, meaning that this HTN implementation requires a small amount of work to be used in other projects.</li>
<li><a><code>src/ecs/ecs.zig</code></a> Contains a generic ECS implementation. It is not currently optimized.</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/107726195?v=4 | zig-gp32 | zig-homebrew/zig-gp32 | 2022-06-18T21:05:10Z | Starter pack for developing GP32 games/applications with Zig | master | 0 | 3 | 0 | 3 | https://api.github.com/repos/zig-homebrew/zig-gp32/tags | - | [
"devkitpro",
"gp32",
"zig"
]
| 3 | false | 2024-05-19T18:01:47Z | true | false | unknown | github | []
| zig-gp32
Getting started
<ul>
<li><a>zig</a></li>
<li><a>devkitPro</a></li>
</ul>
<code>pacman -S gp32-dev
git clone https://github.com/zig-homebrew/zig-gp32
cd zig-gp32/
zig build # then run zig-out/zig-gp32.fxe with geepee32</code>
Resources
<ul>
<li><a>gp32-examples</a></li>
<li><a>libmirko</a></li>
<li><a>Game Park 32</a></li>
<li><a>GP32 WIP: Promotion</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/19897088?v=4 | levent | yusdacra/levent | 2023-01-09T01:37:56Z | A media tagger. | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/yusdacra/levent/tags | Unlicense | [
"imgui",
"zig"
]
| 198 | false | 2024-12-02T07:20:55Z | true | true | 0.14.0 | github | [
{
"commit": "4f8ee943b81da3e344244818e397993a8be0a74c",
"name": "zgui",
"tar_url": "https://github.com/zig-gamedev/zgui/archive/4f8ee943b81da3e344244818e397993a8be0a74c.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zgui"
},
{
"commit": "ce756faacf52c7531bc09bdc0201004596c0a01f",
"name": "zglfw",
"tar_url": "https://github.com/zig-gamedev/zglfw/archive/ce756faacf52c7531bc09bdc0201004596c0a01f.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zglfw"
},
{
"commit": "66aa9c55b19742f1a3878f0fcb5934ff6c2b9097",
"name": "zgpu",
"tar_url": "https://github.com/zig-gamedev/zgpu/archive/66aa9c55b19742f1a3878f0fcb5934ff6c2b9097.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zgpu"
},
{
"commit": "163b4ab18936a3d57b5d8375eba1284114402c80",
"name": "zpool",
"tar_url": "https://github.com/zig-gamedev/zpool/archive/163b4ab18936a3d57b5d8375eba1284114402c80.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zpool"
},
{
"commit": "ec86094475a10ba07b141b12b7020f7b88b0e77b",
"name": "zstbi",
"tar_url": "https://github.com/zig-gamedev/zstbi/archive/ec86094475a10ba07b141b12b7020f7b88b0e77b.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/zstbi"
},
{
"commit": "bf49d627a191e339f70e72668c8333717fb969b0",
"name": "system_sdk",
"tar_url": "https://github.com/zig-gamedev/system-sdk/archive/bf49d627a191e339f70e72668c8333717fb969b0.tar.gz",
"type": "remote",
"url": "https://github.com/zig-gamedev/system-sdk"
},
{
"commit": "ad81729d33da30d5f4fd23718debec48245121ca",
"name": "nfd",
"tar_url": "https://github.com/fabioarnold/nfd-zig/archive/ad81729d33da30d5f4fd23718debec48245121ca.tar.gz",
"type": "remote",
"url": "https://github.com/fabioarnold/nfd-zig"
},
{
"commit": "d3a68014e6b6b53fd330a0ccba99e4dcfffddae5.tar.gz",
"name": "dawn_x86_64_windows_gnu",
"tar_url": "https://github.com/michal-z/webgpu_dawn-x86_64-windows-gnu/archive/d3a68014e6b6b53fd330a0ccba99e4dcfffddae5.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/michal-z/webgpu_dawn-x86_64-windows-gnu"
},
{
"commit": "7d70db023bf254546024629cbec5ee6113e12a42.tar.gz",
"name": "dawn_x86_64_linux_gnu",
"tar_url": "https://github.com/michal-z/webgpu_dawn-x86_64-linux-gnu/archive/7d70db023bf254546024629cbec5ee6113e12a42.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/michal-z/webgpu_dawn-x86_64-linux-gnu"
},
{
"commit": "c1f55e740a62f6942ff046e709ecd509a005dbeb.tar.gz",
"name": "dawn_aarch64_linux_gnu",
"tar_url": "https://github.com/michal-z/webgpu_dawn-aarch64-linux-gnu/archive/c1f55e740a62f6942ff046e709ecd509a005dbeb.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/michal-z/webgpu_dawn-aarch64-linux-gnu"
},
{
"commit": "d2360cdfff0cf4a780cb77aa47c57aca03cc6dfe.tar.gz",
"name": "dawn_aarch64_macos",
"tar_url": "https://github.com/michal-z/webgpu_dawn-aarch64-macos/archive/d2360cdfff0cf4a780cb77aa47c57aca03cc6dfe.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/michal-z/webgpu_dawn-aarch64-macos"
},
{
"commit": "901716b10b31ce3e0d3fe479326b41e91d59c661.tar.gz",
"name": "dawn_x86_64_macos",
"tar_url": "https://github.com/michal-z/webgpu_dawn-x86_64-macos/archive/901716b10b31ce3e0d3fe479326b41e91d59c661.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/michal-z/webgpu_dawn-x86_64-macos"
},
{
"commit": "560c8dd72ab25d556123846254040c5bf9ad3ba4",
"name": "clap",
"tar_url": "https://github.com/Hejsil/zig-clap/archive/560c8dd72ab25d556123846254040c5bf9ad3ba4.tar.gz",
"type": "remote",
"url": "https://github.com/Hejsil/zig-clap"
}
]
| <code>levent</code> is a WIP media tagger.
whats working
<ul>
<li>importing images into levent (w/ thumbnail generation)</li>
<li>tagging images (very simple space separated tags)</li>
<li>filtering images</li>
</ul>
whats next
<ul>
<li>use sqlite or something</li>
<li>importing any file</li>
<li>support showing more metadata about files</li>
<li>add tabs for showing files (with separate filters)</li>
<li>add filtering by various metadata (width, height, etc.)</li>
</ul>
usage
obtain executables from <a>the latest nightly release</a>.
currently supports macos, linux and windows.
also see <code>levent -h</code> for CLI flags / commands.
development
<ul>
<li>obtain zig (current targeted version is <code>0.14.0-dev.2362+a47aa9dd9</code>).<ul>
<li>on linux, you also need <code>gtk-3.0</code>, <code>gdk-3.0</code> and <code>atk-1.0</code>.</li>
</ul>
</li>
<li>run <code>zig build run</code> to run a debug build.</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/64036709?v=4 | rym | CreatorSiSo/rym | 2022-07-19T23:40:17Z | Personal programming language project | v3 | 0 | 3 | 0 | 3 | https://api.github.com/repos/CreatorSiSo/rym/tags | MIT | [
"fsharp",
"go",
"golang",
"ocaml",
"proglang",
"programming-language",
"rust",
"swift",
"zig"
]
| 2,187 | false | 2025-01-31T16:00:39Z | false | false | unknown | github | []
| Rym
<strong>Rym Lang</strong> or just <strong>Rym</strong> is a modern, statically typed programming language inspired by Rust, Swift, Python and others that focuses on ease of use and safety.
Big thanks go to Robert Nystrom who made his book <a>crafting interpreters</a> open source which enabled me to read it and learn a lot :).
Content
<ul>
<li><a>Rym</a></li>
<li><a>Content</a></li>
<li><a>About Rym</a><ul>
<li><a>Name</a></li>
<li><a>Goals</a></li>
</ul>
</li>
<li><a>Examples</a></li>
<li><a>How to install</a></li>
<li><a>Inspirational projects</a></li>
<li><a>Similar projects</a></li>
<li><a>Project Structure</a><ul>
<li><a>Tests</a></li>
</ul>
</li>
<li><a>Todos</a></li>
</ul>
About Rym
Name
<ul>
<li><strong>R</strong>ust<strong>y</strong> ⇒ Heavily borrows 🙃 from Rust</li>
<li><strong>M</strong>ulti-paradigm ⇒ Mix of object oriented, procedural and functional programming</li>
<li>Programming <strong>Lang</strong>uage ⇒ because thats what it is</li>
</ul>
Goals
<ul>
<li><strong>MVP</strong></li>
<li>Safety<ul>
<li>No <code>null</code> <code>nil</code> <code>undefined</code></li>
<li>Optionals wrapped in <code>Option<T></code> enum</li>
<li>Errors wrapped in <code>Result<T></code></li>
<li>Statically typed</li>
</ul>
</li>
<li><strong>1.0</strong></li>
<li>Nice DX (Development Experience)<ul>
<li>Inferred types</li>
<li>Informative errors and warnings</li>
<li>Builtin tools</li>
</ul>
</li>
<li>Great interoperabilty with Rust<ul>
<li>Should just work out of the box</li>
</ul>
</li>
<li><strong>Past 1.0</strong></li>
<li>Ui and Apps programming</li>
</ul>
Examples
```rust
func main() -> Result<(), Error>, ?Io {
const msg = "Hello World"
print(msg)
<code>mut num = 2/4 * (10 - 1)
print("Number:", num)
const msg = msg + "!"
print("Combined:", msg, num)
</code>
}
```
In Rym you can unwrap <code>Tryable</code> values like <code>Option</code>s or <code>Result</code>s
```rust
const inner = maybe_value()!
// Same as
const inner = maybe_value().unwrap()
```
Early returns when unwrapping <code>Tryable</code>s
```rust
func main() -> Result {
const number = maybe_error()?
print(number)
<code>// Same as
const inner = match maybe_error() {
Ok(val) => val,
err => return err,
}
print(inner)
</code>
}
```
Tryable chaining
```rust
const chained = maybe_error()&.to_string()
// Short form of:
const chained = match maybe_error() {
Ok(val) => Ok(val.to_string()),
err => err,
}
// or:
const chained = maybe_error().and_then(|val| Ok(val.to_string()))
```
How to install
<strong>TODO</strong>
Inspirational projects
<ul>
<li><a>HVM</a>: A massively parallel, optimal functional runtime in Rust</li>
<li><a>Unison</a>: A friendly programming language from the future (statically-typed, functional)</li>
<li><a>Fused Effects</a>: A fast, flexible, fused effect system for Haskell</li>
<li><a>Rust</a>: Empowering everyone to build reliable and efficient software.</li>
<li><a>Swift</a>: A Swift is a high-performance system programming language.</li>
</ul>
Similar projects
<ul>
<li><a>Boson</a>: Hybrid programming language written in Rust.</li>
<li><a>Mun</a>: Programming language empowering creation through iteration.</li>
<li><a>Tao</a>: Statically-typed functional language with polymorphism, typeclasses, algebraic effects, sum types, pattern-matching, first-class functions, currying, good diagnostics, and much more!</li>
<li><a>Rhai</a>: Embedded scripting language for Rust.</li>
<li><a>Rune</a>: Embeddable dynamic programming language for Rust.</li>
</ul>
Project Structure
The project is split into many crates that are part of one Cargo workspace:
<code>crates/rym_span</code> ⇒ Span
<code>crates/rym_tt</code> ⇒ TokenTree, TokenStream
<code>crates/rym_lexer</code> ⇒ Isolated initial lexer
<code>crates/ast</code> ⇒ Ast Types: Spanned, AstVisitor, Token, ...
<code>crates/lex</code> ⇒ produce Tokens from source
<code>crates/parse</code> ⇒ produce ast from tokens
<code>crates/code_gen</code> ⇒ generate optimized code (dead code analysis, ...) or give warnings
<code>crates/tree_walk</code> ⇒ evaluate ast
<code>crates/tests</code> ⇒ integration tests
<code>crates/rymx</code> ⇒ command line tool for executing <code>.rym</code> files
And some other scripts located in the root directory:
<code>bench.sh</code> ⇒ builds and runs various benchmarks
<code>test.py</code> ⇒ updates and runs all tests
Tests
Run <code>python test.py</code> to update and execute all tests.
This internally runs <code>cargo r --bin gen -- ./crates/tests/src/integration</code> which includes the source code for all tests into <code>crates/tests/src/integration/mod.rs</code>.
Todos
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> use insta snapshot testing crate
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> add benchmarking capabilities
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> use arena allocator for scopes?
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> benchmark before & after
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> use logos lexer generator?
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> errors
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> use <code>Spanned<T></code> where possible
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> implement error recovery to jump to next safe expr/stmt
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> use error codes that link to a more detailed explanation (https://github.com/rust-lang/rust/tree/master/compiler/rustc_error_codes)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <code>true && (break)</code> currently only returns <code>Error: Expected Literal got RightParen, Span: 14..14</code>, it should also say something along the lines of: <code>Tip: insert expression or semicolon after break</code>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> data types
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <code>number</code>s, <code>string</code>, <code>char</code>, <code>bool</code>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> (literal) values that come from source code directly:
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <code>Literal<u8></code>, <code>Literal<f32></code>, <code>Literal<string></code>, <code>Literal<char></code>, <code>Literal<bool></code>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <code>1</code>, <code>2.2</code>, <code>"Hello World!"</code>, <code>'\n'</code>, <code>false</code>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> type unions: <code>0 | 1 | bool</code>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> type functions <a>docs/functions.md</a>? | []
|
https://avatars.githubusercontent.com/u/40190339?v=4 | tinylisp | daneelsan/tinylisp | 2023-01-10T15:35:42Z | A web-based Lisp interpreter with a "terminal" interface | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/daneelsan/tinylisp/tags | MIT | [
"html",
"javascript",
"lisp",
"wasm",
"zig"
]
| 813 | false | 2025-03-21T14:54:03Z | true | true | 0.14.0 | github | []
| tinylisp
Play with tinylisp at: https://daneelsan.github.io/tinylisp/
tinylisp is a minimal Lisp interpreter implemented in Zig, using NaN boxing for efficient memory representation. It supports core Lisp features like atoms, lists, conditionals, arithmetic, and closures, along with an interactive REPL and debugging tools for inspecting the heap, stack, and environment.
Read my thoughts at https://daneelsan.github.io/2025/03/20/tinylisp.html
Documentation
Atoms
<code>#t</code> (True):
```lisp
λ #t
t
```
<code>ERR</code> (Error):
<code>lisp
λ (cdr 42)
ERR</code>
Arithmetic
<code>+</code> (Addition):
<code>lisp
λ (+ 1 2 3 4)
10</code>
<code>-</code> (Subtraction):
<code>lisp
λ (- 10 2 3)
5</code>
<code>*</code> (Multiplication):
<code>lisp
λ (* 2 3 4)
24</code>
<code>/</code> (Division):
<code>lisp
λ (/ 3.4 4)
0.85</code>
Structural
<code>car</code>:
<code>lisp
λ (car '(1 2 3))
1</code>
<code>cdr</code>:
<code>lisp
λ (cdr '(1 2 3))
(2 3)</code>
<code>cons</code>:
<code>lisp
λ (cons 1 2)
(1 . 2)</code>
<code>lisp
λ (cons 1 '(2 3))
(1 2 3)</code>
Quoting and Evaluation
<code>'</code> (Quoting):
<code>lisp
λ '(+ 1 2 3)
(+ 1 2 3)</code>
<code>eval</code> (Evaluation):
<code>lisp
λ (eval '(+ 1 2 3))
6</code>
Conditionals and Logic
<code>if</code>:
<code>lisp
λ (if (< 1 2) 'true 'false)
true</code>
<code>and</code>:
```lisp
λ (and (< 1 2) (< 2 3))
t
<code></code>lisp
λ (and (< 2 1) (< 2 3))
()
```
<code>or</code>:
```lisp
λ (or (< 1 2) (< 3 2))
t
```
<code>not</code>:
<code>lisp
λ (not (< 1 2))
()</code>
<code>=</code> (Equality):
```lisp
λ (= 1.0 1)
t
<code></code>lisp
λ (= 1.1 1)
()
```
Lambdas and Closures
<code>lambda</code>:
<code>lisp
λ ((lambda (x) (* x x)) 5)
25</code>
<code>define</code>:
<code>lisp
λ (define square (lambda (x) (* x x)))
square</code>
<code>lisp
λ (square 5)
25</code>
<code>lisp
λ (define x 42)
x</code>
<code>lisp
λ (+ x x)
84</code>
Debugging and Introspection
<code>echo</code>:
<code>lisp
λ (+ (echo (* 3 4) 5))
>> 12
12</code>
<code>echo-eval</code>:
<code>lisp
λ (echo-eval (+ (* 3 4) 5))
>> ((+ (* 3 4) 5))
<< 17
17</code>
<code>print-env</code>:
<code>lisp
λ (print-env)
(
(echo-eval . «echo-eval»)
(echo . «echo»)
(print-env . «print-env»)
(print-stack . «print-stack»)
(print-heap . «print-heap»)
(define . «define»)
(lambda . «lambda»)
(if . «if»)
(and . «and»)
(or . «or»)
(not . «not»)
(= . «=»)
(> . «>»)
(< . «<»)
(/ . «/»)
(* . «*»)
(- . «-»)
(+ . «+»)
(int . «int»)
(cdr . «cdr»)
(car . «car»)
(cons . «cons»)
(quote . «quote»)
(eval . «eval»)
(#t . #t)
)
()</code>
<code>print-heap</code>:
```lisp
λ (print-heap)
------------------- HEAP -------------------
| # | address | symbol |
|-----|----------|-------------------------|
| 0 | 0x0000 | ERR |
| 1 | 0x0004 | #t |
| 2 | 0x0007 | eval |
| 3 | 0x000C | quote |
| 4 | 0x0012 | cons |
| 5 | 0x0017 | car |
| 6 | 0x001B | cdr |
| 7 | 0x001F | int |
| 8 | 0x0023 | + |
| 9 | 0x0025 | - |
| 10 | 0x0027 | * |
| 11 | 0x0029 | / |
| 12 | 0x002B | < |
| 13 | 0x002D | > |
| 14 | 0x002F | = |
| 15 | 0x0031 | not |
| 16 | 0x0035 | or |
| 17 | 0x0038 | and |
| 18 | 0x003C | if |
| 19 | 0x003F | lambda |
| 20 | 0x0046 | define |
| 21 | 0x004D | print-heap |
| 22 | 0x0058 | print-stack |
| 23 | 0x0064 | print-env |
| 24 | 0x006E | echo |
| 25 | 0x0073 | echo-evaluation |
| ... |
()
```
<code>print-stack</code>:
<code>lisp
λ (print-stack)
------------- STACK ------------
| pointer | tag | ordinal | Expr
|----------|--------|----------|--------------
| 1024 | ATOM | 0x0004 | #t
| 1023 | ATOM | 0x0004 | #t
| 1022 | CONS | 1022 |
| 1021 | NIL | 0 | ()
| 1020 | ATOM | 0x0007 | eval
| 1019 | PRIM | 0 | «eval»
| 1018 | CONS | 1018 |
| 1017 | CONS | 1020 |
| 1016 | ATOM | 0x000C | quote
| 1015 | PRIM | 1 | «quote»
| 1014 | CONS | 1014 |
| 1013 | CONS | 1016 |
| 1012 | ATOM | 0x0012 | cons
| 1011 | PRIM | 2 | «cons»
| 1010 | CONS | 1010 |
| 1009 | CONS | 1012 |
| 1008 | ATOM | 0x0017 | car
| 1007 | PRIM | 3 | «car»
| 1006 | CONS | 1006 |
| 1005 | CONS | 1008 |
| 1004 | ATOM | 0x001B | cdr
| 1003 | PRIM | 4 | «cdr»
| 1002 | CONS | 1002 |
| 1001 | CONS | 1004 |
| 1000 | ATOM | 0x001F | int
| 999 | PRIM | 5 | «int»
| 998 | CONS | 998 |
| 997 | CONS | 1000 |
| 996 | ATOM | 0x0023 | +
| 995 | PRIM | 6 | «+»
| 994 | CONS | 994 |
| 993 | CONS | 996 |
| 992 | ATOM | 0x0025 | -
| 991 | PRIM | 7 | «-»
| 990 | CONS | 990 |
| 989 | CONS | 992 |
| 988 | ATOM | 0x0027 | *
| 987 | PRIM | 8 | «*»
| 986 | CONS | 986 |
| 985 | CONS | 988 |
| 984 | ATOM | 0x0029 | /
| 983 | PRIM | 9 | «/»
| 982 | CONS | 982 |
| 981 | CONS | 984 |
| 980 | ATOM | 0x002B | <
| 979 | PRIM | 10 | «<»
| 978 | CONS | 978 |
| 977 | CONS | 980 |
| 976 | ATOM | 0x002D | >
| 975 | PRIM | 11 | «>»
| 974 | CONS | 974 |
| 973 | CONS | 976 |
| 972 | ATOM | 0x002F | =
| 971 | PRIM | 12 | «=»
| 970 | CONS | 970 |
| 969 | CONS | 972 |
| 968 | ATOM | 0x0031 | not
| 967 | PRIM | 13 | «not»
| 966 | CONS | 966 |
| 965 | CONS | 968 |
| 964 | ATOM | 0x0035 | or
| 963 | PRIM | 14 | «or»
| 962 | CONS | 962 |
| 961 | CONS | 964 |
| 960 | ATOM | 0x0038 | and
| 959 | PRIM | 15 | «and»
| 958 | CONS | 958 |
| 957 | CONS | 960 |
| 956 | ATOM | 0x003C | if
| 955 | PRIM | 16 | «if»
| 954 | CONS | 954 |
| 953 | CONS | 956 |
| 952 | ATOM | 0x003F | lambda
| 951 | PRIM | 17 | «lambda»
| 950 | CONS | 950 |
| 949 | CONS | 952 |
| 948 | ATOM | 0x0046 | define
| 947 | PRIM | 18 | «define»
| 946 | CONS | 946 |
| 945 | CONS | 948 |
| 944 | ATOM | 0x004D | print-heap
| 943 | PRIM | 19 | «print-heap»
| 942 | CONS | 942 |
| 941 | CONS | 944 |
| 940 | ATOM | 0x0058 | print-stack
| 939 | PRIM | 20 | «print-stack»
| 938 | CONS | 938 |
| 937 | CONS | 940 |
| 936 | ATOM | 0x0064 | print-env
| 935 | PRIM | 21 | «print-env»
| 934 | CONS | 934 |
| 933 | CONS | 936 |
| 932 | ATOM | 0x006E | echo
| 931 | PRIM | 22 | «echo»
| 930 | CONS | 930 |
| 929 | CONS | 932 |
| 928 | ATOM | 0x0073 | echo-eval
| 927 | PRIM | 23 | «echo-eval»
| 926 | CONS | 926 |
| 925 | CONS | 928 |
| 924 | ATOM | 0x0058 | print-stack
| 923 | NIL | 0 | ()
| ... |
|------------------------------|
()</code>
Build
Compiled using zig version:
<code>shell
$ zig version
0.14.0</code>
Build the wasm executable using <code>zig build</code>:
```shell
$ zig build
$ ls zig-out/bin
tinylisp.wasm
```
Additionally, build the local executable using <code>zig build local</code>:
```shell
$ zig build local
$ ls zig-out/bin
tinylisp tinylisp.wasm
```
Or run the local executable directly using <code>zig build run</code>:
<code>shell
$ zig build run
λ</code>
TODO:
General
<ul>
<li>[X] Compile to .wasm and add a javascript REPL</li>
<li>[X] Write a blogpost
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Expand documentation with more examples</li>
</ul>
Zig
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Add tests
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Improve parsing to handle multiple expressions separed by new lines
Terminal
<ul>
<li>[X] <code>Ctrl+c</code> to delete the current line
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Multiline inputs don't work well with the history explorer (<code>Up Arrow</code>)
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Syntax highlighting
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Drop files
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Click to copy input/output</li>
</ul>
Resources
<ul>
<li>
<a>Lisp in 99 lines of C and how to write one yourself - Robert-van-Engelen</a>
</li>
<li>
<a>Passing strings to and from WebAssembly using C</a>
</li>
<li>
<a>TINYLISP: A Minimal Lisp Interpreter in Zig and WebAssembly</a>
</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/22038970?v=4 | zba-gdbstub | paoda/zba-gdbstub | 2022-12-11T08:07:47Z | GDB Server for Debugging guest code in paoda/zba | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/paoda/zba-gdbstub/tags | - | [
"debugger",
"emulation",
"gdb",
"gdb-protocol",
"gdb-rsp",
"gdbstub",
"zig",
"zig-library",
"zig-package"
]
| 61 | false | 2024-07-04T00:46:05Z | true | true | unknown | github | []
| ZBA-GDBSTUB
This is a gdbstub server for paoda/zba, because I don't want to import a C library and i <em>love</em> reinventing the wheel I guess.
Scope
This is tailor made for targeting the GBA. Anything that isn't necessary for stepping through ARMv4T code isn't included. This means lots of hardcoded values and assumptions that would be really awful for any halfway decent gdbstub implementation.
This project will have succeeded as soon as I use it to determine why Rhythm Heaven is stuck in an infinite loop. | [
"https://github.com/paoda/turbo",
"https://github.com/paoda/zba"
]
|
https://avatars.githubusercontent.com/u/74048074?v=4 | zig-template | gamercade-io/zig-template | 2022-09-15T19:46:14Z | A starter template project for Gamercade in Zig. | main | 2 | 3 | 1 | 3 | https://api.github.com/repos/gamercade-io/zig-template/tags | Apache-2.0 | [
"fantasy-console",
"game-dev",
"game-development",
"gamedev",
"retrogames",
"retrogaming",
"wasm",
"zig",
"ziglang"
]
| 12 | false | 2025-03-18T10:56:27Z | true | false | unknown | github | []
| Zig Bindings & Example Project
For <a>Gamercade</a> and the <a>Gamercade Console</a>.
Zig Bindings for Gamercade
Bindings are located at <code>/gamercade</code>.
Import the bindings into your project with <code>const gc = @import("gamercade")</code>.
You can also use the <code>raw</code> api, by going through <code>gc.raw</code>. For example, <code>gc.raw.set_pixel(0, 10, 10)</code>.
Building the Example project
Build the project with <code>zig build</code>.
The file will be output at <code>zig-out/lib/zig-template.wasm</code>.
Then, follow the <a>guide on bundling</a> a game with the editor.
Zig Version
This was built and is compatible with <strong>Zig 0.9.1</strong>.
License
Licensed under either of
<ul>
<li>Apache License, Version 2.0 (<a>LICENSE-APACHE</a> or https://www.apache.org/licenses/LICENSE-2.0)</li>
<li>MIT license (<a>LICENSE-MIT</a> or https://opensource.org/licenses/MIT)</li>
</ul>
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions. | []
|
https://avatars.githubusercontent.com/u/1405886?v=4 | aoc2022 | Vzaa/aoc2022 | 2022-11-30T08:43:36Z | null | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/Vzaa/aoc2022/tags | - | [
"advent-of-code-2022",
"aoc2022",
"zig"
]
| 122 | false | 2022-12-20T14:20:54Z | false | false | unknown | github | []
| 404 | []
|
https://avatars.githubusercontent.com/u/10274397?v=4 | zig-pico-sdk | Linouth/zig-pico-sdk | 2022-05-15T17:12:52Z | Zig wrapper for the Raspberry pico-sdk | master | 0 | 3 | 0 | 3 | https://api.github.com/repos/Linouth/zig-pico-sdk/tags | - | [
"pico",
"rp2040",
"rpi-pico",
"zig",
"ziglang"
]
| 6 | false | 2025-01-10T03:51:08Z | true | false | unknown | github | []
| zig-pico-sdk
After first attempting to rewrite the SDK from scratch in Zig
(<a>zig-pico</a>), I realized that
this would be way too much work for me right now. Instead, this repo is a
wrapper around the official <a>pico-sdk</a>.
It allows you to compile Zig programs for the Pico microcontroller (RP2040),
while being able to use the official SDK.
The <code>build.zig</code> file is setup to use the zig compiler to compile your program to
an object file. Then the pico-sdk will run as normal, and link the libraries
together with this object file into a binary.
Make sure that you have <code>arm-none-eabi-gcc</code>, <code>cmake</code>, <code>make</code>, and
the arm libs installed (<code>arm-none-eabi-newlib</code> on arch).
<strong>This wrapper is extremely experimental still!</strong> I expect plenty of bugs and
issues. Feel free to open issues, or to contribute. | []
|
https://avatars.githubusercontent.com/u/3759175?v=4 | itis | Hejsil/itis | 2022-05-31T22:35:55Z | A small library for asking questions about types | master | 1 | 3 | 0 | 3 | https://api.github.com/repos/Hejsil/itis/tags | MIT | [
"metaprogramming",
"zig",
"zig-library"
]
| 14 | false | 2024-09-13T12:53:58Z | false | false | unknown | github | []
| itis
A small library for asking questions about types.
<code>``zig
/// Example serialize function that uses</code>itis` to serialize ArrayList and ArrayHashMap.
pub fn serialize(writer: anytype, value: anytype) !void {
const T = @TypeOf(value);
if (comptime itis.anArrayList(T)) {
try writer.writeAll("[");
for (value.items) |item, i| {
if (i != 0)
try writer.writeAll(",");
try serialize(writer, item);
}
return writer.writeAll("]");
}
if (comptime itis.anArrayHashMap(T)) {
try writer.writeAll("{");
for (value.keys()) |key, i| {
const v = value.values()[i];
if (i != 0)
try writer.writeAll(",");
<code> try serialize(writer, key);
try writer.writeAll(":");
try serialize(writer, v);
}
return writer.writeAll("}");
}
// The rest is left as an execise for the reader
</code>
}
``` | []
|
https://avatars.githubusercontent.com/u/1422834?v=4 | metro-zig | moznion/metro-zig | 2022-08-10T07:49:46Z | MetroHash library for Zig | main | 1 | 3 | 1 | 3 | https://api.github.com/repos/moznion/metro-zig/tags | NOASSERTION | [
"metrohash",
"zig",
"ziglang"
]
| 12 | false | 2022-08-13T06:32:55Z | true | false | unknown | github | []
| MetroHash for Zig <a></a>
<a>MetroHash</a> library for <a>Zig</a>.
This library provides 64-bit and 128-bit MetroHash hashing functions.
Synopsis
64-bit Hash
<code>zig
var data = [_]u8{
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 48, 49, 50,
};
const seed: u64 = 1;
const hash: u64 = hash64(data[0..], seed);</code>
128-bit Hash
<code>zig
var data = [_]u8{
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 48, 49, 50, 51,
52, 53, 54, 55, 56, 57, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 48, 49, 50, 51, 52, 53,
54, 55, 56, 57, 48, 49, 50,
};
const seed: u64 = 1;
const hash: u128 = hash128(data[0..], seed);</code>
How to build and test
<code>$ git submodule init && git submodule update
$ zig build test</code>
Note
This implementation is based on <a>jandrewrogers/MetroHash</a> and <a>dgryski/go-metro</a>.
License
MIT
Author
moznion (<a>moznion@mail.moznion.net</a>) | []
|
https://avatars.githubusercontent.com/u/81343645?v=4 | calcular-digitos-verificar-cpf | tomasfn87/calcular-digitos-verificar-cpf | 2022-02-14T12:41:43Z | (( Baixar ferramenta CLI Linux aqui! )) Como calcular os dígitos verificadores de um CPF; em Python, TypeScript, Go, Rust, Lua, Java, C++, C#, C, Zig, Ruby, PHP, Odin, Julia, Perl, Ada, Elixir, R, D, COBOL, Pascal, Smalltalk, Lisp, Fortran 90, Algol 68, Mojo, Ring e Haskell. | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/tomasfn87/calcular-digitos-verificar-cpf/tags | - | [
"ada",
"c",
"cli-app",
"cobol",
"csharp",
"go",
"java",
"julia",
"lisp",
"lua",
"luajit",
"odin-lang",
"pascal",
"perl",
"php8",
"python",
"ruby",
"rust",
"typescript",
"zig"
]
| 244 | false | 2025-05-20T09:19:59Z | false | false | unknown | github | []
| calcular-digitos-verificar-cpf
<em>Como calcular os dígitos verificadores de um</em> <strong>CPF</strong>; <em>em</em> <code>Python</code>, <code>Typescript</code>, <code>Go</code>, <code>Rust</code>, <code>Lua</code>, <code>Java</code>, <code>C++</code>, <code>C#</code>, <code>C</code>, <code>Zig</code>, <code>Ruby</code>, <code>PHP</code>, <code>Odin</code>, <code>Julia</code>, <code>Perl</code>, <code>Ada</code>, <code>Elixir</code>, <code>R</code>, <code>D</code>, <code>COBOL</code>, <code>Pascal</code>, <code>Smalltalk</code>, <code>Lisp</code>, <code>Fotran 90</code>, <code>Algol 68</code>, <code>Mojo</code>, <code>Ring</code> e <code>Haskell</code>.
<em>Teste a versão em</em> <code>Go</code>:
- <a>CPF - Calcular Digitos / Verificar</a>
Instale a ferramenta CLI com base na versão em Python via <code>git clone</code> em sistemas <code>Linux</code>
<ul>
<li>É necessário ter privilégios de <strong>administrador</strong>;</li>
<li>É necessário ter o <code>git</code> instalado.</li>
</ul>
<em>Instalação</em>
<code>shell
sudo git clone --depth 1 --no-checkout https://github.com/tomasfn87/calcular-digitos-verificar-cpf /usr/local/lib/calcular-digitos-verificar-cpf && pushd /usr/local/lib/calcular-digitos-verificar-cpf && sudo git sparse-checkout set python/{cpf.py,{calcular_digitos,verificar}_cpf.{py,sh}} && sudo git checkout && sudo mv python/* . && sudo chmod +x *.sh && sudo ln -rs /usr/local/lib/calcular-digitos-verificar-cpf/calcular_digitos_cpf.sh /usr/local/bin/cdcpf && sudo ln -rs /usr/local/lib/calcular-digitos-verificar-cpf/verificar_cpf.sh /usr/local/bin/vcpf && sudo rmdir python && popd && echo "\nUse os comandos vcpf e cdcpf para verificar ou calcular os dígitos de um CPF."</code>
<em>Desinstalação</em>
<code>shell
sudo rm -rf /usr/local/{lib/calcular-digitos-verificar-cpf,bin/{cd,v}cpf}</code>
<em>Atualização</em>
<code>shell
sudo rm -rf /usr/local/lib/calcular-digitos-verificar-cpf && sudo git clone --depth 1 --no-checkout https://github.com/tomasfn87/calcular-digitos-verificar-cpf /usr/local/lib/calcular-digitos-verificar-cpf && pushd /usr/local/lib/calcular-digitos-verificar-cpf && sudo git sparse-checkout set python/{cpf.py,{calcular_digitos,verificar}_cpf.{py,sh}} && sudo git checkout && sudo mv python/* . && sudo chmod +x *.sh && sudo rmdir python && popd && echo "\nvcpf e cdcpf foram atualizados."</code>
Usos
<ul>
<li>É necessário ter o <code>python3</code> instalado.</li>
</ul>
<em><strong>CPF</strong></em> <em>inválido</em>:
<code>shell
vcpf 123.456.789-08</code>
<em><strong>CPF</strong></em> <em>válido</em>:
<code>shell
vcpf 123.456.789-09</code>
<em>Cálculo dos Dígitos verificadores de um</em> <em><strong>CPF</strong></em>:
<code>shell
cdcpf 123.456.789</code>
<em>Cálculo dos Dígitos verificadores de um</em> <em><strong>CPF</strong></em>:
<code>shell
cdcpf 123.456.789-09</code>
<blockquote>
<em>Apenas os</em> <em><strong>9 primeiros dígitos</strong></em> <em>são considerados</em>.
</blockquote> | []
|
https://avatars.githubusercontent.com/u/27089165?v=4 | portmidi-zig | DivergentClouds/portmidi-zig | 2022-08-24T23:10:59Z | A Zig wrapper for PortMidi | main | 3 | 3 | 1 | 3 | https://api.github.com/repos/DivergentClouds/portmidi-zig/tags | MIT | [
"bindings",
"wrapper",
"zig",
"zig-library",
"zig-package"
]
| 37 | false | 2024-05-04T17:59:49Z | false | false | unknown | github | []
| portmidi-zig
A Zig wrapper for PortMidi
Dependencies
<ul>
<li><a>PortMidi</a></li>
<li>Made for <a>commit 103beb1</a>, other versions may or may not work.</li>
</ul>
See also
<ul>
<li><a>porttime-zig</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/3307207?v=4 | zig-sc2 | spudde123/zig-sc2 | 2022-08-21T09:41:56Z | Make scripted bots for Starcraft 2 using the Zig programming language | master | 0 | 3 | 0 | 3 | https://api.github.com/repos/spudde123/zig-sc2/tags | MIT | [
"starcraft2",
"zig"
]
| 759 | false | 2025-05-21T18:25:48Z | false | false | unknown | github | []
| Zig-sc2
Intended to make a Starcraft 2 bot for competing
on <a>sc2ai.net</a>, written in Zig 0.14.0.
It doesn't at this time use everything in the SC2
<a>API</a>,
but nothing important for actually making bots should
be missing.
Start from <a>zig-sc2-template</a> to make your own bot. | []
|
https://avatars.githubusercontent.com/u/33030965?v=4 | zig-parser-combinator | tizee/zig-parser-combinator | 2022-07-29T15:24:20Z | A parser-combinator library in Zig | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/tizee/zig-parser-combinator/tags | Apache-2.0 | [
"parser-combinator",
"zig"
]
| 35 | false | 2023-03-09T02:10:18Z | true | false | unknown | github | []
| parser-combinator-zig
A simple Zig parser combinator library.
<code>shell
$ zig version
0.10.0-dev.3340+c6f5832bb</code>
Examples
<ul>
<li>An simple Emmet parser</li>
</ul>
<code>zig build emmet
./example/emmet "div.root>ul>list>li.5"</code>
Acknowledgment
This project was inspired from following projects:
<ul>
<li>https://github.com/haskell/parsec</li>
<li>https://github.com/Geal/nom</li>
<li>https://github.com/yetone/parsec.js</li>
<li>https://github.com/longlongh4/demo_parser_combinator</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/5464072?v=4 | zig-asn1 | nektro/zig-asn1 | 2022-11-01T07:42:29Z | Zig parser for ASN.1 DER binary encoding. | master | 0 | 3 | 1 | 3 | https://api.github.com/repos/nektro/zig-asn1/tags | MIT | [
"asn1",
"zig",
"zig-package"
]
| 12 | false | 2025-04-18T17:51:55Z | true | false | unknown | github | []
| zig-asn1
Zig parser for ASN.1 DER binary encoding.
<ul>
<li><a>ITU X.680</a> Abstract Syntax Notation One (ASN.1)</li>
<li><a>ITU X.690</a> ASN.1 encoding rules</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/1266011?v=4 | zig-wasm-life | danprince/zig-wasm-life | 2022-12-07T21:39:13Z | Zig + WebAssembly implementation of Life | main | 0 | 3 | 0 | 3 | https://api.github.com/repos/danprince/zig-wasm-life/tags | - | [
"game-of-life",
"webassembly",
"zig"
]
| 7 | false | 2024-12-03T15:02:37Z | true | false | unknown | github | []
| Zig Life
Conway's <a>Game of Life</a> implemented with Zig and WebAssembly.
Mostly built to serve as a reference project. Contains examples of sharing memory, printing with format strings, and two way function calls.
<ul>
<li>Click to paint</li>
<li>space Pause</li>
<li>esc Clear</li>
</ul>
Run <code>zig build</code> to compile a new <code>life.wasm</code>. | []
|
https://avatars.githubusercontent.com/u/16240002?v=4 | mazegen | vilhelmbergsoe/mazegen | 2022-06-07T13:05:34Z | A simple maze generator using the recursive backtracking algorithm | master | 0 | 3 | 1 | 3 | https://api.github.com/repos/vilhelmbergsoe/mazegen/tags | MIT | [
"learning-by-doing",
"maze-generator",
"zig"
]
| 8 | false | 2024-01-03T09:39:37Z | true | false | unknown | github | []
| mazegen
A simple maze generator using the <a>recursive backtracking algorithm</a>.
mazegen is a simple implementation of the recursive backtracking algorithm and
was made as a way of learning the <a>zig programming language</a>.
Dependencies
<code>zig >= 0.10.0</code>
<code>libSDL2</code>
Usage
```sh
$ zig build
$ ./zig-out/bin/mazegen
Generate awesome mazes with the recursive backtracking algorithm
Usage:
./zig-out/bin/mazegen
Options:
width: usize integer
height: usize integer
seed (*optional): unsigned 64-bit integer default = random
$ ./zig-out/bin/mazegen 10 10
$ ./zig-out/bin/mazegen 20 20 42
```
Contributing
Check out <a>ISSUES.md</a> for things to do and send a PR.
License
<a>MIT</a> | []
|
https://avatars.githubusercontent.com/u/1606004?v=4 | ziglearn | pmuens/ziglearn | 2022-04-09T14:30:59Z | Learning Zig via ziglearn.org | master | 0 | 3 | 0 | 3 | https://api.github.com/repos/pmuens/ziglearn/tags | - | [
"tutorial",
"zig",
"zig-lang",
"zig-programming-language"
]
| 43 | false | 2025-03-28T00:54:32Z | false | false | unknown | github | []
| Ziglearn
Learning <a>Zig</a> via <a>ziglearn.org</a>.
Setup
<ol>
<li><code>git clone <url></code></li>
<li>Ensure that <a>Zig</a> and <a>ZLS</a> are installed</li>
<li>Update paths in <a><code>.vscode/settings.json</code></a> file</li>
<li>Create symlink to <code>zig</code> binary (e.g. <code>ln -sf /Users/philipp/Desktop/zig.nosync/zig zig</code>)</li>
<li><code>./zig run <name></code></li>
</ol>
Useful Commands
```sh
zig run
zig test
```
Additional Resources
<ul>
<li>https://ziglearn.org</li>
<li>https://ziglang.org/documentation</li>
<li>https://github.com/zigtools/zls</li>
<li>https://github.com/ratfactor/ziglings</li>
<li>https://dev.to/watzon/debugging-zig-with-vs-code-44ca</li>
<li>https://dev.to/fabioarnold/setup-zig-for-gamedev-2bmf</li>
<li>https://zig.news/jarredsumner/setting-up-visual-studio-code-for-writing-zig-kcj</li>
<li>https://github.com/zigtools/zls/wiki/Installing-for-Visual-Studio-Code</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/28833727?v=4 | bilibili_uwp_mp4_decode | zzk13180/bilibili_uwp_mp4_decode | 2022-11-11T02:39:46Z | 解密哔哩哔哩UWP客户端下载的视频 | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/zzk13180/bilibili_uwp_mp4_decode/tags | MIT | [
"bilibili",
"zig"
]
| 9 | false | 2023-11-06T09:01:14Z | true | false | unknown | github | []
| 解密哔哩哔哩UWP客户端下载的视频
运行
<ul>
<li>git submodule update --init</li>
<li>zig build</li>
<li>zig build run</li>
<li>zig build -h</li>
</ul>
演示
<ul>
<li>https://www.bilibili.com/video/BV1Fe4y147gU/</li>
</ul>
下载
<ul>
<li>https://github.com/zzk13180/bilibili_uwp_mp4_decode/releases</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/106405901?v=4 | zig-opengl-triangle | astral-shining/zig-opengl-triangle | 2022-12-26T13:59:40Z | Zig Triangle using OpenGL Core 3.3 & GLFW | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/astral-shining/zig-opengl-triangle/tags | MIT | [
"opengl-es",
"opengl-tutorial",
"triangle",
"zig"
]
| 48 | false | 2022-12-27T04:30:22Z | true | false | unknown | github | []
| Zig OpenGL Triangle
Hii, this is my 4th day learning zig so I decided implement a triangle using ZGL and mach zig libraries.
I hope it helps.
Installation
<code>sh
git clone https://github.com/astral-shining/zig-opengl-triangle
cd zig-opengl-triangle
git submodule update --init --recursive --depth 1
zig build -Drelease-fast</code> | []
|
https://avatars.githubusercontent.com/u/71951273?v=4 | kritzler | garrisonhh/kritzler | 2022-08-28T14:04:24Z | minimal zig terminal library | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/garrisonhh/kritzler/tags | MIT | [
"terminal",
"zig"
]
| 34 | false | 2022-12-23T06:09:20Z | false | false | unknown | github | []
| kritzler
kritzler is a small library for generating ANSI terminal output in two dimensions.
how the fuck do I use your library
I'm going to assume for the sake of this documentation that you've imported
kritzler as <code>kz</code>, and have an <code>allocator</code> available.
<code>zig
// first, initialize a context. this acts as the memory manager for kritzler.
var ctx = kz.Context.init(allocator);
defer ctx.deinit(); // you usually want this too</code>
with a context, you can create and manipulate text blocks in several different
ways:
<code>``zig
// this is usually what you want. make a text chunk using the</code>std.fmt` api.
fn print(self: *Self, sty: Style, comptime fmt: []const u8, args: anytype) PrintError!Ref
// create a blank chunk.
fn blank(self: *Self, size: Pos) Allocator.Error!Ref
// create a 0x0 chunk.
fn stub(self: *Self) Allocator.Error!Ref
```
once you have a couple refs, there are a few simple ways to manipulate them. a
really important note here is that refs have move semantics, e.g. once you use
a ref it is 'dropped' and invalid.
```zig
// slap directions are .left, .right, .bottom, and .top.
// for the advanced options, see src/context.zig.
// slap some refs together. drops both refs.
fn slap(self: *Self, a: Ref, b: Ref, dir: SlapDirection, opt: SlapOpt) Allocator.Error!Ref
// slap more than 2 refs together. drops all refs.
fn stack(self: *Self, refs: []const Ref, dir: SlapDirection, opt: SlapOpt) Allocator.Error!Ref
// this places chunk b over chunk a at an offset, and drops both refs.
// <code>slap</code> is implemented in terms of unify.
// <code>ctx.getSize(ref)</code> is a useful function to have alongside unify.
fn unify(self: *Self, a: Ref, b: Ref, to: Offset) Allocator.Error!Ref
```
at this point, you may also want these functions:
<code>zig
fn clone(self: *Self, ref: Ref) Allocator.Error!Ref
fn drop(self: *Self, ref: Ref) void</code>
finally, you can write a ref to a writer from the context struct:
```zig
const stdout = @import("std").io.getStdout().writer();
try ctx.write(ref, stdout);
```
<em>this isn't perfectly exhaustive, but it covers everyhing you need to start
effectively using kritzler. start with reading context.zig if you need more.</em>
basic primitives
<code>Ref</code>
<code>Ref</code> acts as a handle for rectangles of text.
<code>Style</code>
<code>Style</code> has three fields, <code>fg</code>, <code>bg</code>, and <code>special</code>. this is an attempt to slim
down the mess that is ANSI console escape codes into a sensible format. see
<code>style.zig</code> for the list of options for each of these (it is pretty small).
<code>Pos</code> and <code>Offset</code>
these are <code>usize</code> and <code>isize</code> 2d vectors, respectively. | []
|
https://avatars.githubusercontent.com/u/4871664?v=4 | zig-zac-zoe | sts10/zig-zac-zoe | 2022-08-19T04:25:34Z | A basic tic-tac-toe game in Zig programming language | main | 0 | 2 | 1 | 2 | https://api.github.com/repos/sts10/zig-zac-zoe/tags | MIT | [
"zig"
]
| 35 | false | 2024-09-20T03:58:00Z | true | false | unknown | github | []
| Zig Zac Zoe
Writing a very basic command-line tic-tac-toe game in <a>Zig</a> as a way of learning the very basics of the language. I also wrote <a>a blog post about this project</a>.
Previously, I did this in <a>Rust</a> and <a>Go</a> as <a>a learning exercise in those two languages</a>.
Installing Zig
Consult <a>the Zig GitHub README</a> for installation options.
I think I installed Zig by running: <code>snap install zig --classic --edge</code>, as listed in <a>Zig's GitHub wiki</a>. I originally wrote this program running v0.9.1.
Running this program
Once Zig is installed, you should be able to run this program with the following command:
<code>shell
zig build run</code>
This program should work with Zig version 0.13.0, though I haven't tested it thoroughly.
Note that most of the code work is in <code>src/main.zig</code>.
Zig resources I found
These are potentially out-dated now, but here are some things I used in 2022:
<ul>
<li><a>Official Zig docs for current version of Zig</a></li>
<li><a>Official Zig docs for v 0.9.1</a> </li>
<li><a>ziglearn.org</a></li>
<li><a>Zig by example</a></li>
<li><a>Ziglings</a> (think this requires an edge version of Zig?)</li>
<li><a>A long video of a beginner Zig programmer who's coming from Rust</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/12962448?v=4 | Paradise | star-tek-mb/Paradise | 2022-10-19T18:40:29Z | WASM first game engine written in Zig. | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/star-tek-mb/Paradise/tags | - | [
"game-engine",
"gamedev",
"zig"
]
| 51 | false | 2024-06-05T09:46:57Z | true | false | unknown | github | []
| Overview
Paradise is a wasm first game engine written in zig.
Status
Development stopped for now until zig stage2 async.
Architecture
All images are embedded qoi images.
Keep engine as simple as possible.
TODO
<ul>
<li>Use package manager to fetch modules (priority)</li>
<li>Find a way to fetch resources (not embed). We should wait for zig async/await in stage2.</li>
<li>Find js object/function/string leaks.</li>
<li>Port to other platforms (not now).</li>
</ul>
Add audio engine.
Usage
```zig
const std = @import("std");
const platform = @import("platform.zig");
const paradise = @import("paradise.zig");
comptime {
_ = platform;
}
pub const log = platform.log;
pub const gl = platform.gl;
var renderer: paradise.Renderer = undefined;
var sprite: paradise.Sprite = undefined;
fn update(_: f32) void {
gl.viewport(0, 0, 800, 600);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.clearColor(0.2, 0.3, 0.3, 1.0);
<code>renderer.start(800, 600);
renderer.renderSprite(sprite);
renderer.stop();
</code>
}
pub fn onKeyDown(key: u16) void {
if (key == 37) {
sprite.x -= 10;
sprite.w = -@fabs(sprite.w);
}
if (key == 39) {
sprite.x += 10;
sprite.w = @fabs(sprite.w);
}
}
pub fn main() !void {
platform.init();
<code>platform.onKeyDown(onKeyDown);
var image = try paradise.Image.load(std.heap.page_allocator, @embedFile("assets/character.qoi"));
defer image.deinit(std.heap.page_allocator);
sprite = try paradise.Sprite.fromImage(image);
sprite.x = 100.0;
sprite.y = 100.0;
sprite.w = 64.0;
sprite.h = 64.0;
sprite.ox = 32.0;
sprite.oy = 32.0;
renderer = paradise.Renderer.init(std.heap.page_allocator);
platform.run(update);
</code>
}
```
see <strong>src/main.zig</strong>
Credits
https://github.com/hexops/mach - for sysjs, for wasmserve
https://github.com/ziglibs/zlm - vector math
https://github.com/MasterQ32/zig-qoi - for image loading | []
|
https://avatars.githubusercontent.com/u/74600205?v=4 | zmath | JungerBoyo/zmath | 2022-09-28T13:57:34Z | simple linear algebra library written in zig | main | 0 | 2 | 1 | 2 | https://api.github.com/repos/JungerBoyo/zmath/tags | MIT | [
"linear-algebra-library",
"math",
"zig"
]
| 7 | false | 2025-05-13T16:46:03Z | true | false | unknown | github | []
| zmath
simple linear algebra library written in zig.
implements
<ul>
<li>Vec{2, 3, 4}x{{f, i, u}x{32, 64}}<blockquote>
dot product, cross product, {+, -, *, /} ops
</blockquote>
</li>
<li>Mat{2x2, 3x3, 4x4}x{{f, i, u}x{32, 64}}<blockquote>
determinant, inverse (without det==0 test), transpose, mul op
</blockquote>
</li>
<li>Mat4x4{f32, f64}<blockquote>
init from unit quaternion, init as rotation from euler angles, projection
</blockquote>
</li>
<li>Quaternion{f32, f64}<blockquote>
mul op, init from 3d vector and angle
</blockquote>
</li>
<li>transforms{f32, f64}<blockquote>
3d point rotation
</blockquote>
</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/36535717?v=4 | Khichu | BlackGoku36/Khichu | 2023-01-21T12:32:59Z | An experimental programming language that targets WASM | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/BlackGoku36/Khichu/tags | Zlib | [
"code-generation",
"compiler",
"wasm",
"zig"
]
| 3,276 | false | 2024-10-22T18:55:59Z | true | false | unknown | github | []
| Khichu
<a>Khichu</a> is experimental programming language that targets WASM and a custom register-based VM (TODO). We do our own code-generation from scratch instead of relying on LLVM or similar code-generation technologies.
This is project done during free time.
Compile and Run
Write the code in <code>test.ul</code> and do:
```
Zig 0.13
zig build run
```
TODO
<ul>
<li>Add some tests running facility</li>
<li>Check if code-gen for assignment statement/expression is good or not.</li>
<li>Find some way to collect as many as errors possible before quitting.</li>
<li>Allow 'var x = 5;', that is allow type inference.</li>
<li>Analyzer<ul>
<li>Check if the identifier used already exists or not.<ul>
<li>Turn symbol table into hashmap.</li>
<li>While reporting error, show where previous identifier is declared.</li>
<li>Maybe do this in semantic analyzer?</li>
</ul>
</li>
<li>Disallow variable shadowing.</li>
<li>Disallow changing type on assignment to same variable (if var is float, then it is legal right now to assign bool to it, but it should be illegal).</li>
</ul>
</li>
<li>Minor refactor:<ul>
<li>Code is bit stinky</li>
</ul>
</li>
<li>What should be better error message?
<code>test.ul:0: Expected ';' after 'expression', found 'identifier'.
x: float = 8.2 + 2.1 / 3.8;
^--------------------------</code></li>
</ul>
Language
<ul>
<li>Add functions, conditioanls and loops</li>
<li>Add data types such as different signedness of integer with different size, arrays, etc.</li>
</ul>
WASM
<ul>
<li>Remove hardcoding of some of wasm code-gen</li>
<li><code>var x: float = 5;</code> interpret 5 as integer, so generated wasm code assignmet doesn't work.</li>
</ul>
VM
<ul>
<li>Start Register-Based VM</li>
</ul>
FUTURE TODO
<ul>
<li>Suggest related variable names, for example, programmer types <code>x_ids</code> but only <code>x_idx</code> exist, so it will suggest <code>x_idx</code>.</li>
</ul>
WASM
<ul>
<li><a>Spec</a></li>
<li><a>Part-1</a></li>
<li><a>Part-2</a></li>
<li><a>Part-3</a></li>
<li><a>Part-4</a></li>
<li><a>Part-5</a></li>
<li><a>Part-6</a></li>
<li><a>Part-7</a></li>
</ul>
Plan
<ol>
<li>Be able to parse all the basics feature a programming language can have. (functions, arrays, loops, etc)</li>
<li>Write WASM code gen for it</li>
<li>Design custom IR</li>
<li>Use this IR to codegen WASM code</li>
<li>Design register-based VM and it's bytecode.</li>
<li>Do optimization on custom IR to produce efficient builds.</li>
<li>Maybe do RISC-V codegen</li>
</ol> | []
|
https://avatars.githubusercontent.com/u/63465728?v=4 | basis-universal-zig | alichraghi/basis-universal-zig | 2022-08-06T13:21:33Z | Zig binding of Basis Universal | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/alichraghi/basis-universal-zig/tags | MIT | [
"basis-universal",
"encoder",
"gpu",
"transcoder",
"zig",
"zig-package"
]
| 906 | false | 2023-01-11T16:06:25Z | true | false | unknown | github | []
| NOTE: moved to https://github.com/hexops/mach
Basis Universal Zig
Zig Binding of Basis Universal
<em>compatible with <a>v16.3</a></em>
Usage
see <code>test "encode/transcode"</code> in <code>src/main.zig</code> for usage example | []
|
https://avatars.githubusercontent.com/u/17385129?v=4 | tinyrenderer_ | OAguinagalde/tinyrenderer_ | 2022-02-27T10:37:24Z | A software renderer exploration written in zig | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/OAguinagalde/tinyrenderer_/tags | NOASSERTION | [
"software-rendering",
"zig"
]
| 82,058 | true | 2024-03-21T12:35:47Z | true | false | unknown | github | []
| Tiny Renderer or how OpenGL works: software rendering in 500 lines of code
Check <a>the wiki</a> for the detailed lessons.
compilation
<code>sh
git clone https://github.com/ssloy/tinyrenderer.git &&
cd tinyrenderer &&
mkdir build &&
cd build &&
cmake .. &&
cmake --build . -j &&
./tinyrenderer ../obj/diablo3_pose/diablo3_pose.obj ../obj/floor.obj</code>
The rendered image is saved to <code>framebuffer.tga</code>.
You can open the project in Gitpod, a free online dev evironment for GitHub:
<a></a>
On open, the editor will compile & run the program as well as open the resulting image in the editor's preview.
Just change the code in the editor and rerun the script (use the terminal's history) to see updated images.
The main idea
<strong>My source code is irrelevant. Read the wiki and implement your own renderer. Only when you suffer through all the tiny details you will learn what is going on.</strong>
In <a>this series of articles</a>, I want to show the way OpenGL works by writing its clone (a much simplified one). Surprisingly enough, I often meet people who cannot overcome the initial hurdle of learning OpenGL / DirectX. Thus, I have prepared a short series of lectures, after which my students show quite good renderers.
So, the task is formulated as follows: using no third-party libraries (especially graphic ones), get something like this picture:
<em>Warning: this is a training material that will loosely repeat the structure of the OpenGL library. It will be a software renderer. <strong>I do not want to show how to write applications for OpenGL. I want to show how OpenGL works.</strong> I am deeply convinced that it is impossible to write efficient applications using 3D libraries without understanding this.</em>
I will try to make the final code about 500 lines. My students need 10 to 20 programming hours to begin making such renderers. At the input, we get a test file with a polygonal wire + pictures with textures. At the output, we’ll get a rendered model. No graphical interface, the program simply generates an image.
Since the goal is to minimize external dependencies, I give my students just one class that allows working with <a>TGA</a> files. It’s one of the simplest formats that supports images in RGB/RGBA/black and white formats. So, as a starting point, we’ll obtain a simple way to work with pictures. You should note that the only functionality available at the very beginning (in addition to loading and saving images) is the capability to set the color of one pixel.
There are no functions for drawing line segments and triangles. We’ll have to do all of this by hand. I provide my source code that I write in parallel with students. But I would not recommend using it, as this doesn’t make sense. The entire code is available on github, and <a>here</a> you will find the source code I give to my students.
```C++
include "tgaimage.h"
const TGAColor white = TGAColor(255, 255, 255, 255);
const TGAColor red = TGAColor(255, 0, 0, 255);
int main(int argc, char** argv) {
TGAImage image(100, 100, TGAImage::RGB);
image.set(52, 41, red);
image.write_tga_file("output.tga");`
return 0;
}
```
output.tga should look something like this:
Teaser: few examples made with the renderer
| []
|
https://avatars.githubusercontent.com/u/40190339?v=4 | ZigLink | daneelsan/ZigLink | 2022-04-03T05:26:27Z | Call Zig code from Wolfram Language via the LibraryLink interface. | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/daneelsan/ZigLink/tags | - | [
"wolfram-language",
"zig"
]
| 281 | false | 2025-01-15T17:57:05Z | true | false | unknown | github | []
| ZigLink
Call Zig code from Wolfram Language via the LibraryLink interface.
Objectives
There are three objectives:
<ol>
<li>
Translate the Wolfram LibraryLink C headers (WolframLibrary.h, WolframNumericArrayLibrary.h) to zig and use
zig code to generate dynamic libraries callable from Wolfram Language.
</li>
<li>
Write a WolframLibraryLink.zig package that uses the translated libraries from 1) but using a more zig-like style, i.e. following the style from the zig standard library.
</li>
<li>
Write Wolfram Language paclet that allows to call the zig built-in compiler/linker, in a similar vein to how CCompilerDriver`CreateLibrary compiles C code.
</li>
</ol>
Objective 1) is underway. Objectives 2) and 3) are TODO.
Directory layout
<code>├── demos # LibraryLink demos written in zig
├── LibraryLink # LibraryLink C headers translated to zig
├── WolframLibrary.zig
├── WolframNumericArrayLibrary.zig
├── LibraryResources # Directory containing all libraries
├── Linux-x86-64
├── MacOSX-ARM64
├── MacOSX-x86-64
├── Windows-x86-64
├── Tests
├── demos # Tests for the demos in zig
├── demo_XXXX.nb # Notebook testing the demo_XXXX
├── demo_XXXX.wlt # Automatic file generated from its .nb counterpart
├── ...
├── WolframResources # Resources that come from your standard Mathematica installation
├── LibraryLink # Wolfram LibraryLink files
├── demos
├── headers
├── build.zig # Zig build "script"
└── README.md</code>
LibraryLink header and demo translation
demo_XXXX.zig
These are zig translated versions of the C LibraryLink demos found in WolframResources/LibraryLink/demos.
building
To build these libraries we will use the zig building system, which is all contained in <code>build.zig</code>.
First, make sure you have zig version 0.9.1 (or later):
<code>shell
$ zig version
0.9.1</code>
Next, build all the demos:
<code>shell
$ zig build demos</code>
The amazing thing about the zig build system is it that allows simple cross-platform compilation.
Not only did the previous command created libraries for all the demos, but it also did so for all
the major supported Wolfram platforms:
<code>shell
$ ls LibraryResources/
Linux-x86-64 MacOSX-ARM64 MacOSX-x86-64 Windows-x86-64</code>
<code>shell
$ find LibraryResources/ -maxdepth 2 -type f
LibraryResources/MacOSX-x86-64/demo.dylib
LibraryResources/MacOSX-x86-64/demo_string.dylib
...
LibraryResources/MacOSX-ARM64/demo.dylib
LibraryResources/MacOSX-ARM64/demo_string.dylib
...
LibraryResources/Linux-x86-64/demo.so
LibraryResources/Linux-x86-64/demo_managed.so
...
LibraryResources/Windows-x86-64/demo_numericarray.pdb
LibraryResources/Windows-x86-64/demo_string.lib</code>
Note: The current paths to Mathematica's headers and libraries is hardcoded in <code>build.zig</code>:
<code>zig
const mathematica_path = "/Applications/Mathematica.app";</code>
so modify these as appropriate.
testing
First add the demo libraries to the <code>$LibraryPath</code> so that these libraries can be found via <code>FindLibrary</code>:
<code>Mathematica
$LibraryPath = PrependTo[$LibraryPath, FileNameJoin[{$ZigLinkDirectory, "LibraryResources", $SystemID}]]</code>
Next, run the .wlt tests found in Tests/demos:
<code>Mathematica
In[]:= TestReport[FileNames["*.wlt", FileNameJoin[{$ZigLinkDirectory, "Tests", "demos"}]]]
Out[]= TestReportObject[<...>]</code>
<code>$ZigLinkDirectory</code> is the directory where the ZigLink repository is located.
How?
The .zig packages where first generated using translate-c. However, many of the macros present in these headers where not translated correctly (or at all) by zig or types where not the most suitable, so they had to be manually tweaked after being translated by zig.
This is mentioned in zig's documentation:
<blockquote>
[...] if you would like to edit the translated code, it is recommended to use zig translate-c and save the results to a file. Common reasons for editing the generated code include: changing anytype parameters in function-like macros to more specific types; changing [<em>c]T pointers to [</em>]T or *T pointers for improved type safety [...]
</blockquote>
The .zig demos where manually translated from the C demos. They mostly follow the C style of coding, minus some uses of the zig standard library.
Progress
Here is a list of the files that need to be translated (and the ones that already have).
headers:
<ul>
<li>[ ] WolframCompileLibrary.h</li>
<li>[ ] WolframImageLibrary.h</li>
<li>[ ] WolframIOLibraryFunctions.h</li>
<li>[x] WolframLibrary.h</li>
<li>[x] WolframNumericArrayLibrary.h</li>
<li>[ ] WolframRawArrayLibrary.h</li>
<li>[ ] WolframRTL.h</li>
<li>[ ] WolframSparseLibrary.h</li>
<li>[ ] WolframStreamsLibrary.h</li>
</ul>
demos:
<ul>
<li>[ ] arbitraryTensor.c</li>
<li>[ ] async-examples-libmain.c</li>
<li>[ ] async-examples.h</li>
<li>[ ] async-tasks-oneshot.c</li>
<li>[ ] async-tasks-repeating.c</li>
<li>[ ] async-tasks-timing.c</li>
<li>[ ] async-tasks-without-thread.c</li>
<li>[ ] demo_callback.c</li>
<li>[x] demo_error.c</li>
<li>[ ] demo_eval.c</li>
<li>[ ] demo_image.cxx</li>
<li>[x] demo_LinkObject.c</li>
<li>[x] demo_managed.cxx</li>
<li>[ ] demo_numerical.c</li>
<li>[x] demo_numericarray.cxx</li>
<li>[x] demo_shared.c</li>
<li>[ ] demo_sparse.c</li>
<li>[x] demo_string.c</li>
<li>[ ] demo.c</li>
<li>[ ] image_external.c</li>
<li>[ ] image_video.cxx</li>
</ul>
References
LibraryLink:
<ul>
<li>https://reference.wolfram.com/language/LibraryLink/tutorial/Overview.html</li>
<li>https://reference.wolfram.com/language/guide/LibraryLink.html</li>
</ul>
Zig:
<ul>
<li>https://ziglearn.org</li>
<li>https://ziglang.org</li>
<li>https://github.com/ziglang/zig</li>
<li>https://ziglang.org/documentation/</li>
<li>https://www.lagerdata.com/articles/an-intro-to-zigs-integer-casting-for-c-programmers</li>
<li>https://zig.news/xq/zig-build-explained-part-1-59lf</li>
</ul>
Other:
<ul>
<li>https://github.com/WolframResearch/wolfram-library-link-rs</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/107726195?v=4 | zig-gb | zig-homebrew/zig-gb | 2022-06-21T23:07:45Z | Starter pack for developing GB games/applications with Zig | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/zig-homebrew/zig-gb/tags | - | [
"gameboy",
"zig"
]
| 3 | false | 2024-02-29T04:27:44Z | true | false | unknown | github | []
| zig-gb
Getting started
<ul>
<li><a>zig</a></li>
</ul>
<code>git clone https://github.com/zig-homebrew/zig-gb
cd zig-gb/
zig build # then run zig-out/zig-gb.gb with vbam</code>
Resources
<ul>
<li><a>gbdk website</a></li>
<li><a>gbdk examples</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/66517224?v=4 | zproxy | 360tetsu360/zproxy | 2022-08-21T03:21:13Z | [WIP] A simple proxy for mcbe. | master | 0 | 2 | 1 | 2 | https://api.github.com/repos/360tetsu360/zproxy/tags | MIT | [
"bedrock",
"mcbe",
"minecraft",
"proxy",
"zig"
]
| 27 | false | 2022-10-24T07:47:03Z | true | false | unknown | github | []
| ZPROXY
[WIP] A simple proxy for mcbe written in zig.
Usage
``` zig
const std = @import("std");
const network = @import("network");
const zproxy = @import("zproxy");
fn handle_client() bool {
return false;
}
fn handle_server() bool {
return false;
}
pub fn main() !void {
try network.init();
defer network.deinit();
<code>const bind_address = .{
.address = .{ .ipv4 = network.Address.IPv4.loopback },
.port = 19130,
};
const target_address = .{
.address = .{ .ipv4 = network.Address.IPv4.loopback },
.port = 19132,
};
try zproxy.startup(bind_address, target_address, handle_client, handle_server);
</code>
}
``` | []
|
https://avatars.githubusercontent.com/u/107519028?v=4 | annotated-bun | better-zig/annotated-bun | 2022-07-31T10:32:31Z | bun 源码分析 | annotated-bun-v0.1.5 | 0 | 2 | 0 | 2 | https://api.github.com/repos/better-zig/annotated-bun/tags | - | [
"annotation",
"bun",
"zig"
]
| 24,873 | true | 2024-12-11T22:18:17Z | true | false | unknown | github | []
| bun 源码分析:
<blockquote>
版本: 基于 <code>bun-v0.1.5</code>
分支: <code>annotated-bun-v0.1.5</code>
</blockquote>
<ul>
<li>注解 bun 源码. zig 目前最大的应用项目.</li>
<li>通过源码分析, 快速掌握 zig.</li>
</ul>
源码分析:
<ul>
<li>bun 分析笔记: <a>.annotated/</a></li>
</ul>
zig 环境搭建:
<ul>
<li><a>zig + vscode/clion 搭建开发环境</a></li>
<li><a>zig + vscode debug 断点调试配置</a></li>
</ul>
bun
<a></a>
bun is a new:
<ul>
<li>JavaScript runtime with Web APIs like <a><code>fetch</code></a>, <a><code>WebSocket</code></a>, and several more built-in. bun embeds JavaScriptCore, which tends to be faster and more memory efficient than more popular engines like V8 (though harder to embed)</li>
<li>JavaScript/TypeScript/JSX transpiler</li>
<li>JavaScript & CSS bundler</li>
<li>Task runner for package.json scripts</li>
<li>npm-compatible package manager</li>
</ul>
All in one fast & easy-to-use tool. Instead of 1,000 node_modules for development, you only need bun.
<strong>bun is experimental software</strong>. Join <a>bun’s Discord</a> for help and have a look at <a>things that don’t work yet</a>.
Today, bun's primary focus is bun.js: bun's JavaScript runtime.
Install
Native: (macOS x64 & Silicon, Linux x64, Windows Subsystem for Linux)
<code>sh
curl -fsSL https://bun.sh/install | bash</code>
Docker: (Linux x64)
<code>sh
docker pull jarredsumner/bun:edge
docker run --rm --init --ulimit memlock=-1:-1 jarredsumner/bun:edge</code>
If using Linux, kernel version 5.6 or higher is strongly recommended, but the minimum is 5.1.
Table of Contents
<ul>
<li><a>bun 源码分析:</a></li>
<li><a>源码分析:</a></li>
<li><a>zig 环境搭建:</a></li>
<li><a>bun</a></li>
<li><a>Install</a></li>
<li><a>Table of Contents</a></li>
<li><a>Using bun.js - a new JavaScript runtime environment</a><ul>
<li><a>Types for bun.js (editor autocomplete)</a></li>
<li><a>Fast paths for Web APIs</a></li>
</ul>
</li>
<li><a>Using bun as a package manager</a></li>
<li><a>Using bun as a task runner</a></li>
<li><a>Creating a Discord bot with Bun</a><ul>
<li><a>Application Commands</a></li>
</ul>
</li>
<li><a>Using bun with Next.js</a></li>
<li><a>Using bun with single-page apps</a><ul>
<li><a>Using bun with Create React App</a></li>
</ul>
</li>
<li><a>Using bun with TypeScript</a><ul>
<li><a>Transpiling TypeScript with Bun</a></li>
<li><a>Adding Type Definitions</a></li>
</ul>
</li>
<li><a>Not implemented yet</a><ul>
<li><a>Limitations & intended usage</a></li>
<li><a>Upcoming breaking changes</a></li>
</ul>
</li>
<li><a>Configuration</a><ul>
<li><a>bunfig.toml</a></li>
<li><a>Loaders</a></li>
<li><a>CSS in JS</a><ul>
<li><a>When <code>platform</code> is <code>browser</code></a></li>
<li><a>When <code>platform</code> is <code>bun</code></a></li>
</ul>
</li>
<li><a>CSS Loader</a></li>
<li><a>CSS runtime</a></li>
<li><a>Frameworks</a></li>
</ul>
</li>
<li><a>Troubleshooting</a><ul>
<li><a>bun not running on an M1 (or Apple Silicon)</a></li>
<li><a>error: Unexpected</a></li>
<li><a>Unzip is required</a></li>
<li><a>Debian / Ubuntu / Mint</a></li>
<li><a>RedHat / CentOS / Fedora</a></li>
<li><a>Arch / Manjaro</a></li>
<li><a>OpenSUSE</a></li>
<li><a>bun install is stuck</a></li>
</ul>
</li>
<li><a>Reference</a><ul>
<li><a><code>bun install</code></a></li>
<li><a>Configuring bun install with <code>bunfig.toml</code></a></li>
<li><a>Configuring with environment variables</a></li>
<li><a>Platform-specific dependencies?</a></li>
<li><a>Peer dependencies?</a></li>
<li><a>Lockfile</a></li>
<li><a>Why is it binary?</a></li>
<li><a>How do I inspect it?</a></li>
<li><a>What does the lockfile store?</a></li>
<li><a>Why is it fast?</a></li>
<li><a>Cache</a></li>
<li><a>npm registry metadata</a></li>
<li><a><code>bun run</code></a></li>
<li><a><code>bun create</code></a></li>
<li><a>Usage</a></li>
<li><a>Local templates</a></li>
<li><a>Flags</a></li>
<li><a>Publishing a new template</a></li>
<li><a>Testing your new template</a></li>
<li><a>Config</a></li>
<li><a>How <code>bun create</code> works</a></li>
<li><a><code>bun bun</code></a></li>
<li><a>Why bundle?</a></li>
<li><a>What is <code>.bun</code>?</a></li>
<li><a>Position-independent code</a></li>
<li><a>Where is the code?</a></li>
<li><a>Advanced</a></li>
<li><a>What is the module ID hash?</a></li>
<li><a><code>bun upgrade</code></a></li>
<li><a>Canary builds</a></li>
<li><a><code>bun completions</code></a></li>
</ul>
</li>
<li><a><code>Bun.serve</code> - fast HTTP server</a><ul>
<li><a>Usage</a></li>
<li><a>Error handling</a></li>
</ul>
</li>
<li><a><code>Bun.write</code> – optimizing I/O</a></li>
<li><a>bun:sqlite (SQLite3 module)</a><ul>
<li><a>bun:sqlite Benchmark</a></li>
<li><a>Getting started with bun:sqlite</a></li>
<li><a><code>Database</code></a></li>
<li><a>Database.prototype.query</a></li>
<li><a>Database.prototype.prepare</a></li>
<li><a>Database.prototype.exec & Database.prototype.run</a></li>
<li><a>Database.prototype.transaction</a></li>
<li><a>Database.prototype.serialize</a></li>
<li><a>Database.prototype.loadExtension</a></li>
<li><a>Statement</a></li>
<li><a>Statement.all</a></li>
<li><a>Statement.values</a></li>
<li><a>Statement.get</a></li>
<li><a>Statement.run</a></li>
<li><a>Statement.finalize</a></li>
<li><a>Statement.toString()</a></li>
<li><a>Datatypes</a></li>
<li><a><code>bun:ffi</code> (Foreign Functions Interface)</a></li>
<li><a>Low-overhead FFI</a></li>
<li><a>Usage</a></li>
<li><a>Supported FFI types (<code>FFIType</code>)</a></li>
<li><a>Strings (<code>CString</code>)</a><ul>
<li><a>Returning a string</a></li>
</ul>
</li>
<li><a>Function pointers (<code>CFunction</code>)</a></li>
<li><a>Pointers</a><ul>
<li><a>Passing a pointer</a></li>
<li><a>Reading pointers</a></li>
<li><a>Not implemented yet</a></li>
</ul>
</li>
<li><a>Node-API (napi)</a></li>
<li><a><code>Bun.Transpiler</code></a></li>
<li><a><code>Bun.Transpiler.transformSync</code></a></li>
<li><a><code>Bun.Transpiler.transform</code></a></li>
<li><a><code>Bun.Transpiler.scan</code></a></li>
<li><a><code>Bun.Transpiler.scanImports</code></a></li>
</ul>
</li>
<li><a>Environment variables</a></li>
<li><a>Credits</a></li>
<li><a>License</a></li>
<li><a>Developing bun</a><ul>
<li><a>VSCode Dev Container (Linux)</a></li>
<li><a>MacOS</a></li>
<li><a>Build bun (macOS)</a></li>
<li><a>Verify it worked (macOS)</a></li>
<li><a>Troubleshooting (macOS)</a></li>
</ul>
</li>
<li><a>vscode-zig</a></li>
</ul>
Using bun.js - a new JavaScript runtime environment
bun.js focuses on performance, developer experience and compatibility with the JavaScript ecosystem.
```ts
// http.ts
export default {
port: 3000,
fetch(request: Request) {
return new Response("Hello World");
},
};
// bun ./http.ts
```
| Requests per second | OS | CPU | bun version |
| ---------------------------------------------------------------------- | ----- | ------------------------------ | ----------- |
| <a>260,000</a> | macOS | Apple Silicon M1 Max | 0.0.76 |
| <a>160,000</a> | Linux | AMD Ryzen 5 3600 6-Core 2.2ghz | 0.0.76 |
Measured with <a target="_blank">http_load_test</a> by running:
```bash
./http_load_test 20 127.0.0.1 3000
```
bun.js prefers Web API compatibility instead of designing new APIs when possible. bun.js also implements some Node.js APIs.
<ul>
<li>TypeScript & JSX support is built-in, powered by Bun's JavaScript transpiler</li>
<li>ESM & CommonJS modules are supported (internally, bun.js uses ESM)</li>
<li>Many npm packages "just work" with bun.js (when they use few/no node APIs)</li>
<li>tsconfig.json <code>"paths"</code> is natively supported, along with <code>"exports"</code> in package.json</li>
<li><code>fs</code>, <code>path</code>, and <code>process</code> from Node are partially implemented</li>
<li>Web APIs like <a><code>fetch</code></a>, <a><code>Response</code></a>, <a><code>URL</code></a> and more are built-in</li>
<li><a><code>HTMLRewriter</code></a> makes it easy to transform HTML in bun.js</li>
<li>Starts <a>4x faster than Node</a> (try it yourself)</li>
<li><code>.env</code> files automatically load into <code>process.env</code> and <code>Bun.env</code></li>
<li>top level await</li>
</ul>
The runtime uses JavaScriptCore, the JavaScript engine powering WebKit and Safari. Some web APIs like <a><code>Headers</code></a> and <a><code>URL</code></a> directly use <a>Safari's implementation</a>.
<code>cat</code> clone that runs <a>2x faster than GNU cat</a> for large files on Linux
```js
// cat.js
import { resolve } from "path";
import { write, stdout, file, argv } from "bun";
const path = resolve(argv.at(-1));
await write(
// stdout is a Blob
stdout,
// file(path) returns a Blob - https://developer.mozilla.org/en-US/docs/Web/API/Blob
file(path)
);
// bun ./cat.js ./path-to-file
```
Server-side render React:
```js
// requires Bun v0.1.0 or later
// react-ssr.tsx
import { renderToReadableStream } from "react-dom/server";
const dt = new Intl.DateTimeFormat();
export default {
port: 3000,
async fetch(request: Request) {
return new Response(
await renderToReadableStream(
Hello World
Hello from React!
The date is {dt.format(new Date())}
)
);
},
};
// bun react-ssr.tsx
```
There are some more examples in the <a>examples</a> folder.
PRs adding more examples are very welcome!
Types for bun.js (editor autocomplete)
The best docs right now are the TypeScript types in the <a><code>bun-types</code></a> npm package. A docs site is coming soon.
To get autocomplete for bun.js types in your editor,
<ol>
<li>Install the <code>bun-types</code> npm package:</li>
</ol>
```bash
yarn/npm/pnpm work too, "bun-types" is an ordinary npm package
bun add bun-types
```
<ol>
<li>Add this to your <code>tsconfig.json</code> or <code>jsconfig.json</code>:</li>
</ol>
<code>jsonc
{
"compilerOptions": {
"lib": ["ESNext"],
"module": "esnext",
"target": "esnext",
// "bun-types" is the important part
"types": ["bun-types"]
}
}</code>
You can also <a>view the types here</a>.
Fast paths for Web APIs
bun.js has fast paths for common use cases that make Web APIs live up to the performance demands of servers and CLIs.
<code>Bun.file(path)</code> returns a <a><code>Blob</code></a> that represents a lazily-loaded file.
When you pass a file blob to <code>Bun.write</code>, Bun automatically uses a faster system call:
<code>js
const blob = Bun.file("input.txt");
await Bun.write("output.txt", blob);</code>
On Linux, this uses the <a><code>copy_file_range</code></a> syscall and on macOS, this becomes <code>clonefile</code> (or <a><code>fcopyfile</code></a>).
<code>Bun.write</code> also supports <a><code>Response</code></a> objects. It automatically converts to a <a><code>Blob</code></a>.
<code>js
// Eventually, this will stream the response to disk but today it buffers
await Bun.write("index.html", await fetch("https://example.com"));</code>
Using bun as a package manager
On Linux, <code>bun install</code> tends to install packages 20x - 100x faster than <code>npm install</code>. On macOS, it’s more like 4x - 80x.
To install packages from package.json:
<code>bash
bun install</code>
To add or remove packages from package.json:
<code>bash
bun remove react
bun add preact</code>
<strong>For Linux users</strong>: <code>bun install</code> needs Linux Kernel 5.6 or higher to work well
The minimum Linux Kernel version is 5.1. If you're on Linux kernel 5.1 - 5.5, `bun install` should still work, but HTTP requests will be slow due to a lack of support for io_uring's `connect()` operation.
If you're using Ubuntu 20.04, here's how to install a [newer kernel](https://wiki.ubuntu.com/Kernel/LTSEnablementStack):
```bash
# If this returns a version >= 5.6, you don't need to do anything
uname -r
# Install the official Ubuntu hardware enablement kernel
sudo apt install --install-recommends linux-generic-hwe-20.04
```
Using bun as a task runner
Instead of waiting 170ms for your npm client to start for each task, you wait 6ms for bun.
To use bun as a task runner, run <code>bun run</code> instead of <code>npm run</code>.
```bash
Instead of "npm run clean"
bun run clean
This also works
bun clean
```
Assuming a package.json with a <code>"clean"</code> command in <code>"scripts"</code>:
<code>json
{
"name": "myapp",
"scripts": {
"clean": "rm -rf dist out node_modules"
}
}</code>
Creating a Discord bot with Bun
Application Commands
<blockquote>
Application commands are native ways to interact with apps in the Discord client. There are 3 types of commands accessible in different interfaces: the chat input, a message's context menu (top-right menu or right-clicking in a message), and a user's context menu (right-clicking on a user).
</blockquote>
To get started you can use the interactions template:
<code>bash
bun create discord-interactions my-interactions-bot
cd my-interactions-bot</code>
If you don't have a Discord bot/application yet, you can create one <a>here (https://discord.com/developers/applications/me)</a>.
Invite bot to your server by visiting <code>https://discord.com/api/oauth2/authorize?client_id=<your_application_id>&scope=bot%20applications.commands</code>
Afterwards you will need to get your bot's token, public key, and application id from the application page and put them into <code>.env.example</code> file
Then you can run the http server that will handle your interactions:
```bash
bun install
mv .env.example .env
bun run.js # listening on port 1337
```
Discord does not accept an insecure HTTP server, so you will need to provide an SSL certificate or put the interactions server behind a secure reverse proxy. For development, you can use ngrok/cloudflare tunnel to expose local ports as secure URL.
Using bun with Next.js
To create a new Next.js app with bun:
<code>bash
bun create next ./app
cd app
bun dev # start dev server</code>
To use an existing Next.js app with bun:
<code>bash
bun add bun-framework-next
echo "framework = 'next'" > bunfig.toml
bun bun # bundle dependencies
bun dev # start dev server</code>
Many of Next.js’ features are supported, but not all.
Here’s what doesn’t work yet:
<ul>
<li><code>getStaticPaths</code></li>
<li>same-origin <code>fetch</code> inside of <code>getStaticProps</code> or <code>getServerSideProps</code></li>
<li>locales, zones, <code>assetPrefix</code> (workaround: change <code>--origin \"http://localhost:3000/assetPrefixInhere\"</code>)</li>
<li><code>next/image</code> is polyfilled to a regular <code><img src></code> tag.</li>
<li><code>proxy</code> and anything else in <code>next.config.js</code></li>
<li>API routes, middleware (middleware is easier to support, though! Similar SSR API)</li>
<li>styled-jsx (technically not Next.js, but often used with it)</li>
<li>React Server Components</li>
</ul>
When using Next.js, bun automatically reads configuration from <code>.env.local</code>, <code>.env.development</code> and <code>.env</code> (in that order). <code>process.env.NEXT_PUBLIC_</code> and <code>process.env.NEXT_</code> automatically are replaced via <code>--define</code>.
Currently, any time you import new dependencies from <code>node_modules</code>, you will need to re-run <code>bun bun --use next</code>. This will eventually be automatic.
Using bun with single-page apps
In your project folder root (where <code>package.json</code> is):
<code>bash
bun bun ./entry-point-1.js ./entry-point-2.jsx
bun</code>
By default, <code>bun</code> will look for any HTML files in the <code>public</code> directory and serve that. For browsers navigating to the page, the <code>.html</code> file extension is optional in the URL, and <code>index.html</code> will automatically rewrite for the directory.
Here are examples of routing from <code>public/</code> and how they’re matched:
| Dev Server URL | File Path |
|----------------|-----------|
| /dir | public/dir/index.html |
| / | public/index.html |
| /index | public/index.html |
| /hi | public/hi.html |
| /file | public/file.html |
| /font/Inter.woff2 | public/font/Inter.woff2 |
| /hello | public/index.html |
If <code>public/index.html</code> exists, it becomes the default page instead of a 404 page, unless that pathname has a file extension.
Using bun with Create React App
To create a new React app:
<code>bash
bun create react ./app
cd app
bun dev # start dev server</code>
To use an existing React app:
```bash
To enable React Fast Refresh, ensure it is installed
bun add -d react-refresh
Generate a bundle for your entry point(s)
bun bun ./src/index.js # jsx, tsx, ts also work. can be multiple files
Start the dev server
bun dev
```
From there, bun relies on the filesystem for mapping dev server paths to source files. All URL paths are relative to the project root (where <code>package.json</code> is located).
Here are examples of routing source code file paths:
| Dev Server URL | File Path (relative to cwd) |
| -------------------------- | --------------------------- |
| /src/components/Button.tsx | src/components/Button.tsx |
| /src/index.tsx | src/index.tsx |
| /pages/index.js | pages/index.js |
You do not need to include file extensions in <code>import</code> paths. CommonJS-style import paths without the file extension work.
You can override the public directory by passing <code>--public-dir="path-to-folder"</code>.
If no directory is specified and <code>./public/</code> doesn’t exist, bun will try <code>./static/</code>. If <code>./static/</code> does not exist, but won’t serve from a public directory. If you pass <code>--public-dir=./</code> bun will serve from the current directory, but it will check the current directory last instead of first.
Using bun with TypeScript
Transpiling TypeScript with Bun
TypeScript just works. There’s nothing to configure and nothing extra to install. If you import a <code>.ts</code> or <code>.tsx</code> file, bun will transpile it into JavaScript. bun also transpiles <code>node_modules</code> containing <code>.ts</code> or <code>.tsx</code> files. This is powered by bun’s TypeScript transpiler, so it’s fast.
bun also reads <code>tsconfig.json</code>, including <code>baseUrl</code> and <code>paths</code>.
Adding Type Definitions
To get TypeScript working with the global API, add <code>bun-types</code> to your project:
<code>sh
bun add -d bun-types</code>
And to the <code>types</code> field in your <code>tsconfig.json</code>:
<code>json
{
"compilerOptions": {
"types": ["bun-types"]
}
}</code>
Not implemented yet
bun is a project with an incredibly large scope and is still in its early days.
You can see <a>Bun's Roadmap</a>, but here are some additional things that are planned:
| Feature | In |
| ------------------------------------------------------------------------------------- | -------------- |
| Web Streams with Fetch API | bun.js |
| Web Streams with HTMLRewriter | bun.js |
| WebSocket Server | bun.js |
| Package hoisting that matches npm behavior | bun install |
| Source Maps (unbundled is supported) | JS Bundler |
| Source Maps | CSS |
| JavaScript Minifier | JS Transpiler |
| CSS Minifier | CSS |
| CSS Parser (it only bundles) | CSS |
| Tree-shaking | JavaScript |
| Tree-shaking | CSS |
| <a><code>extends</code></a> in tsconfig.json | TS Transpiler |
| <a>TypeScript Decorators</a> | TS Transpiler |
| <code>@jsxPragma</code> comments | JS Transpiler |
| Sharing <code>.bun</code> files | bun |
| Dates & timestamps | TOML parser |
| <a>Hash components for Fast Refresh</a> | JSX Transpiler |
JS Transpiler == JavaScript Transpiler
TS Transpiler == TypeScript Transpiler
Package manager == <code>bun install</code>
bun.js == bun’s JavaScriptCore integration that executes JavaScript. Similar to how Node.js & Deno embed V8.
Limitations & intended usage
Today, bun is mostly focused on bun.js: the JavaScript runtime.
While you could use bun's bundler & transpiler separately to build for browsers or node, bun doesn't have a minifier or support tree-shaking yet. For production browser builds, you probably should use a tool like esbuild or swc.
Longer-term, bun intends to replace Node.js, Webpack, Babel, yarn, and PostCSS (in production).
Upcoming breaking changes
<ul>
<li>Bun's CLI flags will change to better support bun as a JavaScript runtime. They were chosen when bun was just a frontend development tool.</li>
<li>Bun's bundling format will change to accommodate production browser bundles and on-demand production bundling</li>
</ul>
Configuration
bunfig.toml
bunfig.toml is bun's configuration file.
It lets you load configuration from a file instead of passing flags to the CLI each time. The config file is loaded before CLI arguments are parsed, which means CLI arguments can override them.
Here is an example:
```toml
Set a default framework to use
By default, bun will look for an npm package like <code>bun-framework-${framework}</code>, followed by <code>${framework}</code>
framework = "next"
logLevel = "debug"
publicDir = "public"
external = ["jquery"]
[macros]
Remap any import like this:
import {graphql} from 'react-relay';
To:
import {graphql} from 'macro:bun-macro-relay';
react-relay = { "graphql" = "bun-macro-relay" }
[bundle]
saveTo = "node_modules.bun"
Don't need this if <code>framework</code> is set, but showing it here as an example anyway
entryPoints = ["./app/index.ts"]
[bundle.packages]
If you're bundling packages that do not actually live in a <code>node_modules</code> folder or do not have the full package name in the file path, you can pass this to bundle them anyway
"@bigapp/design-system" = true
[dev]
Change the default port from 3000 to 5000
Also inherited by Bun.serve
port = 5000
[define]
Replace any usage of "process.env.bagel" with the string <code>lox</code>.
The values are parsed as JSON, except single-quoted strings are supported and <code>'undefined'</code> becomes <code>undefined</code> in JS.
This will probably change in a future release to be just regular TOML instead. It is a holdover from the CLI argument parsing.
"process.env.bagel" = "'lox'"
[loaders]
When loading a .bagel file, run the JS parser
".bagel" = "js"
[debug]
When navigating to a blob: or src: link, open the file in your editor
If not, it tries $EDITOR or $VISUAL
If that still fails, it will try Visual Studio Code, then Sublime Text, then a few others
This is used by Bun.openInEditor()
editor = "code"
List of editors:
- "subl", "sublime"
- "vscode", "code"
- "textmate", "mate"
- "idea"
- "webstorm"
- "nvim", "neovim"
- "vim","vi"
- "emacs"
- "atom"
If you pass it a file path, it will open with the file path instead
It will recognize non-GUI editors, but I don't think it will work yet
```
TODO: list each property name
Loaders
A loader determines how to map imports & file extensions to transforms and output.
Currently, bun implements the following loaders:
| Input | Loader | Output |
| ----- | ----------------------------- | ------ |
| .js | JSX + JavaScript | .js |
| .jsx | JSX + JavaScript | .js |
| .ts | TypeScript + JavaScript | .js |
| .tsx | TypeScript + JSX + JavaScript | .js |
| .mjs | JavaScript | .js |
| .cjs | JavaScript | .js |
| .mts | TypeScript | .js |
| .cts | TypeScript | .js |
| .toml | TOML | .js |
| .css | CSS | .css |
| .env | Env | N/A |
| .* | file | string |
Everything else is treated as <code>file</code>. <code>file</code> replaces the import with a URL (or a path).
You can configure which loaders map to which extensions by passing <code>--loaders</code> to <code>bun</code>. For example:
<code>sh
bun --loader=.js:js</code>
This will disable JSX transforms for <code>.js</code> files.
CSS in JS
When importing CSS in JavaScript-like loaders, CSS is treated special.
By default, bun will transform a statement like this:
<code>js
import "../styles/global.css";</code>
When <code>platform</code> is <code>browser</code>
<code>js
globalThis.document?.dispatchEvent(
new CustomEvent("onimportcss", {
detail: "http://localhost:3000/styles/globals.css",
})
);</code>
An event handler for turning that into a <code><link></code> is automatically registered when HMR is enabled. That event handler can be turned off either in a framework’s <code>package.json</code> or by setting <code>globalThis["Bun_disableCSSImports"] = true;</code> in client-side code. Additionally, you can get a list of every .css file imported this way via <code>globalThis["__BUN"].allImportedStyles</code>.
When <code>platform</code> is <code>bun</code>
<code>js
//@import url("http://localhost:3000/styles/globals.css");</code>
Additionally, bun exposes an API for SSR/SSG that returns a flat list of URLs to css files imported. That function is <code>Bun.getImportedStyles()</code>.
<code>``ts
// This specifically is for "framework" in package.json when loaded via</code>bun dev<code>// This API needs to be changed somewhat to work more generally with Bun.js
// Initially, you could only use bun.js through</code>bun dev`
// and this API was created at that time
addEventListener("fetch", async (event: FetchEvent) => {
var route = Bun.match(event);
const App = await import("pages/_app");
// This returns all .css files that were imported in the line above.
// It’s recursive, so any file that imports a CSS file will be included.
const appStylesheets = bun.getImportedStyles();
// ...rest of code
});
```
This is useful for preventing flash of unstyled content.
CSS Loader
bun bundles <code>.css</code> files imported via <code>@import</code> into a single file. It doesn’t autoprefix or minify CSS today. Multiple <code>.css</code> files imported in one JavaScript file will <em>not</em> be bundled into one file. You’ll have to import those from a <code>.css</code> file.
This input:
<code>css
@import url("./hi.css");
@import url("./hello.css");
@import url("./yo.css");</code>
Becomes:
<code>css
/* hi.css */
/* ...contents of hi.css */
/* hello.css */
/* ...contents of hello.css */
/* yo.css */
/* ...contents of yo.css */</code>
CSS runtime
To support hot CSS reloading, bun inserts <code>@supports</code> annotations into CSS that tag which files a stylesheet is composed of. Browsers ignore this, so it doesn’t impact styles.
By default, bun’s runtime code automatically listens to <code>onimportcss</code> and will insert the <code>event.detail</code> into a <code><link rel="stylesheet" href={${event.detail}}></code> if there is no existing <code>link</code> tag with that stylesheet. That’s how bun’s equivalent of <code>style-loader</code> works.
Frameworks
<blockquote>
<strong>Warning</strong>
This will soon have breaking changes. It was designed when Bun was mostly a dev server and not a JavaScript runtime.
</blockquote>
Frameworks preconfigure bun to enable developers to use bun with their existing tooling.
Frameworks are configured via the <code>framework</code> object in the <code>package.json</code> of the framework (not in the application’s <code>package.json</code>):
Here is an example:
<code>json
{
"name": "bun-framework-next",
"version": "0.0.0-18",
"description": "",
"framework": {
"displayName": "Next.js",
"static": "public",
"assetPrefix": "_next/",
"router": {
"dir": ["pages", "src/pages"],
"extensions": [".js", ".ts", ".tsx", ".jsx"]
},
"css": "onimportcss",
"development": {
"client": "client.development.tsx",
"fallback": "fallback.development.tsx",
"server": "server.development.tsx",
"css": "onimportcss",
"define": {
"client": {
".env": "NEXT_PUBLIC_",
"defaults": {
"process.env.__NEXT_TRAILING_SLASH": "false",
"process.env.NODE_ENV": "\"development\"",
"process.env.__NEXT_ROUTER_BASEPATH": "''",
"process.env.__NEXT_SCROLL_RESTORATION": "false",
"process.env.__NEXT_I18N_SUPPORT": "false",
"process.env.__NEXT_HAS_REWRITES": "false",
"process.env.__NEXT_ANALYTICS_ID": "null",
"process.env.__NEXT_OPTIMIZE_CSS": "false",
"process.env.__NEXT_CROSS_ORIGIN": "''",
"process.env.__NEXT_STRICT_MODE": "false",
"process.env.__NEXT_IMAGE_OPTS": "null"
}
},
"server": {
".env": "NEXT_",
"defaults": {
"process.env.__NEXT_TRAILING_SLASH": "false",
"process.env.__NEXT_OPTIMIZE_FONTS": "false",
"process.env.NODE_ENV": "\"development\"",
"process.env.__NEXT_OPTIMIZE_IMAGES": "false",
"process.env.__NEXT_OPTIMIZE_CSS": "false",
"process.env.__NEXT_ROUTER_BASEPATH": "''",
"process.env.__NEXT_SCROLL_RESTORATION": "false",
"process.env.__NEXT_I18N_SUPPORT": "false",
"process.env.__NEXT_HAS_REWRITES": "false",
"process.env.__NEXT_ANALYTICS_ID": "null",
"process.env.__NEXT_CROSS_ORIGIN": "''",
"process.env.__NEXT_STRICT_MODE": "false",
"process.env.__NEXT_IMAGE_OPTS": "null",
"global": "globalThis",
"window": "undefined"
}
}
}
}
}
}</code>
Here are type definitions:
```ts
type Framework = Environment & {
// This changes what’s printed in the console on load
displayName?: string;
// This allows a prefix to be added (and ignored) to requests.
// Useful for integrating an existing framework that expects internal routes to have a prefix
// e.g. "_next"
assetPrefix?: string;
development?: Environment;
production?: Environment;
// The directory used for serving unmodified assets like fonts and images
// Defaults to "public" if exists, else "static", else disabled.
static?: string;
// "onimportcss" disables the automatic "onimportcss" feature
// If the framework does routing, you may want to handle CSS manually
// "facade" removes CSS imports from JavaScript files,
// and replaces an imported object with a proxy that mimics CSS module support without doing any class renaming.
css?: "onimportcss" | "facade";
// bun’s filesystem router
router?: Router;
};
type Define = {
// By passing ".env", bun will automatically load .env.local, .env.development, and .env if exists in the project root
// (in addition to the processes’ environment variables)
// When "*", all environment variables will be automatically injected into the JavaScript loader
// When a string like "NEXT_PUBLIC_", only environment variables starting with that prefix will be injected
".env": string | "*";
// These environment variables will be injected into the JavaScript loader
// These are the equivalent of Webpack’s resolve.alias and esbuild’s --define.
// Values are parsed as JSON, so they must be valid JSON. The only exception is '' is a valid string, to simplify writing stringified JSON in JSON.
// If not set, <code>process.env.NODE_ENV</code> will be transformed into "development".
defaults: Record;
};
type Environment = {
// This is a wrapper for the client-side entry point for a route.
// This allows frameworks to run initialization code on pages.
client: string;
// This is a wrapper for the server-side entry point for a route.
// This allows frameworks to run initialization code on pages.
server: string;
// This runs when "server" code fails to load due to an exception.
fallback: string;
// This is how environment variables and .env is configured.
define?: Define;
};
// bun’s filesystem router
// Currently, bun supports pages by either an absolute match or a parameter match.
// pages/index.tsx will be executed on navigation to "/" and "/index"
// pages/posts/[id].tsx will be executed on navigation to "/posts/123"
// Routes & parameters are automatically passed to <code>fallback</code> and <code>server</code>.
type Router = {
// This determines the folder to look for pages
dir: string[];
// These are the allowed file extensions for pages.
extensions?: string[];
};
```
To use a framework, you pass <code>bun bun --use package-name</code>.
Your framework’s <code>package.json</code> <code>name</code> should start with <code>bun-framework-</code>. This is so that people can type something like <code>bun bun --use next</code> and it will check <code>bun-framework-next</code> first. This is similar to how Babel plugins tend to start with <code>babel-plugin-</code>.
For developing frameworks, you can also do <code>bun bun --use ./relative-path-to-framework</code>.
If you’re interested in adding a framework integration, please reach out. There’s a lot here, and it’s not entirely documented yet.
Troubleshooting
bun not running on an M1 (or Apple Silicon)
If you see a message like this
<blockquote>
[1] 28447 killed bun create next ./test
</blockquote>
It most likely means you’re running bun’s x64 version on Apple Silicon. This happens if bun is running via Rosetta. Rosetta is unable to emulate AVX2 instructions, which bun indirectly uses.
The fix is to ensure you installed a version of bun built for Apple Silicon.
error: Unexpected
If you see an error like this:
It usually means the max number of open file descriptors is being explicitly set to a low number. By default, bun requests the max number of file descriptors available (which on macOS, is something like 32,000). But, if you previously ran into ulimit issues with, e.g., Chokidar, someone on The Internet may have advised you to run <code>ulimit -n 8096</code>.
That advice unfortunately <strong>lowers</strong> the hard limit to <code>8096</code>. This can be a problem in large repositories or projects with lots of dependencies. Chokidar (and other watchers) don’t seem to call <code>setrlimit</code>, which means they’re reliant on the (much lower) soft limit.
To fix this issue:
<ol>
<li>Remove any scripts that call <code>ulimit -n</code> and restart your shell.</li>
<li>Try again, and if the error still occurs, try setting <code>ulimit -n</code> to an absurdly high number, such as <code>ulimit -n 2147483646</code></li>
<li>Try again, and if that still doesn’t fix it, open an issue</li>
</ol>
Unzip is required
Unzip is required to install bun on Linux. You can use one of the following commands to install <code>unzip</code>:
Debian / Ubuntu / Mint
<code>sh
sudo apt install unzip</code>
RedHat / CentOS / Fedora
<code>sh
sudo dnf install unzip</code>
Arch / Manjaro
<code>sh
sudo pacman -S unzip</code>
OpenSUSE
<code>sh
sudo zypper install unzip</code>
bun install is stuck
Please run <code>bun install --verbose 2> logs.txt</code> and send them to me in bun's discord. If you're on Linux, it would also be helpful if you run <code>sudo perf trace bun install --silent</code> and attach the logs.
Reference
<code>bun install</code>
bun install is a fast package manager & npm client.
bun install can be configured via <code>bunfig.toml</code>, environment variables, and CLI flags.
Configuring bun install with <code>bunfig.toml</code>
<code>bunfig.toml</code> is searched for in the following paths on <code>bun install</code>, <code>bun remove</code>, and <code>bun add</code>:
<ol>
<li><code>$XDG_CONFIG_HOME/.bunfig.toml</code> or <code>$HOME/.bunfig.toml</code></li>
<li><code>./bunfig.toml</code></li>
</ol>
If both are found, the results are merged together.
Configuring with <code>bunfig.toml</code> is optional. bun tries to be zero configuration in general, but that's not always possible.
```toml
Using scoped packages with bun install
[install.scopes]
Scope name The value can be a URL string or an object
"@mybigcompany" = { token = "123456", url = "https://registry.mybigcompany.com" }
URL is optional and fallsback to the default registry
The "@" in the scope is optional
mybigcompany2 = { token = "123456" }
Environment variables can be referenced as a string that starts with $ and it will be replaced
mybigcompany3 = { token = "$npm_config_token" }
Setting username and password turns it into a Basic Auth header by taking base64("username:password")
mybigcompany4 = { username = "myusername", password = "$npm_config_password", url = "https://registry.yarnpkg.com/" }
You can set username and password in the registry URL. This is the same as above.
mybigcompany5 = "https://username:[email protected]/"
You can set a token for a registry URL:
mybigcompany6 = "https://:[email protected]/"
[install]
Default registry
can be a URL string or an object
registry = "https://registry.yarnpkg.com/"
as an object
registry = { url = "https://registry.yarnpkg.com/", token = "123456" }
Install for production? This is the equivalent to the "--production" CLI argument
production = false
Don't actually install
dryRun = true
Install optionalDependencies (default: true)
optional = true
Install local devDependencies (default: true)
dev = true
Install peerDependencies (default: false)
peer = false
When using <code>bun install -g</code>, install packages here
globalDir = "~/.bun/install/global"
When using <code>bun install -g</code>, link package bins here
globalBinDir = "~/.bun/bin"
cache-related configuration
[install.cache]
The directory to use for the cache
dir = "~/.bun/install/cache"
Don't load from the global cache.
Note: bun may still write to node_modules/.cache
disable = false
Always resolve the latest versions from the registry
disableManifest = false
Lockfile-related configuration
[install.lockfile]
Print a yarn v1 lockfile
Note: it does not load the lockfile, it just converts bun.lockb into a yarn.lock
print = "yarn"
Path to read bun.lockb from
path = "bun.lockb"
Path to save bun.lockb to
savePath = "bun.lockb"
Save the lockfile to disk
save = true
```
If it's easier to read as TypeScript types:
```ts
export interface Root {
install: Install;
}
export interface Install {
scopes: Scopes;
registry: Registry;
production: boolean;
dryRun: boolean;
optional: boolean;
dev: boolean;
peer: boolean;
globalDir: string;
globalBinDir: string;
cache: Cache;
lockfile: Lockfile;
logLevel: "debug" | "error" | "warn";
}
type Registry =
| string
| {
url?: string;
token?: string;
username?: string;
password?: string;
};
type Scopes = Record;
export interface Cache {
dir: string;
disable: boolean;
disableManifest: boolean;
}
export interface Lockfile {
print?: "yarn";
path: string;
savePath: string;
save: boolean;
}
```
Configuring with environment variables
Environment variables have a higher priority than <code>bunfig.toml</code>.
| Name | Description |
| -------------------------------- | ------------------------------------------------------------- |
| BUN_CONFIG_REGISTRY | Set an npm registry (default: <a>https://registry.npmjs.org</a>) |
| BUN_CONFIG_TOKEN | Set an auth token (currently does nothing) |
| BUN_CONFIG_LOCKFILE_SAVE_PATH | File path to save the lockfile to (default: bun.lockb) |
| BUN_CONFIG_YARN_LOCKFILE | Save a Yarn v1-style yarn.lock |
| BUN_CONFIG_LINK_NATIVE_BINS | Point <code>bin</code> in package.json to a platform-specific dependency |
| BUN_CONFIG_SKIP_SAVE_LOCKFILE | Don’t save a lockfile |
| BUN_CONFIG_SKIP_LOAD_LOCKFILE | Don’t load a lockfile |
| BUN_CONFIG_SKIP_INSTALL_PACKAGES | Don’t install any packages |
bun always tries to use the fastest available installation method for the target platform. On macOS, that’s <code>clonefile</code> and on Linux, that’s <code>hardlink</code>. You can change which installation method is used with the <code>--backend</code> flag. When unavailable or on error, <code>clonefile</code> and <code>hardlink</code> fallsback to a platform-specific implementation of copying files.
bun stores installed packages from npm in <code>~/.bun/install/cache/${name}@${version}</code>. Note that if the semver version has a <code>build</code> or a <code>pre</code> tag, it is replaced with a hash of that value instead. This is to reduce the chances of errors from long file paths, but unfortunately complicates figuring out where a package was installed on disk.
When the <code>node_modules</code> folder exists, before installing, bun checks if the <code>"name"</code> and <code>"version"</code> in <code>package/package.json</code> in the expected node_modules folder matches the expected <code>name</code> and <code>version</code>. This is how it determines whether it should install. It uses a custom JSON parser which stops parsing as soon as it finds <code>"name"</code> and <code>"version"</code>.
When a <code>bun.lockb</code> doesn’t exist or <code>package.json</code> has changed dependencies, tarballs are downloaded & extracted eagerly while resolving.
When a <code>bun.lockb</code> exists and <code>package.json</code> hasn’t changed, bun downloads missing dependencies lazily. If the package with a matching <code>name</code> & <code>version</code> already exists in the expected location within <code>node_modules</code>, bun won’t attempt to download the tarball.
Platform-specific dependencies?
bun stores normalized <code>cpu</code> and <code>os</code> values from npm in the lockfile, along with the resolved packages. It skips downloading, extracting, and installing packages disabled for the current target at runtime. This means the lockfile won’t change between platforms/architectures even if the packages ultimately installed do change.
Peer dependencies?
Peer dependencies are handled similarly to yarn. <code>bun install</code> does not automatically install peer dependencies and will try to choose an existing dependency.
Lockfile
<code>bun.lockb</code> is bun’s binary lockfile format.
Why is it binary?
In a word: Performance. bun’s lockfile saves & loads incredibly quickly, and saves a lot more data than what is typically inside lockfiles.
How do I inspect it?
For now, the easiest thing is to run <code>bun install -y</code>. That prints a Yarn v1-style yarn.lock file.
What does the lockfile store?
Packages, metadata for those packages, the hoisted install order, dependencies for each package, what packages those dependencies resolved to, an integrity hash (if available), what each package was resolved to and which version (or equivalent).
Why is it fast?
It uses linear arrays for all data. <a>Packages</a> are referenced by an auto-incrementing integer ID or a hash of the package name. Strings longer than 8 characters are de-duplicated. Prior to saving on disk, the lockfile is garbage-collected & made deterministic by walking the package tree and cloning the packages in dependency order.
Cache
To delete the cache:
<code>bash
rm -rf ~/.bun/install/cache</code>
npm registry metadata
bun uses a binary format for caching NPM registry responses. This loads much faster than JSON and tends to be smaller on disk.
You will see these files in <code>~/.bun/install/cache/*.npm</code>. The filename pattern is <code>${hash(packageName)}.npm</code>. It’s a hash so that extra directories don’t need to be created for scoped packages.
bun’s usage of <code>Cache-Control</code> ignores <code>Age</code>. This improves performance, but means bun may be about 5 minutes out of date to receive the latest package version metadata from npm.
<code>bun run</code>
<code>bun run</code> is a fast <code>package.json</code> script runner. Instead of waiting 170ms for your npm client to start every time, you wait 6ms for bun.
By default, <code>bun run</code> prints the script that will be invoked:
<code>bash
bun run clean
$ rm -rf node_modules/.cache dist</code>
You can disable that with <code>--silent</code>
<code>bash
bun run --silent clean</code>
<code>bun run ${script-name}</code> runs the equivalent of <code>npm run script-name</code>. For example, <code>bun run dev</code> runs the <code>dev</code> script in <code>package.json</code>, which may sometimes spin up non-bun processes.
<code>bun run ${javascript-file.js}</code> will run it with bun, as long as the file doesn't have a node shebang.
To print a list of <code>scripts</code>, <code>bun run</code> without additional args:
```bash
This command
bun run
Prints this
hello-create-react-app scripts:
bun run start
react-scripts start
bun run build
react-scripts build
bun run test
react-scripts test
bun run eject
react-scripts eject
4 scripts
```
<code>bun run</code> automatically loads environment variables from <code>.env</code> into the shell/task. <code>.env</code> files are loaded with the same priority as the rest of bun, so that means:
<ol>
<li><code>.env.local</code> is first</li>
<li>if (<code>$NODE_ENV</code> === <code>"production"</code>) <code>.env.production</code> else <code>.env.development</code></li>
<li><code>.env</code></li>
</ol>
If something is unexpected there, you can run <code>bun run env</code> to get a list of environment variables.
The default shell it uses is <code>bash</code>, but if that’s not found, it tries <code>sh</code> and if still not found, it tries <code>zsh</code>. This is not configurable right now, but if you care, file an issue.
<code>bun run</code> automatically adds any parent <code>node_modules/.bin</code> to <code>$PATH</code> and if no scripts match, it will load that binary instead. That means you can run executables from packages, too.
```bash
If you use Relay
bun run relay-compiler
You can also do this, but:
- It will only lookup packages in <code>node_modules/.bin</code> instead of <code>$PATH</code>
- It will start bun’s dev server if the script name doesn’t exist (<code>bun</code> starts the dev server by default)
bun relay-compiler
```
To pass additional flags through to the task or executable, there are two ways:
```bash
Explicit: include "--" and anything after will be added. This is the recommended way because it is more reliable.
bun run relay-compiler -- -–help
Implicit: if you do not include "--", anything <em>after</em> the script name will be passed through
bun flags are parsed first, which means e.g. <code>bun run relay-compiler --help</code> will print bun’s help instead of relay-compiler’s help.
bun run relay-compiler --schema foo.graphql
```
<code>bun run</code> supports lifecycle hooks like <code>post${task}</code> and <code>pre{task}</code>. If they exist, they will run, matching the behavior of npm clients. If the <code>pre${task}</code> fails, the next task will not be run. There is currently no flag to skip these lifecycle tasks if they exist, if you want that file an issue.
<code>bun create</code>
<code>bun create</code> is a fast way to create a new project from a template.
At the time of writing, <code>bun create react app</code> runs ~11x faster on my local computer than <code>yarn create react-app app</code>. <code>bun create</code> currently does no caching (though your npm client does)
Usage
Create a new Next.js project:
<code>bash
bun create next ./app</code>
Create a new React project:
<code>bash
bun create react ./app</code>
Create from a GitHub repo:
<code>bash
bun create ahfarmer/calculator ./app</code>
To see a list of examples, run:
<code>bash
bun create</code>
Format:
<code>bash
bun create github-user/repo-name destination
bun create local-example-or-remote-example destination
bun create /absolute/path/to-template-folder destination
bun create https://github.com/github-user/repo-name destination
bun create github.com/github-user/repo-name destination</code>
Note: you don’t need <code>bun create</code> to use bun. You don’t need any configuration at all. This command exists to make it a little easier.
Local templates
If you have your own boilerplate you prefer using, copy it into <code>$HOME/.bun-create/my-boilerplate-name</code>.
Before checking bun’s examples folder, <code>bun create</code> checks for a local folder matching the input in:
<ul>
<li><code>$BUN_CREATE_DIR/</code></li>
<li><code>$HOME/.bun-create/</code></li>
<li><code>$(pwd)/.bun-create/</code></li>
</ul>
If a folder exists in any of those folders with the input, bun will use that instead of a remote template.
To create a local template, run:
<code>bash
mkdir -p $HOME/.bun-create/new-template-name
echo '{"name":"new-template-name"}' > $HOME/.bun-create/new-template-name/package.json</code>
This lets you run:
<code>bash
bun create new-template-name ./app</code>
Now your new template should appear when you run:
<code>bash
bun create</code>
Warning: unlike with remote templates, <strong>bun will delete the entire destination folder if it already exists.</strong>
Flags
| Flag | Description |
| ------------ | -------------------------------------- |
| --npm | Use <code>npm</code> for tasks & install |
| --yarn | Use <code>yarn</code> for tasks & install |
| --pnpm | Use <code>pnpm</code> for tasks & install |
| --force | Overwrite existing files |
| --no-install | Skip installing <code>node_modules</code> & tasks |
| --no-git | Don’t initialize a git repository |
| --open | Start & open in-browser after finish |
| Environment Variables | Description |
| --------------------- | ------------------------------------------------------------------------------------------------------ |
| GITHUB_API_DOMAIN | If you’re using a GitHub enterprise or a proxy, you can change what the endpoint requests to GitHub go |
| GITHUB_API_TOKEN | This lets <code>bun create</code> work with private repositories or if you get rate-limited |
By default, <code>bun create</code> will cancel if there are existing files it would overwrite and it's a remote template. You can pass <code>--force</code> to disable this behavior.
Publishing a new template
Clone this repository and a new folder in <code>examples/</code> with your new template. The <code>package.json</code> must have a <code>name</code> that starts with <code>@bun-examples/</code>. Do not worry about publishing it, that will happen automatically after the PR is merged.
Make sure to include a <code>.gitignore</code> that includes <code>node_modules</code> so that <code>node_modules</code> aren’t checked in to git when people download the template.
Testing your new template
To test your new template, add it as a local template or pass the absolute path.
<code>bash
bun create /path/to/my/new/template destination-dir</code>
Warning: <strong>This will always delete everything in destination-dir</strong>.
Config
The <code>bun-create</code> section of <code>package.json</code> is automatically removed from the <code>package.json</code> on disk. This lets you add create-only steps without waiting for an extra package to install.
There are currently two options:
<ul>
<li><code>postinstall</code></li>
<li><code>preinstall</code></li>
</ul>
They can be an array of strings or one string. An array of steps will be executed in order.
Here is an example:
<code>json
{
"name": "@bun-examples/next",
"version": "0.0.31",
"main": "index.js",
"dependencies": {
"next": "11.1.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-is": "^17.0.2"
},
"devDependencies": {
"@types/react": "^17.0.19",
"bun-framework-next": "^0.0.0-21",
"typescript": "^4.3.5"
},
"bun-create": {
"postinstall": ["bun bun --use next"]
}
}</code>
By default, all commands run inside the environment exposed by the auto-detected npm client. This incurs a significant performance penalty, something like 150ms spent waiting for the npm client to start on each invocation.
Any command that starts with <code>"bun "</code> will be run without npm, relying on the first <code>bun</code> binary in <code>$PATH</code>.
How <code>bun create</code> works
When you run <code>bun create ${template} ${destination}</code>, here’s what happens:
IF remote template
<ol>
<li>GET <code>registry.npmjs.org/@bun-examples/${template}/latest</code> and parse it</li>
<li>GET <code>registry.npmjs.org/@bun-examples/${template}/-/${template}-${latestVersion}.tgz</code></li>
<li>
Decompress & extract <code>${template}-${latestVersion}.tgz</code> into <code>${destination}</code>
</li>
<li>
If there are files that would overwrite, warn and exit unless <code>--force</code> is passed
</li>
</ol>
IF GitHub repo
<ol>
<li>Download the tarball from GitHub’s API</li>
<li>
Decompress & extract into <code>${destination}</code>
</li>
<li>
If there are files that would overwrite, warn and exit unless <code>--force</code> is passed
</li>
</ol>
ELSE IF local template
<ol>
<li>Open local template folder</li>
<li>Delete destination directory recursively</li>
<li>
Copy files recursively using the fastest system calls available (on macOS <code>fcopyfile</code> and Linux, <code>copy_file_range</code>). Do not copy or traverse into <code>node_modules</code> folder if exists (this alone makes it faster than <code>cp</code>)
</li>
<li>
Parse the <code>package.json</code> (again!), update <code>name</code> to be <code>${basename(destination)}</code>, remove the <code>bun-create</code> section from the <code>package.json</code> and save the updated <code>package.json</code> to disk.
</li>
<li>IF Next.js is detected, add <code>bun-framework-next</code> to the list of dependencies</li>
<li>IF Create React App is detected, add the entry point in /src/index.{js,jsx,ts,tsx} to <code>public/index.html</code></li>
<li>IF Relay is detected, add <code>bun-macro-relay</code> so that Relay works</li>
<li>Auto-detect the npm client, preferring <code>pnpm</code>, <code>yarn</code> (v1), and lastly <code>npm</code></li>
<li>Run any tasks defined in <code>"bun-create": { "preinstall" }</code> with the npm client</li>
<li>Run <code>${npmClient} install</code> unless <code>--no-install</code> is passed OR no dependencies are in package.json</li>
<li>Run any tasks defined in <code>"bun-create": { "preinstall" }</code> with the npm client</li>
<li>
Run <code>git init; git add -A .; git commit -am "Initial Commit";</code>
</li>
<li>
Rename <code>gitignore</code> to <code>.gitignore</code>. NPM automatically removes <code>.gitignore</code> files from appearing in packages.
</li>
<li>If there are dependencies, this runs in a separate thread concurrently while node_modules are being installed</li>
<li>
Using libgit2 if available was tested and performed 3x slower in microbenchmarks
</li>
<li>
Done
</li>
</ol>
<code>misctools/publish-examples.js</code> publishes all examples to npm.
<code>bun bun</code>
Run <code>bun bun ./path-to.js</code> to generate a <code>node_modules.bun</code> file containing all imported dependencies (recursively).
Why bundle?
<ul>
<li>For browsers, loading entire apps without bundling dependencies is typically slow. With a fast bundler & transpiler, the bottleneck eventually becomes the web browser’s ability to run many network requests concurrently. There are many workarounds for this. <code><link rel="modulepreload"></code>, HTTP/3, etc., but none are more effective than bundling. If you have reproducible evidence to the contrary, feel free to submit an issue. It would be better if bundling wasn’t necessary.</li>
<li>On the server, bundling reduces the number of filesystem lookups to load JavaScript. While filesystem lookups are faster than HTTP requests, there’s still overhead.</li>
</ul>
What is <code>.bun</code>?
Note: <a>This format may change soon</a>
The <code>.bun</code> file contains:
<ul>
<li>all the bundled source code</li>
<li>all the bundled source code metadata</li>
<li>project metadata & configuration</li>
</ul>
Here are some of the questions <code>.bun</code> files answer:
<ul>
<li>when I import <code>react/index.js</code>, where in the <code>.bun</code> is the code for that? (not resolving, just the code)</li>
<li>what modules of a package are used?</li>
<li>what framework is used? (e.g., Next.js)</li>
<li>where is the routes directory?</li>
<li>how big is each imported dependency?</li>
<li>what is the hash of the bundle’s contents? (for etags)</li>
<li>what is the name & version of every npm package exported in this bundle?</li>
<li>what modules from which packages are used in this project? ("project" is defined as all the entry points used to generate the .bun)</li>
</ul>
All in one file.
It’s a little like a build cache, but designed for reuse across builds.
Position-independent code
From a design perspective, the most important part of the <code>.bun</code> format is how code is organized. Each module is exported by a hash like this:
<code>js
// preact/dist/preact.module.js
export var $eb6819b = $$m({
"preact/dist/preact.module.js": (module, exports) => {
var n, l, u, i, t, o, r, f, e = {}, c = [], s = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;
// ... rest of code</code>
This makes bundled modules <a>position-independent</a>. In theory, one could import only the exact modules in-use without reparsing code and without generating a new bundle. One bundle can dynamically become many bundles comprising only the modules in use on the webpage. Thanks to the metadata with the byte offsets, a web server can send each module to browsers <a>zero-copy</a> using <a>sendfile</a>. bun itself is not quite this smart yet, but these optimizations would be useful in production and potentially very useful for React Server Components.
To see the schema inside, have a look at <a><code>JavascriptBundleContainer</code></a>. You can find JavaScript bindings to read the metadata in <a>src/api/schema.js</a>. This is not really an API yet. It’s missing the part where it gets the binary data from the bottom of the file. Someday, I want this to be usable by other tools too.
Where is the code?
<code>.bun</code> files are marked as executable.
To print out the code, run <code>./node_modules.bun</code> in your terminal or run <code>bun ./path-to-node_modules.bun</code>.
Here is a copy-pastable example:
<code>bash
./node_modules.bun > node_modules.js</code>
This works because every <code>.bun</code> file starts with this:
```bash
!/usr/bin/env bun
```
To deploy to production with bun, you’ll want to get the code from the <code>.bun</code> file and stick that somewhere your web server can find it (or if you’re using Vercel or a Rails app, in a <code>public</code> folder).
Note that <code>.bun</code> is a binary file format, so just opening it in VSCode or vim might render strangely.
Advanced
By default, <code>bun bun</code> only bundles external dependencies that are <code>import</code>ed or <code>require</code>d in either app code or another external dependency. An "external dependency" is defined as, "A JavaScript-like file that has <code>/node_modules/</code> in the resolved file path and a corresponding <code>package.json</code>".
To force bun to bundle packages which are not located in a <code>node_modules</code> folder (i.e., the final, resolved path following all symlinks), add a <code>bun</code> section to the root project’s <code>package.json</code> with <code>alwaysBundle</code> set to an array of package names to always bundle. Here’s an example:
<code>json
{
"name": "my-package-name-in-here",
"bun": {
"alwaysBundle": ["@mybigcompany/my-workspace-package"]
}
}</code>
Bundled dependencies are not eligible for Hot Module Reloading. The code is served to browsers & bun.js verbatim. But, in the future, it may be sectioned off into only parts of the bundle being used. That’s possible in the current version of the <code>.bun</code> file (so long as you know which files are necessary), but it’s not implemented yet. Longer-term, it will include all <code>import</code> and <code>export</code> of each module inside.
What is the module ID hash?
The <code>$eb6819b</code> hash used here:
<code>js
export var $eb6819b = $$m({</code>
Is generated like this:
<ol>
<li>Murmur3 32-bit hash of <code>[email protected]</code>. This is the hash uniquely identifying the npm package.</li>
<li>Wyhash 64 of the <code>package.hash</code> + <code>package_path</code>. <code>package_path</code> means "relative to the root of the npm package, where is the module imported?". For example, if you imported <code>react/jsx-dev-runtime.js</code>, the <code>package_path</code> is <code>jsx-dev-runtime.js</code>. <code>react-dom/cjs/react-dom.development.js</code> would be <code>cjs/react-dom.development.js</code></li>
<li>Truncate the hash generated above to a <code>u32</code></li>
</ol>
The implementation details of this module ID hash will vary between versions of bun. The important part is the metadata contains the module IDs, the package paths, and the package hashes, so it shouldn’t really matter in practice if other tooling wants to make use of any of this.
<code>bun upgrade</code>
To upgrade bun, run <code>bun upgrade</code>.
It automatically downloads the latest version of bun and overwrites the currently-running version.
This works by checking the latest version of bun in <a>bun-releases-for-updater</a> and unzipping it using the system-provided <code>unzip</code> library (so that Gatekeeper works on macOS)
If for any reason you run into issues, you can also use the curl install script:
<code>bash
curl https://bun.sh/install | bash</code>
It will still work when bun is already installed.
bun is distributed as a single binary file, so you can also do this manually:
<ul>
<li>Download the latest version of bun for your platform in <a>bun-releases-for-updater</a> (<code>darwin</code> == macOS)</li>
<li>Unzip the folder</li>
<li>Move the <code>bun</code> binary to <code>~/.bun/bin</code> (or anywhere)</li>
</ul>
Canary builds
<a>Canary</a> builds are generated on every commit. At the time of writing, only Linux x64 & Linux arm64 are generated.
To install a <a>canary</a> build of bun, run:
<code>bash
bun upgrade --canary</code>
This flag is not persistent (though that might change in the future). If you want to always run the canary build of bun, set the <code>BUN_CANARY</code> environment variable to <code>1</code> in your shell's startup script.
This will download the release zip from https://github.com/oven-sh/bun/releases/tag/canary.
To revert to the latest published version of bun, run:
<code>bash
bun upgrade</code>
<code>bun completions</code>
This command installs completions for <code>zsh</code> and/or <code>fish</code>. It runs automatically on every <code>bun upgrade</code> and on install. It reads from <code>$SHELL</code> to determine which shell to install for. It tries several common shell completion directories for your shell and OS.
If you want to copy the completions manually, run <code>bun completions > path-to-file</code>. If you know the completions directory to install them to, run <code>bun completions /path/to/directory</code>.
<code>Bun.serve</code> - fast HTTP server
For a hello world HTTP server that writes "bun!", <code>Bun.serve</code> serves about 2.5x more requests per second than node.js on Linux:
| Requests per second | Runtime |
| ------------------- | ------- |
| ~64,000 | Node 16 |
| ~160,000 | Bun |
Bigger is better
Code
Bun:
```ts
Bun.serve({
fetch(req: Request) {
return new Response(`bun!`);
},
port: 3000,
});
```
Node:
```ts
require("http")
.createServer((req, res) => res.end("bun!"))
.listen(8080);
```
Usage
Two ways to start an HTTP server with bun.js:
<ol>
<li><code>export default</code> an object with a <code>fetch</code> function</li>
</ol>
If the file used to start bun has a default export with a <code>fetch</code> function, it will start the HTTP server.
```ts
// hi.js
export default {
fetch(req) {
return new Response("HI!");
},
};
// bun ./hi.js
```
<code>fetch</code> receives a <a><code>Request</code></a> object and must return either a <a><code>Response</code> </a> or a <a><code>Promise<Response></code></a>. In a future version, it might have additional arguments for things like cookies.
<ol>
<li><code>Bun.serve</code> starts the HTTP server explicitly</li>
</ol>
<code>ts
Bun.serve({
fetch(req) {
return new Response("HI!");
},
});</code>
Error handling
For error handling, you get an <code>error</code> function.
If <code>development: true</code> and <code>error</code> is not defined or doesn't return a <code>Response</code>, you will get an exception page with a stack trace:
It will hopefully make it easier to debug issues with bun until bun gets debugger support. This error page is based on what <code>bun dev</code> does.
<strong>If the error function returns a <code>Response</code>, it will be served instead</strong>
<code>js
Bun.serve({
fetch(req) {
throw new Error("woops!");
},
error(error: Error) {
return new Response("Uh oh!!\n" + error.toString(), { status: 500 });
},
});</code>
<strong>If the <code>error</code> function itself throws and <code>development</code> is <code>false</code>, a generic 500 page will be shown</strong>
To stop the server, call <code>server.stop()</code>:
```ts
const server = Bun.serve({
fetch() {
return new Response("HI!");
},
});
server.stop();
```
The interface for <code>Bun.serve</code> is based on what <a>Cloudflare Workers</a> does.
<code>Bun.write</code> – optimizing I/O
<code>Bun.write</code> lets you write, copy or pipe files automatically using the fastest system calls compatible with the input and platform.
<code>ts
interface Bun {
write(
destination: string | number | FileBlob,
input: string | FileBlob | Blob | ArrayBufferView
): Promise<number>;
}</code>
| Output | Input | System Call | Platform |
| -------------------------- | -------------- | ----------------------------- | -------- |
| file | file | copy_file_range | Linux |
| file | pipe | sendfile | Linux |
| pipe | pipe | splice | Linux |
| terminal | file | sendfile | Linux |
| terminal | terminal | sendfile | Linux |
| socket | file or pipe | sendfile (if http, not https) | Linux |
| file (path, doesn't exist) | file (path) | clonefile | macOS |
| file | file | fcopyfile | macOS |
| file | Blob or string | write | macOS |
| file | Blob or string | write | Linux |
All this complexity is handled by a single function.
<code>ts
// Write "Hello World" to output.txt
await Bun.write("output.txt", "Hello World");</code>
<code>ts
// log a file to stdout
await Bun.write(Bun.stdout, Bun.file("input.txt"));</code>
<code>ts
// write the HTTP response body to disk
await Bun.write("index.html", await fetch("http://example.com"));
// this does the same thing
await Bun.write(Bun.file("index.html"), await fetch("http://example.com"));</code>
<code>ts
// copy input.txt to output.txt
await Bun.write("output.txt", Bun.file("input.txt"));</code>
bun:sqlite (SQLite3 module)
<code>bun:sqlite</code> is a high-performance built-in <a>SQLite3</a> module for bun.js.
<ul>
<li>Simple, synchronous API (synchronous <em>is</em> faster)</li>
<li>Transactions</li>
<li>Binding named & positional parameters</li>
<li>Prepared statements</li>
<li>Automatic type conversions (<code>BLOB</code> becomes <code>Uint8Array</code>)</li>
<li>toString() prints as SQL</li>
</ul>
Installation:
```sh
there's nothing to install
bun:sqlite is built-in to bun.js
```
Example:
```ts
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
db.run(
"CREATE TABLE IF NOT EXISTS foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
db.run("INSERT INTO foo (greeting) VALUES (?)", "Welcome to bun!");
db.run("INSERT INTO foo (greeting) VALUES (?)", "Hello World!");
// get the first row
db.query("SELECT * FROM foo").get();
// { id: 1, greeting: "Welcome to bun!" }
// get all rows
db.query("SELECT * FROM foo").all();
// [
// { id: 1, greeting: "Welcome to bun!" },
// { id: 2, greeting: "Hello World!" },
// ]
// get all rows matching a condition
db.query("SELECT * FROM foo WHERE greeting = ?").all("Welcome to bun!");
// [
// { id: 1, greeting: "Welcome to bun!" },
// ]
// get first row matching a named condition
db.query("SELECT * FROM foo WHERE greeting = $greeting").get({
$greeting: "Welcome to bun!",
});
// [
// { id: 1, greeting: "Welcome to bun!" },
// ]
```
bun:sqlite Benchmark
Database: <a>Northwind Traders</a>.
This benchmark can be run from <a>./bench/sqlite</a>.
Here are results from an M1 Pro (64GB) on macOS 12.3.1.
<strong>SELECT * FROM "Order"</strong>
| Library | Runtime | ms/iter |
| ------------------ | ----------- | -------------------- |
| bun:sqlite3 | Bun 0.0.83 | 14.31 (1x) |
| better-sqlite3 | Node 18.0.0 | 40.81 (2.8x slower) |
| deno.land/x/sqlite | Deno 1.21.2 | 125.96 (8.9x slower) |
<strong>SELECT * FROM "Product"</strong>
| Library | Runtime | us/iter |
| ------------------ | ----------- | -------------------- |
| bun:sqlite3 | Bun 0.0.83 | 33.85 (1x) |
| better-sqlite3 | Node 18.0.0 | 121.09 (3.5x slower) |
| deno.land/x/sqlite | Deno 1.21.2 | 187.64 (8.9x slower) |
<strong>SELECT * FROM "OrderDetail"</strong>
| Library | Runtime | ms/iter |
| ------------------ | ----------- | -------------------- |
| bun:sqlite3 | Bun 0.0.83 | 146.92 (1x) |
| better-sqlite3 | Node 18.0.0 | 875.73 (5.9x slower) |
| deno.land/x/sqlite | Deno 1.21.2 | 541.15 (3.6x slower) |
In screenshot form (which has a different sorting order)
Getting started with bun:sqlite
bun:sqlite's API is loosely based on <a>better-sqlite3</a>, though the implementation is different.
bun:sqlite has two classes:
<ul>
<li><code>class Database</code></li>
<li><code>class Statement</code></li>
</ul>
<code>Database</code>
Calling <code>new Database(filename)</code> opens or creates the SQLite database.
<code>ts
constructor(
filename: string,
options?:
| number
| {
/**
* Open the database as read-only (no write operations, no create).
*
* Equivalent to {@link constants.SQLITE_OPEN_READONLY}
*/
readonly?: boolean;
/**
* Allow creating a new database
*
* Equivalent to {@link constants.SQLITE_OPEN_CREATE}
*/
create?: boolean;
/**
* Open the database as read-write
*
* Equivalent to {@link constants.SQLITE_OPEN_READWRITE}
*/
readwrite?: boolean;
}
);</code>
To open or create a SQLite3 database:
```ts
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite");
```
Open an in-memory database:
```ts
import { Database } from "bun:sqlite";
// all of these do the same thing
var db = new Database(":memory:");
var db = new Database();
var db = new Database("");
```
Open read-write and throw if the database doesn't exist:
<code>ts
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite", { readwrite: true });</code>
Open read-only and throw if the database doesn't exist:
<code>ts
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite", { readonly: true });</code>
Open read-write, don't throw if new file:
<code>ts
import { Database } from "bun:sqlite";
const db = new Database("mydb.sqlite", { readonly: true, create: true });</code>
Open a database from a <code>Uint8Array</code>:
```ts
import { Database } from "bun:sqlite";
import { readFileSync } from "fs";
// unlike passing a filepath, this will not persist any changes to disk
// it will be read-write but not persistent
const db = new Database(readFileSync("mydb.sqlite"));
```
Close a database:
<code>ts
var db = new Database();
db.close();</code>
Note: <code>close()</code> is called automatically when the database is garbage collected. It is safe to call multiple times but has no effect after the first.
Database.prototype.query
<code>query(sql)</code> creates a <code>Statement</code> for the given SQL and caches it, but does not execute it.
<code>ts
class Database {
query(sql: string): Statement;
}</code>
<code>query</code> returns a <code>Statement</code> object.
It performs the same operation as <code>Database.prototype.prepare</code>, except:
<ul>
<li><code>query</code> caches the prepared statement in the <code>Database</code> object</li>
<li><code>query</code> doesn't bind parameters</li>
</ul>
This intended to make it easier for <code>bun:sqlite</code> to be fast by default. Calling <code>.prepare</code> compiles a SQLite query, which can take some time, so it's better to cache those a little.
You can bind parameters on any call to a statement.
```js
import { Database } from "bun:sqlite";
// generate some data
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
db.run("INSERT INTO foo (greeting) VALUES ($greeting)", {
$greeting: "Welcome to bun",
});
// get the query
const stmt = db.query("SELECT * FROM foo WHERE greeting = ?");
// run the query
stmt.all("Welcome to bun!");
stmt.get("Welcome to bun!");
stmt.run("Welcome to bun!");
```
Database.prototype.prepare
<code>prepare(sql)</code> creates a <code>Statement</code> for the given SQL, but does not execute it.
Unlike <code>query()</code>, this does not cache the compiled query.
```ts
import { Database } from "bun:sqlite";
// generate some data
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
// compile the prepared statement
const stmt = db.prepare("SELECT * FROM foo WHERE bar = ?");
// run the prepared statement
stmt.all("baz");
```
Internally, this calls <a><code>sqlite3_prepare_v3</code></a>.
Database.prototype.exec & Database.prototype.run
<code>exec</code> is for one-off executing a query which does not need to return anything.
<code>run</code> is an alias.
<code>ts
class Database {
// exec is an alias for run
exec(sql: string, ...params: ParamsType): void;
run(sql: string, ...params: ParamsType): void;
}</code>
This is useful for things like
Creating a table:
```ts
import { Database } from "bun:sqlite";
var db = new Database();
db.exec(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
```
Inserting one row:
```ts
import { Database } from "bun:sqlite";
var db = new Database();
db.exec(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
// insert one row
db.exec("INSERT INTO foo (greeting) VALUES ($greeting)", {
$greeting: "Welcome to bun",
});
```
For queries which aren't intended to be run multiple times, it should be faster to use <code>exec()</code> than <code>prepare()</code> or <code>query()</code> because it doesn't create a <code>Statement</code> object.
Internally, this function calls <a><code>sqlite3_prepare</code></a>, <a><code>sqlite3_step</code></a>, and <a><code>sqlite3_finalize</code></a>.
Database.prototype.transaction
Creates a function that always runs inside a transaction. When the function is invoked, it will begin a new transaction. When the function returns, the transaction will be committed. If an exception is thrown, the transaction will be rolled back (and the exception will propagate as usual).
```ts
// setup
import { Database } from "bun:sqlite";
const db = Database.open(":memory:");
db.exec(
"CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)"
);
const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)");
const insertMany = db.transaction((cats) => {
for (const cat of cats) insert.run(cat);
});
insertMany([
{ $name: "Joey", $age: 2 },
{ $name: "Sally", $age: 4 },
{ $name: "Junior", $age: 1 },
]);
```
Transaction functions can be called from inside other transaction functions. When doing so, the inner transaction becomes a savepoint.
```ts
// setup
import { Database } from "bun:sqlite";
const db = Database.open(":memory:");
db.exec(
"CREATE TABLE expenses (id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, dollars INTEGER);"
);
db.exec(
"CREATE TABLE cats (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, age INTEGER)"
);
const newExpense = db.prepare(
"INSERT INTO expenses (note, dollars) VALUES (?, ?)"
);
const insert = db.prepare("INSERT INTO cats (name, age) VALUES ($name, $age)");
const insertMany = db.transaction((cats) => {
for (const cat of cats) insert.run(cat);
});
const adopt = db.transaction((cats) => {
newExpense.run("adoption fees", 20);
insertMany(cats); // nested transaction
});
adopt([
{ $name: "Joey", $age: 2 },
{ $name: "Sally", $age: 4 },
{ $name: "Junior", $age: 1 },
]);
```
Transactions also come with <code>deferred</code>, <code>immediate</code>, and <code>exclusive</code> versions.
<code>ts
insertMany(cats); // uses "BEGIN"
insertMany.deferred(cats); // uses "BEGIN DEFERRED"
insertMany.immediate(cats); // uses "BEGIN IMMEDIATE"
insertMany.exclusive(cats); // uses "BEGIN EXCLUSIVE"</code>
Any arguments passed to the transaction function will be forwarded to the wrapped function, and any values returned from the wrapped function will be returned from the transaction function. The wrapped function will also have access to the same binding as the transaction function.
bun:sqlite's transaction implementation is based on <a>better-sqlite3</a> (along with this section of the docs), so thanks to Joshua Wise and better-sqlite3 contributors.
Database.prototype.serialize
SQLite has a built-in way to <a>serialize</a> and <a>deserialize</a> databases to and from memory.
<code>bun:sqlite</code> fully supports it:
```ts
var db = new Database();
// write some data
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
db.run("INSERT INTO foo VALUES (?)", "Welcome to bun!");
db.run("INSERT INTO foo VALUES (?)", "Hello World!");
const copy = db.serialize();
// => Uint8Array
const db2 = new Database(copy);
db2.query("SELECT * FROM foo").all();
// => [
// { id: 1, greeting: "Welcome to bun!" },
// { id: 2, greeting: "Hello World!" },
// ]
```
<code>db.serialize()</code> returns a <code>Uint8Array</code> of the database.
Internally, it calls <a><code>sqlite3_serialize</code></a>.
Database.prototype.loadExtension
<code>bun:sqlite</code> supports <a>SQLite extensions</a>.
To load a SQLite extension, call <code>Database.prototype.loadExtension(name)</code>:
```ts
import { Database } from "bun:sqlite";
var db = new Database();
db.loadExtension("myext");
```
If you're on macOS, you will need to first use a custom SQLite install (you can install with homebrew). By default, bun uses Apple's proprietary build of SQLite because it benchmarks about 50% faster. However, they disabled extension support, so you will need to have a custom build of SQLite to use extensions on macOS.
```ts
import { Database } from "bun:sqlite";
// on macOS, this must be run before any other calls to <code>Database</code>
// if called on linux, it will return true and do nothing
// on linux it will still check that a string was passed
Database.setCustomSQLite("/path/to/sqlite.dylib");
var db = new Database();
db.loadExtension("myext");
```
To install sqlite with homebrew:
<code>bash
brew install sqlite</code>
Statement
<code>Statement</code> is a prepared statement. Use it to run queries that get results.
TLDR:
<ul>
<li><a><code>Statement.all(...optionalParamsToBind)</code></a> returns all rows as an array of objects</li>
<li><a><code>Statement.values(...optionalParamsToBind)</code></a> returns all rows as an array of arrays</li>
<li><a><code>Statement.get(...optionalParamsToBind)</code></a> returns the first row as an object</li>
<li><a><code>Statement.run(...optionalParamsToBind)</code></a> runs the statement and returns nothing</li>
<li><a><code>Statement.finalize()</code></a> closes the statement</li>
<li><a><code>Statement.toString()</code></a> prints the expanded SQL, including bound parameters</li>
<li><code>get Statement.columnNames</code> get the returned column names</li>
<li><code>get Statement.paramsCount</code> how many parameters are expected?</li>
</ul>
You can bind parameters on any call to a statement. Named parameters and positional parameters are supported. Bound parameters are remembered between calls and reset the next time you pass parameters to bind.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT)"
);
db.run("INSERT INTO foo VALUES (?)", "Welcome to bun!");
db.run("INSERT INTO foo VALUES (?)", "Hello World!");
// Statement object
var statement = db.query("SELECT * FROM foo");
// returns all the rows
statement.all();
// returns the first row
statement.get();
// runs the query, without returning anything
statement.run();
```
Statement.all
Calling <code>all()</code> on a <code>Statement</code> instance runs the query and returns the rows as an array of objects.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)"
);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0);
db.run(
"INSERT INTO foo (greeting, count) VALUES (?, ?)",
"Welcome to bun!!!!",
2
);
// Statement object
var statement = db.query("SELECT * FROM foo WHERE count = ?");
// return all the query results, binding 2 to the count parameter
statement.all(2);
// => [
// { id: 1, greeting: "Welcome to bun!", count: 2 },
// { id: 3, greeting: "Welcome to bun!!!!", count: 2 },
// ]
```
Internally, this calls <a><code>sqlite3_reset</code></a> and repeatedly calls <a><code>sqlite3_step</code></a> until it returns <code>SQLITE_DONE</code>.
Statement.values
Calling <code>values()</code> on a <code>Statement</code> instance runs the query and returns the rows as an array of arrays.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)"
);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0);
db.run(
"INSERT INTO foo (greeting, count) VALUES (?, ?)",
"Welcome to bun!!!!",
2
);
// Statement object
var statement = db.query("SELECT * FROM foo WHERE count = ?");
// return all the query results as an array of arrays, binding 2 to "count"
statement.values(2);
// => [
// [ 1, "Welcome to bun!", 2 ],
// [ 3, "Welcome to bun!!!!", 2 ],
// ]
// Statement object, but with named parameters
var statement = db.query("SELECT * FROM foo WHERE count = $count");
// return all the query results as an array of arrays, binding 2 to "count"
statement.values({ $count: 2 });
// => [
// [ 1, "Welcome to bun!", 2 ],
// [ 3, "Welcome to bun!!!!", 2 ],
// ]
```
Internally, this calls <a><code>sqlite3_reset</code></a> and repeatedly calls <a><code>sqlite3_step</code></a> until it returns <code>SQLITE_DONE</code>.
Statement.get
Calling <code>get()</code> on a <code>Statement</code> instance runs the query and returns the first result as an object.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)"
);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0);
db.run(
"INSERT INTO foo (greeting, count) VALUES (?, ?)",
"Welcome to bun!!!!",
2
);
// Statement object
var statement = db.query("SELECT * FROM foo WHERE count = ?");
// return the first row as an object, binding 2 to the count parameter
statement.get(2);
// => { id: 1, greeting: "Welcome to bun!", count: 2 }
// Statement object, but with named parameters
var statement = db.query("SELECT * FROM foo WHERE count = $count");
// return the first row as an object, binding 2 to the count parameter
statement.get({ $count: 2 });
// => { id: 1, greeting: "Welcome to bun!", count: 2 }
```
Internally, this calls <a><code>sqlite3_reset</code></a> and calls <a><code>sqlite3_step</code></a> once. Stepping through all the rows is not necessary when you only want the first row.
Statement.run
Calling <code>run()</code> on a <code>Statement</code> instance runs the query and returns nothing.
This is useful if you want to repeatedly run a query, but don't care about the results.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)"
);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0);
db.run(
"INSERT INTO foo (greeting, count) VALUES (?, ?)",
"Welcome to bun!!!!",
2
);
// Statement object (TODO: use a better example query)
var statement = db.query("SELECT * FROM foo");
// run the query, returning nothing
statement.run();
```
Internally, this calls <a><code>sqlite3_reset</code></a> and calls <a><code>sqlite3_step</code></a> once. Stepping through all the rows is not necessary when you don't care about the results.
Statement.finalize
This method finalizes the statement, freeing any resources associated with it.
After a statement has been finalized, it cannot be used for any further queries. Any attempt to run the statement will throw an error. Calling it multiple times will have no effect.
It is a good idea to finalize a statement when you are done with it, but the garbage collector will do it for you if you don't.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)"
);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0);
db.run(
"INSERT INTO foo (greeting, count) VALUES (?, ?)",
"Welcome to bun!!!!",
2
);
// Statement object
var statement = db.query("SELECT * FROM foo WHERE count = ?");
statement.finalize();
// this will throw
statement.run();
```
Statement.toString()
Calling <code>toString()</code> on a <code>Statement</code> instance prints the expanded SQL query. This is useful for debugging.
```ts
import { Database } from "bun:sqlite";
// setup
var db = new Database();
db.run(
"CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, greeting TEXT, count INTEGER)"
);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Welcome to bun!", 2);
db.run("INSERT INTO foo (greeting, count) VALUES (?, ?)", "Hello World!", 0);
db.run(
"INSERT INTO foo (greeting, count) VALUES (?, ?)",
"Welcome to bun!!!!",
2
);
// Statement object
const statement = db.query("SELECT * FROM foo WHERE count = ?");
console.log(statement.toString());
// => "SELECT * FROM foo WHERE count = NULL"
statement.run(2); // bind the param
console.log(statement.toString());
// => "SELECT * FROM foo WHERE count = 2"
```
Internally, this calls <a><code>sqlite3_expanded_sql</code></a>.
Datatypes
| JavaScript type | SQLite type |
| --------------- | ---------------------- |
| <code>string</code> | <code>TEXT</code> |
| <code>number</code> | <code>INTEGER</code> or <code>DECIMAL</code> |
| <code>boolean</code> | <code>INTEGER</code> (1 or 0) |
| <code>Uint8Array</code> | <code>BLOB</code> |
| <code>Buffer</code> | <code>BLOB</code> |
| <code>bigint</code> | <code>INTEGER</code> |
| <code>null</code> | <code>NULL</code> |
<code>bun:ffi</code> (Foreign Functions Interface)
<code>bun:ffi</code> lets you efficiently call native libraries from JavaScript. It works with languages that support the C ABI (Zig, Rust, C/C++, C#, Nim, Kotlin, etc).
This snippet prints sqlite3's version number:
```ts
import { dlopen, FFIType, suffix } from "bun:ffi";
// <code>suffix</code> is either "dylib", "so", or "dll" depending on the platform
// you don't have to use "suffix", it's just there for convenience
const path = <code>libsqlite3.${suffix}</code>;
const {
symbols: {
// sqlite3_libversion is the function we will call
sqlite3_libversion,
},
} =
// dlopen() expects:
// 1. a library name or file path
// 2. a map of symbols
dlopen(path, {
// <code>sqlite3_libversion</code> is a function that returns a string
sqlite3_libversion: {
// sqlite3_libversion takes no arguments
args: [],
// sqlite3_libversion returns a pointer to a string
returns: FFIType.cstring,
},
});
console.log(<code>SQLite 3 version: ${sqlite3_libversion()}</code>);
```
Low-overhead FFI
3ns to go from JavaScript <> native code with <code>bun:ffi</code> (on my machine, an M1 Pro with 64GB of RAM)
<ul>
<li>5x faster than napi (Node v17.7.1)</li>
<li>100x faster than Deno v1.21.1</li>
</ul>
As measured in <a>this simple benchmark</a>
Why is bun:ffi fast?
Bun generates & just-in-time compiles C bindings that efficiently convert values between JavaScript types and native types.
To compile C, Bun embeds [TinyCC](https://github.com/TinyCC/tinycc), a small and fast C compiler.
Usage
With Zig:
<code>zig
// add.zig
pub export fn add(a: i32, b: i32) i32 {
return a + b;
}</code>
To compile:
<code>bash
zig build-lib add.zig -dynamic -OReleaseFast</code>
Pass <code>dlopen</code> the path to the shared library and the list of symbols you want to import.
```ts
import { dlopen, FFIType, suffix } from "bun:ffi";
const path = <code>libadd.${suffix}</code>;
const lib = dlopen(path, {
add: {
args: [FFIType.i32, FFIType.i32],
returns: FFIType.i32,
},
});
lib.symbols.add(1, 2);
```
With Rust:
```rust
// add.rs
[no_mangle]
pub extern "C" fn add(a: isize, b: isize) -> isize {
a + b
}
```
To compile:
<code>bash
rustc --crate-type cdylib add.rs</code>
Supported FFI types (<code>FFIType</code>)
| <code>FFIType</code> | C Type | Aliases |
| --------- | ---------- | --------------------------- |
| cstring | <code>char*</code> | |
| ptr | <code>void*</code> | <code>pointer</code>, <code>void*</code>, <code>char*</code> |
| i8 | <code>int8_t</code> | <code>int8_t</code> |
| i16 | <code>int16_t</code> | <code>int16_t</code> |
| i32 | <code>int32_t</code> | <code>int32_t</code>, <code>int</code> |
| i64 | <code>int64_t</code> | <code>int32_t</code> |
| u8 | <code>uint8_t</code> | <code>uint8_t</code> |
| u16 | <code>uint16_t</code> | <code>uint16_t</code> |
| u32 | <code>uint32_t</code> | <code>uint32_t</code> |
| u64 | <code>uint64_t</code> | <code>uint32_t</code> |
| f32 | <code>float</code> | <code>float</code> |
| f64 | <code>double</code> | <code>double</code> |
| bool | <code>bool</code> | |
| char | <code>char</code> | |
Strings (<code>CString</code>)
JavaScript strings and C-like strings are different, and that complicates using strings with native libraries.
How are JavaScript strings and C strings different?
JavaScript strings:
- UTF16 (2 bytes per letter) or potentially latin1, depending on the JavaScript engine & what characters are used
- `length` stored separately
- Immutable
C strings:
- UTF8 (1 byte per letter), usually
- The length is not stored. Instead, the string is null-terminated which means the length is the index of the first `\0` it finds
- Mutable
To help with that, <code>bun:ffi</code> exports <code>CString</code> which extends JavaScript's built-in <code>String</code> to support null-terminated strings and add a few extras:
<code>``ts
class CString extends String {
/**
* Given a</code>ptr<code>, this will automatically search for the closing</code>\0` character and transcode from UTF-8 to UTF-16 if necessary.
*/
constructor(ptr: number, byteOffset?: number, byteLength?: number): string;
/*<em>
* The ptr to the C string
*
* This <code>CString</code> instance is a clone of the string, so it
* is safe to continue using this instance after the <code>ptr</code> has been
* freed.
</em>/
ptr: number;
byteOffset?: number;
byteLength?: number;
}
```
To convert from a null-terminated string pointer to a JavaScript string:
<code>ts
const myString = new CString(ptr);</code>
To convert from a pointer with a known length to a JavaScript string:
<code>ts
const myString = new CString(ptr, 0, byteLength);</code>
<code>new CString</code> clones the C string, so it is safe to continue using <code>myString</code> after <code>ptr</code> has been freed.
```ts
my_library_free(myString.ptr);
// this is safe because myString is a clone
console.log(myString);
```
Returning a string
When used in <code>returns</code>, <code>FFIType.cstring</code> coerces the pointer to a JavaScript <code>string</code>. When used in <code>args</code>, <code>cstring</code> is identical to <code>ptr</code>.
Function pointers (<code>CFunction</code>)
To call a function pointer from JavaScript, use <code>CFunction</code>
This is useful if using Node-API (napi) with Bun, and you've already loaded some symbols.
```ts
import { CFunction } from "bun:ffi";
var myNativeLibraryGetVersion = /<em> somehow, you got this pointer </em>/
const getVersion = new CFunction({
returns: "cstring",
args: [],
ptr: myNativeLibraryGetVersion,
});
getVersion();
```
If you have multiple function pointers, you can define them all at once with <code>linkSymbols</code>:
```ts
import { linkSymbols } from "bun:ffi";
// getVersionPtrs defined elsewhere
const [majorPtr, minorPtr, patchPtr] = getVersionPtrs();
const lib = linkSymbols({
// Unlike with dlopen(), the names here can be whatever you want
getMajor: {
returns: "cstring",
args: [],
<code>// Since this doesn't use dlsym(), you have to provide a valid ptr
// That ptr could be a number or a bigint
// An invalid pointer will crash your program.
ptr: majorPtr,
</code>
},
getMinor: {
returns: "cstring",
args: [],
ptr: minorPtr,
},
getPatch: {
returns: "cstring",
args: [],
ptr: patchPtr,
},
});
const [major, minor, patch] = [
lib.symbols.getMajor(),
lib.symbols.getMinor(),
lib.symbols.getPatch(),
];
```
Pointers
Bun represents <a>pointers</a> as a <code>number</code> in JavaScript.
How does a 64 bit pointer fit in a JavaScript number?
64-bit processors support up to [52 bits of addressable space](https://en.wikipedia.org/wiki/64-bit_computing#Limits_of_processors).
[JavaScript numbers](https://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64) support 53 bits of usable space, so that leaves us with about 11 bits of extra space.
Why not `BigInt`?
`BigInt` is slower. JavaScript engines allocate a separate `BigInt` which means they can't just fit in a regular javascript value.
If you pass a `BigInt` to a function, it will be converted to a `number`
<strong>To convert from a TypedArray to a pointer</strong>:
<code>ts
import { ptr } from "bun:ffi";
var myTypedArray = new Uint8Array(32);
const myPtr = ptr(myTypedArray);</code>
<strong>To convert from a pointer to an ArrayBuffer</strong>:
```ts
import { ptr, toArrayBuffer } from "bun:ffi";
var myTypedArray = new Uint8Array(32);
const myPtr = ptr(myTypedArray);
// toTypedArray accepts a <code>byteOffset</code> and <code>byteLength</code>
// if <code>byteLength</code> is not provided, it is assumed to be a null-terminated pointer
myTypedArray = new Uint8Array(toArrayBuffer(myPtr, 0, 32), 0, 32);
```
<strong>Pointers & memory safety</strong>
Using raw pointers outside of FFI is extremely not recommended.
A future version of bun may add a CLI flag to disable <code>bun:ffi</code> (or potentially a separate build of bun).
<strong>Pointer alignment</strong>
If an API expects a pointer sized to something other than <code>char</code> or <code>u8</code>, make sure the typed array is also that size.
A <code>u64*</code> is not exactly the same as <code>[8]u8*</code> due to alignment
Passing a pointer
Where FFI functions expect a pointer, pass a TypedArray of equivalent size
Easymode:
```ts
import { dlopen, FFIType } from "bun:ffi";
const {
symbols: { encode_png },
} = dlopen(myLibraryPath, {
encode_png: {
// FFIType's can be specified as strings too
args: ["ptr", "u32", "u32"],
returns: FFIType.ptr,
},
});
const pixels = new Uint8ClampedArray(128 * 128 * 4);
pixels.fill(254);
pixels.subarray(0, 32 * 32 * 2).fill(0);
const out = encode_png(
// pixels will be passed as a pointer
pixels,
128,
128
);
```
The <a>auto-generated wrapper</a> converts the pointer to a TypedArray
Hardmode
If you don't want the automatic conversion or you want a pointer to a specific byte offset within the TypedArray, you can also directly get the pointer to the TypedArray:
```ts
import { dlopen, FFIType, ptr } from "bun:ffi";
const {
symbols: { encode_png },
} = dlopen(myLibraryPath, {
encode_png: {
// FFIType's can be specified as strings too
args: ["ptr", "u32", "u32"],
returns: FFIType.ptr,
},
});
const pixels = new Uint8ClampedArray(128 * 128 * 4);
pixels.fill(254);
// this returns a number! not a BigInt!
const myPtr = ptr(pixels);
const out = encode_png(
myPtr,
// dimensions:
128,
128
);
```
Reading pointers
```ts
const out = encode_png(
// pixels will be passed as a pointer
pixels,
// dimensions:
128,
128
);
// assuming it is 0-terminated, it can be read like this:
var png = new Uint8Array(toArrayBuffer(out));
// save it to disk:
await Bun.write("out.png", png);
```
Not implemented yet
<code>bun:ffi</code> has a few more things planned but not implemented yet:
<ul>
<li>callback functions</li>
<li>async functions</li>
</ul>
Node-API (napi)
Bun.js implements 90% of the APIs available in <a>Node-API</a> (napi).
You can see the status of <a>this here</a>.
Loading Node-API modules in Bun.js works the same as in Node.js:
<code>js
const napi = require("./my-node-module.node");</code>
You can also use <code>process.dlopen</code>:
<code>js
var mod = { exports: {} };
process.dlopen(mod, "./my-node-module.node");</code>
As part of that work, Bun.js also polyfills the <a><code>detect-libc</code></a> package, which is used by many Node-API modules to detect which <code>.node</code> binding to <code>require</code>.
This implementation of Node-API is from scratch. It doesn't use any code from Node.js.
<strong>Some implementation details</strong>
When requiring a <code>*.node</code> module, Bun's JavaScript transpiler transforms the <code>require</code> expression into a call to <code>import.meta.require</code>:
```js
// this is the input
require("./my-node-module.node");
// this is the output
import.meta.require("./my-node-module.node");
```
Bun doesn't currently support dynamic requires, but <code>import.meta.require</code> is an escape hatch for that. It uses a <a>JavaScriptCore built-in function</a>.
<code>Bun.Transpiler</code>
<code>Bun.Transpiler</code> lets you use Bun's transpiler from JavaScript (available in Bun.js)
````ts
type Loader = "jsx" | "js" | "ts" | "tsx";
interface TranspilerOptions {
// Replace key with value. Value must be a JSON string.
// @example
// <code>// { "process.env.NODE_ENV": "\"production\"" }
//</code>
define: Record,
// What is the default loader used for this transpiler?
loader: Loader,
// What platform are we targeting? This may affect how import and/or require is used
platform: "browser" | "bun" | "macro" | "node",
// TSConfig.json file as stringified JSON or an object
// Use this to set a custom JSX factory, fragment, or import source
// For example, if you want to use Preact instead of React. Or if you want to use Emotion.
tsconfig: string | TSConfig,
// Replace imports with macros
macros: MacroMap,
}
// This lets you use macros
interface MacroMap {
// @example
// <code>// {
// "react-relay": {
// "graphql": "bun-macro-relay/bun-macro-relay.tsx"
// }
// }
//</code>
<code>[importItemName: string]: string,
</code>
},
}
class Bun.Transpiler {
constructor(options: TranspilerOptions)
transform(code: string, loader?: Loader): Promise
transformSync(code: string, loader?: Loader): string
scan(code: string): {exports: string[], imports: Import}
scanImports(code: string): Import[]
}
type Import = {
path: string,
kind:
// import foo from 'bar'; in JavaScript
| "import-statement"
// require("foo") in JavaScript
| "require-call"
// require.resolve("foo") in JavaScript
| "require-resolve"
// Dynamic import() in JavaScript
| "dynamic-import"
// @import() in CSS
| "import-rule"
// url() in CSS
| "url-token"
// The import was injected by Bun
| "internal"
// Entry point
// Probably won't see this one
| "entry-point"
}
const transpiler = new Bun.Transpiler({ loader: "jsx" });
````
<code>Bun.Transpiler.transformSync</code>
This lets you transpile JavaScript, TypeScript, TSX, and JSX using Bun's transpiler. It does not resolve modules.
It is synchronous and runs in the same thread as other JavaScript code.
<code>js
const transpiler = new Bun.Transpiler({ loader: "jsx" });
transpiler.transformSync("<div>hi!</div>");</code>
```js
import { __require as require } from "bun:wrap";
import * as JSX from "react/jsx-dev-runtime";
var jsx = require(JSX).jsxDEV;
export default jsx(
"div",
{
children: "hi!",
},
undefined,
false,
undefined,
this
);
```
If a macro is used, it will be run in the same thread as the transpiler, but in a separate event loop from the rest of your application. Currently, globals between macros and regular code are shared, which means it is possible (but not recommended) to share states between macros and regular code. Attempting to use AST nodes outside of a macro is undefined behavior.
<code>Bun.Transpiler.transform</code>
This lets you transpile JavaScript, TypeScript, TSX, and JSX using Bun's transpiler. It does not resolve modules.
It is async and automatically runs in Bun's worker threadpool. That means, if you run it 100 times, it will run it across <code>Math.floor($cpu_count * 0.8)</code> threads without blocking the main JavaScript thread.
If code uses a macro, it will potentially spawn a new copy of Bun.js' JavaScript runtime environment in that new thread.
Unless you're transpiling <em>many</em> large files, you should probably use <code>Bun.Transpiler.transformSync</code>. The cost of the threadpool will often take longer than actually transpiling code.
<code>js
const transpiler = new Bun.Transpiler({ loader: "jsx" });
await transpiler.transform("<div>hi!</div>");</code>
```js
import { __require as require } from "bun:wrap";
import * as JSX from "react/jsx-dev-runtime";
var jsx = require(JSX).jsxDEV;
export default jsx(
"div",
{
children: "hi!",
},
undefined,
false,
undefined,
this
);
```
You can also pass a <code>Loader</code> as a string
<code>js
await transpiler.transform("<div>hi!</div>", "tsx");</code>
<code>Bun.Transpiler.scan</code>
This is a fast way to get a list of imports & exports used in a JavaScript/jsx or TypeScript/tsx file.
This function is synchronous.
```ts
const transpiler = new Bun.Transpiler({ loader: "ts" });
transpiler.scan(`
import React from 'react';
import Remix from 'remix';
import type {ReactNode} from 'react';
export const loader = () => import('./loader');
`);
```
```ts
{
"exports": [
"loader"
],
"imports": [
{
"kind": "import-statement",
"path": "react"
},
{
"kind": "import-statement",
"path": "remix"
},
{
"kind": "dynamic-import",
"path": "./loader"
}
]
}
```
<code>Bun.Transpiler.scanImports</code>
This is a fast path for getting a list of imports used in a JavaScript/jsx or TypeScript/tsx file. It skips the visiting pass, which means it is faster but less accurate. You probably won't notice a difference between <code>Bun.Transpiler.scan</code> and <code>Bun.Transpiler.scanImports</code> often. You might notice it for very large files (megabytes).
This function is synchronous.
```ts
const transpiler = new Bun.Transpiler({ loader: "ts" });
transpiler.scanImports(`
import React from 'react';
import Remix from 'remix';
import type {ReactNode} from 'react';
export const loader = () => import('./loader');
`);
```
<code>json
[
{
"kind": "import-statement",
"path": "react"
},
{
"kind": "import-statement",
"path": "remix"
},
{
"kind": "dynamic-import",
"path": "./loader"
}
]</code>
Environment variables
<ul>
<li><code>GOMAXPROCS</code>: For <code>bun bun</code>, this sets the maximum number of threads to use. If you’re experiencing an issue with <code>bun bun</code>, try setting <code>GOMAXPROCS=1</code> to force bun to run single-threaded</li>
<li><code>DISABLE_BUN_ANALYTICS=1</code> this disables bun’s analytics. bun records bundle timings (so we can answer with data, "is bun getting faster?") and feature usage (e.g., "are people actually using macros?"). The request body size is about 60 bytes, so it’s not a lot of data</li>
<li><code>TMPDIR</code>: Before <code>bun bun</code> completes, it stores the new <code>.bun</code> in <code>$TMPDIR</code>. If unset, <code>TMPDIR</code> defaults to the platform-specific temporary directory (on Linux, <code>/tmp</code> and on macOS <code>/private/tmp</code>)</li>
</ul>
Credits
<ul>
<li>While written in Zig instead of Go, bun’s JS transpiler, CSS lexer, and node module resolver source code is based on <a>@evanw</a>’s <a>esbuild</a> project. Evan did a fantastic job with esbuild.</li>
<li>The idea for the name "bun" came from <a>@kipply</a></li>
</ul>
License
bun itself is MIT-licensed.
However, JavaScriptCore (and WebKit) is LGPL-2 and bun statically links it. WebCore files from WebKit are also licensed under LGPL2.
Per LGPL2:
<blockquote>
(1) If you statically link against an LGPL’d library, you must also provide your application in an object (not necessarily source) format, so that a user has the opportunity to modify the library and relink the application.
</blockquote>
You can find the patched version of WebKit used by bun here: <a>https://github.com/jarred-sumner/webkit</a>. If you would like to relink bun with changes:
<ul>
<li><code>git submodule update --init --recursive</code></li>
<li><code>make jsc</code></li>
<li><code>zig build</code></li>
</ul>
This compiles JavaScriptCore, compiles bun’s <code>.cpp</code> bindings for JavaScriptCore (which are the object files using JavaScriptCore) and outputs a new <code>bun</code> binary with your changes.
bun also statically links these libraries:
<ul>
<li><a><code>boringssl</code></a>, which has <a>several licenses</a></li>
<li><a><code>libarchive</code></a>, which has <a>several licenses</a></li>
<li><a><code>libiconv</code></a>, which is LGPL2. It’s a dependency of libarchive.</li>
<li><a><code>lol-html</code></a>, which is BSD 3-Clause licensed</li>
<li><a><code>mimalloc</code></a>, which is MIT licensed</li>
<li><a><code>picohttp</code></a>, which is dual-licensed under the Perl License or the MIT License</li>
<li><a><code>tinycc</code></a>, which is LGPL v2.1 licensed</li>
<li><a><code>uSockets</code></a>, which is Apache 2.0 licensed</li>
<li><a><code>zlib-cloudflare</code></a>, which is zlib licensed</li>
<li><code>libicu</code> 66.1, which can be found here: <a>https://github.com/unicode-org/icu/blob/main/icu4c/LICENSE</a></li>
<li>A fork of <a><code>uWebsockets</code></a>, which is Apache 2.0 licensed</li>
</ul>
For compatibility reasons, these NPM packages are embedded into bun’s binary and injected if imported.
<ul>
<li><a><code>assert</code></a> (MIT license)</li>
<li><a><code>browserify-zlib</code></a> (MIT license)</li>
<li><a><code>buffer</code></a> (MIT license)</li>
<li><a><code>constants-browserify</code></a> (MIT license)</li>
<li><a><code>crypto-browserify</code></a> (MIT license)</li>
<li><a><code>domain-browser</code></a> (MIT license)</li>
<li><a><code>events</code></a> (MIT license)</li>
<li><a><code>https-browserify</code></a> (MIT license)</li>
<li><a><code>os-browserify</code></a> (MIT license)</li>
<li><a><code>path-browserify</code></a> (MIT license)</li>
<li><a><code>process</code></a> (MIT license)</li>
<li><a><code>punycode</code></a> (MIT license)</li>
<li><a><code>querystring-es3</code></a> (MIT license)</li>
<li><a><code>stream-browserify</code></a> (MIT license)</li>
<li><a><code>stream-http</code></a> (MIT license)</li>
<li><a><code>string_decoder</code></a> (MIT license)</li>
<li><a><code>timers-browserify</code></a> (MIT license)</li>
<li><a><code>tty-browserify</code></a> (MIT license)</li>
<li><a><code>url</code></a> (MIT license)</li>
<li><a><code>util</code></a> (MIT license)</li>
<li><a><code>vm-browserify</code></a> (MIT license)</li>
</ul>
Developing bun
Estimated: 30-90 minutes :(
VSCode Dev Container (Linux)
The VSCode Dev Container in this repository is the easiest way to get started. It comes with Zig, JavaScriptCore, Zig Language Server, vscode-zig, and more pre-installed on an instance of Ubuntu.
To get started, install the devcontainer cli:
<code>bash
npm install -g @vscode/dev-container-cli</code>
Then, in the <code>bun</code> repository locally run:
<code>bash
devcontainer build
devcontainer open</code>
You will need to clone the GitHub repository inside that container, which also requires authenticating with GitHub (until bun's repository is public). Make sure to login with a Personal Access Token rather than a web browser.
Inside the container, run this:
```bash
First time setup
gh auth login
gh repo clone oven-sh/bun . -- --depth=1 --progress -j8
update all submodules except webkit because webkit takes awhile and it's already compiled for you.
git -c submodule."src/bun.js/WebKit".update=none submodule update --init --recursive --depth=1 --progress
Compile bun dependencies (zig is already compiled)
make devcontainer
Build bun for development
make dev
Run bun
bun-debug
```
It is very similar to my own development environment.
MacOS
Install LLVM 13 and homebrew dependencies:
<code>bash
brew install llvm@13 coreutils libtool cmake libiconv automake [email protected] ninja gnu-sed pkg-config esbuild go rust</code>
bun (& the version of Zig) need LLVM 13 and Clang 13 (clang is part of LLVM). Weird build & runtime errors will happen otherwise.
Make sure LLVM 13 is in your <code>$PATH</code>:
<code>bash
which clang-13</code>
If it is not, you will have to run this to link it:
<code>bash
export PATH=$(brew --prefix llvm@13)/bin:$PATH
export LDFLAGS="$LDFLAGS -L$(brew --prefix llvm@13)/lib"
export CPPFLAGS="$CPPFLAGS -I$(brew --prefix llvm@13)/include"</code>
On fish that looks like <code>fish_add_path (brew --prefix llvm@13)/bin</code>
You’ll want to make sure <code>zig</code> is in <code>$PATH</code>. The specific version of Zig expected is the HEAD in <a>Jarred-Sumner/zig</a>.
Build bun (macOS)
If you're building on a macOS device, you'll need to have a valid Developer Certificate, or else the code signing step will fail. To check if you have one, open the <code>Keychain Access</code> app, go to the <code>login</code> profile and search for <code>Apple Development</code>. You should have at least one certificate with a name like <code>Apple Development: [email protected] (WDYABC123)</code>. If you don't have one, follow <a>this guide</a> to get one.
In <code>bun</code>:
```bash
If you omit --depth=1, <code>git submodule update</code> will take 17.5 minutes on 1gbps internet, mostly due to WebKit.
git submodule update --init --recursive --progress --depth=1
make vendor identifier-cache jsc dev
```
Verify it worked (macOS)
First ensure the node dependencies are installed
<code>bash
(cd test/snippets && npm i)
(cd test/scripts && npm i)</code>
Then
<code>bash
make test-dev-all</code>
Troubleshooting (macOS)
If you see an error when compiling <code>libarchive</code>, run this:
<code>bash
brew install pkg-config</code>
If you see an error about missing files on <code>zig build obj</code>, make sure you built the headers
vscode-zig
Note: this is automatically installed on the devcontainer
You will want to install the fork of <code>vscode-zig</code> so you get a <code>Run test</code> and a <code>Debug test</code> button.
To do that:
<code>bash
curl -L https://github.com/Jarred-Sumner/vscode-zig/releases/download/fork-v1/zig-0.2.5.vsix > vscode-zig.vsix
code --install-extension vscode-zig.vsix</code>
<a target="_blank"></a> | []
|
https://avatars.githubusercontent.com/u/68057?v=4 | zig_uv | ousttrue/zig_uv | 2022-09-13T12:18:08Z | libuv zig build and uvbook | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/ousttrue/zig_uv/tags | - | [
"libuv",
"zig"
]
| 1,932 | false | 2025-05-08T14:44:21Z | true | true | unknown | github | [
{
"commit": null,
"name": "zig_uv",
"tar_url": null,
"type": "relative",
"url": "deps/zig_uv"
},
{
"commit": null,
"name": "uvbook",
"tar_url": null,
"type": "relative",
"url": "deps/uvbook"
}
]
| libuv from zig
<code>zig-0.13.0</code>
zig-0.14.0
```
error: lld-link: undefined symbol: __declspec(dllimport) _CrtSetReportHook
if debug
add link to ucrtbased
```
dependencies
<code>master required</code> <code>v1.48.0</code> has CONTAINING_RECORD issue.
```sh
<blockquote>
zig fetch --save=libuv git+https://github.com/libuv/libuv.git
```
</blockquote>
trobule
CONTAINING_RECORD cause runtime INVALID INSTRUCTION
patch for src/win/req-inl.h
<code>c
INLINE static uv_req_t* uv__overlapped_to_req(OVERLAPPED* overlapped) {
// cause illegal instruction
// return CONTAINING_RECORD(overlapped, uv_req_t, u.io.overlapped);
return (uv_req_t*)((char*)overlapped - offsetof(uv_req_t, u.io.overlapped));
}</code>
same https://github.com/libuv/libuv/pull/4254
merged 2024/08/06
error: dependency loop detected
<ul>
<li>https://github.com/ziglang/zig/issues/18247</li>
</ul>
```zig
pub const struct_uv_stream_s = extern struct {
read_cb: uv_read_cb = @import("std").mem.zeroes(uv_read_cb),
};
// 👆👇
pub const uv_read_cb = ?<em>const fn ([</em>c]uv_stream_t, isize, [*c]const uv_buf_t) callconv(.C) void;
// workaround
pub const uv_read_cb = ?<em>const fn (</em>anyopaque, isize, [*c]const uv_buf_t) callconv(.C) void;
```
uvbook
<ul>
<li>https://docs.libuv.org/en/v1.x/guide/introduction.html</li>
</ul>
```sh
<blockquote>
zig build -l
install (default) Copy build artifacts to prefix path
uninstall Remove build artifacts from prefix path
c_helloworld Build & run c_helloworld
zig_helloworld Build & run zig_helloworld
zig build c-helloworld
```
</blockquote>
[Basics of libuv]https://docs.libuv.org/en/v1.x/guide/basics.html
| name | c-win32 | zig |
| ---------------------------------------------------------------------------------- | ------- | --- |
| <a>helloworld</a> | o | o |
| <a>idle-basic</a> | o | o |
<a>Filesystem</a>
| name | c-win32 | zig |
| ------------------------------------------------------------------------------ | ------- | ------------ |
| <a>uvcat</a> | o | o translated |
| <a>uvtee</a> | o | o translated |
| <a>onchange</a> | o | o |
<a>Networking</a>
| name | c-win32 | zig |
| -------------------------------------------------------------------------------------------- | ------- | -------------------------- |
| <a>tcp-echo-server</a> | o | o translated, TODO: client |
| <a>udp-dhcp</a> | o | o translated |
| <a>dns</a> | o | o TODO: not work |
| <a>interfaces</a> | o | x @cimport error |
<a>Threads</a>
| name | c-win32 | zig |
| ---------------------------------------------------------------------------------------- | --------------- | --- |
| <a>thread-create</a> | c | o |
| <a>locks</a> | uv_barrier_wait | |
| <a>queue-work</a> | <code><unistd.h></code> | |
| <a>queue-cancel</a> | <code><unistd.h></code> | |
| <a>progress</a> | <code><unistd.h></code> | |
<a>Process</a>
| name | c-win32 | zig |
| ------------------------------------------------------------------------------------------------ | ------------ | ------------ |
| <a>spawn</a> | o | o translated |
| <a>detach</a> | o | |
| <a>signal</a> | <code><unistd.h></code> | |
| <a>proc-streams</a> | o | |
| <a>cgi</a> | o | and cgi/tick |
| <a>pipe-echo-server</a> | o | |
| <a>multi-echo-server</a> | o | |
<a>Advanced event loops</a>
| name | c-win32 | zig |
| -------------------------------------------------------------------------- | ------- | --- |
| <a>uvstop</a> | o | x |
<a>Utilities</a>
| name | c-win32 | zig |
| ---------------------------------------------------------------------------------------- | ---------- | ------------------ |
| <a> ref-timer </a> | o | |
| <a> idle-compute </a> | o | |
| <a> uvwget </a> | <code><curl.h></code> | |
| <a> plugin </a> | o | and plugin/hello.c |
| <a> tty </a> | o | |
| <a> tty-gravity </a> | o | o translated | | [
"https://github.com/ousttrue/zig_uv"
]
|
https://avatars.githubusercontent.com/u/69708036?v=4 | learn-dart | better-dart/learn-dart | 2022-09-05T16:55:08Z | learn dart | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/better-dart/learn-dart/tags | MIT | [
"c",
"dart",
"ffi",
"ffi-bindings",
"flutter",
"rust",
"zig"
]
| 344 | false | 2023-08-28T19:30:55Z | false | false | unknown | github | []
| Learn Dart:
<ul>
<li>flutter/dart monorepo.</li>
</ul>
Packages:
<ul>
<li>✅ <a>ffi-app</a>: ffi 示例</li>
<li><a>ffi-binding</a><ul>
<li>zig + ffi + dart/flutter</li>
<li>rust + ffi + dart/flutter</li>
<li>c + ffi + dart/flutter</li>
</ul>
</li>
<li><a>ffi-with-zig</a></li>
<li><a>ffi-with-c</a></li>
<li><a>ffi-with-rust</a></li>
</ul>
Development:
<blockquote>
prepare:
</blockquote>
<ul>
<li>Flutter: 3.3.0 + FVM</li>
<li>Zig: <code>0.10.0</code></li>
<li>go-task</li>
</ul>
```ruby
➤ flutter --version
Flutter 3.3.0 • channel stable • https://github.com/flutter/flutter.git
Framework • revision ffccd96b62 (7 days ago) • 2022-08-29 17:28:57 -0700
Engine • revision 5e9e0e0aa8
Tools • Dart 2.18.0 • DevTools 2.15.0
➤ zig version
0.10.0-dev.2617+47c4d4450
```
<blockquote>
setup development environment:
</blockquote>
<ul>
<li>setup zig environment: https://github.com/hhstore/blog/issues/376</li>
<li>setup flutter environment:</li>
<li>https://github.com/hhstore/blog/issues/216</li>
<li>https://github.com/hhstore/blog/issues/204</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/463136?v=4 | examples.zig | guidoschmidt/examples.zig | 2022-11-23T21:42:06Z | Hodgepodge of examples collected while learning zig | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/guidoschmidt/examples.zig/tags | - | [
"examples",
"examples-zig",
"learn",
"learning",
"zig",
"zigcc",
"ziglang"
]
| 123 | false | 2025-04-15T18:31:35Z | true | false | unknown | github | []
| <a></a>
<a>zig</a> Examples
<blockquote>
Hodgepodge of examples created while learning zig
</blockquote>
Bulid and run the examples
Build all examples:
<code>zig build</code>
Build and run a single example with <code>zig build example_name</code>, e.g.
<code>zig build greet</code> | []
|
https://avatars.githubusercontent.com/u/93405784?v=4 | Furball.Mola | Furball-Engine/Furball.Mola | 2022-09-11T03:21:34Z | A specialized software renderer for Furball.Vixie | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/Furball-Engine/Furball.Mola/tags | - | [
"gamedev",
"graphics",
"graphics-programming",
"software-render",
"software-renderer",
"software-rendering",
"zig",
"ziglang"
]
| 29 | false | 2024-03-11T13:15:57Z | true | false | unknown | github | []
| Furball.Mola
A specialized software renderer for Furball.Vixie
Supports all the functionality required by Furball.Vixie, and not much more, not meant for external consumption. | []
|
https://avatars.githubusercontent.com/u/107726195?v=4 | zig-wiiu | zig-homebrew/zig-wiiu | 2022-06-19T22:05:57Z | Starter pack for developing WiiU games/applications with Zig | master | 0 | 2 | 0 | 2 | https://api.github.com/repos/zig-homebrew/zig-wiiu/tags | - | [
"devkitpro",
"wiiu",
"zig"
]
| 2 | false | 2023-12-22T22:50:39Z | true | false | unknown | github | []
| zig-wiiu
Building works, but running in cemu crashes. Not sure why this is the case.
Getting started
<ul>
<li><a>zig</a></li>
<li><a>devkitPro</a></li>
</ul>
<code>pacman -S wiiu-dev
git clone https://github.com/zig-homebrew/zig-wiiu
cd zig-wiiu/
zig build # then run zig-out/zig-wiiu.rpx with cemu</code>
Resources
<ul>
<li><a>wii-examples</a></li>
<li><a>libogc repository</a></li>
<li><a>libogc documentation</a></li>
</ul> | []
|
https://avatars.githubusercontent.com/u/65933340?v=4 | Learn-Zig | seanpm2001/Learn-Zig | 2022-04-14T23:43:52Z | A repository for showcasing my knowledge of the Zig programming language, and continuing to learn the language. | Learn-Zig | 0 | 2 | 1 | 2 | https://api.github.com/repos/seanpm2001/Learn-Zig/tags | GPL-3.0 | [
"article",
"collection",
"education",
"gpl3",
"gplv3",
"learn",
"learn-zig",
"learn-zig-lang",
"learn-zig-language",
"md",
"seanpm2001",
"seanpm2001-education",
"seanpm2001-life-archive",
"txt",
"zig",
"zig-collection",
"zig-lang",
"zig-language"
]
| 319 | false | 2022-11-06T01:42:21Z | false | false | unknown | github | []
|
By:
<a>Seanpm2001</a>, <a></a> Et; Al.
Top
<code>README.md</code>
Read this article in a different language
<strong>Sorted by:</strong> <code>A-Z</code>
<a>Sorting options unavailable</a>
( <a>af Afrikaans</a> Afrikaans | <a>sq Shqiptare</a> Albanian | <a>am አማርኛ</a> Amharic | <a>ar عربى</a> Arabic | <a>hy հայերեն</a> Armenian | <a>az Azərbaycan dili</a> Azerbaijani | <a>eu Euskara</a> Basque | <a>be Беларуская</a> Belarusian | <a>bn বাংলা</a> Bengali | <a>bs Bosanski</a> Bosnian | <a>bg български</a> Bulgarian | <a>ca Català</a> Catalan | <a>ceb Sugbuanon</a> Cebuano | <a>ny Chichewa</a> Chichewa | <a>zh-CN 简体中文</a> Chinese (Simplified) | <a>zh-t 中國傳統的)</a> Chinese (Traditional) | <a>co Corsu</a> Corsican | <a>hr Hrvatski</a> Croatian | <a>cs čeština</a> Czech | <a>da dansk</a> Danish | <a>nl Nederlands</a> Dutch | <a><strong>en-us English</strong></a> English | <a>EO Esperanto</a> Esperanto | <a>et Eestlane</a> Estonian | <a>tl Pilipino</a> Filipino | <a>fi Suomalainen</a> Finnish | <a>fr français</a> French | <a>fy Frysk</a> Frisian | <a>gl Galego</a> Galician | <a>ka ქართველი</a> Georgian | <a>de Deutsch</a> German | <a>el Ελληνικά</a> Greek | <a>gu ગુજરાતી</a> Gujarati | <a>ht Kreyòl ayisyen</a> Haitian Creole | <a>ha Hausa</a> Hausa | <a>haw Ōlelo Hawaiʻi</a> Hawaiian | <a>he עִברִית</a> Hebrew | <a>hi हिन्दी</a> Hindi | <a>hmn Hmong</a> Hmong | <a>hu Magyar</a> Hungarian | <a>is Íslenska</a> Icelandic | <a>ig Igbo</a> Igbo | <a>id bahasa Indonesia</a> Icelandic | <a>ga Gaeilge</a> Irish | <a>it Italiana/Italiano</a> | <a>ja 日本語</a> Japanese | <a>jw Wong jawa</a> Javanese | <a>kn ಕನ್ನಡ</a> Kannada | <a>kk Қазақ</a> Kazakh | <a>km ខ្មែរ</a> Khmer | <a>rw Kinyarwanda</a> Kinyarwanda | <a>ko-south 韓國語</a> Korean (South) | <a>ko-north 문화어</a> Korean (North) (NOT YET TRANSLATED) | <a>ku Kurdî</a> Kurdish (Kurmanji) | <a>ky Кыргызча</a> Kyrgyz | <a>lo ລາວ</a> Lao | <a>la Latine</a> Latin | <a>lt Lietuvis</a> Lithuanian | <a>lb Lëtzebuergesch</a> Luxembourgish | <a>mk Македонски</a> Macedonian | <a>mg Malagasy</a> Malagasy | <a>ms Bahasa Melayu</a> Malay | <a>ml മലയാളം</a> Malayalam | <a>mt Malti</a> Maltese | <a>mi Maori</a> Maori | <a>mr मराठी</a> Marathi | <a>mn Монгол</a> Mongolian | <a>my မြန်မာ</a> Myanmar (Burmese) | <a>ne नेपाली</a> Nepali | <a>no norsk</a> Norwegian | <a>or ଓଡିଆ (ଓଡିଆ)</a> Odia (Oriya) | <a>ps پښتو</a> Pashto | <a>fa فارسی</a> |Persian <a>pl polski</a> Polish | <a>pt português</a> Portuguese | <a>pa ਪੰਜਾਬੀ</a> Punjabi | No languages available that start with the letter Q | <a>ro Română</a> Romanian | <a>ru русский</a> Russian | <a>sm Faasamoa</a> Samoan | <a>gd Gàidhlig na h-Alba</a> Scots Gaelic | <a>sr Српски</a> Serbian | <a>st Sesotho</a> Sesotho | <a>sn Shona</a> Shona | <a>sd سنڌي</a> Sindhi | <a>si සිංහල</a> Sinhala | <a>sk Slovák</a> Slovak | <a>sl Slovenščina</a> Slovenian | <a>so Soomaali</a> Somali | [<a>es en español</a> Spanish | <a>su Sundanis</a> Sundanese | <a>sw Kiswahili</a> Swahili | <a>sv Svenska</a> Swedish | <a>tg Тоҷикӣ</a> Tajik | <a>ta தமிழ்</a> Tamil | <a>tt Татар</a> Tatar | <a>te తెలుగు</a> Telugu | <a>th ไทย</a> Thai | <a>tr Türk</a> Turkish | <a>tk Türkmenler</a> Turkmen | <a>uk Український</a> Ukrainian | <a>ur اردو</a> Urdu | <a>ug ئۇيغۇر</a> Uyghur | <a>uz O'zbek</a> Uzbek | <a>vi Tiếng Việt</a> Vietnamese | <a>cy Cymraeg</a> Welsh | <a>xh isiXhosa</a> Xhosa | <a>yi יידיש</a> Yiddish | <a>yo Yoruba</a> Yoruba | <a>zu Zulu</a> Zulu ) Available in 110 languages (108 when not counting English and North Korean, as North Korean has not been translated yet <a>Read about it here</a>)
Translations in languages other than English are machine translated and are not yet accurate. No errors have been fixed yet as of March 21st 2021. Please report translation errors <a>here</a>. Make sure to backup your correction with sources and guide me, as I don't know languages other than English well (I plan on getting a translator eventually) please cite <a>wiktionary</a> and other sources in your report. Failing to do so will result in a rejection of the correction being published.
Note: due to limitations with GitHub's interpretation of markdown (and pretty much every other web-based interpretation of markdown) clicking these links will redirect you to a separate file on a separate page that isn't the intended page. You will be redirected to the <a>.github folder</a> of this project, where the README translations are hosted.
Translations are currently done with Bing translate and DeepL. Support for Google Translate translations is coming to a close due to privacy concerns.
Index
<a>00.0 - Top</a>
<blockquote>
<a>00.1 - Title</a>
<a>00.2 - Read this article in a different language</a>
<a>00.3 - Index</a>
</blockquote>
<a>01.0 - Description</a>
<a>02.0 - About</a>
<a>03.0 - Wiki</a>
<a>04.0 - History</a>
<blockquote>
<a>04.1 - Pre-history</a>
<a>04.2 - Alpha History</a>
<a>04.3 - Beta History</a>
<a>04.4 - Modern History</a>
</blockquote>
<a>05.0 - Copying</a>
<a>06.0 - Credits</a>
<a>07.0 - Installation</a>
<a>08.0 - Version history</a>
<a>09.0 - Version history</a>
<a>10.0 - Software status</a>
<a>11.0 - Sponsor info</a>
<a>12.0 - Contributers</a>
<a>13.0 - Issues</a>
<blockquote>
<a>13.1 - Current issues</a>
<a>13.2 - Past issues</a>
<a>13.3 - Past pull requests</a>
<a>13.4 - Active pull requests</a>
</blockquote>
<a>14.0 - Resources</a>
<a>15.0 - Contributing</a>
<a>16.0 - About README</a>
<a>17.0 - README Version history</a>
<a>18.0 - Footer</a>
<blockquote>
<a>18.9 - End of file</a>
</blockquote>
About
See above.
Wiki
<a>Click/tap here to view this projects Wiki</a>
If the project has been forked, the Wiki was likely removed. Luckily, I include an embedded version. You can view it <a>here</a>.
History
Write about this projects history here.
Pre-history
No pre-history to show for this project.
Alpha history
No Alpha history to show for this project.
Beta history
No Beta history to show for this project.
Modern history
No Modern history to show for this project.
Copying
View the copying license for this project <a>here</a> (if you haven't built the project yet with the makefile, here is the original link: <a>COPYINGL</a>
Please note that you also have to follow the rules of the GNU General Public License v3 (GPL3) which you can view <a>here</a>
Credits
View the credits file for this project and see the people who got together to make this project by <a>clicking/tapping here</a>
Installation
View the installation instructions file for this project <a>here</a>
Requirements: Read the instructions for more info, and get the latest up-to-date instructions <a>here</a>
Sponsor info
You can sponsor this project if you like, but please specify what you want to donate to. <a>See the funds you can donate to here</a>
You can view other sponsor info <a>here</a>
Try it out! The sponsor button is right up next to the watch/unwatch button.
Version history
<strong>Version history currently unavailable</strong>
<strong>No other versions listed</strong>
Software status
All of my works are free some restrictions. DRM (<strong>D</strong>igital <strong>R</strong>estrictions <strong>M</strong>anagement) is not present in any of my works.
This sticker is supported by the Free Software Foundation. I never intend to include DRM in my works.
I am using the abbreviation "Digital Restrictions Management" instead of the more known "Digital Rights Management" as the common way of addressing it is false, there are no rights with DRM. The spelling "Digital Restrictions Management" is more accurate, and is supported by <a>Richard M. Stallman (RMS)</a> and the <a>Free Software Foundation (FSF)</a>
This section is used to raise awareness for the problems with DRM, and also to protest it. DRM is defective by design and is a major threat to all computer users and software freedom.
Image credit: <a>defectivebydesign.org/drm-free/...</a>
Contributers
Currently, I am the only contributer. Contributing is allowed, as long as you follow the rules of the <a>CONTRIBUTING.md</a> file.
<blockquote>
<ul>
<li>
<ol>
<li><a>seanpm2001</a> - x commits (As of Yr, DoW, Month, DoM, at ##:## a/pm)</li>
</ol>
</li>
<li>
<ol>
<li>No other contributers.</li>
</ol>
</li>
</ul>
</blockquote>
Issues
Current issues
<ul>
<li>
None at the moment
</li>
<li>
No other current issues
</li>
</ul>
If the repository has been forked, issues likely have been removed. Luckily I keep an archive of certain images <a>here</a>
<a>Read the privacy policy on issue archival here</a>
<strong>TL;DR</strong>
I archive my own issues. Your issue won't be archived unless you request it to be archived.
Past issues
<ul>
<li>
None at the moment
</li>
<li>
No other past issues
</li>
</ul>
If the repository has been forked, issues likely have been removed. Luckily I keep an archive of certain images <a>here</a>
<a>Read the privacy policy on issue archival here</a>
<strong>TL;DR</strong>
I archive my own issues. Your issue won't be archived unless you request it to be archived.
Past pull requests
<ul>
<li>
None at the moment
</li>
<li>
No other past pull requests
</li>
</ul>
If the repository has been forked, issues likely have been removed. Luckily I keep an archive of certain images <a>here</a>
<a>Read the privacy policy on issue archival here</a>
<strong>TL;DR</strong>
I archive my own issues. Your issue won't be archived unless you request it to be archived.
Active pull requests
<ul>
<li>
None at the moment
</li>
<li>
No other active pull requests
</li>
</ul>
If the repository has been forked, issues likely have been removed. Luckily I keep an archive of certain images <a>here</a>
<a>Read the privacy policy on issue archival here</a>
<strong>TL;DR</strong>
I archive my own issues. Your issue won't be archived unless you request it to be archived.
Resources
Here are some other resources for this project:
<a>Project language file A</a>
<a>Join the discussion on GitHub</a>
No other resources at the moment.
Contributing
Contributing is allowed for this project, as long as you follow the rules of the <code>CONTRIBUTING.md</code> file.
<a>Click/tap here to view the contributing rules for this project</a>
About README
<strong>File type:</strong> <code>Markdown Document (*.md *.mkd *.markdown)</code>
<strong>File version:</strong> <code>0.1.6 (Monday, August 23rd 2021 at 6:37 pm)</code>
<strong>Line count (including blank lines and compiler line):</strong> <code>0,407</code>
README version history
Version 0.1 (Sunday, March 21st 2021 at 7:50 pm)
<blockquote>
Changes:
<ul>
<li>
Started the file
</li>
<li>
Added the title section
</li>
<li>
Added the index
</li>
<li>
Added the about section
</li>
<li>
Added the Wiki section
</li>
<li>
Added the version history section
</li>
<li>
Added the issues section.
</li>
<li>
Added the past issues section
</li>
<li>
Added the past pull requests section
</li>
<li>
Added the active pull requests section
</li>
<li>
Added the contributors section
</li>
<li>
Added the contributing section
</li>
<li>
Added the about README section
</li>
<li>
Added the README version history section
</li>
<li>
Added the resources section
</li>
<li>
Added a software status section, with a DRM free sticker and message
</li>
<li>
Added the sponsor info section
</li>
</ul>
</blockquote>
<strong>ITERATION 5</strong>
<blockquote>
<ul>
<li>
Updated the title section
</li>
<li>
Updated the index
</li>
<li>
Added the history section
</li>
<li>
Updated the file info section
</li>
<li>
Updated the file history section
</li>
</ul>
</blockquote>
<strong>ITERATION 6</strong>
<blockquote>
<ul>
<li>
Updated the title section
</li>
<li>
Fixed and update template links
</li>
<li>
Updated the index
</li>
<li>
Added the copying section
</li>
<li>
Added the credits section
</li>
<li>
Added the installation section
</li>
<li>
Updated the resources section
</li>
<li>
Updated the contributors section
</li>
<li>
Added the technical notes section
</li>
<li>
Updated the footer
</li>
<li>
Updated the file info section
</li>
<li>
Updated the file history section
</li>
<li>
No other changes in version 0.1
</li>
</ul>
</blockquote>
Version 1 (Coming soon)
<blockquote>
Changes:
<ul>
<li>
Coming soon
</li>
<li>
No other changes in version 1
</li>
</ul>
</blockquote>
Version 2 (Coming soon)
<blockquote>
Changes:
<ul>
<li>
Coming soon
</li>
<li>
No other changes in version 2
</li>
</ul>
</blockquote>
You have reached the end of the README file
( <a>Back to top</a> | <a>Exit to GitHub</a> | <a>Exit to Bing</a> | <a>Exit to DuckDuckGo</a> | <a>Exit to Ecosia</a> )
EOF
| []
|
https://avatars.githubusercontent.com/u/25238?v=4 | jumper | jsyrjala/jumper | 2022-05-18T16:35:35Z | Platformer game with zig and WASM-4. Nitor codecamp. | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/jsyrjala/jumper/tags | - | [
"wasm",
"wasm-4",
"webassembly",
"zig"
]
| 113 | false | 2024-08-19T09:05:16Z | true | false | unknown | github | []
| jumper
A game written in <a>Zig</a> for the <a>WASM-4</a> fantasy console.
Running in https://jsyrjala.github.io/jumper/
Development
Install Zig: https://ziglang.org/download/
Install WASM-4:
<code>shell
npm install wasm4</code>
Run development server:
<code>shell
w4 watch</code>
For more info about setting up WASM-4, see the <a>quickstart guide</a>.
Building
Build the cart by running:
<code>shell
zig build -Drelease-small=true</code>
Then run it with:
<code>shell
w4 run zig-out/lib/cart.wasm</code>
Bundling
Bundling creates a single all-in-one HTML file that can be deployed to web server.
<code>shell
w4 bundle --html zig-out/index.html --title Jumper --description "Simple platformer" zig-out/lib/cart.wasm</code>
Links
<ul>
<li><a>WASM-4 Documentation</a>: Learn more about WASM-4.</li>
<li><a>Zig documentation</a>: Learn more about Zig.</li>
</ul> | []
|
https://avatars.githubusercontent.com/u/1562827?v=4 | roc-cli-platform-zig | travisstaloch/roc-cli-platform-zig | 2022-10-10T04:37:41Z | An experimental roc lang cli platform in zig | main | 0 | 2 | 0 | 2 | https://api.github.com/repos/travisstaloch/roc-cli-platform-zig/tags | MIT | [
"hacktoberfest",
"roc-lang",
"zig"
]
| 52 | false | 2023-09-29T05:24:23Z | false | false | unknown | github | []
| cli-platform-zig
An experimental <a>roc lang</a> cli platform in <a>zig</a>. Adapated from roc's <a>rust cli platform</a>.
dependencies
<ul>
<li>a roc compiler in PATH</li>
<li>zig version 0.9.1 in PATH</li>
</ul>
usage
<ol>
<li>clone this repo</li>
<li>reference <a>platform/main.roc</a> in your roc app like this:
<code>packages { pf: "path/to/platform/main.roc" }</code> (see <a>test/main.roc</a> for an example)</li>
</ol>
test
<code>console
./test/run.sh # builds and runs test/main.roc and other testing scripts</code>
status
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Stdout.line, Stderr.line
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> File.readBytes - includes some error handling
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Process.withArgs
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Env.{var,cwd,setCwd,exePath}
see <a>test/main.roc</a> to see what works.
notes
<ul>
<li>copied to platform/ from roc repo</li>
<li>examples/cli/tui-platform/host.zig</li>
<li>examples/cli/cli-platform/main.roc</li>
<li>examples/cli/cli-platform/*.roc</li>
<li>crates/compiler/builtins/bitcode/src/{utils,list}.zig</li>
</ul>
todo
<ul>
<li>File.write, delete, ...</li>
</ul>
contributors
<ul>
<li>bhansconnect@github</li>
</ul> | []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.