FFI & Native Helpers#
Buntok includes an optional native acceleration layer powered by bun:ffi. When the native library is available, it accelerates JSON string escaping, query parsing, and cookie parsing. When unavailable, pure JS fallbacks are used transparently.
How It Works#
On startup, Buntok attempts to load a native shared library (libbuntok_json) from your project's node_modules/.buntok-native/, dist/native/, or zig-out/lib/ directories. If found, the native backend is used for performance-critical operations.
| Operation | Native | JS Fallback |
|---|---|---|
| JSON string escaping | Zig-optimized via FFI | Pure JS implementation |
| Query string parsing | JS (same as fallback) | Pure JS implementation |
| Cookie parsing | JS (same as fallback) | Pure JS implementation |
Checking Native Status#
import { isNativeAvailable, getBackend } from "@buntok/core";
// Check if native FFI is available
if (isNativeAvailable()) {
console.log("Native acceleration enabled");
} else {
console.log("Using JS fallbacks");
}
// Get the current backend name
const backend = getBackend(); // "native" | "js"
console.log(`Backend: ${backend}`);Installing the Native Library#
The native library is optional. To enable it, build the libbuntok_json shared library and place it in one of these locations:
node_modules/.buntok-native/libbuntok_json.{so,dylib,dll}dist/native/libbuntok_json.{so,dylib,dll}zig-out/lib/libbuntok_json.{so,dylib,dll}
# Build with Zig (if available)
zig build -Doptimize=ReleaseFast
# The library will be output to zig-out/lib/
ls zig-out/lib/libbuntok_json.so # Linux
ls zig-out/lib/libbuntok_json.dylib # macOSURL Routing Trie#
Buntok uses a Trie-based URL router for efficient pattern matching. The native Trie was benchmarked and found to be 38% slower than the pure JS implementation due to FFI sync overhead, so the JS version is used by default.
Map.get/set in native C++, making the FFI round-trip overhead unnecessary.Performance Notes#
- JSON string escaping: ~2-3x faster with native backend
- Query/cookie parsing: identical performance (JS-only)
- URL routing: JS is faster than native+JS due to no FFI sync overhead
- The framework auto-selects the best backend per operation