### Initialize Project and Install bun-zigar (Shell)
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
Commands to create a new project directory, initialize a Bun.js project, and install the bun-zigar package. This sets up the basic structure for the application.
```shell
mkdir hello
cd hello
bun init
bun install bun-zigar
bunx bun-zigar preload
mkdir zig
```
--------------------------------
### Initialize Project and Install Dependencies (Shell)
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(NW.js)
This snippet demonstrates the initial setup of a project directory, navigation into it, initializing a Node.js project with npm, and installing the 'node-zigar' package. It also creates necessary subdirectories for source files, images, and Zig code.
```sh
mkdir filter
cd filter
npm init -y
npm install node-zigar
mkdir src img zig
```
--------------------------------
### Initialize Node.js Project and Install Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Tarball-server
This snippet demonstrates the initial setup for a Node.js project. It creates a directory, initializes an npm project, and installs the 'fastify' web framework and 'node-zigar' development dependency. It also sets up necessary subdirectories for Zig code.
```sh
mkdir filter
cd filter
npm init -y
npm install fastify
npm install --save-dev node-zigar
mkdir src zig
```
--------------------------------
### Initialize and Configure node-zigar Project
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Node)
Commands to set up the project directory structure, install the node-zigar dependency, and configure the package.json for execution.
```shell
mkdir hello
cd hello
npm init -y
npm install node-zigar
mkdir src zig
```
```json
{
"type": "module",
"scripts": {
"start": "node --loader=node-zigar --no-warnings src/index.js",
"start:cjs": "node src/index.cjs",
"start:async": "node src/index.async.js"
}
}
```
--------------------------------
### Initialize Project and Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Node)
Commands to create the project directory structure and install necessary dependencies including Fastify, Sharp, and node-zigar.
```shell
mkdir filter
cd filter
npm init -y
npm install fastify sharp node-zigar
mkdir src zig img
```
--------------------------------
### Database Setup and Server Initialization
Source: https://github.com/chung-leong/zigar/wiki/MySQL
Initializes the database connection with specific credentials and starts the Fastify server. It handles incoming requests and manages database lifecycle hooks.
```javascript
openDatabase({
host: '172.17.0.2',
username: 'zig_user',
password: 'password123',
database: 'testdb',
threads: 4,
});
const address = await fastify.listen({ port: 3000 });
console.log(`Listening at ${address}`);
fastify.addHook('onClose', () => closeDatabase());
```
--------------------------------
### Install and Configure Zigar for Runtimes and Bundlers
Source: https://context7.com/chung-leong/zigar/llms.txt
Provides installation commands and configuration examples for Node.js, Bun.js, Vite/Rollup, and Webpack environments.
```shell
npm install node-zigar
npm install --save-dev rollup-plugin-zigar
npm install --save-dev zigar-loader
bun install bun-zigar
bunx bun-zigar preload
```
```javascript
// Node.js ESM usage
import { hello } from '../zig/hello.zig';
hello();
// Vite configuration
import zigar from 'rollup-plugin-zigar';
export default defineConfig({ plugins: [zigar()] });
// Webpack configuration
module.exports = { module: { rules: [{ test: /\.zig$/, use: 'zigar-loader' }] } };
```
--------------------------------
### Initializing node-zigar configuration
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Node)
CLI command to generate the initial node-zigar.config.json file for project settings.
```bash
npx zigar init
```
--------------------------------
### Invoke Zig from JavaScript
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Node)
Examples showing how to import and execute Zig functions using ESM, CommonJS, and dynamic CommonJS require patterns.
```javascript
import { hello } from '../zig/hello.zig';
hello();
```
```javascript
require('node-zigar/cjs');
const { hello } = require('../zig/hello.zig');
hello();
```
```javascript
const { createRequire } = await import('node-zigar/cjs');
const { hello } = createRequire(import.meta.url)('../zig/hello.zig');
hello();
```
--------------------------------
### Start Fastify Server (Shell)
Source: https://github.com/chung-leong/zigar/wiki/Saving-to-server-over-HTTP-2
Starts the Fastify HTTP server using Node.js. This command should be run after the server code is in place and dependencies are installed.
```shell
node src/server.js
```
--------------------------------
### Project Setup Files
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Webpack)
Standard entry point, HTML template, Babel configuration, and NPM scripts for the project.
```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
,
)
```
```html
Webpack + React + Zigar
```
```json
{
"presets": [
"@babel/preset-env",
[ "@babel/preset-react", { "runtime": "automatic" } ]
]
}
```
```json
{
"scripts": {
"dev": "webpack serve --mode development",
"build": "webpack --mode production",
"preview": "http-server ./dist"
}
}
```
--------------------------------
### Start Electron App
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Electron)
Starts the Electron application using the npm run script. This command compiles and launches the Electron app, which will then execute the integrated Zig code.
```sh
npm run start
```
--------------------------------
### Build and preview commands
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Rollup)
Shell commands for building the project distribution and starting a local development server.
```bash
npm run build
```
```bash
npm run preview
```
--------------------------------
### Initialize Project and Install Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Donut
Commands to scaffold a new Vite project and install the required Zigar rollup plugin.
```sh
npm create vite@latest donut -- --template react
cd donut
npm install
npm install --save-dev rollup-plugin-zigar
mkdir zig
```
--------------------------------
### Initialize Vite Project and Install Dependencies
Source: https://github.com/chung-leong/zigar/wiki/SHA1-digest-(Vite)
This sequence of commands initializes a new Vite project with React and JavaScript (SWC), installs necessary dependencies including rollup-plugin-zigar, and sets up a directory for Zig files.
```shell
npm create vite@latest
cd sha1
npm install
npm install --save-dev rollup-plugin-zigar
mkdir zig
```
--------------------------------
### Initialize Node Project and Install Dependencies (Shell)
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Rollup)
Initializes a new Node.js project, creates necessary directories, and installs Rollup, Zigar plugins, and other development dependencies. This sets up the build environment for the project.
```sh
mkdir filter
cd filter
npm init -y
npm install --save-dev rollup rollup-plugin-zigar @rollup/plugin-terser @rollup/plugin-node-resolve http-server
mkdir src zig
```
--------------------------------
### Initialize and Configure Project
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Bun)
Commands to initialize a Bun project, install necessary dependencies including Fastify, Sharp, and bun-zigar, and prepare the directory structure.
```shell
mkdir filter
cd filter
bun init
bun install fastify sharp bun-zigar
bunx bun-zigar preload
mkdir zig img
```
--------------------------------
### Initialize and Configure Project
Source: https://github.com/chung-leong/zigar/wiki/Creating-website-backed-by-a-client-side-database
Commands to scaffold a Vite project, install Zigar dependencies, and fetch the zig-sqlite package.
```shell
npm create vite@latest
cd sqlite-rwt
npm install
npm install --save-dev rollup-plugin-zigar
mkdir zig
cd zig
touch build.zig
zig fetch --save https://github.com/vrischmann/zig-sqlite/archive/refs/heads/master.zip
npx zigar extra
```
--------------------------------
### Initialize Project and Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Webpack)
Sets up the project directory, initializes npm, and installs necessary build tools and loaders including zigar-loader for WebAssembly integration.
```shell
mkdir filter
cd filter
npm init -y
npm install --save-dev react react-dom webpack webpack-cli webpack-dev-server css-loader style-loader file-loader html-webpack-plugin @babel/core @babel/preset-env @babel/preset-react babel-loader http-server zigar-loader
mkdir src zig img
```
--------------------------------
### Verifying deployment with Docker
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Node)
Command to test the application in an Alpine Linux environment to ensure cross-compilation compatibility.
```bash
docker run --rm -v ./:/test -w /test node:alpine npm run start
```
--------------------------------
### Initialize Vite Project and Install Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Tarball-viewer
Commands to scaffold a new React project using Vite and install the necessary Zigar rollup plugin.
```shell
npm create vite@latest
cd code-viewer
npm install
npm install --save-dev rollup-plugin-zigar
mkdir zig
```
--------------------------------
### JavaScript WASI Setup and Print
Source: https://github.com/chung-leong/zigar/wiki/System-object-‣-wasi
A JavaScript example demonstrating how to set up the WASI environment and use the `print` function. It imports necessary modules from Node.js and the Zigar WASI implementation. The code initializes WASI with specific configurations and then calls the `print` function with the current file's path.
```javascript
import { fileURLToPath } from 'node:url';
import { WASI } from 'node:wasi';
import { __zigar, print } from './system-object-wasi-example-1.zig';
const { set } = __zigar;
set('wasi', new WASI({
version: 'preview1',
args: [],
env: {},
preopens: { '/': '/' },
}));
const path = fileURLToPath(import.meta.url);
print(path);
```
```javascript
import { fileURLToPath } from 'node:url';
import { WASI } from 'node:wasi';
import { __zigar, print } from './system-object-wasi-example-1.zig';
const { set } = __zigar;
set('wasi', new WASI({
version: 'preview1',
args: [],
env: {},
preopens: { '/': '/' },
}));
const path = fileURLToPath(import.meta.url);
print(path);
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/chung-leong/zigar/blob/main/node-zigar/demos/electron/raylib/README.md
Installs all necessary project dependencies using npm. This command should be run after cloning the repository to set up the development environment.
```bash
npm install
```
--------------------------------
### Building production modules
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Node)
CLI command to trigger the compilation of Zig modules and Node.js native addons based on the configuration file.
```bash
npx zigar build
```
--------------------------------
### Initialize Electron Project
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Electron)
Commands to initialize a new Electron project, create necessary directories, and install the node-zigar dependency.
```shell
npm init electron-app@latest filter
cd filter
mkdir zig img
npm install node-zigar
```
--------------------------------
### Initialize Node Project and Install Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(NW.js)
Sets up a new Node.js project and installs the node-zigar package. This is the foundational step for building the application.
```sh
mkdir hello
cd hello
npm init -y
npm install node-zigar
mkdir src zig
```
--------------------------------
### Initialize Project Environment
Source: https://github.com/chung-leong/zigar/wiki/SHA1-digest-(NW.js)
Commands to set up the project directory structure and install the necessary node-zigar dependencies.
```sh
mkdir sha1
cd sha1
npm init -y
npm install node-zigar
mkdir src zig
```
--------------------------------
### Initialize Node.js Project for Zig C Functions
Source: https://github.com/chung-leong/zigar/wiki/Snprintf
Sets up a new Node.js project, creates necessary directories for source and Zig files, and installs the 'node-zigar' package. This is the initial setup for integrating Zig with Node.js.
```sh
mkdir snprintf
cd snprintf
npm init -y
npm install node-zigar
mkdir src zig
```
--------------------------------
### Configure npm Start Script
Source: https://github.com/chung-leong/zigar/wiki/MySQL
Adds a 'start' script to the `package.json` file that uses Node.js with the `node-zigar` loader to run the main JavaScript file. This enables the execution of Zig code within the Node.js environment.
```json
"scripts": {
"start": "node --loader=node-zigar --no-warnings src/index.js",
```
--------------------------------
### Implement Fastify Server with Sharp
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Node)
A Fastify server setup that serves an HTML page with image tags and a route handler to process and resize images using the Sharp library.
```javascript
import Fastify from 'fastify';
import Sharp from 'sharp';
import { fileURLToPath } from 'url';
const fastify = Fastify();
fastify.get('/', (req, reply) => {
const name = 'sample';
const filter = 'sepia';
const tags = [
{ width: 150, height: 100, intensity: 0.0 },
{ width: 150, height: 100, intensity: 0.3 },
{ width: 300, height: 300, intensity: 0.2 },
{ width: 300, height: 300, intensity: 0.4 },
{ width: 400, height: 400, intensity: 0.3 },
{ width: 500, height: 200, intensity: 0.5 },
].map((params) => {
const json = JSON.stringify(params);
const base64 = Buffer.from(json).toString('base64');
const url = `img/${name}/${filter}/${base64}`;
return `
`;
});
reply.type('text/html');
return `\n\n \n \n Image filter test\n \n ${tags.join('')}\n`;
});
fastify.get('/img/:name/:filter/:base64', async (req, reply) => {
const { name, filter, base64 } = req.params;
const json = Buffer.from(base64, 'base64');
const params = JSON.parse(json);
const url = new URL(`../img/${name}.png`, import.meta.url);
const path = fileURLToPath(url);
const { width, height, ...filterParams } = params;
const inputImage = Sharp(path).ensureAlpha().resize(width, height);
const { data, info } = await inputImage.raw().toBuffer({ resolveWithObject: true });
const outputImage = Sharp(data, { raw: info, });
reply.type('image/jpeg');
return outputImage.jpeg().toBuffer();
});
const address = await fastify.listen({ port: 3000 });
console.log(`Listening at ${address}`);
```
--------------------------------
### Initialize Node.js and Zigar Project
Source: https://github.com/chung-leong/zigar/wiki/Raylib
Commands to scaffold a new Node project, install Zigar dependencies, and fetch the Raylib library for Zig.
```bash
mkdir raylib
cd raylib
npm init -y
npm install node-zigar
mkdir src zig
cd zig
touch build.zig
zig fetch --save https://github.com/raysan5/raylib/archive/60eb3a14d7d1bc27adfd1e5586fefa540016edab.zip
npx zigar extra
```
--------------------------------
### Build and Test Zigar Modules
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Node)
Commands for building Zigar libraries and testing the application using Docker.
```bash
npx zigar build
docker run --rm -v ./:/test -w /test -p 3000 node:alpine npm run start
```
--------------------------------
### Initialize and Configure Zigar Project
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Vite)
Commands to scaffold a Vite project, install dependencies, and configure the rollup-plugin-zigar in the Vite configuration file.
```bash
npm create vite@latest hello
cd hello
npm install
npm install --save-dev rollup-plugin-zigar
mkdir zig
```
```javascript
import react from '@vitejs/plugin-react-swc';
import zigar from 'rollup-plugin-zigar';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [ react(), zigar() ],
})
```
--------------------------------
### Install Node Dependencies and Node-Zigar
Source: https://github.com/chung-leong/zigar/wiki/SQLite
Navigates into the project directory, installs initial npm packages, and then adds the node-zigar module. Node-zigar is essential for bridging Zig code with Node.js environments.
```sh
cd sqlite
npm install
npm install node-zigar
```
--------------------------------
### Initialize bun-zigar Configuration (Shell)
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
Command to generate a default bun-zigar configuration file. This file is used to manage compilation settings, module mappings, and cross-compilation targets.
```shell
bunx bun-zigar init
```
--------------------------------
### Build bun-zigar Modules (Shell)
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
Command to compile the Zig code into platform-specific libraries based on the bun-zigar configuration. This prepares the application for deployment.
```shell
bunx bun-zigar build
```
--------------------------------
### Invoke Zig Functions from JavaScript
Source: https://github.com/chung-leong/zigar/wiki/SQLite
Examples of calling the Zig-defined database functions from an Electron/Node.js environment.
```javascript
const db = openDb(path);
printAlbums(db, 'best');
closeDb(db);
// Using the return-based approach
for(const album of findAlbums(db, 'best')) {
console.log(`${album.AlbumId} ${album.Title.string}`);
}
```
--------------------------------
### Invoke Zig from React
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Vite)
Importing the Zig function into a React component and triggering it via a button click event.
```javascript
import { hello } from '../zig/hello.zig';
function App() {
return (
);
}
```
--------------------------------
### bun-zigar Configuration File
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
A TOML configuration file for bun-zigar. It specifies optimization level, maps Zig source files to .zigar modules, and defines cross-compilation targets for different platforms and architectures.
```toml
optimize = "ReleaseSmall"
[modules."lib/hello.zigar"]
source = "zig/hello.zig"
[[targets]]
platform = "linux"
arch = "x64"
[[targets]]
platform = "linux"
arch = "arm64"
[[targets]]
platform = "linux-musl"
arch = "x64"
[[targets]]
platform = "linux-musl"
arch = "arm64"
```
--------------------------------
### Defining node-zigar build configuration
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Node)
JSON configuration schema for setting optimization levels, mapping source files to modules, and specifying cross-compilation targets.
```json
{
"optimize": "ReleaseSmall",
"modules": {
"lib/hello.zigar": {
"source": "zig/hello.zig"
}
},
"targets": [
{ "platform": "linux", "arch": "x64" },
{ "platform": "linux", "arch": "arm64" },
{ "platform": "linux-musl", "arch": "x64" },
{ "platform": "linux-musl", "arch": "arm64" }
]
}
```
--------------------------------
### Initialize Electron App
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Electron)
Initializes a new Electron application using npm and the electron-app package with the vite template. This command sets up the basic project structure and dependencies for an Electron app.
```sh
npm init electron-app@latest hello
```
--------------------------------
### Start Thread Pool (Zig)
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Node)
Initializes the work queue with a specified number of jobs (threads). This function is called from JavaScript to set up the thread pool.
```zig
pub fn startThreadPool(count: u32) !void {
try work_queue.init(.{
.allocator = internal_allocator,
.stack_size = 65536,
.n_jobs = count,
});
}
```
--------------------------------
### Initialize and Wait for Threads (Zig)
Source: https://github.com/chung-leong/zigar/wiki/zigar.thread.WorkQueue(ns).waitAsync(self,-promise)
Initializes a WorkQueue with a specified number of threads and waits for all threads to start. It handles potential errors during file opening in the worker thread. Dependencies include the 'std' and 'zigar' libraries.
```zig
const std = @import("std");
const zigar = @import("zigar");
const WorkQueue = zigar.thread.WorkQueue(worker);
var work_queue: WorkQueue = .{};
pub fn startup(num_threads: usize, promise: zigar.function.PromiseArgOf(WorkQueue.waitAsync)) !void {
try work_queue.init(.{
.n_jobs = num_threads,
.thread_start_params = .{"/tmp/no-where"},
});
work_queue.waitAsync(promise);
}
const worker = struct {
threadlocal var file: ?std.fs.File = null;
pub fn onThreadStart(path: []const u8) !void {
file = try std.fs.openFileAbsolute(path, .{});
}
};
```
--------------------------------
### WorkQueue Startup API
Source: https://github.com/chung-leong/zigar/wiki/zigar.thread.WorkQueue(ns).waitAsync(self,-promise)
Initiates the startup process for a work queue. It waits for all specified threads to start and call `ns.onThreadStart()` (if defined). The provided promise is resolved upon successful startup or rejected if any thread encounters an error.
```APIDOC
## POST /work-queue/startup
### Description
Initiates the startup process for a work queue. It waits for all specified threads to start and call `ns.onThreadStart()` (if defined). The provided promise is resolved upon successful startup or rejected if any thread encounters an error.
### Method
POST
### Endpoint
/work-queue/startup
### Parameters
#### Query Parameters
- **num_threads** (usize) - Required - The number of threads to start.
- **promise** (PromiseArgOf(WorkQueue.waitAsync)) - Required - The promise to resolve or reject upon completion of thread startup.
#### Request Body
```json
{
"num_threads": 4,
"promise": ""
}
```
### Request Example
```js
import { startup } from './work-queue-example-5.zig';
await startup(4);
```
### Response
#### Success Response (200)
- **status** (string) - Indicates the operation was successful.
#### Error Response (e.g., 500)
- **error** (string) - A message describing the error.
- **details** (object) - Additional error information, potentially including a `number` field.
#### Response Example
```json
{
"status": "success"
}
```
```json
{
"error": "File not found",
"details": { "number": 51 }
}
```
```
--------------------------------
### Run MariaDB using Docker
Source: https://github.com/chung-leong/zigar/wiki/MySQL
This command starts a MariaDB container in detached mode, making it accessible for testing. It sets an environment variable to allow empty root passwords for easier initial setup.
```sh
docker run --detach --name some-mariadb --env MARIADB_ALLOW_EMPTY_ROOT_PASSWORD=1 mariadb:latest
```
--------------------------------
### Embed WASM in JS for Production Build
Source: https://github.com/chung-leong/zigar/wiki/SHA1-digest-(Vite)
This JavaScript configuration modifies the Vite setup to embed the compiled WebAssembly code directly into the JavaScript bundle. This can improve loading performance by reducing the number of network requests.
```javascript
export default defineConfig({
plugins: [ react(), zigar({ embedWASM: true }) ],
})
```
--------------------------------
### Hello World in Zig and JavaScript
Source: https://github.com/chung-leong/zigar/wiki/Introduction
Demonstrates the basic structure of a Zig program and how to import and execute that Zig function within a JavaScript environment using Zigar.
```zig
const std = @import("std");
pub fn main() void {
std.debug.print("Hello world!", .{});
}
```
```javascript
import { main } from './hello.zig';
main();
```
--------------------------------
### Slice PtrI32 with JavaScript
Source: https://github.com/chung-leong/zigar/wiki/Special-method-‣-slice(start,-end)
Demonstrates creating and manipulating slices of a Zig `PtrI32` type using JavaScript. It shows how to create slices using start and end indices (inclusive and exclusive), negative indices, and how modifications to a slice affect the original data.
```javascript
import { PtrI32 } from './slice-example-1.zig';
const sliceO = new PtrI32([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]);
const sliceA = sliceO.slice(1, 5);
console.log('SliceA before:', [ ...sliceA ]);
sliceA[0] = 100;
console.log('SliceA after:', [ ...sliceA ]);
console.log('SliceO after:', [ ...sliceO ]);
const sliceB = sliceO.slice(-9, -1);
console.log('SliceB:', [ ...sliceB ]);
const sliceC = sliceO.slice();
console.log('SliceC:', [ ...sliceC ]);
```
--------------------------------
### Create Zig Directory and File
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Electron)
Navigates into the created Electron app directory and creates a 'zig' subdirectory to store Zig source files. This organizes the Zig code separately within the project.
```sh
cd hello
mkdir zig
```
--------------------------------
### Build Electron Packages for Linux
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Electron)
Use the npm run make command to build Electron packages for Linux, specifying the desired platforms and architectures. This process may take time as it involves downloading Electron executables.
```bash
npm run make -- --platform linux --arch x64,arm64
```
--------------------------------
### Multithreaded Async with WorkQueue in Zigar and JavaScript
Source: https://context7.com/chung-leong/zigar/llms.txt
Demonstrates the use of Zigar's `WorkQueue` for managing thread pools and dispatching asynchronous tasks. The example shows initializing a work queue, starting and stopping it, and calculating factorials concurrently. This is crucial for performance-intensive operations that can benefit from parallel execution.
```zig
const std = @import("std");
const zigar = @import("zigar");
var work_queue: zigar.thread.WorkQueue(thread_ns) = .{};
pub fn start(threads: usize) !void {
try work_queue.init(.{
.allocator = zigar.mem.getDefaultAllocator(),
.n_jobs = threads,
});
}
pub fn stop(promise: zigar.function.Promise(void)) void {
work_queue.deinitAsync(promise);
}
const Promise = zigar.function.PromiseOf(thread_ns.calcFactorial);
pub fn calcFactorial(n: u32, promise: Promise) !void {
try work_queue.push(thread_ns.calcFactorial, .{n}, promise);
}
const thread_ns = struct {
pub fn calcFactorial(n: u32) !u4096 {
if (n == 0) return 1;
var f: u4096 = n;
var i = n - 1;
while (i > 0) : (i -= 1) {
f, const overflow_bit = @mulWithOverflow(f, i);
if (overflow_bit != 0) return error.IntegerOverflow;
}
return f;
}
};
```
--------------------------------
### JavaScript Import and Call Zig Function (Development)
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
JavaScript code that imports the 'hello' function from the Zig file and calls it. This is used during development before configuring for deployment.
```javascript
import { hello } from '../zig/hello.zig';
hello();
```
--------------------------------
### Build Electron Packages for Windows
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Electron)
Use the npm run make command to build Electron packages for Windows, specifying the desired platforms and architectures. This command is executed after building for Linux.
```bash
npm run make -- --platform win32 --arch x64,ia32,arm64
```
--------------------------------
### Initialize Input and Process Output in JavaScript
Source: https://github.com/chung-leong/zigar/wiki/Image-filter-(Bun)
Demonstrates initializing the Zigar input object from JavaScript and consuming the processed output buffer using Sharp.
```javascript
const input = {
src: {
data,
width: info.width,
height: info.height,
}
};
// Process output
const outputImage = Sharp(output.dst.data, { raw: info });
```
--------------------------------
### Install Node-Zigar and Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Lua-interpreter
Installs the node-zigar module and other project dependencies after navigating into the project directory. This step ensures that the necessary packages for Zig integration are available.
```sh
cd lua
npm install
npm install node-zigar
```
--------------------------------
### JSON Representation of Zigar Numeric Types
Source: https://github.com/chung-leong/zigar/wiki/examples/bare-union-example-1d.txt
Presents a JSON object that represents Zigar's numeric types. This example shows how these types are serialized into a standard JSON format, where BigInt is typically represented as a standard number if within safe integer limits, or as a string for larger values (though this example uses a standard number).
```json
{
"integer": 1234567890,
"big_integer": 1234567890,
"decimal": 6.09957582e-315,
"complex": {
"re": 6.09957582e-315,
"im": 0
}
}
```
--------------------------------
### Initialize and Configure Project Dependencies
Source: https://github.com/chung-leong/zigar/wiki/Client-side-SQLite
Commands to scaffold a new Vite project, install the Zigar rollup plugin, and fetch the zig-sqlite dependency using the Zig package manager.
```shell
npm create vite@latest
cd sqlite
npm install
npm install --save-dev rollup-plugin-zigar
mkdir zig
cd zig
touch build.zig
zig fetch --save https://github.com/vrischmann/zig-sqlite/archive/refs/heads/master.zip
npx zigar extra
```
--------------------------------
### Zig Memory Management Example
Source: https://github.com/chung-leong/zigar/wiki/examples/generator-example-5.txt
Provides examples of memory allocation and deallocation in Zig. This snippet likely demonstrates using an allocator to manage memory for various data structures.
```zig
const std = @import("std");
pub fn main() !void {
var allocator = std.heap.page_allocator;
// Allocate memory for an integer
var ptr = try allocator.create(i32);
defer allocator.destroy(ptr);
ptr.* = 123;
std.debug.print("Allocated integer: {d}\\n", .{ptr.*});
// Allocate memory for a struct
const MyStruct = struct {
x: i32,
y: f32,
};
var struct_ptr = try allocator.create(MyStruct);
defer allocator.destroy(struct_ptr);
struct_ptr.x = 456;
struct_ptr.y = 7.89;
std.debug.print("Allocated struct: {{ .x = {d}, .y = {d} }}\\n", .{ struct_ptr.x, struct_ptr.y });
}
```
--------------------------------
### JavaScript Import and Call Zig Function (Deployment)
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
JavaScript code that imports the 'hello' function from a .zigar file. This import path is used after configuring bun-zigar for deployment, referencing a more permanent location for compiled modules.
```javascript
import { hello } from '../lib/hello.zigar';
hello();
```
--------------------------------
### Install node-zigar
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Electron)
Installs the node-zigar package, which is necessary for integrating Zig code into Node.js and Electron applications. This dependency allows JavaScript to call Zig functions.
```sh
npm install node-zigar
```
--------------------------------
### Initialize and Use Work Queue in Zig
Source: https://github.com/chung-leong/zigar/wiki/Tarball-viewer
Demonstrates setting up a work queue for asynchronous operations in Zig, specifically for the Zigar project. It shows how to promisify shutdown and asyncify the extract function for JavaScript integration.
```zig
const std = @import("std");
const zigar = @import("zigar");
var work_queue: zigar.thread.WorkQueue(thread_ns) = .{};
pub const shutdown = work_queue.promisify(.shutdown);
pub const extract = work_queue.asyncify(worker.extract);
```
--------------------------------
### Initialize Zigar Project Environment
Source: https://github.com/chung-leong/zigar/wiki/MySQL
Shell commands to create the project directory structure, initialize a Node.js package, and install necessary dependencies including node-zigar and fastify.
```shell
mkdir myzql
cd myzql
npm init -y
npm install node-zigar fastify @fastify/formbody
mkdir src zig
```
--------------------------------
### Zig Hello World Function
Source: https://github.com/chung-leong/zigar/wiki/Hello-world-(Bun)
A simple Zig function that prints 'Hello world!' to the console. This is the core logic written in Zig that will be exposed to JavaScript.
```zig
const std = @import("std");
pub fn hello() void {
std.debug.print("Hello world!", .{});
}
```