Skip to content

Lightpanda: the headless browser designed for AI and automation

Upgrade to Zig 0.17

Adrià Arrufat10609b025a88
diff --git a/.github/actions/install/action.yml b/.github/actions/install/action.yml
index ad5df1b5e..631db155a 100644
--- a/.github/actions/install/action.yml
+++ b/.github/actions/install/action.yml
@@ -41,14 +41,6 @@ runs:
# Zig version used from the `minimum_zig_version` field in build.zig.zon
- uses: mlugg/setup-zig@d1434d08867e3ee9daa34448df10607b98908d29 # v2.2.1
- # Zig 0.16 writes fetched .zip archives to <global cache>/tmp but no longer
- # creates that directory, so zip dependencies (sqlite amalgamation) fail
- # with "failed to create temporary zip file: FileNotFound" on the fresh
- # cache dir setup-zig points ZIG_GLOBAL_CACHE_DIR at.
- - name: Zig 0.16 zip-fetch workaround
- shell: bash
- run: mkdir -p "${ZIG_GLOBAL_CACHE_DIR:-$HOME/.cache/zig}/tmp"
-
# Rust Toolchain for src/rust (html5ever bridge, renderer)
- uses: dtolnay/rust-toolchain@2c7215f132e9ebf062739d9130488b56d53c060c # master
with:
diff --git a/.github/actions/v8-snapshot/action.yml b/.github/actions/v8-snapshot/action.yml
index f6c2ab732..53a0c8b2a 100644
--- a/.github/actions/v8-snapshot/action.yml
+++ b/.github/actions/v8-snapshot/action.yml
@@ -44,4 +44,4 @@ runs:
- name: v8 snapshot
shell: bash
if: hashFiles('src/snapshot.bin') == ''
- run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
+ run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast snapshot_creator -- src/snapshot.bin
diff --git a/.github/workflows/agent-regression.yml b/.github/workflows/agent-regression.yml
index a3f689548..a6cf22521 100644
--- a/.github/workflows/agent-regression.yml
+++ b/.github/workflows/agent-regression.yml
@@ -28,7 +28,7 @@ jobs:
- uses: ./.github/actions/v8-snapshot
- name: zig build release
- run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64
+ run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast -Dcpu=x86_64
- name: upload artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
diff --git a/.github/workflows/e2e-integration-test.yml b/.github/workflows/e2e-integration-test.yml
index 5a52a23cd..3d0067332 100644
--- a/.github/workflows/e2e-integration-test.yml
+++ b/.github/workflows/e2e-integration-test.yml
@@ -27,7 +27,7 @@ jobs:
- uses: ./.github/actions/install
- name: zig build release
- run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64
+ run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast -Dcpu=x86_64
- name: upload artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml
index 9c06217a1..fe309b801 100644
--- a/.github/workflows/e2e-test.yml
+++ b/.github/workflows/e2e-test.yml
@@ -53,7 +53,7 @@ jobs:
- uses: ./.github/actions/v8-snapshot
- name: zig build release
- run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dorderfile=orderfile/lightpanda.ld -Dcpu=x86_64
+ run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast -Dorderfile=orderfile/lightpanda.ld -Dcpu=x86_64
- name: upload artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
diff --git a/.github/workflows/orderfile.yml b/.github/workflows/orderfile.yml
index e12814505..83fae4e8a 100644
--- a/.github/workflows/orderfile.yml
+++ b/.github/workflows/orderfile.yml
@@ -56,7 +56,7 @@ jobs:
- uses: ./.github/actions/orderfile
id: orderfile
with:
- build-args: -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=x86_64
+ build-args: -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast -Dcpu=x86_64
- name: open a pull request
env:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 67d83551a..93fe84757 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -58,10 +58,10 @@ jobs:
arch: ${{env.ARCH}}
- name: v8 snapshot
- run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
+ run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast snapshot_creator -- src/snapshot.bin
- name: zig build
- run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dorderfile=orderfile/lightpanda.ld ${{ matrix.cpu_flag }} ${{ env.VERSION_FLAG }}
+ run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast -Dorderfile=orderfile/lightpanda.ld ${{ matrix.cpu_flag }} ${{ env.VERSION_FLAG }}
- name: Rename binary
run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}
@@ -118,10 +118,10 @@ jobs:
arch: ${{env.ARCH}}
- name: v8 snapshot
- run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin
+ run: zig build -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast snapshot_creator -- src/snapshot.bin
- name: zig build
- run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast ${{ env.VERSION_FLAG }}
+ run: zig build -Dsnapshot_path=../../snapshot.bin -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast ${{ env.VERSION_FLAG }}
- name: Rename binary
run: mv zig-out/bin/lightpanda lightpanda-${{ env.ARCH }}-${{ env.OS }}
diff --git a/.github/workflows/wpt.yml b/.github/workflows/wpt.yml
index 3a1f75c7f..0ec1db6c5 100644
--- a/.github/workflows/wpt.yml
+++ b/.github/workflows/wpt.yml
@@ -37,7 +37,7 @@ jobs:
arch: ${{env.ARCH}}
- name: zig build release
- run: zig build -Dwpt_extensions -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=ReleaseFast -Dcpu=generic
+ run: zig build -Dwpt_extensions -Dprebuilt_v8_path=v8/libc_v8.a -Doptimize=fast -Dcpu=generic
- name: upload artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
diff --git a/AGENTS.md b/AGENTS.md
index f5f688947..0a90cfa15 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for how to open a pull request (CLA, dev
Run `make download-v8` once first: it fetches the prebuilt V8 archive into `.lp-cache/`, which `build.zig` picks up automatically. Without it every build compiles V8 from source (10+ minutes).
-The C and Rust dependencies are built in ReleaseFast whatever `-Doptimize` is, so debug and release builds share them. Pass `ZIGFLAGS=-Ddebug_deps` to step into a dependency with a debugger.
+The C and Rust dependencies are built with `-Doptimize=fast` whatever `-Doptimize` is, so debug and release builds share them. Pass `ZIGFLAGS=-Ddebug_deps` to step into a dependency with a debugger.
```bash
make test # Run all tests
diff --git a/Dockerfile b/Dockerfile
index a66fa0419..822aebd89 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -52,12 +52,12 @@ RUN case $TARGETPLATFORM in \
mv libc_v8.a v8/libc_v8.a
# build v8 snapshot
-RUN zig build -Doptimize=ReleaseFast \
+RUN zig build -Doptimize=fast \
-Dprebuilt_v8_path=v8/libc_v8.a \
snapshot_creator -- src/snapshot.bin
# build release
-RUN zig build -Doptimize=ReleaseFast \
+RUN zig build -Doptimize=fast \
-Dsnapshot_path=../../snapshot.bin \
-Dprebuilt_v8_path=v8/libc_v8.a \
-Dorderfile=orderfile/lightpanda.ld
diff --git a/Makefile b/Makefile
index 16a4f8f70..1894cb0cd 100644
--- a/Makefile
+++ b/Makefile
@@ -77,14 +77,7 @@ help:
# $(ZIG) commands
# ------------
-.PHONY: build build-v8-snapshot build-dev download-v8 run run-release test bench data end2end clean zig-cache-tmp
-
-# Zig 0.16.0 doesn't create <global cache>/tmp before fetching .zip deps.
-# https://codeberg.org/ziglang/zig/issues/31964
-zig-cache-tmp:
- @dir=$$($(ZIG) env | sed -n 's/^ *\.global_cache_dir = "\(.*\)",$$/\1/p'); \
- test -n "$$dir" || { printf "\033[31mCould not read global_cache_dir from '$(ZIG) env'\033[0m\n"; exit 1; }; \
- mkdir -p "$$dir/tmp"
+.PHONY: build build-v8-snapshot build-dev download-v8 run run-release test bench data end2end clean
## Download the prebuilt V8 libraries (skips the 10+ min source build)
download-v8:
@@ -105,19 +98,19 @@ ifeq ($(OS)_$(ARCH),linux_x86_64)
endif
## Build v8 snapshot
-build-v8-snapshot: zig-cache-tmp
+build-v8-snapshot:
@printf "\033[36mBuilding v8 snapshot (release safe)...\033[0m\n"
- @$(ZIG) build $(ZIGFLAGS) -Doptimize=ReleaseFast snapshot_creator -- src/snapshot.bin || (printf "\033[31mBuild ERROR\033[0m\n"; exit 1;)
+ @$(ZIG) build $(ZIGFLAGS) -Doptimize=fast snapshot_creator -- src/snapshot.bin || (printf "\033[31mBuild ERROR\033[0m\n"; exit 1;)
@printf "\033[32mBuild OK\033[0m\n"
## Build in release-fast mode
build: build-v8-snapshot
@printf "\033[36mBuilding (release fast)...\033[0m\n"
- @$(ZIG) build $(ZIGFLAGS) -Doptimize=ReleaseFast -Dsnapshot_path=../../snapshot.bin || (printf "\033[31mBuild ERROR\033[0m\n"; exit 1;)
+ @$(ZIG) build $(ZIGFLAGS) -Doptimize=fast -Dsnapshot_path=../../snapshot.bin || (printf "\033[31mBuild ERROR\033[0m\n"; exit 1;)
@printf "\033[32mBuild OK\033[0m\n"
## Build in debug mode
-build-dev: zig-cache-tmp
+build-dev:
@printf "\033[36mBuilding (debug)...\033[0m\n"
@$(ZIG) build $(ZIGFLAGS) || (printf "\033[31mBuild ERROR\033[0m\n"; exit 1;)
@printf "\033[32mBuild OK\033[0m\n"
@@ -132,7 +125,7 @@ run-debug: build-dev
@printf "\033[36mRunning...\033[0m\n"
@./zig-out/bin/lightpanda || (printf "\033[31mRun ERROR\033[0m\n"; exit 1;)
-test: zig-cache-tmp
+test:
TEST_FILTER="$(or $(F),$(TEST_FILTER))" $(ZIG) build $(ZIGFLAGS) test -freference-trace
## Run demo/runner end to end tests
diff --git a/README.md b/README.md
index 461ae20ea..777a22649 100644
--- a/README.md
+++ b/README.md
@@ -458,7 +458,7 @@ zig build -Dwpt_extensions run -- fetch \
it's useful to build in `releaseFast` mode to make tests faster.
```
-zig build -Dwpt_extensions -Doptimize=ReleaseFast run -- serve ...
+zig build -Dwpt_extensions -Doptimize=fast run -- serve ...
```
## Contributing
diff --git a/build.zig b/build.zig
index 4eb495f8a..8677c590d 100644
--- a/build.zig
+++ b/build.zig
@@ -18,6 +18,7 @@
const std = @import("std");
const builtin = @import("builtin");
+const Translator = @import("translate_c").Translator;
const lightpanda_version = std.SemanticVersion.parse(@import("build.zig.zon").version) catch unreachable;
const min_zig_version = std.SemanticVersion.parse(@import("build.zig.zon").minimum_zig_version) catch unreachable;
@@ -44,18 +45,18 @@ pub fn build(b: *Build) !void {
const prebuilt_v8_path_option = b.option([]const u8, "prebuilt_v8_path", "Path to a prebuilt libc_v8.a or libc_v8.so");
const dev_fast = b.option(bool, "dev_fast", "Linux debug builds: shared V8 + self-hosted backend. Implies -Dshared_v8, -Duse_llvm=false and a bundled-CRT target") orelse
- (builtin.os.tag == .linux and builtin.cpu.arch == .x86_64 and
- optimize == .Debug and requested_target.query.isNative() and
+ (builtin.target.os.tag == .linux and builtin.target.cpu.arch == .x86_64 and
+ optimize == .debug and requested_target.query.isNative() and
!enable_tsan and !enable_asan and
(prebuilt_v8_path_option == null or std.mem.endsWith(u8, prebuilt_v8_path_option.?, ".so")));
if (dev_fast) {
- if (builtin.os.tag != .linux) {
- std.debug.print("-Ddev_fast is Linux-only (host is {s})\n", .{@tagName(builtin.os.tag)});
+ if (builtin.target.os.tag != .linux) {
+ std.debug.print("-Ddev_fast is Linux-only (host is {s})\n", .{@tagName(builtin.target.os.tag)});
return error.DevFastUnsupportedHost;
}
- if (optimize != .Debug) {
- std.debug.print("-Ddev_fast is Debug-only (optimize is {s})\n", .{@tagName(optimize)});
+ if (optimize != .debug) {
+ std.debug.print("-Ddev_fast is debug-only (optimize is {s})\n", .{@tagName(optimize)});
return error.DevFastRequiresDebug;
}
if (!requested_target.query.isNative()) {
@@ -75,10 +76,10 @@ pub fn build(b: *Build) !void {
// Dependencies never follow -Doptimize, and they build for the requested
// target rather than the dev_fast bundled-CRT query, so debug and release
// builds share one set of dependency objects in the cache.
- const debug_deps = b.option(bool, "debug_deps", "Build the C and Rust dependencies in Debug instead of ReleaseFast") orelse false;
+ const debug_deps = b.option(bool, "debug_deps", "Build the C and Rust dependencies in debug instead of fast") orelse false;
const deps: Deps = .{
.target = requested_target,
- .optimize = if (debug_deps) .Debug else .ReleaseFast,
+ .optimize = if (debug_deps) .debug else .fast,
};
// Without an explicit -Dprebuilt_v8_path, pick up whatever `make
@@ -118,7 +119,7 @@ pub fn build(b: *Build) !void {
const fmt_step = b.step("fmt", "Check code formatting");
const fmt = b.addFmt(.{
- .paths = &.{ "src", "build.zig", "build.zig.zon" },
+ .paths = b.pathList(&.{ "src", "build.zig", "build.zig.zon" }),
.check = true,
});
fmt_step.dependOn(&fmt.step);
@@ -167,9 +168,7 @@ pub fn build(b: *Build) !void {
b.installArtifact(exe);
const run_cmd = b.addRunArtifact(exe);
- if (b.args) |args| {
- run_cmd.addArgs(args);
- }
+ run_cmd.addPassthruArgs();
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
@@ -185,9 +184,7 @@ pub fn build(b: *Build) !void {
extras_step.dependOn(&b.addInstallArtifact(exe, .{}).step);
const run_cmd = b.addRunArtifact(exe);
- if (b.args) |args| {
- run_cmd.addArgs(args);
- }
+ run_cmd.addPassthruArgs();
const run_step = b.step("snapshot_creator", "Generate a v8 snapshot");
run_step.dependOn(&run_cmd.step);
}
@@ -197,7 +194,7 @@ pub fn build(b: *Build) !void {
const exe = addExe(b, exe_config, "lightpanda-skills", "skills_check", "src/main_skills.zig");
const run_cmd = b.addRunArtifact(exe);
- const out_dir = run_cmd.addOutputDirectoryArg("skills");
+ const out_dir = run_cmd.addOutputDirectoryArg2("skills", .{});
const install = b.addInstallDirectory(.{
.source_dir = out_dir,
.install_dir = .prefix,
@@ -222,14 +219,14 @@ pub fn build(b: *Build) !void {
const Deps = struct {
target: Build.ResolvedTarget,
- optimize: std.builtin.OptimizeMode,
+ optimize: std.lang.Optimize,
};
const ExeConfig = struct {
check: *Build.Step,
lightpanda_module: *Build.Module,
target: Build.ResolvedTarget,
- optimize: std.builtin.OptimizeMode,
+ optimize: std.lang.Optimize,
use_llvm: bool,
orderfile: ?[]const u8,
sanitize_c: ?std.zig.SanitizeC,
@@ -255,7 +252,7 @@ fn addExe(b: *Build, config: ExeConfig, name: []const u8, check_name: []const u8
if (config.orderfile) |path| {
// Per-function/per-datum sections exist only so the orderfile script
// can place individual hot functions; the self-hosted backend used by
- // Debug builds does not support them on the C libraries, so they are
+ // debug builds does not support them on the C libraries, so they are
// gated on the orderfile being set (release/LLVM only).
exe.link_function_sections = true;
exe.link_data_sections = true;
@@ -282,9 +279,11 @@ fn devFastGlibcVersion(b: *Build) std.SemanticVersion {
/// it cannot drift from CI (the Makefile reads the same source of truth).
fn findPrebuiltV8(b: *Build, target: Build.ResolvedTarget, dev_fast: bool) ?[]const u8 {
const io = b.graph.io;
+ const action_path = ".github/actions/install/action.yml";
+ b.dependOnFileContents(b.path(action_path));
const action = std.Io.Dir.cwd().readFileAlloc(
io,
- b.pathFromRoot(".github/actions/install/action.yml"),
+ rootPath(b, action_path),
b.allocator,
.limited(64 * 1024),
) catch return null;
@@ -294,7 +293,7 @@ fn findPrebuiltV8(b: *Build, target: Build.ResolvedTarget, dev_fast: bool) ?[]co
return null;
}
- const cache_dir = b.pathFromRoot(".lp-cache");
+ const cache_dir = ".lp-cache";
// The .so must keep the name the exe's DT_NEEDED records; the archive
// name encodes V8 version, os and arch.
const path = if (dev_fast)
@@ -307,7 +306,8 @@ fn findPrebuiltV8(b: *Build, target: Build.ResolvedTarget, dev_fast: bool) ?[]co
@tagName(target.result.cpu.arch),
}) });
};
- std.Io.Dir.cwd().access(io, path, .{}) catch {
+ b.dependOnFileMetadata(b.path(path));
+ std.Io.Dir.cwd().access(io, rootPath(b, path), .{}) catch {
std.debug.print("No prebuilt V8 at {s}; using the V8 source-build path. `make download-v8` fetches the prebuilt.\n", .{path});
return null;
};
@@ -315,6 +315,10 @@ fn findPrebuiltV8(b: *Build, target: Build.ResolvedTarget, dev_fast: bool) ?[]co
return path;
}
+fn rootPath(b: *Build, sub_path: []const u8) []const u8 {
+ return b.root.joinString(b.allocator, sub_path) catch @panic("OOM");
+}
+
/// Returns the quoted `default:` value of a top-level `key` in the install
/// action's yaml.
fn actionDefault(action: []const u8, key: []const u8) ?[]const u8 {
@@ -346,18 +350,18 @@ fn markHotSections(b: *Build, archive: Build.LazyPath) Build.LazyPath {
.root_module = b.createModule(.{
.root_source_file = b.path("orderfile/mark_hot_sections.zig"),
.target = b.graph.host,
- .optimize = .ReleaseSafe,
+ .optimize = .safe,
}),
});
const run = b.addRunArtifact(tool);
run.addFileArg(archive);
run.addFileArg(b.path("orderfile/v8.txt"));
- return run.addOutputFileArg("libc_v8.a");
+ return run.addOutputFileArg2("libc_v8.a", .{});
}
/// Per-function/per-datum sections let the -Dorderfile linker script place
/// individual hot functions. Only enabled for orderfile (release/LLVM) builds:
-/// the self-hosted backend used by Debug builds fails to link the C libraries
+/// the self-hosted backend used by debug builds fails to link the C libraries
/// with them.
fn sectionize(lib: *Build.Step.Compile, enabled: bool) *Build.Step.Compile {
if (enabled) {
@@ -384,7 +388,7 @@ fn linkV8(
.is_tsan = is_tsan,
.inspector_subtype = false,
.v8_enable_sandbox = is_tsan,
- .cache_root = b.pathFromRoot(".lp-cache"),
+ .cache_root = rootPath(b, ".lp-cache"),
.prebuilt_v8_path = prebuilt_v8_path,
.shared_v8 = shared_v8,
});
@@ -393,7 +397,7 @@ fn linkV8(
fn linkRust(b: *Build, mod: *Build.Module, deps: Deps) void {
// Cargo's "dev" profile writes to target/debug.
- const profile, const out_subdir = if (deps.optimize == .Debug) .{ "dev", "debug" } else .{ "release", "release" };
+ const profile, const out_subdir = if (deps.optimize == .debug) .{ "dev", "debug" } else .{ "release", "release" };
// One cargo workspace, one staticlib (src/rust/Cargo.toml explains why).
const exec_cargo = b.addSystemCommand(&.{
@@ -412,7 +416,7 @@ fn linkRust(b: *Build, mod: *Build.Module, deps: Deps) void {
_ = exec_cargo.captureStdErr(.{});
// TODO: We can prefer `--artifact-dir` once it become stable.
- const out_dir = exec_cargo.addPrefixedOutputDirectoryArg("--target-dir=", "rust");
+ const out_dir = exec_cargo.addOutputDirectoryArg2("rust", .{ .prefix = "--target-dir=" });
const rust_step = b.step("rust", "Build the Rust staticlib (requires cargo)");
rust_step.dependOn(&exec_cargo.step);
@@ -425,14 +429,18 @@ fn linkRust(b: *Build, mod: *Build.Module, deps: Deps) void {
/// input of `run`, skipping the `skip_dir` subtree at any depth.
fn addDirInputs(b: *Build, run: *Build.Step.Run, root: []const u8, skip_dir: []const u8) !void {
const io = b.graph.io;
- var dir = try b.build_root.handle.openDir(io, root, .{ .iterate = true });
+ var dir = try std.Io.Dir.cwd().openDir(io, rootPath(b, root), .{ .iterate = true });
defer dir.close(io);
+ b.dependOnDirectoryContents(b.path(root));
var walker = try dir.walk(b.allocator);
defer walker.deinit();
while (try walker.next(io)) |entry| {
switch (entry.kind) {
- .directory => if (std.mem.eql(u8, entry.basename, skip_dir)) walker.leave(io),
+ .directory => if (std.mem.eql(u8, entry.basename, skip_dir))
+ walker.leave(io)
+ else
+ b.dependOnDirectoryContents(b.path(b.pathJoin(&.{ root, entry.path }))),
.file => run.addFileInput(b.path(b.pathJoin(&.{ root, entry.path }))),
else => {},
}
@@ -440,14 +448,12 @@ fn addDirInputs(b: *Build, run: *Build.Step.Run, root: []const u8, skip_dir: []c
}
fn linkSqlite(b: *Build, mod: *Build.Module, deps: Deps, enable_csan: ?std.zig.SanitizeC, is_tsan: bool, section: bool) void {
- const dep = b.dependency("sqlite3", .{
- .target = deps.target,
- .optimize = deps.optimize,
- });
+ const dep = b.dependency("sqlite3", .{});
- const lib = sectionize(dep.artifact("sqlite3"), section);
- lib.root_module.sanitize_c = enable_csan;
- lib.root_module.sanitize_thread = is_tsan;
+ const lib_mod = cLibModule(b, deps.target, deps.optimize, is_tsan);
+ lib_mod.sanitize_c = enable_csan;
+ lib_mod.addCSourceFile(.{ .file = dep.path("sqlite3.c") });
+ const lib = sectionize(b.addLibrary(.{ .name = "sqlite3", .root_module = lib_mod }), section);
const macros = [_]struct { []const u8, []const u8 }{
.{ "SQLITE_DEFAULT_FILE_PERMISSIONS", "0600" },
@@ -489,12 +495,7 @@ fn linkSqlite(b: *Build, mod: *Build.Module, deps: Deps, enable_csan: ?std.zig.S
mod.linkLibrary(lib);
- const translate_c = b.addTranslateC(.{
- .root_source_file = lib.getEmittedIncludeTree().path(b, "sqlite3.h"),
- .target = mod.resolved_target.?,
- .optimize = mod.optimize.?,
- });
- mod.addImport("sqlite3", translate_c.createModule());
+ mod.addImport("sqlite3", translateC(b, mod, dep.path("sqlite3.h")).mod);
}
fn linkPcre2(b: *Build, mod: *Build.Module, deps: Deps, enable_csan: ?std.zig.SanitizeC, is_tsan: bool, section: bool) void {
@@ -509,13 +510,9 @@ fn linkPcre2(b: *Build, mod: *Build.Module, deps: Deps, enable_csan: ?std.zig.Sa
lib.root_module.sanitize_thread = is_tsan;
mod.linkLibrary(lib);
- const translate_c = b.addTranslateC(.{
- .root_source_file = lib.getEmittedIncludeTree().path(b, "pcre2.h"),
- .target = mod.resolved_target.?,
- .optimize = mod.optimize.?,
- });
- translate_c.defineCMacro("PCRE2_CODE_UNIT_WIDTH", "8");
- mod.addImport("pcre2", translate_c.createModule());
+ const translator = translateC(b, mod, lib.getEmittedIncludeTree().path(b, "pcre2.h"));
+ translator.defineCMacro("PCRE2_CODE_UNIT_WIDTH", "8");
+ mod.addImport("pcre2", translator.mod);
}
fn linkCurl(b: *Build, mod: *Build.Module, deps: Deps, is_tsan: bool, section: bool) void {
@@ -523,13 +520,9 @@ fn linkCurl(b: *Build, mod: *Build.Module, deps: Deps, is_tsan: bool, section: b
mod.linkLibrary(curl);
const dep = b.dependency("curl", .{});
- const translate_c = b.addTranslateC(.{
- .root_source_file = dep.path("include/curl/curl.h"),
- .target = mod.resolved_target.?,
- .optimize = mod.optimize.?,
- });
- translate_c.addIncludePath(dep.path("include"));
- mod.addImport("curl", translate_c.createModule());
+ const translator = translateC(b, mod, dep.path("include/curl/curl.h"));
+ translator.addIncludePath(dep.path("include"));
+ mod.addImport("curl", translator.mod);
const zlib = buildZlib(b, deps.target, deps.optimize, is_tsan, section);
curl.root_module.linkLibrary(zlib);
@@ -545,9 +538,7 @@ fn linkCurl(b: *Build, mod: *Build.Module, deps: Deps, is_tsan: bool, section: b
if (deps.target.result.os.tag == .macos) {
// needed for proxying on mac
- const framework_path = if (b.sysroot) |sysroot|
- b.pathJoin(&.{ sysroot, "System/Library/Frameworks" })
- else if (b.graph.environ_map.get("SDKROOT")) |sdk_root|
+ const framework_path = if (b.graph.environ_map.get("SDKROOT")) |sdk_root|
b.pathJoin(&.{ sdk_root, "System/Library/Frameworks" })
else
"/System/Library/Frameworks";
@@ -557,7 +548,7 @@ fn linkCurl(b: *Build, mod: *Build.Module, deps: Deps, is_tsan: bool, section: b
}
}
-fn cLibModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool) *Build.Module {
+fn cLibModule(b: *Build, target: Build.ResolvedTarget, optimize: std.lang.Optimize, is_tsan: bool) *Build.Module {
return b.createModule(.{
.target = target,
.optimize = optimize,
@@ -566,7 +557,7 @@ fn cLibModule(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Opt
});
}
-fn buildZlib(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool, section: bool) *Build.Step.Compile {
+fn buildZlib(b: *Build, target: Build.ResolvedTarget, optimize: std.lang.Optimize, is_tsan: bool, section: bool) *Build.Step.Compile {
const dep = b.dependency("zlib", .{});
const mod = cLibModule(b, target, optimize, is_tsan);
@@ -592,7 +583,7 @@ fn buildZlib(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Opti
return lib;
}
-fn buildBrotli(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool, section: bool) [3]*Build.Step.Compile {
+fn buildBrotli(b: *Build, target: Build.ResolvedTarget, optimize: std.lang.Optimize, is_tsan: bool, section: bool) [3]*Build.Step.Compile {
const dep = b.dependency("brotli", .{});
const mod = cLibModule(b, target, optimize, is_tsan);
@@ -634,7 +625,7 @@ fn buildBrotli(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.Op
return .{ brotlicmn, brotlidec, brotlienc };
}
-fn buildBoringSsl(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, section: bool) [2]*Build.Step.Compile {
+fn buildBoringSsl(b: *Build, target: Build.ResolvedTarget, optimize: std.lang.Optimize, section: bool) [2]*Build.Step.Compile {
const dep = b.dependency("boringssl-zig", .{
.target = target,
.optimize = optimize,
@@ -650,7 +641,7 @@ fn buildBoringSsl(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin
return .{ ssl, crypto };
}
-fn buildNghttp2(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, is_tsan: bool, section: bool) *Build.Step.Compile {
+fn buildNghttp2(b: *Build, target: Build.ResolvedTarget, optimize: std.lang.Optimize, is_tsan: bool, section: bool) *Build.Step.Compile {
const dep = b.dependency("nghttp2", .{});
const mod = cLibModule(b, target, optimize, is_tsan);
@@ -696,7 +687,7 @@ fn buildNghttp2(b: *Build, target: Build.ResolvedTarget, optimize: std.builtin.O
fn buildCurl(
b: *Build,
target: Build.ResolvedTarget,
- optimize: std.builtin.OptimizeMode,
+ optimize: std.lang.Optimize,
is_tsan: bool,
section: bool,
) *Build.Step.Compile {
@@ -721,7 +712,7 @@ fn buildCurl(
const byte_size = struct {
fn it(b2: *std.Build, target2: Build.ResolvedTarget, name: []const u8, comptime ctype: std.Target.CType) []const u8 {
- return b2.fmt("#define SIZEOF_{s} {d}", .{ name, target2.result.cTypeByteSize(ctype) });
+ return b2.fmt("#define SIZEOF_{s} {d}", .{ name, target2.result.cTypeByteSize(ctype).? });
}
}.it;
@@ -731,7 +722,6 @@ fn buildCurl(
.USE_NGHTTP2 = true,
.USE_OPENSSL = true,
- .OPENSSL_IS_BORINGSSL = true,
.CURL_BORINGSSL_VERSION = null,
.CURL_CA_PATH = null,
.CURL_CA_BUNDLE = null,
@@ -751,11 +741,9 @@ fn buildCurl(
.CURL_DISABLE_LDAP = true,
.CURL_DISABLE_LDAPS = true,
.CURL_DISABLE_MQTT = true,
- .CURL_DISABLE_NTLM = true,
.CURL_DISABLE_PROGRESS_METER = true,
.CURL_DISABLE_POP3 = true,
.CURL_DISABLE_RTSP = true,
- .CURL_DISABLE_SMB = true,
.CURL_DISABLE_SMTP = true,
.CURL_DISABLE_TELNET = true,
.CURL_DISABLE_TFTP = true,
@@ -777,7 +765,6 @@ fn buildCurl(
.SIZEOF_INT_CODE = byte_size(b, target, "INT", .int),
.SIZEOF_LONG_CODE = byte_size(b, target, "LONG", .long),
- .SIZEOF_LONG_LONG_CODE = byte_size(b, target, "LONG_LONG", .longlong),
.SIZEOF_OFF_T_CODE = byte_size(b, target, "OFF_T", .longlong),
.SIZEOF_CURL_OFF_T_CODE = byte_size(b, target, "CURL_OFF_T", .longlong),
@@ -805,8 +792,6 @@ fn buildCurl(
.HAVE_PWD_H = !is_windows,
.HAVE_STDATOMIC_H = true,
.HAVE_STDBOOL_H = true,
- .HAVE_STDDEF_H = true,
- .HAVE_STDINT_H = true,
.HAVE_STRINGS_H = true,
.HAVE_STROPTS_H = false,
.HAVE_SYS_EVENTFD_H = is_linux or is_freebsd or is_netbsd,
@@ -835,18 +820,15 @@ fn buildCurl(
.HAVE_BUILTIN_AVAILABLE = true,
.HAVE_CLOCK_GETTIME_MONOTONIC = !is_darwin and !is_windows,
.HAVE_CLOCK_GETTIME_MONOTONIC_RAW = is_linux,
- .HAVE_FILE_OFFSET_BITS = true,
.HAVE_GETEUID = !is_windows,
.HAVE_GETPPID = !is_windows,
.HAVE_GETTIMEOFDAY = true,
.HAVE_GLIBC_STRERROR_R = is_gnu,
.HAVE_GMTIME_R = !is_windows,
.HAVE_LOCALTIME_R = !is_windows,
- .HAVE_LONGLONG = !is_windows,
.HAVE_MACH_ABSOLUTE_TIME = is_darwin,
.HAVE_MEMRCHR = !is_darwin and !is_windows,
.HAVE_POSIX_STRERROR_R = !is_gnu and !is_windows,
- .HAVE_PTHREAD_H = !is_windows,
.HAVE_THREADS_POSIX = !is_windows,
.HAVE_SETLOCALE = true,
.HAVE_SETRLIMIT = !is_windows,
@@ -854,12 +836,8 @@ fn buildCurl(
.HAVE_SIGINTERRUPT = !is_windows,
.HAVE_SIGNAL = true,
.HAVE_SIGSETJMP = !is_windows,
- .HAVE_SIZEOF_SA_FAMILY_T = false,
- .HAVE_SIZEOF_SUSECONDS_T = false,
- .HAVE_SNPRINTF = true,
.HAVE_STRCASECMP = !is_windows,
.HAVE_STRCMPI = false,
- .HAVE_STRDUP = true,
.HAVE_STRERROR_R = !is_windows,
.HAVE_STRICMP = false,
.HAVE_STRUCT_TIMEVAL = true,
@@ -867,8 +845,6 @@ fn buildCurl(
.HAVE_UTIME = true,
.HAVE_UTIMES = !is_windows,
.HAVE_WRITABLE_ARGV = !is_windows,
- .HAVE__SETMODE = is_windows,
- .USE_THREADS_POSIX = !is_windows,
.USE_RESOLV_THREADED = !is_windows,
// filesystem, network
@@ -885,16 +861,12 @@ fn buildCurl(
.HAVE_FSETXATTR = is_darwin or is_linux or is_netbsd,
.HAVE_FSETXATTR_5 = is_linux or is_netbsd,
.HAVE_FSETXATTR_6 = is_darwin,
- .HAVE_FTRUNCATE = true,
.HAVE_GETADDRINFO = true,
.HAVE_GETADDRINFO_THREADSAFE = is_linux or is_freebsd or is_netbsd,
.HAVE_GETHOSTBYNAME_R = is_linux or is_freebsd,
.HAVE_GETHOSTBYNAME_R_3 = false,
- .HAVE_GETHOSTBYNAME_R_3_REENTRANT = false,
.HAVE_GETHOSTBYNAME_R_5 = false,
- .HAVE_GETHOSTBYNAME_R_5_REENTRANT = false,
.HAVE_GETHOSTBYNAME_R_6 = is_linux,
- .HAVE_GETHOSTBYNAME_R_6_REENTRANT = is_linux,
.HAVE_GETHOSTNAME = true,
.HAVE_GETIFADDRS = if (is_windows) false else !is_android or target.result.os.versionRange().linux.android >= 24,
.HAVE_GETPASS_R = is_netbsd,
@@ -910,7 +882,6 @@ fn buildCurl(
.HAVE_IOCTLSOCKET_FIONBIO = is_windows,
.HAVE_IOCTL_FIONBIO = !is_windows,
.HAVE_IOCTL_SIOCGIFADDR = !is_windows,
- .HAVE_MSG_NOSIGNAL = !is_windows,
.HAVE_OPENDIR = true,
.HAVE_PIPE = !is_windows,
.HAVE_PIPE2 = is_linux or is_freebsd or is_netbsd or is_openbsd,
@@ -922,9 +893,7 @@ fn buildCurl(
.HAVE_SEND = true,
.HAVE_SENDMMSG = !is_darwin and !is_windows,
.HAVE_SENDMSG = !is_windows,
- .HAVE_SETMODE = !is_linux,
.HAVE_SETSOCKOPT_SO_NONBLOCK = false,
- .HAVE_SOCKADDR_IN6_SIN6_ADDR = !is_windows,
.HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID = true,
.HAVE_SOCKET = true,
.HAVE_SOCKETPAIR = !is_windows,
@@ -1022,12 +991,17 @@ fn linkIsocline(b: *Build, mod: *Build.Module) void {
.file = dep.path("src/isocline.c"),
});
- const translate_c = b.addTranslateC(.{
- .root_source_file = dep.path("include/isocline.h"),
+ mod.addImport("isocline", translateC(b, mod, dep.path("include/isocline.h")).mod);
+}
+
+fn translateC(b: *Build, mod: *Build.Module, header: Build.LazyPath) Translator {
+ return .init(b.dependency("translate_c", .{}), .{
+ .c_source_file = header,
.target = mod.resolved_target.?,
.optimize = mod.optimize.?,
+ // Zig 0.16's built-in translate-c defaulted to this.
+ .default_init = true,
});
- mod.addImport("isocline", translate_c.createModule());
}
/// Resolves the semantic version of the build.
@@ -1072,10 +1046,14 @@ fn resolveVersion(b: *std.Build) std.SemanticVersion {
}
fn runGit(b: *std.Build, args: []const []const u8) ![]const u8 {
- var code: u8 = undefined;
+ // HEAD moves without touching any file the cache could track cheaply.
+ b.graph.poisonCache();
const command = try std.mem.concat(b.allocator, []const u8, &.{
- &.{ "git", "-C", b.pathFromRoot(".") },
+ &.{ "git", "-C", rootPath(b, ".") },
args,
});
- return b.runAllowFail(command, &code, .ignore);
+ return switch (b.runFallible(command, .{ .stderr_behavior = .ignore })) {
+ .success => |stdout| stdout,
+ else => error.GitFailed,
+ };
}
diff --git a/build.zig.zon b/build.zig.zon
index 8fa11a202..3bf2fac20 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -2,11 +2,11 @@
.name = .browser,
.version = "1.1.0-dev",
.fingerprint = 0xda130f3af836cea0, // Changing this has security and trust implications.
- .minimum_zig_version = "0.16.0",
+ .minimum_zig_version = "0.17.0",
.dependencies = .{
.v8 = .{
- .url = "https://github.com/lightpanda-io/zig-v8-fork/archive/200123d4a5eee5136aa96a3933c651cc3d2c069f.tar.gz",
- .hash = "v8-0.0.0-xddH67dJAwAdG6Puk7KzLsWsEzP8kqxLDfS-6tpkKS5B",
+ .url = "https://github.com/lightpanda-io/zig-v8-fork/archive/10f6a11e81fd4809988a24e3f5b3d5d4fd3a73fe.tar.gz",
+ .hash = "v8-0.0.0-xddH6w1QAwDcuJPtc73VXElNBsgPgrRBqQR__jWhy_C4",
},
// .v8 = .{ .path = "../zig-v8-fork" },
.brotli = .{
@@ -32,20 +32,24 @@
.hash = "N-V-__8AALJXUwHr71AwttzhEqqYTvFb_jz0EQ5Ou3OWpHBM",
},
.sqlite3 = .{
- .url = "https://github.com/allyourcodebase/sqlite3/archive/7a615f5af79009cd733e3480658586d9b0d28b35.tar.gz",
- .hash = "sqlite3-3.53.2-DMxLWuAOAAA_Px0arJOIOaP4AKEu5prbsQgPMA35W1zz",
+ .url = "https://sqlite.org/2026/sqlite-amalgamation-3530200.zip",
+ .hash = "N-V-__8AALc_rgC04POe18O0LKFRm4ouQpLtL3riscEmWp-Q",
},
.zenai = .{
- .url = "git+https://github.com/lightpanda-io/zenai.git#b3386fde741d3d9f76674e4706ac1db27923c855",
- .hash = "zenai-0.0.0-iOY_VJEhBwBj9qGuHOtw1TdQw0aiIbOZhXlybkSqhXKs",
+ .url = "git+https://github.com/lightpanda-io/zenai.git#63df800afc438c0e90603270a4696689eb339ccc",
+ .hash = "zenai-0.0.0-iOY_VEuBBwAanO_h2hbjC9Up37-a4pjYlViKeOYJLQjS",
},
.isocline = .{
.url = "git+https://github.com/arrufat/isocline#4a99434bee4a5ed04c1639514224d48cd55e1405",
.hash = "N-V-__8AAHxtEwB16xj2Xz-zx_uklGdTP5C2-GHXDoSzah-8",
},
.pcre2 = .{
- .url = "https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.49/pcre2-10.49.tar.gz",
- .hash = "pcre2-10.49.0-IZ6r68cregBKN199ndY6AaKNyKJpNmnQVSm8-h0gp4sj",
+ .url = "git+https://github.com/PCRE2Project/pcre2#9ad4a2e956876747a5022bf04614c7e39e71d4ec",
+ .hash = "pcre2-10.50.0-DEV-IZ6r6yDTrgCmI3jcBntPIdZLWLhNORGZZSi8hxQkc11x",
+ },
+ .translate_c = .{
+ .url = "git+https://codeberg.org/ziglang/translate-c?ref=2.0.0#0da7a16c3235b935b82421646076e0657cda21f6",
+ .hash = "translate_c-2.0.0-Q_BUWltOBwA0229IE8wwSxxGzOxyRso3hvcb1nN8oJX_",
},
},
.paths = .{""},
diff --git a/orderfile/README.md b/orderfile/README.md
index 7a61991e7..de72ba60e 100644
--- a/orderfile/README.md
+++ b/orderfile/README.md
@@ -59,7 +59,7 @@ below), with no change in run duration.
```bash
# root for /sys/kernel/debug/fault_around_bytes; ../demo checked out with
# `npm install` done; node, go, python3 and binutils on the PATH.
-orderfile/tools/regen.sh -Doptimize=ReleaseFast -Dsnapshot_path=../../snapshot.bin -Dcpu=x86_64
+orderfile/tools/regen.sh -Doptimize=fast -Dsnapshot_path=../../snapshot.bin -Dcpu=x86_64
```
The script
diff --git a/orderfile/mark_hot_sections.zig b/orderfile/mark_hot_sections.zig
index 59bd5df07..8fa61020a 100644
--- a/orderfile/mark_hot_sections.zig
+++ b/orderfile/mark_hot_sections.zig
@@ -123,7 +123,7 @@ fn rewriteArchive(gpa: Allocator, archive: []const u8, hot: *const HotSet, out:
out.appendSliceAssumeCapacity("!<arch>\n");
for (members.items) |m| {
var header = m.header.*;
- _ = try std.fmt.bufPrint(header[48..58], "{d:<10}", .{m.body.len});
+ _ = try std.mem.print(header[48..58], "{d:<10}", .{m.body.len});
out.appendSliceAssumeCapacity(&header);
const start = out.items.len;
out.appendSliceAssumeCapacity(m.body);
diff --git a/orderfile/tools/regen.sh b/orderfile/tools/regen.sh
index 741372022..1f9f3d9d6 100755
--- a/orderfile/tools/regen.sh
+++ b/orderfile/tools/regen.sh
@@ -4,7 +4,7 @@
#
# usage: orderfile/tools/regen.sh [zig build args...]
# The build args are those of the release build minus -Dorderfile, e.g.
-# -Doptimize=ReleaseFast -Dsnapshot_path=../../snapshot.bin -Dcpu=x86_64
+# -Doptimize=fast -Dsnapshot_path=../../snapshot.bin -Dcpu=x86_64
#
# Needs root (sudo) for /sys/kernel/debug/fault_around_bytes, a checkout of
# lightpanda-io/demo (DEMO_DIR, npm install done), node, go, python3 and
diff --git a/src/Arena.zig b/src/Arena.zig
index 96b288025..006d01307 100644
--- a/src/Arena.zig
+++ b/src/Arena.zig
@@ -109,8 +109,8 @@ pub fn dupe(self: *Arena, comptime T: type, m: []const T) ![]T {
return self.allocator().dupe(T, m);
}
-pub fn dupeZ(self: *Arena, comptime T: type, m: []const T) ![:0]T {
- return self.allocator().dupeZ(T, m);
+pub fn dupeSentinel(self: *Arena, comptime T: type, m: []const T, comptime sentinel: T) ![:sentinel]T {
+ return self.allocator().dupeSentinel(T, m, sentinel);
}
// Arena is being released. Account goes back to 0 (everything is being released)
diff --git a/src/Config.zig b/src/Config.zig
index 0bb03abdb..2b2b8a402 100644
--- a/src/Config.zig
+++ b/src/Config.zig
@@ -358,7 +358,7 @@ pub const AgentVerbosity = enum {
high,
pub fn atLeast(self: AgentVerbosity, min: AgentVerbosity) bool {
- return @intFromEnum(self) >= @intFromEnum(min);
+ return @backingInt(self) >= @backingInt(min);
}
};
@@ -1038,7 +1038,7 @@ pub const HttpHeaders = struct {
languages: []const []const u8,
pub fn init(allocator: Allocator, value: []const u8) !AcceptLanguage {
- const header = try allocator.dupeZ(u8, value);
+ const header = try allocator.dupeSentinel(u8, value, 0);
errdefer allocator.free(header);
var languages: std.ArrayList([]const u8) = .empty;
@@ -1067,15 +1067,15 @@ pub const HttpHeaders = struct {
pub fn init(allocator: Allocator, config: *const Config) !HttpHeaders {
const user_agent: [:0]const u8 = if (config.userAgent()) |ua|
- try allocator.dupeZ(u8, ua)
+ try allocator.dupeSentinel(u8, ua, 0)
else if (config.userAgentSuffix()) |suffix|
- try std.fmt.allocPrintSentinel(allocator, "{s} {s}", .{ user_agent_base, suffix }, 0)
+ try allocator.printSentinel("{s} {s}", .{ user_agent_base, suffix }, 0)
else
user_agent_base;
errdefer if (config.userAgent() != null or config.userAgentSuffix() != null) allocator.free(user_agent);
const proxy_bearer_header: ?[:0]const u8 = if (config.proxyBearerToken()) |token|
- try std.fmt.allocPrintSentinel(allocator, "Proxy-Authorization: Bearer {s}", .{token}, 0)
+ try allocator.printSentinel("Proxy-Authorization: Bearer {s}", .{token}, 0)
else
null;
errdefer if (proxy_bearer_header) |hdr| allocator.free(hdr);
@@ -1133,7 +1133,7 @@ pub fn printUsageAndExit(self: *const Config, allocator: Allocator, help_for: Ru
\\{s}
\\
, .{Help.general});
- break :text try std.fmt.allocPrint(allocator, template, .{exec_name});
+ break :text try allocator.print(template, .{exec_name});
},
inline .fetch, .serve, .mcp, .agent, .run => |tag| text: {
const template = comptimePrint(
@@ -1142,11 +1142,11 @@ pub fn printUsageAndExit(self: *const Config, allocator: Allocator, help_for: Ru
\\{s}
\\
, .{ @field(Help, @tagName(tag)), Help.common_options });
- break :text try std.fmt.allocPrint(allocator, template, .{ exec_name, info_or_warn, pretty_or_logfmt });
+ break :text try allocator.print(template, .{ exec_name, info_or_warn, pretty_or_logfmt });
},
.version => text: {
const template = Help.version ++ "\n";
- break :text try std.fmt.allocPrint(allocator, template, .{exec_name});
+ break :text try allocator.print(template, .{exec_name});
},
};
defer allocator.free(text);
@@ -1228,8 +1228,8 @@ pub fn parseArgs(allocator: Allocator, proc_args: std.process.Args) !Config {
}
// run's fields are a strict subset of Agent's (compile error otherwise).
var agent_opts: Agent = .{};
- inline for (@typeInfo(@TypeOf(run)).@"struct".fields) |f| {
- @field(agent_opts, f.name) = @field(run, f.name);
+ inline for (@typeInfo(@TypeOf(run)).@"struct".field_names) |field_name| {
+ @field(agent_opts, field_name) = @field(run, field_name);
}
command = .{ .agent = agent_opts };
}
@@ -1428,7 +1428,7 @@ test "Config: validateLocale" {
try std.testing.expectError(error.InvalidSubtag, validateLocale("en-U"));
try std.testing.expectError(error.InvalidSubtag, validateLocale("en-US-x-toolongsub"));
try std.testing.expectError(error.InvalidSubtag, validateLocale("en-U$"));
- try std.testing.expectError(error.TooLong, validateLocale("en-" ++ "a" ** 40));
+ try std.testing.expectError(error.TooLong, validateLocale("en-" ++ string.repeat("a", 40)));
}
test "Config: validateTimezone" {
@@ -1438,7 +1438,7 @@ test "Config: validateTimezone" {
try std.testing.expectError(error.Empty, validateTimezone(""));
try std.testing.expectError(error.InvalidCharacter, validateTimezone("Europe/ Paris"));
try std.testing.expectError(error.InvalidCharacter, validateTimezone("UTC\n"));
- try std.testing.expectError(error.TooLong, validateTimezone("a" ** 65));
+ try std.testing.expectError(error.TooLong, validateTimezone(string.repeat("a", 65)));
}
test "Config: HttpHeaders.acceptLanguageFor" {
@@ -1634,7 +1634,7 @@ pub fn validateUserAgent(ua: []const u8) !void {
}
}
- if (std.ascii.indexOfIgnoreCase(ua, "mozilla") != null) {
+ if (std.ascii.findIgnoreCase(ua, "mozilla") != null) {
return error.Reserved;
}
}
@@ -1645,7 +1645,7 @@ fn localeValidator(allocator: Allocator, args: *std.process.Args.Iterator, field
log.fatal(.app, "invalid option value", .{ .arg = "--locale", .value = str, .err = err, .hint = "must be a BCP 47 tag such as en-US, de or zh-Hant-TW" });
return error.InvalidArgument;
};
- field.* = try allocator.dupeZ(u8, str);
+ field.* = try allocator.dupeSentinel(u8, str, 0);
}
fn timezoneValidator(allocator: Allocator, args: *std.process.Args.Iterator, field: *?[:0]const u8) !void {
@@ -1654,7 +1654,7 @@ fn timezoneValidator(allocator: Allocator, args: *std.process.Args.Iterator, fie
log.fatal(.app, "invalid option value", .{ .arg = "--timezone", .value = str, .err = err, .hint = "must be an IANA time zone such as Europe/Paris or UTC" });
return error.InvalidArgument;
};
- field.* = try allocator.dupeZ(u8, str);
+ field.* = try allocator.dupeSentinel(u8, str, 0);
}
/// A BCP 47 tag restricted to what ICU and the Accept-Language derivation
@@ -1708,8 +1708,8 @@ pub const tagNames = cli.tagNames;
/// `<a|b|c>` ghost-text hint built from the same enum's tag names.
pub fn tagHint(comptime E: type) []const u8 {
var s: []const u8 = "<";
- for (@typeInfo(E).@"enum".fields, 0..) |f, i| {
- s = s ++ (if (i == 0) f.name else "|" ++ f.name);
+ for (@typeInfo(E).@"enum".field_names, 0..) |field_name, i| {
+ s = s ++ (if (i == 0) field_name else "|" ++ field_name);
}
return s ++ ">";
}
@@ -1717,8 +1717,8 @@ pub fn tagHint(comptime E: type) []const u8 {
/// JSON array `["a","b","c"]` representation of the enum tag names.
pub fn tagJsonArray(comptime E: type) []const u8 {
var s: []const u8 = "[";
- for (@typeInfo(E).@"enum".fields, 0..) |f, i| {
- s = s ++ (if (i == 0) "\"" else ",\"") ++ f.name ++ "\"";
+ for (@typeInfo(E).@"enum".field_names, 0..) |field_name, i| {
+ s = s ++ (if (i == 0) "\"" else ",\"") ++ field_name ++ "\"";
}
return s ++ "]";
}
diff --git a/src/Metrics.zig b/src/Metrics.zig
index c92278d6f..5fb5cdc89 100644
--- a/src/Metrics.zig
+++ b/src/Metrics.zig
@@ -151,8 +151,8 @@ fn _write(self: *const Metrics, writer: *std.Io.Writer) !void {
"# TYPE build_info gauge\nbuild_info{{version=\"{s}\"}} 1\n",
.{lp.build_config.version},
);
- inline for (@typeInfo(Metrics).@"struct".fields) |f| {
- try @field(self, f.name).write(f.name, @field(help, f.name), writer);
+ inline for (@typeInfo(Metrics).@"struct".field_names) |field_name| {
+ try @field(self, field_name).write(field_name, @field(help, field_name), writer);
}
}
diff --git a/src/Notification.zig b/src/Notification.zig
index ab43e73ab..f13e8deb2 100644
--- a/src/Notification.zig
+++ b/src/Notification.zig
@@ -484,12 +484,7 @@ pub fn dispatch(self: *Notification, comptime event: EventType, data: ArgType(ev
// Given an event type enum, returns the type of arg the event emits
pub fn ArgType(comptime event: Notification.EventType) type {
- inline for (std.meta.fields(Notification.Events)) |f| {
- if (std.mem.eql(u8, f.name, @tagName(event))) {
- return f.type;
- }
- }
- unreachable;
+ return @FieldType(Notification.Events, @tagName(event));
}
// Given an event type enum, returns the listening function type
diff --git a/src/RecyclingAllocator.zig b/src/RecyclingAllocator.zig
index 663d8c10b..9f40cf121 100644
--- a/src/RecyclingAllocator.zig
+++ b/src/RecyclingAllocator.zig
@@ -43,7 +43,7 @@ free_lists: std.array_hash_map.Custom(Class, ?[*]u8, Class.Context, false) = .em
// class, e.g. a 34-byte string and a 40-byte node recycle each other.
const Class = packed struct(u64) {
alignment: Alignment,
- size: std.meta.Int(.unsigned, 64 - @bitSizeOf(Alignment)),
+ size: @Int(.unsigned, 64 - @bitSizeOf(Alignment)),
fn of(len: usize, alignment: Alignment) Class {
const class_alignment = Alignment.max(alignment, .of(usize));
diff --git a/src/Regex.zig b/src/Regex.zig
index a5c567f60..f37798b05 100644
--- a/src/Regex.zig
+++ b/src/Regex.zig
@@ -25,6 +25,7 @@
const std = @import("std");
const pcre2 = @import("pcre2");
+const repeat = @import("string.zig").repeat;
const Allocator = std.mem.Allocator;
@@ -171,8 +172,9 @@ const MATCH_SCRATCH = 24 * 1024;
/// Whether the pattern matches anywhere in `text`, as `RegExp.test` would
/// answer. A match that hits the backtracking limits counts as no match.
pub fn matches(self: Regex, text: []const u8) bool {
- var scratch = std.heap.stackFallback(MATCH_SCRATCH, self.context.allocator);
- var allocator = scratch.get();
+ var scratch_buf: [MATCH_SCRATCH]u8 = undefined;
+ var scratch: std.heap.BufferFirstAllocator = .init(&scratch_buf, self.context.allocator);
+ var allocator = scratch.allocator();
const general = pcre2.pcre2_general_context_create_8(Context.cMalloc, Context.cFree, &allocator) orelse return false;
defer pcre2.pcre2_general_context_free_8(general);
@@ -236,9 +238,9 @@ test "Regex: invalid patterns are errors, runaway ones no match" {
// the caller.
const runaway = try context.compile("^(a+)+$", .{ .case_insensitive = true }, null);
defer runaway.deinit();
- const subject = "a" ** 64 ++ "b";
+ const subject = repeat("a", 64) ++ "b";
try testing.expect(!runaway.matches(subject));
- try testing.expect(runaway.matches("a" ** 64));
+ try testing.expect(runaway.matches(repeat("a", 64)));
}
test "Regex: dot_all and multiline follow the JavaScript flags" {
diff --git a/src/SemanticTree.zig b/src/SemanticTree.zig
index 575337cd2..76cb4b07f 100644
--- a/src/SemanticTree.zig
+++ b/src/SemanticTree.zig
@@ -385,7 +385,7 @@ const JsonVisitor = struct {
try self.jw.beginObject();
try self.jw.objectField("nodeId");
- try self.jw.write(try std.fmt.allocPrint(self.tree.arena, "{d}", .{data.id}));
+ try self.jw.write(try self.tree.arena.print("{d}", .{data.id}));
try self.jw.objectField("backendDOMNodeId");
try self.jw.write(data.id);
diff --git a/src/Sighandler.zig b/src/Sighandler.zig
index c6638efbe..aabeef9d2 100644
--- a/src/Sighandler.zig
+++ b/src/Sighandler.zig
@@ -129,7 +129,7 @@ fn sighandle(self: *SigHandler) noreturn {
std.process.exit(1);
}
- switch (@as(std.posix.SIG, @enumFromInt(sig))) {
+ switch (@as(std.posix.SIG, @fromBackingInt(@intCast(sig)))) {
.INT, .TERM => {
self.mutex.lockUncancelable(lp.io);
if (self.attempt > 1 and !self.no_hard_exit) {
diff --git a/src/TestWSServer.zig b/src/TestWSServer.zig
index ed24c380a..9f889ce60 100644
--- a/src/TestWSServer.zig
+++ b/src/TestWSServer.zig
@@ -145,7 +145,7 @@ fn handleClient(client: posix.socket_t) void {
// Send upgrade response
var resp_buf: [256]u8 = undefined;
- const resp = std.fmt.bufPrint(&resp_buf, "HTTP/1.1 101 Switching Protocols\r\n" ++
+ const resp = std.mem.print(&resp_buf, "HTTP/1.1 101 Switching Protocols\r\n" ++
"Upgrade: websocket\r\n" ++
"Connection: Upgrade\r\n" ++
"Sec-WebSocket-Accept: {s}\r\n\r\n", .{accept_key}) catch return;
diff --git a/src/agent/Agent.zig b/src/agent/Agent.zig
index 15b0a76b5..a605c13c3 100644
--- a/src/agent/Agent.zig
+++ b/src/agent/Agent.zig
@@ -55,8 +55,8 @@ const UserError = error{
};
pub fn isUserError(err: anyerror) bool {
- inline for (@typeInfo(UserError).error_set.?) |e| {
- if (err == @field(anyerror, e.name)) return true;
+ inline for (@typeInfo(UserError).error_set.error_names.?) |name| {
+ if (err == @field(anyerror, name)) return true;
}
return false;
}
@@ -194,7 +194,7 @@ api_error_buf: [512]u8 = undefined,
api_error_detail: ?[]const u8 = null,
pub fn init(allocator: std.mem.Allocator, app: *App, opts: Config.Agent) !*Agent {
- var providers_buf: [@typeInfo(Config.AiProvider).@"enum".fields.len]Candidate = undefined;
+ var providers_buf: [@typeInfo(Config.AiProvider).@"enum".field_names.len]Candidate = undefined;
const found_providers = settings.availableProviders(&providers_buf);
const available_providers = try allocator.alloc([]const u8, found_providers.len);
for (found_providers, 0..) |f, i| {
@@ -233,8 +233,9 @@ pub fn init(allocator: std.mem.Allocator, app: *App, opts: Config.Agent) !*Agent
// Load remembered selection up front so a saved null provider can flip the
// REPL into basic mode before resolution. Pure script runs need nothing.
- const remembered: ?settings.Remembered = if (will_repl or is_one_shot) settings.loadRemembered(allocator) else null;
- defer if (remembered) |r| std.zon.parse.free(allocator, r);
+ var remembered_arena: std.heap.ArenaAllocator = .init(allocator);
+ defer remembered_arena.deinit();
+ const remembered: ?settings.Remembered = if (will_repl or is_one_shot) settings.loadRemembered(allocator, remembered_arena.allocator()) else null;
// A remembered null provider means the user disabled the LLM via
// `/provider null`; honor it for the REPL only (one-shot --task and script
@@ -645,7 +646,7 @@ fn runRepl(self: *Agent) void {
self.terminal.printError("{s}", .{switch (err) {
error.OutOfMemory => "out of memory",
error.FrameNotLoaded => "no page loaded — run /goto <url> first (Esc exits JS mode)",
- else => std.fmt.allocPrint(aa, "evaluate failed: {s}", .{@errorName(err)}) catch "evaluate failed",
+ else => aa.print("evaluate failed: {s}", .{@errorName(err)}) catch "evaluate failed",
}});
continue :repl;
};
@@ -699,7 +700,7 @@ fn runRepl(self: *Agent) void {
.comment => continue :repl,
.llm => |lc| {
var label_buf: [32]u8 = undefined;
- const label = std.fmt.bufPrint(&label_buf, "/{s}", .{@tagName(lc)}) catch "/?";
+ const label = std.mem.print(&label_buf, "/{s}", .{@tagName(lc)}) catch "/?";
if (!self.requireLlm(label)) continue :repl;
_ = self.runTurn(.{ .prompt = lc.prompt(), .record_comment = line, .capture_for_save = true, .label = label });
},
@@ -1008,7 +1009,7 @@ fn subscriptionLogin(self: *Agent, desc: *const auth.Descriptor) ?auth.Session {
fn promptStoredSubscription(self: *Agent, desc: *const auth.Descriptor, stored: auth.Session) ?auth.Session {
var session = stored;
var header_buf: [128]u8 = undefined;
- const header = std.fmt.bufPrint(&header_buf, "Already logged in with your {s}. Pick:", .{desc.label}) catch
+ const header = std.mem.print(&header_buf, "Already logged in with your {s}. Pick:", .{desc.label}) catch
"Already logged in. Pick:";
const idx = picker.promptNumberedChoice(header, &.{
"keep — use the stored login",
@@ -1167,7 +1168,7 @@ fn handleSave(self: *Agent, arena: std.mem.Allocator, rest: []const u8) void {
fn promptSaveMode(self: *Agent, path: []const u8) ?save.Mode {
var header_buf: [256]u8 = undefined;
- const header = std.fmt.bufPrint(&header_buf, "{s} already exists. Pick save mode:", .{path}) catch
+ const header = std.mem.print(&header_buf, "{s} already exists. Pick save mode:", .{path}) catch
"File already exists. Pick save mode:";
const with_llm = self.ai_client != null;
const modes: []const save.Mode = if (with_llm)
@@ -1507,7 +1508,7 @@ fn runCommand(self: *Agent, arena: std.mem.Allocator, tc: Command.ToolCall) brow
.text = switch (err) {
error.OutOfMemory => "out of memory",
error.FrameNotLoaded => "no page loaded — run /goto <url> first",
- else => std.fmt.allocPrint(arena, "{s} failed: {s}", .{ tc.name(), browser_tools.errorMessage(err) }) catch "tool failed",
+ else => arena.print("{s} failed: {s}", .{ tc.name(), browser_tools.errorMessage(err) }) catch "tool failed",
},
.is_error = true,
};
@@ -1634,7 +1635,7 @@ fn recordSlashToolCall(
const tool_calls = try ma.alloc(zenai.provider.ToolCall, 1);
tool_calls[0] = .{
- .id = try std.fmt.allocPrint(ma, "lp-slash-{d}", .{self.synthetic_tool_call_id}),
+ .id = try ma.print("lp-slash-{d}", .{self.synthetic_tool_call_id}),
.name = try ma.dupe(u8, tool_name),
.arguments = if (args) |v| try zenai.json.dupeValue(ma, v) else null,
};
@@ -1685,9 +1686,9 @@ fn formatApiError(self: *Agent, client: zenai.provider.Client, err: anyerror) []
else
"";
if (e.message) |m| {
- if (std.fmt.bufPrint(&self.api_error_buf, "HTTP {d} — {s}{s}", .{ status, m, hint })) |s| return s else |_| {}
+ if (std.mem.print(&self.api_error_buf, "HTTP {d} — {s}{s}", .{ status, m, hint })) |s| return s else |_| {}
}
- return std.fmt.bufPrint(&self.api_error_buf, "HTTP {d}{s}", .{ status, hint }) catch @errorName(err);
+ return std.mem.print(&self.api_error_buf, "HTTP {d}{s}", .{ status, hint }) catch @errorName(err);
}
/// Returned text lives in `conversation.arena`, valid only until the next prune.
@@ -1932,7 +1933,7 @@ fn capToolOutput(allocator: std.mem.Allocator, tool_name: []const u8, output: []
if (output.len <= cap) return output;
const prefix = string.truncateUtf8(output, cap);
var suffix_buf: [128]u8 = undefined;
- const suffix = std.fmt.bufPrint(&suffix_buf, "\n...[truncated, original {d} bytes — re-read scoped (selector/backendNodeId)]", .{output.len}) catch return prefix;
+ const suffix = std.mem.print(&suffix_buf, "\n...[truncated, original {d} bytes — re-read scoped (selector/backendNodeId)]", .{output.len}) catch return prefix;
return std.mem.concat(allocator, u8, &.{ prefix, suffix }) catch prefix;
}
@@ -1954,7 +1955,7 @@ fn handleToolCall(ctx: *anyopaque, allocator: std.mem.Allocator, tool_name: []co
var selector: ?[]const u8 = null;
const outcome = self.toolOutcome(allocator, tool_name, arguments, &selector) catch |err| zenai.provider.Client.ToolHandler.Result{
- .content = std.fmt.allocPrint(allocator, "Error: {s}", .{browser_tools.errorMessage(err)}) catch "Error: tool execution failed",
+ .content = allocator.print("Error: {s}", .{browser_tools.errorMessage(err)}) catch "Error: tool execution failed",
.is_error = true,
};
if (self.capturing_for_save) {
diff --git a/src/agent/Conversation.zig b/src/agent/Conversation.zig
index 5b4a8e3c4..c851a3db3 100644
--- a/src/agent/Conversation.zig
+++ b/src/agent/Conversation.zig
@@ -151,7 +151,7 @@ test "expireImages keeps the newest images and annotates the rest" {
const image = [_]zenai.provider.ContentPart{.{ .image = .{ .data = "AAAA", .mime_type = "image/png" } }};
for (0..4) |n| {
const results = try a.alloc(zenai.provider.ToolResult, 1);
- results[0] = .{ .id = "c", .name = "screenshot", .content = try std.fmt.allocPrint(a, "shot {d}", .{n}), .parts = &image };
+ results[0] = .{ .id = "c", .name = "screenshot", .content = try a.print("shot {d}", .{n}), .parts = &image };
try conv.messages.append(std.testing.allocator, .{ .role = .tool, .tool_results = results });
}
diff --git a/src/agent/Spinner.zig b/src/agent/Spinner.zig
index 500b55cbc..70cfde678 100644
--- a/src/agent/Spinner.zig
+++ b/src/agent/Spinner.zig
@@ -140,7 +140,7 @@ pub fn stop(self: *Spinner) void {
const elapsed_s = @as(f64, @floatFromInt(elapsed_ms)) / @as(f64, std.time.ms_per_s);
var buf: [frame_buf_bytes]u8 = undefined;
- const summary = std.fmt.bufPrint(
+ const summary = std.mem.print(
&buf,
"\r" ++ clear_eol ++ ansi.dim ++ "[agent: worked for {d:.1}s · {d} tool call{s}]" ++ ansi.reset ++ "\n",
.{ elapsed_s, self.tool_calls, if (self.tool_calls == 1) "" else "s" },
@@ -275,7 +275,7 @@ fn renderLocked(self: *Spinner) void {
const glyph = braille[self.frame % braille.len];
const written = switch (self.state) {
.idle => return,
- .thinking => std.fmt.bufPrint(
+ .thinking => std.mem.print(
&buf,
"\r" ++ ansi.yellow ++ "{s}" ++ ansi.reset ++ " " ++ ansi.dim ++ "[agent: thinking]" ++ ansi.reset ++ clear_eol,
.{glyph},
@@ -297,7 +297,7 @@ fn renderLocked(self: *Spinner) void {
const cap = @min(max_args_cells, room);
const cut = truncToCells(all_args, cap);
const suffix: []const u8 = if (cut < all_args.len) ellipsis else "";
- break :blk std.fmt.bufPrint(
+ break :blk std.mem.print(
&buf,
"\r" ++ ansi.yellow ++ "{s}" ++ ansi.reset ++ " " ++ ansi.dim ++ "[{s}{s} {s}{s}]" ++ ansi.reset ++ clear_eol,
.{ glyph, prefix, name, all_args[0..cut], suffix },
diff --git a/src/agent/Terminal.zig b/src/agent/Terminal.zig
index 6dcd2a295..d2669e2e4 100644
--- a/src/agent/Terminal.zig
+++ b/src/agent/Terminal.zig
@@ -141,7 +141,7 @@ fn emitStderr(self: *Terminal, bytes: []const u8) void {
fn formatBulletLine(arena: std.mem.Allocator, name: []const u8, args: []const u8, ok: bool) ![]const u8 {
const bullet_color = if (ok) ansi.green else ansi.red;
- return std.fmt.allocPrint(arena, bullet_line_fmt, .{ bullet_color, ansi.reset, ansi.dim, name, ansi.reset, args });
+ return arena.print(bullet_line_fmt, .{ bullet_color, ansi.reset, ansi.dim, name, ansi.reset, args });
}
pub fn setIdleCallback(fun: ?*const c.ic_idle_fun_t, arg: ?*anyopaque) void {
@@ -307,7 +307,7 @@ pub fn printToolOutcome(self: *Terminal, name: []const u8, text: []const u8, is_
pub fn printScriptDone(self: *Terminal, name: []const u8, args: []const u8) void {
if (!self.spinner.isEnabled()) return;
var buf: [256]u8 = undefined;
- const line = std.fmt.bufPrint(
+ const line = std.mem.print(
&buf,
ansi.green ++ "●" ++ ansi.reset ++ " " ++ ansi.dim ++ "[{s} {s}]" ++ ansi.reset ++ "\n",
.{ name, args },
@@ -354,7 +354,7 @@ pub fn printWarning(self: *Terminal, comptime fmt: []const u8, args: anytype) vo
fn printSeverity(self: *Terminal, color: []const u8, label: []const u8, comptime fmt: []const u8, args: anytype) void {
if (self.repl_arena) |*a| {
defer _ = a.reset(.retain_capacity);
- const bytes = std.fmt.allocPrint(a.allocator(), "{s}●{s} " ++ fmt ++ "\n", .{ color, ansi.reset } ++ args) catch return;
+ const bytes = a.allocator().print("{s}●{s} " ++ fmt ++ "\n", .{ color, ansi.reset } ++ args) catch return;
return self.emitStderr(bytes);
}
std.debug.print("{s}{s}{s}: " ++ fmt ++ "{s}\n", .{ ansi.bold, color, label } ++ args ++ .{ansi.reset});
diff --git a/src/agent/auth/auth.zig b/src/agent/auth/auth.zig
index 074a4ad50..de06eb296 100644
--- a/src/agent/auth/auth.zig
+++ b/src/agent/auth/auth.zig
@@ -50,7 +50,7 @@ pub const TokenSet = struct {
account_id: ?[]const u8 = null,
pub fn dup(allocator: std.mem.Allocator, access: []const u8, refresh: []const u8, expires_at_ms: i64, account_id: ?[]const u8) !TokenSet {
- const a = try allocator.dupeZ(u8, access);
+ const a = try allocator.dupeSentinel(u8, access, 0);
errdefer allocator.free(a);
const r = try allocator.dupe(u8, refresh);
errdefer allocator.free(r);
diff --git a/src/agent/auth/codex.zig b/src/agent/auth/codex.zig
index cdee87474..c69f4f3db 100644
--- a/src/agent/auth/codex.zig
+++ b/src/agent/auth/codex.zig
@@ -108,13 +108,13 @@ fn parseTokenResponse(allocator: std.mem.Allocator, body: []const u8) !auth.Toke
}
fn refreshBody(arena: std.mem.Allocator, refresh_token: []const u8) ![]u8 {
- return std.fmt.allocPrint(arena, "grant_type=refresh_token&client_id=" ++ client_id ++ "&refresh_token={s}", .{
+ return arena.print("grant_type=refresh_token&client_id=" ++ client_id ++ "&refresh_token={s}", .{
try lp.URL.percentEncodeSegment(arena, refresh_token, .component),
});
}
fn exchangeBody(arena: std.mem.Allocator, code: []const u8, code_verifier: []const u8) ![]u8 {
- return std.fmt.allocPrint(arena, "grant_type=authorization_code&client_id=" ++ client_id ++
+ return arena.print("grant_type=authorization_code&client_id=" ++ client_id ++
"&redirect_uri=" ++ device_redirect_uri ++ "&code={s}&code_verifier={s}", .{
try lp.URL.percentEncodeSegment(arena, code, .component),
try lp.URL.percentEncodeSegment(arena, code_verifier, .component),
@@ -155,7 +155,7 @@ fn deviceLogin(allocator: std.mem.Allocator, interrupt: ?*zenai.http.Interrupt)
const code_res = try post(a, interrupt, device_code_url, "application/json", "{\"client_id\":\"" ++ client_id ++ "\"}");
if (code_res.status != .ok) {
- log.warn(.app, "codex device-code failed", .{ .status = @intFromEnum(code_res.status), .body = code_res.body });
+ log.warn(.app, "codex device-code failed", .{ .status = @backingInt(code_res.status), .body = code_res.body });
return error.DeviceCodeRequestFailed;
}
const dc = try std.json.parseFromSliceLeaky(DeviceCode, a, code_res.body, .{ .ignore_unknown_fields = true });
@@ -166,7 +166,7 @@ fn deviceLogin(allocator: std.mem.Allocator, interrupt: ?*zenai.http.Interrupt)
.{ verify_url, dc.user_code },
);
- const poll_body = try std.fmt.allocPrint(a, "{f}", .{std.json.fmt(
+ const poll_body = try a.print("{f}", .{std.json.fmt(
.{ .device_auth_id = dc.device_auth_id, .user_code = dc.user_code },
.{},
)});
@@ -178,7 +178,7 @@ fn deviceLogin(allocator: std.mem.Allocator, interrupt: ?*zenai.http.Interrupt)
// Still pending — the user hasn't finished authorizing.
.forbidden, .not_found => continue,
else => {
- log.warn(.app, "codex device-auth poll failed", .{ .status = @intFromEnum(res.status), .body = res.body });
+ log.warn(.app, "codex device-auth poll failed", .{ .status = @backingInt(res.status), .body = res.body });
return error.DeviceAuthFailed;
},
}
@@ -187,7 +187,7 @@ fn deviceLogin(allocator: std.mem.Allocator, interrupt: ?*zenai.http.Interrupt)
const exchange = try exchangeBody(a, dt.authorization_code, dt.code_verifier);
const tok_res = try post(a, interrupt, token_url, "application/x-www-form-urlencoded", exchange);
if (tok_res.status != .ok) {
- log.warn(.app, "codex token exchange failed", .{ .status = @intFromEnum(tok_res.status), .body = tok_res.body });
+ log.warn(.app, "codex token exchange failed", .{ .status = @backingInt(tok_res.status), .body = tok_res.body });
return error.TokenExchangeFailed;
}
return parseTokenResponse(allocator, tok_res.body);
@@ -200,7 +200,7 @@ fn refreshGrant(allocator: std.mem.Allocator, refresh_token: []const u8) !auth.T
const body = try refreshBody(a, refresh_token);
const res = try post(a, null, token_url, "application/x-www-form-urlencoded", body);
if (res.status != .ok) {
- log.warn(.app, "codex token refresh failed", .{ .status = @intFromEnum(res.status), .body = res.body });
+ log.warn(.app, "codex token refresh failed", .{ .status = @backingInt(res.status), .body = res.body });
return error.RefreshFailed;
}
return parseTokenResponse(allocator, res.body);
@@ -233,7 +233,7 @@ fn makeJwt(arena: std.mem.Allocator, payload_json: []const u8) ![]const u8 {
const enc = std.base64.url_safe_no_pad.Encoder;
const p = try arena.alloc(u8, enc.calcSize(payload_json.len));
_ = enc.encode(p, payload_json);
- return std.fmt.allocPrint(arena, "aGVhZGVy.{s}.c2ln", .{p});
+ return arena.print("aGVhZGVy.{s}.c2ln", .{p});
}
test "accountIdFromJwt: top-level chatgpt_account_id" {
@@ -281,7 +281,7 @@ test "parseTokenResponse derives account id and absolute expiry" {
defer arena.deinit();
const a = arena.allocator();
const jwt = try makeJwt(a, "{\"chatgpt_account_id\":\"acct-x\"}");
- const body = try std.fmt.allocPrint(a, "{{\"access_token\":\"acc\",\"refresh_token\":\"ref\",\"id_token\":\"{s}\",\"expires_in\":3600}}", .{jwt});
+ const body = try a.print("{{\"access_token\":\"acc\",\"refresh_token\":\"ref\",\"id_token\":\"{s}\",\"expires_in\":3600}}", .{jwt});
const tokens = try parseTokenResponse(std.testing.allocator, body);
defer tokens.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("acc", tokens.access_token);
diff --git a/src/agent/auth/models_dev.zig b/src/agent/auth/models_dev.zig
index 9e3221b96..12d6fb4d1 100644
--- a/src/agent/auth/models_dev.zig
+++ b/src/agent/auth/models_dev.zig
@@ -51,7 +51,7 @@ const Cache = struct {
};
fn cachePath(arena: std.mem.Allocator, app_dir: []const u8, provider_id: []const u8) ![]const u8 {
- const name = try std.fmt.allocPrint(arena, "models-dev-{s}.json", .{provider_id});
+ const name = try arena.print("models-dev-{s}.json", .{provider_id});
return std.fs.path.join(arena, &.{ app_dir, name });
}
diff --git a/src/agent/md_term.zig b/src/agent/md_term.zig
index 239db1029..e59534a81 100644
--- a/src/agent/md_term.zig
+++ b/src/agent/md_term.zig
@@ -19,6 +19,7 @@
const std = @import("std");
const ansi = @import("ansi.zig");
const js_highlight = @import("js_highlight.zig");
+const repeat = @import("../string.zig").repeat;
/// Render markdown `src` as ANSI-styled terminal output to `w`. Tables are
/// aligned straight from `src`, so unlike `Stream` there is no size limit.
@@ -470,7 +471,7 @@ fn renderLine(w: *std.Io.Writer, line: []const u8, js: ?*js_highlight.State) !vo
// Dashed, unlike the solid fence rules, so adjacent ones read differently.
if (isHorizontalRule(trimmed)) {
- try styled(w, "┄" ** rule_width, ansi.dim);
+ try styled(w, repeat("┄", rule_width), ansi.dim);
return;
}
@@ -729,8 +730,8 @@ test "md_term: nested inline styles" {
);
}
-const open_rule = "\x1b[2m╭" ++ "─" ** 23 ++ "\x1b[0m";
-const close_rule = "\x1b[2m╰" ++ "─" ** 23 ++ "\x1b[0m";
+const open_rule = "\x1b[2m╭" ++ repeat("─", 23) ++ "\x1b[0m";
+const close_rule = "\x1b[2m╰" ++ repeat("─", 23) ++ "\x1b[0m";
test "md_term: fenced code block is highlighted as JavaScript" {
try expectRender(
@@ -743,13 +744,13 @@ test "md_term: fenced code block is highlighted as JavaScript" {
test "md_term: fence rules carry the language tag" {
try expectRender(
- "\x1b[2m╭─ js " ++ "─" ** 18 ++ "\x1b[0m\n\nx\n\n" ++ close_rule,
+ "\x1b[2m╭─ js " ++ repeat("─", 18) ++ "\x1b[0m\n\nx\n\n" ++ close_rule,
"```js\nx\n```",
);
// An overlong info string doesn't fit the rule and is dropped.
try expectRender(
open_rule ++ "\n\nx\n\n" ++ close_rule,
- "```" ++ "x" ** 20 ++ "\nx\n```",
+ "```" ++ repeat("x", 20) ++ "\nx\n```",
);
}
@@ -791,8 +792,8 @@ test "md_term: blockquote" {
}
test "md_term: horizontal rule" {
- try expectRender("\x1b[2m" ++ "┄" ** 24 ++ "\x1b[0m", "---");
- try expectRender("\x1b[2m" ++ "┄" ** 24 ++ "\x1b[0m", "***");
+ try expectRender("\x1b[2m" ++ repeat("┄", 24) ++ "\x1b[0m", "---");
+ try expectRender("\x1b[2m" ++ repeat("┄", 24) ++ "\x1b[0m", "***");
try expectRender("---x", "---x");
}
@@ -828,7 +829,7 @@ test "md_term: pipe rows without a separator pass through" {
try expectRender("| a |\n", "| a |\n");
}
-const big_table = "| A | B |\n|-|-|\n" ++ ("| " ++ "a" ** 16 ++ " | " ++ "b" ** 16 ++ " |\n") ** 500;
+const big_table = "| A | B |\n|-|-|\n" ++ repeat("| " ++ repeat("a", 16) ++ " | " ++ repeat("b", 16) ++ " |\n", 500);
test "md_term: batch aligns tables beyond the stream table buffer" {
try testing.expect(big_table.len > table_buf_len);
@@ -839,8 +840,8 @@ test "md_term: batch aligns tables beyond the stream table buffer" {
const pipe = "\x1b[2m│\x1b[0m";
try testing.expectEqual(0, std.mem.count(u8, out, "| a"));
- try testing.expectEqual(500, std.mem.count(u8, out, pipe ++ " " ++ "a" ** 16 ++ " " ++ pipe));
- try testing.expect(std.mem.indexOf(u8, out, "\x1b[2m├" ++ "─" ** 18 ++ "┼" ++ "─" ** 18 ++ "┤\x1b[0m\n") != null);
+ try testing.expectEqual(500, std.mem.count(u8, out, pipe ++ " " ++ repeat("a", 16) ++ " " ++ pipe));
+ try testing.expect(std.mem.indexOf(u8, out, "\x1b[2m├" ++ repeat("─", 18) ++ "┼" ++ repeat("─", 18) ++ "┤\x1b[0m\n") != null);
}
test "md_term: stream falls back to raw rows past its table buffer" {
@@ -853,8 +854,8 @@ test "md_term: stream falls back to raw rows past its table buffer" {
}
test "md_term: overwide table falls back to verbatim rows" {
- const header = "|a" ** 17 ++ "|";
- const sep = "|-" ** 17 ++ "|";
+ const header = repeat("|a", 17) ++ "|";
+ const sep = repeat("|-", 17) ++ "|";
try expectRender(
"\x1b[1m" ++ header ++ "\x1b[0m\n\x1b[2m" ++ sep ++ "\x1b[0m\n",
header ++ "\n" ++ sep,
diff --git a/src/agent/picker.zig b/src/agent/picker.zig
index 79879b32a..097fb3d75 100644
--- a/src/agent/picker.zig
+++ b/src/agent/picker.zig
@@ -118,8 +118,8 @@ const RawTerminal = struct {
raw.lflag.ICANON = false;
raw.lflag.IEXTEN = false;
raw.lflag.ISIG = false;
- raw.cc[@intFromEnum(std.c.V.MIN)] = 0;
- raw.cc[@intFromEnum(std.c.V.TIME)] = 1;
+ raw.cc[@backingInt(std.c.V.MIN)] = 0;
+ raw.cc[@backingInt(std.c.V.TIME)] = 1;
std.posix.tcsetattr(std.posix.STDIN_FILENO, .FLUSH, raw) catch return error.NotInteractive;
// Under `ansi.kitty_disambiguate` (pushed by `Terminal.readLine`),
// cursor keys arrive as CSI-u the byte reader can't parse; push the
diff --git a/src/agent/prompt_assist.zig b/src/agent/prompt_assist.zig
index eaa5be3be..6b200b9b8 100644
--- a/src/agent/prompt_assist.zig
+++ b/src/agent/prompt_assist.zig
@@ -72,13 +72,13 @@ const kind_styles = blk: {
const n = std.enums.values(js_highlight.Kind).len;
var arr: [n]?[:0]const u8 = @splat(null);
for (styles) |s| for (s.kinds) |kind| {
- if (arr[@intFromEnum(kind)] != null) @compileError("kind styled twice: " ++ @tagName(kind));
- arr[@intFromEnum(kind)] = s.name;
+ if (arr[@backingInt(kind)] != null) @compileError("kind styled twice: " ++ @tagName(kind));
+ arr[@backingInt(kind)] = s.name;
};
var out: [n][:0]const u8 = undefined;
for (arr, 0..) |name, i| {
out[i] = name orelse @compileError("js_highlight.Kind with no ps-* style: " ++
- @tagName(@as(js_highlight.Kind, @enumFromInt(i))));
+ @tagName(@as(js_highlight.Kind, @fromBackingInt(@intCast(i)))));
}
break :blk out;
};
@@ -169,7 +169,7 @@ fn addPrefixedCompletion(
partial: []const u8,
) void {
if (!std.ascii.startsWithIgnoreCase(name, partial)) return;
- const text = std.fmt.bufPrintZ(buf, "{s}{s}{s}", .{ prefix, name, suffix }) catch return;
+ const text = std.mem.printSentinel(buf, "{s}{s}{s}", .{ prefix, name, suffix }, 0) catch return;
_ = c.ic_add_completion_prim(cenv, text.ptr, null, null, @intCast(input.len), 0);
}
@@ -408,7 +408,7 @@ fn addPathCompletions(
var name_buf: [completion_buf_len]u8 = undefined;
while (matches.next()) |m| {
const suffix: []const u8 = if (m.is_dir) "/" else "";
- const full = std.fmt.bufPrint(&name_buf, "{s}{s}", .{ matches.dir_part, m.name }) catch continue;
+ const full = std.mem.print(&name_buf, "{s}{s}", .{ matches.dir_part, m.name }) catch continue;
addPrefixedCompletion(cenv, buf, input, prefix, full, suffix, body);
}
}
@@ -580,7 +580,7 @@ fn ghostPathFirstMatch(body: []const u8) [*c]const u8 {
defer matches.deinit();
const m = matches.next() orelse return null;
const suffix: []const u8 = if (m.is_dir) "/" else "";
- const text = std.fmt.bufPrintZ(&hint_buf, "{s}{s}", .{ m.name[matches.base.len..], suffix }) catch return null;
+ const text = std.mem.printSentinel(&hint_buf, "{s}{s}", .{ m.name[matches.base.len..], suffix }, 0) catch return null;
return text.ptr;
}
@@ -589,7 +589,7 @@ fn ghostPathFirstMatch(body: []const u8) [*c]const u8 {
fn ghostFirstMatch(names: []const []const u8, body: []const u8, lead: []const u8) [*c]const u8 {
for (names) |v| {
if (!std.ascii.startsWithIgnoreCase(v, body)) continue;
- const text = std.fmt.bufPrintZ(&hint_buf, "{s}{s}", .{ lead, v[body.len..] }) catch return null;
+ const text = std.mem.printSentinel(&hint_buf, "{s}{s}", .{ lead, v[body.len..] }, 0) catch return null;
return text.ptr;
}
return null;
@@ -621,7 +621,7 @@ fn renderSchemaHint(schema: *const Schema, body: []const u8, ends_ws: bool) [*c]
for (schema.hints) |slot| {
if (a.isUsed(slot.name)) continue;
if (!std.ascii.startsWithIgnoreCase(slot.name, pk)) continue;
- const text = std.fmt.bufPrintZ(&hint_buf, "{s}=…", .{slot.name[pk.len..]}) catch return null;
+ const text = std.mem.printSentinel(&hint_buf, "{s}=…", .{slot.name[pk.len..]}, 0) catch return null;
return text.ptr;
}
return null;
@@ -725,7 +725,7 @@ const IcSink = struct {
henv: ?*c.ic_highlight_env_t,
pub fn emit(self: IcSink, start: usize, len: usize, kind: js_highlight.Kind) void {
- c.ic_highlight(self.henv, @intCast(start), @intCast(len), kind_styles[@intFromEnum(kind)].ptr);
+ c.ic_highlight(self.henv, @intCast(start), @intCast(len), kind_styles[@backingInt(kind)].ptr);
}
};
diff --git a/src/agent/save.zig b/src/agent/save.zig
index d2f212009..ccbf988a7 100644
--- a/src/agent/save.zig
+++ b/src/agent/save.zig
@@ -72,7 +72,7 @@ pub fn randomFilename(arena: std.mem.Allocator) ![]const u8 {
var n_bytes: [8]u8 = undefined;
lp.io.random(&n_bytes);
const n = std.mem.readInt(u64, &n_bytes, .little);
- const path = try std.fmt.allocPrint(arena, "session-{x}.js", .{n});
+ const path = try arena.print("session-{x}.js", .{n});
if (!(try fileExists(path))) return path;
}
return error.NameCollision;
diff --git a/src/agent/settings.zig b/src/agent/settings.zig
index 817d6ca78..3594b71e4 100644
--- a/src/agent/settings.zig
+++ b/src/agent/settings.zig
@@ -126,7 +126,7 @@ pub fn gcloudAccessToken(allocator: std.mem.Allocator) ![:0]const u8 {
std.debug.print("`gcloud auth print-access-token` failed:\n{s}", .{result.stderr});
return error.GcloudTokenFailed;
}
- return allocator.dupeZ(u8, token);
+ return allocator.dupeSentinel(u8, token, 0);
}
/// True when a non-Ollama provider key is available (flag, remembered, or
@@ -271,24 +271,24 @@ pub const Remembered = struct {
search_engine: ?lp.tools.SearchEngine = null,
};
-pub fn loadRemembered(allocator: std.mem.Allocator) ?Remembered {
- const data = std.Io.Dir.cwd().readFileAllocOptions(lp.io, remembered_path, allocator, .limited(1024), .of(u8), 0) catch return null;
- defer allocator.free(data);
- return parseRemembered(allocator, data);
+/// The result's strings live in `arena`.
+pub fn loadRemembered(gpa: std.mem.Allocator, arena: std.mem.Allocator) ?Remembered {
+ const data = std.Io.Dir.cwd().readFileAllocOptions(lp.io, remembered_path, gpa, .limited(1024), .of(u8), 0) catch return null;
+ defer gpa.free(data);
+ return parseRemembered(gpa, arena, data);
}
-fn parseRemembered(allocator: std.mem.Allocator, data: [:0]const u8) ?Remembered {
- // A real Diagnostics, not null: a type-check failure allocates an owned
- // error note that leaks unless a Diagnostics owns it to free on deinit.
- var diag: std.zon.parse.Diagnostics = .{};
- defer diag.deinit(allocator);
- const remembered = std.zon.parse.fromSliceAlloc(Remembered, allocator, data, &diag, .{}) catch return null;
+fn parseRemembered(gpa: std.mem.Allocator, arena: std.mem.Allocator, data: [:0]const u8) ?Remembered {
+ var diag: std.zon.parse.Diagnostics = undefined;
+ const remembered = std.zon.parse.fromSlice(Remembered, .{
+ .gpa = gpa,
+ .arena = arena,
+ .source = data,
+ .diagnostics = &diag,
+ }) catch return null;
// An empty model is corrupt only when a provider is set; a null provider
// (LLM disabled) legitimately has no model to remember.
- if (remembered.provider != null and remembered.model.len == 0) {
- std.zon.parse.free(allocator, remembered);
- return null;
- }
+ if (remembered.provider != null and remembered.model.len == 0) return null;
return remembered;
}
@@ -423,15 +423,16 @@ pub fn reconcileModel(
const testing = @import("../testing.zig");
-test "parseRemembered: invalid enum is rejected without leaking" {
- // A bad enum builds an owned error note; the leak detector fails here if
- // the Diagnostics doesn't free it.
- try testing.expect(parseRemembered(testing.allocator, ".{ .provider = .not_a_provider, .model = \"x\" }") == null);
+test "parseRemembered: invalid enum is rejected" {
+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);
+ defer arena.deinit();
+ try testing.expect(parseRemembered(testing.allocator, arena.allocator(), ".{ .provider = .not_a_provider, .model = \"x\" }") == null);
}
test "parseRemembered: valid file round-trips" {
- const remembered = parseRemembered(testing.allocator, ".{ .provider = null, .model = \"some-model\" }").?;
- defer std.zon.parse.free(testing.allocator, remembered);
+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);
+ defer arena.deinit();
+ const remembered = parseRemembered(testing.allocator, arena.allocator(), ".{ .provider = null, .model = \"some-model\" }").?;
try testing.expect(remembered.provider == null);
try testing.expectString("some-model", remembered.model);
// Absent `stream` is null so pre-streaming files still fall back to the default.
@@ -439,14 +440,16 @@ test "parseRemembered: valid file round-trips" {
}
test "parseRemembered: stream field round-trips" {
- const remembered = parseRemembered(testing.allocator, ".{ .model = \"m\", .stream = false }").?;
- defer std.zon.parse.free(testing.allocator, remembered);
+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);
+ defer arena.deinit();
+ const remembered = parseRemembered(testing.allocator, arena.allocator(), ".{ .model = \"m\", .stream = false }").?;
try testing.expect(remembered.stream == false);
}
test "parseRemembered: search_engine field round-trips" {
- const remembered = parseRemembered(testing.allocator, ".{ .model = \"m\", .search_engine = .brave }").?;
- defer std.zon.parse.free(testing.allocator, remembered);
+ var arena: std.heap.ArenaAllocator = .init(testing.allocator);
+ defer arena.deinit();
+ const remembered = parseRemembered(testing.allocator, arena.allocator(), ".{ .model = \"m\", .search_engine = .brave }").?;
try testing.expect(remembered.search_engine == .brave);
}
diff --git a/src/agent/welcome.zig b/src/agent/welcome.zig
index 517f045e5..27754d1cc 100644
--- a/src/agent/welcome.zig
+++ b/src/agent/welcome.zig
@@ -83,7 +83,7 @@ comptime {
/// hints beside it, vertically centered. `llm_active` picks the tagline.
pub fn print(llm_active: bool) void {
var version_buf: [192]u8 = undefined;
- const version: []const u8 = std.fmt.bufPrint(&version_buf, ansi.dim ++ "{s}" ++ ansi.reset, .{lp.build_config.version}) catch "";
+ const version: []const u8 = std.mem.print(&version_buf, ansi.dim ++ "{s}" ++ ansi.reset, .{lp.build_config.version}) catch "";
var lines: [9][]const u8 = undefined;
var n: usize = 0;
diff --git a/src/browser/EventManagerBase.zig b/src/browser/EventManagerBase.zig
index f15d26646..1e0ce977c 100644
--- a/src/browser/EventManagerBase.zig
+++ b/src/browser/EventManagerBase.zig
@@ -476,7 +476,7 @@ pub const Listener = struct {
};
},
.string => |string| {
- const str = try arena.dupeZ(u8, string.str());
+ const str = try arena.dupeSentinel(u8, string.str(), 0);
local.eval(str, null) catch |err| {
if (err == error.ExecutionTerminated) {
return error.ExecutionTerminated;
diff --git a/src/browser/Factory.zig b/src/browser/Factory.zig
index dd3280c8b..cedcc6eda 100644
--- a/src/browser/Factory.zig
+++ b/src/browser/Factory.zig
@@ -479,21 +479,14 @@ pub fn chained(self: *Factory, values: anytype) !*ChainedLeaf(@TypeOf(values)) {
}
pub fn chainedWithAllocator(allocator: Allocator, values: anytype) !*ChainedLeaf(@TypeOf(values)) {
- const fields = @typeInfo(@TypeOf(values)).@"struct".fields;
- const types = comptime blk: {
- var types: [fields.len]type = undefined;
- for (fields, 0..) |f, i| {
- types[i] = f.type;
- }
- break :blk types;
- };
+ const types = @typeInfo(@TypeOf(values)).@"struct".field_types;
comptime {
for (types[1..], 0..) |T, i| {
assert(reflect.Proto(T).? == types[i]);
}
}
- const chain = try PrototypeChain(&types).allocate(allocator);
+ const chain = try PrototypeChain(types).allocate(allocator);
inline for (0..types.len) |i| {
const ptr = chain.get(i);
ptr.* = values[i];
@@ -505,8 +498,8 @@ pub fn chainedWithAllocator(allocator: Allocator, values: anytype) !*ChainedLeaf
}
fn ChainedLeaf(comptime Values: type) type {
- const fields = @typeInfo(Values).@"struct".fields;
- return fields[fields.len - 1].type;
+ const field_types = @typeInfo(Values).@"struct".field_types;
+ return field_types[field_types.len - 1];
}
pub fn document(self: *Factory, child: anytype) !*@TypeOf(child) {
@@ -684,8 +677,8 @@ fn typeInit(comptime Parent: type, value: anytype) Parent.Type {
}
fn subtypeTag(comptime Parent: type, comptime V: type) Parent.Type {
- for (@typeInfo(Parent.Type).@"enum".fields) |f| {
- const tag: Parent.Type = @enumFromInt(f.value);
+ for (@typeInfo(Parent.Type).@"enum".field_values) |field_value| {
+ const tag: Parent.Type = @fromBackingInt(field_value);
if (Parent.Subtype(tag) == V) return tag;
}
@compileError(@typeName(V) ++ " is not a subtype of " ++ @typeName(Parent));
@@ -699,9 +692,9 @@ fn subtypeTag(comptime Parent: type, comptime V: type) Parent.Type {
// This only works because we never have a union with a field S and another
// field *S.
fn unionFieldName(comptime T: type, comptime V: type) []const u8 {
- inline for (@typeInfo(T).@"union".fields) |field| {
- if (reflect.Struct(field.type) == reflect.Struct(V)) {
- return field.name;
+ inline for (@typeInfo(T).@"union".field_names, @typeInfo(T).@"union".field_types) |field_name, field_type| {
+ if (reflect.Struct(field_type) == reflect.Struct(V)) {
+ return field_name;
}
}
@compileError(@typeName(V) ++ " is not a valid type for " ++ @typeName(T) ++ ".type");
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index 11d70286c..ea6073350 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -696,7 +696,7 @@ pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !vo
else if (is_srcdoc)
"about:srcdoc"
else
- try self.arena.dupeZ(u8, request_url);
+ try self.arena.dupeSentinel(u8, request_url, 0);
// even though about:blank navigations may share the same _data_, we
// have to do this to make sure window.location is at a unique _address_.
@@ -825,7 +825,7 @@ pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !vo
self.url = blk: {
if (URL.isCompleteHTTPUrl(request_url)) {
- break :blk try self.arena.dupeZ(u8, request_url);
+ break :blk try self.arena.dupeSentinel(u8, request_url, 0);
}
break :blk try std.mem.concatWithSentinel(self.arena, u8, &.{ "http://", request_url }, 0);
};
@@ -836,7 +836,7 @@ pub fn navigate(self: *Frame, request_url: [:0]const u8, opts: NavigateOpts) !vo
.reason = opts.reason,
.method = opts.method,
.body = if (opts.body) |b| try self.arena.dupe(u8, b) else null,
- .header = if (opts.header) |h| try self.arena.dupeZ(u8, h) else null,
+ .header = if (opts.header) |h| try self.arena.dupeSentinel(u8, h, 0) else null,
};
const transfer = try http_client.newRequest(.{
@@ -947,7 +947,7 @@ pub fn scheduleNavigation(self: *Frame, request_url: []const u8, opts: NavigateO
fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_url: []const u8, opts: NavigateOpts, nt: Navigation) !void {
const resolved_url, const is_about_something = blk: {
if (URL.isCompleteHTTPUrl(request_url)) {
- break :blk .{ try arena.dupeZ(u8, request_url), false };
+ break :blk .{ try arena.dupeSentinel(u8, request_url, 0), false };
}
if (std.mem.eql(u8, request_url, "about:blank")) {
@@ -1012,7 +1012,7 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_url
const is_fragment_navigation = !std.mem.eql(u8, target.url, resolved_url) and URL.eqlDocument(target.url, resolved_url);
if (!opts.force and is_fragment_navigation) {
const old_url = target.url;
- target.url = try target.arena.dupeZ(u8, resolved_url);
+ target.url = try target.arena.dupeSentinel(u8, resolved_url, 0);
const location = try Location.init(target.url, target);
location.acquireRef();
@@ -1061,7 +1061,7 @@ fn scheduleNavigationWithArena(originator: *Frame, arena: *lp.Arena, request_url
// that from its owner. Only a top-level navigation's initiator is another
// document.
if (nav_opts.initiator_url == null and target.parent == null and std.mem.startsWith(u8, referrer_source, "http")) {
- nav_opts.initiator_url = .{ .url = try arena.dupeZ(u8, referrer_source) };
+ nav_opts.initiator_url = .{ .url = try arena.dupeSentinel(u8, referrer_source, 0) };
}
if (nav_opts.initiator_origin == null) {
if (originator.origin) |o| {
@@ -1468,7 +1468,7 @@ fn frameHeaderDoneCallback(transfer: *HttpClient.Transfer) !HttpClient.Transfer.
const response_url = transfer.req.url;
if (std.mem.eql(u8, response_url, self.url) == false) {
// would be different than self.url in the case of a redirect
- self.url = try self.arena.dupeZ(u8, response_url);
+ self.url = try self.arena.dupeSentinel(u8, response_url, 0);
self.origin = try URL.getOrigin(self.arena, self.url);
}
@@ -3868,10 +3868,10 @@ pub fn submitForm(self: *Frame, submitter_: ?*Element, form_: ?*Element.Html.For
opts.body = buf.written();
opts.header = switch (encoding) {
.urlencode => "Content-Type: application/x-www-form-urlencoded",
- .formdata => |b| try std.fmt.allocPrintSentinel(arena.allocator(), "Content-Type: multipart/form-data; boundary={s}", .{b}, 0),
+ .formdata => |b| try arena.allocator().printSentinel("Content-Type: multipart/form-data; boundary={s}", .{b}, 0),
// Per WHATWG HTML §4.10.21.6, text/plain submissions include the form's
// resolved encoding (accept-charset or document charset).
- .plaintext => try std.fmt.allocPrintSentinel(arena.allocator(), "Content-Type: text/plain; charset={s}", .{charset}, 0),
+ .plaintext => try arena.allocator().printSentinel("Content-Type: text/plain; charset={s}", .{charset}, 0),
};
} else {
action = try URL.concatQueryString(arena.allocator(), action, buf.written());
diff --git a/src/browser/Mime.zig b/src/browser/Mime.zig
index 9ca9ae385..2300b803f 100644
--- a/src/browser/Mime.zig
+++ b/src/browser/Mime.zig
@@ -17,6 +17,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
const std = @import("std");
+const repeat = @import("../string.zig").repeat;
const Allocator = std.mem.Allocator;
const Mime = @This();
@@ -28,9 +29,15 @@ charset_len: usize = default_charset_len,
is_default_charset: bool = true,
/// String "UTF-8" continued by null characters.
-const default_charset = .{ 'U', 'T', 'F', '-', '8' } ++ .{0} ** 36;
+const default_charset = charsetBuf("UTF-8");
const default_charset_len = 5;
+fn charsetBuf(comptime name: []const u8) [41]u8 {
+ var buf: [41]u8 = @splat(0);
+ @memcpy(buf[0..name.len], name);
+ return buf;
+}
+
/// Mime with unknown Content-Type, empty params and empty charset.
pub const unknown = Mime{ .content_type = .{ .unknown = {} } };
@@ -376,7 +383,7 @@ pub fn sniff(body: []const u8) ?Mime {
// UTF-16 big-endian BOM
return .{
.content_type = .{ .text_plain = {} },
- .charset = .{ 'U', 'T', 'F', '-', '1', '6', 'B', 'E' } ++ .{0} ** 33,
+ .charset = comptime charsetBuf("UTF-16BE"),
.charset_len = 8,
.is_default_charset = false,
};
@@ -385,7 +392,7 @@ pub fn sniff(body: []const u8) ?Mime {
// UTF-16 little-endian BOM
return .{
.content_type = .{ .text_plain = {} },
- .charset = .{ 'U', 'T', 'F', '-', '1', '6', 'L', 'E' } ++ .{0} ** 33,
+ .charset = comptime charsetBuf("UTF-16LE"),
.charset_len = 8,
.is_default_charset = false,
};
@@ -1017,7 +1024,7 @@ test "Mime: parse charset (WHATWG parameter semantics)" {
try expect(.{ .content_type = .{ .text_html = {} }, .charset = "UTF-8" }, "text/html;charset =gbk");
// A long preceding parameter doesn't hide a later charset.
- try expect(.{ .content_type = .{ .text_html = {} }, .charset = "gbk" }, "text/html;" ++ ("a" ** 130) ++ "=x;charset=gbk");
+ try expect(.{ .content_type = .{ .text_html = {} }, .charset = "gbk" }, "text/html;" ++ (repeat("a", 130)) ++ "=x;charset=gbk");
}
test "Mime: isHTML" {
diff --git a/src/browser/Page.zig b/src/browser/Page.zig
index 63c165473..9e7f20d6c 100644
--- a/src/browser/Page.zig
+++ b/src/browser/Page.zig
@@ -406,7 +406,7 @@ pub fn createBlobUrl(self: *Page, blob: *Blob, origin: ?[]const u8, creator_fram
var uuid: [36]u8 = undefined;
@import("../id.zig").uuidv4(&uuid);
- const url = try std.fmt.allocPrint(self.frame_arena, "blob:{s}/{s}", .{ origin orelse "null", uuid });
+ const url = try self.frame_arena.print("blob:{s}/{s}", .{ origin orelse "null", uuid });
try self.blob_urls.put(self.frame_arena, url, .{ .blob = blob, .creator = creator_frame_id });
blob.acquireRef();
return url;
diff --git a/src/browser/ScriptManager.zig b/src/browser/ScriptManager.zig
index 824c7c2d4..a492cc730 100644
--- a/src/browser/ScriptManager.zig
+++ b/src/browser/ScriptManager.zig
@@ -141,7 +141,7 @@ pub fn preloadScript(self: *ScriptManager, element: ?*Element.Html, url: []const
const arena = try frame.getArena(.small, "SM.preloadScript");
errdefer arena.release();
- const owned_url = try arena.dupeZ(u8, url);
+ const owned_url = try arena.dupeSentinel(u8, url, 0);
const script = try arena.create(Script);
script.* = .{
diff --git a/src/browser/SelectorPath.zig b/src/browser/SelectorPath.zig
index c5713cd51..a8b8c75bd 100644
--- a/src/browser/SelectorPath.zig
+++ b/src/browser/SelectorPath.zig
@@ -63,7 +63,7 @@ fn buildGreedy(self: SelectorPath, target: *Element) !?[]const u8 {
var el = target.parentElement();
while (el) |ancestor| {
el = ancestor.parentElement();
- const trial = try std.fmt.allocPrint(self.arena, "{s} {s}", .{ try self.localSegment(ancestor), candidate });
+ const trial = try self.arena.print("{s} {s}", .{ try self.localSegment(ancestor), candidate });
const trial_count = self.matchCount(trial);
if (trial_count != 0 and trial_count < count) {
candidate = trial;
@@ -92,7 +92,7 @@ fn buildStrictPath(self: SelectorPath, target: *Element) !?[]const u8 {
fn localSegment(self: SelectorPath, el: *Element) ![]const u8 {
if (el.getId()) |id| {
if (id.len != 0) {
- const id_sel = try std.fmt.allocPrint(self.arena, "#{s}", .{try CSS.escape(id, self.frame)});
+ const id_sel = try self.arena.print("#{s}", .{try CSS.escape(id, self.frame)});
if (self.isFirstMatch(el, id_sel)) return id_sel;
}
}
@@ -101,7 +101,7 @@ fn localSegment(self: SelectorPath, el: *Element) ![]const u8 {
if (!self.siblingMatches(el, base)) return base;
if (try self.hasSegment(el, base)) |sel| return sel;
- if (nthOfType(el)) |n| return try std.fmt.allocPrint(self.arena, "{s}:nth-of-type({d})", .{ base, n });
+ if (nthOfType(el)) |n| return try self.arena.print("{s}:nth-of-type({d})", .{ base, n });
return base;
}
@@ -118,7 +118,7 @@ fn hasSegment(self: SelectorPath, el: *Element, base: []const u8) !?[]const u8 {
try self.enqueueChildren(&queue, d);
const desc = (try self.descriptor(d)) orelse continue;
- const candidate = try std.fmt.allocPrint(self.arena, "{s}:has({s})", .{ base, desc });
+ const candidate = try self.arena.print("{s}:has({s})", .{ base, desc });
if (self.isFirstMatch(el, candidate)) return candidate;
}
return null;
@@ -150,7 +150,7 @@ fn qualifyByAttrs(self: SelectorPath, base: []const u8, el: *Element, comptime a
inline for (attrs) |attr| {
if (el.getAttributeSafe(comptime .wrap(attr))) |value| {
if (value.len != 0 and isPlainAttrValue(value)) {
- sel = try std.fmt.allocPrint(self.arena, "{s}[{s}=\"{s}\"]", .{ sel, attr, value });
+ sel = try self.arena.print("{s}[{s}=\"{s}\"]", .{ sel, attr, value });
added = true;
}
}
diff --git a/src/browser/StyleManager.zig b/src/browser/StyleManager.zig
index 853a08c7a..834ba50b8 100644
--- a/src/browser/StyleManager.zig
+++ b/src/browser/StyleManager.zig
@@ -312,7 +312,7 @@ fn registerLayerPath(self: *StyleManager, build_arena: Allocator, parent: u16, d
fn internAnonymousLayer(self: *StyleManager, build_arena: Allocator, parent: u16) Allocator.Error!u16 {
const id = self.next_anon_layer;
// \x00{d} isn't a valid layer name, so this can't conflict
- const name = try std.fmt.allocPrint(build_arena, "\x00{d}", .{id});
+ const name = try build_arena.print("\x00{d}", .{id});
self.next_anon_layer = id + 1;
return self.internLayer(build_arena, parent, name);
}
@@ -321,7 +321,7 @@ fn internLayer(self: *StyleManager, build_arena: Allocator, parent: u16, name: [
const path = if (parent == NO_LAYER)
try build_arena.dupe(u8, name)
else
- try std.fmt.allocPrint(build_arena, "{s}.{s}", .{ self.layers.items[parent].path, name });
+ try build_arena.print("{s}.{s}", .{ self.layers.items[parent].path, name });
const gop = try self.layer_ids.getOrPut(build_arena, path);
if (gop.found_existing) {
@@ -738,7 +738,7 @@ fn Group(comptime Spec: type) type {
const Declared = Spec.Declared;
const Computed = Spec.Computed;
const Field = std.meta.FieldEnum(Declared);
- const fields = std.meta.fieldNames(Declared);
+ const fields = @typeInfo(Declared).@"struct".field_names;
comptime {
// compute copies each declared value into its Computed namesake
@@ -1026,7 +1026,7 @@ pub fn ruleInserted(self: *StyleManager, sheet: *CSSStyleSheet, rule: *CSSRule)
fn appendable(self: *const StyleManager, sheet: *CSSStyleSheet, rule: *CSSRule) bool {
const rules = sheet._css_rules orelse return false;
- if (rules._rules.getLastOrNull() != rule) {
+ if (rules._rules.last() != rule) {
return false;
}
const sheets = self.frame.document._style_sheets orelse return false;
@@ -1282,7 +1282,7 @@ const Visibility = struct {
// element — per CSS Cascade §6.1 any normal-origin author rule beats UA
// origin regardless of specificity, so `.x { display: flex }` on a
// `<div class="x" hidden>` must report visible.
- fn finish(p: *Computed, el: *Element, priorities: *const Priorities(Declared)) void {
+ pub fn finish(p: *Computed, el: *Element, priorities: *const Priorities(Declared)) void {
p.author_display = priorities.get(.display) != 0;
if (!p.author_display and matchesUaDisplayNoneRule(el)) {
p.display = .none;
@@ -1367,10 +1367,10 @@ const Declarations = struct {
}
};
-const group_fields = std.meta.fieldNames(Declarations);
+const group_fields = @typeInfo(Declarations).@"struct".field_names;
fn declaresAny(declared: anytype) bool {
- inline for (comptime std.meta.fieldNames(@TypeOf(declared))) |field| {
+ inline for (@typeInfo(@TypeOf(declared)).@"struct".field_names) |field| {
if (@field(declared, field) != null) {
return true;
}
diff --git a/src/browser/URL.zig b/src/browser/URL.zig
index de07480be..72f85d1bb 100644
--- a/src/browser/URL.zig
+++ b/src/browser/URL.zig
@@ -47,7 +47,7 @@ pub fn resolve(
}
defer href.deinit();
- return allocator.dupeZ(u8, href.slice());
+ return allocator.dupeSentinel(u8, href.slice(), 0);
}
/// Resolves a user-provided "address bar" URL the way curl does. Bare host like
@@ -55,7 +55,7 @@ pub fn resolve(
pub fn resolveNavigation(allocator: Allocator, url: []const u8, options: ResolveOptions) ![:0]const u8 {
return resolve(allocator, "", url, options) catch |err| switch (err) {
error.TypeError => {
- const with_scheme = try std.fmt.allocPrintSentinel(allocator, "http://{s}", .{url}, 0);
+ const with_scheme = try allocator.printSentinel("http://{s}", .{url}, 0);
return resolve(allocator, "", with_scheme, options);
},
else => return err,
@@ -241,7 +241,7 @@ pub fn isLoopbackHost(hostname: []const u8) bool {
const address = std.Io.net.IpAddress.parseLiteral(host) catch return false;
return switch (address) {
.ip4 => |ip4| ip4.bytes[0] == 127,
- .ip6 => |ip6| std.mem.eql(u8, &ip6.bytes, &([_]u8{0} ** 15 ++ [_]u8{1})),
+ .ip6 => |ip6| std.mem.eql(u8, &ip6.bytes, &(@as([15]u8, @splat(0)) ++ [_]u8{1})),
};
}
@@ -332,7 +332,7 @@ pub fn getOrigin(allocator: Allocator, raw: [:0]const u8) !?[]const u8 {
// Not a port (probably IPv6)
if (has_user_info) {
// Need to allocate to exclude user info
- return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ raw[0 .. scheme_end + 1], host_part });
+ return try allocator.print("{s}//{s}", .{ raw[0 .. scheme_end + 1], host_part });
}
// Can return a slice
return raw[0..authority_end];
@@ -348,14 +348,14 @@ pub fn getOrigin(allocator: Allocator, raw: [:0]const u8) !?[]const u8 {
// Need to allocate to build origin without default port and/or user info
const hostname = host_part[0..colon_pos_in_host];
if (is_default) {
- return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ protocol, hostname });
+ return try allocator.print("{s}//{s}", .{ protocol, hostname });
} else {
- return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ protocol, host_part });
+ return try allocator.print("{s}//{s}", .{ protocol, host_part });
}
}
} else if (has_user_info) {
// No port, but has user info - need to allocate
- return try std.fmt.allocPrint(allocator, "{s}//{s}", .{ raw[0 .. scheme_end + 1], host_part });
+ return try allocator.print("{s}//{s}", .{ raw[0 .. scheme_end + 1], host_part });
}
// Common case: no user info, no default port - return slice (zero allocation!)
@@ -409,7 +409,7 @@ fn buildUrl(
search: []const u8,
hash: []const u8,
) ![:0]const u8 {
- return std.fmt.allocPrintSentinel(allocator, "{s}//{s}{s}{s}{s}", .{
+ return allocator.printSentinel("{s}//{s}{s}{s}{s}", .{
protocol,
host,
pathname,
@@ -426,7 +426,7 @@ pub fn setProtocol(current: [:0]const u8, value: []const u8, allocator: Allocato
// Add : suffix if not present
const protocol = if (value.len > 0 and value[value.len - 1] != ':')
- try std.fmt.allocPrint(allocator, "{s}:", .{value})
+ try allocator.print("{s}:", .{value})
else
value;
@@ -455,7 +455,7 @@ pub fn setHost(current: [:0]const u8, value: []const u8, allocator: Allocator) !
// No port in new value - preserve existing port
const current_port = getPort(current);
if (current_port.len > 0) {
- break :blk try std.fmt.allocPrint(allocator, "{s}:{s}", .{ value, current_port });
+ break :blk try allocator.print("{s}:{s}", .{ value, current_port });
}
break :blk value;
};
@@ -466,7 +466,7 @@ pub fn setHost(current: [:0]const u8, value: []const u8, allocator: Allocator) !
pub fn setHostname(current: [:0]const u8, value: []const u8, allocator: Allocator) ![:0]const u8 {
const current_port = getPort(current);
const new_host = if (current_port.len > 0)
- try std.fmt.allocPrint(allocator, "{s}:{s}", .{ value, current_port })
+ try allocator.print("{s}:{s}", .{ value, current_port })
else
value;
@@ -492,7 +492,7 @@ pub fn setPort(current: [:0]const u8, value: ?[]const u8, allocator: Allocator)
if (std.mem.eql(u8, protocol, "http:") and std.mem.eql(u8, port_str, "80")) {
break :blk hostname;
}
- break :blk try std.fmt.allocPrint(allocator, "{s}:{s}", .{ hostname, port_str });
+ break :blk try allocator.print("{s}:{s}", .{ hostname, port_str });
} else hostname;
return buildUrl(allocator, protocol, new_host, pathname, search, hash);
@@ -508,7 +508,7 @@ pub fn setPathname(current: [:0]const u8, value: []const u8, allocator: Allocato
// Add / prefix if not present and value is not empty
const pathname = if (encoded.len > 0 and encoded[0] != '/')
- try std.fmt.allocPrint(allocator, "/{s}", .{encoded})
+ try allocator.print("/{s}", .{encoded})
else
encoded;
@@ -525,7 +525,7 @@ pub fn setSearch(current: [:0]const u8, value: []const u8, allocator: Allocator)
// Add ? prefix if not present and value is not empty
const search = if (encoded.len > 0 and value[0] != '?')
- try std.fmt.allocPrint(allocator, "?{s}", .{encoded})
+ try allocator.print("?{s}", .{encoded})
else
encoded;
@@ -542,7 +542,7 @@ pub fn setHash(current: [:0]const u8, value: []const u8, allocator: Allocator) !
// Add # prefix if not present and value is not empty
const hash = if (encoded.len > 0 and encoded[0] != '#')
- try std.fmt.allocPrint(allocator, "#{s}", .{encoded})
+ try allocator.print("#{s}", .{encoded})
else
encoded;
@@ -586,7 +586,7 @@ fn buildUrlWithUserInfo(
if (username.len == 0 and password.len == 0) {
return buildUrl(allocator, protocol, host, pathname, search, hash);
} else if (password.len == 0) {
- return std.fmt.allocPrintSentinel(allocator, "{s}//{s}@{s}{s}{s}{s}", .{
+ return allocator.printSentinel("{s}//{s}@{s}{s}{s}{s}", .{
protocol,
username,
host,
@@ -595,7 +595,7 @@ fn buildUrlWithUserInfo(
hash,
}, 0);
} else {
- return std.fmt.allocPrintSentinel(allocator, "{s}//{s}:{s}@{s}{s}{s}{s}", .{
+ return allocator.printSentinel("{s}//{s}:{s}@{s}{s}{s}{s}", .{
protocol,
username,
password,
@@ -609,7 +609,7 @@ fn buildUrlWithUserInfo(
pub fn concatQueryString(arena: Allocator, url: []const u8, query_string: []const u8) ![:0]const u8 {
if (query_string.len == 0) {
- return arena.dupeZ(u8, url);
+ return arena.dupeSentinel(u8, url, 0);
}
var buf: std.ArrayList(u8) = .empty;
@@ -633,8 +633,7 @@ pub fn concatQueryString(arena: Allocator, url: []const u8, query_string: []cons
pub fn getRobotsUrl(arena: Allocator, url: [:0]const u8) ![:0]const u8 {
const origin = try getOrigin(arena, url) orelse return error.NoOrigin;
- return try std.fmt.allocPrintSentinel(
- arena,
+ return try arena.printSentinel(
"{s}/robots.txt",
.{origin},
0,
diff --git a/src/browser/clutter.zig b/src/browser/clutter.zig
index 5c64fb482..d77280ed1 100644
--- a/src/browser/clutter.zig
+++ b/src/browser/clutter.zig
@@ -102,7 +102,7 @@ fn describe(node: *Node) []const u8 {
const S = struct {
threadlocal var buf: [96]u8 = undefined;
};
- return std.fmt.bufPrint(&S.buf, "{s}.{s}#{s}", .{ @tagName(el.getTag()), el.getClassName() orelse "", el.getId() orelse "" }) catch S.buf[0..];
+ return std.mem.print(&S.buf, "{s}.{s}#{s}", .{ @tagName(el.getTag()), el.getClassName() orelse "", el.getId() orelse "" }) catch S.buf[0..];
}
const Stats = struct {
diff --git a/src/browser/data_url.zig b/src/browser/data_url.zig
index fce62bb8f..49496aa90 100644
--- a/src/browser/data_url.zig
+++ b/src/browser/data_url.zig
@@ -55,7 +55,7 @@ pub fn parse(arena: Allocator, url: []const u8) !Parsed {
content_type = "text/plain;charset=US-ASCII";
} else if (content_type[0] == ';') {
// e.g. "data:;charset=utf-8,x" -> "text/plain;charset=utf-8"
- content_type = try std.fmt.allocPrint(arena, "text/plain{s}", .{content_type});
+ content_type = try arena.print("text/plain{s}", .{content_type});
}
const body_text = try URL.unescape(arena, encoded_body);
diff --git a/src/browser/frame/framing.zig b/src/browser/frame/framing.zig
index f06b6bc6a..eb9486cd7 100644
--- a/src/browser/frame/framing.zig
+++ b/src/browser/frame/framing.zig
@@ -57,7 +57,7 @@ pub fn allowed(frame: *const Frame, transfer: *HttpClient.Transfer) bool {
fn hasFrameAncestors(csp: []const u8) bool {
const name = "frame-ancestors";
var pos: usize = 0;
- while (std.ascii.indexOfIgnoreCasePos(csp, pos, name)) |start| {
+ while (std.ascii.findIgnoreCasePos(csp, pos, name)) |start| {
pos = start + name.len;
// A directive name starts a policy (',') or a directive (';'), so
diff --git a/src/browser/frame/node_factory.zig b/src/browser/frame/node_factory.zig
index 41cf0dfab..09a29f84a 100644
--- a/src/browser/frame/node_factory.zig
+++ b/src/browser/frame/node_factory.zig
@@ -1156,7 +1156,7 @@ fn parserAttributeName(frame: *Frame, qname: Parser.QualName) ![]const u8 {
if (prefix.len == 0) {
return local;
}
- return std.fmt.allocPrint(frame.local_arena, "{s}:{s}", .{ prefix, local });
+ return frame.local_arena.print("{s}:{s}", .{ prefix, local });
}
// Called when `new MyElement()` is invoked directly in JS (not via the
@@ -1300,7 +1300,7 @@ fn isXmlNameChar(c: u21) bool {
(c >= 0x203F and c <= 0x2040);
}
-fn asUint(comptime string: anytype) std.meta.Int(
+fn asUint(comptime string: anytype) @Int(
.unsigned,
@bitSizeOf(@TypeOf(string.*)) - 8, // (- 8) to exclude sentinel 0
) {
diff --git a/src/browser/image_dimensions.zig b/src/browser/image_dimensions.zig
index d8ec40c7c..33ea60817 100644
--- a/src/browser/image_dimensions.zig
+++ b/src/browser/image_dimensions.zig
@@ -113,7 +113,7 @@ fn exifOrientation(segment: []const u8) u16 {
}
const tiff = segment[6..];
- const endian: std.builtin.Endian = if (std.mem.eql(u8, tiff[0..2], "II"))
+ const endian: std.lang.Endian = if (std.mem.eql(u8, tiff[0..2], "II"))
.little
else if (std.mem.eql(u8, tiff[0..2], "MM"))
.big
diff --git a/src/browser/interactive.zig b/src/browser/interactive.zig
index c6f4e219f..aeb24bd41 100644
--- a/src/browser/interactive.zig
+++ b/src/browser/interactive.zig
@@ -238,7 +238,7 @@ fn walkInteractive(
if (filter.name) |nf| {
const n = name orelse continue;
const hit = switch (nf) {
- .substring => |s| std.ascii.indexOfIgnoreCase(n, s) != null,
+ .substring => |s| std.ascii.findIgnoreCase(n, s) != null,
.regex => |re| re.matches(n),
};
if (!hit) continue;
diff --git a/src/browser/js/Caller.zig b/src/browser/js/Caller.zig
index 7cf091dc3..82c937d6f 100644
--- a/src/browser/js/Caller.zig
+++ b/src/browser/js/Caller.zig
@@ -105,7 +105,7 @@ pub fn deinit(self: *Caller) void {
// Unlike call_arena, local_arena is reset on _every_ return, since its
// users promise not to hold data across a nested call. In debug, free
// back to the backing allocator so a stale pointer trips the
- // DebugAllocator's use-after-free detection; in release, retain a buffer
+ // SafeAllocator's use-after-free detection; in release, retain a buffer
// to avoid realloc churn.
{
const local_arena: *ArenaAllocator = @ptrCast(@alignCast(ctx.local_arena.ptr));
@@ -202,7 +202,7 @@ fn _getIndex(comptime T: type, local: *const Local, func: anytype, idx: u32, inf
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = idx;
- if (@typeInfo(F).@"fn".params.len == 3) {
+ if (@typeInfo(F).@"fn".param_types.len == 3) {
@field(args, "2") = getGlobalArg(@TypeOf(args.@"2"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -228,7 +228,7 @@ fn _getNamedIndex(comptime T: type, local: *const Local, func: anytype, name: *c
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
- if (@typeInfo(F).@"fn".params.len == 3) {
+ if (@typeInfo(F).@"fn".param_types.len == 3) {
@field(args, "2") = getGlobalArg(@TypeOf(args.@"2"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -255,7 +255,7 @@ fn _setIndex(comptime T: type, local: *const Local, func: anytype, idx: u32, js_
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = idx;
@field(args, "2") = try local.jsValueToZig(@TypeOf(@field(args, "2")), js_value);
- if (@typeInfo(F).@"fn".params.len == 4) {
+ if (@typeInfo(F).@"fn".param_types.len == 4) {
@field(args, "3") = getGlobalArg(@TypeOf(args.@"3"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -281,7 +281,7 @@ fn _deleteOrDefineIndex(comptime T: type, local: *const Local, func: anytype, id
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = idx;
- if (@typeInfo(F).@"fn".params.len == 3) {
+ if (@typeInfo(F).@"fn".param_types.len == 3) {
@field(args, "2") = getGlobalArg(@TypeOf(args.@"2"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -308,7 +308,7 @@ fn _setNamedIndex(comptime T: type, local: *const Local, func: anytype, name: *c
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
@field(args, "2") = try local.jsValueToZig(@TypeOf(@field(args, "2")), js_value);
- if (@typeInfo(F).@"fn".params.len == 4) {
+ if (@typeInfo(F).@"fn".param_types.len == 4) {
@field(args, "3") = getGlobalArg(@TypeOf(args.@"3"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -334,7 +334,7 @@ fn _deleteOrDefineNamedIndex(comptime T: type, local: *const Local, func: anytyp
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
- if (@typeInfo(F).@"fn".params.len == 3) {
+ if (@typeInfo(F).@"fn".param_types.len == 3) {
@field(args, "2") = getGlobalArg(@TypeOf(args.@"2"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -359,7 +359,7 @@ fn _getEnumerator(comptime T: type, local: *const Local, func: anytype, info: Pr
const F = @TypeOf(func);
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
- if (@typeInfo(F).@"fn".params.len == 2) {
+ if (@typeInfo(F).@"fn".param_types.len == 2) {
@field(args, "1") = getGlobalArg(@TypeOf(args.@"1"), local.ctx);
}
const ret = @call(.auto, func, args);
@@ -385,7 +385,7 @@ fn _getIndexQuery(comptime T: type, local: *const Local, func: anytype, idx: u32
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = idx;
- if (@typeInfo(F).@"fn".params.len == 3) {
+ if (@typeInfo(F).@"fn".param_types.len == 3) {
@field(args, "2") = getGlobalArg(@TypeOf(args.@"2"), local.ctx);
}
return queryReturn(local, @call(.auto, func, args), info);
@@ -410,7 +410,7 @@ fn _getNamedQuery(comptime T: type, local: *const Local, func: anytype, name: *c
var args: ParameterTypes(F) = undefined;
@field(args, "0") = try TaggedOpaque.fromJS(*T, info.getThis());
@field(args, "1") = try nameToString(local, @TypeOf(args.@"1"), name);
- if (@typeInfo(F).@"fn".params.len == 3) {
+ if (@typeInfo(F).@"fn".param_types.len == 3) {
@field(args, "2") = getGlobalArg(@TypeOf(args.@"2"), local.ctx);
}
return queryReturn(local, @call(.auto, func, args), info);
@@ -483,8 +483,8 @@ fn returnsBool(comptime F: type) bool {
}
fn isInErrorSet(err: anyerror, comptime T: type) bool {
- inline for (@typeInfo(T).error_set.?) |e| {
- if (err == @field(anyerror, e.name)) return true;
+ inline for (@typeInfo(T).error_set.error_names.?) |name| {
+ if (err == @field(anyerror, name)) return true;
}
return false;
}
@@ -666,11 +666,11 @@ fn serializeFunctionArgs(local: *const Local, info: FunctionCallbackInfo) ![]con
// Takes a function, and returns a tuple for its argument. Used when we
// @call a function
fn ParameterTypes(comptime F: type) type {
- const params = @typeInfo(F).@"fn".params;
- var types: [params.len]type = undefined;
+ const param_types = @typeInfo(F).@"fn".param_types;
+ var types: [param_types.len]type = undefined;
- inline for (params, 0..) |param, i| {
- types[i] = param.type.?;
+ inline for (param_types, 0..) |param_type, i| {
+ types[i] = param_type.?;
}
return @Tuple(&types);
@@ -1018,7 +1018,7 @@ pub const Function = struct {
fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info: FunctionCallbackInfo) !ParameterTypes(F) {
var args: ParameterTypes(F) = undefined;
- const params = @typeInfo(F).@"fn".params[offset..];
+ const params = @typeInfo(F).@"fn".param_types[offset..];
// Except for the constructor, the first parameter is always `self`
// This isn't something we'll bind from JS, so skip it.
const params_to_map = blk: {
@@ -1029,7 +1029,7 @@ fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info:
// If the last parameter is Frame/Page/Execution, set it from
// context and exclude it from our params slice, because we don't want
// to bind it to a JS argument.
- const LastParamType = params[params.len - 1].type.?;
+ const LastParamType = params[params.len - 1].?;
if (comptime isFrame(LastParamType) or isPage(LastParamType) or isExecution(LastParamType)) {
@field(args, tupleFieldName(params.len - 1 + offset)) = getGlobalArg(LastParamType, local.ctx);
break :blk params[0 .. params.len - 1];
@@ -1053,7 +1053,7 @@ fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info:
// is a slice AND the corresponding javascript parameter is
// NOT an an array, then we'll treat it as a variadic.
- const last_parameter_type = params_to_map[params_to_map.len - 1].type.?;
+ const last_parameter_type = params_to_map[params_to_map.len - 1].?;
const last_parameter_type_info = @typeInfo(last_parameter_type);
if (last_parameter_type_info == .pointer and last_parameter_type_info.pointer.size == .slice) {
const slice_type = last_parameter_type_info.pointer.child;
@@ -1075,7 +1075,7 @@ fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info:
}
}
- inline for (params_to_map, 0..) |param, i| {
+ inline for (params_to_map, 0..) |param_type, i| {
const field_index = comptime i + offset;
if (comptime i == params_to_map.len - 1) {
if (is_variadic) {
@@ -1083,14 +1083,14 @@ fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info:
}
}
- if (comptime isFrame(param.type.?)) {
+ if (comptime isFrame(param_type.?)) {
@compileError("Frame must be the last parameter: " ++ @typeName(F));
- } else if (comptime isPage(param.type.?)) {
+ } else if (comptime isPage(param_type.?)) {
@compileError("Page must be the last parameter: " ++ @typeName(F));
- } else if (comptime isExecution(param.type.?)) {
+ } else if (comptime isExecution(param_type.?)) {
@compileError("Execution must be the last parameter: " ++ @typeName(F));
} else if (i >= js_parameter_count) {
- if (@typeInfo(param.type.?) != .optional) {
+ if (@typeInfo(param_type.?) != .optional) {
return error.InvalidArgument;
}
@field(args, tupleFieldName(field_index)) = null;
@@ -1102,7 +1102,7 @@ fn getArgs(comptime F: type, comptime offset: usize, local: *const Local, info:
// to the right DOMException. Compared by name because the per-
// type instantiation of jsValueToZig may not include such errors
// in its inferred error set.
- @field(args, tupleFieldName(field_index)) = local.jsValueToZig(param.type.?, js_val) catch |err| {
+ @field(args, tupleFieldName(field_index)) = local.jsValueToZig(param_type.?, js_val) catch |err| {
if (err == error.JsException) {
// an exception thrown by user code (e.g. a toString
// getter) is pending; propagate it untouched
diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zig
index 6609b4413..2b496293c 100644
--- a/src/browser/js/Context.zig
+++ b/src/browser/js/Context.zig
@@ -367,7 +367,7 @@ pub fn module(self: *Context, comptime want_result: bool, local: *const js.Local
}
}
- const owned_url = try arena.dupeZ(u8, url);
+ const owned_url = try arena.dupeSentinel(u8, url, 0);
if (cacheable and !gop.found_existing) {
gop.key_ptr.* = owned_url;
}
@@ -529,7 +529,7 @@ fn postCompileModule(self: *Context, mod: js.Module, url: [:0]const u8, local: *
};
const nested_gop = try self.module_cache.getOrPut(self.arena.allocator(), normalized_specifier);
if (!nested_gop.found_existing) {
- const owned_specifier = try self.arena.dupeZ(u8, normalized_specifier);
+ const owned_specifier = try self.arena.dupeSentinel(u8, normalized_specifier, 0);
nested_gop.key_ptr.* = owned_specifier;
nested_gop.value_ptr.* = .{};
try script_manager.preloadImport(owned_specifier, url, .{});
@@ -537,7 +537,7 @@ fn postCompileModule(self: *Context, mod: js.Module, url: [:0]const u8, local: *
// Entry exists but module failed to compile previously.
// The imported_modules entry may have been consumed, so
// re-preload to ensure waitForImport can find it.
- // Key was stored via dupeZ so it has a sentinel in memory.
+ // Key was stored via dupeSentinel so it has a sentinel in memory.
const key = nested_gop.key_ptr.*;
const key_z: [:0]const u8 = key.ptr[0..key.len :0];
try script_manager.preloadImport(key_z, url, .{});
diff --git a/src/browser/js/Function.zig b/src/browser/js/Function.zig
index 4d08c5524..ccef13de5 100644
--- a/src/browser/js/Function.zig
+++ b/src/browser/js/Function.zig
@@ -196,12 +196,12 @@ fn _tryCallWithThis(self: *const Function, comptime T: type, this: anytype, args
const js_args: []const *const v8.Value = switch (@typeInfo(@TypeOf(aargs))) {
.@"struct" => |s| blk: {
- const fields = s.fields;
- var js_args: [fields.len]*const v8.Value = undefined;
- inline for (fields, 0..) |f, i| {
- js_args[i] = (try local.zigValueToJs(@field(aargs, f.name), .{})).handle;
+ const field_names = s.field_names;
+ var js_args: [field_names.len]*const v8.Value = undefined;
+ inline for (field_names, 0..) |field_name, i| {
+ js_args[i] = (try local.zigValueToJs(@field(aargs, field_name), .{})).handle;
}
- const cargs: [fields.len]*const v8.Value = js_args;
+ const cargs: [field_names.len]*const v8.Value = js_args;
break :blk &cargs;
},
.pointer => blk: {
diff --git a/src/browser/js/Isolate.zig b/src/browser/js/Isolate.zig
index 53809d5d4..6324429c5 100644
--- a/src/browser/js/Isolate.zig
+++ b/src/browser/js/Isolate.zig
@@ -48,7 +48,7 @@ pub const MemoryPressureLevel = enum(u32) {
};
pub fn memoryPressureNotification(self: Isolate, level: MemoryPressureLevel) void {
- v8.v8__Isolate__MemoryPressureNotification(self.handle, @intFromEnum(level));
+ v8.v8__Isolate__MemoryPressureNotification(self.handle, @backingInt(level));
}
// Tells V8 how much native memory is hanging off objects in this isolate, so
diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zig
index fee409ad0..470895b59 100644
--- a/src/browser/js/Local.zig
+++ b/src/browser/js/Local.zig
@@ -496,9 +496,9 @@ pub fn zigValueToJs(self: *const Local, value: anytype, comptime opts: CallOpts)
if (s.is_tuple) {
// return the tuple struct as an array
- var js_arr = self.newArray(@intCast(s.fields.len));
- inline for (s.fields, 0..) |f, i| {
- if (try js_arr.set(@intCast(i), @field(value, f.name), opts) == false) {
+ var js_arr = self.newArray(@intCast(s.field_names.len));
+ inline for (s.field_names, 0..) |field_name, i| {
+ if (try js_arr.set(@intCast(i), @field(value, field_name), opts) == false) {
return error.FailedToCreateArray;
}
}
@@ -506,8 +506,8 @@ pub fn zigValueToJs(self: *const Local, value: anytype, comptime opts: CallOpts)
}
const js_obj = self.newObject();
- inline for (s.fields) |f| {
- if (try js_obj.set(f.name, @field(value, f.name), opts) == false) {
+ inline for (s.field_names) |field_name| {
+ if (try js_obj.set(field_name, @field(value, field_name), opts) == false) {
return error.CreateObjectFailure;
}
}
@@ -518,9 +518,9 @@ pub fn zigValueToJs(self: *const Local, value: anytype, comptime opts: CallOpts)
return self.zigJsonToJs(value);
}
if (un.tag_type) |UnionTagType| {
- inline for (un.fields) |field| {
- if (value == @field(UnionTagType, field.name)) {
- return self.zigValueToJs(@field(value, field.name), opts);
+ inline for (un.field_names) |field_name| {
+ if (value == @field(UnionTagType, field_name)) {
+ return self.zigValueToJs(@field(value, field_name), opts);
}
}
unreachable;
@@ -695,13 +695,13 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
// compatible with. A compatible field has higher precedence
// than a coercible, but still isn't a perfect match.
var compatible_index: ?usize = null;
- inline for (u.fields, 0..) |field, i| {
- switch (try self.probeJsValueToZig(field.type, js_val)) {
- .value => |v| return @unionInit(T, field.name, v),
+ inline for (u.field_names, u.field_types, 0..) |field_name, field_type, i| {
+ switch (try self.probeJsValueToZig(field_type, js_val)) {
+ .value => |v| return @unionInit(T, field_name, v),
.ok => {
// a perfect match like above case, except the probing
// didn't get the value for us.
- return @unionInit(T, field.name, try self.jsValueToZig(field.type, js_val));
+ return @unionInit(T, field_name, try self.jsValueToZig(field_type, js_val));
},
.coerce => if (coerce_index == null) {
coerce_index = i;
@@ -715,9 +715,9 @@ pub fn jsValueToZig(self: *const Local, comptime T: type, js_val: js.Value) !T {
// We didn't find a perfect match.
const closest = compatible_index orelse coerce_index orelse return error.InvalidArgument;
- inline for (u.fields, 0..) |field, i| {
+ inline for (u.field_names, u.field_types, 0..) |field_name, field_type, i| {
if (i == closest) {
- return @unionInit(T, field.name, try self.jsValueToZig(field.type, js_val));
+ return @unionInit(T, field_name, try self.jsValueToZig(field_type, js_val));
}
}
unreachable;
@@ -767,7 +767,7 @@ fn jsValueToStruct(self: *const Local, comptime T: type, js_val: js.Value) !?T {
js.TypedArray(f32), js.TypedArray(f64),
// zig fmt: on
=> {
- const ValueType = @typeInfo(std.meta.fieldInfo(T, .values).type).pointer.child;
+ const ValueType = @typeInfo(@FieldType(T, "values")).pointer.child;
const arr = (try jsValueToTypedArray(ValueType, js_val)) orelse return null;
return .{ .values = arr };
},
@@ -846,27 +846,27 @@ fn jsValueToStruct(self: *const Local, comptime T: type, js_val: js.Value) !?T {
const js_obj = js_val.toObject();
var value: T = undefined;
- inline for (@typeInfo(T).@"struct".fields) |field| {
- if (comptime std.mem.eql(u8, field.name, dictionary_group_marker)) {
+ const info = @typeInfo(T).@"struct";
+ inline for (info.field_names, info.field_types, info.field_attrs) |name, FieldType, attrs| {
+ if (comptime std.mem.eql(u8, name, dictionary_group_marker)) {
continue;
}
- const name = field.name;
const key = isolate.initStringHandle(name);
if (js_obj.has(key)) {
const member = try js_obj.get(key);
- const default_for_undefined = comptime field.defaultValue();
+ const default_for_undefined = comptime attrs.defaultValue(FieldType);
@field(value, name) = blk: {
if (comptime default_for_undefined) |dflt| {
if (member.isUndefined()) {
break :blk dflt;
}
}
- break :blk try self.jsValueToZig(field.type, member);
+ break :blk try self.jsValueToZig(FieldType, member);
};
- } else if (@typeInfo(field.type) == .optional) {
+ } else if (@typeInfo(FieldType) == .optional) {
@field(value, name) = null;
} else {
- const dflt = field.defaultValue() orelse return null;
+ const dflt = attrs.defaultValue(FieldType) orelse return null;
@field(value, name) = dflt;
}
}
@@ -883,10 +883,10 @@ pub const dictionary_group_marker = "js_grouped_dictionary";
// fire in a predictable order. Could probably comptime this to work
// automatically, but it's a lot easier just to check it and ask for a manual fix.
pub fn assertDictionaryFieldOrder(comptime T: type) void {
- const fields = @typeInfo(T).@"struct".fields;
+ const field_names = @typeInfo(T).@"struct".field_names;
var i: usize = 1;
- while (i < fields.len) : (i += 1) {
- if (std.mem.order(u8, fields[i - 1].name, fields[i].name) == .gt) {
+ while (i < field_names.len) : (i += 1) {
+ if (std.mem.order(u8, field_names[i - 1], field_names[i]) == .gt) {
@compileError("dictionary fields must be declared in lexicographic order: " ++ @typeName(T));
}
}
@@ -1350,17 +1350,17 @@ fn resolveValue(value: anytype) Resolved {
}
const U = @typeInfo(@TypeOf(value._type)).@"union";
- inline for (U.fields) |field| {
- if (value._type == @field(U.tag_type.?, field.name)) {
- const child = switch (@typeInfo(field.type)) {
- .pointer => @field(value._type, field.name),
- .@"struct" => &@field(value._type, field.name),
+ inline for (U.field_names, U.field_types) |field_name, field_type| {
+ if (value._type == @field(U.tag_type.?, field_name)) {
+ const child = switch (@typeInfo(field_type)) {
+ .pointer => @field(value._type, field_name),
+ .@"struct" => &@field(value._type, field_name),
.void => {
// Unusual case, but the Event (and maybe others) can be
// returned as-is. In that case, it has a dummy void type.
return resolveT(T, value);
},
- else => @compileError(@typeName(field.type) ++ " has an unsupported _type field"),
+ else => @compileError(@typeName(field_type) ++ " has an unsupported _type field"),
};
return resolveValue(child);
}
@@ -1573,8 +1573,8 @@ pub fn ToLocalReturnType(comptime T: type) type {
if (@typeInfo(T) == .optional) {
const GlobalType = @typeInfo(T).optional.child;
const struct_info = @typeInfo(GlobalType).@"struct";
- inline for (struct_info.decls) |decl| {
- if (std.mem.eql(u8, decl.name, "local")) {
+ inline for (struct_info.decl_names) |decl_name| {
+ if (std.mem.eql(u8, decl_name, "local")) {
const Fn = @TypeOf(@field(GlobalType, "local"));
const fn_info = @typeInfo(Fn).@"fn";
return ?fn_info.return_type.?;
@@ -1583,8 +1583,8 @@ pub fn ToLocalReturnType(comptime T: type) type {
@compileError("Type does not have local method");
} else {
const struct_info = @typeInfo(T).@"struct";
- inline for (struct_info.decls) |decl| {
- if (std.mem.eql(u8, decl.name, "local")) {
+ inline for (struct_info.decl_names) |decl_name| {
+ if (std.mem.eql(u8, decl_name, "local")) {
const Fn = @TypeOf(@field(T, "local"));
const fn_info = @typeInfo(Fn).@"fn";
return fn_info.return_type.?;
diff --git a/src/browser/js/Module.zig b/src/browser/js/Module.zig
index 0936caa3e..a7ce4e4e2 100644
--- a/src/browser/js/Module.zig
+++ b/src/browser/js/Module.zig
@@ -36,7 +36,7 @@ pub const Status = enum(u32) {
};
pub fn getStatus(self: Module) Status {
- return @enumFromInt(v8.v8__Module__GetStatus(self.handle));
+ return @fromBackingInt(@intCast(v8.v8__Module__GetStatus(self.handle)));
}
pub fn getException(self: Module) js.Value {
diff --git a/src/browser/js/Promise.zig b/src/browser/js/Promise.zig
index 1dc531289..64b49428d 100644
--- a/src/browser/js/Promise.zig
+++ b/src/browser/js/Promise.zig
@@ -55,7 +55,7 @@ pub const State = enum(u32) {
};
pub fn state(self: Promise) State {
- return @enumFromInt(v8.v8__Promise__State(self.handle));
+ return @fromBackingInt(@intCast(v8.v8__Promise__State(self.handle)));
}
/// Settled value (fulfillment or rejection). Caller must check `state` first.
diff --git a/src/browser/js/Snapshot.zig b/src/browser/js/Snapshot.zig
index ccd6f0202..35e5504b2 100644
--- a/src/browser/js/Snapshot.zig
+++ b/src/browser/js/Snapshot.zig
@@ -348,10 +348,10 @@ fn createSnapshotContext(
const func_obj: *const v8.Object = @ptrCast(func);
if (v8.v8__Object__Get(func_obj, context, prototype_key)) |proto_handle| {
const proto_obj: *const v8.Object = @ptrCast(proto_handle);
- inline for (@typeInfo(JsApi).@"struct".decls) |d| {
- const exposed = comptime memberExposed(@field(JsApi, d.name));
+ inline for (@typeInfo(JsApi).@"struct".decl_names) |decl_name| {
+ const exposed = comptime memberExposed(@field(JsApi, decl_name));
if (comptime exposed != .both and exposed != realm.asExposed()) {
- const name: [:0]const u8 = d.name;
+ const name: [:0]const u8 = decl_name;
const name_v8 = v8.v8__String__NewFromUtf8(isolate, name.ptr, v8.kNormal, @intCast(name.len));
var maybe_deleted: v8.MaybeBool = undefined;
v8.v8__Object__Delete(proto_obj, context, name_v8, &maybe_deleted);
@@ -399,8 +399,8 @@ fn createSnapshotContext(
fn hasGatedMember(comptime JsApi: type) bool {
comptime {
- for (@typeInfo(JsApi).@"struct".decls) |d| {
- if (memberExposed(@field(JsApi, d.name)) != .both) {
+ for (@typeInfo(JsApi).@"struct".decl_names) |decl_name| {
+ if (memberExposed(@field(JsApi, decl_name)) != .both) {
return true;
}
}
@@ -444,9 +444,9 @@ fn countExternalReferences() comptime_int {
count += 1;
}
- const declarations = @typeInfo(JsApi).@"struct".decls;
- inline for (declarations) |d| {
- const value = @field(JsApi, d.name);
+ const decl_names = @typeInfo(JsApi).@"struct".decl_names;
+ inline for (decl_names) |decl_name| {
+ const value = @field(JsApi, decl_name);
const T = @TypeOf(value);
if (T == bridge.Accessor) {
if (value.wpt_only and wpt_extensions_enabled == false) {
@@ -524,9 +524,9 @@ fn collectExternalReferences() [countExternalReferences()]isize {
idx += 1;
}
- const declarations = @typeInfo(JsApi).@"struct".decls;
- inline for (declarations) |d| {
- const value = @field(JsApi, d.name);
+ const decl_names = @typeInfo(JsApi).@"struct".decl_names;
+ inline for (decl_names) |decl_name| {
+ const value = @field(JsApi, decl_name);
const T = @TypeOf(value);
if (T == bridge.Accessor) {
if (value.wpt_only and wpt_extensions_enabled == false) {
@@ -619,8 +619,8 @@ fn countInternalFields(comptime JsApi: type) u8 {
var last_used_id = 0;
var cache_count: u8 = 0;
- inline for (@typeInfo(JsApi).@"struct".decls) |d| {
- const name: [:0]const u8 = d.name;
+ inline for (@typeInfo(JsApi).@"struct".decl_names) |decl_name| {
+ const name: [:0]const u8 = decl_name;
const value = @field(JsApi, name);
const definition = @TypeOf(value);
@@ -687,9 +687,9 @@ fn illegalConstructorCallback(raw_info: ?*const v8.FunctionCallbackInfo) callcon
// Helper to check if a JsApi has a NamedIndexed handler (public for reuse)
fn hasNamedIndexedGetter(comptime JsApi: type) bool {
- const declarations = @typeInfo(JsApi).@"struct".decls;
- inline for (declarations) |d| {
- const value = @field(JsApi, d.name);
+ const decl_names = @typeInfo(JsApi).@"struct".decl_names;
+ inline for (decl_names) |decl_name| {
+ const value = @field(JsApi, decl_name);
const T = @TypeOf(value);
if (T == bridge.NamedIndexed) {
return true;
@@ -805,13 +805,12 @@ fn attachClass(comptime JsApi: type, comptime flatten: bool, isolate: *v8.Isolat
const own_properties = @hasDecl(JsApi.Meta, "own_properties") and JsApi.Meta.own_properties;
const member_template = if (own_properties) instance else prototype;
- const declarations = @typeInfo(JsApi).@"struct".decls;
+ const decl_names = @typeInfo(JsApi).@"struct".decl_names;
var has_named_index_getter = false;
const wpt_extensions_enabled = lp.build_config.wpt_extensions;
- inline for (declarations) |d| {
- const name: [:0]const u8 = d.name;
+ inline for (decl_names) |name| {
const value = @field(JsApi, name);
const definition = @TypeOf(value);
@@ -992,10 +991,10 @@ const unforgeables: []const Unforgeable = blk: {
@setEvalBranchQuota(100_000);
var list: []const Unforgeable = &.{};
for (JsApis) |Api| {
- for (@typeInfo(Api).@"struct".decls) |d| {
- const value = @field(Api, d.name);
+ for (@typeInfo(Api).@"struct".decl_names) |decl_name| {
+ const value = @field(Api, decl_name);
if (@TypeOf(value) == bridge.Accessor and value.unforgeable and !value.static) {
- list = list ++ &[_]Unforgeable{.{ .Owner = Api, .name = d.name, .accessor = value }};
+ list = list ++ &[_]Unforgeable{.{ .Owner = Api, .name = decl_name, .accessor = value }};
}
}
}
diff --git a/src/browser/js/TaggedOpaque.zig b/src/browser/js/TaggedOpaque.zig
index 3d32b1da1..1f9411598 100644
--- a/src/browser/js/TaggedOpaque.zig
+++ b/src/browser/js/TaggedOpaque.zig
@@ -26,7 +26,7 @@ const bridge = js.bridge;
//
// In a simple/perfect world, we could use this knowledge to cast the *anyopaque
// to the parameter type:
-// const arg: @typeInfo(@TypeOf(function)).@"fn".params[0] = @ptrCast(v8_data);
+// const arg: @typeInfo(@TypeOf(function)).@"fn".param_types[0].? = @ptrCast(v8_data);
//
// But there are 2 reasons we can't do that.
//
diff --git a/src/browser/js/TryCatch.zig b/src/browser/js/TryCatch.zig
index 561377bad..723bbd5bd 100644
--- a/src/browser/js/TryCatch.zig
+++ b/src/browser/js/TryCatch.zig
@@ -136,10 +136,10 @@ pub const Caught = struct {
pub fn logFmt(self: Caught, prefix: []const u8, writer: anytype) !void {
var buf: [64]u8 = undefined;
- try writer.write(try std.fmt.bufPrint(&buf, "{s}.exception", .{prefix}), self.exception orelse "???");
- try writer.write(try std.fmt.bufPrint(&buf, "{s}.stack", .{prefix}), self.stack orelse "na");
- try writer.write(try std.fmt.bufPrint(&buf, "{s}.line", .{prefix}), self.line);
- try writer.write(try std.fmt.bufPrint(&buf, "{s}.caught", .{prefix}), self.caught);
+ try writer.write(try std.mem.print(&buf, "{s}.exception", .{prefix}), self.exception orelse "???");
+ try writer.write(try std.mem.print(&buf, "{s}.stack", .{prefix}), self.stack orelse "na");
+ try writer.write(try std.mem.print(&buf, "{s}.line", .{prefix}), self.line);
+ try writer.write(try std.mem.print(&buf, "{s}.caught", .{prefix}), self.caught);
}
pub fn jsonStringify(self: Caught, jw: anytype) !void {
diff --git a/src/browser/js/Value.zig b/src/browser/js/Value.zig
index e43f6062b..edfca281c 100644
--- a/src/browser/js/Value.zig
+++ b/src/browser/js/Value.zig
@@ -853,7 +853,7 @@ const Inert = struct {
if (i != 0) {
try writer.writeByte(',');
}
- const key = std.fmt.bufPrint(&key_buf, "{d}", .{i}) catch unreachable;
+ const key = std.mem.print(&key_buf, "{d}", .{i}) catch unreachable;
const element = self.ownDataProperty(@ptrCast(handle), key) orelse continue;
if (v8.v8__Value__IsNullOrUndefined(element)) {
continue;
@@ -1012,7 +1012,7 @@ test "Value: inert formatting runs no page JS" {
};
for (cases) |case| {
const value = try ls.local.exec(case.expr, null);
- const out = try std.fmt.allocPrint(testing.allocator, "{f}", .{value});
+ const out = try testing.allocator.print("{f}", .{value});
defer testing.allocator.free(out);
try testing.expectEqualSlices(u8, case.expected, out);
}
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index 17c33454a..e02f52d99 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -207,9 +207,9 @@ pub const Function = struct {
const Session = @import("../Session.zig");
var count: usize = 0;
- var params = @typeInfo(T).@"fn".params;
- for (params[start..]) |p| { // start at 1, skip self
- const PT = p.type.?;
+ const param_types = @typeInfo(T).@"fn".param_types;
+ for (param_types[start..]) |param_type| { // start at 1, skip self
+ const PT = param_type.?;
if (PT == *Frame or PT == *const Frame) {
break;
}
@@ -440,18 +440,18 @@ pub const Indexed = struct {
fn hasNotHandled(comptime E: type) bool {
// anyerror includes it
- const errors = @typeInfo(E).error_set orelse return true;
- for (errors) |e| {
- if (std.mem.eql(u8, e.name, "NotHandled")) return true;
+ const error_names = @typeInfo(E).error_set.error_names orelse return true;
+ for (error_names) |name| {
+ if (std.mem.eql(u8, name, "NotHandled")) return true;
}
return false;
}
// Default index query if one isn't provided. Uses the getter to determine the result
fn GetterQuery(comptime getter: anytype, comptime attrs: u32) type {
- const params = @typeInfo(@TypeOf(getter)).@"fn".params;
- const Self = params[0].type.?;
- const Index = params[1].type.?;
+ const param_types = @typeInfo(@TypeOf(getter)).@"fn".param_types;
+ const Self = param_types[0].?;
+ const Index = param_types[1].?;
// A getter that can return neither null nor error.NotHandled would report
// every index as present.
@@ -465,13 +465,13 @@ fn GetterQuery(comptime getter: anytype, comptime attrs: u32) type {
}
return struct {
- const query = if (params.len == 3) withGlobal else plain;
+ const query = if (param_types.len == 3) withGlobal else plain;
fn plain(self: Self, idx: Index) !u32 {
return attributes(getter(self, idx));
}
- fn withGlobal(self: Self, idx: Index, global: params[2].type.?) !u32 {
+ fn withGlobal(self: Self, idx: Index, global: param_types[2].?) !u32 {
return attributes(getter(self, idx, global));
}
@@ -804,7 +804,7 @@ pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8
// });
// if (!ignored.has(property)) {
// var buf: [2048]u8 = undefined;
- // const key = std.fmt.bufPrint(&buf, "Window:{s}", .{property}) catch return js.Intercepted.no;
+ // const key = std.mem.print(&buf, "Window:{s}", .{property}) catch return js.Intercepted.no;
// logUnknownProperty(local, key) catch return js.Intercepted.no;
// }
// }
@@ -870,7 +870,7 @@ pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8
// const ignored = std.StaticStringMap(void).initComptime(.{});
// if (!ignored.has(property)) {
// var buf: [2048]u8 = undefined;
-// const key = std.fmt.bufPrint(&buf, "{s}:{s}", .{ if (@hasDecl(JsApi.Meta, "name")) JsApi.Meta.name else @typeName(JsApi), property }) catch return js.Intercepted.no;
+// const key = std.mem.print(&buf, "{s}:{s}", .{ if (@hasDecl(JsApi.Meta, "name")) JsApi.Meta.name else @typeName(JsApi), property }) catch return js.Intercepted.no;
// logUnknownProperty(local, key) catch return js.Intercepted.no;
// }
// return js.Intercepted.no;
@@ -1001,7 +1001,7 @@ pub const JsApiLookup = struct {
/// Returns the ID for the given type.
pub inline fn getId(t: type) BackingInt {
- return @intFromEnum(getIndex(t));
+ return @backingInt(getIndex(t));
}
};
diff --git a/src/browser/markdown.zig b/src/browser/markdown.zig
index c4c756eac..6bf76e9a4 100644
--- a/src/browser/markdown.zig
+++ b/src/browser/markdown.zig
@@ -29,6 +29,7 @@ const Slot = @import("webapi/element/html/Slot.zig");
const LimitedWriter = @import("../LimitedWriter.zig");
const isAllWhitespace = @import("../string.zig").isAllWhitespace;
+const repeat = @import("../string.zig").repeat;
pub const Opts = struct {
max_bytes: ?u32 = null,
@@ -895,7 +896,7 @@ test "browser.markdown: max_bytes truncates with marker" {
const doc = frame.window._document;
const div = try doc.createElement("div", null, frame);
- try Frame.parse.htmlAsChildren(frame, div.asNode(), "<p>" ++ ("AAAA " ** 100) ++ "</p>");
+ try Frame.parse.htmlAsChildren(frame, div.asNode(), "<p>" ++ (repeat("AAAA ", 100)) ++ "</p>");
var aw: std.Io.Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zig
index e9778bb49..d7e19c776 100644
--- a/src/browser/parser/Parser.zig
+++ b/src/browser/parser/Parser.zig
@@ -542,7 +542,7 @@ fn _createElementCallback(self: *Parser, data: *anyopaque, qname: h5e.QualName,
// like createElementNS. html5ever never sets a prefix; xml5ever does.
const name = if (qname.prefix.unwrap()) |prefix| blk: {
if (prefix.len == 0) break :blk local;
- break :blk try std.fmt.allocPrint(frame.local_arena, "{s}:{s}", .{ prefix.slice(), local });
+ break :blk try frame.local_arena.print("{s}:{s}", .{ prefix.slice(), local });
} else local;
const namespace_string = qname.ns.slice();
const namespace = if (namespace_string.len == 0) default_namespace else Element.Namespace.parse(namespace_string);
@@ -953,7 +953,7 @@ fn getNode(ref: *anyopaque) *Node {
return getParsed(ref).node;
}
-fn asUint(comptime string: anytype) std.meta.Int(
+fn asUint(comptime string: anytype) @Int(
.unsigned,
@bitSizeOf(@TypeOf(string.*)) - 8, // (- 8) to exclude sentinel 0
) {
diff --git a/src/browser/pdf.zig b/src/browser/pdf.zig
index 7cce969b2..e0ea9321b 100644
--- a/src/browser/pdf.zig
+++ b/src/browser/pdf.zig
@@ -291,7 +291,7 @@ const Document = struct {
const layout = self.layout;
const lines = layout.lines();
for (layout.blocks(), 0..) |b, bi| {
- if (b.kind == @intFromEnum(screenshot.LpBlock.Kind.rule)) {
+ if (b.kind == @backingInt(screenshot.LpBlock.Kind.rule)) {
const pg, const py = self.pageOf(b.y);
if (self.selected[pg]) {
try rect(&self.pages[pg].writer, layout.raw.rule_color, b.x, py, self.column_w - b.x, 1);
@@ -311,7 +311,7 @@ const Document = struct {
const h = boxes[j].bottom - boxes[i].top;
if (self.selected[pg]) {
const w = &self.pages[pg].writer;
- if (b.kind == @intFromEnum(screenshot.LpBlock.Kind.pre) and self.opts.print_background) {
+ if (b.kind == @backingInt(screenshot.LpBlock.Kind.pre) and self.opts.print_background) {
const x0 = b.x - layout.raw.pre_pad;
try rect(w, layout.raw.pre_bg, x0, top, self.column_w - x0, h);
}
@@ -351,7 +351,7 @@ const Document = struct {
/// Each line's vertical extent. A <pre> grows its first and last line by
/// the padding so the background stays with the text across a break.
fn lineBoxes(self: *const Document, b: screenshot.LpLayoutBlock, block_lines: []const screenshot.LpLine) ![]const Box {
- const pad: f32 = if (b.kind == @intFromEnum(screenshot.LpBlock.Kind.pre)) self.layout.raw.pre_pad else 0;
+ const pad: f32 = if (b.kind == @backingInt(screenshot.LpBlock.Kind.pre)) self.layout.raw.pre_pad else 0;
const boxes = try self.arena.alloc(Box, block_lines.len);
for (boxes, block_lines, 0..) |*box, line, i| {
box.* = .{
@@ -584,11 +584,11 @@ fn paginate(arena: Allocator, layout: *const screenshot.Layout, page_h: f32) ![]
try breaks.append(arena, 0);
const lines = layout.lines();
for (layout.blocks()) |b| {
- if (b.kind == @intFromEnum(screenshot.LpBlock.Kind.rule)) {
+ if (b.kind == @backingInt(screenshot.LpBlock.Kind.rule)) {
try fit(arena, &breaks, b.y, b.y + 1, page_h);
continue;
}
- const pad: f32 = if (b.kind == @intFromEnum(screenshot.LpBlock.Kind.pre)) layout.raw.pre_pad else 0;
+ const pad: f32 = if (b.kind == @backingInt(screenshot.LpBlock.Kind.pre)) layout.raw.pre_pad else 0;
for (lines[b.lines..][0..b.lines_len], 0..) |line, i| {
const top = line.top - if (i == 0) pad else 0;
const bottom = line.bottom + if (i + 1 == b.lines_len) pad else 0;
@@ -673,10 +673,10 @@ const FontUse = struct {
const ttf = &self.ttf;
const k = 1000 / @as(f32, @floatFromInt(ttf.upem));
const gids = try self.sortedGids(arena);
- const name = try std.fmt.allocPrint(arena, "{s}+{s}", .{ SUBSET_TAG, self.info.name[0..self.info.name_len] });
+ const name = try arena.print("{s}+{s}", .{ SUBSET_TAG, self.info.name[0..self.info.name_len] });
const file = ttf.subset(arena, gids) catch ttf.data;
- const file_id = try out.stream(try std.fmt.allocPrint(arena, "/Length1 {d}", .{file.len}), file);
+ const file_id = try out.stream(try arena.print("/Length1 {d}", .{file.len}), file);
const descriptor = try out.alloc();
try out.begin(descriptor);
@@ -988,7 +988,7 @@ const Out = struct {
}
fn print(self: *Out, comptime fmt: []const u8, args: anytype) !void {
- try self.write(try std.fmt.allocPrint(self.arena, fmt, args));
+ try self.write(try self.arena.print(fmt, args));
}
fn alloc(self: *Out) !usize {
diff --git a/src/browser/referrer.zig b/src/browser/referrer.zig
index 0e3250441..5743d943c 100644
--- a/src/browser/referrer.zig
+++ b/src/browser/referrer.zig
@@ -19,6 +19,7 @@
// Referrer Policy: https://www.w3.org/TR/referrer-policy/
const std = @import("std");
const URL = @import("URL.zig");
+const repeat = @import("../string.zig").repeat;
const Allocator = std.mem.Allocator;
@@ -106,7 +107,7 @@ pub fn compute(arena: Allocator, policy: Policy, referrer_url: [:0]const u8, tar
if (full) {
// Serializing through origin + path + query strips credentials and
// the fragment, and normalizes away default ports.
- const value = try std.fmt.allocPrint(arena, "{s}{s}{s}", .{
+ const value = try arena.print("{s}{s}{s}", .{
referrer_origin,
URL.getPathname(referrer_url),
URL.getSearch(referrer_url),
@@ -117,7 +118,7 @@ pub fn compute(arena: Allocator, policy: Policy, referrer_url: [:0]const u8, tar
return value;
}
}
- return try std.fmt.allocPrint(arena, "{s}/", .{referrer_origin});
+ return try arena.print("{s}/", .{referrer_origin});
}
fn staticStringMapEqlAsciiIgnoreCase(a: []const u8, b: []const u8) bool {
@@ -207,14 +208,14 @@ test "referrer: compute" {
}
test "referrer: compute caps at 4096 bytes" {
- const path = "/" ++ ("a" ** 4096);
+ const path = "/" ++ (repeat("a", 4096));
const url = "http://a.com" ++ path;
// over the cap: falls back to the origin form
try testing.expectEqual("http://a.com/", (try compute(testing.arena_allocator, .unsafe_url, url, "http://b.com/x")).?);
try testing.expectEqual("http://a.com/", (try compute(testing.arena_allocator, .no_referrer_when_downgrade, url, "http://a.com/x")).?);
// exactly at the cap: sent in full
- const at_cap = "http://a.com/" ++ ("a" ** (4096 - "http://a.com/".len));
+ const at_cap = "http://a.com/" ++ (repeat("a", 4096 - "http://a.com/".len));
try testing.expectEqual(at_cap, (try compute(testing.arena_allocator, .unsafe_url, at_cap, "http://b.com/x")).?);
// origin-only policies are unaffected by the referrer's length
diff --git a/src/browser/screenshot.zig b/src/browser/screenshot.zig
index 00d88b337..01dff71e1 100644
--- a/src/browser/screenshot.zig
+++ b/src/browser/screenshot.zig
@@ -887,7 +887,7 @@ const Builder = struct {
if (stray) self.list_depth = 1;
if (!stray and self.list_stack[self.list_depth - 1].ordered) {
const state = &self.list_stack[self.list_depth - 1];
- self.pending_marker = try std.fmt.allocPrint(self.arena, "{d}.", .{state.index});
+ self.pending_marker = try self.arena.print("{d}.", .{state.index});
state.index += 1;
} else {
self.pending_marker = "•";
@@ -1171,9 +1171,9 @@ test "browser.screenshot: rust abi matches" {
.span_strike = SPAN_STRIKE,
.span_has_color = SPAN_HAS_COLOR,
- .block_heading = @intFromEnum(LpBlock.Kind.heading),
- .block_pre = @intFromEnum(LpBlock.Kind.pre),
- .block_rule = @intFromEnum(LpBlock.Kind.rule),
+ .block_heading = @backingInt(LpBlock.Kind.heading),
+ .block_pre = @backingInt(LpBlock.Kind.pre),
+ .block_rule = @backingInt(LpBlock.Kind.rule),
.block_tight = BLOCK_TIGHT,
.render_measure_only = RENDER_MEASURE_ONLY,
@@ -1189,9 +1189,9 @@ test "browser.screenshot: rust abi matches" {
// Size first: a field present on only one side of LpAbi itself shifts
// everything after it, and the per-field loop would just report noise.
try testing.expectEqual(expected.size, got.size);
- inline for (@typeInfo(LpAbi).@"struct".fields) |f| {
- testing.expectEqual(@field(expected, f.name), @field(got, f.name)) catch |err| {
- std.debug.print("rust/zig abi mismatch on {s}\n", .{f.name});
+ inline for (@typeInfo(LpAbi).@"struct".field_names) |field_name| {
+ testing.expectEqual(@field(expected, field_name), @field(got, field_name)) catch |err| {
+ std.debug.print("rust/zig abi mismatch on {s}\n", .{field_name});
return err;
};
}
diff --git a/src/browser/tools.zig b/src/browser/tools.zig
index 0f4783b92..e90924957 100644
--- a/src/browser/tools.zig
+++ b/src/browser/tools.zig
@@ -783,11 +783,11 @@ const url_params_schema = minify(
\\}
);
-/// Materialized form of `Tool.definition` keyed by `@intFromEnum(Tool)`.
+/// Materialized form of `Tool.definition` keyed by `@backingInt(Tool)`.
/// Built at comptime by iterating every `Tool` tag — order and count
/// can't drift because both come from the enum itself.
-pub const tool_defs: [@typeInfo(Tool).@"enum".fields.len]Tool.Definition = blk: {
- var arr: [@typeInfo(Tool).@"enum".fields.len]Tool.Definition = undefined;
+pub const tool_defs: [@typeInfo(Tool).@"enum".field_names.len]Tool.Definition = blk: {
+ var arr: [@typeInfo(Tool).@"enum".field_names.len]Tool.Definition = undefined;
for (std.enums.values(Tool), 0..) |t, i| arr[i] = t.definition();
break :blk arr;
};
@@ -795,10 +795,10 @@ pub const tool_defs: [@typeInfo(Tool).@"enum".fields.len]Tool.Definition = blk:
/// Comptime-built flat array of tool names, in `Tool` declaration order.
/// Use this when callers only need the names (slash-command lookup, MCP
/// `tools/list`).
-pub const names: [@typeInfo(Tool).@"enum".fields.len][]const u8 = blk: {
- const fields = @typeInfo(Tool).@"enum".fields;
- var arr: [fields.len][]const u8 = undefined;
- for (fields, 0..) |f, i| arr[i] = f.name;
+pub const names: [@typeInfo(Tool).@"enum".field_names.len][]const u8 = blk: {
+ const field_names = @typeInfo(Tool).@"enum".field_names;
+ var arr: [field_names.len][]const u8 = undefined;
+ for (field_names, 0..) |field_name, i| arr[i] = field_name;
break :blk arr;
};
@@ -913,7 +913,7 @@ pub fn call(
// `multi_tool_use.parallel` wrapper) learns the name is wrong instead of
// retrying it with different arguments.
const tool = std.meta.stringToEnum(Tool, tool_name) orelse return .{
- .text = try std.fmt.allocPrint(arena, "Unknown tool: {s}", .{tool_name}),
+ .text = try arena.print("Unknown tool: {s}", .{tool_name}),
.is_error = true,
};
if (diagnoseArgs(arena, arguments)) |msg|
@@ -1012,7 +1012,7 @@ fn dispatch(
fn formatNavigationError(arena: std.mem.Allocator, session: *lp.Session) ?[]const u8 {
const frame = session.currentFrame() orelse return null;
const err = frame._last_navigate_error orelse return null;
- return std.fmt.allocPrint(arena, "navigation failed: {s}", .{@errorName(err)}) catch null;
+ return arena.print("navigation failed: {s}", .{@errorName(err)}) catch null;
}
/// Run JavaScript against the current page. The script need not be
@@ -1023,7 +1023,7 @@ pub fn evalScript(
registry: *NodeRegistry,
script: []const u8,
) ToolError!ToolResult {
- const z = try arena.dupeZ(u8, script);
+ const z = try arena.dupeSentinel(u8, script, 0);
const page = try ensurePage(session, registry, null, null);
return runEval(arena, page, z, null);
}
@@ -1109,9 +1109,9 @@ fn navStatus(arena: std.mem.Allocator, frame: *const lp.Frame) []const u8 {
// `std.http.Status` is an enum(u10) and `_http_status` is only clamped to
// u16 (`http.getResponseCode`), so a server answering with a 4-digit code
// would make the cast illegal behaviour rather than an unknown phrase.
- const phrase = if (status > 599) "" else @as(std.http.Status, @enumFromInt(status)).phrase() orelse "";
- if (phrase.len == 0) return std.fmt.allocPrint(arena, "{d}", .{status}) catch "unknown";
- return std.fmt.allocPrint(arena, "{d} {s}", .{ status, phrase }) catch "unknown";
+ const phrase = if (status > 599) "" else @as(std.http.Status, @fromBackingInt(@intCast(status))).phrase() orelse "";
+ if (phrase.len == 0) return arena.print("{d}", .{status}) catch "unknown";
+ return arena.print("{d} {s}", .{ status, phrase }) catch "unknown";
}
fn execGoto(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeRegistry, arguments: ?std.json.Value) ToolError![]const u8 {
@@ -1119,8 +1119,8 @@ fn execGoto(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeRegis
const result = try performGoto(session, registry, args.url, .{ .timeout = args.timeout, .wait_until = args.waitUntil });
const status = if (session.currentFrame()) |frame| navStatus(arena, frame) else "unknown";
return switch (result) {
- .completed => std.fmt.allocPrint(arena, "Navigated successfully. HTTP {s}.", .{status}),
- .timeout => std.fmt.allocPrint(arena, "Navigation started (HTTP {s}) but the page did not finish loading before the timeout.", .{status}),
+ .completed => arena.print("Navigated successfully. HTTP {s}.", .{status}),
+ .timeout => arena.print("Navigation started (HTTP {s}) but the page did not finish loading before the timeout.", .{status}),
} catch ToolError.InternalError;
}
@@ -1521,17 +1521,17 @@ fn execScreenshot(arena: std.mem.Allocator, session: *lp.Session, registry: *Nod
if (args.path) |path| {
const content_height = writePng(&prepared, path) catch |err| return .{
- .text = std.fmt.allocPrint(arena, "could not write {s}: {s}", .{ path, @errorName(err) }) catch return ToolError.OutOfMemory,
+ .text = arena.print("could not write {s}: {s}", .{ path, @errorName(err) }) catch return ToolError.OutOfMemory,
.is_error = true,
};
// The renderer reports the content height; a fixed strip is its own height.
const height = if (prepared.opts.height == 0) content_height else prepared.opts.height;
- return .{ .text = std.fmt.allocPrint(arena, "Saved {d}x{d} PNG to {s}", .{ prepared.opts.width, height, absolutePath(arena, path) }) catch return ToolError.OutOfMemory };
+ return .{ .text = arena.print("Saved {d}x{d} PNG to {s}", .{ prepared.opts.width, height, absolutePath(arena, path) }) catch return ToolError.OutOfMemory };
}
prepared.fit(inline_image_max_width, inline_image_max_height) catch return ToolError.InternalError;
return .{
- .text = std.fmt.allocPrint(arena, "PNG, {d}x{d}", .{ prepared.opts.width, prepared.opts.height }) catch return ToolError.OutOfMemory,
+ .text = arena.print("PNG, {d}x{d}", .{ prepared.opts.width, prepared.opts.height }) catch return ToolError.OutOfMemory,
.image = prepared,
};
}
@@ -1646,14 +1646,12 @@ fn execEvaluate(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeR
// Block scope preserves a trailing expression's value and keeps top-level
// `let`/`const` from leaking; top-level `await`/`return` need the async IIFE.
- const block_script = std.fmt.allocPrintSentinel(
- arena,
+ const block_script = arena.printSentinel(
"{{ {s}\n}}",
.{args.script},
0,
) catch return ToolError.OutOfMemory;
- const iife_script = std.fmt.allocPrintSentinel(
- arena,
+ const iife_script = arena.printSentinel(
"(async function(){{ \"use strict\"; {s} }})()",
.{args.script},
0,
@@ -1697,7 +1695,7 @@ fn execEvaluate(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeR
if (result.text.len == 0) return result; // silenced save=; don't re-emit via nav suffix
const page_title = after.getTitle() catch null;
- const text = std.fmt.allocPrint(arena, "{s}\n(Navigated to {s}, HTTP {s}, title: {s})", .{
+ const text = arena.print("{s}\n(Navigated to {s}, HTTP {s}, title: {s})", .{
result.text, after.url, navStatus(arena, after), page_title orelse "(none)",
}) catch return ToolError.InternalError;
return .{ .text = text };
@@ -1811,7 +1809,7 @@ fn bridgePrelude(arena: std.mem.Allocator, store: *const BridgeStore) ![:0]const
try aw.writer.writeAll(kv.value_ptr.*);
}
try aw.writer.writeAll("};");
- return arena.dupeZ(u8, aw.written());
+ return arena.dupeSentinel(u8, aw.written(), 0);
}
const bridge_postlude: [:0]const u8 = "JSON.stringify(globalThis.lp)";
@@ -1925,7 +1923,7 @@ fn formatActionResult(
target: ActionTarget,
suffix: []const u8,
) ToolError![]const u8 {
- return std.fmt.allocPrint(arena, "{s} ({f}){s}", .{ prefix, target, suffix }) catch ToolError.InternalError;
+ return arena.print("{s} ({f}){s}", .{ prefix, target, suffix }) catch ToolError.InternalError;
}
/// What `finalizeAction` compares against; take it before the action runs.
@@ -1972,7 +1970,7 @@ fn finalizeAction(arena: std.mem.Allocator, session: *lp.Session, registry: *Nod
}
const page_title = page.getTitle() catch null;
- return std.fmt.allocPrint(arena, "{s}.{s} Page url: {s}, HTTP {s}, title: {s}", .{
+ return arena.print("{s}.{s} Page url: {s}, HTTP {s}, title: {s}", .{
body, note, page.url, navStatus(arena, page), page_title orelse "(none)",
}) catch ToolError.InternalError;
}
@@ -2009,7 +2007,7 @@ fn execFill(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeRegis
lp.actions.fill(resolved.node, text, resolved.page) catch |err| return mapActionError(err);
// Show the original reference (e.g. $LP_PASSWORD) in the result, not the resolved value
- const suffix = std.fmt.allocPrint(arena, " with \"{s}\"", .{raw_text}) catch return ToolError.InternalError;
+ const suffix = arena.print(" with \"{s}\"", .{raw_text}) catch return ToolError.InternalError;
const body = try formatActionResult(arena, "Filled element", resolved.target, suffix);
return finalizeAction(arena, session, registry, scope, body);
}
@@ -2032,15 +2030,15 @@ fn execScroll(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeReg
const result = lp.actions.scroll(if (resolved) |r| r.node else null, args.x, args.y, page) catch |err| return mapActionError(err);
const body = (switch (result.target) {
- .window => std.fmt.allocPrint(arena, "Scrolled window to x: {d}, y: {d}", .{ result.x, result.y }),
- .node => std.fmt.allocPrint(arena, "Scrolled element ({f}) to x: {d}, y: {d}", .{
+ .window => arena.print("Scrolled window to x: {d}, y: {d}", .{ result.x, result.y }),
+ .node => arena.print("Scrolled element ({f}) to x: {d}, y: {d}", .{
resolved.?.target,
result.x,
result.y,
}),
.container => |container| blk: {
const registered = registry.register(container) catch return ToolError.InternalError;
- break :blk std.fmt.allocPrint(arena, "Scrolled scroll container ({f}) of element ({f}) to x: {d}, y: {d}", .{
+ break :blk arena.print("Scrolled scroll container ({f}) of element ({f}) to x: {d}, y: {d}", .{
ActionTarget{ .backend_node_id = registered.id },
resolved.?.target,
result.x,
@@ -2087,7 +2085,7 @@ fn execWaitForSelector(arena: std.mem.Allocator, session: *lp.Session, registry:
};
const registered = registry.register(node) catch return ToolError.InternalError;
- return std.fmt.allocPrint(arena, "Element found. backendNodeId: {d}", .{registered.id}) catch return ToolError.InternalError;
+ return arena.print("Element found. backendNodeId: {d}", .{registered.id}) catch return ToolError.InternalError;
}
fn execWaitForScript(arena: std.mem.Allocator, session: *lp.Session, arguments: ?std.json.Value) ToolError![]const u8 {
@@ -2138,7 +2136,7 @@ fn execWaitForState(arena: std.mem.Allocator, session: *lp.Session, arguments: ?
},
};
- return std.fmt.allocPrint(arena, "Page reached {s}.", .{@tagName(args.state)}) catch return ToolError.InternalError;
+ return arena.print("Page reached {s}.", .{@tagName(args.state)}) catch return ToolError.InternalError;
}
fn execHover(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeRegistry, arguments: ?std.json.Value) ToolError![]const u8 {
@@ -2182,7 +2180,7 @@ fn execPress(arena: std.mem.Allocator, session: *lp.Session, registry: *NodeRegi
// Pressing Enter on a form input triggers implicit form submission;
// `finalizeAction` drains the queued navigation before tagging the body.
- const body = std.fmt.allocPrint(arena, "Pressed key '{s}'", .{args.key}) catch return ToolError.InternalError;
+ const body = arena.print("Pressed key '{s}'", .{args.key}) catch return ToolError.InternalError;
return finalizeAction(arena, session, registry, scope, body);
}
@@ -2199,7 +2197,7 @@ fn execSelectOption(arena: std.mem.Allocator, session: *lp.Session, registry: *N
lp.actions.selectOption(resolved.node, args.value, resolved.page) catch |err| return mapActionError(err);
- const prefix = std.fmt.allocPrint(arena, "Selected option '{s}'", .{args.value}) catch return ToolError.InternalError;
+ const prefix = arena.print("Selected option '{s}'", .{args.value}) catch return ToolError.InternalError;
const body = try formatActionResult(arena, prefix, resolved.target, "");
return finalizeAction(arena, session, registry, scope, body);
}
@@ -2218,7 +2216,7 @@ fn execSetChecked(arena: std.mem.Allocator, session: *lp.Session, registry: *Nod
lp.actions.setChecked(resolved.node, args.checked, resolved.page) catch |err| return mapActionError(err);
const state_str: []const u8 = if (args.checked) "checked" else "unchecked";
- const suffix = std.fmt.allocPrint(arena, " to {s}", .{state_str}) catch return ToolError.InternalError;
+ const suffix = arena.print(" to {s}", .{state_str}) catch return ToolError.InternalError;
const body = try formatActionResult(arena, "Set element", resolved.target, suffix);
return finalizeAction(arena, session, registry, scope, body);
}
@@ -2247,7 +2245,7 @@ fn execFindElement(arena: std.mem.Allocator, session: *lp.Session, registry: *No
's' => options.dot_all = true,
'm' => options.multiline = true,
else => return .{
- .text = try std.fmt.allocPrint(arena, "findElement: unsupported regex flag '{c}' in '{s}'", .{ flag, name }),
+ .text = try arena.print("findElement: unsupported regex flag '{c}' in '{s}'", .{ flag, name }),
.is_error = true,
},
};
@@ -2255,7 +2253,7 @@ fn execFindElement(arena: std.mem.Allocator, session: *lp.Session, registry: *No
const regex = session.browser.app.regex_context.compile(lit.body, options, &diag) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.InvalidRegex => return .{
- .text = try std.fmt.allocPrint(arena, "findElement: invalid name regex '{s}': {s} at offset {d}", .{ lit.body, diag.message(), diag.offset }),
+ .text = try arena.print("findElement: invalid name regex '{s}': {s} at offset {d}", .{ lit.body, diag.message(), diag.offset }),
.is_error = true,
},
};
@@ -2315,7 +2313,7 @@ fn execGetEnv(arena: std.mem.Allocator, arguments: ?std.json.Value) ToolError![]
if (args.name) |name| {
if (lookupLpEnv(name)) |value| return value;
- return std.fmt.allocPrint(arena, "Environment variable '{s}' is not set", .{name}) catch ToolError.InternalError;
+ return arena.print("Environment variable '{s}' is not set", .{name}) catch ToolError.InternalError;
}
const env_names = lpEnvNames(arena) catch return ToolError.InternalError;
@@ -2390,7 +2388,7 @@ fn execGetCookies(arena: std.mem.Allocator, session: *lp.Session, arguments: ?st
const filter_url: ?[:0]const u8 = blk: {
if (args.all) break :blk null;
- if (args.url) |u| break :blk arena.dupeZ(u8, u) catch return ToolError.InternalError;
+ if (args.url) |u| break :blk arena.dupeSentinel(u8, u, 0) catch return ToolError.InternalError;
if (session.currentFrame()) |f| break :blk f.url;
return "No current page. Pass `url` to filter by host or `all=true` to list every cookie.";
};
@@ -2410,7 +2408,7 @@ fn execGetCookies(arena: std.mem.Allocator, session: *lp.Session, arguments: ?st
}
if (count == 0) {
const label = filter_url orelse "(unfiltered)";
- return std.fmt.allocPrint(arena, "No cookies for {s}.", .{label}) catch ToolError.InternalError;
+ return arena.print("No cookies for {s}.", .{label}) catch ToolError.InternalError;
}
return aw.written();
}
@@ -2544,7 +2542,7 @@ fn diagnoseArgs(arena: std.mem.Allocator, arguments: ?std.json.Value) ?[]const u
if (args.object.get("state")) |v| switch (v) {
.string => |s| if (std.meta.stringToEnum(lp.Config.WaitUntil, s) == null)
return formatEnumError(arena, "state", s, lp.Config.WaitUntil),
- else => return std.fmt.allocPrint(arena, "state must be a string", .{}) catch null,
+ else => return arena.print("state must be a string", .{}) catch null,
};
return null;
@@ -2553,9 +2551,9 @@ fn diagnoseArgs(arena: std.mem.Allocator, arguments: ?std.json.Value) ?[]const u
fn formatEnumError(arena: std.mem.Allocator, field: []const u8, got: []const u8, comptime E: type) ?[]const u8 {
var aw: std.Io.Writer.Allocating = .init(arena);
aw.writer.print("invalid {s} '{s}'. Expected one of: ", .{ field, got }) catch return null;
- inline for (std.meta.fields(E), 0..) |f, i| {
+ inline for (@typeInfo(E).@"enum".field_names, 0..) |field_name, i| {
if (i > 0) aw.writer.writeAll(", ") catch return null;
- aw.writer.writeAll(f.name) catch return null;
+ aw.writer.writeAll(field_name) catch return null;
}
return aw.written();
}
@@ -2601,7 +2599,7 @@ pub fn normalizeArgKeys(arena: std.mem.Allocator, tool: Tool, args: ?std.json.Va
if (v != .object) return v;
const schemas = lp.Schema.all();
- const tool_idx = @intFromEnum(tool);
+ const tool_idx = @backingInt(tool);
if (tool_idx >= schemas.len) return v;
const schema = schemas[tool_idx];
@@ -2719,7 +2717,7 @@ pub fn reverseSubstituteEnvVars(arena: std.mem.Allocator, input: []const u8) err
var changed = false;
for (pairs.items) |p| {
if (std.mem.indexOf(u8, current, p.value) == null) continue;
- const placeholder = try std.fmt.allocPrint(arena, "${s}", .{p.name});
+ const placeholder = try arena.print("${s}", .{p.name});
current = try std.mem.replaceOwned(u8, arena, current, p.value, placeholder);
changed = true;
}
@@ -2751,12 +2749,12 @@ test "tree and nodeDetails read the node's own frame" {
const input_id = (try registry.register(input)).id;
const aa = testing.arena_allocator;
- const tree_args = try std.json.parseFromSliceLeaky(std.json.Value, aa, try std.fmt.allocPrint(aa, "{{\"backendNodeId\":{d}}}", .{html_id}), .{});
+ const tree_args = try std.json.parseFromSliceLeaky(std.json.Value, aa, try aa.print("{{\"backendNodeId\":{d}}}", .{html_id}), .{});
const tree = try call(aa, page.session, &registry, "tree", tree_args, .{});
try std.testing.expect(std.mem.indexOf(u8, tree.text, "child-label") != null);
try std.testing.expect(std.mem.indexOf(u8, tree.text, "parent-") == null);
- const details_args = try std.json.parseFromSliceLeaky(std.json.Value, aa, try std.fmt.allocPrint(aa, "{{\"backendNodeId\":{d}}}", .{input_id}), .{});
+ const details_args = try std.json.parseFromSliceLeaky(std.json.Value, aa, try aa.print("{{\"backendNodeId\":{d}}}", .{input_id}), .{});
const details = try call(aa, page.session, &registry, "nodeDetails", details_args, .{});
try std.testing.expect(std.mem.indexOf(u8, details.text, "child-label") != null);
}
diff --git a/src/browser/webapi/Blob.zig b/src/browser/webapi/Blob.zig
index ccd2c81bc..d90db46d2 100644
--- a/src/browser/webapi/Blob.zig
+++ b/src/browser/webapi/Blob.zig
@@ -277,7 +277,7 @@ fn writePartWithEndings(part: []const u8, use_native_endings: bool, writer: *Wri
const match = chunk == cr;
// Create a bitset out of match vector.
- const bitset = std.bit_set.IntegerBitSet(vector_len){
+ const bitset = std.bit_set.Integer(vector_len){
.mask = @bitCast(@intFromBool(match)),
};
@@ -453,7 +453,7 @@ test "Blob: a pinned arena reaches the browser's account and is given back" {
browser.flushArenaMemory();
try testing.expectEqual(0, browser.arena_account.pending);
- const data = [_]u8{'x'} ** (64 * 1024);
+ const data: [64 * 1024]u8 = @splat('x');
const blob = try Blob.initFromBytes(&data, "text/plain", &frame.js.execution);
try testing.expect(browser.arena_account.pending >= data.len);
diff --git a/src/browser/webapi/CSS.zig b/src/browser/webapi/CSS.zig
index 136b8a276..3b82168bf 100644
--- a/src/browser/webapi/CSS.zig
+++ b/src/browser/webapi/CSS.zig
@@ -107,7 +107,7 @@ pub fn escape(value: []const u8, frame: *Frame) ![]const u8 {
// Second char (i==0) is a digit and first is '-', needs hex escape
if (i == 0 and first == '-' and c >= '0' and c <= '9') {
result[pos] = '\\';
- const hex_str = std.fmt.bufPrint(result[pos + 1 ..], "{x} ", .{c}) catch unreachable;
+ const hex_str = std.mem.print(result[pos + 1 ..], "{x} ", .{c}) catch unreachable;
pos += 1 + hex_str.len;
} else if (!needsEscape(false, c)) {
result[pos] = c;
@@ -180,7 +180,7 @@ fn writeEscape(comptime is_first: bool, buf: []u8, c: u8) usize {
var data = buf[1..];
if (isHexEscape(c) or ((comptime is_first) and c >= '0' and c <= '9')) {
- const hex_str = std.fmt.bufPrint(data, "{x} ", .{c}) catch unreachable;
+ const hex_str = std.mem.print(data, "{x} ", .{c}) catch unreachable;
return 1 + hex_str.len;
}
diff --git a/src/browser/webapi/Console.zig b/src/browser/webapi/Console.zig
index 4ff029ed0..60ff76503 100644
--- a/src/browser/webapi/Console.zig
+++ b/src/browser/webapi/Console.zig
@@ -203,7 +203,7 @@ const ValueWriter = struct {
pub fn logFmt(self: ValueWriter, _: []const u8, writer: anytype) !void {
var buf: [32]u8 = undefined;
for (self.valuesToLog(), 0..) |value, i| {
- const name = try std.fmt.bufPrint(&buf, "param.{d}", .{i});
+ const name = try std.mem.print(&buf, "param.{d}", .{i});
try writer.write(name, value);
}
}
diff --git a/src/browser/webapi/DOMException.zig b/src/browser/webapi/DOMException.zig
index 3e64d9161..41b9c79cf 100644
--- a/src/browser/webapi/DOMException.zig
+++ b/src/browser/webapi/DOMException.zig
@@ -73,7 +73,7 @@ fn getCode(self: *const DOMException) u8 {
return switch (self._code) {
// no legacy numeric code
.operation_error, .data_error, .constraint_error, .version_error, .transaction_inactive_error, .read_only_error => 0,
- else => @intFromEnum(self._code),
+ else => @backingInt(self._code),
};
}
@@ -162,7 +162,7 @@ pub fn toString(self: *const DOMException, exec: *js.Execution) ![]const u8 {
else => break :blk self.getMessage(),
}
};
- return std.fmt.bufPrint(exec.buf, "{s}: {s}", .{ self.getName(), msg }) catch return msg;
+ return std.mem.print(exec.buf, "{s}: {s}", .{ self.getName(), msg }) catch return msg;
}
const Code = enum(u8) {
diff --git a/src/browser/webapi/DOMMatrix.zig b/src/browser/webapi/DOMMatrix.zig
index 3362210e2..d1abaebc2 100644
--- a/src/browser/webapi/DOMMatrix.zig
+++ b/src/browser/webapi/DOMMatrix.zig
@@ -206,7 +206,7 @@ fn invertSelf(self: *DOMMatrix) !*DOMMatrix {
if (RO.invertMatrix(state.matrix)) |v| {
state.matrix = v;
} else {
- state.matrix = .{std.math.nan(f64)} ** 16;
+ state.matrix = @splat(std.math.nan(f64));
state.is_2d = false;
}
return self.applyState(state);
diff --git a/src/browser/webapi/DOMMatrixReadOnly.zig b/src/browser/webapi/DOMMatrixReadOnly.zig
index 3bd40f58d..997e66c5f 100644
--- a/src/browser/webapi/DOMMatrixReadOnly.zig
+++ b/src/browser/webapi/DOMMatrixReadOnly.zig
@@ -758,7 +758,7 @@ fn inverse(self: *const DOMMatrixReadOnly, page: *Page) !*DOMMatrix {
return DOMMatrix.create(v, self._is_2d, page);
}
// Non-invertible matrices become all-NaN with is2D = false.
- return DOMMatrix.create(.{std.math.nan(f64)} ** 16, false, page);
+ return DOMMatrix.create(@splat(std.math.nan(f64)), false, page);
}
fn toFloat32Array(self: *const DOMMatrixReadOnly, exec: *const js.Execution) !js.TypedArray(f32) {
@@ -783,7 +783,7 @@ pub fn toString(self: *const DOMMatrixReadOnly, exec: *const js.Execution) ![]co
return error.InvalidStateError;
}
}
- return std.fmt.allocPrint(exec.local_arena, "matrix({d}, {d}, {d}, {d}, {d}, {d})", .{
+ return exec.local_arena.print("matrix({d}, {d}, {d}, {d}, {d}, {d})", .{
m[0], m[1], m[4], m[5], m[12], m[13],
});
}
@@ -792,7 +792,7 @@ pub fn toString(self: *const DOMMatrixReadOnly, exec: *const js.Execution) ![]co
return error.InvalidStateError;
}
}
- return std.fmt.allocPrint(exec.local_arena, "matrix3d({d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d})", .{
+ return exec.local_arena.print("matrix3d({d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d}, {d})", .{
m[0], m[1], m[2], m[3],
m[4], m[5], m[6], m[7],
m[8], m[9], m[10], m[11],
diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zig
index e4f460bd3..93e4c2885 100644
--- a/src/browser/webapi/Document.zig
+++ b/src/browser/webapi/Document.zig
@@ -218,7 +218,7 @@ fn getLastModified(self: *const Document, frame: *Frame) ![]const u8 {
};
const tm = try dt.localTime(timestamp);
- return std.fmt.allocPrint(frame.local_arena, "{d:0>2}/{d:0>2}/{d} {d:0>2}:{d:0>2}:{d:0>2}", .{
+ return frame.local_arena.print("{d:0>2}/{d:0>2}/{d} {d:0>2}:{d:0>2}:{d:0>2}", .{
@as(u32, @intCast(tm.tm_mon + 1)),
@as(u32, @intCast(tm.tm_mday)),
tm.tm_year + 1900,
@@ -1223,7 +1223,7 @@ fn writeInternal(self: *Document, text: []const []const u8, append_newline: bool
}
frame.domChanged();
- self._write_insertion_point = children_to_insert.getLast();
+ self._write_insertion_point = children_to_insert.last().?;
}
pub fn open(self: *Document, call_frame: *Frame) !*Document {
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index 50bfd8377..038add03a 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -733,7 +733,7 @@ fn prefixedAttributeName(namespace: []const u8, local_name: []const u8, frame: *
}
return null;
};
- return try std.fmt.allocPrint(frame.local_arena, "{s}:{s}", .{ prefix, local_name });
+ return try frame.local_arena.print("{s}:{s}", .{ prefix, local_name });
}
pub fn getAttributeSafe(self: *const Element, name: String) ?[]const u8 {
diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zig
index 732469e90..cd15525b8 100644
--- a/src/browser/webapi/Event.zig
+++ b/src/browser/webapi/Event.zig
@@ -295,7 +295,7 @@ fn setCancelBubble(self: *Event) void {
}
fn getEventPhase(self: *const Event) u8 {
- return @intFromEnum(self._event_phase);
+ return @backingInt(self._event_phase);
}
fn getTimeStamp(self: *const Event, exec: *js.Execution) f64 {
@@ -399,42 +399,30 @@ pub fn inheritOptions(comptime T: type, comptime additions: anytype) type {
// this per-level check produce.
js.Local.assertDictionaryFieldOrder(additions);
- var all_fields: []const std.builtin.Type.StructField = &.{};
+ var names: []const [:0]const u8 = &.{};
+ var types: []const type = &.{};
+ var attrs: []const std.lang.Type.Struct.FieldAttributes = &.{};
if (@hasField(T, "_proto")) {
- const t_fields = @typeInfo(T).@"struct".fields;
-
- inline for (t_fields) |field| {
- if (std.mem.eql(u8, field.name, "_proto")) {
- const ProtoType = @typeInfo(field.type).pointer.child;
- if (@hasDecl(ProtoType, "Options")) {
- const parent_options = @typeInfo(ProtoType.Options);
- for (parent_options.@"struct".fields) |f| {
- if (!std.mem.eql(u8, f.name, js.Local.dictionary_group_marker)) {
- all_fields = all_fields ++ &[_]std.builtin.Type.StructField{f};
- }
- }
+ const ProtoType = @typeInfo(@FieldType(T, "_proto")).pointer.child;
+ if (@hasDecl(ProtoType, "Options")) {
+ const parent_options = @typeInfo(ProtoType.Options).@"struct";
+ for (parent_options.field_names, parent_options.field_types, parent_options.field_attrs) |field_name, field_type, field_attrs| {
+ if (!std.mem.eql(u8, field_name, js.Local.dictionary_group_marker)) {
+ names = names ++ .{field_name};
+ types = types ++ .{field_type};
+ attrs = attrs ++ .{field_attrs};
}
}
}
}
- const additions_info = @typeInfo(additions);
- all_fields = all_fields ++ additions_info.@"struct".fields;
-
+ const additions_info = @typeInfo(additions).@"struct";
const marker_default: void = {};
- var names: [all_fields.len + 1][:0]const u8 = undefined;
- var types: [all_fields.len + 1]type = undefined;
- var attrs: [all_fields.len + 1]std.builtin.Type.StructField.Attributes = undefined;
- for (all_fields, 0..) |f, i| {
- names[i] = f.name;
- types[i] = f.type;
- attrs[i] = .{ .@"comptime" = f.is_comptime, .@"align" = f.alignment, .default_value_ptr = f.default_value_ptr };
- }
- names[all_fields.len] = js.Local.dictionary_group_marker;
- types[all_fields.len] = void;
- attrs[all_fields.len] = .{ .default_value_ptr = @ptrCast(&marker_default) };
- return @Struct(.auto, null, &names, &types, &attrs);
+ names = names ++ additions_info.field_names ++ .{js.Local.dictionary_group_marker};
+ types = types ++ additions_info.field_types ++ .{void};
+ attrs = attrs ++ additions_info.field_attrs ++ .{std.lang.Type.Struct.FieldAttributes{ .default_value_ptr = @ptrCast(&marker_default) }};
+ return @Struct(.auto, null, names, types, attrs);
}
pub fn populatePrototypes(self: anytype, opts: anytype, trusted: bool) void {
@@ -494,10 +482,10 @@ pub const JsApi = struct {
pub const cancelBubble = bridge.accessor(Event.getCancelBubble, Event.setCancelBubble, .{});
// Event phase constants
- pub const NONE = bridge.property(@intFromEnum(EventPhase.none), .{ .template = true });
- pub const CAPTURING_PHASE = bridge.property(@intFromEnum(EventPhase.capturing_phase), .{ .template = true });
- pub const AT_TARGET = bridge.property(@intFromEnum(EventPhase.at_target), .{ .template = true });
- pub const BUBBLING_PHASE = bridge.property(@intFromEnum(EventPhase.bubbling_phase), .{ .template = true });
+ pub const NONE = bridge.property(@backingInt(EventPhase.none), .{ .template = true });
+ pub const CAPTURING_PHASE = bridge.property(@backingInt(EventPhase.capturing_phase), .{ .template = true });
+ pub const AT_TARGET = bridge.property(@backingInt(EventPhase.at_target), .{ .template = true });
+ pub const BUBBLING_PHASE = bridge.property(@backingInt(EventPhase.bubbling_phase), .{ .template = true });
};
// tested in event_target
diff --git a/src/browser/webapi/EventCounts.zig b/src/browser/webapi/EventCounts.zig
index 1e74c60c6..63609a082 100644
--- a/src/browser/webapi/EventCounts.zig
+++ b/src/browser/webapi/EventCounts.zig
@@ -77,7 +77,7 @@ const tracked_event_types = [_][]const u8{
};
// Counts stored in a fixed array
-_counts: [tracked_event_types.len]u32 = [_]u32{0} ** tracked_event_types.len,
+_counts: [tracked_event_types.len]u32 = @splat(0),
pub fn increment(self: *EventCounts, event_type: []const u8) void {
if (getIndex(event_type)) |idx| {
diff --git a/src/browser/webapi/FileReader.zig b/src/browser/webapi/FileReader.zig
index d6ea0303d..271757306 100644
--- a/src/browser/webapi/FileReader.zig
+++ b/src/browser/webapi/FileReader.zig
@@ -150,7 +150,7 @@ fn setOnProgress(self: *FileReader, cb: ?js.Function.Global) !void {
}
fn getReadyState(self: *const FileReader) u8 {
- return @intFromEnum(self._ready_state);
+ return @backingInt(self._ready_state);
}
fn getResult(self: *const FileReader) ?Result {
@@ -466,9 +466,9 @@ pub const JsApi = struct {
pub const constructor = bridge.constructor(FileReader.init, .{});
// State constants
- pub const EMPTY = bridge.property(@intFromEnum(FileReader.ReadyState.empty), .{ .template = true });
- pub const LOADING = bridge.property(@intFromEnum(FileReader.ReadyState.loading), .{ .template = true });
- pub const DONE = bridge.property(@intFromEnum(FileReader.ReadyState.done), .{ .template = true });
+ pub const EMPTY = bridge.property(@backingInt(FileReader.ReadyState.empty), .{ .template = true });
+ pub const LOADING = bridge.property(@backingInt(FileReader.ReadyState.loading), .{ .template = true });
+ pub const DONE = bridge.property(@backingInt(FileReader.ReadyState.done), .{ .template = true });
// Properties
pub const readyState = bridge.accessor(FileReader.getReadyState, null, .{});
diff --git a/src/browser/webapi/History.zig b/src/browser/webapi/History.zig
index 67717c23a..08c21f8d7 100644
--- a/src/browser/webapi/History.zig
+++ b/src/browser/webapi/History.zig
@@ -56,7 +56,7 @@ pub fn pushState(_: *History, state: js.Value, _: ?[]const u8, _url: ?[]const u8
const url = if (_url) |u|
try @import("../URL.zig").resolve(arena.allocator(), frame.url, u, .{})
else
- try arena.dupeZ(u8, frame.url);
+ try arena.dupeSentinel(u8, frame.url, 0);
const json = state.toJson(arena.allocator()) catch return error.DataClone;
_ = try session.navigation.pushEntry(url, .{ .source = .history, .value = json }, frame, true);
@@ -80,7 +80,7 @@ fn replaceState(_: *History, state: js.Value, _: ?[]const u8, _url: ?[]const u8,
const url = if (_url) |u|
try @import("../URL.zig").resolve(arena.allocator(), frame.url, u, .{})
else
- try arena.dupeZ(u8, frame.url);
+ try arena.dupeSentinel(u8, frame.url, 0);
const json = state.toJson(arena.allocator()) catch return error.DataClone;
_ = try session.navigation.replaceEntry(url, .{ .source = .history, .value = json }, frame, true);
diff --git a/src/browser/webapi/Location.zig b/src/browser/webapi/Location.zig
index 488e19ca7..5e08c6ecd 100644
--- a/src/browser/webapi/Location.zig
+++ b/src/browser/webapi/Location.zig
@@ -114,7 +114,7 @@ fn setHash(_: *const Location, hash: []const u8, frame: *Frame) !void {
}
// Scratch only: scheduleNavigation dupes the URL into its own arena
// synchronously, so the local arena suffices.
- break :blk try std.fmt.allocPrint(frame.local_arena, "#{s}", .{hash});
+ break :blk try frame.local_arena.print("#{s}", .{hash});
};
// Per the Location hash setter, when the fragment doesn't change no
diff --git a/src/browser/webapi/Navigator.zig b/src/browser/webapi/Navigator.zig
index 4c09aac52..720b5a7dd 100644
--- a/src/browser/webapi/Navigator.zig
+++ b/src/browser/webapi/Navigator.zig
@@ -122,7 +122,7 @@ pub fn getGlobalPrivacyControl(_: *const Navigator) bool {
}
pub fn getPlatform(_: *const Navigator) []const u8 {
- return switch (builtin.os.tag) {
+ return switch (builtin.target.os.tag) {
.macos => "MacIntel",
.windows => "Win32",
.linux => "Linux x86_64",
diff --git a/src/browser/webapi/NavigatorUAData.zig b/src/browser/webapi/NavigatorUAData.zig
index 37fce6afd..0d4c371da 100644
--- a/src/browser/webapi/NavigatorUAData.zig
+++ b/src/browser/webapi/NavigatorUAData.zig
@@ -93,7 +93,7 @@ fn brandList() []const Brand {
}
fn uaPlatform() []const u8 {
- return switch (builtin.os.tag) {
+ return switch (builtin.target.os.tag) {
.macos => "macOS",
.windows => "Windows",
.linux => "Linux",
@@ -103,7 +103,7 @@ fn uaPlatform() []const u8 {
}
fn uaArchitecture() []const u8 {
- return switch (builtin.cpu.arch) {
+ return switch (builtin.target.cpu.arch) {
.x86, .x86_64 => "x86",
.aarch64, .aarch64_be, .arm, .armeb => "arm",
else => "",
@@ -111,7 +111,7 @@ fn uaArchitecture() []const u8 {
}
fn uaBitness() []const u8 {
- return switch (builtin.cpu.arch) {
+ return switch (builtin.target.cpu.arch) {
.x86_64, .aarch64, .aarch64_be, .powerpc64, .powerpc64le, .riscv64 => "64",
else => "32",
};
diff --git a/src/browser/webapi/PerformanceObserver.zig b/src/browser/webapi/PerformanceObserver.zig
index b8d49f809..5aacb45b3 100644
--- a/src/browser/webapi/PerformanceObserver.zig
+++ b/src/browser/webapi/PerformanceObserver.zig
@@ -112,10 +112,10 @@ pub fn observe(self: *PerformanceObserver, maybe_options: ?ObserveOptions) !void
// Update entries.
var interests: u16 = 0;
for (entry_types) |entry_type| {
- const fields = @typeInfo(Performance.Entry.Type.Enum).@"enum".fields;
- inline for (fields) |field| {
- if (std.mem.eql(u8, field.name, entry_type)) {
- const flag = @as(u16, 1) << @as(u16, field.value);
+ const info = @typeInfo(Performance.Entry.Type.Enum).@"enum";
+ inline for (info.field_names, info.field_values) |field_name, field_value| {
+ if (std.mem.eql(u8, field_name, entry_type)) {
+ const flag = @as(u16, 1) << @as(u16, field_value);
interests |= flag;
}
}
@@ -182,7 +182,7 @@ pub fn interested(
}
pub fn interestedIn(self: *const PerformanceObserver, kind: Performance.Entry.Type.Enum) bool {
- const flag = @as(u16, 1) << @intCast(@intFromEnum(kind));
+ const flag = @as(u16, 1) << @intCast(@backingInt(kind));
return self._interests & flag != 0;
}
diff --git a/src/browser/webapi/Sanitizer.zig b/src/browser/webapi/Sanitizer.zig
index 2472f91d9..40a22d750 100644
--- a/src/browser/webapi/Sanitizer.zig
+++ b/src/browser/webapi/Sanitizer.zig
@@ -127,7 +127,7 @@ const NameContext = struct {
pub fn hash(_: NameContext, key: Name) u32 {
var hasher = std.hash.Wyhash.init(0);
hasher.update(key.name.str());
- hasher.update(&.{@intFromEnum(std.meta.activeTag(key.namespace))});
+ hasher.update(&.{@backingInt(std.meta.activeTag(key.namespace))});
if (key.namespace == .other) {
hasher.update(key.namespace.other);
}
@@ -1181,7 +1181,7 @@ fn sanitize(self: *const Sanitizer, root: *Node, safe: bool, frame: *Frame) !voi
fn touch(touched: *std.ArrayList(*Node), parent: *Node, arena: Allocator) !void {
// Siblings are removed one after another, so this catches most repeats.
// Those it misses just get a second, no-op, merge.
- if (touched.getLastOrNull() != parent) {
+ if (touched.last() != parent) {
try touched.append(arena, parent);
}
}
diff --git a/src/browser/webapi/ServiceWorkerGlobalScope.zig b/src/browser/webapi/ServiceWorkerGlobalScope.zig
index a88091470..64f03a49e 100644
--- a/src/browser/webapi/ServiceWorkerGlobalScope.zig
+++ b/src/browser/webapi/ServiceWorkerGlobalScope.zig
@@ -93,7 +93,7 @@ fn init(
const arena = try session.getArena(.small, "ServiceWorker");
errdefer arena.release();
- const owned_url = try arena.dupeZ(u8, script_url);
+ const owned_url = try arena.dupeSentinel(u8, script_url, 0);
const frame_id = session.nextFrameId();
const loader_id = session.nextLoaderId();
diff --git a/src/browser/webapi/SharedWorker.zig b/src/browser/webapi/SharedWorker.zig
index cb9d7072f..e0bd6847f 100644
--- a/src/browser/webapi/SharedWorker.zig
+++ b/src/browser/webapi/SharedWorker.zig
@@ -68,7 +68,7 @@ pub fn init(url: []const u8, name_or_options: ?NameOrOpts, frame: *Frame) !*Shar
const scope = blk: {
const session = frame._session;
// \x00 can appear in neither a URL nor a name
- const lookup_key = try std.fmt.allocPrint(frame.call_arena, "{s}\x00{s}", .{ resolved_url, options.name });
+ const lookup_key = try frame.call_arena.print("{s}\x00{s}", .{ resolved_url, options.name });
if (session.shared_workers.get(lookup_key)) |existing| {
break :blk existing;
}
diff --git a/src/browser/webapi/SharedWorkerGlobalScope.zig b/src/browser/webapi/SharedWorkerGlobalScope.zig
index 06a8e1bed..25816d05d 100644
--- a/src/browser/webapi/SharedWorkerGlobalScope.zig
+++ b/src/browser/webapi/SharedWorkerGlobalScope.zig
@@ -63,7 +63,7 @@ pub fn init(frame: *Frame, url: [:0]const u8, name: []const u8, worker_type: Wor
const arena = try session.getArena(.small, "SharedWorker");
errdefer arena.release();
- const owned_url = try arena.dupeZ(u8, url);
+ const owned_url = try arena.dupeSentinel(u8, url, 0);
const frame_id = session.nextFrameId();
const loader_id = session.nextLoaderId();
const self = try WorkerGlobalScope.init(
diff --git a/src/browser/webapi/SubtleCrypto.zig b/src/browser/webapi/SubtleCrypto.zig
index 1c4118e5c..413209b3a 100644
--- a/src/browser/webapi/SubtleCrypto.zig
+++ b/src/browser/webapi/SubtleCrypto.zig
@@ -286,13 +286,13 @@ fn exportJwk(key: *CryptoKey, exec: *const Execution) !js.Promise {
// The `alg` registry value depends on the algorithm and key length.
const alg: []const u8 = switch (key._type) {
- .aes => try std.fmt.allocPrint(exec.local_arena, "A{d}{s}", .{
+ .aes => try exec.local_arena.print("A{d}{s}", .{
key._key.len * 8,
key._algorithm.name[4..], // strip "AES-"
}),
.hmac => blk: {
const hash: []const u8 = key._algorithm.hash orelse "SHA-";
- break :blk try std.fmt.allocPrint(exec.local_arena, "HS{s}", .{hash[4..]}); // strip "SHA-"
+ break :blk try exec.local_arena.print("HS{s}", .{hash[4..]}); // strip "SHA-"
},
else => {
log.debug(.not_implemented, "SubtleCrypto.exportKey", .{ .format = "jwk", .type = key._type });
diff --git a/src/browser/webapi/URL.zig b/src/browser/webapi/URL.zig
index 8f574768c..6509cec04 100644
--- a/src/browser/webapi/URL.zig
+++ b/src/browser/webapi/URL.zig
@@ -154,7 +154,7 @@ fn setHost(self: *URL, value: []const u8) void {
pub fn getPort(self: *URL) []const u8 {
const port = U.urlGetPort(self._url) orelse return "";
- return std.fmt.bufPrint(&self._port, "{d}", .{port}) catch unreachable;
+ return std.mem.print(&self._port, "{d}", .{port}) catch unreachable;
}
/// Spec requires us to silently ignore errors of this setter.
diff --git a/src/browser/webapi/URLPattern.zig b/src/browser/webapi/URLPattern.zig
index e793d73ba..ecac70368 100644
--- a/src/browser/webapi/URLPattern.zig
+++ b/src/browser/webapi/URLPattern.zig
@@ -312,9 +312,9 @@ fn match(self: *const URLPattern, input: ?Input, base_url: ?[]const u8, exec: *c
// The IDL conversion yields a fresh dictionary; that, not the
// caller's object, is what ends up in result.inputs.
const dict = local.newObject();
- inline for (@typeInfo(Init).@"struct".fields) |f| {
- if (@field(dict_init, f.name)) |v| {
- _ = try dict.set(f.name, v, .{});
+ inline for (@typeInfo(Init).@"struct".field_names) |field_name| {
+ if (@field(dict_init, field_name)) |v| {
+ _ = try dict.set(field_name, v, .{});
}
}
inputs = local.newArray(1);
@@ -357,7 +357,7 @@ fn match(self: *const URLPattern, input: ?Input, base_url: ?[]const u8, exec: *c
const groups = local.newObject();
var key_buf: [16]u8 = undefined;
for (component.group_names, 1..) |group_name, i| {
- const key = std.fmt.bufPrint(&key_buf, "{d}", .{i}) catch unreachable;
+ const key = std.mem.print(&key_buf, "{d}", .{i}) catch unreachable;
_ = try groups.set(group_name, try exec_result.get(key), .{});
}
@field(result, name) = .{ .input = value, .groups = groups };
@@ -874,7 +874,7 @@ fn urlHost(url: *const U.Url) []const u8 {
fn urlPort(arena: Allocator, url: *const U.Url) Error![]const u8 {
const port = U.urlGetPort(url) orelse return "";
- return std.fmt.allocPrint(arena, "{d}", .{port});
+ return arena.print("{d}", .{port});
}
fn urlPath(url: *const U.Url) []const u8 {
@@ -1005,7 +1005,7 @@ fn canonicalizePort(arena: Allocator, value: []const u8, protocol: ?[]const u8)
if (digits == 0) {
return error.TypeError;
}
- const serialized = try std.fmt.allocPrint(arena, "{d}", .{port});
+ const serialized = try arena.print("{d}", .{port});
if (protocol) |p| {
if (defaultPort(p)) |default| {
if (std.mem.eql(u8, default, serialized)) {
@@ -1546,7 +1546,7 @@ const Parser = struct {
if (name_token) |t| {
name = t.value;
} else if (regexp_or_wildcard != null) {
- name = try std.fmt.allocPrint(self.env.arena, "{d}", .{self.next_numeric_name});
+ name = try self.env.arena.print("{d}", .{self.next_numeric_name});
self.next_numeric_name += 1;
}
for (self.parts.items) |part| {
diff --git a/src/browser/webapi/WebDriver.zig b/src/browser/webapi/WebDriver.zig
index 0e472abcb..e5486af2e 100644
--- a/src/browser/webapi/WebDriver.zig
+++ b/src/browser/webapi/WebDriver.zig
@@ -173,10 +173,17 @@ const ActionSequence = struct {
frame.js.localScope(&ls);
defer ls.deinit();
- errdefer |err| {
+ performSources(self, &ls) catch |err| {
ls.toLocal(self.resolver).reject("WebDriver.actionSequence", ls.local.newString(@errorName(err)));
- }
+ return err;
+ };
+
+ ls.toLocal(self.resolver).resolve("WebDriver.actionSequence", {});
+ return null;
+ }
+ fn performSources(self: *ActionSequence, ls: *js.Local.Scope) !void {
+ const frame = self.frame;
const sources = self.sources.local(&ls.local).toArray();
for (0..sources.len()) |i| {
const source_val = try sources.get(@intCast(i));
@@ -194,9 +201,6 @@ const ActionSequence = struct {
}
// "none" sources only carry pauses, which have no observable effect here.
}
-
- ls.toLocal(self.resolver).resolve("WebDriver.actionSequence", {});
- return null;
}
fn finalize(ptr: *anyopaque) void {
diff --git a/src/browser/webapi/cache/Cache.zig b/src/browser/webapi/cache/Cache.zig
index 7180f02bd..1c64565e7 100644
--- a/src/browser/webapi/cache/Cache.zig
+++ b/src/browser/webapi/cache/Cache.zig
@@ -113,7 +113,7 @@ fn keys(self: *Cache, exec: *const Execution) !js.Promise {
};
for (entries) |entry| {
- const url = try exec.call_arena.dupeZ(u8, entry.url);
+ const url = try exec.call_arena.dupeSentinel(u8, entry.url, 0);
const request = try Request.init(.{ .url = url }, null, exec);
request.acquireRef();
requests.appendAssumeCapacity(request);
@@ -324,7 +324,7 @@ fn toEntry(allocator: Allocator, url: []const u8, response: *const Response, bod
kv.* = .{ try arena.dupe(u8, header.name.str()), try arena.dupe(u8, header.value.str()) };
}
- entry.response_url = try arena.dupeZ(u8, response._url);
+ entry.response_url = try arena.dupeSentinel(u8, response._url, 0);
entry.status = response._status;
entry.status_text = try arena.dupe(u8, response._status_text);
entry.response_type = response._type;
@@ -343,7 +343,7 @@ fn toResponse(entry: *const Store.Entry, exec: *const Execution) !*Response {
._arena = arena,
._status = entry.status,
._status_text = try arena.dupe(u8, entry.status_text),
- ._url = try arena.dupeZ(u8, entry.response_url),
+ ._url = try arena.dupeSentinel(u8, entry.response_url, 0),
._body = .{ .bytes = try arena.dupe(u8, entry.body) },
._type = entry.response_type,
._is_redirected = entry.is_redirected,
diff --git a/src/browser/webapi/canvas/WebGLRenderingContext.zig b/src/browser/webapi/canvas/WebGLRenderingContext.zig
index f75c0e0ad..784c13ca9 100644
--- a/src/browser/webapi/canvas/WebGLRenderingContext.zig
+++ b/src/browser/webapi/canvas/WebGLRenderingContext.zig
@@ -79,15 +79,9 @@ const Extension = union(enum) {
/// Reified enum type from the fields of this union.
const Kind = blk: {
- const info = @typeInfo(Extension).@"union";
- const fields = info.fields;
- const Tag = std.math.IntFittingRange(0, if (fields.len == 0) 0 else fields.len - 1);
- var names: [fields.len][:0]const u8 = undefined;
- for (fields, 0..) |field, i| {
- names[i] = field.name;
- }
-
- break :blk @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, fields.len));
+ const names = @typeInfo(Extension).@"union".field_names;
+ const Tag = std.math.IntFittingRange(0, if (names.len == 0) 0 else names.len - 1);
+ break :blk @Enum(Tag, .exhaustive, names, &std.simd.iota(Tag, names.len));
};
/// Returns the `Extension.Kind` by its name.
@@ -98,9 +92,9 @@ const Extension = union(enum) {
const kvs = comptime build_kvs: {
const T = Extension.Kind;
const EnumKV = struct { []const u8, T };
- var kvs_array: [@typeInfo(T).@"enum".fields.len]EnumKV = undefined;
- for (@typeInfo(T).@"enum".fields, 0..) |enumField, i| {
- kvs_array[i] = .{ enumField.name, @field(T, enumField.name) };
+ var kvs_array: [@typeInfo(T).@"enum".field_names.len]EnumKV = undefined;
+ for (@typeInfo(T).@"enum".field_names, 0..) |field_name, i| {
+ kvs_array[i] = .{ field_name, @field(T, field_name) };
}
break :build_kvs kvs_array[0..];
};
@@ -180,7 +174,7 @@ fn getExtension(_: *const WebGLRenderingContext, name: []const u8, frame: *Frame
/// Returns a list of all the supported WebGL extensions.
fn getSupportedExtensions(_: *const WebGLRenderingContext) []const []const u8 {
- return std.meta.fieldNames(Extension.Kind);
+ return @typeInfo(Extension.Kind).@"enum".field_names;
}
pub const JsApi = struct {
diff --git a/src/browser/webapi/canvas/context2d.zig b/src/browser/webapi/canvas/context2d.zig
index 6ae6de15f..68212fb0a 100644
--- a/src/browser/webapi/canvas/context2d.zig
+++ b/src/browser/webapi/canvas/context2d.zig
@@ -66,7 +66,7 @@ pub const State = struct {
stroke_style: Style = .{ .color = color.RGBA.Named.black },
font_size: f64 = 10,
- font_buf: [font_capacity]u8 = default_font.* ++ [_]u8{0} ** (font_capacity - default_font.len),
+ font_buf: [font_capacity]u8 = default_font.* ++ @as([font_capacity - default_font.len]u8, @splat(0)),
font_len: u16 = default_font.len,
font_overflow: ?[]const u8 = null,
diff --git a/src/browser/webapi/collections/iterator.zig b/src/browser/webapi/collections/iterator.zig
index 51d015f6c..f73fda75e 100644
--- a/src/browser/webapi/collections/iterator.zig
+++ b/src/browser/webapi/collections/iterator.zig
@@ -94,7 +94,7 @@ fn reflect(comptime Inner: type, comptime field: ?[]const u8) Reflect {
const R = fn_info.return_type.?;
const has_error_return = @typeInfo(R) == .error_union;
// The executor type is the last parameter of inner.next (after self)
- const Executor = fn_info.params[1].type.?;
+ const Executor = fn_info.param_types[1].?;
return .{
.has_error_return = has_error_return,
.ValueType = ValueType(unwrapOptional(unwrapError(R)), field),
@@ -121,9 +121,9 @@ fn unwrapOptional(comptime T: type) type {
fn ValueType(comptime R: type, comptime field_: ?[]const u8) type {
const field = field_ orelse return R;
- inline for (@typeInfo(R).@"struct".fields) |f| {
- if (comptime std.mem.eql(u8, f.name, field)) {
- return f.type;
+ inline for (@typeInfo(R).@"struct".field_names, @typeInfo(R).@"struct".field_types) |field_name, field_type| {
+ if (comptime std.mem.eql(u8, field_name, field)) {
+ return field_type;
}
}
@compileError("Unknown EntryIterator field " ++ @typeName(R) ++ "." ++ field);
diff --git a/src/browser/webapi/collections/node_live.zig b/src/browser/webapi/collections/node_live.zig
index 4c88e30e9..c4f1f3366 100644
--- a/src/browser/webapi/collections/node_live.zig
+++ b/src/browser/webapi/collections/node_live.zig
@@ -77,7 +77,7 @@ const Filters = union(Mode) {
fn TypeOf(comptime mode: Mode) type {
@setEvalBranchQuota(10_000);
- return std.meta.fieldInfo(Filters, mode).type;
+ return @FieldType(Filters, @tagName(mode));
}
};
diff --git a/src/browser/webapi/css/CSSRule.zig b/src/browser/webapi/css/CSSRule.zig
index 683c5524d..1eb25aa5f 100644
--- a/src/browser/webapi/css/CSSRule.zig
+++ b/src/browser/webapi/css/CSSRule.zig
@@ -68,7 +68,7 @@ pub fn getType(self: *const CSSRule) u16 {
// `@layer` rules postdate the legacy numeric type constants, so
// their `type` is 0 (CSSOM §6.4.1) — same as unknown at-rules.
.layer, .unknown => 0,
- else => @as(u16, @intFromEnum(std.meta.activeTag(self._type))) + 1,
+ else => @as(u16, @backingInt(std.meta.activeTag(self._type))) + 1,
};
}
diff --git a/src/browser/webapi/css/CSSStyleDeclaration.zig b/src/browser/webapi/css/CSSStyleDeclaration.zig
index ea4b0bce3..911171ee8 100644
--- a/src/browser/webapi/css/CSSStyleDeclaration.zig
+++ b/src/browser/webapi/css/CSSStyleDeclaration.zig
@@ -195,7 +195,7 @@ fn resolvedDimension(element: *Element, dimension: enum { width, height }, frame
.width => element.boxAxis(frame, .width),
.height => element.boxAxis(frame, .height),
};
- return std.fmt.allocPrint(frame.local_arena, "{d}px", .{value}) catch "auto";
+ return frame.local_arena.print("{d}px", .{value}) catch "auto";
}
pub fn getPropertyPriority(self: *const CSSStyleDeclaration, property_name: []const u8, frame: *Frame) []const u8 {
diff --git a/src/browser/webapi/element/DOMStringMap.zig b/src/browser/webapi/element/DOMStringMap.zig
index 9bdaedb8c..de1433c3b 100644
--- a/src/browser/webapi/element/DOMStringMap.zig
+++ b/src/browser/webapi/element/DOMStringMap.zig
@@ -162,7 +162,7 @@ pub const JsApi = struct {
}
fn indexName(idx: u32, frame: *Frame) !String {
var buf: [15]u8 = undefined;
- const name = std.fmt.bufPrint(&buf, "data-{d}", .{idx}) catch unreachable;
+ const name = std.mem.print(&buf, "data-{d}", .{idx}) catch unreachable;
return String.init(frame.local_arena, name, .{});
}
diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zig
index 83c4d7b52..a1715b608 100644
--- a/src/browser/webapi/element/Html.zig
+++ b/src/browser/webapi/element/Html.zig
@@ -511,7 +511,7 @@ pub fn getAccessKeyLabel(self: *HtmlElement, frame: *Frame) ![]const u8 {
if (codepoints != 1) {
return "";
}
- return std.fmt.allocPrint(frame.local_arena, "Alt+{s}", .{value});
+ return frame.local_arena.print("Alt+{s}", .{value});
}
pub fn getPopover(self: *HtmlElement) ?[]const u8 {
@@ -555,7 +555,7 @@ pub fn getTabIndex(self: *HtmlElement) i32 {
pub fn setTabIndex(self: *HtmlElement, value: i32, frame: *Frame) !void {
var buf: [12]u8 = undefined;
- const str = std.fmt.bufPrint(&buf, "{d}", .{value}) catch unreachable;
+ const str = std.mem.print(&buf, "{d}", .{value}) catch unreachable;
try self.asElement().setAttributeSafe(comptime .wrap("tabindex"), .wrap(str), frame);
}
diff --git a/src/browser/webapi/element/html/Image.zig b/src/browser/webapi/element/html/Image.zig
index b1b05d24a..62188c35b 100644
--- a/src/browser/webapi/element/html/Image.zig
+++ b/src/browser/webapi/element/html/Image.zig
@@ -53,11 +53,11 @@ pub fn constructor(w_: ?u32, h_: ?u32, frame: *Frame) !*Image {
const el = node.as(Element);
if (w_) |w| blk: {
- const w_string = std.fmt.bufPrint(&frame.buf, "{d}", .{w}) catch break :blk;
+ const w_string = std.mem.print(&frame.buf, "{d}", .{w}) catch break :blk;
try el.setAttributeSafe(comptime .wrap("width"), .wrap(w_string), frame);
}
if (h_) |h| blk: {
- const h_string = std.fmt.bufPrint(&frame.buf, "{d}", .{h}) catch break :blk;
+ const h_string = std.mem.print(&frame.buf, "{d}", .{h}) catch break :blk;
try el.setAttributeSafe(comptime .wrap("height"), .wrap(h_string), frame);
}
return el.as(Image);
diff --git a/src/browser/webapi/element/html/Input.zig b/src/browser/webapi/element/html/Input.zig
index 418848f5b..8c55eef80 100644
--- a/src/browser/webapi/element/html/Input.zig
+++ b/src/browser/webapi/element/html/Input.zig
@@ -340,7 +340,7 @@ fn getValueForJS(self: *const Input, frame: *Frame) ![]const u8 {
if (fl._files.len == 0) {
return "";
}
- return try std.fmt.allocPrint(frame.local_arena, "C:\\fakepath\\{s}", .{fl._files[0]._name});
+ return try frame.local_arena.print("C:\\fakepath\\{s}", .{fl._files[0]._name});
}
fn getValidationMessage(self: *Input, frame: *Frame) []const u8 {
@@ -437,7 +437,7 @@ pub fn suffersPatternMismatch(self: *const Input, frame: *Frame) bool {
try_catch.init(&ls.local);
defer try_catch.deinit();
- const wrapped = std.fmt.allocPrint(frame.call_arena, "^(?:{s})$", .{pattern}) catch return false;
+ const wrapped = frame.call_arena.print("^(?:{s})$", .{pattern}) catch return false;
const re = js.RegExp.init(&ls.local, wrapped, js.RegExp.Flag.unicode_sets) catch return false;
const matched = re.match(value) catch return false;
@@ -966,7 +966,7 @@ fn valueToNumber(typ: Type, value: []const u8) ?f64 {
fn numberToValue(typ: Type, number: f64, buf: []u8) ?[]const u8 {
if (std.math.isNan(number) or @abs(number) > max_time_value) return null;
switch (typ) {
- .number, .range => return std.fmt.bufPrint(buf, "{d}", .{number}) catch null,
+ .number, .range => return std.mem.print(buf, "{d}", .{number}) catch null,
.date => {
const days: i64 = @floor(number / ms_per_day);
return formatDate(civilFromDays(days), buf);
@@ -975,7 +975,7 @@ fn numberToValue(typ: Type, number: f64, buf: []u8) ?[]const u8 {
const months: i64 = @floor(number);
const year = 1970 + @divFloor(months, 12);
if (year < 1) return null;
- return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}", .{ @as(u64, @intCast(year)), @as(u64, @intCast(@mod(months, 12) + 1)) }) catch null;
+ return std.mem.print(buf, "{d:0>4}-{d:0>2}", .{ @as(u64, @intCast(year)), @as(u64, @intCast(@mod(months, 12) + 1)) }) catch null;
},
.week => {
const days: i64 = @floor(number / ms_per_day);
@@ -984,7 +984,7 @@ fn numberToValue(typ: Type, number: f64, buf: []u8) ?[]const u8 {
const year = civilFromDays(thursday).year;
if (year < 1) return null;
const week = @divFloor(thursday - isoWeekMonday(year, 1), 7) + 1;
- return std.fmt.bufPrint(buf, "{d:0>4}-W{d:0>2}", .{ @as(u64, @intCast(year)), @as(u64, @intCast(week)) }) catch null;
+ return std.mem.print(buf, "{d:0>4}-W{d:0>2}", .{ @as(u64, @intCast(year)), @as(u64, @intCast(week)) }) catch null;
},
.time => return formatTime(@mod(number, ms_per_day), buf),
.@"datetime-local" => {
@@ -1034,7 +1034,7 @@ const Civil = struct { year: i64, month: i64, day: i64 };
fn formatDate(civil: Civil, buf: []u8) ?[]const u8 {
if (civil.year < 1) return null;
- return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}", .{ @as(u64, @intCast(civil.year)), @as(u64, @intCast(civil.month)), @as(u64, @intCast(civil.day)) }) catch null;
+ return std.mem.print(buf, "{d:0>4}-{d:0>2}-{d:0>2}", .{ @as(u64, @intCast(civil.year)), @as(u64, @intCast(civil.month)), @as(u64, @intCast(civil.day)) }) catch null;
}
/// Normalized time string: seconds only when needed, fraction always 3 digits.
@@ -1045,12 +1045,12 @@ fn formatTime(ms_in_day: f64, buf: []u8) ?[]const u8 {
const second = (total / 1000) % 60;
const millis = total % 1000;
if (second == 0 and millis == 0) {
- return std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}", .{ hour, minute }) catch null;
+ return std.mem.print(buf, "{d:0>2}:{d:0>2}", .{ hour, minute }) catch null;
}
if (millis == 0) {
- return std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hour, minute, second }) catch null;
+ return std.mem.print(buf, "{d:0>2}:{d:0>2}:{d:0>2}", .{ hour, minute, second }) catch null;
}
- return std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}", .{ hour, minute, second, millis }) catch null;
+ return std.mem.print(buf, "{d:0>2}:{d:0>2}:{d:0>2}.{d:0>3}", .{ hour, minute, second, millis }) catch null;
}
// Howard Hinnant's civil-from-days and days-from-civil.
@@ -1364,7 +1364,7 @@ fn snapToStep(value: f64, min: f64, max: f64, step_base: f64, step_attr: []const
/// Format an f64 to its shortest decimal representation, arena-allocated.
fn formatFloat(arena: std.mem.Allocator, value: f64) ![]const u8 {
- return std.fmt.allocPrint(arena, "{d}", .{value});
+ return arena.print("{d}", .{value});
}
/// Parse a slice that must be ALL ASCII digits into a u32. Returns null if any non-digit or empty.
diff --git a/src/browser/webapi/element/html/Media.zig b/src/browser/webapi/element/html/Media.zig
index aef99e9a1..8f95667fc 100644
--- a/src/browser/webapi/element/html/Media.zig
+++ b/src/browser/webapi/element/html/Media.zig
@@ -204,11 +204,11 @@ pub fn getDuration(_: *const Media) f64 {
}
fn getReadyState(self: *const Media) u16 {
- return @intFromEnum(self._ready_state);
+ return @backingInt(self._ready_state);
}
fn getNetworkState(self: *const Media) u16 {
- return @intFromEnum(self._network_state);
+ return @backingInt(self._network_state);
}
fn getEnded(_: *const Media) bool {
@@ -277,16 +277,16 @@ pub const JsApi = struct {
pub const crossOrigin = reflect.enumerated("crossorigin", &.{ "anonymous", "use-credentials" }, .{ .missing = null, .nullable = true, .invalid = "anonymous" });
pub const defaultMuted = reflect.boolean("muted");
- pub const NETWORK_EMPTY = bridge.property(@intFromEnum(NetworkState.NETWORK_EMPTY), .{ .template = true });
- pub const NETWORK_IDLE = bridge.property(@intFromEnum(NetworkState.NETWORK_IDLE), .{ .template = true });
- pub const NETWORK_LOADING = bridge.property(@intFromEnum(NetworkState.NETWORK_LOADING), .{ .template = true });
- pub const NETWORK_NO_SOURCE = bridge.property(@intFromEnum(NetworkState.NETWORK_NO_SOURCE), .{ .template = true });
+ pub const NETWORK_EMPTY = bridge.property(@backingInt(NetworkState.NETWORK_EMPTY), .{ .template = true });
+ pub const NETWORK_IDLE = bridge.property(@backingInt(NetworkState.NETWORK_IDLE), .{ .template = true });
+ pub const NETWORK_LOADING = bridge.property(@backingInt(NetworkState.NETWORK_LOADING), .{ .template = true });
+ pub const NETWORK_NO_SOURCE = bridge.property(@backingInt(NetworkState.NETWORK_NO_SOURCE), .{ .template = true });
- pub const HAVE_NOTHING = bridge.property(@intFromEnum(ReadyState.HAVE_NOTHING), .{ .template = true });
- pub const HAVE_METADATA = bridge.property(@intFromEnum(ReadyState.HAVE_METADATA), .{ .template = true });
- pub const HAVE_CURRENT_DATA = bridge.property(@intFromEnum(ReadyState.HAVE_CURRENT_DATA), .{ .template = true });
- pub const HAVE_FUTURE_DATA = bridge.property(@intFromEnum(ReadyState.HAVE_FUTURE_DATA), .{ .template = true });
- pub const HAVE_ENOUGH_DATA = bridge.property(@intFromEnum(ReadyState.HAVE_ENOUGH_DATA), .{ .template = true });
+ pub const HAVE_NOTHING = bridge.property(@backingInt(ReadyState.HAVE_NOTHING), .{ .template = true });
+ pub const HAVE_METADATA = bridge.property(@backingInt(ReadyState.HAVE_METADATA), .{ .template = true });
+ pub const HAVE_CURRENT_DATA = bridge.property(@backingInt(ReadyState.HAVE_CURRENT_DATA), .{ .template = true });
+ pub const HAVE_FUTURE_DATA = bridge.property(@backingInt(ReadyState.HAVE_FUTURE_DATA), .{ .template = true });
+ pub const HAVE_ENOUGH_DATA = bridge.property(@backingInt(ReadyState.HAVE_ENOUGH_DATA), .{ .template = true });
pub const src = bridge.accessor(Media.getSrc, Media.setSrc, .{ .ce_reactions = true });
pub const currentSrc = bridge.accessor(Media.getSrc, null, .{});
diff --git a/src/browser/webapi/element/html/Track.zig b/src/browser/webapi/element/html/Track.zig
index 61a309db1..5913132e7 100644
--- a/src/browser/webapi/element/html/Track.zig
+++ b/src/browser/webapi/element/html/Track.zig
@@ -61,10 +61,10 @@ pub const JsApi = struct {
pub const kind = reflect.enumerated("kind", &.{ "subtitles", "captions", "descriptions", "chapters", "metadata" }, .{ .missing = "subtitles", .invalid = "metadata" });
- pub const NONE = bridge.property(@as(u16, @intFromEnum(ReadyState.none)), .{ .template = true });
- pub const LOADING = bridge.property(@as(u16, @intFromEnum(ReadyState.loading)), .{ .template = true });
- pub const LOADED = bridge.property(@as(u16, @intFromEnum(ReadyState.loaded)), .{ .template = true });
- pub const ERROR = bridge.property(@as(u16, @intFromEnum(ReadyState.@"error")), .{ .template = true });
+ pub const NONE = bridge.property(@as(u16, @backingInt(ReadyState.none)), .{ .template = true });
+ pub const LOADING = bridge.property(@as(u16, @backingInt(ReadyState.loading)), .{ .template = true });
+ pub const LOADED = bridge.property(@as(u16, @backingInt(ReadyState.loaded)), .{ .template = true });
+ pub const ERROR = bridge.property(@as(u16, @backingInt(ReadyState.@"error")), .{ .template = true });
};
const testing = @import("../../../../testing.zig");
diff --git a/src/browser/webapi/element/reflection.zig b/src/browser/webapi/element/reflection.zig
index 31070b0de..5db7634f5 100644
--- a/src/browser/webapi/element/reflection.zig
+++ b/src/browser/webapi/element/reflection.zig
@@ -291,7 +291,7 @@ pub fn setDouble(el: *Element, comptime attr: []const u8, value: f64, frame: *Fr
fn setInteger(el: *Element, comptime attr: []const u8, value: i64, frame: *Frame) !void {
var buf: [24]u8 = undefined;
- const str = std.fmt.bufPrint(&buf, "{d}", .{value}) catch unreachable;
+ const str = std.mem.print(&buf, "{d}", .{value}) catch unreachable;
try el.setAttributeSafe(.wrap(attr), .wrap(str), frame);
}
diff --git a/src/browser/webapi/event/KeyboardEvent.zig b/src/browser/webapi/event/KeyboardEvent.zig
index 570728c4e..6fcc0c838 100644
--- a/src/browser/webapi/event/KeyboardEvent.zig
+++ b/src/browser/webapi/event/KeyboardEvent.zig
@@ -135,11 +135,11 @@ pub const Key = union(enum) {
pub fn fromString(allocator: std.mem.Allocator, str: []const u8) !Key {
const key_type_info = @typeInfo(Key);
- inline for (key_type_info.@"union".fields) |field| {
- if (comptime std.mem.eql(u8, field.name, "standard")) continue;
+ inline for (key_type_info.@"union".field_names) |field_name| {
+ if (comptime std.mem.eql(u8, field_name, "standard")) continue;
- if (std.mem.eql(u8, field.name, str)) {
- return @unionInit(Key, field.name, {});
+ if (std.mem.eql(u8, field_name, str)) {
+ return @unionInit(Key, field_name, {});
}
}
@@ -486,10 +486,10 @@ pub const JsApi = struct {
pub const getModifierState = bridge.function(KeyboardEvent.getModifierState, .{});
pub const initKeyboardEvent = bridge.function(KeyboardEvent.initKeyboardEvent, .{});
- pub const DOM_KEY_LOCATION_STANDARD = bridge.property(@intFromEnum(Location.DOM_KEY_LOCATION_STANDARD), .{ .template = true });
- pub const DOM_KEY_LOCATION_LEFT = bridge.property(@intFromEnum(Location.DOM_KEY_LOCATION_LEFT), .{ .template = true });
- pub const DOM_KEY_LOCATION_RIGHT = bridge.property(@intFromEnum(Location.DOM_KEY_LOCATION_RIGHT), .{ .template = true });
- pub const DOM_KEY_LOCATION_NUMPAD = bridge.property(@intFromEnum(Location.DOM_KEY_LOCATION_NUMPAD), .{ .template = true });
+ pub const DOM_KEY_LOCATION_STANDARD = bridge.property(@backingInt(Location.DOM_KEY_LOCATION_STANDARD), .{ .template = true });
+ pub const DOM_KEY_LOCATION_LEFT = bridge.property(@backingInt(Location.DOM_KEY_LOCATION_LEFT), .{ .template = true });
+ pub const DOM_KEY_LOCATION_RIGHT = bridge.property(@backingInt(Location.DOM_KEY_LOCATION_RIGHT), .{ .template = true });
+ pub const DOM_KEY_LOCATION_NUMPAD = bridge.property(@backingInt(Location.DOM_KEY_LOCATION_NUMPAD), .{ .template = true });
};
const testing = @import("../../../testing.zig");
diff --git a/src/browser/webapi/geolocation/GeolocationPositionError.zig b/src/browser/webapi/geolocation/GeolocationPositionError.zig
index 645563bdb..be3034ab8 100644
--- a/src/browser/webapi/geolocation/GeolocationPositionError.zig
+++ b/src/browser/webapi/geolocation/GeolocationPositionError.zig
@@ -64,7 +64,7 @@ pub fn releaseRef(self: *GeolocationPositionError, page: *Page) void {
}
fn getCode(self: *const GeolocationPositionError) u16 {
- return @intFromEnum(self._code);
+ return @backingInt(self._code);
}
fn getMessage(self: *const GeolocationPositionError) []const u8 {
@@ -83,7 +83,7 @@ pub const JsApi = struct {
pub const code = bridge.accessor(GeolocationPositionError.getCode, null, .{});
pub const message = bridge.accessor(GeolocationPositionError.getMessage, null, .{});
- pub const PERMISSION_DENIED = bridge.property(@intFromEnum(Code.permission_denied), .{ .template = true });
- pub const POSITION_UNAVAILABLE = bridge.property(@intFromEnum(Code.position_unavailable), .{ .template = true });
- pub const TIMEOUT = bridge.property(@intFromEnum(Code.timeout), .{ .template = true });
+ pub const PERMISSION_DENIED = bridge.property(@backingInt(Code.permission_denied), .{ .template = true });
+ pub const POSITION_UNAVAILABLE = bridge.property(@backingInt(Code.position_unavailable), .{ .template = true });
+ pub const TIMEOUT = bridge.property(@backingInt(Code.timeout), .{ .template = true });
};
diff --git a/src/browser/webapi/global_event_handlers.zig b/src/browser/webapi/global_event_handlers.zig
index 519cf70c5..1de308562 100644
--- a/src/browser/webapi/global_event_handlers.zig
+++ b/src/browser/webapi/global_event_handlers.zig
@@ -42,7 +42,7 @@ const Key = struct {
if (comptime lp.IS_DEBUG) {
lp.assert(ptr < (1 << 57), "Key.fuse: pointer overflow", .{ .ptr = ptr });
}
- return ptr | (@as(u64, @intFromEnum(self.handler)) << 57);
+ return ptr | (@as(u64, @backingInt(self.handler)) << 57);
}
};
@@ -168,10 +168,10 @@ pub const Handler = enum(u7) {
};
const typeToHandler = std.StaticStringMap(Handler).initComptime(blk: {
- const fields = std.meta.fields(Handler);
- var entries: [fields.len]struct { []const u8, Handler } = undefined;
- for (fields, 0..) |field, i| {
- entries[i] = .{ field.name[2..], @enumFromInt(field.value) };
+ const info = @typeInfo(Handler).@"enum";
+ var entries: [info.field_names.len]struct { []const u8, Handler } = undefined;
+ for (info.field_names, info.field_values, 0..) |field_name, field_value, i| {
+ entries[i] = .{ field_name[2..], @fromBackingInt(field_value) };
}
break :blk entries;
});
diff --git a/src/browser/webapi/navigation/Navigation.zig b/src/browser/webapi/navigation/Navigation.zig
index f9892674c..7dbd5f0e4 100644
--- a/src/browser/webapi/navigation/Navigation.zig
+++ b/src/browser/webapi/navigation/Navigation.zig
@@ -214,7 +214,7 @@ pub fn pushEntry(
should_dispatch: bool,
) !*NavigationHistoryEntry {
const arena = frame._session.arena;
- const url = try arena.dupeZ(u8, _url);
+ const url = try arena.dupeSentinel(u8, _url, 0);
// truncates our history here.
const retained_index = self._index + 1;
@@ -242,7 +242,7 @@ pub fn pushEntry(
const id = self._next_entry_id;
self._next_entry_id += 1;
- const id_str = try std.fmt.allocPrint(arena.allocator(), "{d}", .{id});
+ const id_str = try arena.allocator().print("{d}", .{id});
const entry = try Factory.chainedWithAllocator(arena.allocator(), .{
EventTarget{ ._type = .navigation_history_entry },
@@ -277,13 +277,13 @@ pub fn replaceEntry(
should_dispatch: bool,
) !*NavigationHistoryEntry {
const arena = frame._session.arena;
- const url = try arena.dupeZ(u8, _url);
+ const url = try arena.dupeSentinel(u8, _url, 0);
const previous = self.getCurrentEntry();
const id = self._next_entry_id;
self._next_entry_id += 1;
- const id_str = try std.fmt.allocPrint(arena.allocator(), "{d}", .{id});
+ const id_str = try arena.allocator().print("{d}", .{id});
const entry = try Factory.chainedWithAllocator(arena.allocator(), .{
EventTarget{ ._type = .navigation_history_entry },
@@ -403,7 +403,7 @@ pub fn navigateInner(
// Keeping the same url generates a crash during WPT test navigate-history-push-same-url.html.
// When building a script's src, script's base and frame url overlap.
if (is_same_document) {
- new_url = try arena.dupeZ(u8, new_url);
+ new_url = try arena.dupeSentinel(u8, new_url, 0);
}
// Captured before the switch overwrites frame.url in the same_document
diff --git a/src/browser/webapi/net/EventSource.zig b/src/browser/webapi/net/EventSource.zig
index f1f68a905..5fed4fbdc 100644
--- a/src/browser/webapi/net/EventSource.zig
+++ b/src/browser/webapi/net/EventSource.zig
@@ -331,7 +331,7 @@ fn httpHeaderDoneCallback(transfer: *Transfer) !Transfer.HeaderResult {
self._exec.js.localScope(&ls);
defer ls.deinit();
- const final_url = try self._arena.dupeZ(u8, transfer.req.url);
+ const final_url = try self._arena.dupeSentinel(u8, transfer.req.url, 0);
self._event_origin = (URL.getOrigin(self._arena.allocator(), final_url) catch null) orelse "";
// https://html.spec.whatwg.org/multipage/server-sent-events.html#announce-the-connection
@@ -570,7 +570,7 @@ pub fn getUrl(self: *const EventSource) []const u8 {
}
fn getReadyState(self: *const EventSource) u16 {
- return @intFromEnum(self._ready_state);
+ return @backingInt(self._ready_state);
}
fn getWithCredentials(self: *const EventSource) bool {
@@ -621,9 +621,9 @@ pub const JsApi = struct {
pub const constructor = bridge.constructor(EventSource.init, .{});
- pub const CONNECTING = bridge.property(@intFromEnum(ReadyState.connecting), .{ .template = true });
- pub const OPEN = bridge.property(@intFromEnum(ReadyState.open), .{ .template = true });
- pub const CLOSED = bridge.property(@intFromEnum(ReadyState.closed), .{ .template = true });
+ pub const CONNECTING = bridge.property(@backingInt(ReadyState.connecting), .{ .template = true });
+ pub const OPEN = bridge.property(@backingInt(ReadyState.open), .{ .template = true });
+ pub const CLOSED = bridge.property(@backingInt(ReadyState.closed), .{ .template = true });
pub const url = bridge.accessor(EventSource.getUrl, null, .{});
pub const readyState = bridge.accessor(EventSource.getReadyState, null, .{});
diff --git a/src/browser/webapi/net/Fetch.zig b/src/browser/webapi/net/Fetch.zig
index 685adac56..43958a0a0 100644
--- a/src/browser/webapi/net/Fetch.zig
+++ b/src/browser/webapi/net/Fetch.zig
@@ -237,8 +237,8 @@ fn httpHeaderDoneCallback(transfer: *Transfer) !Transfer.HeaderResult {
res._status_text = if (transfer.statusText()) |st|
try arena.allocator().dupe(u8, st)
else
- std.http.Status.phrase(@enumFromInt(status)) orelse "";
- res._url = try arena.dupeZ(u8, transfer.req.url);
+ std.http.Status.phrase(@fromBackingInt(@intCast(status))) orelse "";
+ res._url = try arena.dupeSentinel(u8, transfer.req.url, 0);
res._is_redirected = transfer.redirectCount().? > 0;
// no-cors mode: regardless of what the server returned, JS only ever sees
diff --git a/src/browser/webapi/net/FormData.zig b/src/browser/webapi/net/FormData.zig
index 5e3b3470d..fec52ffb8 100644
--- a/src/browser/webapi/net/FormData.zig
+++ b/src/browser/webapi/net/FormData.zig
@@ -530,7 +530,7 @@ fn indexOfSpecial(slice: []const u8) ?usize {
const chunk: Vector = slice[end..][0..vector_len].*;
const mask = @intFromBool(chunk == percent) | @intFromBool(chunk == plus);
- const mask_int = @as(std.meta.Int(.unsigned, vector_len), @bitCast(mask));
+ const mask_int = @as(@Int(.unsigned, vector_len), @bitCast(mask));
if (mask_int != 0) {
return end + @ctz(mask_int);
@@ -812,8 +812,8 @@ fn collectForm(arena: Allocator, form_: ?*Form, submitter_: ?*Element, charset:
}
const name = element.getName();
- const x_key = if (name) |n| try std.fmt.allocPrint(arena, "{s}.x", .{n}) else "x";
- const y_key = if (name) |n| try std.fmt.allocPrint(arena, "{s}.y", .{n}) else "y";
+ const x_key = if (name) |n| try arena.print("{s}.x", .{n}) else "x";
+ const y_key = if (name) |n| try arena.print("{s}.y", .{n}) else "y";
try appendString(&list, arena, x_key, "0");
try appendString(&list, arena, y_key, "0");
continue;
diff --git a/src/browser/webapi/net/Request.zig b/src/browser/webapi/net/Request.zig
index a9531ee01..42b7a3485 100644
--- a/src/browser/webapi/net/Request.zig
+++ b/src/browser/webapi/net/Request.zig
@@ -120,7 +120,7 @@ pub fn init(input: Input, opts_: ?InitOpts, exec: *const Execution) !*Request {
const url = switch (input) {
.url => |u| try URL.resolve(arena.allocator(), exec.base(), u, .{ .encoding = exec.charset.* }),
- .request => |r| try arena.dupeZ(u8, r._url),
+ .request => |r| try arena.dupeSentinel(u8, r._url, 0),
};
const opts = opts_ orelse InitOpts{};
@@ -212,7 +212,7 @@ pub fn init(input: Input, opts_: ?InitOpts, exec: *const Execution) !*Request {
} else if (opts_ != null) .client else switch (input) {
.url => .client,
.request => |r| switch (r._referrer) {
- .url => |u| .{ .url = try arena.dupeZ(u8, u) },
+ .url => |u| .{ .url = try arena.dupeSentinel(u8, u, 0) },
else => r._referrer,
},
};
@@ -417,7 +417,7 @@ pub fn clone(self: *Request, exec: *const Execution) !*Request {
const request = try arena.create(Request);
request.* = .{
- ._url = try arena.dupeZ(u8, self._url),
+ ._url = try arena.dupeSentinel(u8, self._url, 0),
._arena = arena,
._method = self._method,
._headers = if (self._headers) |h| try Headers.initGuarded(.{ .obj = h }, h._guard, exec) else null,
@@ -428,7 +428,7 @@ pub fn clone(self: *Request, exec: *const Execution) !*Request {
._body = if (body) |b| try arena.dupe(u8, b) else null,
._signal = self._signal,
._referrer = switch (self._referrer) {
- .url => |u| .{ .url = try arena.dupeZ(u8, u) },
+ .url => |u| .{ .url = try arena.dupeSentinel(u8, u, 0) },
else => self._referrer,
},
._referrer_policy = self._referrer_policy,
diff --git a/src/browser/webapi/net/Response.zig b/src/browser/webapi/net/Response.zig
index be6f4602c..b1f493418 100644
--- a/src/browser/webapi/net/Response.zig
+++ b/src/browser/webapi/net/Response.zig
@@ -563,7 +563,7 @@ pub fn clone(self: *const Response, exec: *const Execution) !*Response {
.stream => .empty, // TODO: implement stream tee for proper cloning
};
const status_text = try arena.dupe(u8, self._status_text);
- const url = try arena.dupeZ(u8, self._url);
+ const url = try arena.dupeSentinel(u8, self._url, 0);
const cloned = try arena.create(Response);
cloned.* = .{
diff --git a/src/browser/webapi/net/WebSocket.zig b/src/browser/webapi/net/WebSocket.zig
index 75b5b8021..c41052d44 100644
--- a/src/browser/webapi/net/WebSocket.zig
+++ b/src/browser/webapi/net/WebSocket.zig
@@ -167,10 +167,10 @@ pub fn init(url: []const u8, protocols: [][]const u8, exec: *const Execution) !*
// yup, this is what we're supposed to do.
if (std.mem.eql(u8, scheme, "http:")) {
- break :blk try std.fmt.allocPrintSentinel(arena.allocator(), "ws{s}", .{resolved["http".len..]}, 0);
+ break :blk try arena.allocator().printSentinel("ws{s}", .{resolved["http".len..]}, 0);
}
if (std.mem.eql(u8, scheme, "https:")) {
- break :blk try std.fmt.allocPrintSentinel(arena.allocator(), "wss{s}", .{resolved["https".len..]}, 0);
+ break :blk try arena.allocator().printSentinel("wss{s}", .{resolved["https".len..]}, 0);
}
return error.SyntaxError;
@@ -659,7 +659,7 @@ pub fn getUrl(self: *const WebSocket) []const u8 {
}
fn getReadyState(self: *const WebSocket) u16 {
- return @intFromEnum(self._ready_state);
+ return @backingInt(self._ready_state);
}
fn getBufferedAmount(self: *const WebSocket) u32 {
@@ -1031,10 +1031,10 @@ pub const JsApi = struct {
pub const constructor = bridge.constructor(WebSocket.init, .{});
- pub const CONNECTING = bridge.property(@intFromEnum(ReadyState.connecting), .{ .template = true });
- pub const OPEN = bridge.property(@intFromEnum(ReadyState.open), .{ .template = true });
- pub const CLOSING = bridge.property(@intFromEnum(ReadyState.closing), .{ .template = true });
- pub const CLOSED = bridge.property(@intFromEnum(ReadyState.closed), .{ .template = true });
+ pub const CONNECTING = bridge.property(@backingInt(ReadyState.connecting), .{ .template = true });
+ pub const OPEN = bridge.property(@backingInt(ReadyState.open), .{ .template = true });
+ pub const CLOSING = bridge.property(@backingInt(ReadyState.closing), .{ .template = true });
+ pub const CLOSED = bridge.property(@backingInt(ReadyState.closed), .{ .template = true });
pub const url = bridge.accessor(WebSocket.getUrl, null, .{});
pub const readyState = bridge.accessor(WebSocket.getReadyState, null, .{});
diff --git a/src/browser/webapi/net/XMLHttpRequest.zig b/src/browser/webapi/net/XMLHttpRequest.zig
index 2b6c186e8..ae1ffb00f 100644
--- a/src/browser/webapi/net/XMLHttpRequest.zig
+++ b/src/browser/webapi/net/XMLHttpRequest.zig
@@ -454,7 +454,7 @@ fn getUpload(self: *XMLHttpRequest) !*XMLHttpRequestUpload {
}
fn getReadyState(self: *const XMLHttpRequest) u32 {
- return @intFromEnum(self._ready_state);
+ return @backingInt(self._ready_state);
}
pub fn getResponseHeader(self: *const XMLHttpRequest, name: []const u8) ?[]const u8 {
@@ -532,7 +532,7 @@ fn getStatusText(self: *const XMLHttpRequest) []const u8 {
if (self._response_status_text) |st| {
return st;
}
- return std.http.Status.phrase(@enumFromInt(self._response_status)) orelse "";
+ return std.http.Status.phrase(@fromBackingInt(@intCast(self._response_status))) orelse "";
}
fn getResponseURL(self: *XMLHttpRequest) []const u8 {
@@ -659,7 +659,7 @@ fn applyResponseHeaders(self: *XMLHttpRequest, headers: []const http.Header) !vo
if (Headers.isForbiddenResponseHeaderName(hdr.name)) {
continue;
}
- const joined = try std.fmt.allocPrint(self._arena.allocator(), "{s}: {s}", .{ hdr.name, hdr.value });
+ const joined = try self._arena.allocator().print("{s}: {s}", .{ hdr.name, hdr.value });
try self._response_headers.append(self._arena.allocator(), joined);
}
}
@@ -696,7 +696,7 @@ fn httpHeaderDoneCallback(transfer: *Transfer) !Transfer.HeaderResult {
self._response_len = cl;
}
try self._response_data.ensureTotalCapacityPrecise(self._arena.allocator(), transfer.bodyLen());
- self._response_url = try self._arena.dupeZ(u8, transfer.req.url);
+ self._response_url = try self._arena.dupeSentinel(u8, transfer.req.url, 0);
const exec = self._exec;
@@ -846,11 +846,11 @@ pub const JsApi = struct {
};
pub const constructor = bridge.constructor(XMLHttpRequest.init, .{});
- pub const UNSENT = bridge.property(@intFromEnum(XMLHttpRequest.ReadyState.unsent), .{ .template = true });
- pub const OPENED = bridge.property(@intFromEnum(XMLHttpRequest.ReadyState.opened), .{ .template = true });
- pub const HEADERS_RECEIVED = bridge.property(@intFromEnum(XMLHttpRequest.ReadyState.headers_received), .{ .template = true });
- pub const LOADING = bridge.property(@intFromEnum(XMLHttpRequest.ReadyState.loading), .{ .template = true });
- pub const DONE = bridge.property(@intFromEnum(XMLHttpRequest.ReadyState.done), .{ .template = true });
+ pub const UNSENT = bridge.property(@backingInt(XMLHttpRequest.ReadyState.unsent), .{ .template = true });
+ pub const OPENED = bridge.property(@backingInt(XMLHttpRequest.ReadyState.opened), .{ .template = true });
+ pub const HEADERS_RECEIVED = bridge.property(@backingInt(XMLHttpRequest.ReadyState.headers_received), .{ .template = true });
+ pub const LOADING = bridge.property(@backingInt(XMLHttpRequest.ReadyState.loading), .{ .template = true });
+ pub const DONE = bridge.property(@backingInt(XMLHttpRequest.ReadyState.done), .{ .template = true });
pub const onreadystatechange = bridge.accessor(XMLHttpRequest.getOnReadyStateChange, XMLHttpRequest.setOnReadyStateChange, .{});
pub const upload = bridge.accessor(XMLHttpRequest.getUpload, null, .{});
diff --git a/src/browser/webapi/net/body_init.zig b/src/browser/webapi/net/body_init.zig
index 5f10a3e3d..e622fba38 100644
--- a/src/browser/webapi/net/body_init.zig
+++ b/src/browser/webapi/net/body_init.zig
@@ -94,7 +94,7 @@ pub const BodyInit = union(enum) {
var buf = std.Io.Writer.Allocating.init(arena);
try fd.write(arena, .{ .encoding = .{ .formdata = &boundary } }, &buf.writer);
- const ct = try std.fmt.allocPrint(arena, "multipart/form-data; boundary={s}", .{boundary});
+ const ct = try arena.print("multipart/form-data; boundary={s}", .{boundary});
return .{
.bytes = buf.written(),
.content_type = ct,
@@ -211,7 +211,7 @@ test "BodyInit: FormData emits multipart with random boundary" {
try testing.expect(std.mem.indexOf(u8, r.bytes, "Content-Disposition: form-data; name=\"email\"") != null);
try testing.expect(std.mem.indexOf(u8, r.bytes, "alice") != null);
try testing.expect(std.mem.indexOf(u8, r.bytes, "[email protected]") != null);
- const closer = try std.fmt.allocPrint(arena.allocator(), "--{s}--\r\n", .{boundary});
+ const closer = try arena.allocator().print("--{s}--\r\n", .{boundary});
try testing.expect(std.mem.endsWith(u8, r.bytes, closer));
}
diff --git a/src/browser/webapi/sanitizer_defaults.zig b/src/browser/webapi/sanitizer_defaults.zig
index 652ff17ef..72300c5c7 100644
--- a/src/browser/webapi/sanitizer_defaults.zig
+++ b/src/browser/webapi/sanitizer_defaults.zig
@@ -260,7 +260,7 @@ pub const baseline_remove_elements: []const Name = &.{
// behind by removeUnsafe().
pub const event_handler_attributes: []const []const u8 = blk: {
@setEvalBranchQuota(200_000);
- const handlers = std.meta.fieldNames(global_event_handlers.Handler);
+ const handlers = @typeInfo(global_event_handlers.Handler).@"enum".field_names;
var all: [html_event_handler_attributes.len + handlers.len][]const u8 = undefined;
for (html_event_handler_attributes, 0..) |name, i| {
all[i] = name;
diff --git a/src/browser/webapi/selector/List.zig b/src/browser/webapi/selector/List.zig
index 5614c1e26..0ff018265 100644
--- a/src/browser/webapi/selector/List.zig
+++ b/src/browser/webapi/selector/List.zig
@@ -439,7 +439,7 @@ fn matchesAttribute(el: *Node.Element, attr: Selector.Attribute) bool {
},
.substring => |expected| {
return if (attr.case_insensitive)
- std.ascii.indexOfIgnoreCase(value, expected) != null
+ std.ascii.findIgnoreCase(value, expected) != null
else
std.mem.indexOf(u8, value, expected) != null;
},
@@ -1033,7 +1033,7 @@ pub const NthCache = struct {
of_type_from_end: u32,
};
- const TypeCounts = [@typeInfo(Node.Element.Tag).@"enum".fields.len]u32;
+ const TypeCounts = [@typeInfo(Node.Element.Tag).@"enum".field_names.len]u32;
pub fn deinit(self: *NthCache) void {
self.entries.deinit(self.allocator);
@@ -1058,7 +1058,7 @@ pub const NthCache = struct {
while (it.next()) |child| {
const el = child.is(Node.Element) orelse continue;
child_count += 1;
- const of_type = &type_counts[@intFromEnum(el.getTag())];
+ const of_type = &type_counts[@backingInt(el.getTag())];
of_type.* += 1;
try self.entries.put(self.allocator, child, .{
.child = child_count,
@@ -1075,7 +1075,7 @@ pub const NthCache = struct {
while (it.next()) |child| {
const el = child.is(Node.Element) orelse continue;
seen_count += 1;
- const tag = @intFromEnum(el.getTag());
+ const tag = @backingInt(el.getTag());
seen_types[tag] += 1;
const ordinals = self.entries.getPtr(child).?;
diff --git a/src/browser/webapi/selector/Parser.zig b/src/browser/webapi/selector/Parser.zig
index fa2cad3ac..02e2b465a 100644
--- a/src/browser/webapi/selector/Parser.zig
+++ b/src/browser/webapi/selector/Parser.zig
@@ -1163,7 +1163,7 @@ fn attributeValue(self: *Parser, arena: Allocator) ![]const u8 {
return arena.dupe(u8, value);
}
-fn asUint(comptime string: anytype) std.meta.Int(
+fn asUint(comptime string: anytype) @Int(
.unsigned,
@bitSizeOf(@TypeOf(string.*)) - 8, // (- 8) to exclude sentinel 0
) {
diff --git a/src/browser/webapi/storage/Cookie.zig b/src/browser/webapi/storage/Cookie.zig
index 789f58b0a..35d550178 100644
--- a/src/browser/webapi/storage/Cookie.zig
+++ b/src/browser/webapi/storage/Cookie.zig
@@ -23,6 +23,7 @@ const URL = @import("../../URL.zig");
const DateTime = @import("../../../datetime.zig").DateTime;
const Notification = @import("../../../Notification.zig");
const public_suffix_list = @import("../../../data/public_suffix_list.zig").lookup;
+const repeat = @import("../../../string.zig").repeat;
const log = lp.log;
const Allocator = std.mem.Allocator;
@@ -895,15 +896,15 @@ test "Jar: add limit" {
.domain = "lightpanda.io",
.path = "/",
.expires = null,
- .value = "v" ** 4096 ++ "v",
+ .value = repeat("v", 4096) ++ "v",
}, now, true));
// generate unique names.
const names = comptime blk: {
- @setEvalBranchQuota(max_jar_size);
+ @setEvalBranchQuota(max_jar_size * 10);
var result: [max_jar_size][]const u8 = undefined;
for (0..max_jar_size) |i| {
- result[i] = "v" ** i;
+ result[i] = repeat("v", i);
}
break :blk result;
};
@@ -1511,8 +1512,8 @@ test "Cookie: parse domain" {
}
test "Cookie: parse limit" {
- try expectError(error.CookieHeaderSizeExceeded, "http://lightpanda.io/", "v" ** 8192 ++ ";domain=lightpanda.io");
- try expectError(error.CookieSizeExceeded, "http://lightpanda.io/", "v" ** 4096 ++ "v;domain=lightpanda.io");
+ try expectError(error.CookieHeaderSizeExceeded, "http://lightpanda.io/", repeat("v", 8192) ++ ";domain=lightpanda.io");
+ try expectError(error.CookieSizeExceeded, "http://lightpanda.io/", repeat("v", 4096) ++ "v;domain=lightpanda.io");
}
const ExpectedCookie = struct {
@@ -1545,14 +1546,14 @@ fn expectAttribute(expected: anytype, url_: ?[:0]const u8, set_cookie: []const u
var cookie = try Cookie.parse(testing.allocator, url_ orelse test_url, set_cookie);
defer cookie.deinit();
- inline for (@typeInfo(@TypeOf(expected)).@"struct".fields) |f| {
- if (comptime std.mem.eql(u8, f.name, "expires")) {
+ inline for (@typeInfo(@TypeOf(expected)).@"struct".field_names) |field_name| {
+ if (comptime std.mem.eql(u8, field_name, "expires")) {
switch (@typeInfo(@TypeOf(expected.expires))) {
.int, .comptime_int => try testing.expectDelta(@as(f64, @floatFromInt(expected.expires)), cookie.expires, 1.0),
else => try testing.expectDelta(expected.expires, cookie.expires, 1.0),
}
} else {
- try testing.expectEqual(@field(expected, f.name), @field(cookie, f.name));
+ try testing.expectEqual(@field(expected, field_name), @field(cookie, field_name));
}
}
}
diff --git a/src/browser/webapi/storage/idb/Engine.zig b/src/browser/webapi/storage/idb/Engine.zig
index dabe3ac6a..6a0164a5b 100644
--- a/src/browser/webapi/storage/idb/Engine.zig
+++ b/src/browser/webapi/storage/idb/Engine.zig
@@ -481,13 +481,13 @@ pub fn clearIndexRecordsForStore(self: *Engine, object_store_id: i64) !void {
pub fn deleteIndexRecordsForRange(self: *Engine, object_store_id: i64, b: Bounds) !void {
const ops = rangeOps(b);
var buf: [400]u8 = undefined;
- const sql = try std.fmt.bufPrintZ(&buf,
+ const sql = try std.mem.printSentinel(&buf,
\\ delete from idb_index_records where index_id in (
\\ select id from idb_indexes where object_store_id = ?1
\\ ) and primary_key in (
\\ select key from idb_records where object_store_id = ?1 and key {s} ?2 and key {s} ?3
\\)
- , .{ ops.lo, ops.hi });
+ , .{ ops.lo, ops.hi }, 0);
return self.conn.exec(sql, .{ object_store_id, b.lower, b.upper });
}
@@ -514,7 +514,7 @@ pub fn indexGetRange(self: *const Engine, arena: Allocator, object_store_id: i64
const ops = rangeOps(b);
var buf: [512]u8 = undefined;
- const sql = try std.fmt.bufPrint(&buf,
+ const sql = try std.mem.print(&buf,
\\ select r.value
\\ from idb_index_records ir
\\ join idb_records r on r.object_store_id = ?1 and r.key = ir.primary_key
@@ -532,7 +532,7 @@ pub fn indexGetRange(self: *const Engine, arena: Allocator, object_store_id: i64
pub fn indexGetKeyRange(self: *const Engine, arena: Allocator, index_id: i64, b: Bounds) !?[]u8 {
const ops = rangeOps(b);
var buf: [320]u8 = undefined;
- const sql = try std.fmt.bufPrint(&buf,
+ const sql = try std.mem.print(&buf,
\\ select primary_key
\\ from idb_index_records
\\ where index_id = ?1 and key {s} ?2 and key {s} ?3
@@ -548,7 +548,7 @@ pub fn indexGetKeyRange(self: *const Engine, arena: Allocator, index_id: i64, b:
pub fn indexCountRange(self: *const Engine, index_id: i64, b: Bounds) !i64 {
const ops = rangeOps(b);
var buf: [320]u8 = undefined;
- const sql = try std.fmt.bufPrint(&buf,
+ const sql = try std.mem.print(&buf,
\\ select count(*)
\\ from idb_index_records
\\ where index_id = ?1 and key {s} ?2 and key {s} ?3
@@ -569,7 +569,7 @@ pub fn indexGetAllRows(self: *const Engine, object_store_id: i64, index_id: i64,
const order = if (reverse) "desc" else "asc";
var buf: [640]u8 = undefined;
- const sql = try std.fmt.bufPrint(&buf,
+ const sql = try std.mem.print(&buf,
\\ select ir.key, {s}, r.value
\\ from idb_index_records ir
\\ join idb_records r on r.object_store_id = ?1 and r.key = ir.primary_key
@@ -619,7 +619,7 @@ pub fn indexCursorSeek(
const pk_op = if (reverse) (if (pk_inclusive) "<= " else "< ") else (if (pk_inclusive) ">= " else "> ");
var buf: [768]u8 = undefined;
- const sql = try std.fmt.bufPrint(
+ const sql = try std.mem.print(
&buf,
\\ select ir.key, {s}{s} from idb_index_records ir {s}
\\ where ir.index_id = ?2 and ir.key {s} ?3 and ir.key {s} ?4 and (ir.key {s}?5 or (ir.key = ?5 and ir.primary_key {s}?6))
@@ -710,17 +710,19 @@ fn rangeSql(buf: []u8, head: []const u8, b: Bounds, tail: []const u8) ![:0]u8 {
if (b.is_point) {
// optimized query for [common] point query. (key = ?2 or key = ?3)
// to keep the param list the side for the caller.
- return std.fmt.bufPrintZ(
+ return std.mem.printSentinel(
buf,
"{s} from idb_records where object_store_id = ?1 and (key = ?2 or key = ?3) {s}",
.{ head, tail },
+ 0,
);
}
- return std.fmt.bufPrintZ(
+ return std.mem.printSentinel(
buf,
"{s} from idb_records where object_store_id = ?1 and key {s} ?2 and key {s} ?3{s}",
.{ head, b.lower_op, b.upper_op, tail },
+ 0,
);
}
@@ -800,7 +802,7 @@ pub fn cursorSeek(
const order = if (reverse) "desc" else "asc";
var buf: [320]u8 = undefined;
- const sql = try std.fmt.bufPrint(
+ const sql = try std.mem.print(
&buf,
"{s} from idb_records where object_store_id = ?1 and key {s} ?2 and key {s} ?3 and key {s} ?4 order by key {s} limit 1 offset ?5",
.{ if (with_value) "select key, value" else "select key", lower_op, upper_op, from_op, order },
@@ -1022,7 +1024,7 @@ fn seedNumbers(engine: *Engine, store_id: i64, arena: Allocator, ns: []const u8)
for (ns) |n| {
const enc = try Key.number(@floatFromInt(n)).encode(arena);
var buf: [8]u8 = undefined;
- try engine.add(store_id, enc, try std.fmt.bufPrint(&buf, "v{d}", .{n}));
+ try engine.add(store_id, enc, try std.mem.print(&buf, "v{d}", .{n}));
}
}
diff --git a/src/browser/webapi/storage/idb/Manager.zig b/src/browser/webapi/storage/idb/Manager.zig
index 17cbbca8a..3eff3c06a 100644
--- a/src/browser/webapi/storage/idb/Manager.zig
+++ b/src/browser/webapi/storage/idb/Manager.zig
@@ -19,6 +19,7 @@
const std = @import("std");
const Engine = @import("Engine.zig");
+const repeat = @import("../../../../string.zig").repeat;
const Allocator = std.mem.Allocator;
@@ -101,7 +102,7 @@ test "IDB - Manager: on-disk engines hash to per-origin files, isolated" {
// A long origin (hostname near the 253-byte limit) must still open: the
// hashed file name stays well under NAME_MAX where a transcribed one would
// not.
- const long_host = "https://" ++ ("a" ** 250) ++ ".com";
+ const long_host = "https://" ++ (repeat("a", 250)) ++ ".com";
const a = try mgr.engineForOrigin(long_host);
_ = try a.upsertDatabase("db", 7);
diff --git a/src/browser/webapi/storage/storage.zig b/src/browser/webapi/storage/storage.zig
index c5bf932ff..7fd1d1102 100644
--- a/src/browser/webapi/storage/storage.zig
+++ b/src/browser/webapi/storage/storage.zig
@@ -187,22 +187,22 @@ pub const Lookup = struct {
// int -> string conversion
fn _getByIndex(self: *const Lookup, idx: u32) ?[]const u8 {
var buf: [10]u8 = undefined;
- return self._data.get(std.fmt.bufPrint(&buf, "{d}", .{idx}) catch unreachable);
+ return self._data.get(std.mem.print(&buf, "{d}", .{idx}) catch unreachable);
}
fn _setByIndex(self: *Lookup, idx: u32, value: []const u8) !void {
var buf: [10]u8 = undefined;
- return self.setItem(std.fmt.bufPrint(&buf, "{d}", .{idx}) catch unreachable, value);
+ return self.setItem(std.mem.print(&buf, "{d}", .{idx}) catch unreachable, value);
}
fn _removeByIndex(self: *Lookup, idx: u32) void {
var buf: [10]u8 = undefined;
- return self.removeItem(std.fmt.bufPrint(&buf, "{d}", .{idx}) catch unreachable);
+ return self.removeItem(std.mem.print(&buf, "{d}", .{idx}) catch unreachable);
}
fn _indexHas(self: *const Lookup, idx: u32) bool {
var buf: [10]u8 = undefined;
- return self._data.contains(std.fmt.bufPrint(&buf, "{d}", .{idx}) catch unreachable);
+ return self._data.contains(std.mem.print(&buf, "{d}", .{idx}) catch unreachable);
}
};
};
diff --git a/src/browser/webapi/svg/Angle.zig b/src/browser/webapi/svg/Angle.zig
index 88ab69023..3139b6c3e 100644
--- a/src/browser/webapi/svg/Angle.zig
+++ b/src/browser/webapi/svg/Angle.zig
@@ -69,7 +69,7 @@ fn getUnitType(self: *Angle) u16 {
self.syncFromAttribute();
return switch (self._unit) {
.turn => 0,
- else => @intFromEnum(self._unit),
+ else => @backingInt(self._unit),
};
}
@@ -173,7 +173,7 @@ fn writeBack(self: *Angle, frame: *Frame) !void {
}
fn serialize(self: *const Angle, frame: *Frame) ![]const u8 {
- return std.fmt.allocPrint(frame.local_arena, "{d}{s}", .{ self._value, unitSuffix(self._unit) });
+ return frame.local_arena.print("{d}{s}", .{ self._value, unitSuffix(self._unit) });
}
const Parsed = struct {
diff --git a/src/browser/webapi/svg/AnimatedNumber.zig b/src/browser/webapi/svg/AnimatedNumber.zig
index 132ae025b..9ff719c95 100644
--- a/src/browser/webapi/svg/AnimatedNumber.zig
+++ b/src/browser/webapi/svg/AnimatedNumber.zig
@@ -78,7 +78,7 @@ fn setBaseVal(self: *AnimatedNumber, value: f32, frame: *Frame) !void {
if (!std.math.isFinite(value)) {
return error.TypeError;
}
- const serialized = try std.fmt.allocPrint(frame.local_arena, "{d}", .{value});
+ const serialized = try frame.local_arena.print("{d}", .{value});
try self._element.setAttributeSafe(self._attr_name, .wrap(serialized), frame);
}
diff --git a/src/browser/webapi/svg/Length.zig b/src/browser/webapi/svg/Length.zig
index e250b808b..069084090 100644
--- a/src/browser/webapi/svg/Length.zig
+++ b/src/browser/webapi/svg/Length.zig
@@ -106,7 +106,7 @@ pub fn reflectedConfigured(
fn getUnitType(self: *Length) u16 {
self.syncFromAttribute();
- return @intFromEnum(self._unit);
+ return @backingInt(self._unit);
}
// An attribute SVG could not parse reports the unknown unit type. Callers that
@@ -218,7 +218,7 @@ fn writeBack(self: *Length, frame: *Frame) !void {
}
fn serialize(self: *const Length, frame: *Frame) ![]const u8 {
- return std.fmt.allocPrint(frame.local_arena, "{d}{s}", .{ self._value, units.suffix(toShared(self._unit)) });
+ return frame.local_arena.print("{d}{s}", .{ self._value, units.suffix(toShared(self._unit)) });
}
fn unitToUserUnits(self: *const Length, unit: Unit, frame: *Frame) f64 {
diff --git a/src/browser/webapi/svg/PreserveAspectRatio.zig b/src/browser/webapi/svg/PreserveAspectRatio.zig
index eeaca6db7..d6fea46d1 100644
--- a/src/browser/webapi/svg/PreserveAspectRatio.zig
+++ b/src/browser/webapi/svg/PreserveAspectRatio.zig
@@ -85,7 +85,7 @@ fn current(self: *const PreserveAspectRatio) Value {
fn write(self: *PreserveAspectRatio, value: Value, frame: *Frame) !void {
const alignment = alignName(value.alignment) orelse return error.TypeError;
const meet_or_slice = meetOrSliceName(value.meet_or_slice) orelse return error.TypeError;
- const serialized = try std.fmt.allocPrint(frame.local_arena, "{s} {s}", .{ alignment, meet_or_slice });
+ const serialized = try frame.local_arena.print("{s} {s}", .{ alignment, meet_or_slice });
try self._element.setAttributeSafe(String.wrap("preserveAspectRatio"), .wrap(serialized), frame);
}
diff --git a/src/browser/xpath/result.zig b/src/browser/xpath/result.zig
index b03e88845..d73ec7696 100644
--- a/src/browser/xpath/result.zig
+++ b/src/browser/xpath/result.zig
@@ -115,9 +115,9 @@ pub fn numberToString(arena: Allocator, n: f64) error{OutOfMemory}![]const u8 {
if (std.math.isNegativeInf(n)) return "-Infinity";
if (n == 0) return "0"; // covers +0 and -0
if (@trunc(n) == n and n >= -9.007199254740992e15 and n <= 9.007199254740992e15) {
- return std.fmt.allocPrint(arena, "{d}", .{@as(i64, @trunc(n))});
+ return arena.print("{d}", .{@as(i64, @trunc(n))});
}
- return std.fmt.allocPrint(arena, "{d}", .{n});
+ return arena.print("{d}", .{n});
}
const testing = std.testing;
diff --git a/src/cli.zig b/src/cli.zig
index 47d0414c2..9ed8caf9b 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -192,9 +192,9 @@ const string = @import("string.zig");
/// ```
pub fn tagNames(comptime E: type) []const []const u8 {
return comptime blk: {
- const fields = @typeInfo(E).@"enum".fields;
- var names: [fields.len][]const u8 = undefined;
- for (fields, &names) |f, *n| n.* = f.name;
+ const field_names = @typeInfo(E).@"enum".field_names;
+ var names: [field_names.len][]const u8 = undefined;
+ for (field_names, &names) |field_name, *n| n.* = field_name;
const frozen = names;
break :blk &frozen;
};
@@ -209,10 +209,10 @@ pub fn isUrlLike(arg: []const u8) bool {
/// `prefix` was stripped from `value` before matching, like `--log-filter`'s sign.
pub fn invalidChoice(arg: []const u8, prefix: []const u8, value: []const u8, choices: []const []const u8) error{InvalidArgument} {
var value_buf: [128]u8 = undefined;
- const typed = std.fmt.bufPrint(&value_buf, "{s}{s}", .{ prefix, value }) catch value;
+ const typed = std.mem.print(&value_buf, "{s}{s}", .{ prefix, value }) catch value;
if (string.closest(value, choices)) |near| {
var near_buf: [128]u8 = undefined;
- const suggestion = std.fmt.bufPrint(&near_buf, "{s}{s}", .{ prefix, near }) catch near;
+ const suggestion = std.mem.print(&near_buf, "{s}{s}", .{ prefix, near }) catch near;
log.fatal(.app, "invalid option choice", .{ .arg = arg, .value = log.red(typed), .did_you_mean = log.green(suggestion) });
} else {
log.fatal(.app, "invalid option choice", .{ .arg = arg, .value = log.red(typed) });
@@ -243,9 +243,15 @@ pub fn Builder(comptime commands: anytype) type {
const command_names = tagNames(Enum);
- /// Creates an array of `StructField` out of given options.
- fn optionsToStructFields(comptime options: anytype) [options.len]std.builtin.Type.StructField {
- var fields: [options.len]std.builtin.Type.StructField = undefined;
+ const Field = struct {
+ name: [:0]const u8,
+ type: type,
+ attrs: std.lang.Type.Struct.FieldAttributes,
+ };
+
+ /// Creates an array of `Field` out of given options.
+ fn optionsToFields(comptime options: anytype) [options.len]Field {
+ var fields: [options.len]Field = undefined;
inline for (options, 0..) |option, j| {
// Whether prefer `ArrayList` for the option.
@@ -310,9 +316,7 @@ pub fn Builder(comptime commands: anytype) type {
fields[j] = .{
.name = name,
.type = T,
- .default_value_ptr = default,
- .is_comptime = false,
- .alignment = @alignOf(T),
+ .attrs = .{ .default_value_ptr = default },
};
}
@@ -322,11 +326,11 @@ pub fn Builder(comptime commands: anytype) type {
/// Drops duplicate fields, keeping the first occurrence. Only an exact
/// duplicate (same name and type) is deduplicated; a name that
/// reappears with a different type is a conflict.
- fn dedupeStructFields(comptime fields: []const std.builtin.Type.StructField) []const std.builtin.Type.StructField {
+ fn dedupeFields(comptime fields: []const Field) []const Field {
// The pairwise name comparisons blow the default 1000-branch quota.
@setEvalBranchQuota(1000 + fields.len * fields.len * 100);
- var out: [fields.len]std.builtin.Type.StructField = undefined;
+ var out: [fields.len]Field = undefined;
var len: usize = 0;
outer: for (fields) |field| {
@@ -350,7 +354,8 @@ pub fn Builder(comptime commands: anytype) type {
/// Union type for provided commands.
pub const Union = blk: {
const len = commands.len + 1;
- var union_fields: [len]std.builtin.Type.UnionField = undefined;
+ var names: [len][:0]const u8 = undefined;
+ var types: [len]type = undefined;
var i: usize = 0;
while (i < commands.len) : (i += 1) {
@@ -358,53 +363,44 @@ pub fn Builder(comptime commands: anytype) type {
const Command = @TypeOf(command);
const options = command.options;
- const all_fields = optionsToStructFields(options) ++
+ const all_fields = optionsToFields(options) ++
(if (@hasField(Command, "shared_options"))
- optionsToStructFields(command.shared_options)
+ optionsToFields(command.shared_options)
else
.{}) ++
(if (@hasField(Command, "positional"))
- [1]std.builtin.Type.StructField{positionalField(command.positional)}
+ [1]Field{positionalField(command.positional)}
else
.{});
- const T = StructFromFields(dedupeStructFields(&all_fields));
-
- union_fields[i] = .{ .name = command.name, .type = T, .alignment = @alignOf(T) };
+ names[i] = command.name;
+ types[i] = StructFromFields(dedupeFields(&all_fields));
}
// Entry for help; just takes `Enum` itself.
- const Help = Enum;
- union_fields[i] = .{ .name = "help", .type = Help, .alignment = @alignOf(Help) };
+ names[i] = "help";
+ types[i] = Enum;
- var names: [len][:0]const u8 = undefined;
- var types: [len]type = undefined;
- var attrs: [len]std.builtin.Type.UnionField.Attributes = undefined;
- for (union_fields, 0..) |f, j| {
- names[j] = f.name;
- types[j] = f.type;
- attrs[j] = .{ .@"align" = f.alignment };
- }
- break :blk @Union(.auto, Enum, &names, &types, &attrs);
+ break :blk @Union(.auto, Enum, &names, &types, &@splat(.{}));
};
- fn StructFromFields(comptime fields: []const std.builtin.Type.StructField) type {
+ fn StructFromFields(comptime fields: []const Field) type {
var names: [fields.len][:0]const u8 = undefined;
var types: [fields.len]type = undefined;
- var attrs: [fields.len]std.builtin.Type.StructField.Attributes = undefined;
+ var attrs: [fields.len]std.lang.Type.Struct.FieldAttributes = undefined;
for (fields, 0..) |f, i| {
names[i] = f.name;
types[i] = f.type;
- attrs[i] = .{ .@"comptime" = f.is_comptime, .@"align" = f.alignment, .default_value_ptr = f.default_value_ptr };
+ attrs[i] = f.attrs;
}
return @Struct(.auto, null, &names, &types, &attrs);
}
- /// Builds the `StructField` for a command's positional argument. A plain
+ /// Builds the `Field` for a command's positional argument. A plain
/// positional is an optional that defaults to `null`; a `multiple`
/// positional collects every occurrence into an `ArrayList` that
/// defaults to empty.
- fn positionalField(comptime positional: anytype) std.builtin.Type.StructField {
+ fn positionalField(comptime positional: anytype) Field {
const is_multiple = @hasField(@TypeOf(positional), "multiple") and positional.multiple;
const T = if (is_multiple) std.ArrayList(positional.type) else positional.type;
const default: *const anyopaque = if (is_multiple)
@@ -414,9 +410,7 @@ pub fn Builder(comptime commands: anytype) type {
return .{
.name = positional.name,
.type = T,
- .default_value_ptr = default,
- .is_comptime = false,
- .alignment = @alignOf(T),
+ .attrs = .{ .default_value_ptr = default },
};
}
@@ -620,7 +614,7 @@ pub fn Builder(comptime commands: anytype) type {
// Parse by type.
return switch (option_info) {
.int => |int| {
- const Int = std.meta.Int(int.signedness, int.bits);
+ const Int = @Int(int.signedness, int.bits);
const str = args.next() orelse return error.MissingArgument;
const v = std.fmt.parseInt(Int, str, 10) catch |err| {
@@ -649,14 +643,14 @@ pub fn Builder(comptime commands: anytype) type {
// DupeZ branch.
if (comptime pointer.sentinel()) |sentinel| {
- const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.alignment orelse @alignOf(u8)), str.len + 1);
+ const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.attrs.@"align" orelse @alignOf(u8)), str.len + 1);
@memcpy(buf[0..str.len], str);
buf[str.len] = sentinel;
break :blk buf[0..str.len :sentinel];
}
// Dupe branch.
- const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.alignment orelse @alignOf(u8)), str.len);
+ const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.attrs.@"align" orelse @alignOf(u8)), str.len);
@memcpy(buf, str);
break :blk buf;
};
@@ -684,14 +678,14 @@ pub fn Builder(comptime commands: anytype) type {
outer: while (it.next()) |part| {
const trimmed = std.mem.trim(u8, part, &std.ascii.whitespace);
- inline for (_struct.fields) |f| {
- lp.assert(f.type == bool, "all fields of packed struct must be boolean", .{
+ inline for (_struct.field_names, _struct.field_types) |field_name, field_type| {
+ lp.assert(field_type == bool, "all fields of packed struct must be boolean", .{
.option = option.name,
- .field = f.name,
+ .field = field_name,
});
- if (std.mem.eql(u8, trimmed, @as([]const u8, f.name))) {
- @field(target, f.name) = true;
+ if (std.mem.eql(u8, trimmed, @as([]const u8, field_name))) {
+ @field(target, field_name) = true;
continue :outer;
}
}
@@ -871,14 +865,14 @@ pub fn Builder(comptime commands: anytype) type {
const v = blk: {
// DupeZ branch.
if (comptime pointer.sentinel()) |sentinel| {
- const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.alignment orelse @alignOf(u8)), str.len + 1);
+ const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.attrs.@"align" orelse @alignOf(u8)), str.len + 1);
@memcpy(buf[0..str.len], str);
buf[str.len] = sentinel;
break :blk buf[0..str.len :sentinel];
}
// Dupe branch.
- const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.alignment orelse @alignOf(u8)), str.len);
+ const buf = try allocator.alignedAlloc(u8, .fromByteUnits(pointer.attrs.@"align" orelse @alignOf(u8)), str.len);
@memcpy(buf, str);
break :blk buf;
};
diff --git a/src/cookies.zig b/src/cookies.zig
index de8ffff8e..f10431952 100644
--- a/src/cookies.zig
+++ b/src/cookies.zig
@@ -282,7 +282,7 @@ pub const NetscapeFormat = struct {
// off that dot, so the column is what decides it here.
const bare_domain = if (fields.domain.len > 0 and fields.domain[0] == '.') fields.domain[1..] else fields.domain;
const domain = if (fields.include_subdomains)
- try std.fmt.allocPrint(allocator, ".{s}", .{bare_domain})
+ try allocator.print(".{s}", .{bare_domain})
else
try allocator.dupe(u8, bare_domain);
diff --git a/src/core_dump.zig b/src/core_dump.zig
index e71584ebc..a5c590981 100644
--- a/src/core_dump.zig
+++ b/src/core_dump.zig
@@ -42,7 +42,7 @@ pub fn disableIfRequested() void {
}
fn shouldDisable() bool {
- if (builtin.os.tag == .windows) return false;
+ if (builtin.target.os.tag == .windows) return false;
return std.c.getenv("LIGHTPANDA_DISABLE_CORE_DUMP") != null;
}
@@ -70,7 +70,7 @@ test "core_dump: disabled only when the env var is set" {
}
test "core_dump: disable zeroes the soft RLIMIT_CORE" {
- if (builtin.os.tag == .windows) return;
+ if (builtin.target.os.tag == .windows) return;
const original = try std.posix.getrlimit(.CORE);
defer std.posix.setrlimit(.CORE, original) catch {};
diff --git a/src/crash_handler.zig b/src/crash_handler.zig
index e73488921..1f6c45a00 100644
--- a/src/crash_handler.zig
+++ b/src/crash_handler.zig
@@ -28,7 +28,7 @@ var panic_level: usize = 0;
var panic_mutex: std.Io.Mutex = .init;
// overwrite's Zig default panic handler
-pub fn panic(msg: []const u8, _: ?*std.builtin.StackTrace, begin_addr: ?usize) noreturn {
+pub fn panic(msg: []const u8, _: ?*std.lang.StackTrace, begin_addr: ?usize) noreturn {
@branchHint(.cold);
crash(msg, .{ .source = "global" }, begin_addr orelse @returnAddress());
}
@@ -60,13 +60,13 @@ pub noinline fn crash(
) catch abort();
writer.print("\nreason: {s}\n", .{reason}) catch abort();
- writer.print("OS: {s}\n", .{@tagName(builtin.os.tag)}) catch abort();
+ writer.print("OS: {s}\n", .{@tagName(builtin.target.os.tag)}) catch abort();
writer.print("mode: {s}\n", .{@tagName(builtin.mode)}) catch abort();
writer.print("version: {s}\n", .{lp.build_config.version}) catch abort();
writeCurrentPage(writer);
- inline for (@typeInfo(@TypeOf(args)).@"struct".fields) |f| {
- writer.writeAll(f.name ++ ": ") catch break;
- lp.log.writeValue(.pretty, @field(args, f.name), writer) catch abort();
+ inline for (@typeInfo(@TypeOf(args)).@"struct".field_names) |field_name| {
+ writer.writeAll(field_name ++ ": ") catch break;
+ lp.log.writeValue(.pretty, @field(args, field_name), writer) catch abort();
writer.writeByte('\n') catch abort();
}
@@ -118,14 +118,14 @@ fn report(reason: []const u8, begin_addr: usize, args: anytype) !void {
var body_buffer: [8192]u8 = undefined;
const body = blk: {
var writer: std.Io.Writer = .fixed(body_buffer[0..8191]); // reserve 1 space
- inline for (@typeInfo(@TypeOf(args)).@"struct".fields) |f| {
+ inline for (@typeInfo(@TypeOf(args)).@"struct".field_names) |field_name| {
// remove url value from the crash report.
- if (comptime std.mem.eql(u8, f.name, "url")) {
+ if (comptime std.mem.eql(u8, field_name, "url")) {
writer.writeAll("url: REDACTED\n") catch break;
continue;
}
- writer.writeAll(f.name ++ ": ") catch break;
- lp.log.writeValue(.pretty, @field(args, f.name), &writer) catch {};
+ writer.writeAll(field_name ++ ": ") catch break;
+ lp.log.writeValue(.pretty, @field(args, field_name), &writer) catch {};
writer.writeByte('\n') catch {};
}
@@ -209,7 +209,7 @@ var signal_handlers_attached = false;
// V8's WebAssembly trap handler is not enabled; enabling it would require
// giving it first chance at SIGSEGV/SIGBUS here.
pub fn attachSignalHandlers() void {
- if (builtin.os.tag != .linux or signal_handlers_attached) return;
+ if (builtin.target.os.tag != .linux or signal_handlers_attached) return;
signal_handlers_attached = true;
signal_output_fd = openSignalOutput();
var mask = std.posix.sigemptyset();
@@ -223,7 +223,7 @@ pub fn attachSignalHandlers() void {
}
fn openSignalOutput() std.c.fd_t {
- if (builtin.os.tag != .linux) return -1;
+ if (builtin.target.os.tag != .linux) return -1;
const S = std.os.linux.S;
const raw_flags = std.c.fcntl(2, std.posix.F.GETFL);
@@ -290,7 +290,7 @@ fn handleFatalSignal(sig: std.posix.SIG, info: *const std.posix.siginfo_t, ctx_p
}
_ = std.c.raise(sig);
- std.c._exit(@intCast(128 + @intFromEnum(sig)));
+ std.c._exit(@intCast(128 + @backingInt(sig)));
}
// The page this thread was working on. Local output only (never sent to the
@@ -315,7 +315,7 @@ fn writeRecord(record: []const u8) void {
fn writeSignalContext(writer: *std.Io.Writer, sig: std.posix.SIG, info: *const std.posix.siginfo_t, context: ?*const std.debug.cpu_context.Native) !void {
try writer.print("\nLightpanda fatal signal: {t} ({d})\nversion: {s}\nOS: {s}\nmode: {s}\ncode: {d}\n", .{
- sig, @intFromEnum(sig), lp.build_config.version, @tagName(builtin.os.tag), @tagName(builtin.mode), info.code,
+ sig, @backingInt(sig), lp.build_config.version, @tagName(builtin.target.os.tag), @tagName(builtin.mode), info.code,
});
if (faultAddress(info)) |address| {
try writer.print("address: 0x{x}\n", .{address});
@@ -327,7 +327,7 @@ fn writeSignalContext(writer: *std.Io.Writer, sig: std.posix.SIG, info: *const s
if (context) |ctx| {
try writer.print("pc: 0x{x}\nfp: 0x{x}\n", .{ ctx.getPc(), ctx.getFp() });
if (stackPointer(ctx)) |sp| try writer.print("sp: 0x{x}\n", .{sp});
- switch (builtin.cpu.arch) {
+ switch (builtin.target.cpu.arch) {
.aarch64 => try writer.print("lr: 0x{x}\n", .{ctx.x[30]}),
else => {},
}
@@ -364,7 +364,7 @@ fn writeBacktrace(ctx: *const std.debug.cpu_context.Native) void {
}
fn stackPointer(ctx: *const std.debug.cpu_context.Native) ?usize {
- return switch (builtin.cpu.arch) {
+ return switch (builtin.target.cpu.arch) {
.aarch64 => ctx.sp,
.x86_64 => ctx.gprs.get(.rsp),
else => null,
@@ -380,7 +380,7 @@ fn faultAddress(info: *const std.posix.siginfo_t) ?usize {
const testing = @import("testing.zig");
test "crash_handler: fatal signals preserve termination with unavailable stderr" {
- if (builtin.os.tag != .linux) return error.SkipZigTest;
+ if (builtin.target.os.tag != .linux) return error.SkipZigTest;
for (fatal_signals) |sig| {
for ([_]SignalTestMode{ .normal, .pipe, .tty, .closed, .broken_pipe, .locked_panic, .regular_file, .read_only_pipe }) |mode| {
try testSignal(sig, mode);
@@ -389,7 +389,7 @@ test "crash_handler: fatal signals preserve termination with unavailable stderr"
}
test "crash_handler: full stderr must not delay termination" {
- if (builtin.os.tag != .linux) return error.SkipZigTest;
+ if (builtin.target.os.tag != .linux) return error.SkipZigTest;
for (fatal_signals) |sig| {
try testSignal(sig, .full_pipe);
try testSignal(sig, .full_socket);
@@ -397,12 +397,12 @@ test "crash_handler: full stderr must not delay termination" {
}
test "crash_handler: hardware fault reports the interrupted context" {
- if (builtin.os.tag != .linux) return error.SkipZigTest;
+ if (builtin.target.os.tag != .linux) return error.SkipZigTest;
try testSignal(.SEGV, .hardware);
}
test "crash_handler: fatal signal after fork from a non-main thread" {
- if (builtin.os.tag != .linux) return error.SkipZigTest;
+ if (builtin.target.os.tag != .linux) return error.SkipZigTest;
const Worker = struct {
fn run(result: *?anyerror) void {
testSignal(.SEGV, .hardware) catch |err| {
@@ -417,7 +417,7 @@ test "crash_handler: fatal signal after fork from a non-main thread" {
}
test "crash_handler: unknown signal addresses are not read" {
- if (builtin.os.tag != .linux) return error.SkipZigTest;
+ if (builtin.target.os.tag != .linux) return error.SkipZigTest;
var info: std.posix.siginfo_t = undefined;
for ([_]c_int{ 0, -1, -6, 128, 0x10001 }) |code| {
info.code = code;
@@ -490,7 +490,7 @@ fn testSignal(sig: std.posix.SIG, mode: SignalTestMode) !void {
}
if (pid == 0) {
// Keep a regression from hanging the runner or writing a core.
- _ = std.os.linux.prctl(@intFromEnum(std.os.linux.PR.SET_DUMPABLE), 0, 0, 0, 0);
+ _ = std.os.linux.prctl(@backingInt(std.os.linux.PR.SET_DUMPABLE), 0, 0, 0, 0);
const default: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.DFL }, .mask = std.posix.sigemptyset(), .flags = 0 };
std.posix.sigaction(.ALRM, &default, null);
std.posix.sigaction(.PIPE, &default, null);
@@ -514,7 +514,7 @@ fn testSignal(sig: std.posix.SIG, mode: SignalTestMode) !void {
const flags = std.c.fcntl(2, std.posix.F.GETFL);
const nonblock: c_int = @bitCast(@as(u32, @bitCast(std.posix.O{ .NONBLOCK = true })));
if (std.c.fcntl(2, std.posix.F.SETFL, flags | nonblock) < 0) std.c._exit(1);
- const fill = [_]u8{'x'} ** 1024;
+ const fill: [1024]u8 = @splat('x');
for ([_]usize{ fill.len, 1 }) |len| {
while (true) {
const written = std.c.write(2, &fill, len);
@@ -561,7 +561,7 @@ fn testSignal(sig: std.posix.SIG, mode: SignalTestMode) !void {
// only ever goes pending and the handler's fallback exit is what ends
// the process. Everything before that point is unaffected.
try testing.expectEqual(true, std.posix.W.IFEXITED(raw));
- try testing.expectEqual(@as(u8, @intCast(128 + @intFromEnum(sig))), std.posix.W.EXITSTATUS(raw));
+ try testing.expectEqual(@as(u8, @intCast(128 + @backingInt(sig))), std.posix.W.EXITSTATUS(raw));
} else {
try testing.expectEqual(true, std.posix.W.IFSIGNALED(raw));
try testing.expectEqual(sig, std.posix.W.TERMSIG(raw));
@@ -592,7 +592,7 @@ fn testSignal(sig: std.posix.SIG, mode: SignalTestMode) !void {
try testing.expectEqual(true, std.mem.containsAtLeast(u8, text, 1, "\nbacktrace: 0x"));
if (mode == .hardware) {
var address_buffer: [64]u8 = undefined;
- const address = try std.fmt.bufPrint(&address_buffer, "address: 0x{x}\n", .{@intFromPtr(guard.?.ptr)});
+ const address = try std.mem.print(&address_buffer, "address: 0x{x}\n", .{@intFromPtr(guard.?.ptr)});
try testing.expectEqual(true, std.mem.containsAtLeast(u8, text, 1, address));
// The faulting pc alone is not a backtrace: the walk has to have
// followed at least one link out of the frame that faulted.
diff --git a/src/datetime.zig b/src/datetime.zig
index bf7fcf78e..0a4ef1714 100644
--- a/src/datetime.zig
+++ b/src/datetime.zig
@@ -339,7 +339,7 @@ pub const DateTime = struct {
_ = std.meta.stringToEnum(enum { UT, GMT, Z }, parser.rest()) orelse return error.UnsupportedTimeZone;
- return initUTC(year, @intFromEnum(month) + 1, day, tm.hour, tm.min, tm.sec, tm.micros);
+ return initUTC(year, @backingInt(month) + 1, day, tm.hour, tm.min, tm.sec, tm.micros);
}
fn parseRFC3339(input: []const u8) !DateTime {
@@ -831,13 +831,13 @@ test "Date: json" {
test "Date: format" {
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Date{ .year = 2023, .month = 5, .day = 22 }});
+ const out = try std.mem.print(&buf, "{f}", .{Date{ .year = 2023, .month = 5, .day = 22 }});
try testing.expectString("2023-05-22", out);
}
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Date{ .year = -102, .month = 12, .day = 9 }});
+ const out = try std.mem.print(&buf, "{f}", .{Date{ .year = -102, .month = 12, .day = 9 }});
try testing.expectString("-0102-12-09", out);
}
}
@@ -1022,37 +1022,37 @@ test "Time: json" {
test "Time: format" {
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Time{ .hour = 23, .min = 59, .sec = 59, .micros = 0 }});
+ const out = try std.mem.print(&buf, "{f}", .{Time{ .hour = 23, .min = 59, .sec = 59, .micros = 0 }});
try testing.expectString("23:59:59", out);
}
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 12 }});
+ const out = try std.mem.print(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 12 }});
try testing.expectString("08:09:10.000012", out);
}
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 123 }});
+ const out = try std.mem.print(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 123 }});
try testing.expectString("08:09:10.000123", out);
}
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 1234 }});
+ const out = try std.mem.print(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 1234 }});
try testing.expectString("08:09:10.001234", out);
}
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 12345 }});
+ const out = try std.mem.print(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 12345 }});
try testing.expectString("08:09:10.012345", out);
}
{
var buf: [20]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 123456 }});
+ const out = try std.mem.print(&buf, "{f}", .{Time{ .hour = 8, .min = 9, .sec = 10, .micros = 123456 }});
try testing.expectString("08:09:10.123456", out);
}
}
@@ -1737,37 +1737,37 @@ test "DateTime: json" {
test "DateTime: format" {
{
var buf: [30]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 23, 59, 59, 0)});
+ const out = try std.mem.print(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 23, 59, 59, 0)});
try testing.expectString("2023-05-22T23:59:59Z", out);
}
{
var buf: [30]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 8, 9, 10, 12)});
+ const out = try std.mem.print(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 8, 9, 10, 12)});
try testing.expectString("2023-05-22T08:09:10.000012Z", out);
}
{
var buf: [30]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 8, 9, 10, 123)});
+ const out = try std.mem.print(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 8, 9, 10, 123)});
try testing.expectString("2023-05-22T08:09:10.000123Z", out);
}
{
var buf: [30]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 8, 9, 10, 1234)});
+ const out = try std.mem.print(&buf, "{f}", .{try DateTime.initUTC(2023, 5, 22, 8, 9, 10, 1234)});
try testing.expectString("2023-05-22T08:09:10.001234Z", out);
}
{
var buf: [30]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{try DateTime.initUTC(-102, 12, 9, 8, 9, 10, 12345)});
+ const out = try std.mem.print(&buf, "{f}", .{try DateTime.initUTC(-102, 12, 9, 8, 9, 10, 12345)});
try testing.expectString("-0102-12-09T08:09:10.012345Z", out);
}
{
var buf: [30]u8 = undefined;
- const out = try std.fmt.bufPrint(&buf, "{f}", .{try DateTime.initUTC(-102, 12, 9, 8, 9, 10, 123456)});
+ const out = try std.mem.print(&buf, "{f}", .{try DateTime.initUTC(-102, 12, 9, 8, 9, 10, 123456)});
try testing.expectString("-0102-12-09T08:09:10.123456Z", out);
}
}
@@ -2171,7 +2171,7 @@ test "DateTime: sub" {
fn expectDateTime(expected: []const u8, dt: DateTime) !void {
var buf: [30]u8 = undefined;
- const actual = try std.fmt.bufPrint(&buf, "{f}", .{dt});
+ const actual = try std.mem.print(&buf, "{f}", .{dt});
try testing.expectString(expected, actual);
}
diff --git a/src/lightpanda.zig b/src/lightpanda.zig
index 68a13942c..c7f8c94a1 100644
--- a/src/lightpanda.zig
+++ b/src/lightpanda.zig
@@ -73,7 +73,7 @@ pub const Command = @import("script/command.zig").Command;
pub var metrics = @import("Metrics.zig"){};
pub const IS_TEST = @import("builtin").is_test;
-pub const IS_DEBUG = @import("builtin").mode == .Debug;
+pub const IS_DEBUG = @import("builtin").mode == .debug;
/// Process-wide Io instance for blocking syscalls (fs, net, time, futex).
/// Single-threaded-init only disables Io.async/Io.concurrent task spawning;
diff --git a/src/log.zig b/src/log.zig
index ccc301908..d8387e331 100644
--- a/src/log.zig
+++ b/src/log.zig
@@ -48,7 +48,7 @@ pub const Scope = enum {
cors,
};
-const num_scopes = @typeInfo(Scope).@"enum".fields.len;
+const num_scopes = @typeInfo(Scope).@"enum".field_names.len;
/// A single `--log-filter-scopes` directive. `scope == null` targets every
/// scope (the `all` keyword). `enable` is true for `+X` (filter in), false
@@ -63,10 +63,10 @@ pub const FilterRule = struct {
/// scope then re-enables `cdp`. Scopes untouched by any directive stay
/// enabled.
pub fn resolveFilters(rules: []const FilterRule) [num_scopes]bool {
- var scope_enabled = [_]bool{true} ** num_scopes;
+ var scope_enabled: [num_scopes]bool = @splat(true);
for (rules) |rule| {
if (rule.scope) |scope| {
- scope_enabled[@intFromEnum(scope)] = rule.enable;
+ scope_enabled[@backingInt(scope)] = rule.enable;
} else {
for (&scope_enabled) |*e| e.* = rule.enable;
}
@@ -78,7 +78,7 @@ const Opts = struct {
format: Format = if (lp.IS_DEBUG) .pretty else .logfmt,
level: Level = if (lp.IS_DEBUG) .info else .warn,
// Per-scope enabled flags; a `false` entry suppresses that scope's logs.
- scope_enabled: [num_scopes]bool = [_]bool{true} ** num_scopes,
+ scope_enabled: [num_scopes]bool = @splat(true),
color: ?bool = null,
};
@@ -118,11 +118,11 @@ fn clearColor(writer: *std.Io.Writer) !void {
pub var sink: ?*const fn (bytes: []const u8) void = null;
pub fn enabled(scope: Scope, level: Level) bool {
- if (@intFromEnum(level) < @intFromEnum(opts.level)) {
+ if (@backingInt(level) < @backingInt(opts.level)) {
return false;
}
- if (opts.scope_enabled[@intFromEnum(scope)] == false) {
+ if (opts.scope_enabled[@backingInt(scope)] == false) {
return false;
}
@@ -138,7 +138,7 @@ var expected_logs: [num_scopes]u16 = @splat(0);
pub fn expectLog(comptime scopes: []const Scope) void {
comptime std.debug.assert(lp.IS_TEST);
inline for (scopes) |scope| {
- expected_logs[@intFromEnum(scope)] += 1;
+ expected_logs[@backingInt(scope)] += 1;
}
}
@@ -240,15 +240,15 @@ pub fn warnDisabledIFrame() void {
}
pub fn log(scope: Scope, level: Level, msg: []const u8, data: anytype) void {
- var kvs: [@typeInfo(@TypeOf(data)).@"struct".fields.len]KV = undefined;
+ var kvs: [@typeInfo(@TypeOf(data)).@"struct".field_names.len]KV = undefined;
initKVs(data, &kvs);
logKVs(scope, level, msg, &kvs);
}
inline fn initKVs(data: anytype, kvs: []KV) void {
- inline for (@typeInfo(@TypeOf(data)).@"struct".fields, 0..) |f, i| {
- const value = @field(data, f.name);
- kvs[i] = .{ .key = f.name, .value = Value.init(&value) };
+ inline for (@typeInfo(@TypeOf(data)).@"struct".field_names, 0..) |field_name, i| {
+ const value = @field(data, field_name);
+ kvs[i] = .{ .key = field_name, .value = Value.init(&value) };
}
}
@@ -258,7 +258,7 @@ pub fn logKVs(scope: Scope, level: Level, msg: []const u8, kvs: []const KV) void
}
if (comptime lp.IS_TEST) {
- const expected = &expected_logs[@intFromEnum(scope)];
+ const expected = &expected_logs[@backingInt(scope)];
if (expected.* > 0) {
expected.* -= 1;
return;
@@ -266,7 +266,7 @@ pub fn logKVs(scope: Scope, level: Level, msg: []const u8, kvs: []const KV) void
}
if (current_page) |page| {
- if (level != .note and @intFromEnum(level) > @intFromEnum(page.max_level)) {
+ if (level != .note and @backingInt(level) > @backingInt(page.max_level)) {
page.max_level = level;
}
}
@@ -294,7 +294,7 @@ pub fn logKVs(scope: Scope, level: Level, msg: []const u8, kvs: []const KV) void
// Like `log`, but to an explicit writer and without the enabled/sink
// gating. Only used by tests.
fn logTo(scope: Scope, level: Level, msg: []const u8, data: anytype, out: *std.Io.Writer) !void {
- var kvs: [@typeInfo(@TypeOf(data)).@"struct".fields.len]KV = undefined;
+ var kvs: [@typeInfo(@TypeOf(data)).@"struct".field_names.len]KV = undefined;
initKVs(data, &kvs);
return logToErased(scope, level, msg, &kvs, out);
}
@@ -882,8 +882,8 @@ test "log: resolveFilters" {
// No directives: everything enabled.
{
const se = resolveFilters(&.{});
- try testing.expectEqual(true, se[@intFromEnum(Scope.cdp)]);
- try testing.expectEqual(true, se[@intFromEnum(Scope.http)]);
+ try testing.expectEqual(true, se[@backingInt(Scope.cdp)]);
+ try testing.expectEqual(true, se[@backingInt(Scope.http)]);
}
// Backward compatible: bare/`-` scope filters that scope out, rest stay in.
@@ -892,9 +892,9 @@ test "log: resolveFilters" {
.{ .scope = .cdp, .enable = false },
.{ .scope = .http, .enable = false },
});
- try testing.expectEqual(false, se[@intFromEnum(Scope.cdp)]);
- try testing.expectEqual(false, se[@intFromEnum(Scope.http)]);
- try testing.expectEqual(true, se[@intFromEnum(Scope.js)]);
+ try testing.expectEqual(false, se[@backingInt(Scope.cdp)]);
+ try testing.expectEqual(false, se[@backingInt(Scope.http)]);
+ try testing.expectEqual(true, se[@backingInt(Scope.js)]);
}
// `-all,+cdp`: disable everything, then re-enable cdp.
@@ -903,9 +903,9 @@ test "log: resolveFilters" {
.{ .scope = null, .enable = false },
.{ .scope = .cdp, .enable = true },
});
- try testing.expectEqual(true, se[@intFromEnum(Scope.cdp)]);
- try testing.expectEqual(false, se[@intFromEnum(Scope.http)]);
- try testing.expectEqual(false, se[@intFromEnum(Scope.js)]);
+ try testing.expectEqual(true, se[@backingInt(Scope.cdp)]);
+ try testing.expectEqual(false, se[@backingInt(Scope.http)]);
+ try testing.expectEqual(false, se[@backingInt(Scope.js)]);
}
// `+all,-cdp`: enable everything, then disable cdp. Order matters.
@@ -914,7 +914,7 @@ test "log: resolveFilters" {
.{ .scope = null, .enable = true },
.{ .scope = .cdp, .enable = false },
});
- try testing.expectEqual(false, se[@intFromEnum(Scope.cdp)]);
- try testing.expectEqual(true, se[@intFromEnum(Scope.http)]);
+ try testing.expectEqual(false, se[@backingInt(Scope.cdp)]);
+ try testing.expectEqual(true, se[@backingInt(Scope.http)]);
}
}
diff --git a/src/main.zig b/src/main.zig
index 04955996d..9b379bed5 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -32,13 +32,13 @@ pub const std_options: std.Options = .{
pub fn main(init: std.process.Init) !void {
// allocator
- // - in Debug mode we use the General Purpose Allocator to detect memory leaks
+ // - in Debug mode we use the SafeAllocator to detect memory leaks
// - in Release mode we use the c allocator
- var gpa_instance: std.heap.DebugAllocator(.{ .stack_trace_frames = 10 }) = .init;
+ var gpa_instance: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{ .stack_trace_frames = 10 });
const gpa = if (lp.IS_DEBUG) gpa_instance.allocator() else std.heap.c_allocator;
defer if (lp.IS_DEBUG) {
- if (gpa_instance.detectLeaks() != 0) std.process.exit(1);
+ if (gpa_instance.deinit() != 0) std.process.exit(1);
};
// arena for main-specific allocations
diff --git a/src/malloc_tuning.zig b/src/malloc_tuning.zig
index 8dffa6622..23e165696 100644
--- a/src/malloc_tuning.zig
+++ b/src/malloc_tuning.zig
@@ -41,7 +41,7 @@ const M_MMAP_THRESHOLD: c_int = -3;
extern "c" fn mallopt(param: c_int, value: c_int) c_int;
pub fn apply() void {
- if (comptime (builtin.os.tag != .linux or builtin.abi.isGnu() == false)) {
+ if (comptime (builtin.target.os.tag != .linux or builtin.target.abi.isGnu() == false)) {
return;
}
if (userConfigured()) {
diff --git a/src/mcp/HttpServer.zig b/src/mcp/HttpServer.zig
index 52cac92fa..59989e270 100644
--- a/src/mcp/HttpServer.zig
+++ b/src/mcp/HttpServer.zig
@@ -211,7 +211,7 @@ pub fn run(self: *HttpServer, address: sys_net.IpAddress) !void {
self.listener = listener;
// On non-Linux stop() closes the listener itself to unblock accept.
- defer if (builtin.os.tag == .linux) {
+ defer if (builtin.target.os.tag == .linux) {
_ = std.c.close(listener);
};
@@ -234,7 +234,7 @@ pub fn run(self: *HttpServer, address: sys_net.IpAddress) !void {
/// only on close(), in which case run() must not close it again.
pub fn stop(self: *HttpServer) void {
self.shutting_down.store(true, .release);
- switch (builtin.os.tag) {
+ switch (builtin.target.os.tag) {
.linux => sys_net.shutdown(self.listener, .recv) catch {},
else => _ = std.c.close(self.listener),
}
diff --git a/src/mcp/Server.zig b/src/mcp/Server.zig
index 1ec925c66..78ce30836 100644
--- a/src/mcp/Server.zig
+++ b/src/mcp/Server.zig
@@ -147,7 +147,7 @@ pub fn useSession(self: *Self, id: ?[]const u8) !*lp.ToolSession {
pub fn nextSessionId(self: *Self, arena: std.mem.Allocator) ![]const u8 {
while (true) {
self.session_seq += 1;
- const candidate = try std.fmt.allocPrint(arena, "s{d}", .{self.session_seq});
+ const candidate = try arena.print("s{d}", .{self.session_seq});
if (!self.sessions.contains(candidate)) return candidate;
}
}
diff --git a/src/mcp/Transport.zig b/src/mcp/Transport.zig
index 16f4f7bfc..ea7aedbaf 100644
--- a/src/mcp/Transport.zig
+++ b/src/mcp/Transport.zig
@@ -77,7 +77,7 @@ pub fn sendError(self: *Self, id: std.json.Value, code: protocol.ErrorCode, mess
try self.sendResponse(protocol.Response{
.id = id,
.@"error" = protocol.Error{
- .code = @intFromEnum(code),
+ .code = @backingInt(code),
.message = message,
},
});
diff --git a/src/mcp/protocol.zig b/src/mcp/protocol.zig
index 5b2efc198..0ecd3e4af 100644
--- a/src/mcp/protocol.zig
+++ b/src/mcp/protocol.zig
@@ -318,7 +318,7 @@ test "MCP.protocol - error formatting" {
const response = Response{
.id = .{ .string = "abc" },
.@"error" = .{
- .code = @intFromEnum(ErrorCode.MethodNotFound),
+ .code = @backingInt(ErrorCode.MethodNotFound),
.message = "Method not found",
},
};
diff --git a/src/mcp/tools.zig b/src/mcp/tools.zig
index b6d9b917c..f1d42de05 100644
--- a/src/mcp/tools.zig
+++ b/src/mcp/tools.zig
@@ -13,16 +13,16 @@ const McpTool = protocol.Tool;
/// Tool identity comes from the `BrowserTool` tag — `tool_defs` only
/// carries the LLM-facing description and JSON schema.
const browser_tool_list = blk: {
- const fields = @typeInfo(BrowserTool).@"enum".fields;
- var tools: [fields.len]McpTool = undefined;
- for (browser_tools.tool_defs, fields, 0..) |td, f, i| {
+ const field_names = @typeInfo(BrowserTool).@"enum".field_names;
+ var tools: [field_names.len]McpTool = undefined;
+ for (browser_tools.tool_defs, field_names, 0..) |td, field_name, i| {
tools[i] = .{
- .name = f.name,
+ .name = field_name,
.title = td.summary,
.description = td.description,
.inputSchema = td.input_schema,
- .outputSchema = if (@field(BrowserTool, f.name).reportsPageState()) page_state_schema else null,
- .annotations = annotations(@field(BrowserTool, f.name)),
+ .outputSchema = if (@field(BrowserTool, field_name).reportsPageState()) page_state_schema else null,
+ .annotations = annotations(@field(BrowserTool, field_name)),
};
}
break :blk tools;
@@ -226,14 +226,14 @@ fn handleSave(server: *Server, arena: std.mem.Allocator, id: std.json.Value, arg
return sendErrorContent(server, id, "out of memory");
writeScript(args.path, script) catch |err| {
- const msg = std.fmt.allocPrint(arena, "could not write {s}: {s}", .{ args.path, @errorName(err) }) catch
+ const msg = arena.print("could not write {s}: {s}", .{ args.path, @errorName(err) }) catch
return sendErrorContent(server, id, "could not write script file");
return sendErrorContent(server, id, msg);
};
const where = browser_tools.absolutePath(arena, args.path);
const lines = std.mem.count(u8, script, "\n") + 1;
- const msg = std.fmt.allocPrint(arena, "saved {d} line(s) to {s}", .{ lines, where }) catch
+ const msg = arena.print("saved {d} line(s) to {s}", .{ lines, where }) catch
return sendErrorContent(server, id, "out of memory");
try sendToolResultText(server, id, msg, false);
@@ -321,7 +321,7 @@ fn sendErrorContent(server: *Server, id: std.json.Value, msg: []const u8) !void
}
fn sendToolResultFmt(server: *Server, arena: std.mem.Allocator, id: std.json.Value, comptime fmt: []const u8, args: anytype) !void {
- const msg = std.fmt.allocPrint(arena, fmt, args) catch
+ const msg = arena.print(fmt, args) catch
return sendErrorContent(server, id, "out of memory");
return sendToolResultText(server, id, msg, false);
}
@@ -1238,7 +1238,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const btn = frame.document.getElementById("btn", frame).?.asNode();
const btn_id = (try server.active_session.registry.register(btn)).id;
var btn_id_buf: [12]u8 = undefined;
- const btn_id_str = std.fmt.bufPrint(&btn_id_buf, "{d}", .{btn_id}) catch unreachable;
+ const btn_id_str = std.mem.print(&btn_id_buf, "{d}", .{btn_id}) catch unreachable;
const click_msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"click\",\"arguments\":{\"backendNodeId\":", btn_id_str, "}}}" });
try router.handleMessage(server, aa, click_msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Clicked element") != null);
@@ -1247,7 +1247,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
}
for ([_][]const u8{ "#btnPreventDefault", "#btnDisabled", "#focusTarget", "#plain" }) |selector| {
- const msg = try std.fmt.allocPrint(aa, "{{\"jsonrpc\":\"2.0\",\"id\":10,\"method\":\"tools/call\",\"params\":{{\"name\":\"click\",\"arguments\":{{\"selector\":\"{s}\"}}}}}}", .{selector});
+ const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":10,\"method\":\"tools/call\",\"params\":{{\"name\":\"click\",\"arguments\":{{\"selector\":\"{s}\"}}}}}}", .{selector});
try router.handleMessage(server, aa, msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Clicked element") != null);
out.clearRetainingCapacity();
@@ -1257,7 +1257,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const inp = frame.document.getElementById("inp", frame).?.asNode();
const inp_id = (try server.active_session.registry.register(inp)).id;
var inp_id_buf: [12]u8 = undefined;
- const inp_id_str = std.fmt.bufPrint(&inp_id_buf, "{d}", .{inp_id}) catch unreachable;
+ const inp_id_str = std.mem.print(&inp_id_buf, "{d}", .{inp_id}) catch unreachable;
const fill_msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"fill\",\"arguments\":{\"backendNodeId\":", inp_id_str, ",\"value\":\"hello\"}}}" });
try router.handleMessage(server, aa, fill_msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Filled element") != null);
@@ -1269,7 +1269,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const sel = frame.document.getElementById("sel", frame).?.asNode();
const sel_id = (try server.active_session.registry.register(sel)).id;
var sel_id_buf: [12]u8 = undefined;
- const sel_id_str = std.fmt.bufPrint(&sel_id_buf, "{d}", .{sel_id}) catch unreachable;
+ const sel_id_str = std.mem.print(&sel_id_buf, "{d}", .{sel_id}) catch unreachable;
const fill_sel_msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"fill\",\"arguments\":{\"backendNodeId\":", sel_id_str, ",\"value\":\"opt2\"}}}" });
try router.handleMessage(server, aa, fill_sel_msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Filled element") != null);
@@ -1284,9 +1284,9 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const plain = frame.document.getElementById("plain", frame).?.asNode();
const plain_id = (try server.active_session.registry.register(plain)).id;
for ([_]struct { id: lp.NodeRegistry.Id, y: i32 }{ .{ .id = scrollbox_id, .y = 50 }, .{ .id = plain_id, .y = 7 } }) |c| {
- const msg = try std.fmt.allocPrint(aa, "{{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":{d}}}}}}}", .{ c.id, c.y });
+ const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":{d}}}}}}}", .{ c.id, c.y });
try router.handleMessage(server, aa, msg);
- const expected = try std.fmt.allocPrint(aa, "Scrolled element (backendNodeId: {d}) to x: 0, y: {d}", .{ c.id, c.y });
+ const expected = try aa.print("Scrolled element (backendNodeId: {d}) to x: 0, y: {d}", .{ c.id, c.y });
try testing.expect(std.mem.indexOf(u8, out.written(), expected) != null);
out.clearRetainingCapacity();
}
@@ -1297,9 +1297,9 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const leaf_id = (try server.active_session.registry.register(leaf)).id;
const outer = frame.document.getElementById("outerscroll", frame).?.asNode();
const outer_id = (try server.active_session.registry.register(outer)).id;
- const msg = try std.fmt.allocPrint(aa, "{{\"jsonrpc\":\"2.0\",\"id\":40,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":30}}}}}}", .{leaf_id});
+ const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":40,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":30}}}}}}", .{leaf_id});
try router.handleMessage(server, aa, msg);
- const expected = try std.fmt.allocPrint(aa, "Scrolled scroll container (backendNodeId: {d}) of element (backendNodeId: {d}) to x: 0, y: 30", .{ outer_id, leaf_id });
+ const expected = try aa.print("Scrolled scroll container (backendNodeId: {d}) of element (backendNodeId: {d}) to x: 0, y: 30", .{ outer_id, leaf_id });
try testing.expect(std.mem.indexOf(u8, out.written(), expected) != null);
out.clearRetainingCapacity();
}
@@ -1311,7 +1311,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
try router.handleMessage(server, aa,
\\{"jsonrpc":"2.0","id":41,"method":"tools/call","params":{"name":"scroll","arguments":{"selector":"#innerleaf","y":30}}}
);
- const expected = try std.fmt.allocPrint(aa, "Scrolled scroll container (backendNodeId: {d}) of element (selector: #innerleaf) to x: 0, y: 30", .{outer_id});
+ const expected = try aa.print("Scrolled scroll container (backendNodeId: {d}) of element (selector: #innerleaf) to x: 0, y: 30", .{outer_id});
try testing.expect(std.mem.indexOf(u8, out.written(), expected) != null);
out.clearRetainingCapacity();
}
@@ -1322,9 +1322,9 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const leaf_id = (try server.active_session.registry.register(leaf)).id;
const outer = frame.document.getElementById("sheetscroll", frame).?.asNode();
const outer_id = (try server.active_session.registry.register(outer)).id;
- const msg = try std.fmt.allocPrint(aa, "{{\"jsonrpc\":\"2.0\",\"id\":44,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":30}}}}}}", .{leaf_id});
+ const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":44,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":30}}}}}}", .{leaf_id});
try router.handleMessage(server, aa, msg);
- const expected = try std.fmt.allocPrint(aa, "Scrolled scroll container (backendNodeId: {d}) of element (backendNodeId: {d}) to x: 0, y: 30", .{ outer_id, leaf_id });
+ const expected = try aa.print("Scrolled scroll container (backendNodeId: {d}) of element (backendNodeId: {d}) to x: 0, y: 30", .{ outer_id, leaf_id });
try testing.expect(std.mem.indexOf(u8, out.written(), expected) != null);
out.clearRetainingCapacity();
}
@@ -1347,7 +1347,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const el = frame.document.getElementById("hoverTarget", frame).?.asNode();
const el_id = (try server.active_session.registry.register(el)).id;
var id_buf: [12]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{el_id}) catch unreachable;
+ const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;
const msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"tools/call\",\"params\":{\"name\":\"hover\",\"arguments\":{\"backendNodeId\":", id_str, "}}}" });
try router.handleMessage(server, aa, msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Hovered element") != null);
@@ -1358,7 +1358,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const el = frame.document.getElementById("keyTarget", frame).?.asNode();
const el_id = (try server.active_session.registry.register(el)).id;
var id_buf: [12]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{el_id}) catch unreachable;
+ const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;
const msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"tools/call\",\"params\":{\"name\":\"press\",\"arguments\":{\"key\":\"Enter\",\"backendNodeId\":", id_str, "}}}" });
try router.handleMessage(server, aa, msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Pressed key") != null);
@@ -1369,7 +1369,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const el = frame.document.getElementById("sel2", frame).?.asNode();
const el_id = (try server.active_session.registry.register(el)).id;
var id_buf: [12]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{el_id}) catch unreachable;
+ const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;
const msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/call\",\"params\":{\"name\":\"selectOption\",\"arguments\":{\"backendNodeId\":", id_str, ",\"value\":\"b\"}}}" });
try router.handleMessage(server, aa, msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "Selected option") != null);
@@ -1380,7 +1380,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const el = frame.document.getElementById("chk", frame).?.asNode();
const el_id = (try server.active_session.registry.register(el)).id;
var id_buf: [12]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{el_id}) catch unreachable;
+ const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;
const msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":8,\"method\":\"tools/call\",\"params\":{\"name\":\"setChecked\",\"arguments\":{\"backendNodeId\":", id_str, ",\"checked\":true}}}" });
try router.handleMessage(server, aa, msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "checked") != null);
@@ -1391,7 +1391,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked
const el = frame.document.getElementById("rad", frame).?.asNode();
const el_id = (try server.active_session.registry.register(el)).id;
var id_buf: [12]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{el_id}) catch unreachable;
+ const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;
const msg = try std.mem.concat(aa, u8, &.{ "{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"tools/call\",\"params\":{\"name\":\"setChecked\",\"arguments\":{\"backendNodeId\":", id_str, ",\"checked\":true}}}" });
try router.handleMessage(server, aa, msg);
try testing.expect(std.mem.indexOf(u8, out.written(), "checked") != null);
@@ -1456,7 +1456,7 @@ test "MCP - click that navigates clears node registry" {
try testing.expect(server.active_session.registry.lookup_by_id.contains(link_id));
var id_buf: [12]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{link_id}) catch unreachable;
+ const id_str = std.mem.print(&id_buf, "{d}", .{link_id}) catch unreachable;
const click_msg = try std.mem.concat(aa, u8, &.{
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"click\",\"arguments\":{\"backendNodeId\":",
id_str,
diff --git a/src/network/CorsGate.zig b/src/network/CorsGate.zig
index 8cc3577bc..cff54f5de 100644
--- a/src/network/CorsGate.zig
+++ b/src/network/CorsGate.zig
@@ -414,7 +414,7 @@ const CorsPreflightContext = struct {
const capped_ms = capped_s * 1000;
const methods_wildcard = acam != null and std.mem.eql(u8, acam.?, "*") and !self.wants_credentials;
- var methods = std.EnumSet(http.Method).initEmpty();
+ var methods = std.EnumSet(http.Method).empty;
if (!methods_wildcard) {
if (acam) |list| {
var it = std.mem.splitScalar(u8, list, ',');
@@ -575,7 +575,7 @@ fn fetchThenResume(self: *CorsGate, transfer: *Transfer, authored_headers: []con
const arena = try arena_pool.acquire(.tiny, "CorsGate.CorsPreflightContext");
errdefer arena_pool.release(arena);
- const owned_url = try arena.dupeZ(u8, transfer.req.url);
+ const owned_url = try arena.dupeSentinel(u8, transfer.req.url, 0);
const owned_key = try arena.dupe(u8, key);
const owned_origin = try arena.dupe(u8, origin);
diff --git a/src/network/CorsStore.zig b/src/network/CorsStore.zig
index 6674542b1..552ce56ef 100644
--- a/src/network/CorsStore.zig
+++ b/src/network/CorsStore.zig
@@ -297,7 +297,7 @@ test "CorsStore: expired entries are treated as a miss on covers" {
try store.put(.{ .origin = "https://a.example", .target = "https://api.example", .credentials = false }, .{
.methods_wildcard = true,
- .methods = .initEmpty(),
+ .methods = .empty,
.headers_wildcard = true,
.headers = &.{}, // empty slice, nothing to free
.expires_at = lp.datetime.milliTimestamp(.real) - 1,
@@ -356,7 +356,7 @@ test "CorsStore: credentialed and non-credentialed grants for same origin/target
// Non-credentialed grant: wildcard headers allowed (valid per spec for non-cred requests).
try store.put(.{ .origin = origin, .target = target, .credentials = false }, .{
.methods_wildcard = true,
- .methods = .initEmpty(),
+ .methods = .empty,
.headers_wildcard = true,
.headers = &.{},
.expires_at = lp.datetime.milliTimestamp(.real) + 60_000,
@@ -407,7 +407,7 @@ test "CorsStore: covers never lets a wildcard cover Authorization" {
const key = Key{ .origin = "https://a.example", .target = "https://api.example", .credentials = false };
try store.put(key, .{
.methods_wildcard = true,
- .methods = .initEmpty(),
+ .methods = .empty,
.headers_wildcard = true,
.headers = &.{},
.expires_at = std.math.maxInt(u64),
diff --git a/src/network/HttpClient.zig b/src/network/HttpClient.zig
index 760f482cc..26eacc5e4 100644
--- a/src/network/HttpClient.zig
+++ b/src/network/HttpClient.zig
@@ -38,6 +38,7 @@ const Cache = @import("cache/Cache.zig");
const RobotsGate = @import("RobotsGate.zig");
const CorsGate = @import("CorsGate.zig");
const UrlBlocklist = @import("UrlBlocklist.zig");
+const repeat = @import("../string.zig").repeat;
pub const BlockPattern = UrlBlocklist.Pattern;
@@ -307,7 +308,7 @@ pub fn incrReqId(self: *Client) u32 {
// Set a user agent override, allocated from self.allocator.
pub fn setUserAgentOverride(self: *Client, ua: []const u8) !void {
self.clearUserAgentOverride();
- self.user_agent_override = try self.allocator.dupeZ(u8, ua);
+ self.user_agent_override = try self.allocator.dupeSentinel(u8, ua, 0);
}
// Clear any user agent override, restoring the default from config.
@@ -381,12 +382,12 @@ pub fn changeProxy(self: *Client, proxy: ?[:0]const u8) !void {
self.http_proxy_owned = null;
}
- // Reset to the config default; if dupeZ below fails, http_proxy is
+ // Reset to the config default; if dupeSentinel below fails, http_proxy is
// left pointing at this rather than at the freed dup.
self.http_proxy = self.network.config.httpProxy();
if (proxy) |p| {
- const owned = try self.allocator.dupeZ(u8, p);
+ const owned = try self.allocator.dupeSentinel(u8, p, 0);
self.http_proxy_owned = owned;
self.http_proxy = owned;
}
@@ -688,7 +689,7 @@ pub fn newRequest(self: *Client, req: Request, owner: ?*Owner) anyerror!*Transfe
//
// These are all small, so duping them into the transfer's arena is
// cheap and can solve some nasty UAF.
- owned.url = try arena.dupeZ(u8, req.url);
+ owned.url = try arena.dupeSentinel(u8, req.url, 0);
var cookie_jar: ?*CookieJar = null;
if (owner) |o| {
@@ -702,12 +703,12 @@ pub fn newRequest(self: *Client, req: Request, owner: ?*Owner) anyerror!*Transfe
// nothing reads the caller's (possibly short-lived) url through it.
const cookie_origin: Cookie.SiteForCookies = switch (req.cookie_origin orelse if (owner) |o| o.siteForCookies() else .none) {
.none => .none,
- .url => |url| .{ .url = try arena.dupeZ(u8, url) },
+ .url => |url| .{ .url = try arena.dupeSentinel(u8, url, 0) },
};
owned.cookie_origin = null;
if (req.basic_auth_credentials) |c| {
- owned.basic_auth_credentials = try arena.dupeZ(u8, c);
+ owned.basic_auth_credentials = try arena.dupeSentinel(u8, c, 0);
}
const raw_origin: ?[]const u8 = req.origin orelse if (owner) |o| o.scope.origin() else null;
@@ -1296,7 +1297,7 @@ fn cacheLookup(self: *Client, transfer: *Transfer) !bool {
// URL this lookup ran against, not the final hop. req.url is arena-owned,
// so the captured slice outlives any redirect rewrite.
const key: [:0]const u8 = if (req.partial != null)
- try std.fmt.allocPrintSentinel(arena.allocator(), "partial:{s}", .{req.url}, 0)
+ try arena.allocator().printSentinel("partial:{s}", .{req.url}, 0)
else
req.url;
transfer._cache_key = key;
@@ -2228,8 +2229,19 @@ fn fulfillRedirect(
headers: []const http.Header,
location: []const u8,
) !void {
- errdefer |err| transfer.abortPipelineError(err);
+ self.fulfillRedirectInner(transfer, status, headers, location) catch |err| {
+ transfer.abortPipelineError(err);
+ return err;
+ };
+}
+fn fulfillRedirectInner(
+ self: *Client,
+ transfer: *Transfer,
+ status: u16,
+ headers: []const http.Header,
+ location: []const u8,
+) !void {
// retrieve cookies from the fulfilled response's headers.
if (transfer.req.credentialsAllowed()) {
if (transfer.cookie_jar) |jar| {
@@ -2503,7 +2515,7 @@ pub const Transfer = struct {
return .none;
}
// it can only get further, so redirect a -> b -> a doesn't appear as a -> a
- return @enumFromInt(@max(@intFromEnum(self), @intFromEnum(forRequest(req))));
+ return @fromBackingInt(@max(@backingInt(self), @backingInt(forRequest(req))));
}
};
@@ -3392,7 +3404,7 @@ pub const Transfer = struct {
}
// buildResponseHeader stores a curl-owned url pointer; re-anchor it
// in the arena so it survives the conn release.
- self.res.header.?.url = (try arena.dupeZ(u8, std.mem.span(self.res.header.?.url))).ptr;
+ self.res.header.?.url = (try arena.dupeSentinel(u8, std.mem.span(self.res.header.?.url), 0)).ptr;
self.setResponseHeaders(try conn.collectResponseHeaders(arena.allocator()));
@@ -3667,7 +3679,7 @@ pub const Transfer = struct {
// value we have now as the base
if (transfer.findRequestHeader("referer")) |current| {
const alloc = arena.allocator();
- if (try referrer.compute(alloc, policy, try alloc.dupeZ(u8, current), req.url)) |value| {
+ if (try referrer.compute(alloc, policy, try alloc.dupeSentinel(u8, current, 0), req.url)) |value| {
try transfer.setHeader("Referer", value, .{});
} else {
transfer.removeHeader("Referer");
@@ -3786,7 +3798,7 @@ pub const Transfer = struct {
}
found = true;
- if (@intFromEnum(hdr.source) > @intFromEnum(source)) {
+ if (@backingInt(hdr.source) > @backingInt(source)) {
if (hdr.source == .fixed) {
log.debug(.http, "ignore overriding fixed header", .{ .header = hdr.name });
}
@@ -3794,7 +3806,7 @@ pub const Transfer = struct {
}
if (mode == .append and hdr.source == source) {
const sep = if (std.ascii.eqlIgnoreCase(name, "cookie")) "; " else ", ";
- hdr.value = try std.fmt.allocPrint(self.arena.allocator(), "{s}{s}{s}", .{ hdr.value, sep, value });
+ hdr.value = try self.arena.allocator().print("{s}{s}{s}", .{ hdr.value, sep, value });
return;
}
hdr.value = try self.arena.allocator().dupe(u8, value);
@@ -4859,12 +4871,12 @@ test "HttpClient: adblock verdicts apply per request" {
}));
try testing.expect(!testIsUrlBlocked(&client, .{
.url = "https://ads.example.com/pixel.gif",
- .document = "https://" ++ "a" ** 254 ++ ".com/",
+ .document = "https://" ++ repeat("a", 254) ++ ".com/",
.resource_type = .image,
}));
// Same for a URL too long to normalize (uppercase forces the copy).
try testing.expect(!testIsUrlBlocked(&client, .{
- .url = "https://ads.example.com/" ++ "A" ** (8 * 1024),
+ .url = "https://ads.example.com/" ++ repeat("A", 8 * 1024),
.document = "https://news.com/",
.resource_type = .image,
}));
@@ -5047,7 +5059,7 @@ test "HttpClient: Fetch header overrides restore after one hop" {
};
var transfer: Transfer = undefined;
- transfer.req_headers = .{ .items = &overridden, .capacity = overridden.len };
+ transfer.req_headers = .fromOwnedSlice(&overridden);
transfer._intercept_original_headers = &original;
transfer.restoreInterceptHeaders();
diff --git a/src/network/RateLimiter.zig b/src/network/RateLimiter.zig
index 1d4087d55..4d591c2dc 100644
--- a/src/network/RateLimiter.zig
+++ b/src/network/RateLimiter.zig
@@ -164,7 +164,7 @@ test "RateLimiter: sweep" {
var buf: [16]u8 = undefined;
for (0..3) |i| {
- _ = try rl.reserve(try std.fmt.bufPrint(&buf, "h{d}.test", .{i}), 1000);
+ _ = try rl.reserve(try std.mem.print(&buf, "h{d}.test", .{i}), 1000);
}
try testing.expectEqual(3, rl.next.count());
@@ -174,7 +174,7 @@ test "RateLimiter: sweep" {
try testing.expectEqual(8, rl.sweep_at);
for (4..7) |i| {
- _ = try rl.reserve(try std.fmt.bufPrint(&buf, "h{d}.test", .{i}), 1000);
+ _ = try rl.reserve(try std.mem.print(&buf, "h{d}.test", .{i}), 1000);
}
try testing.expectEqual(7, rl.next.count());
diff --git a/src/network/RobotsGate.zig b/src/network/RobotsGate.zig
index 29f6a66c4..46a798c0c 100644
--- a/src/network/RobotsGate.zig
+++ b/src/network/RobotsGate.zig
@@ -86,7 +86,7 @@ fn fetchThenResume(self: *RobotsGate, robots_url: [:0]const u8, transfer: *Trans
const arena = try client.arena_pool.acquire(.small, "RobotsGate.RobotsContext");
errdefer arena.release();
- const owned_url = try arena.dupeZ(u8, robots_url);
+ const owned_url = try arena.dupeSentinel(u8, robots_url, 0);
const robots_ctx = try arena.create(RobotsContext);
robots_ctx.* = .{
.gate = self,
diff --git a/src/network/WebBotAuth.zig b/src/network/WebBotAuth.zig
index 79e2245a0..05f54de45 100644
--- a/src/network/WebBotAuth.zig
+++ b/src/network/WebBotAuth.zig
@@ -73,8 +73,7 @@ pub fn fromConfig(allocator: std.mem.Allocator, config: *const Config) !WebBotAu
const pkey = try parsePemPrivateKey(pem);
errdefer crypto.EVP_PKEY_free(pkey);
- const directory_url = try std.fmt.allocPrintSentinel(
- allocator,
+ const directory_url = try allocator.printSentinel(
"https://{s}/.well-known/http-message-signatures-directory",
.{config.domain},
0,
@@ -99,15 +98,13 @@ pub fn signRequest(
const expires = now + 60;
// build the signature-input value (without the sig1= label)
- const sig_input_value = try std.fmt.allocPrint(
- arena,
+ const sig_input_value = try arena.print(
"(\"@authority\" \"signature-agent\");created={d};expires={d};keyid=\"{s}\";alg=\"ed25519\";tag=\"web-bot-auth\"",
.{ now, expires, self.keyid },
);
// build the canonical string to sign
- const canonical = try std.fmt.allocPrint(
- arena,
+ const canonical = try arena.print(
"\"@authority\": {s}\n\"signature-agent\": \"{s}\"\n\"@signature-params\": {s}",
.{ authority, self.directory_url, sig_input_value },
);
@@ -121,9 +118,9 @@ pub fn signRequest(
const encoded = try arena.alloc(u8, encoded_len);
_ = std.base64.standard.Encoder.encode(encoded, &sig);
- try transfer.setHeader("Signature-Agent", try std.fmt.allocPrint(arena, "\"{s}\"", .{self.directory_url}), .{});
- try transfer.setHeader("Signature-Input", try std.fmt.allocPrint(arena, "sig1={s}", .{sig_input_value}), .{});
- try transfer.setHeader("Signature", try std.fmt.allocPrint(arena, "sig1=:{s}:", .{encoded}), .{});
+ try transfer.setHeader("Signature-Agent", try arena.print("\"{s}\"", .{self.directory_url}), .{});
+ try transfer.setHeader("Signature-Input", try arena.print("sig1={s}", .{sig_input_value}), .{});
+ try transfer.setHeader("Signature", try arena.print("sig1=:{s}:", .{encoded}), .{});
}
pub fn deinit(self: WebBotAuth, allocator: std.mem.Allocator) void {
@@ -221,9 +218,10 @@ test "signRequest: adds headers with correct names" {
;
const pkey = try parsePemPrivateKey(pem);
- const directory_url = try allocator.dupeZ(
+ const directory_url = try allocator.dupeSentinel(
u8,
"https://example.com/.well-known/http-message-signatures-directory",
+ 0,
);
var auth = WebBotAuth{
diff --git a/src/network/adblock/AdBlocker.zig b/src/network/adblock/AdBlocker.zig
index b078cfd2c..b655bccdd 100644
--- a/src/network/adblock/AdBlocker.zig
+++ b/src/network/adblock/AdBlocker.zig
@@ -29,6 +29,7 @@ const Parser = @import("Parser.zig");
const Engine = @import("Engine.zig");
const HostnameTrie = @import("HostnameTrie.zig");
const NetworkFilter = @import("NetworkFilter.zig");
+const repeat = @import("../../string.zig").repeat;
const Regex = lp.Regex;
const log = lp.log;
@@ -443,7 +444,7 @@ fn identity(filter: *const NetworkFilter) u64 {
}
hasher.update(&std.mem.toBytes(filter.types.bits()));
hasher.update(&.{
- @intFromEnum(filter.kind),
+ @backingInt(filter.kind),
@intFromBool(filter.exception),
@intFromBool(filter.important),
@intFromBool(filter.first_party),
@@ -608,7 +609,7 @@ test "adblock.AdBlocker: tokens past the request buffer still match" {
// 140 tokens of query noise push the filter's token ("utm", its rarest)
// past what the request holds; the engine walks the rest of the URL.
- const noise = "https://example.com/?" ++ "a=1&" ** 70;
+ const noise = "https://example.com/?" ++ repeat("a=1&", 70);
var buf: [512]u8 = undefined;
const overflowing: Request = Request.init(noise ++ "utm_tracker=1", &buf, "a.com", script).?;
try testing.expect(overflowing.tail.len != 0);
diff --git a/src/network/adblock/Engine.zig b/src/network/adblock/Engine.zig
index ff19e3684..dcda3fece 100644
--- a/src/network/adblock/Engine.zig
+++ b/src/network/adblock/Engine.zig
@@ -40,6 +40,7 @@ const HttpClient = @import("../HttpClient.zig");
const domain = @import("domain.zig");
const pattern = @import("pattern.zig");
const NetworkFilter = @import("NetworkFilter.zig");
+const repeat = @import("../../string.zig").repeat;
const Allocator = std.mem.Allocator;
@@ -739,7 +740,7 @@ test "adblock.Engine: a request keeps its first tokens, the rest as tail" {
const kind: NetworkFilter.ResourceTypes = .{ .script = true };
// Exactly as many tokens as the buffer holds: nothing is left to walk...
- const full = "x/" ** (max - 1) ++ "x";
+ const full = repeat("x/", max - 1) ++ "x";
var buf: [512]u8 = undefined;
var request: Request = Request.init(full, &buf, "", kind).?;
try testing.expectEqual(max, request.tokens_len);
diff --git a/src/network/adblock/HostnameTrie.zig b/src/network/adblock/HostnameTrie.zig
index e19d066bd..501ecf40f 100644
--- a/src/network/adblock/HostnameTrie.zig
+++ b/src/network/adblock/HostnameTrie.zig
@@ -52,6 +52,7 @@ const std = @import("std");
const Allocator = std.mem.Allocator;
const lp = @import("lightpanda");
+const repeat = @import("../../string.zig").repeat;
const HostnameTrie = @This();
@@ -365,7 +366,7 @@ test "adblock.HostnameTrie: hostnames longer than one segment" {
const root = try trie.createTrie(testing.allocator);
// 191 bytes: the leaf spans two chained segments (127 + 64).
- const long = "a" ** 63 ++ "." ++ "b" ** 63 ++ "." ++ "c" ** 63;
+ const long = repeat("a", 63) ++ "." ++ repeat("b", 63) ++ "." ++ repeat("c", 63);
try trie.add(testing.allocator, root, long);
const cells_len = trie.cells.items.len;
try trie.add(testing.allocator, root, long); // duplicate multi-segment entry: no-op
@@ -373,7 +374,7 @@ test "adblock.HostnameTrie: hostnames longer than one segment" {
try testing.expectEqual(0, trie.matches(root, long).?);
try testing.expectEqual(2, trie.matches(root, "x." ++ long).?);
// A suffix of the stored hostname is not an entry.
- try testing.expectEqual(null, trie.matches(root, "b" ** 63 ++ "." ++ "c" ** 63));
+ try testing.expectEqual(null, trie.matches(root, repeat("b", 63) ++ "." ++ repeat("c", 63)));
}
test "adblock.HostnameTrie: stored deeper than query" {
diff --git a/src/network/cache/Cache.zig b/src/network/cache/Cache.zig
index 9a667fde3..1735854c4 100644
--- a/src/network/cache/Cache.zig
+++ b/src/network/cache/Cache.zig
@@ -465,7 +465,7 @@ pub fn tryCache(arena: std.mem.Allocator, candidate: CacheCandidate) !?CachePutR
}
return .{
- .url = try arena.dupeZ(u8, url),
+ .url = try arena.dupeSentinel(u8, url, 0),
.content_type = if (candidate.content_type) |ct| try arena.dupe(u8, ct) else "application/octet-stream",
.status = status,
.stored_at = candidate.timestamp,
diff --git a/src/network/cache/SqliteCache.zig b/src/network/cache/SqliteCache.zig
index d33e3eb3c..fbe4b48fe 100644
--- a/src/network/cache/SqliteCache.zig
+++ b/src/network/cache/SqliteCache.zig
@@ -108,8 +108,7 @@ pub fn init(allocator: std.mem.Allocator, path: SqliteCachePath, entry_limit: u3
return e;
};
- const full_path = try std.fmt.allocPrintSentinel(
- allocator,
+ const full_path = try allocator.printSentinel(
"{s}/cache.db",
.{std.mem.trimEnd(u8, cache_dir, &.{'/'})},
0,
diff --git a/src/network/http.zig b/src/network/http.zig
index b66d3f793..691f09fa3 100644
--- a/src/network/http.zig
+++ b/src/network/http.zig
@@ -26,6 +26,7 @@ const crypto = @import("../sys/libcrypto.zig");
const IpFilter = @import("IpFilter.zig");
const Certificates = @import("Certificates.zig");
+const repeat = @import("../string.zig").repeat;
const log = lp.log;
const posix = std.posix;
@@ -347,9 +348,9 @@ pub const Connection = struct {
// copies the string, so `allocator` only backs the transient join.
pub fn addHeader(self: *Connection, allocator: std.mem.Allocator, name: []const u8, value: []const u8) !void {
const joined = if (value.len == 0)
- try std.fmt.allocPrintSentinel(allocator, "{s};", .{name}, 0)
+ try allocator.printSentinel("{s};", .{name}, 0)
else
- try std.fmt.allocPrintSentinel(allocator, "{s}: {s}", .{ name, value }, 0);
+ try allocator.printSentinel("{s}: {s}", .{ name, value }, 0);
return self.addRawHeader(joined);
}
@@ -633,7 +634,7 @@ pub const Connection = struct {
pub fn getHttpVersion(self: *const Connection) !libcurl.CurlHttpVersion {
var version: c_long = undefined;
try libcurl.curl_easy_getinfo(self._easy, .http_version, &version);
- return @enumFromInt(version);
+ return @fromBackingInt(@intCast(version));
}
pub fn getConnectHeader(self: *const Connection, name: [:0]const u8, index: usize) ?HeaderValue {
@@ -1038,7 +1039,7 @@ test "StatusText.fromStatusLine" {
// curl's synthesized HTTP/2 status line has no phrase
try testing.expectEqualSlices(u8, "", StatusText.fromStatusLine("HTTP/2 200 \r\n").get().?);
try testing.expectEqualSlices(u8, "", StatusText.fromStatusLine("HTTP/1.1 200\r\n").get().?);
- try testing.expectEqual(StatusText.MAX_LEN, StatusText.fromStatusLine("HTTP/1.1 200 " ++ "x" ** 200).get().?.len);
+ try testing.expectEqual(StatusText.MAX_LEN, StatusText.fromStatusLine("HTTP/1.1 200 " ++ repeat("x", 200)).get().?.len);
}
test "opensocketCallback: private IPv4 returns CURL_SOCKET_BAD" {
@@ -1046,7 +1047,7 @@ test "opensocketCallback: private IPv4 returns CURL_SOCKET_BAD" {
const filter = IpFilter.init(true, null);
var sa = makeSockAddrV4(.{ 127, 0, 0, 1 });
- const result = opensocketCallback(@ptrCast(@constCast(&filter)), @intFromEnum(libcurl.CurlSockType.ipcxn), &sa);
+ const result = opensocketCallback(@ptrCast(@constCast(&filter)), @backingInt(libcurl.CurlSockType.ipcxn), &sa);
try testing.expectEqual(libcurl.CURL_SOCKET_BAD, result);
}
@@ -1055,7 +1056,7 @@ test "opensocketCallback: public IPv4 opens a real socket" {
const filter = IpFilter.init(true, null);
var sa = makeSockAddrV4(.{ 8, 8, 8, 8 });
- const fd = opensocketCallback(@ptrCast(@constCast(&filter)), @intFromEnum(libcurl.CurlSockType.ipcxn), &sa);
+ const fd = opensocketCallback(@ptrCast(@constCast(&filter)), @backingInt(libcurl.CurlSockType.ipcxn), &sa);
defer _ = std.c.close(fd);
// A real fd is always >= 0
@@ -1064,7 +1065,7 @@ test "opensocketCallback: public IPv4 opens a real socket" {
test "opensocketCallback: null clientp returns CURL_SOCKET_BAD (fail-closed)" {
var sa = makeSockAddrV4(.{ 8, 8, 8, 8 });
- const result = opensocketCallback(null, @intFromEnum(libcurl.CurlSockType.ipcxn), &sa);
+ const result = opensocketCallback(null, @backingInt(libcurl.CurlSockType.ipcxn), &sa);
try testing.expectEqual(libcurl.CURL_SOCKET_BAD, result);
}
@@ -1072,7 +1073,7 @@ test "opensocketCallback: block_private=false allows private IP" {
// When block_private is false the filter blocks nothing
const filter = IpFilter.init(false, null);
var sa = makeSockAddrV4(.{ 127, 0, 0, 1 });
- const fd = opensocketCallback(@ptrCast(@constCast(&filter)), @intFromEnum(libcurl.CurlSockType.ipcxn), &sa);
+ const fd = opensocketCallback(@ptrCast(@constCast(&filter)), @backingInt(libcurl.CurlSockType.ipcxn), &sa);
defer _ = std.c.close(fd);
try testing.expect(fd >= 0);
diff --git a/src/script/Runtime.zig b/src/script/Runtime.zig
index 9794776a3..0b3172bc1 100644
--- a/src/script/Runtime.zig
+++ b/src/script/Runtime.zig
@@ -291,7 +291,7 @@ pub fn runSource(self: *Runtime, source: []const u8, name: []const u8) RunError!
// `return <expr>` becomes that Promise's value, which we echo. (A bare
// trailing expression no longer auto-prints — `await` and a script
// completion value are mutually exclusive in JS.)
- const wrapped = std.fmt.allocPrint(self.call_arena.allocator(), "(async () => {{\n{s}\n}})()", .{source}) catch
+ const wrapped = self.call_arena.allocator().print("(async () => {{\n{s}\n}})()", .{source}) catch
return try self.dupeError("out of memory");
const script_source = self.env.isolate.initStringHandle(wrapped);
@@ -717,7 +717,7 @@ fn callTool(
const result = browser_tools.call(arena, self.session, self.registry, @tagName(tool), args, .{}) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
error.FrameNotLoaded => return .{ .fail = "no page loaded - run page.goto(url) first" },
- else => return .{ .fail = std.fmt.allocPrint(arena, "{s} failed: {s}", .{ @tagName(tool), @errorName(err) }) catch return error.OutOfMemory },
+ else => return .{ .fail = arena.print("{s} failed: {s}", .{ @tagName(tool), @errorName(err) }) catch return error.OutOfMemory },
};
if (result.is_error) return .{ .fail = result.text };
@@ -822,7 +822,7 @@ fn extractSchemaString(arena: std.mem.Allocator, value: std.json.Value) error{Ou
fn normalizeExtractSchemaString(arena: std.mem.Allocator, schema: []const u8) error{OutOfMemory}![]const u8 {
const trimmed = std.mem.trim(u8, schema, &std.ascii.whitespace);
if (trimmed.len == 0 or trimmed[0] != '[') return schema;
- return try std.fmt.allocPrint(arena, "{{\"__root\":{s}}}", .{schema});
+ return try arena.print("{{\"__root\":{s}}}", .{schema});
}
fn argJson(
@@ -925,7 +925,7 @@ fn formatCaught(
break :blk if (n < 0) null else @as(u32, @intCast(n));
};
if (line) |n| {
- return std.fmt.allocPrint(arena, "line {d}: {s}", .{ n, exception }) catch return error.OutOfMemory;
+ return arena.print("line {d}: {s}", .{ n, exception }) catch return error.OutOfMemory;
}
return try self.dupeError(exception);
}
diff --git a/src/script/Schema.zig b/src/script/Schema.zig
index b19cc0f85..e33359c4a 100644
--- a/src/script/Schema.zig
+++ b/src/script/Schema.zig
@@ -340,7 +340,7 @@ pub fn parseSlashCommand(input: []const u8) ?Split {
fn find(schemas: []const Schema, name: []const u8) ?*const Schema {
if (std.meta.stringToEnum(BrowserTool, name)) |tool| {
- const idx = @intFromEnum(tool);
+ const idx = @backingInt(tool);
if (idx < schemas.len) return &schemas[idx];
}
for (schemas) |*s| {
@@ -353,7 +353,7 @@ pub fn findByName(name: []const u8) ?*const Schema {
return find(all(), name);
}
-/// Lazy process-wide cache, keyed by `@intFromEnum(BrowserTool)`.
+/// Lazy process-wide cache, keyed by `@backingInt(BrowserTool)`.
/// Panics on init failure — `tool_defs` is comptime-constant, so any
/// parse/build error is a build-time bug.
pub fn all() []const Schema {
@@ -369,7 +369,7 @@ fn initGlobal() void {
global_arena = .init(std.heap.page_allocator);
const a = global_arena.allocator();
for (browser_tools.tool_defs, 0..) |td, i| {
- const tool: BrowserTool = @enumFromInt(i);
+ const tool: BrowserTool = @fromBackingInt(@intCast(i));
const parsed = std.json.parseFromSliceLeaky(std.json.Value, a, td.input_schema, .{}) catch |err| {
std.debug.panic("failed to parse schema for tool '{s}': {s}", .{ @tagName(tool), @errorName(err) });
};
@@ -436,7 +436,7 @@ fn buildHints(arena: std.mem.Allocator, required: []const []const u8, fields: []
out[idx] = .{
.name = name,
.required = true,
- .fragment = try std.fmt.allocPrint(arena, "<{s}>", .{name}),
+ .fragment = try arena.print("<{s}>", .{name}),
};
idx += 1;
}
@@ -445,7 +445,7 @@ fn buildHints(arena: std.mem.Allocator, required: []const []const u8, fields: []
out[idx] = .{
.name = f.name,
.required = false,
- .fragment = try std.fmt.allocPrint(arena, "[{s}=…]", .{f.name}),
+ .fragment = try arena.print("[{s}=…]", .{f.name}),
};
idx += 1;
}
diff --git a/src/script/command.zig b/src/script/command.zig
index cc8037eab..9263417c4 100644
--- a/src/script/command.zig
+++ b/src/script/command.zig
@@ -100,7 +100,7 @@ pub const Command = union(enum) {
}
fn schema(self: ToolCall) *const Schema {
- return &Schema.all()[@intFromEnum(self.tool)];
+ return &Schema.all()[@backingInt(self.tool)];
}
/// Skip the line when the recorded form would not round-trip:
@@ -160,10 +160,10 @@ pub const Command = union(enum) {
const split = Schema.splitNameRest(trimmed[1..]) orelse return error.MissingName;
- inline for (std.meta.fields(LlmCommand)) |f| {
- if (std.ascii.eqlIgnoreCase(split.name, f.name)) {
+ inline for (@typeInfo(LlmCommand).@"enum".field_names) |field_name| {
+ if (std.ascii.eqlIgnoreCase(split.name, field_name)) {
if (split.rest.len > 0) return error.MalformedKv;
- return .{ .llm = @field(LlmCommand, f.name) };
+ return .{ .llm = @field(LlmCommand, field_name) };
}
}
diff --git a/src/server/Link.zig b/src/server/Link.zig
index f5be9b110..e0ab57828 100644
--- a/src/server/Link.zig
+++ b/src/server/Link.zig
@@ -27,6 +27,7 @@ const sys_net = @import("../sys/net.zig");
const WS = @import("WS.zig");
const CDP = @import("cdp/CDP.zig");
const Driver = @import("Driver.zig");
+const repeat = @import("../string.zig").repeat;
const posix = std.posix;
const Allocator = std.mem.Allocator;
@@ -206,7 +207,7 @@ pub fn sendJSON(self: *Link, message: anytype, opts: SendOpts) !void {
// 512 covers the envelope (id, sessionId, field names) around the payload.
var aw = try std.Io.Writer.Allocating.initCapacity(allocator, 512 + opts.size_hint);
- try aw.writer.writeAll(&[_]u8{0} ** 10);
+ try aw.writer.writeAll(&@as([10]u8, @splat(0)));
try std.json.Stringify.value(message, opts.stringify, &aw.writer);
const framed = WS.fillHeader(aw.toArrayList());
return self.send(framed);
@@ -402,12 +403,12 @@ test "link: nested serialization preserves complete frames and recovers from err
try w.beginObject();
try w.objectField("head");
try w.write("outer head");
- self.link.sendJSON(.{ .nested = "x" ** 64 }, .{}) catch return error.WriteFailed;
+ self.link.sendJSON(.{ .nested = repeat("x", 64) }, .{}) catch return error.WriteFailed;
self.link.sendPong("ping") catch return error.WriteFailed;
- self.link.sendJSON(.{ .nested = "y" ** 64 }, .{}) catch return error.WriteFailed;
+ self.link.sendJSON(.{ .nested = repeat("y", 64) }, .{}) catch return error.WriteFailed;
if (self.fail) return error.WriteFailed;
try w.objectField("tail");
- try w.write("outer tail" ** 128);
+ try w.write(repeat("outer tail", 128));
try w.endObject();
}
};
@@ -417,16 +418,16 @@ test "link: nested serialization preserves complete frames and recovers from err
const link = &ctx.cdp().link;
try link.sendJSON(Nested{ .link = link, .fail = false }, .{});
- try ctx.expectSent(.{ .nested = "x" ** 64 }, .{ .index = 0 });
- try ctx.expectSent(.{ .nested = "y" ** 64 }, .{ .index = 1 });
- try ctx.expectSent(.{ .head = "outer head", .tail = "outer tail" ** 128 }, .{ .index = 2 });
+ try ctx.expectSent(.{ .nested = repeat("x", 64) }, .{ .index = 0 });
+ try ctx.expectSent(.{ .nested = repeat("y", 64) }, .{ .index = 1 });
+ try ctx.expectSent(.{ .head = "outer head", .tail = repeat("outer tail", 128) }, .{ .index = 2 });
try testing.expectEqual(0, link.send_depth);
try testing.expectError(error.WriteFailed, link.sendJSON(Nested{ .link = link, .fail = true }, .{}));
try testing.expectEqual(0, link.send_depth);
try link.sendJSON(.{ .recovered = true }, .{});
- try testing.expectJson(.{ .nested = "x" ** 64 }, (try ctx.getSentMessage(3)).?);
- try testing.expectJson(.{ .nested = "y" ** 64 }, (try ctx.getSentMessage(4)).?);
+ try testing.expectJson(.{ .nested = repeat("x", 64) }, (try ctx.getSentMessage(3)).?);
+ try testing.expectJson(.{ .nested = repeat("y", 64) }, (try ctx.getSentMessage(4)).?);
try ctx.expectSent(.{ .recovered = true }, .{ .index = 5 });
try testing.expectEqual(6, ctx.received.items.len);
}
diff --git a/src/server/Server.zig b/src/server/Server.zig
index 559807cc8..fb0641949 100644
--- a/src/server/Server.zig
+++ b/src/server/Server.zig
@@ -34,6 +34,7 @@ const Driver = @import("Driver.zig");
const Inbox = @import("../Inbox.zig");
const http_command = @import("bidi/http_command.zig");
+const repeat = @import("../string.zig").repeat;
const log = lp.log;
const posix = std.posix;
@@ -156,7 +157,7 @@ pub fn init(app: *App, address: sys_net.IpAddress) !*Server {
json_version_response = try http.buildJSONVersionResponse(app, bound_address.getPort());
errdefer allocator.free(json_version_response);
- bidi_session_url = try std.fmt.allocPrint(allocator, "ws://{s}:{d}/session/", .{ config.advertiseHost(), bound_address.getPort() });
+ bidi_session_url = try allocator.print("ws://{s}:{d}/session/", .{ config.advertiseHost(), bound_address.getPort() });
errdefer allocator.free(bidi_session_url);
try sys_net.listen(l, config.maxPendingConnections());
@@ -374,7 +375,7 @@ fn accept(self: *Server, now: u64) !void {
fn configureSocket(socket: posix.socket_t) void {
setSocketOption(socket, posix.SOL.SOCKET, posix.SO.KEEPALIVE, @as(c_int, 1), "SO_KEEPALIVE");
- const idle_opt = switch (builtin.os.tag) {
+ const idle_opt = switch (builtin.target.os.tag) {
.macos, .ios => posix.TCP.KEEPALIVE,
else => posix.TCP.KEEPIDLE,
};
@@ -382,7 +383,7 @@ fn configureSocket(socket: posix.socket_t) void {
setSocketOption(socket, posix.IPPROTO.TCP, posix.TCP.KEEPINTVL, Config.CDP_KEEPALIVE_INTVL_S, "TCP_KEEPINTVL");
setSocketOption(socket, posix.IPPROTO.TCP, posix.TCP.KEEPCNT, Config.CDP_KEEPALIVE_CNT, "TCP_KEEPCNT");
- if (comptime builtin.os.tag == .linux) {
+ if (comptime builtin.target.os.tag == .linux) {
setSocketOption(socket, posix.IPPROTO.TCP, std.os.linux.TCP.USER_TIMEOUT, Config.CDP_TCP_USER_TIMEOUT_MS, "TCP_USER_TIMEOUT");
}
}
@@ -851,7 +852,7 @@ fn fdBudget(config: *const Config) usize {
return @intCast(@max(budget, 8));
}
-const IOEngine = switch (builtin.os.tag) {
+const IOEngine = switch (builtin.target.os.tag) {
.linux => EPoll,
.macos, .ios, .tvos, .watchos, .freebsd, .netbsd, .dragonfly, .openbsd => KQueue,
else => unreachable,
@@ -1448,7 +1449,7 @@ test "Client: http header past the initial buffer" {
// A header this size doesn't fit the buffer a connection starts with; it
// grows to take it rather than rejecting the request.
- const res = try c.httpRequest("GET /over/9000 HTTP/1.1\r\n" ++ "Header: " ++ ("a" ** 4100) ++ "\r\n\r\n");
+ const res = try c.httpRequest("GET /over/9000 HTTP/1.1\r\n" ++ "Header: " ++ (repeat("a", 4100)) ++ "\r\n\r\n");
try testing.expectEqual("HTTP/1.1 404 \r\n" ++
"Connection: Close\r\n" ++
"Content-Length: 9\r\n\r\n" ++
@@ -1462,7 +1463,7 @@ test "Client: http request past the limit" {
// The body never arrives: Content-Length alone is enough to turn it down,
// so we never read (or make room for) any of it.
var buf: [128]u8 = undefined;
- const request = try std.fmt.bufPrint(&buf, "POST /session HTTP/1.1\r\nContent-Length: {d}\r\n\r\n", .{
+ const request = try std.mem.print(&buf, "POST /session HTTP/1.1\r\nContent-Length: {d}\r\n\r\n", .{
@as(u64, testing.test_app.config.cdpMaxHTTPMessageSize()) + 1,
});
const res = try c.httpRequest(request);
@@ -1546,7 +1547,7 @@ test "Client: http handshake origin" {
defer c.deinit();
var buf: [256]u8 = undefined;
- const res = try c.httpRequest(try std.fmt.bufPrint(&buf, with_origin, .{origin}));
+ const res = try c.httpRequest(try std.mem.print(&buf, with_origin, .{origin}));
try testing.expectEqual("HTTP/1.1 403 \r\n" ++
"Connection: Close\r\n" ++
"Content-Length: 18\r\n\r\n" ++
@@ -1591,7 +1592,7 @@ test "Client: http handshake host" {
try assertHTTPError(
403,
"Host not allowed",
- try std.fmt.bufPrint(&buf, with_host, .{host}),
+ try std.mem.print(&buf, with_host, .{host}),
);
}
@@ -1601,7 +1602,7 @@ test "Client: http handshake host" {
var c = try createTestClient();
defer c.deinit();
var buf: [256]u8 = undefined;
- const res = try c.httpRequest(try std.fmt.bufPrint(&buf, with_host, .{"localhost:9583"}));
+ const res = try c.httpRequest(try std.mem.print(&buf, with_host, .{"localhost:9583"}));
try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 101 Switching Protocols\r\n"));
}
}
@@ -1770,7 +1771,7 @@ test "server: bidi browsingContext" {
const url = "http://127.0.0.1:9582/src/browser/tests/cdp/dom2.html";
var buf: [256]u8 = undefined;
- try c.bidiCommand(try std.fmt.bufPrint(
+ try c.bidiCommand(try std.mem.print(
&buf,
"{{\"id\":5,\"method\":\"browsingContext.navigate\",\"params\":{{\"context\":\"{s}\",\"url\":\"" ++ url ++ "\",\"wait\":\"complete\"}}}}",
.{&context_id},
@@ -1797,7 +1798,7 @@ test "server: bidi browsingContext" {
try c.bidiCommand("{\"id\":7,\"method\":\"browsingContext.create\",\"params\":{\"type\":\"tab\"}}");
try assertBidiMessage(&c, .{ .type = "error", .id = 7, .@"error" = "unsupported operation" });
- try c.bidiCommand(try std.fmt.bufPrint(
+ try c.bidiCommand(try std.mem.print(
&buf,
"{{\"id\":8,\"method\":\"browsingContext.close\",\"params\":{{\"context\":\"{s}\"}}}}",
.{&context_id},
@@ -1819,7 +1820,7 @@ test "server: HTTP session bootstrap" {
// The session already exists on the advertised URL: no session.new
// needed (or possible), everything else works as usual.
var path_buf: [64]u8 = undefined;
- try c.handshake(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
+ try c.handshake(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
try c.bidiCommand("{\"id\":1,\"method\":\"session.status\"}");
try assertBidiMessage(&c, .{ .type = "success", .id = 1, .result = .{ .ready = false, .message = "session already started" } });
@@ -1836,7 +1837,7 @@ test "server: HTTP session bootstrap" {
var c2 = try createTestClient();
defer c2.deinit();
var path_buf: [64]u8 = undefined;
- const res = try c2.upgradeRequest(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
+ const res = try c2.upgradeRequest(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
try testing.expectEqual("HTTP/1.1 409 \r\nConnection: Close\r\nContent-Length: 25\r\n\r\nSession already connected", res);
}
@@ -1855,7 +1856,7 @@ test "server: HTTP session bootstrap" {
var c2 = try createTestClient();
defer c2.deinit();
var path_buf: [64]u8 = undefined;
- const res = try c2.upgradeRequest(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
+ const res = try c2.upgradeRequest(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
try testing.expectEqual("HTTP/1.1 404 \r\nConnection: Close\r\nContent-Length: 9\r\n\r\nNot found", res);
}
}
@@ -1867,7 +1868,7 @@ test "server: HTTP session outlives its websocket" {
defer deleteHTTPSession(&session_id, true) catch |err| @panic(@errorName(err));
var path_buf: [64]u8 = undefined;
- const path = try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id});
+ const path = try std.mem.print(&path_buf, "/session/{s}", .{&session_id});
{
var c = try createTestClient();
@@ -1923,7 +1924,7 @@ test "server: HTTP session idle timeout" {
var c = try createTestClient();
defer c.deinit();
var request_buf: [128]u8 = undefined;
- const res = try c.httpRequest(try std.fmt.bufPrint(&request_buf, "DELETE /session/{s} HTTP/1.1\r\nContent-Length: 0\r\n\r\n", .{&session_id}));
+ const res = try c.httpRequest(try std.mem.print(&request_buf, "DELETE /session/{s} HTTP/1.1\r\nContent-Length: 0\r\n\r\n", .{&session_id}));
if (std.mem.startsWith(u8, res, "HTTP/1.1 404 ")) {
break;
}
@@ -2013,7 +2014,7 @@ test "server: HTTP navigate" {
var ws = try createTestClient();
defer ws.deinit();
var path_buf: [64]u8 = undefined;
- try ws.handshake(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
+ try ws.handshake(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
try ws.bidiCommand("{\"id\":1,\"method\":\"browsingContext.getTree\"}");
const msg = try ws.readWebsocketMessage() orelse return error.NoMessage;
defer if (msg.cleanup_fragment) ws.reader.cleanup();
@@ -2037,7 +2038,7 @@ test "server: HTTP page commands" {
};
{
const body = responseBody(try sessionCommand(&c, "GET", &session_id, "/window/handles", ""));
- try testing.expectEqual(try std.fmt.allocPrint(testing.arena_allocator, "{{\"value\":[\"{s}\"]}}", .{handle}), body);
+ try testing.expectEqual(try testing.arena_allocator.print("{{\"value\":[\"{s}\"]}}", .{handle}), body);
}
const url = "http://127.0.0.1:9582/src/browser/tests/bidi/input.html";
@@ -2049,7 +2050,7 @@ test "server: HTTP page commands" {
try testing.expect(std.mem.startsWith(u8, body, "{\"value\":\"<!DOCTYPE html>\\n<html><head><title>bidi input</title>"));
}
{
- const res = try c.httpRequestAlloc(try std.fmt.allocPrint(testing.arena_allocator, "GET /session/{s}/screenshot HTTP/1.1\r\n\r\n", .{&session_id}));
+ const res = try c.httpRequestAlloc(try testing.arena_allocator.print("GET /session/{s}/screenshot HTTP/1.1\r\n\r\n", .{&session_id}));
defer testing.allocator.free(res);
// base64 of the PNG signature
try testing.expect(std.mem.startsWith(u8, responseBody(res), "{\"value\":\"iVBORw0KGgo"));
@@ -2069,8 +2070,8 @@ test "server: HTTP page commands" {
var ws = try createTestClient();
defer ws.deinit();
var path_buf: [64]u8 = undefined;
- try ws.handshake(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
- try ws.bidiCommand(try std.fmt.allocPrint(testing.arena_allocator,
+ try ws.handshake(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
+ try ws.bidiCommand(try testing.arena_allocator.print(
\\{{"id":1,"method":"browsingContext.locateNodes","params":{{"context":"{s}","locator":{{"type":"css","value":"#btn"}}}}}}
, .{handle}));
try expectWebsocketContains(&ws, "\"sharedId\":\"1\"");
@@ -2078,7 +2079,7 @@ test "server: HTTP page commands" {
try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "POST", &session_id, "/actions", actions)));
try testing.expectEqual("{\"value\":null}", responseBody(try sessionCommand(&c, "DELETE", &session_id, "/actions", "")));
- try ws.bidiCommand(try std.fmt.allocPrint(testing.arena_allocator,
+ try ws.bidiCommand(try testing.arena_allocator.print(
\\{{"id":2,"method":"script.evaluate","params":{{"expression":"window.events.join(' ')","awaitPromise":false,"target":{{"context":"{s}"}}}}}}
, .{handle}));
try expectWebsocketContains(&ws, "\"value\":\"mousemove@btn mousedown@btn mouseup@btn click@btn keydown:a@btn keyup:a@btn\"");
@@ -2216,14 +2217,14 @@ test "server: HTTP element commands" {
// scoped to an element: the two <p> inside #box, not the rest of the page
{
- const path = try std.fmt.allocPrint(testing.arena_allocator, "/element/{s}/elements", .{box});
+ const path = try testing.arena_allocator.print("/element/{s}/elements", .{box});
const res = responseBody(try sessionCommand(&c, "POST", &session_id, path, "{\"using\":\"css selector\",\"value\":\".item\"}"));
const references = try elementReferences(res);
try testing.expectEqual(2, references.len);
try testing.expectEqual(msg, references[0]);
}
{
- const path = try std.fmt.allocPrint(testing.arena_allocator, "/element/{s}/element", .{box});
+ const path = try testing.arena_allocator.print("/element/{s}/element", .{box});
const res = responseBody(try sessionCommand(&c, "POST", &session_id, path, "{\"using\":\"tag name\",\"value\":\"p\"}"));
const parsed = try std.json.parseFromSliceLeaky(std.json.Value, testing.arena_allocator, res, .{});
try testing.expectEqual(msg, parsed.object.get("value").?.object.get(http_command.element_key).?.string);
@@ -2247,13 +2248,13 @@ test "server: HTTP element commands" {
var ws = try createTestClient();
defer ws.deinit();
var path_buf: [64]u8 = undefined;
- try ws.handshake(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
- try ws.bidiCommand(try std.fmt.allocPrint(testing.arena_allocator,
+ try ws.handshake(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
+ try ws.bidiCommand(try testing.arena_allocator.print(
\\{{"id":1,"method":"script.evaluate","params":{{"expression":"document.getElementById('msg').remove()","awaitPromise":false,"target":{{"context":"{s}"}}}}}}
, .{handle}));
try expectWebsocketContains(&ws, "\"type\":\"success\"");
- const path = try std.fmt.allocPrint(testing.arena_allocator, "/element/{s}/text", .{msg});
+ const path = try testing.arena_allocator.print("/element/{s}/text", .{msg});
const res = try sessionCommand(&c, "GET", &session_id, path, "");
try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 404 Not Found\r\n"));
try testing.expect(std.mem.indexOf(u8, res, "\"error\":\"stale element reference\"") != null);
@@ -2353,7 +2354,7 @@ test "server: HTTP element input" {
}
fn elementPost(c: *TestClient, session_id: *const [36]u8, id: []const u8, suffix: []const u8, body: []const u8) ![]const u8 {
- const path = try std.fmt.allocPrint(testing.arena_allocator, "/element/{s}{s}", .{ id, suffix });
+ const path = try testing.arena_allocator.print("/element/{s}{s}", .{ id, suffix });
return sessionCommand(c, "POST", session_id, path, body);
}
@@ -2410,7 +2411,7 @@ test "server: HTTP execute script" {
try testing.expectEqual(reference, try findElement(&c, &session_id, "css selector", "#msg"));
try testing.expectEqual("{\"value\":\"hello\"}", try elementCommand(&c, &session_id, reference, "/text"));
- const args = try std.fmt.allocPrint(testing.arena_allocator, "[{{\"" ++ http_command.element_key ++ "\":\"{s}\"}}]", .{reference});
+ const args = try testing.arena_allocator.print("[{{\"" ++ http_command.element_key ++ "\":\"{s}\"}}]", .{reference});
try testing.expectEqual("{\"value\":\"msg\"}", try executeSync(&c, &session_id, "return arguments[0].id;", args));
}
@@ -2434,12 +2435,12 @@ test "server: HTTP execute script" {
const parsed = try std.json.parseFromSliceLeaky(std.json.Value, testing.arena_allocator, body, .{});
const reference = parsed.object.get("value").?.object.get(http_command.element_key).?.string;
- const path = try std.fmt.allocPrint(testing.arena_allocator, "/element/{s}/text", .{reference});
+ const path = try testing.arena_allocator.print("/element/{s}/text", .{reference});
const res = try sessionCommand(&c, "GET", &session_id, path, "");
try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 404 Not Found\r\n"));
try testing.expect(std.mem.indexOf(u8, res, "\"error\":\"stale element reference\"") != null);
- const args = try std.fmt.allocPrint(testing.arena_allocator, "[{{\"" ++ http_command.element_key ++ "\":\"{s}\"}}]", .{reference});
+ const args = try testing.arena_allocator.print("[{{\"" ++ http_command.element_key ++ "\":\"{s}\"}}]", .{reference});
const arg_res = try executeRaw(&c, &session_id, "sync", "return 1;", args);
try testing.expect(std.mem.indexOf(u8, arg_res, "\"error\":\"stale element reference\"") != null);
}
@@ -2570,7 +2571,7 @@ test "server: HTTP execute script" {
var ws = try createTestClient();
defer ws.deinit();
var path_buf: [64]u8 = undefined;
- try ws.handshake(try std.fmt.bufPrint(&path_buf, "/session/{s}", .{&session_id}));
+ try ws.handshake(try std.mem.print(&path_buf, "/session/{s}", .{&session_id}));
// the script never calls back, so its connection parks
var parked = try createTestClient();
@@ -2578,7 +2579,7 @@ test "server: HTTP execute script" {
try writeSessionCommand(&parked, "POST", &session_id, "/execute/async", "{\"script\":\"// never calls back\",\"args\":[]}");
lp.io.sleep(.fromMilliseconds(50), .awake) catch {};
- try ws.bidiCommand(try std.fmt.allocPrint(testing.arena_allocator,
+ try ws.bidiCommand(try testing.arena_allocator.print(
\\{{"id":1,"method":"browsingContext.navigate","params":{{"context":"{s}","url":"about:blank","wait":"complete"}}}}
, .{handle}));
@@ -2593,8 +2594,8 @@ test "server: HTTP execute script" {
fn executeRaw(c: *TestClient, session_id: *const [36]u8, kind: []const u8, script: []const u8, args: []const u8) ![]const u8 {
const arena = testing.arena_allocator;
const quoted = try std.json.Stringify.valueAlloc(arena, script, .{});
- const body = try std.fmt.allocPrint(arena, "{{\"script\":{s},\"args\":{s}}}", .{ quoted, args });
- const path = try std.fmt.allocPrint(arena, "/execute/{s}", .{kind});
+ const body = try arena.print("{{\"script\":{s},\"args\":{s}}}", .{ quoted, args });
+ const path = try arena.print("/execute/{s}", .{kind});
return sessionCommand(c, "POST", session_id, path, body);
}
@@ -2607,7 +2608,7 @@ fn executeAsync(c: *TestClient, session_id: *const [36]u8, script: []const u8, a
}
fn findElement(c: *TestClient, session_id: *const [36]u8, using: []const u8, value: []const u8) ![]const u8 {
- const body = try std.fmt.allocPrint(testing.arena_allocator, "{{\"using\":\"{s}\",\"value\":\"{s}\"}}", .{ using, value });
+ const body = try testing.arena_allocator.print("{{\"using\":\"{s}\",\"value\":\"{s}\"}}", .{ using, value });
const res = responseBody(try sessionCommand(c, "POST", session_id, "/element", body));
const parsed = try std.json.parseFromSliceLeaky(std.json.Value, testing.arena_allocator, res, .{});
const reference = parsed.object.get("value").?.object;
@@ -2616,7 +2617,7 @@ fn findElement(c: *TestClient, session_id: *const [36]u8, using: []const u8, val
// The raw response, so a test can assert on an error too.
fn findElements(c: *TestClient, session_id: *const [36]u8, using: []const u8, value: []const u8) ![]const u8 {
- const body = try std.fmt.allocPrint(testing.arena_allocator, "{{\"using\":\"{s}\",\"value\":\"{s}\"}}", .{ using, value });
+ const body = try testing.arena_allocator.print("{{\"using\":\"{s}\",\"value\":\"{s}\"}}", .{ using, value });
return sessionCommand(c, "POST", session_id, "/elements", body);
}
@@ -2631,7 +2632,7 @@ fn elementReferences(body: []const u8) ![]const []const u8 {
}
fn elementCommand(c: *TestClient, session_id: *const [36]u8, id: []const u8, suffix: []const u8) ![]const u8 {
- const path = try std.fmt.allocPrint(testing.arena_allocator, "/element/{s}{s}", .{ id, suffix });
+ const path = try testing.arena_allocator.print("/element/{s}{s}", .{ id, suffix });
return responseBody(try sessionCommand(c, "GET", session_id, path, ""));
}
@@ -2742,7 +2743,7 @@ test "server: HTTP command errors" {
var c = try createTestClient();
defer c.deinit();
var request_buf: [128]u8 = undefined;
- const res = try c.httpRequest(try std.fmt.bufPrint(&request_buf, "DELETE /session/{s}/url HTTP/1.1\r\n\r\n", .{&session_id}));
+ const res = try c.httpRequest(try std.mem.print(&request_buf, "DELETE /session/{s}/url HTTP/1.1\r\n\r\n", .{&session_id}));
try testing.expect(std.mem.startsWith(u8, res, "HTTP/1.1 404 Not Found\r\n"));
try testing.expect(std.mem.endsWith(u8, res, "{\"value\":{\"error\":\"unknown command\",\"message\":\"unknown command\",\"stacktrace\":\"\"}}"));
}
@@ -2783,7 +2784,7 @@ fn sessionCommand(c: *TestClient, method: []const u8, session_id: *const [36]u8,
fn writeSessionCommand(c: *TestClient, method: []const u8, session_id: *const [36]u8, command: []const u8, body: []const u8) !void {
var head_buf: [128]u8 = undefined;
- try sys_net.writeAll(c.socket, try std.fmt.bufPrint(&head_buf, "{s} /session/{s}{s} HTTP/1.1\r\nContent-Length: {d}\r\n\r\n", .{ method, session_id, command, body.len }));
+ try sys_net.writeAll(c.socket, try std.mem.print(&head_buf, "{s} /session/{s}{s} HTTP/1.1\r\nContent-Length: {d}\r\n\r\n", .{ method, session_id, command, body.len }));
try sys_net.writeAll(c.socket, body);
}
@@ -2794,7 +2795,7 @@ fn createHTTPSession(body: []const u8, expect_ws_url: bool) ![36]u8 {
// the body can arrive after the headers
var head_buf: [128]u8 = undefined;
- try sys_net.writeAll(c.socket, try std.fmt.bufPrint(&head_buf, "POST /session HTTP/1.1\r\n" ++
+ try sys_net.writeAll(c.socket, try std.mem.print(&head_buf, "POST /session HTTP/1.1\r\n" ++
"Content-Type: application/json;charset=UTF-8\r\n" ++
"Content-Length: {d}\r\n\r\n", .{body.len}));
lp.io.sleep(.fromMilliseconds(20), .awake) catch {};
@@ -2826,7 +2827,7 @@ fn deleteHTTPSession(session_id: *const [36]u8, expect_live: bool) !void {
var c = try createTestClient();
defer c.deinit();
var request_buf: [128]u8 = undefined;
- const res = try c.httpRequest(try std.fmt.bufPrint(&request_buf, "DELETE /session/{s} HTTP/1.1\r\nContent-Length: 0\r\n\r\n", .{session_id}));
+ const res = try c.httpRequest(try std.mem.print(&request_buf, "DELETE /session/{s} HTTP/1.1\r\nContent-Length: 0\r\n\r\n", .{session_id}));
if (expect_live) {
try testing.expectEqual("HTTP/1.1 200 OK\r\n" ++
"Content-Length: 14\r\n" ++
@@ -3328,7 +3329,7 @@ const TestClient = struct {
fn upgradeRequest(self: *TestClient, path: []const u8) ![]const u8 {
var request_buf: [256]u8 = undefined;
- const request = try std.fmt.bufPrint(&request_buf, "GET {s} HTTP/1.1\r\n" ++
+ const request = try std.mem.print(&request_buf, "GET {s} HTTP/1.1\r\n" ++
"Connection: upgrade\r\n" ++
"Upgrade: websocket\r\n" ++
"sec-websocket-version:13\r\n" ++
diff --git a/src/server/WS.zig b/src/server/WS.zig
index ea0635912..58c8da371 100644
--- a/src/server/WS.zig
+++ b/src/server/WS.zig
@@ -19,6 +19,7 @@
const std = @import("std");
const lp = @import("lightpanda");
const builtin = @import("builtin");
+const repeat = @import("../string.zig").repeat;
const Allocator = std.mem.Allocator;
@@ -61,7 +62,7 @@ const OpCode = enum(u8) {
// the used prefix.
pub fn frameHeader(buf: *[10]u8, op_code: OpCode, payload_len: usize) []const u8 {
const len = payload_len;
- buf[0] = @intFromEnum(op_code);
+ buf[0] = @backingInt(op_code);
if (len <= 125) {
buf[1] = @intCast(len);
@@ -491,7 +492,7 @@ fn simpleMask(m: []const u8, payload: []u8) void {
const testing = std.testing;
test "mask" {
var buf: [4000]u8 = undefined;
- const messages = [_][]const u8{ "1234", "1234" ** 99, "1234" ** 999 };
+ const messages = [_][]const u8{ "1234", repeat("1234", 99), repeat("1234", 999) };
for (messages) |message| {
// we need the message to be mutable since mask operates in-place
const payload = buf[0..message.len];
@@ -507,7 +508,7 @@ test "mask" {
// Builds an unmasked (server->client) text frame.
fn writeFrame(list: *std.ArrayList(u8), allocator: Allocator, payload: []const u8) !void {
- try list.append(allocator, @intFromEnum(OpCode.text)); // FIN + text opcode
+ try list.append(allocator, @backingInt(OpCode.text)); // FIN + text opcode
if (payload.len <= 125) {
try list.append(allocator, @intCast(payload.len));
} else if (payload.len <= 65535) {
diff --git a/src/server/bidi/browsing_context.zig b/src/server/bidi/browsing_context.zig
index 969c1c71b..8bfe00e86 100644
--- a/src/server/bidi/browsing_context.zig
+++ b/src/server/bidi/browsing_context.zig
@@ -256,12 +256,12 @@ pub fn reload(cmd: *BiDi.Command, ctx: *Context, wait: NavigateOpts.Wait) !void
// the frame's arena, which these live in, is gone once the reload commits
const arena = cmd.arena;
- const url = try arena.dupeZ(u8, frame.url);
+ const url = try arena.dupeSentinel(u8, frame.url, 0);
var nav_opts: Frame.NavigateOpts = .{ .reason = .address_bar, .kind = .reload };
if (frame._navigated_options) |prev| {
nav_opts.method = prev.method;
nav_opts.body = if (prev.body) |b| try arena.dupe(u8, b) else null;
- nav_opts.header = if (prev.header) |h| try arena.dupeZ(u8, h) else null;
+ nav_opts.header = if (prev.header) |h| try arena.dupeSentinel(u8, h, 0) else null;
}
return startNavigation(cmd, ctx, frame, url, nav_opts, wait);
}
diff --git a/src/server/bidi/http_command.zig b/src/server/bidi/http_command.zig
index e1a846530..0bcb7804d 100644
--- a/src/server/bidi/http_command.zig
+++ b/src/server/bidi/http_command.zig
@@ -213,8 +213,8 @@ const Route = struct {
@field(value, parameter) = std.Uri.percentDecodeInPlace(try arena.dupe(u8, captured[i]));
}
const parsed = try parseBody(Body(T, self.parameters), arena, body);
- inline for (@typeInfo(@TypeOf(parsed)).@"struct".fields) |field| {
- @field(value, field.name) = @field(parsed, field.name);
+ inline for (@typeInfo(@TypeOf(parsed)).@"struct".field_names) |field_name| {
+ @field(value, field_name) = @field(parsed, field_name);
}
return @unionInit(Command, name, value);
}
@@ -292,23 +292,15 @@ pub fn parse(arena: Allocator, method: Method, path: []const u8, body: []const u
// What's left of a command once its path parameters, which are its leading
// fields, are taken out: the part that comes from the body.
fn Body(comptime T: type, comptime parameters: []const []const u8) type {
- const fields = @typeInfo(T).@"struct".fields;
- for (parameters, fields[0..parameters.len]) |parameter, field| {
- if (!std.mem.eql(u8, parameter, field.name)) {
- @compileError(@typeName(T) ++ ": field '" ++ field.name ++ "' should be the path parameter '" ++ parameter ++ "'");
+ const info = @typeInfo(T).@"struct";
+ for (parameters, info.field_names[0..parameters.len]) |parameter, field_name| {
+ if (!std.mem.eql(u8, parameter, field_name)) {
+ @compileError(@typeName(T) ++ ": field '" ++ field_name ++ "' should be the path parameter '" ++ parameter ++ "'");
}
}
- const rest = fields[parameters.len..];
- var field_names: [rest.len][:0]const u8 = undefined;
- var types: [rest.len]type = undefined;
- var attrs: [rest.len]std.builtin.Type.StructField.Attributes = undefined;
- for (rest, 0..) |field, i| {
- field_names[i] = field.name;
- types[i] = field.type;
- attrs[i] = .{ .@"align" = field.alignment, .default_value_ptr = field.default_value_ptr };
- }
- return @Struct(.auto, null, &field_names, &types, &attrs);
+ const n = parameters.len;
+ return @Struct(.auto, null, info.field_names[n..], info.field_types[n..], info.field_attrs[n..]);
}
// Both are split on '/', so a leading empty segment lines up on either side.
@@ -318,7 +310,7 @@ fn parseBody(comptime T: type, arena: Allocator, body: []const u8) ParseError!T
// POSTs without parameters still send a body ("{}"); nothing to read
return {};
}
- if (@typeInfo(T).@"struct".fields.len == 0) {
+ if (@typeInfo(T).@"struct".field_names.len == 0) {
// everything the command takes came from the path
return .{};
}
@@ -925,7 +917,7 @@ pub const Reference = struct {
pub fn init(arena: Allocator, registry: *NodeRegistry, node: *Node) !Reference {
const registered = try registry.register(node);
- return .{ .shared_id = try std.fmt.allocPrint(arena, "{d}", .{registered.id}) };
+ return .{ .shared_id = try arena.print("{d}", .{registered.id}) };
}
fn initFromCommand(cmd: *BiDi.Command, node: *Node) !Reference {
diff --git a/src/server/bidi/input.zig b/src/server/bidi/input.zig
index da63d1332..9fa2614d8 100644
--- a/src/server/bidi/input.zig
+++ b/src/server/bidi/input.zig
@@ -112,10 +112,10 @@ pub fn release(cmd: *BiDi.Command) !void {
for (state.sources.items) |*source| {
switch (source.kind) {
- .key => while (source.key.pressed.getLastOrNull()) |cp| {
+ .key => while (source.key.pressed.last()) |cp| {
dispatch(bidi, frame, source, &.{ .key_up = cp }) catch |err| return dispatchFailed(cmd, err);
},
- .pointer => while (source.pointer.pressed.getLastOrNull()) |button| {
+ .pointer => while (source.pointer.pressed.last()) |button| {
dispatch(bidi, frame, source, &.{ .pointer_up = button }) catch |err| return dispatchFailed(cmd, err);
},
.none, .wheel => {},
diff --git a/src/server/bidi/remote_value.zig b/src/server/bidi/remote_value.zig
index 682c0b98b..99733f72a 100644
--- a/src/server/bidi/remote_value.zig
+++ b/src/server/bidi/remote_value.zig
@@ -343,7 +343,7 @@ pub const Serializer = struct {
const handle: ?[]const u8 = if (own and (value.isObject() or value.isSymbol())) blk: {
const id = try self.handles.add(value);
handle_id = id;
- break :blk try std.fmt.allocPrint(self.arena, "{d}", .{id});
+ break :blk try self.arena.print("{d}", .{id});
} else null;
return .{ .handle = handle, .body = try self.body(value, depth) };
@@ -500,7 +500,7 @@ pub const Serializer = struct {
const registered = try self.registry.register(dom_node);
var value: NodeValue = .{
- .shared_id = try std.fmt.allocPrint(arena, "{d}", .{registered.id}),
+ .shared_id = try arena.print("{d}", .{registered.id}),
.node_type = dom_node.getNodeType(),
.child_node_count = dom_node.getChildrenCount(),
};
diff --git a/src/server/bidi/script.zig b/src/server/bidi/script.zig
index 27f89d4e0..c56dbff77 100644
--- a/src/server/bidi/script.zig
+++ b/src/server/bidi/script.zig
@@ -114,7 +114,7 @@ fn callFunction(cmd: *BiDi.Command) !void {
// parenthesized is what turns it into something callable. \n added incase
// the functionDeclaration has a trailing comment.
const arena = cmd.arena;
- const source = try std.fmt.allocPrint(arena, "({s}\n)", .{p.functionDeclaration});
+ const source = try arena.print("({s}\n)", .{p.functionDeclaration});
const reply: Reply = .init(cmd, ctx);
const declaration = ls.local.exec(source, "bidi.callFunction") catch |err| {
return sendException(&reply, frame, &ls.local, &try_catch, err);
diff --git a/src/server/bidi/session.zig b/src/server/bidi/session.zig
index 3a3f8049c..688050b9a 100644
--- a/src/server/bidi/session.zig
+++ b/src/server/bidi/session.zig
@@ -87,15 +87,16 @@ pub const Capabilities = struct {
// when it's null.
pub fn jsonStringify(self: *const Capabilities, jws: anytype) !void {
try jws.beginObject();
- inline for (std.meta.fields(Capabilities)) |field| {
- const value = @field(self, field.name);
- if (@typeInfo(field.type) == .optional) {
+ const info = @typeInfo(Capabilities).@"struct";
+ inline for (info.field_names, info.field_types) |field_name, field_type| {
+ const value = @field(self, field_name);
+ if (@typeInfo(field_type) == .optional) {
if (value) |v| {
- try jws.objectField(field.name);
+ try jws.objectField(field_name);
try jws.write(v);
}
} else {
- try jws.objectField(field.name);
+ try jws.objectField(field_name);
try jws.write(value);
}
}
@@ -163,9 +164,9 @@ fn matchesAny(haystack: []const []const u8, needle: []const u8) bool {
return false;
}
-const platform_name = switch (builtin.os.tag) {
+const platform_name = switch (builtin.target.os.tag) {
.macos, .ios => "mac",
.windows => "windows",
.linux => "linux",
- else => @tagName(builtin.os.tag),
+ else => @tagName(builtin.target.os.tag),
};
diff --git a/src/server/bidi/testing.zig b/src/server/bidi/testing.zig
index 1c7d1aea4..236291e86 100644
--- a/src/server/bidi/testing.zig
+++ b/src/server/bidi/testing.zig
@@ -112,7 +112,7 @@ pub const TestContext = struct {
.method = "browsingContext.navigate",
.params = .{
.context = context_id,
- .url = try std.fmt.allocPrint(base.arena_allocator, test_server ++ "{s}", .{url}),
+ .url = try base.arena_allocator.print(test_server ++ "{s}", .{url}),
.wait = "none",
},
});
diff --git a/src/server/cdp/AXNode.zig b/src/server/cdp/AXNode.zig
index 88ce091fb..6af12e550 100644
--- a/src/server/cdp/AXNode.zig
+++ b/src/server/cdp/AXNode.zig
@@ -116,7 +116,7 @@ pub const Writer = struct {
// be serialized as JSON strings even though we track them internally as u32.
fn writeIdString(id: u32, w: anytype) !void {
var buf: [10]u8 = undefined;
- const s = try std.fmt.bufPrint(&buf, "{d}", .{id});
+ const s = try std.mem.print(&buf, "{d}", .{id});
try w.write(s);
}
@@ -206,7 +206,7 @@ pub const Writer = struct {
// Use a small stack buffer to format the number (max "9999. " = 6 chars)
var buf: [6]u8 = undefined;
- const marker_text = try std.fmt.bufPrint(&buf, "{d}. ", .{count});
+ const marker_text = try std.mem.print(&buf, "{d}. ", .{count});
try w.write(marker_text);
},
else => unreachable,
@@ -299,7 +299,7 @@ pub const Writer = struct {
// CDP spec requires integer values to be serialized as strings.
// 20 bytes is enough for the decimal representation of a 64-bit integer.
var buf: [20]u8 = undefined;
- const s = try std.fmt.bufPrint(&buf, "{d}", .{v});
+ const s = try std.mem.print(&buf, "{d}", .{v});
try w.write(s);
},
inline else => |v| try w.write(v),
diff --git a/src/server/cdp/CDP.zig b/src/server/cdp/CDP.zig
index 5fc29e8cf..f05d2d486 100644
--- a/src/server/cdp/CDP.zig
+++ b/src/server/cdp/CDP.zig
@@ -235,7 +235,7 @@ fn dispatchParsed(self: *CDP, arena: Allocator, sender: Command.Sender, str: []c
error.InvalidMethod, error.UnknownDomain, error.UnknownMethod => {
lp.metrics.serve_unknown_commands.incr(.cdp);
// Chrome's code and wording; drivers feature-detect on it.
- const message = std.fmt.allocPrint(command.arena, "'{s}' wasn't found", .{input.method}) catch return err;
+ const message = command.arena.print("'{s}' wasn't found", .{input.method}) catch return err;
command.sendError(-32601, message, .{}) catch return err;
},
else => command.sendError(-31998, @errorName(err), .{}) catch return err,
diff --git a/src/server/cdp/Node.zig b/src/server/cdp/Node.zig
index eaefba5e8..fce4d9cce 100644
--- a/src/server/cdp/Node.zig
+++ b/src/server/cdp/Node.zig
@@ -85,7 +85,7 @@ pub const Search = struct {
7 => "7",
8 => "8",
9 => "9",
- else => try std.fmt.allocPrint(arena, "{d}", .{search_id}),
+ else => try arena.print("{d}", .{search_id}),
};
var registry = self.registry;
diff --git a/src/server/cdp/domains/fetch.zig b/src/server/cdp/domains/fetch.zig
index 8be3b84eb..177291742 100644
--- a/src/server/cdp/domains/fetch.zig
+++ b/src/server/cdp/domains/fetch.zig
@@ -204,7 +204,7 @@ fn continueRequest(cmd: *CDP.Command) !void {
const request = &transfer.req;
// Update the request with the new parameters
if (params.url) |url| {
- request.url = try arena.dupeZ(u8, url);
+ request.url = try arena.dupeSentinel(u8, url, 0);
}
if (params.method) |method| {
request.method = std.meta.stringToEnum(http.Method, method) orelse return error.InvalidParams;
@@ -269,8 +269,7 @@ fn continueWithAuth(cmd: *CDP.Command) !void {
// fails, release it. Scoped so the errdefer does NOT cover
// continueTransfer (which owns its failures).
errdefer transfer.abortAuthChallenge();
- transfer.updateCredentials(try std.fmt.allocPrintSentinel(
- transfer.arena.allocator(),
+ transfer.updateCredentials(try transfer.arena.allocator().printSentinel(
"{s}:{s}",
.{
params.authChallengeResponse.username,
diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zig
index c590d7649..bb4e01e35 100644
--- a/src/server/cdp/domains/input.zig
+++ b/src/server/cdp/domains/input.zig
@@ -1577,7 +1577,7 @@ test "cdp.input: dispatchKeyEvent Enter clicks buttons and submits once" {
var id: u32 = 1;
for (cases) |c| {
var buf: [32]u8 = undefined;
- _ = try ls.local.compileAndRun(try std.fmt.bufPrint(&buf, "arm('{s}')", .{c.id}), null);
+ _ = try ls.local.compileAndRun(try std.mem.print(&buf, "arm('{s}')", .{c.id}), null);
try ctx.processMessage(.{ .id = id, .method = "Input.dispatchKeyEvent", .params = .{ .type = "keyDown", .key = "Enter", .code = "Enter" } });
try ctx.expectSentResult(null, .{ .id = id });
diff --git a/src/server/cdp/domains/lp.zig b/src/server/cdp/domains/lp.zig
index ea554b832..aedec0495 100644
--- a/src/server/cdp/domains/lp.zig
+++ b/src/server/cdp/domains/lp.zig
@@ -414,7 +414,7 @@ fn waitForSelector(cmd: anytype) !void {
const frame = bc.mainFrame() orelse return error.FrameNotLoaded;
const timeout_ms = params.timeout orelse lp.tools.defaultWaitTimeout(frame);
- const selector_z = try cmd.arena.dupeZ(u8, params.selector);
+ const selector_z = try cmd.arena.dupeSentinel(u8, params.selector, 0);
const node = lp.actions.waitForSelector(selector_z, timeout_ms, frame._frame_id, bc.session) catch |err| {
if (err == error.InvalidSelector) return error.InvalidParam;
diff --git a/src/server/cdp/domains/network.zig b/src/server/cdp/domains/network.zig
index 9b60e1e00..1e5dd0e05 100644
--- a/src/server/cdp/domains/network.zig
+++ b/src/server/cdp/domains/network.zig
@@ -1207,7 +1207,7 @@ test "cdp.Network: setBlockedURLs blocks requests with inspector reason" {
error_context.err = null;
var redirect_request_id: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&redirect_request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
+ _ = std.mem.print(&redirect_request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
try client.request(.{
.frame_id = page.frame_id,
@@ -1244,7 +1244,7 @@ test "cdp.Network: POST body exposed as postData" {
try ctx.expectSentResult(null, .{ .id = 1 });
var request_id: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
+ _ = std.mem.print(&request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
// \xE9 exercises the Latin-1 -> UTF-8 transcode in postData;
// postDataEntries carry the raw bytes in base64.
@@ -1310,7 +1310,7 @@ const EchoDriver = struct {
fn run(bc: *CDP.BrowserContext, frame_id: u32, body: []const u8, partial: ?u32) ![14]u8 {
const client = &bc.cdp.browser.http_client;
var request_id: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
+ _ = std.mem.print(&request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
var driver: EchoDriver = .{};
try client.request(.{
@@ -1556,7 +1556,7 @@ test "cdp.Network: redirect hop precedes Fetch pause and carries redirectRespons
const start_url = "http://127.0.0.1:9582/redirect-cross-origin-x-hop";
const target_url = "http://localhost:9582/echo-x-hop";
var request_id: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
+ _ = std.mem.print(&request_id, "REQ-{d:0>10}", .{client.next_request_id +% 1}) catch unreachable;
try client.request(.{
.frame_id = page.frame_id,
diff --git a/src/server/cdp/domains/page.zig b/src/server/cdp/domains/page.zig
index 835a1f1bb..8791ea23b 100644
--- a/src/server/cdp/domains/page.zig
+++ b/src/server/cdp/domains/page.zig
@@ -210,7 +210,7 @@ fn addScriptToEvaluateOnNewDocument(cmd: *CDP.Command) !void {
}
var id_buf: [16]u8 = undefined;
- const id_str = std.fmt.bufPrint(&id_buf, "{d}", .{script_id}) catch "1";
+ const id_str = std.mem.print(&id_buf, "{d}", .{script_id}) catch "1";
return cmd.sendResult(.{
.identifier = id_str,
}, .{});
@@ -307,9 +307,9 @@ fn createIsolatedWorldContext(arena: Allocator, bc: *CDP.BrowserContext, world:
fn registerIsolatedWorldContext(arena: Allocator, bc: *CDP.BrowserContext, world: *CDP.IsolatedWorld, js_context: *js.Context, frame: *const Frame, loader_id: ?[]const u8) !void {
const frame_id = &id.toFrameId(frame._frame_id);
const aux_data = if (loader_id) |lid|
- try std.fmt.allocPrint(arena, "{{\"isDefault\":false,\"type\":\"isolated\",\"frameId\":\"{s}\",\"loaderId\":\"{s}\"}}", .{ frame_id, lid })
+ try arena.print("{{\"isDefault\":false,\"type\":\"isolated\",\"frameId\":\"{s}\",\"loaderId\":\"{s}\"}}", .{ frame_id, lid })
else
- try std.fmt.allocPrint(arena, "{{\"isDefault\":false,\"type\":\"isolated\",\"frameId\":\"{s}\"}}", .{frame_id});
+ try arena.print("{{\"isDefault\":false,\"type\":\"isolated\",\"frameId\":\"{s}\"}}", .{frame_id});
var ls: js.Local.Scope = undefined;
js_context.localScope(&ls);
@@ -393,13 +393,13 @@ fn doReload(cmd: *CDP.Command) !void {
// we free the old frame's arena. Replaying the same HTTP
// method on reload matches Chrome's F5 behavior — POST navigations
// re-submit, GET navigations re-fetch.
- const reload_url = try cmd.arena.dupeZ(u8, frame.url);
+ const reload_url = try cmd.arena.dupeSentinel(u8, frame.url, 0);
const prev_nav = frame._navigated_options;
const prev_body: ?[]const u8, const prev_header: ?[:0]const u8 = blk: {
const p = prev_nav orelse break :blk .{ null, null };
break :blk .{
if (p.body) |b| try cmd.arena.dupe(u8, b) else null,
- if (p.header) |h| try cmd.arena.dupeZ(u8, h) else null,
+ if (p.header) |h| try cmd.arena.dupeSentinel(u8, h, 0) else null,
};
};
@@ -737,7 +737,7 @@ pub fn frameNavigated(arena: Allocator, bc: *CDP.BrowserContext, event: *const N
}, .{ .session_id = session_id });
{
- const aux_data = try std.fmt.allocPrint(arena, "{{\"isDefault\":true,\"type\":\"default\",\"frameId\":\"{s}\",\"loaderId\":\"{s}\"}}", .{ frame_id, loader_id });
+ const aux_data = try arena.print("{{\"isDefault\":true,\"type\":\"default\",\"frameId\":\"{s}\",\"loaderId\":\"{s}\"}}", .{ frame_id, loader_id });
var ls: js.Local.Scope = undefined;
frame.js.localScope(&ls);
@@ -1139,7 +1139,7 @@ fn printToPDF(cmd: *CDP.Command) !void {
const handle = try cmd.cdp.streams.add(try aw.toOwnedSlice());
return cmd.sendResult(.{
.data = "",
- .stream = try std.fmt.allocPrint(cmd.arena, "{d}", .{handle}),
+ .stream = try cmd.arena.print("{d}", .{handle}),
}, .{});
}
diff --git a/src/server/cdp/domains/runtime.zig b/src/server/cdp/domains/runtime.zig
index b5e1a1be3..23a43ed1e 100644
--- a/src/server/cdp/domains/runtime.zig
+++ b/src/server/cdp/domains/runtime.zig
@@ -21,6 +21,7 @@ const std = @import("std");
const CDP = @import("../CDP.zig");
const js = @import("../../../browser/js/js.zig");
const Notification = @import("../../../Notification.zig");
+const repeat = @import("../../../string.zig").repeat;
const Allocator = std.mem.Allocator;
@@ -114,7 +115,7 @@ const RemoteObject = struct {
self.value = .{ .float = n };
}
} else if (value.isBigInt()) {
- self.unserializableValue = try std.fmt.allocPrint(arena, "{s}n", .{try value.toStringSliceWithAlloc(arena)});
+ self.unserializableValue = try arena.print("{s}n", .{try value.toStringSliceWithAlloc(arena)});
}
}
};
@@ -365,7 +366,7 @@ test "cdp.runtime: console notifications run no page JS" {
\\console.log('head-marker', probe, 'tail-marker-'.repeat(20));
, null);
- const tail = "tail-marker-" ** 20;
+ const tail = repeat("tail-marker-", 20);
try ctx.expectSentEvent("Console.messageAdded", .{ .level = "log", .text = "head-marker [object Object] " ++ tail }, .{});
try ctx.expectSentEvent("Runtime.consoleAPICalled", .{ .type = "log", .args = .{ .{ .type = "string", .value = "head-marker" }, .{ .type = "object", .className = "Object" }, .{ .type = "string", .value = tail } } }, .{});
const probed = try ls.local.exec("globalThis.probed", null);
diff --git a/src/server/cdp/domains/target.zig b/src/server/cdp/domains/target.zig
index 6ddcb438b..7af5c83cb 100644
--- a/src/server/cdp/domains/target.zig
+++ b/src/server/cdp/domains/target.zig
@@ -195,7 +195,7 @@ fn createTarget(cmd: *CDP.Command) !void {
frame.js.localScope(&ls);
defer ls.deinit();
- const aux_data = try std.fmt.allocPrint(cmd.arena, "{{\"isDefault\":true,\"type\":\"default\",\"frameId\":\"{s}\"}}", .{target_id});
+ const aux_data = try cmd.arena.print("{{\"isDefault\":true,\"type\":\"default\",\"frameId\":\"{s}\"}}", .{target_id});
bc.inspector().contextCreated(
&ls.local,
"",
diff --git a/src/server/cdp/id.zig b/src/server/cdp/id.zig
index 2a75f448c..f4a6880c6 100644
--- a/src/server/cdp/id.zig
+++ b/src/server/cdp/id.zig
@@ -28,13 +28,13 @@ pub fn parseFrameId(input: []const u8) !u32 {
pub fn toFrameId(id: u32) [14]u8 {
var buf: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&buf, "FID-{d:0>10}", .{id}) catch unreachable;
+ _ = std.mem.print(&buf, "FID-{d:0>10}", .{id}) catch unreachable;
return buf;
}
pub fn toLoaderId(id: u32) [14]u8 {
var buf: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&buf, "LID-{d:0>10}", .{id}) catch unreachable;
+ _ = std.mem.print(&buf, "LID-{d:0>10}", .{id}) catch unreachable;
return buf;
}
@@ -47,19 +47,19 @@ pub fn toRequestId(transfer: *const Transfer) [14]u8 {
}
var buf: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&buf, "REQ-{d:0>10}", .{transfer.id}) catch unreachable;
+ _ = std.mem.print(&buf, "REQ-{d:0>10}", .{transfer.id}) catch unreachable;
return buf;
}
pub fn toInterceptId(id: u32) [14]u8 {
var buf: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&buf, "INT-{d:0>10}", .{id}) catch unreachable;
+ _ = std.mem.print(&buf, "INT-{d:0>10}", .{id}) catch unreachable;
return buf;
}
pub fn toInvocationId(id: u32) [14]u8 {
var buf: [14]u8 = undefined;
- _ = std.fmt.bufPrint(&buf, "INV-{d:0>10}", .{id}) catch unreachable;
+ _ = std.mem.print(&buf, "INV-{d:0>10}", .{id}) catch unreachable;
return buf;
}
@@ -84,7 +84,7 @@ pub fn Incrementing(comptime T: type, comptime prefix: []const u8) type {
};
const buffer = blk: {
- var b = [_]u8{0} ** MAX_BYTES;
+ var b: [MAX_BYTES]u8 = @splat(0);
@memcpy(b[0..prefix.len], prefix);
b[prefix.len] = '-';
break :blk b;
diff --git a/src/server/cdp/testing.zig b/src/server/cdp/testing.zig
index 3bac1b10f..8af7fec67 100644
--- a/src/server/cdp/testing.zig
+++ b/src/server/cdp/testing.zig
@@ -106,8 +106,7 @@ pub const TestContext = struct {
bc.target_id = "TID-000000000Z".*;
}
const page = try bc.session.createPage();
- const full_url = try std.fmt.allocPrintSentinel(
- base.arena_allocator,
+ const full_url = try base.arena_allocator.printSentinel(
"http://127.0.0.1:9582/src/browser/tests/{s}",
.{url},
0,
diff --git a/src/server/http.zig b/src/server/http.zig
index bf1bf9d80..c3ac1badd 100644
--- a/src/server/http.zig
+++ b/src/server/http.zig
@@ -29,6 +29,7 @@ const Driver = @import("Driver.zig");
const bidi_session = @import("bidi/session.zig");
const http_command = @import("bidi/http_command.zig");
const uuidv4 = @import("../id.zig").uuidv4;
+const repeat = @import("../string.zig").repeat;
const log = lp.log;
const posix = std.posix;
@@ -176,7 +177,7 @@ pub const Connection = struct {
fn contentLength(header: []const u8) !usize {
const key = "\r\ncontent-length:";
- const at = std.ascii.indexOfIgnoreCase(header, key) orelse return 0;
+ const at = std.ascii.findIgnoreCase(header, key) orelse return 0;
const start = at + key.len;
const end = std.mem.indexOfPos(u8, header, start, "\r\n") orelse return error.InvalidHeader;
const value = std.mem.trim(u8, header[start..end], " \t");
@@ -674,8 +675,8 @@ fn fillHeader(buf: []u8, status: std.http.Status, comptime content_type: []const
comptime std.debug.assert(header_format.len + 3 + 31 + 20 <= HEADER_RESERVE);
var header_buf: [HEADER_RESERVE]u8 = undefined;
- const header = std.fmt.bufPrint(&header_buf, header_format, .{
- @intFromEnum(status),
+ const header = std.mem.print(&header_buf, header_format, .{
+ @backingInt(status),
status.phrase() orelse "",
buf.len - HEADER_RESERVE,
}) catch unreachable;
@@ -794,7 +795,7 @@ fn newSession(server: *Server, conn: *Connection, req: *Connection.Request) !Ser
const url: ?[]const u8 = blk: {
if (is_requesting_websocket_url) {
- break :blk try std.fmt.allocPrint(req.arena, "{s}{s}", .{ server.bidi_session_url, &session_id });
+ break :blk try req.arena.print("{s}{s}", .{ server.bidi_session_url, &session_id });
}
break :blk null;
};
@@ -1055,7 +1056,7 @@ pub fn buildJSONVersionResponse(app: *const App, port: u16) ![]const u8 {
"Content-Length: {d}\r\n" ++
"Content-Type: application/json; charset=UTF-8\r\n\r\n" ++
body_format;
- return try std.fmt.allocPrint(app.allocator, response_format, .{ body_len, host, port });
+ return try app.allocator.print(response_format, .{ body_len, host, port });
}
// Where the upgraded socket goes: a new worker, or an existing session's.
@@ -1082,7 +1083,7 @@ fn upgrade(server: *Server, conn: *Connection, req: *Connection.Request, target:
// The 101 is ~129 bytes into an empty send buffer, so a single write
// always completes; a partial write here means the peer is already gone.
var response_buf: [160]u8 = undefined;
- const response = std.fmt.bufPrint(&response_buf, "HTTP/1.1 101 Switching Protocols\r\n" ++
+ const response = std.mem.print(&response_buf, "HTTP/1.1 101 Switching Protocols\r\n" ++
"Upgrade: websocket\r\n" ++
"Connection: upgrade\r\n" ++
"Sec-Websocket-Accept: {s}\r\n\r\n", .{accept_key}) catch unreachable;
@@ -1123,7 +1124,7 @@ fn webSocketAccept(head: []const u8, out: *[28]u8) ![]const u8 {
if (h.value.len != 2 or h.value[0] != '1' or h.value[1] != '3') return error.MissingHeader;
found |= FOUND_VERSION;
} else if (std.ascii.eqlIgnoreCase(h.key, "connection")) {
- if (std.ascii.indexOfIgnoreCase(h.value, "upgrade") == null) return error.MissingHeader;
+ if (std.ascii.findIgnoreCase(h.value, "upgrade") == null) return error.MissingHeader;
found |= FOUND_CONNECTION;
} else if (std.ascii.eqlIgnoreCase(h.key, "sec-websocket-key")) {
key = h.value;
@@ -1177,7 +1178,7 @@ test "http: the read buffer grows with the request and gives the space back" {
try testing.expectEqual(INITIAL_BUFFER_SIZE, buffer.buf.len);
// a header declares no length, so the buffer doubles to take it
- const filler = "a" ** max;
+ const filler = repeat("a", max);
try sys_net.writeAll(pair[1], filler);
while (buffer.len < filler.len) {
_ = try buffer.read(pair[0]);
@@ -1208,7 +1209,7 @@ test "http: a declared body is sized upfront" {
var state: Connection.State = .header;
const body_len = INITIAL_BUFFER_SIZE * 4;
var head_buf: [64]u8 = undefined;
- const head = try std.fmt.bufPrint(&head_buf, "POST /session HTTP/1.1\r\nContent-Length: {d}\r\n\r\n", .{body_len});
+ const head = try std.mem.print(&head_buf, "POST /session HTTP/1.1\r\nContent-Length: {d}\r\n\r\n", .{body_len});
try sys_net.writeAll(pair[1], head);
// the header alone is enough to know how much room the body needs
diff --git a/src/string.zig b/src/string.zig
index 32a953647..a61703d68 100644
--- a/src/string.zig
+++ b/src/string.zig
@@ -524,7 +524,7 @@ pub const Global = struct {
str: String,
};
-fn asUint(comptime string: anytype) std.meta.Int(
+fn asUint(comptime string: anytype) @Int(
.unsigned,
@bitSizeOf(@TypeOf(string.*)) - 8, // (- 8) to exclude sentinel 0
) {
@@ -537,6 +537,27 @@ fn asUint(comptime string: anytype) std.meta.Int(
return @bitCast(@as(*const [byteLength]u8, string).*);
}
+/// `s` concatenated `n` times, the replacement for the removed `s ** n`.
+pub fn repeat(comptime s: []const u8, comptime n: usize) *const [s.len * n:0]u8 {
+ return &Repeated(s, n).value;
+}
+
+fn Repeated(comptime s: []const u8, comptime n: usize) type {
+ return struct {
+ const value: [s.len * n:0]u8 = blk: {
+ var buf: [s.len * n:0]u8 = undefined;
+ if (s.len == 1) {
+ buf = @splat(s[0]);
+ } else {
+ @setEvalBranchQuota(1000 + 10 * n);
+ for (0..n) |i| @memcpy(buf[i * s.len ..][0..s.len], s);
+ }
+ buf[buf.len] = 0;
+ break :blk buf;
+ };
+ };
+}
+
const testing = @import("testing.zig");
test "truncateUtf8" {
@@ -576,7 +597,7 @@ test "editDistance" {
try testing.expectEqual(@as(usize, 3), editDistance("", "abc"));
try testing.expectEqual(@as(usize, 3), editDistance("abc", ""));
- const long = "x" ** 64;
+ const long = repeat("x", 64);
try testing.expectEqual(@as(usize, 0), editDistance(long, long));
try testing.expectEqual(std.math.maxInt(usize), editDistance(long ++ "x", long));
}
@@ -618,11 +639,11 @@ test "latin1ToUtf8" {
test "String" {
const other_short = try String.init(undefined, "other_short", .{});
- const other_long = try String.init(testing.allocator, "other_long" ** 100, .{});
+ const other_long = try String.init(testing.allocator, repeat("other_long", 100), .{});
defer other_long.deinit(testing.allocator);
inline for (0..100) |i| {
- const input = "a" ** i;
+ const input = repeat("a", i);
const str = try String.init(testing.allocator, input, .{});
defer str.deinit(testing.allocator);
@@ -634,7 +655,7 @@ test "String" {
try testing.expectEqual(false, str.eqlSlice("other_short"));
try testing.expectEqual(false, str.eql(other_long));
- try testing.expectEqual(false, str.eqlSlice("other_long" ** 100));
+ try testing.expectEqual(false, str.eqlSlice(repeat("other_long", 100)));
}
}
@@ -651,8 +672,8 @@ test "String.trim" {
try expect("hi", " hi ", " "); // SSO, both ends
try expect("hello", "hello", " "); // nothing to trim (no allocation)
try expect("", " ", " "); // fully trimmed away
- try expect("x" ** 20, " " ++ ("x" ** 20) ++ "\t", &.{ ' ', '\t' }); // heap stays heap (view)
- try expect("abc", "abc" ++ (" " ** 6), " "); // heap trims down to SSO
+ try expect(repeat("x", 20), " " ++ (repeat("x", 20)) ++ "\t", &.{ ' ', '\t' }); // heap stays heap (view)
+ try expect("abc", "abc" ++ (repeat(" ", 6)), " "); // heap trims down to SSO
}
test "String.concat" {
diff --git a/src/sys/libcurl.zig b/src/sys/libcurl.zig
index 588b7ac63..3d31fad0a 100644
--- a/src/sys/libcurl.zig
+++ b/src/sys/libcurl.zig
@@ -651,7 +651,7 @@ pub fn curl_easy_setopt(easy: *Curl, comptime option: CurlOption, value: anytype
.ssl_ctx_data => @as(*crypto.X509_STORE, value),
- .http_version => @as(c_long, @intFromEnum(@as(CurlHttpVersion, value))),
+ .http_version => @as(c_long, @backingInt(@as(CurlHttpVersion, value))),
.debug_function => @as(CurlDebugFunction, value),
.opensocket_function => @as(CurlOpenSocketFunction, value),
@@ -660,7 +660,7 @@ pub fn curl_easy_setopt(easy: *Curl, comptime option: CurlOption, value: anytype
.write_function => @as(CurlWriteFunction, value),
.ssl_ctx_function => @as(CurlSslCtxFunction, value),
};
- const code = c.curl_easy_setopt(easy, @intFromEnum(option), v);
+ const code = c.curl_easy_setopt(easy, @backingInt(option), v);
return errorCheck(code);
}
@@ -669,7 +669,7 @@ pub fn curl_easy_getinfo(easy: *Curl, comptime info: CurlInfo, out: anytype) Err
@compileError("curl_easy_getinfo out must be a pointer, got " ++ @typeName(@TypeOf(out)));
}
- const inf: c.CURLINFO = @intFromEnum(info);
+ const inf: c.CURLINFO = @backingInt(info);
const code = switch (info) {
.effective_url => blk: {
const p: *[*c]u8 = out;
@@ -718,7 +718,7 @@ pub fn curl_easy_header(
hout: *?*CurlHeader,
) ErrorHeader!void {
var c_hout: [*c]CurlHeader = null;
- const code = c.curl_easy_header(easy, name, index, @intFromEnum(origin), request, &c_hout);
+ const code = c.curl_easy_header(easy, name, index, @backingInt(origin), request, &c_hout);
switch (code) {
c.CURLHE_OK => {
hout.* = @ptrCast(c_hout);
@@ -745,7 +745,7 @@ pub fn curl_easy_nextheader(
request: c_int,
prev: ?*CurlHeader,
) ?*CurlHeader {
- const ptr = c.curl_easy_nextheader(easy, @intFromEnum(origin), request, prev);
+ const ptr = c.curl_easy_nextheader(easy, @backingInt(origin), request, prev);
if (ptr == null) return null;
return @ptrCast(ptr);
}
@@ -759,7 +759,7 @@ pub fn curl_multi_cleanup(multi: *CurlM) ErrorMulti!void {
}
pub fn curl_multi_setopt(multi: *CurlM, comptime option: CurlMOption, value: anytype) ErrorMulti!void {
- const opt: c.CURLMoption = @intFromEnum(option);
+ const opt: c.CURLMoption = @backingInt(option);
const code = switch (option) {
.max_host_connections, .max_connects => blk: {
const n: c_long = switch (@typeInfo(@TypeOf(value))) {
diff --git a/src/sys/net.zig b/src/sys/net.zig
index e6ec19d08..38024e3c8 100644
--- a/src/sys/net.zig
+++ b/src/sys/net.zig
@@ -25,7 +25,7 @@ const builtin = @import("builtin");
const c = std.c;
const posix = std.posix;
-const native_os = builtin.os.tag;
+const native_os = builtin.target.os.tag;
pub const socket_t = posix.socket_t;
pub const IpAddress = std.Io.net.IpAddress;
@@ -98,7 +98,7 @@ pub fn socket(domain: u32, socket_type: u32, protocol: u32) !socket_t {
// SOCK.NONBLOCK/CLOEXEC are Zig-invented shim values); strip them and
// apply via fcntl instead. Linux/FreeBSD accept them natively.
const flag_bits = posix.SOCK.NONBLOCK | posix.SOCK.CLOEXEC;
- const extra: u32 = if (comptime builtin.os.tag.isDarwin()) socket_type & flag_bits else 0;
+ const extra: u32 = if (comptime builtin.target.os.tag.isDarwin()) socket_type & flag_bits else 0;
const rc = c.socket(domain, socket_type & ~extra, protocol);
if (rc < 0) {
return errnoError(c.errno(rc));
diff --git a/src/telemetry/lightpanda.zig b/src/telemetry/lightpanda.zig
index 2ff1770e5..b698b2649 100644
--- a/src/telemetry/lightpanda.zig
+++ b/src/telemetry/lightpanda.zig
@@ -23,13 +23,13 @@ const LINGER_MS = 5000;
const LINGER_BATCH = 16;
const URL = "https://telemetry.lightpanda.io/v2";
-const OS_CODE = switch (builtin.os.tag) {
+const OS_CODE = switch (builtin.target.os.tag) {
.linux => "L",
.macos => "M",
.ios => "I",
else => "O",
};
-const ARCH_CODE = switch (builtin.cpu.arch) {
+const ARCH_CODE = switch (builtin.target.cpu.arch) {
.x86_64 => "X",
.aarch64 => "A",
else => "O",
@@ -391,7 +391,7 @@ test "Telemetry: header wire format" {
};
try std.json.Stringify.value(&header, .{}, &w.writer);
- const expected = try std.fmt.allocPrint(testing.allocator, "[\"the-iid\",\"H\",\"S\",1,\"{s}\",\"{s}\",\"{s}\"]", .{ OS_CODE, ARCH_CODE, build_config.version });
+ const expected = try testing.allocator.print("[\"the-iid\",\"H\",\"S\",1,\"{s}\",\"{s}\",\"{s}\"]", .{ OS_CODE, ARCH_CODE, build_config.version });
defer testing.allocator.free(expected);
try testing.expectEqual(expected, w.written());
diff --git a/src/test_runner.zig b/src/test_runner.zig
index a4a83a240..d72b210f7 100644
--- a/src/test_runner.zig
+++ b/src/test_runner.zig
@@ -22,7 +22,7 @@ const builtin = @import("builtin");
const Io = std.Io;
const Allocator = std.mem.Allocator;
-const BORDER = "=" ** 80;
+const BORDER: [80]u8 = @splat('=');
// use in custom panic handler
var current_test: ?[]const u8 = null;
@@ -35,7 +35,7 @@ pub fn main(init: std.process.Init) !void {
var mem: [8192]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&mem);
- var gpa: std.heap.DebugAllocator(.{}) = .init;
+ var gpa: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{});
var arena = std.heap.ArenaAllocator.init(gpa.allocator());
defer arena.deinit();
@@ -90,7 +90,7 @@ const Runner = struct {
Printer.fmt("\r\x1b[0K", .{}); // beginning of line and clear to end of line
- var after_each: ?std.builtin.TestFn = null;
+ var after_each: ?std.lang.TestFn = null;
for (builtin.test_functions) |t| {
if (isAfterEach(t)) {
after_each = t;
@@ -148,7 +148,10 @@ const Runner = struct {
}
current_test = friendly_name;
- std.testing.allocator_instance = .{};
+ std.testing.allocator_instance = .init(std.heap.page_allocator, .{
+ .canary = 0xc3a701ba,
+ .check_write_after_free = true,
+ });
var result = t.func();
if (after_each) |ae| {
// always runs, so that it can reset state, but it can only
@@ -168,7 +171,7 @@ const Runner = struct {
const ns_taken = slowest.endTiming(io, friendly_name, is_unnamed_test);
ns_duration += ns_taken;
- if (std.testing.allocator_instance.deinit() == .leak) {
+ if (std.testing.allocator_instance.deinit() != 0) {
leak += 1;
Printer.status(.fail, "\n{s}\n\"{s}\" - Memory Leak\n{s}\n", .{ BORDER, friendly_name, BORDER });
}
@@ -186,7 +189,7 @@ const Runner = struct {
status = .fail;
fail += 1;
Printer.status(.fail, "\n{s}\n\"{s}\" - {s}\n", .{ BORDER, friendly_name, @errorName(err) });
- if (self.subtests.getLastOrNull()) |st| {
+ if (self.subtests.last()) |st| {
Printer.status(.fail, " {s}\n", .{st});
}
Printer.status(.fail, BORDER ++ "\n", .{});
@@ -447,7 +450,7 @@ pub const panic = std.debug.FullPanic(struct {
fn panicFn(msg: []const u8, first_trace_addr: ?usize) noreturn {
if (current_test) |ct| {
std.debug.print("\x1b[31m{s}\npanic running \"{s}\"\n", .{ BORDER, ct });
- if (RUNNER.subtests.getLastOrNull()) |st| {
+ if (RUNNER.subtests.last()) |st| {
std.debug.print(" {s}\n", .{st});
}
std.debug.print("\x1b[0m{s}\n", .{BORDER});
@@ -456,7 +459,7 @@ pub const panic = std.debug.FullPanic(struct {
}
}.panicFn);
-fn isUnnamed(t: std.builtin.TestFn) bool {
+fn isUnnamed(t: std.lang.TestFn) bool {
const marker = ".test_";
const test_name = t.name;
const index = std.mem.indexOf(u8, test_name, marker) orelse return false;
@@ -464,15 +467,15 @@ fn isUnnamed(t: std.builtin.TestFn) bool {
return true;
}
-fn isSetup(t: std.builtin.TestFn) bool {
+fn isSetup(t: std.lang.TestFn) bool {
return std.mem.endsWith(u8, t.name, "tests:beforeAll");
}
-fn isTeardown(t: std.builtin.TestFn) bool {
+fn isTeardown(t: std.lang.TestFn) bool {
return std.mem.endsWith(u8, t.name, "tests:afterAll");
}
-fn isAfterEach(t: std.builtin.TestFn) bool {
+fn isAfterEach(t: std.lang.TestFn) bool {
return std.mem.endsWith(u8, t.name, "tests:afterEach");
}
diff --git a/src/testing.zig b/src/testing.zig
index 949a42e2a..09e5dd23a 100644
--- a/src/testing.zig
+++ b/src/testing.zig
@@ -18,6 +18,7 @@
const std = @import("std");
const lp = @import("lightpanda");
+const repeat = @import("string.zig").repeat;
const log = lp.log;
const Allocator = std.mem.Allocator;
@@ -66,8 +67,8 @@ pub fn expectEqual(expected: anytype, actual: anytype) !void {
}
},
.@"struct" => |structType| {
- inline for (structType.fields) |field| {
- try expectEqual(@field(expected, field.name), @field(actual, field.name));
+ inline for (structType.field_names) |field_name| {
+ try expectEqual(@field(expected, field_name), @field(actual, field_name));
}
return;
},
@@ -90,9 +91,9 @@ pub fn expectEqual(expected: anytype, actual: anytype) !void {
const actualTag = @as(Tag, actual);
try expectEqual(expectedTag, actualTag);
- inline for (std.meta.fields(@TypeOf(actual))) |fld| {
- if (std.mem.eql(u8, fld.name, @tagName(actualTag))) {
- try expectEqual(@field(expected, fld.name), @field(actual, fld.name));
+ inline for (@typeInfo(@TypeOf(actual)).@"union".field_names) |field_name| {
+ if (std.mem.eql(u8, field_name, @tagName(actualTag))) {
+ try expectEqual(@field(expected, field_name), @field(actual, field_name));
return;
}
}
@@ -148,7 +149,7 @@ fn isStringArray(comptime T: type) bool {
}
const TraitFn = fn (type) bool;
-pub fn is(comptime id: std.builtin.TypeId) TraitFn {
+pub fn is(comptime id: std.lang.TypeId) TraitFn {
const Closure = struct {
fn trait(comptime T: type) bool {
return id == @typeInfo(T);
@@ -157,7 +158,7 @@ pub fn is(comptime id: std.builtin.TypeId) TraitFn {
return Closure.trait;
}
-fn isPtrTo(comptime id: std.builtin.TypeId) TraitFn {
+fn isPtrTo(comptime id: std.lang.TypeId) TraitFn {
const Closure = struct {
fn trait(comptime T: type) bool {
if (!comptime isSingleItemPtr(T)) return false;
@@ -421,8 +422,7 @@ fn runWebApiTest(test_file: [:0]const u8, timeout_ms: u32) !void {
const page = try test_session.createPage();
defer page.close();
- const url = try std.fmt.allocPrintSentinel(
- arena_allocator,
+ const url = try arena_allocator.printSentinel(
"http://127.0.0.1:9582/{s}",
.{test_file},
0,
@@ -495,8 +495,7 @@ pub fn pageTest(comptime test_file: []const u8, opts: PageTestOpts) !Session.Pag
const page = try test_session.createPage();
errdefer page.close();
- const url = try std.fmt.allocPrintSentinel(
- arena_allocator,
+ const url = try arena_allocator.printSentinel(
"http://127.0.0.1:9582/{s}{s}",
.{ WEB_API_TEST_ROOT, test_file },
0,
@@ -658,7 +657,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
}
if (std.mem.eql(u8, path, "/xhr")) {
- return req.respond("1234567890" ** 10, .{
+ return req.respond(repeat("1234567890", 10), .{
.extra_headers = &.{
.{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
},
@@ -767,7 +766,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
// whose origin must change between its request and its response.
if (std.mem.startsWith(u8, path, "/redirect-cross-origin/")) {
var location_buf: [1024]u8 = undefined;
- const location = try std.fmt.bufPrint(&location_buf, "http://localhost:9582/{s}", .{path["/redirect-cross-origin/".len..]});
+ const location = try std.mem.print(&location_buf, "http://localhost:9582/{s}", .{path["/redirect-cross-origin/".len..]});
return req.respond("", .{
.status = .found,
.extra_headers = &.{
@@ -889,7 +888,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
};
slot.* += 1;
var buf: [64]u8 = undefined;
- const body = try std.fmt.bufPrint(&buf, "window.__serve_count_{s} = {d};", .{ name, slot.* });
+ const body = try std.mem.print(&buf, "window.__serve_count_{s} = {d};", .{ name, slot.* });
return req.respond(body, .{
.extra_headers = &.{
.{ .name = "Content-Type", .value = "application/javascript" },
@@ -900,7 +899,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
if (std.mem.startsWith(u8, path, "/status/")) {
const code = try std.fmt.parseInt(u16, path["/status/".len..], 10);
- return req.respond("", .{ .status = @enumFromInt(code) });
+ return req.respond("", .{ .status = @fromBackingInt(@intCast(code)) });
}
if (std.mem.eql(u8, path, "/xhr/reason")) {
@@ -1198,7 +1197,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
}
}
var html_buf: [512]u8 = undefined;
- const html = try std.fmt.bufPrint(&html_buf, "<html><body>referer={s}</body></html>", .{referer});
+ const html = try std.mem.print(&html_buf, "<html><body>referer={s}</body></html>", .{referer});
return req.respond(html, .{
.extra_headers = &.{
.{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
@@ -1225,7 +1224,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
// method the navigation used. Used by the Page.reload-replays-POST test.
const method_name = @tagName(req.head.method);
var html_buf: [128]u8 = undefined;
- const html = try std.fmt.bufPrint(&html_buf, "<html><body>method={s}</body></html>", .{method_name});
+ const html = try std.mem.print(&html_buf, "<html><body>method={s}</body></html>", .{method_name});
return req.respond(html, .{
.extra_headers = &.{
.{ .name = "Content-Type", .value = "text/html; charset=utf-8" },
@@ -1265,7 +1264,7 @@ fn testHTTPHandler(req: *std.http.Server.Request) !void {
var pos: usize = 0;
var it = req.iterateHeaders();
while (it.next()) |header| {
- const line = try std.fmt.bufPrint(buf[pos..], "{s}: {s}\n", .{ header.name, header.value });
+ const line = try std.mem.print(buf[pos..], "{s}: {s}\n", .{ header.name, header.value });
pos += line.len;
}
return req.respond(buf[0..pos], .{
@@ -1374,7 +1373,7 @@ pub const expectLog = log.expectLog;
/// Suppresses every line from `scopes` for the rest of the test.
pub fn silenceLog(comptime scopes: []const log.Scope) void {
inline for (scopes) |scope| {
- log.opts.scope_enabled[@intFromEnum(scope)] = false;
+ log.opts.scope_enabled[@backingInt(scope)] = false;
}
}
@@ -1393,7 +1392,7 @@ test "tests:afterEach" {
continue;
}
failed = true;
- const scope: log.Scope = @enumFromInt(i);
+ const scope: log.Scope = @fromBackingInt(@intCast(i));
std.debug.print("expected {d} more {s} log line(s)\n", .{ count, @tagName(scope) });
}