aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.devcontainer/scripts/zig-env.sh2
-rw-r--r--Dockerfile4
-rw-r--r--Dockerfile.devcontainer2
-rw-r--r--Makefile20
-rw-r--r--README.md2
-rw-r--r--bench/hot-module-reloading/css-stress-test/Makefile4
-rw-r--r--build.zig284
-rw-r--r--misctools/fetch.zig4
-rw-r--r--misctools/http_bench.zig4
-rw-r--r--misctools/readlink-getfd.zig6
-rw-r--r--misctools/readlink-realpath.zig4
-rw-r--r--misctools/tgz.zig8
-rw-r--r--src/allocators.zig2
-rw-r--r--src/analytics/analytics_thread.zig10
-rw-r--r--src/baby_list.zig7
-rw-r--r--src/base64/base64.zig8
-rw-r--r--src/bindgen.zig5
-rw-r--r--src/bun.js/api/bun.zig14
-rw-r--r--src/bun.js/api/bun/socket.zig2
-rw-r--r--src/bun.js/api/bun/spawn.zig4
-rw-r--r--src/bun.js/api/bun/subprocess.zig3
-rw-r--r--src/bun.js/api/ffi.zig66
-rw-r--r--src/bun.js/api/filesystem_router.zig4
-rw-r--r--src/bun.js/api/transpiler.zig2
-rw-r--r--src/bun.js/base.zig22
-rw-r--r--src/bun.js/bindings/bindings.zig4
-rw-r--r--src/bun.js/bindings/exports.zig8
-rw-r--r--src/bun.js/bindings/header-gen.zig24
-rw-r--r--src/bun.js/bindings/headers-cpp.h2
-rw-r--r--src/bun.js/bindings/headers.h2
-rw-r--r--src/bun.js/bindings/shimmer.zig2
-rw-r--r--src/bun.js/bindings/sizes.zig2
-rw-r--r--src/bun.js/event_loop.zig1
-rw-r--r--src/bun.js/javascript.zig18
-rw-r--r--src/bun.js/module_loader.zig20
-rw-r--r--src/bun.js/node/node_os.zig68
-rw-r--r--src/bun.js/node/syscall.zig2
-rw-r--r--src/bun.js/node/types.zig12
-rw-r--r--src/bun.js/test/jest.zig20
-rw-r--r--src/bun.js/uuid.zig4
-rw-r--r--src/bun.js/webcore/base64.zig8
-rw-r--r--src/bun.js/webcore/blob.zig8
-rw-r--r--src/bun.js/webcore/body.zig28
-rw-r--r--src/bun.js/webcore/encoding.zig2
-rw-r--r--src/bun.js/webcore/request.zig4
-rw-r--r--src/bun.js/webcore/response.zig14
-rw-r--r--src/bun.js/webcore/streams.zig8
-rw-r--r--src/bun.zig77
-rw-r--r--src/bundler.zig2
-rw-r--r--src/bundler/generate_node_modules_bundle.zig12
-rw-r--r--src/bunfig.zig8
-rw-r--r--src/cli.zig16
-rw-r--r--src/cli/build_command.zig2
-rw-r--r--src/cli/bunx_command.zig10
-rw-r--r--src/cli/colon_list_type.zig2
-rw-r--r--src/cli/create_command.zig16
-rw-r--r--src/cli/init_command.zig4
-rw-r--r--src/cli/install_completions_command.zig30
-rw-r--r--src/cli/package_manager_command.zig6
-rw-r--r--src/cli/run_command.zig2
-rw-r--r--src/cli/shell_completions.zig8
-rw-r--r--src/cli/test_command.zig4
-rw-r--r--src/cli/upgrade_command.zig4
-rw-r--r--src/comptime_string_map.zig2
-rw-r--r--src/deps/c_ares.zig8
-rw-r--r--src/deps/picohttp.zig4
-rw-r--r--src/deps/zig-clap/clap/args.zig2
-rw-r--r--src/deps/zig-clap/clap/comptime.zig4
-rw-r--r--src/deps/zig-datetime/src/datetime.zig4
-rw-r--r--src/env_loader.zig12
-rw-r--r--src/exact_size_matcher.zig2
-rw-r--r--src/fs.zig8
-rw-r--r--src/futex.zig2
-rw-r--r--src/http.zig8
-rw-r--r--src/http/websocket.zig4
-rw-r--r--src/http/websocket_http_client.zig4
-rw-r--r--src/http_client_async.zig18
-rw-r--r--src/install/bin.zig2
-rw-r--r--src/install/bit_set.zig24
-rw-r--r--src/install/dependency.zig8
-rw-r--r--src/install/install.zig10
-rw-r--r--src/install/lockfile.zig62
-rw-r--r--src/install/npm.zig8
-rw-r--r--src/io/io_darwin.zig2
-rw-r--r--src/js_ast.zig14
-rw-r--r--src/js_lexer/identifier_cache.zig2
-rw-r--r--src/js_parser.zig34
-rw-r--r--src/js_printer.zig32
-rw-r--r--src/json_parser.zig2
-rw-r--r--src/libarchive/libarchive.zig16
-rw-r--r--src/logger.zig8
-rw-r--r--src/main.zig5
-rw-r--r--src/mdx/mdx_parser.zig2
-rw-r--r--src/napi/napi.zig2
-rw-r--r--src/node_module_bundle.zig10
-rw-r--r--src/open.zig6
-rw-r--r--src/options.zig14
-rw-r--r--src/report.zig4
-rw-r--r--src/resolver/package_json.zig12
-rw-r--r--src/resolver/resolver.zig6
-rw-r--r--src/router.zig7
-rw-r--r--src/runtime.zig4
-rw-r--r--src/sha.zig2
-rw-r--r--src/sourcemap/sourcemap.zig2
-rw-r--r--src/sourcemap/vlq_bench.zig32
-rw-r--r--src/string_immutable.zig54
-rw-r--r--src/string_mutable.zig6
-rw-r--r--src/sync.zig4
-rw-r--r--src/tagged_pointer.zig4
-rw-r--r--src/url.zig8
-rw-r--r--src/walker_skippable.zig2
-rw-r--r--src/watcher.zig10
-rw-r--r--src/zlib.zig5
-rw-r--r--test/bun.js/bunExe.ts6
-rw-r--r--test/bun.js/test-test.test.ts4
115 files changed, 772 insertions, 702 deletions
diff --git a/.devcontainer/scripts/zig-env.sh b/.devcontainer/scripts/zig-env.sh
index c9dd6131b..c98539a74 100644
--- a/.devcontainer/scripts/zig-env.sh
+++ b/.devcontainer/scripts/zig-env.sh
@@ -5,4 +5,4 @@ git clone https://github.com/zigtools/zls /home/ubuntu/zls
cd /home/ubuntu/zls
git checkout aabdb0c6ecb3c9a47feff2c2bfb9be4e95adf723
git submodule update --init --recursive --progress --depth=1
-zig build -Drelease-fast
+zig build -Doptimize=ReleaseFast
diff --git a/Dockerfile b/Dockerfile
index 2aeb5e1d6..7b14725ad 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -12,7 +12,7 @@ ARG TRIPLET=${ARCH}-linux-gnu
ARG BUILDARCH=amd64
ARG WEBKIT_TAG=feb9
ARG ZIG_TAG=jul1
-ARG ZIG_VERSION="0.11.0-dev.1393+38eebf3c4"
+ARG ZIG_VERSION="0.11.0-dev.1783+436e99d13"
ARG WEBKIT_BASENAME="bun-webkit-linux-$BUILDARCH"
ARG ZIG_FOLDERNAME=zig-linux-${BUILD_MACHINE_ARCH}-${ZIG_VERSION}
@@ -426,7 +426,7 @@ ENV CCACHE_DIR=/ccache
RUN --mount=type=cache,target=/ccache cd $BUN_DIR && mkdir -p src/bun.js/bindings-obj && rm -rf $HOME/.cache zig-cache && make prerelease && \
mkdir -p $BUN_RELEASE_DIR && \
- OUTPUT_DIR=/tmp/bun-${TRIPLET}-${GIT_SHA} $ZIG_PATH/zig build obj -Doutput-dir=/tmp/bun-${TRIPLET}-${GIT_SHA} -Drelease-fast -Dtarget="${TRIPLET}" -Dcpu="${CPU_TARGET}" && \
+ OUTPUT_DIR=/tmp/bun-${TRIPLET}-${GIT_SHA} $ZIG_PATH/zig build obj -Doutput-dir=/tmp/bun-${TRIPLET}-${GIT_SHA} -Doptimize=ReleaseFast -Dtarget="${TRIPLET}" -Dcpu="${CPU_TARGET}" && \
cp /tmp/bun-${TRIPLET}-${GIT_SHA}/bun.o /tmp/bun-${TRIPLET}-${GIT_SHA}/bun-${BUN_BASE_VERSION}.$(cat ${BUN_DIR}/src/build-id).o && cd / && rm -rf $BUN_DIR
FROM scratch as build_release_obj
diff --git a/Dockerfile.devcontainer b/Dockerfile.devcontainer
index 369a313e6..952d4f07b 100644
--- a/Dockerfile.devcontainer
+++ b/Dockerfile.devcontainer
@@ -8,7 +8,7 @@ ARG BUN_RELEASE_DIR=${GITHUB_WORKSPACE}/bun-release
ARG BUN_DEPS_OUT_DIR=${GITHUB_WORKSPACE}/bun-deps
ARG BUN_DIR=${GITHUB_WORKSPACE}/bun
ARG BUN_PACKAGES_DIR=${BUN_DIR}/packages
-ARG ZIG_VERSION="0.11.0-dev.1393+38eebf3c4"
+ARG ZIG_VERSION="0.11.0-dev.1783+436e99d13"
ARG ZIG_FOLDERNAME=zig-linux-${ARCH}-${ZIG_VERSION}
ARG ZIG_FILENAME=${ZIG_FOLDERNAME}.tar.xz
diff --git a/Makefile b/Makefile
index e0b1a8635..2dc951524 100644
--- a/Makefile
+++ b/Makefile
@@ -628,7 +628,7 @@ libarchive:
.PHONY: tgz
tgz:
- $(ZIG) build tgz-obj -Drelease-fast
+ $(ZIG) build tgz-obj -Doptimize=ReleaseFast
$(CXX) $(PACKAGE_DIR)/tgz.o -g -o ./misctools/tgz $(DEFAULT_LINKER_FLAGS) -lc $(ARCHIVE_FILES)
rm -rf $(PACKAGE_DIR)/tgz.o
@@ -665,7 +665,7 @@ init-submodules:
.PHONY: build-obj
build-obj:
- $(ZIG) build obj -Drelease-fast -Dcpu="$(CPU_TARGET)"
+ $(ZIG) build obj -Doptimize=ReleaseFast -Dcpu="$(CPU_TARGET)"
.PHONY: dev-build-obj-wasm
dev-build-obj-wasm:
@@ -682,7 +682,7 @@ dev-wasm: dev-build-obj-wasm
.PHONY: build-obj-wasm
build-obj-wasm:
- $(ZIG) build bun-wasm -Drelease-fast -Dtarget=wasm32-freestanding --prominent-compile-errors
+ $(ZIG) build bun-wasm -Doptimize=ReleaseFast -Dtarget=wasm32-freestanding --prominent-compile-errors
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \
-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/libmimalloc.a.wasm \
@@ -692,7 +692,7 @@ build-obj-wasm:
.PHONY: build-obj-wasm-small
build-obj-wasm-small:
- $(ZIG) build bun-wasm -Drelease-small -Dtarget=wasm32-freestanding --prominent-compile-errors
+ $(ZIG) build bun-wasm -Doptimize=ReleaseSmall -Dtarget=wasm32-freestanding --prominent-compile-errors
emcc -sEXPORTED_FUNCTIONS="['_bun_free', '_cycleStart', '_cycleEnd', '_bun_malloc', '_scan', '_transform', '_init']" \
-g -s ERROR_ON_UNDEFINED_SYMBOLS=0 -DNDEBUG \
$(BUN_DEPS_DIR)/libmimalloc.a.wasm \
@@ -719,7 +719,7 @@ wasm: api build-obj-wasm-small
.PHONY: build-obj-safe
build-obj-safe:
- $(ZIG) build obj -Drelease-safe
+ $(ZIG) build obj -Doptimize=ReleaseSafe
UWS_CC_FLAGS = -pthread -DLIBUS_USE_OPENSSL=1 -DUWS_HTTPRESPONSE_NO_WRITEMARK=1 -DLIBUS_USE_BORINGSSL=1 -DWITH_BORINGSSL=1 -Wpedantic -Wall -Wextra -Wsign-conversion -Wconversion $(UWS_INCLUDE) -DUWS_WITH_PROXY
UWS_CXX_FLAGS = $(UWS_CC_FLAGS) -std=$(CXX_VERSION) -fno-exceptions
@@ -821,13 +821,13 @@ generate-install-script:
.PHONY: fetch
fetch: $(IO_FILES)
- $(ZIG) build -Drelease-fast fetch-obj
+ $(ZIG) build -Doptimize=ReleaseFast fetch-obj
$(CXX) $(PACKAGE_DIR)/fetch.o -g $(OPTIMIZATION_LEVEL) -o ./misctools/fetch $(IO_FILES) $(DEFAULT_LINKER_FLAGS) -lc $(MINIMUM_ARCHIVE_FILES)
rm -rf $(PACKAGE_DIR)/fetch.o
.PHONY: sha
sha:
- $(ZIG) build -Drelease-fast sha-bench-obj
+ $(ZIG) build -Doptimize=ReleaseFast sha-bench-obj
$(CXX) $(PACKAGE_DIR)/sha.o -g $(OPTIMIZATION_LEVEL) -o ./misctools/sha $(DEFAULT_LINKER_FLAGS) -lc $(MINIMUM_ARCHIVE_FILES)
rm -rf $(PACKAGE_DIR)/sha.o
@@ -843,7 +843,7 @@ machbench-debug: $(IO_FILES)
.PHONY: machbench
machbench: $(IO_FILES)
- $(ZIG) build -Drelease-fast machbench-obj
+ $(ZIG) build -Doptimize=ReleaseFast machbench-obj
$(CXX) $(PACKAGE_DIR)/machbench.o -g $(OPTIMIZATION_LEVEL) -o ./misctools/machbench $(IO_FILES) $(DEFAULT_LINKER_FLAGS) -lc $(MINIMUM_ARCHIVE_FILES)
rm -rf $(PACKAGE_DIR)/machbench.o
@@ -855,7 +855,7 @@ httpbench-debug: $(IO_FILES)
.PHONY: httpbench-release
httpbench-release: $(IO_FILES)
- $(ZIG) build -Drelease-fast httpbench-obj
+ $(ZIG) build -Doptimize=ReleaseFast httpbench-obj
$(CXX) $(PACKAGE_DIR)/httpbench.o -g $(OPTIMIZATION_LEVEL) -o ./misctools/httpbench $(IO_FILES) $(DEFAULT_LINKER_FLAGS) -lc $(MINIMUM_ARCHIVE_FILES)
rm -rf $(PACKAGE_DIR)/httpbench.o
@@ -1076,7 +1076,7 @@ release-bin-dir:
.PHONY: dev-obj
dev-obj:
- $(ZIG) build obj --prominent-compile-errors
+ $(ZIG) build obj --prominent-compile-errors -freference-trace
.PHONY: dev-obj-linux
dev-obj-linux:
diff --git a/README.md b/README.md
index f57ee6f36..2f712d64d 100644
--- a/README.md
+++ b/README.md
@@ -5231,7 +5231,7 @@ On fish that looks like `fish_add_path (brew --prefix llvm@15)/bin`
Install the version of Zig referenced in the [`Dockerfile`](./Dockerfile) using [zigup](https://github.com/marler8997/zigup). For example:
```bash
-zigup 0.11.0-dev.1393+38eebf3c4
+zigup 0.11.0-dev.1783+436e99d13
```
#### Build bun (macOS)
diff --git a/bench/hot-module-reloading/css-stress-test/Makefile b/bench/hot-module-reloading/css-stress-test/Makefile
index cc24641b9..cab212e81 100644
--- a/bench/hot-module-reloading/css-stress-test/Makefile
+++ b/bench/hot-module-reloading/css-stress-test/Makefile
@@ -29,7 +29,7 @@ loop:
-e 'if windows is not {} then perform action "AXRaise" of item 1 of windows' \
-e 'end tell'
sleep 0.5
- cd src; zig run -Drelease-fast ../color-looper.zig -- ./colors.css:0 $(SLEEP_INTERVAL)
+ cd src; zig run -Doptimize=ReleaseFast ../color-looper.zig -- ./colors.css:0 $(SLEEP_INTERVAL)
cp src/colors.css.blob $(PROJECT)/colors.css.blob
loop-emotion:
@@ -40,7 +40,7 @@ loop-emotion:
-e 'if windows is not {} then perform action "AXRaise" of item 1 of windows' \
-e 'end tell'
sleep 0.5
- cd src; zig run -Drelease-fast ../color-looper.emotion.zig -- ./css-in-js-styles.tsx:0 $(SLEEP_INTERVAL)
+ cd src; zig run -Doptimize=ReleaseFast ../color-looper.emotion.zig -- ./css-in-js-styles.tsx:0 $(SLEEP_INTERVAL)
cp src/css-in-js-styles.tsx.blob $(PROJECT)/css-in-js-styles.blob
process_video:
diff --git a/build.zig b/build.zig
index e89ad8cdf..2f8316ef1 100644
--- a/build.zig
+++ b/build.zig
@@ -1,14 +1,14 @@
const std = @import("std");
-fn pkgPath(comptime out: []const u8) std.build.FileSource {
+fn moduleSource(comptime out: []const u8) FileSource {
if (comptime std.fs.path.dirname(@src().file)) |base| {
const outpath = comptime base ++ std.fs.path.sep_str ++ out;
- return .{ .path = outpath };
+ return FileSource.relative(outpath);
} else {
- return .{ .path = out };
+ return FileSource.relative(out);
}
}
-pub fn addPicoHTTP(step: *std.build.LibExeObjStep, comptime with_obj: bool) void {
+pub fn addPicoHTTP(step: *CompileStep, comptime with_obj: bool) void {
step.addIncludePath("src/deps");
if (with_obj) {
@@ -45,91 +45,29 @@ const color_map = std.ComptimeStringMap([]const u8, .{
var compiler_rt_path: []const u8 = "";
var compiler_rt_path_buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
-fn addInternalPackages(step: *std.build.LibExeObjStep, allocator: std.mem.Allocator, zig_exe: []const u8, target: anytype) !void {
- var bun = std.build.Pkg{
- .name = "bun",
- .source = pkgPath("src/bun_redirect.zig"),
- };
-
- var io_darwin: std.build.Pkg = .{
- .name = "async_io",
- .source = pkgPath("src/io/io_darwin.zig"),
- };
- var io_linux: std.build.Pkg = .{
- .name = "async_io",
- .source = pkgPath("src/io/io_linux.zig"),
- };
- var io_stub: std.build.Pkg = .{
- .name = "async_io",
- .source = pkgPath("src/io/io_stub.zig"),
- };
-
- var io = if (target.isDarwin())
- io_darwin
- else if (target.isLinux())
- io_linux
- else
- io_stub;
+fn addInternalPackages(b: *Build, step: *CompileStep, _: std.mem.Allocator, _: []const u8, target: anytype) !void {
+ var bun = b.createModule(.{
+ .source_file = FileSource.relative("src/bun_redirect.zig"),
+ });
- var javascript_core_real: std.build.Pkg = .{
- .name = "javascript_core",
- .source = pkgPath("src/jsc.zig"),
- };
+ var io: *Module = brk: {
+ if (target.isDarwin()) {
+ break :brk b.createModule(.{
+ .source_file = FileSource.relative("src/io/io_darwin.zig"),
+ });
+ } else if (target.isLinux()) {
+ break :brk b.createModule(.{
+ .source_file = FileSource.relative("src/io/io_linux.zig"),
+ });
+ }
- var javascript_core_stub: std.build.Pkg = .{
- .name = "javascript_core",
- .source = pkgPath("src/jsc_stub.zig"),
+ break :brk b.createModule(.{
+ .source_file = FileSource.relative("src/io/io_stub.zig"),
+ });
};
- var javascript_core = if (target.getOsTag() == .freestanding)
- javascript_core_stub
- else
- javascript_core_real;
- javascript_core.dependencies = &[_]std.build.Pkg{};
- step.addPackage(io);
- step.addPackage(bun);
-
- const paths_to_try = .{
- "{s}/../lib/compiler_rt/stack_probe.zig",
- "{s}/../../lib/compiler_rt/stack_probe.zig",
- "{s}/../../../lib/compiler_rt/stack_probe.zig",
- "{s}/../../../../lib/compiler_rt/stack_probe.zig",
- "{s}/../lib/zig/compiler_rt/stack_probe.zig",
- "{s}/../../lib/zig/compiler_rt/stack_probe.zig",
- "{s}/../../../lib/zig/compiler_rt/stack_probe.zig",
- "{s}/../../../../lib/zig/compiler_rt/stack_probe.zig",
- };
- var found = false;
- if (compiler_rt_path.len > 0) {
- const compiler_rt: std.build.Pkg = .{
- .name = "compiler_rt",
- .source = .{ .path = compiler_rt_path },
- };
- found = true;
- step.addPackage(compiler_rt);
- } else {
- inline for (paths_to_try) |path_fmt| {
- if (!found) brk: {
- // workaround for https://github.com/ziglang/zig/issues/14099
- const path = try std.fmt.allocPrint(allocator, path_fmt, .{zig_exe});
- var target_path = std.os.realpath(
- std.fs.path.resolve(allocator, &.{path}) catch break :brk,
- &compiler_rt_path_buf,
- ) catch break :brk;
- const compiler_rt: std.build.Pkg = .{
- .name = "compiler_rt",
- .source = .{ .path = target_path },
- };
- found = true;
- step.addPackage(compiler_rt);
- compiler_rt_path = target_path;
- }
- }
- }
-
- if (!found) {
- std.io.getStdErr().writeAll("\nwarning: Could not find compiler_rt. This might cause a build error until https://github.com/ziglang/zig/issues/14099 is fixed.\n\n") catch {};
- }
+ step.addModule("async_io", io);
+ step.addModule("bun", bun);
}
const BunBuildOptions = struct {
@@ -154,7 +92,7 @@ const BunBuildOptions = struct {
var output_dir: []const u8 = "";
fn panicIfNotFound(comptime filepath: []const u8) []const u8 {
- var file = std.fs.cwd().openFile(filepath, .{ .mode = .read_only }) catch |err| {
+ var file = std.fs.cwd().openFile(filepath, .{ .optimize = .read_only }) catch |err| {
std.debug.panic("error: {s} opening {s}. Please ensure you've downloaded git submodules, and ran `make vendor`, `make jsc`.", .{ filepath, @errorName(err) });
};
file.close();
@@ -197,14 +135,22 @@ fn updateRuntime() anyerror!void {
}
var x64 = "x64";
-var mode: std.builtin.Mode = undefined;
+var optimize: std.builtin.OptimizeMode = undefined;
-const Builder = std.build.Builder;
+const Build = std.Build;
const CrossTarget = std.zig.CrossTarget;
-const Mode = std.builtin.Mode;
+const OptimizeMode = std.builtin.OptimizeMode;
+const CompileStep = std.build.CompileStep;
+const FileSource = std.build.FileSource;
+const Module = std.build.Module;
const fs = std.fs;
-pub fn build(b: *std.build.Builder) !void {
+const l = enum {
+ Hello,
+ Enum,
+};
+
+pub fn build(b: *Build) !void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
@@ -212,10 +158,10 @@ pub fn build(b: *std.build.Builder) !void {
var target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
- mode = b.standardReleaseOptions();
+ optimize = b.standardOptimizeOption(.{});
var output_dir_buf = std.mem.zeroes([4096]u8);
- var bin_label = if (mode == std.builtin.Mode.Debug) "packages/debug-bun-" else "packages/bun-";
+ var bin_label = if (optimize == std.builtin.OptimizeMode.Debug) "packages/debug-bun-" else "packages/bun-";
var triplet_buf: [64]u8 = undefined;
var os_tagname = @tagName(target.getOs().tag);
@@ -258,7 +204,7 @@ pub fn build(b: *std.build.Builder) !void {
}
std.fs.cwd().makePath(output_dir) catch {};
- const bun_executable_name = if (mode == std.builtin.Mode.Debug) "bun-debug" else "bun";
+ const bun_executable_name = if (optimize == std.builtin.OptimizeMode.Debug) "bun-debug" else "bun";
const root_src = if (target.getOsTag() == std.Target.Os.Tag.freestanding)
"src/main_wasm.zig"
else
@@ -268,15 +214,22 @@ pub fn build(b: *std.build.Builder) !void {
const min_version: std.builtin.Version = if (target.getOsTag() != .freestanding)
target.getOsVersionMin().semver
- else .{ .major = 0, .minor = 0, .patch = 0 };
+ else
+ .{ .major = 0, .minor = 0, .patch = 0 };
const max_version: std.builtin.Version = if (target.getOsTag() != .freestanding)
target.getOsVersionMax().semver
- else .{ .major = 0, .minor = 0, .patch = 0 };
+ else
+ .{ .major = 0, .minor = 0, .patch = 0 };
var obj_step = b.step("obj", "Build bun as a .o file");
obj_step.dependOn(&b.addLog("Output: {s}/{s}\n", .{ output_dir, bun_executable_name }).step);
- var obj = b.addObject(bun_executable_name, root_src);
+ var obj = b.addObject(.{
+ .name = bun_executable_name,
+ .root_source_file = FileSource.relative(root_src),
+ .target = target,
+ .optimize = optimize,
+ });
var default_build_options: BunBuildOptions = brk: {
const is_baseline = arch.isX86() and (target.cpu_model == .baseline or
!std.Target.x86.featureSetHas(target.getCpuFeatures(), .avx2));
@@ -316,11 +269,11 @@ pub fn build(b: *std.build.Builder) !void {
};
{
- obj.setTarget(target);
addPicoHTTP(obj, false);
obj.setMainPkgPath(b.pathFromRoot("."));
try addInternalPackages(
+ b,
obj,
b.allocator,
b.zig_exe,
@@ -351,7 +304,7 @@ pub fn build(b: *std.build.Builder) !void {
defer obj_step.dependOn(&obj.step);
- obj.setBuildMode(mode);
+ // obj.setBuildMode(optimize);
var actual_build_options = default_build_options;
if (b.option(bool, "generate-sizes", "Generate sizes of things") orelse false) {
@@ -364,8 +317,8 @@ pub fn build(b: *std.build.Builder) !void {
obj.linkLibC();
obj.strip = false;
- obj.bundle_compiler_rt = true;
- obj.omit_frame_pointer = mode != .Debug;
+ obj.bundle_compiler_rt = false;
+ obj.omit_frame_pointer = optimize != .Debug;
if (b.option(bool, "for-editor", "Do not emit bin, just check for errors") orelse false) {
obj.emit_bin = .no_emit;
@@ -384,7 +337,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("headers-obj", "Build JavaScriptCore headers");
- var headers_obj: *std.build.LibExeObjStep = b.addObject("headers", "src/bindgen.zig");
+ var headers_obj = b.addObject(.{
+ .name = "headers",
+ .root_source_file = FileSource.relative("src/bindgen.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
var headers_build_options = default_build_options;
@@ -395,7 +353,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const wasm = b.step("bun-wasm", "Build WASM");
- var wasm_step: *std.build.LibExeObjStep = b.addStaticLibrary("bun-wasm", "src/main_wasm.zig");
+ var wasm_step = b.addStaticLibrary(.{
+ .name = "bun-wasm",
+ .root_source_file = FileSource.relative("src/main_wasm.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer wasm.dependOn(&wasm_step.step);
wasm_step.strip = false;
// wasm_step.link_function_sections = true;
@@ -406,7 +369,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("httpbench-obj", "Build HTTPBench tool (object files)");
- var headers_obj: *std.build.LibExeObjStep = b.addObject("httpbench", "misctools/http_bench.zig");
+ var headers_obj = b.addObject(.{
+ .name = "httpbench",
+ .root_source_file = FileSource.relative("misctools/http_bench.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -414,7 +382,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("machbench-obj", "Build Machbench tool (object files)");
- var headers_obj: *std.build.LibExeObjStep = b.addObject("machbench", "misctools/machbench.zig");
+ var headers_obj = b.addObject(.{
+ .name = "machbench",
+ .root_source_file = FileSource.relative("misctools/machbench.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -422,7 +395,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("fetch-obj", "Build fetch (object files)");
- var headers_obj: *std.build.LibExeObjStep = b.addObject("fetch", "misctools/fetch.zig");
+ var headers_obj = b.addObject(.{
+ .name = "fetch",
+ .root_source_file = FileSource.relative("misctools/fetch.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -430,7 +408,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("string-bench", "Build string bench");
- var headers_obj: *std.build.LibExeObjStep = b.addExecutable("string-bench", "src/bench/string-handling.zig");
+ var headers_obj = b.addExecutable(.{
+ .name = "string-bench",
+ .root_source_file = FileSource.relative("src/bench/string-handling.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -438,7 +421,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("sha-bench-obj", "Build sha bench");
- var headers_obj: *std.build.LibExeObjStep = b.addObject("sha", "src/sha.zig");
+ var headers_obj = b.addObject(.{
+ .name = "sha",
+ .root_source_file = FileSource.relative("src/sha.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -446,7 +434,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("vlq-bench", "Build vlq bench");
- var headers_obj: *std.build.LibExeObjStep = b.addExecutable("vlq-bench", "src/sourcemap/vlq_bench.zig");
+ var headers_obj: *CompileStep = b.addExecutable(.{
+ .name = "vlq-bench",
+ .root_source_file = FileSource.relative("src/sourcemap/vlq_bench.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -454,7 +447,12 @@ pub fn build(b: *std.build.Builder) !void {
{
const headers_step = b.step("tgz-obj", "Build tgz (object files)");
- var headers_obj: *std.build.LibExeObjStep = b.addObject("tgz", "misctools/tgz.zig");
+ var headers_obj: *CompileStep = b.addObject(.{
+ .name = "tgz",
+ .root_source_file = FileSource.relative("misctools/tgz.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
defer headers_step.dependOn(&headers_obj.step);
try configureObjectStep(b, headers_obj, @TypeOf(target), target, obj.main_pkg_path.?);
headers_obj.addOptions("build_options", default_build_options.step(b));
@@ -467,7 +465,10 @@ pub fn build(b: *std.build.Builder) !void {
var test_bin_ = b.option([]const u8, "test-bin", "Emit bin to");
var test_filter = b.option([]const u8, "test-filter", "Filter for test");
- var headers_obj: *std.build.LibExeObjStep = b.addTest(test_file orelse "src/main.zig");
+ var headers_obj: *CompileStep = b.addTest(.{
+ .root_source_file = FileSource.relative(test_file orelse "src/main.zig"),
+ .target = target,
+ });
headers_obj.setFilter(test_filter);
if (test_bin_) |test_bin| {
headers_obj.name = std.fs.path.basename(test_bin);
@@ -486,28 +487,33 @@ pub fn build(b: *std.build.Builder) !void {
headers_obj.addOptions("build_options", default_build_options.step(b));
}
- for (headers_obj.packages.items) |pkg_| {
- const pkg: std.build.Pkg = pkg_;
- if (std.mem.eql(u8, pkg.name, "clap")) continue;
- var test_ = b.addTestSource(pkg.source);
-
- test_.setMainPkgPath(obj.main_pkg_path.?);
- test_.setTarget(target);
- try configureObjectStep(b, test_, @TypeOf(target), target, obj.main_pkg_path.?);
- try linkObjectFiles(b, test_, target);
- test_.addOptions("build_options", default_build_options.step(b));
-
- if (pkg.dependencies) |children| {
- test_.packages = std.ArrayList(std.build.Pkg).init(b.allocator);
- try test_.packages.appendSlice(children);
- }
-
- var before = b.addLog("\x1b[" ++ color_map.get("magenta").? ++ "\x1b[" ++ color_map.get("b").? ++ "[{s} tests]" ++ "\x1b[" ++ color_map.get("d").? ++ " ----\n\n" ++ "\x1b[0m", .{pkg.name});
- var after = b.addLog("\x1b[" ++ color_map.get("d").? ++ "–––---\n\n" ++ "\x1b[0m", .{});
- headers_step.dependOn(&before.step);
- headers_step.dependOn(&test_.step);
- headers_step.dependOn(&after.step);
- }
+ // var iter = headers_obj.modules.iterator();
+ // while (iter.next()) |item| {
+ // const module = @ptrCast(*Module, item.value_ptr);
+ // }
+ // // while (headers_obj.modules.)
+ // for (headers_obj.packages.items) |pkg_| {
+ // const pkg: std.build.Pkg = pkg_;
+ // if (std.mem.eql(u8, pkg.name, "clap")) continue;
+ // var test_ = b.addTestSource(pkg.source);
+
+ // b
+ // .test_.setMainPkgPath(obj.main_pkg_path.?);
+ // try configureObjectStep(b, test_, @TypeOf(target), target, obj.main_pkg_path.?);
+ // try linkObjectFiles(b, test_, target);
+ // test_.addOptions("build_options", default_build_options.step(b));
+
+ // if (pkg.dependencies) |children| {
+ // test_.packages = std.ArrayList(std.build.Pkg).init(b.allocator);
+ // try test_.packages.appendSlice(children);
+ // }
+
+ // var before = b.addLog("\x1b[" ++ color_map.get("magenta").? ++ "\x1b[" ++ color_map.get("b").? ++ "[{s} tests]" ++ "\x1b[" ++ color_map.get("d").? ++ " ----\n\n" ++ "\x1b[0m", .{pkg.name});
+ // var after = b.addLog("\x1b[" ++ color_map.get("d").? ++ "–––---\n\n" ++ "\x1b[0m", .{});
+ // headers_step.dependOn(&before.step);
+ // headers_step.dependOn(&test_.step);
+ // headers_step.dependOn(&after.step);
+ // }
}
if (obj.emit_bin != .no_emit)
obj.setOutputDir(output_dir);
@@ -520,7 +526,7 @@ pub var original_make_fn: ?*const fn (step: *std.build.Step) anyerror!void = nul
// we cannot use this with debugging
// so I am leaving this here for now, with the eventual intent to switch to std.build.Builder
// but it is dead code
-pub fn linkObjectFiles(b: *std.build.Builder, obj: *std.build.LibExeObjStep, target: anytype) !void {
+pub fn linkObjectFiles(b: *Build, obj: *CompileStep, target: anytype) !void {
if (target.getOsTag() == .freestanding)
return;
var dirs_to_search = std.BoundedArray([]const u8, 32).init(0) catch unreachable;
@@ -577,22 +583,22 @@ pub fn linkObjectFiles(b: *std.build.Builder, obj: *std.build.LibExeObjStep, tar
}
}
-pub fn configureObjectStep(b: *std.build.Builder, obj: *std.build.LibExeObjStep, comptime Target: type, target: Target, main_pkg_path: []const u8) !void {
+pub fn configureObjectStep(b: *std.build.Builder, obj: *CompileStep, comptime Target: type, target: Target, main_pkg_path: []const u8) !void {
obj.setMainPkgPath(main_pkg_path);
- obj.setTarget(target);
- try addInternalPackages(obj, std.heap.page_allocator, b.zig_exe, target);
+ // obj.setTarget(target);
+ try addInternalPackages(b, obj, std.heap.page_allocator, b.zig_exe, target);
if (target.getOsTag() != .freestanding)
addPicoHTTP(obj, false);
obj.strip = false;
obj.setOutputDir(output_dir);
- obj.setBuildMode(mode);
- obj.bundle_compiler_rt = true;
+ // obj.setBuildMode(optimize);
+ obj.bundle_compiler_rt = false;
if (target.getOsTag() != .freestanding) obj.linkLibC();
- if (target.getOsTag() != .freestanding) obj.bundle_compiler_rt = true;
+ if (target.getOsTag() != .freestanding) obj.bundle_compiler_rt = false;
if (target.getOsTag() == .linux) {
// obj.want_lto = tar;
diff --git a/misctools/fetch.zig b/misctools/fetch.zig
index 74622b0ef..cdefd29d4 100644
--- a/misctools/fetch.zig
+++ b/misctools/fetch.zig
@@ -108,7 +108,7 @@ pub const Arguments = struct {
if (args.option("--file")) |file_path| {
if (file_path.len > 0) {
var cwd = try std.process.getCwd(&cwd_buf);
- var parts = [_]string{std.mem.span(file_path)};
+ var parts = [_]string{file_path};
var absolute_path = path_handler.joinAbsStringBuf(cwd, &file_path_buf, &parts, .auto);
file_path_buf[absolute_path.len] = 0;
file_path_buf[absolute_path.len + 1] = 0;
@@ -132,7 +132,7 @@ pub const Arguments = struct {
var raw_arg_i: usize = 0;
while (raw_arg_i < raw_args.items.len) : (raw_arg_i += 1) {
const arg = raw_args.items[raw_arg_i];
- if (MethodNames.get(std.mem.span(arg))) |method_| {
+ if (MethodNames.get(arg[0..])) |method_| {
method = method_;
_ = raw_args.swapRemove(raw_arg_i);
}
diff --git a/misctools/http_bench.zig b/misctools/http_bench.zig
index 84fa29600..5e12f0157 100644
--- a/misctools/http_bench.zig
+++ b/misctools/http_bench.zig
@@ -112,7 +112,7 @@ pub const Arguments = struct {
if (args.option("--file")) |file_path| {
if (file_path.len > 0) {
var cwd = try std.process.getCwd(&cwd_buf);
- var parts = [_]string{std.mem.span(file_path)};
+ var parts = [_]string{file_path};
var absolute_path = path_handler.joinAbsStringBuf(cwd, &file_path_buf, &parts, .auto);
file_path_buf[absolute_path.len] = 0;
file_path_buf[absolute_path.len + 1] = 0;
@@ -136,7 +136,7 @@ pub const Arguments = struct {
var raw_arg_i: usize = 0;
while (raw_arg_i < raw_args.items.len) : (raw_arg_i += 1) {
const arg = raw_args.items[raw_arg_i];
- if (MethodNames.get(std.mem.span(arg))) |method_| {
+ if (MethodNames.get(arg[0..])) |method_| {
method = method_;
_ = raw_args.swapRemove(raw_arg_i);
}
diff --git a/misctools/readlink-getfd.zig b/misctools/readlink-getfd.zig
index 94713562d..79c1a7e34 100644
--- a/misctools/readlink-getfd.zig
+++ b/misctools/readlink-getfd.zig
@@ -12,7 +12,7 @@ const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
-// zig build-exe -Drelease-fast --main-pkg-path ../ ./readlink-getfd.zig
+// zig build-exe -Doptimize=ReleaseFast --main-pkg-path ../ ./readlink-getfd.zig
pub fn main() anyerror!void {
var stdout_ = std.io.getStdOut();
var stderr_ = std.io.getStdErr();
@@ -24,7 +24,7 @@ pub fn main() anyerror!void {
var fixed_buffer = std.heap.FixedBufferAllocator.init(&args_buffer);
var allocator = fixed_buffer.allocator();
- var args = std.mem.span(try std.process.argsAlloc(allocator));
+ var args = std.mem.bytesAsSlice([]u8, try std.process.argsAlloc(allocator));
const to_resolve = args[args.len - 1];
const cwd = try std.process.getCwdAlloc(allocator);
@@ -33,7 +33,7 @@ pub fn main() anyerror!void {
var j: usize = 0;
while (j < 1000) : (j += 1) {
- var parts = [1][]const u8{std.mem.span(to_resolve)};
+ var parts = [1][]const u8{to_resolve};
var joined_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var joined = path_handler.joinAbsStringBuf(
cwd,
diff --git a/misctools/readlink-realpath.zig b/misctools/readlink-realpath.zig
index 1e9c7e3d1..d466c8fd3 100644
--- a/misctools/readlink-realpath.zig
+++ b/misctools/readlink-realpath.zig
@@ -12,7 +12,7 @@ const stringZ = bun.stringZ;
const default_allocator = bun.default_allocator;
const C = bun.C;
-// zig build-exe -Drelease-fast --main-pkg-path ../ ./readlink-getfd.zig
+// zig build-exe -Doptimize=ReleaseFast --main-pkg-path ../ ./readlink-getfd.zig
pub fn main() anyerror!void {
var stdout_ = std.io.getStdOut();
var stderr_ = std.io.getStdErr();
@@ -24,7 +24,7 @@ pub fn main() anyerror!void {
var fixed_buffer = std.heap.FixedBufferAllocator.init(&args_buffer);
var allocator = fixed_buffer.allocator();
- var args = std.mem.span(try std.process.argsAlloc(allocator));
+ var args = std.mem.bytesAsSlice([]u8, try std.process.argsAlloc(allocator));
const to_resolve = args[args.len - 1];
var out_buffer: [bun.MAX_PATH_BYTES]u8 = undefined;
diff --git a/misctools/tgz.zig b/misctools/tgz.zig
index 214ff1bdf..a5887c77d 100644
--- a/misctools/tgz.zig
+++ b/misctools/tgz.zig
@@ -23,8 +23,8 @@ const RecognizedExtensions = std.ComptimeStringMap(void, .{
var buf: [32 * 1024 * 1024]u8 = undefined;
-// zig build-exe -Drelease-fast --main-pkg-path ../ ./tgz.zig ../src/deps/zlib/libz.a ../src/deps/libarchive.a -lc -liconv
-// zig build-exe -Drelease-fast --main-pkg-path ../ ./tgz.zig ../src/deps/zlib/libz.a ../src/deps/libarchive.a -lc -liconv
+// zig build-exe -Doptimize=ReleaseFast --main-pkg-path ../ ./tgz.zig ../src/deps/zlib/libz.a ../src/deps/libarchive.a -lc -liconv
+// zig build-exe -Doptimize=ReleaseFast --main-pkg-path ../ ./tgz.zig ../src/deps/zlib/libz.a ../src/deps/libarchive.a -lc -liconv
pub fn main() anyerror!void {
var stdout_ = std.io.getStdOut();
var stderr_ = std.io.getStdErr();
@@ -38,13 +38,13 @@ pub fn main() anyerror!void {
}
var tarball_path_buf: [bun.MAX_PATH_BYTES]u8 = undefined;
- var basename = std.fs.path.basename(std.mem.span(args[args.len - 1]));
+ var basename = std.fs.path.basename(bun.asByteSlice(args[args.len - 1]));
while (RecognizedExtensions.has(std.fs.path.extension(basename))) {
basename = basename[0 .. basename.len - std.fs.path.extension(basename).len];
}
var parts = [_][]const u8{
- std.mem.span(args[args.len - 1]),
+ bun.asByteSlice(args[args.len - 1]),
};
const tarball_path = path_handler.joinAbsStringBuf(try std.process.getCwdAlloc(std.heap.c_allocator), &tarball_path_buf, &parts, .auto);
diff --git a/src/allocators.zig b/src/allocators.zig
index 813875bf6..f7d05b849 100644
--- a/src/allocators.zig
+++ b/src/allocators.zig
@@ -349,7 +349,7 @@ pub fn BSSStringList(comptime _count: usize, comptime _item_length: usize) type
self.mutex.lock();
defer self.mutex.unlock();
- for (_value) |c, i| {
+ for (_value, 0..) |c, i| {
lowercase_append_buf[i] = std.ascii.toLower(c);
}
var slice = lowercase_append_buf[0.._value.len];
diff --git a/src/analytics/analytics_thread.zig b/src/analytics/analytics_thread.zig
index f4c799849..06b882901 100644
--- a/src/analytics/analytics_thread.zig
+++ b/src/analytics/analytics_thread.zig
@@ -261,13 +261,13 @@ pub const GenerateHeader = struct {
pub const GeneratePlatform = struct {
var osversion_name: [32]u8 = undefined;
pub fn forMac() Analytics.Platform {
- std.mem.set(u8, std.mem.span(&osversion_name), 0);
+ @memset(&osversion_name, 0, osversion_name.len);
var platform = Analytics.Platform{ .os = Analytics.OperatingSystem.macos, .version = &[_]u8{}, .arch = platform_arch };
var len = osversion_name.len - 1;
if (std.c.sysctlbyname("kern.osrelease", &osversion_name, &len, null, 0) == -1) return platform;
- platform.version = std.mem.span(std.mem.sliceTo(std.mem.span(&osversion_name), @as(u8, 0)));
+ platform.version = bun.sliceTo(&osversion_name, 0);
return platform;
}
@@ -292,7 +292,7 @@ pub const GenerateHeader = struct {
@compileError("This function is only implemented on Linux");
}
_ = forOS();
- const release = std.mem.span(&linux_os_name.release);
+ const release = bun.sliceTo(&linux_os_name.release, 0);
const sliced_string = Semver.SlicedString.init(release, release);
const result = Semver.Version.parse(sliced_string, bun.default_allocator);
// we only care about major, minor, patch so we don't care about the string
@@ -304,8 +304,8 @@ pub const GenerateHeader = struct {
_ = std.c.uname(&linux_os_name);
- const release = std.mem.span(&linux_os_name.release);
- const version = std.mem.sliceTo(std.mem.span(&linux_os_name.version).ptr, @as(u8, 0));
+ const release = bun.sliceTo(&linux_os_name.release, 0);
+ const version = std.mem.sliceTo(&linux_os_name.version, @as(u8, 0));
// Linux DESKTOP-P4LCIEM 5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
if (std.mem.indexOf(u8, release, "microsoft") != null) {
return Analytics.Platform{ .os = Analytics.OperatingSystem.wsl, .version = version, .arch = platform_arch };
diff --git a/src/baby_list.zig b/src/baby_list.zig
index 99844d72e..0df33b2dc 100644
--- a/src/baby_list.zig
+++ b/src/baby_list.zig
@@ -184,13 +184,6 @@ pub fn BabyList(comptime Type: type) type {
}
}
- if (comptime Environment.allow_assert) {
- // sanity check that encoding produced a consistent result
- var allocated = try strings.toUTF8Alloc(allocator, str);
- defer allocator.free(allocated);
- const encoded = this.ptr[initial..this.len];
- std.testing.expectEqualStrings(allocated, encoded) catch unreachable;
- }
return this.len - initial;
}
};
diff --git a/src/base64/base64.zig b/src/base64/base64.zig
index 8173767bc..daf5b228e 100644
--- a/src/base64/base64.zig
+++ b/src/base64/base64.zig
@@ -37,7 +37,6 @@ pub fn decodeURLSafe(destination: []u8, source: []const u8) DecodeResult {
pub fn encode(destination: []u8, source: []const u8) usize {
return zig_base64.standard.Encoder.encode(destination, source).len;
-
}
pub fn decodeLenUpperBound(len: usize) usize {
@@ -59,7 +58,6 @@ pub fn encodeLen(source: anytype) usize {
return zig_base64.standard.Encoder.calcSize(source.len);
}
-
pub const urlsafe = zig_base64.Base64DecoderWithIgnore.init(
zig_base64.url_safe_alphabet_chars,
null,
@@ -219,7 +217,7 @@ const zig_base64 = struct {
};
var char_in_alphabet = [_]bool{false} ** 256;
- for (alphabet_chars) |c, i| {
+ for (alphabet_chars, 0..) |c, i| {
assert(!char_in_alphabet[c]);
assert(pad_char == null or c != pad_char.?);
@@ -264,7 +262,7 @@ const zig_base64 = struct {
var acc_len: u4 = 0;
var dest_idx: usize = 0;
var leftover_idx: ?usize = null;
- for (source) |c, src_idx| {
+ for (source, 0..) |c, src_idx| {
const d = decoder.char_to_index[c];
if (d == invalid_char) {
if (decoder.pad_char == null or c != decoder.pad_char.?) return error.InvalidCharacter;
@@ -342,7 +340,7 @@ const zig_base64 = struct {
wrote.* = leftover_idx orelse dest_idx;
}
- for (source) |c, src_idx| {
+ for (source, 0..) |c, src_idx| {
if (decoder_with_ignore.char_is_ignored[c]) continue;
const d = decoder.char_to_index[c];
if (d == Base64Decoder.invalid_char) {
diff --git a/src/bindgen.zig b/src/bindgen.zig
index 0880799d7..252ce4e9e 100644
--- a/src/bindgen.zig
+++ b/src/bindgen.zig
@@ -5,8 +5,3 @@ pub export fn PLCrashReportHandler(_: ?*anyopaque) void {}
pub export fn mkdirp(_: ?*anyopaque) void {}
pub const build_options = @import("build_options");
pub const bun = @import("./bun.zig");
-
-comptime {
- if (!bun.Environment.isRelease)
- _ = @import("compiler_rt");
-}
diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig
index 78927f85a..fd91ef897 100644
--- a/src/bun.js/api/bun.zig
+++ b/src/bun.js/api/bun.zig
@@ -456,7 +456,7 @@ pub fn getArgv(
var allocator = argv_list.get();
var argv = allocator.alloc(ZigString, std.os.argv.len) catch unreachable;
defer if (argv.len > 128) allocator.free(argv);
- for (std.os.argv) |arg, i| {
+ for (std.os.argv, 0..) |arg, i| {
argv[i] = ZigString.init(std.mem.span(arg));
}
@@ -504,7 +504,7 @@ pub fn getFilePath(ctx: js.JSContextRef, arguments: []const js.JSValueRef, buf:
var temp_strings_list: [32]string = undefined;
var temp_strings_list_len: u8 = 0;
defer {
- for (temp_strings_list[0..temp_strings_list_len]) |_, i| {
+ for (temp_strings_list[0..temp_strings_list_len], 0..) |_, i| {
temp_strings_list[i] = "";
}
}
@@ -680,7 +680,7 @@ pub fn getRouteFiles(
const router = &VirtualMachine.get().bundler.router.?;
const list = router.getPublicPaths() catch unreachable;
- for (routes_list_strings[0..@min(list.len, routes_list_strings.len)]) |_, i| {
+ for (routes_list_strings[0..@min(list.len, routes_list_strings.len)], 0..) |_, i| {
routes_list_strings[i] = ZigString.init(list[i]);
}
@@ -701,7 +701,7 @@ pub fn getRouteNames(
const router = &VirtualMachine.get().bundler.router.?;
const list = router.getNames() catch unreachable;
- for (routes_list_strings[0..@min(list.len, routes_list_strings.len)]) |_, i| {
+ for (routes_list_strings[0..@min(list.len, routes_list_strings.len)], 0..) |_, i| {
routes_list_strings[i] = ZigString.init(list[i]);
}
@@ -1452,7 +1452,7 @@ pub const Crypto = struct {
var all = std.EnumArray(Algorithm, ZigString).initUndefined();
var iter = all.iterator();
while (iter.next()) |entry| {
- entry.value.* = ZigString.init(std.mem.span(@tagName(entry.key)));
+ entry.value.* = ZigString.init(@tagName(entry.key));
}
break :brk all;
};
@@ -1612,7 +1612,7 @@ pub const Crypto = struct {
this: *CryptoHasher,
globalObject: *JSC.JSGlobalObject,
) callconv(.C) JSC.JSValue {
- return ZigString.fromUTF8(std.mem.span(@tagName(this.evp.algorithm))).toValueGC(globalObject);
+ return ZigString.fromUTF8(bun.asByteSlice(@tagName(this.evp.algorithm))).toValueGC(globalObject);
}
pub fn getAlgorithms(
@@ -3976,7 +3976,7 @@ pub const EnvironmentVariables = struct {
var vm = globalObject.bunVM();
const keys = vm.bundler.env.map.map.keys();
const max = @min(names.len, keys.len);
- for (keys[0..max]) |key, i| {
+ for (keys[0..max], 0..) |key, i| {
names[i] = ZigString.initUTF8(key);
}
return keys.len;
diff --git a/src/bun.js/api/bun/socket.zig b/src/bun.js/api/bun/socket.zig
index cf482e242..e18d7f9e5 100644
--- a/src/bun.js/api/bun/socket.zig
+++ b/src/bun.js/api/bun/socket.zig
@@ -578,7 +578,7 @@ pub const Listener = struct {
}
if (ssl) |ssl_config| {
- if (std.mem.span(ssl_config.server_name).len > 0)
+ if (bun.asByteSlice(ssl_config.server_name).len > 0)
uws.us_socket_context_add_server_name(1, socket.socket_context, ssl_config.server_name, ctx_opts, null);
}
diff --git a/src/bun.js/api/bun/spawn.zig b/src/bun.js/api/bun/spawn.zig
index b71e49dbc..8f52109f7 100644
--- a/src/bun.js/api/bun/spawn.zig
+++ b/src/bun.js/api/bun/spawn.zig
@@ -207,7 +207,9 @@ pub const PosixSpawn = struct {
);
if (comptime bun.Environment.allow_assert)
JSC.Node.Syscall.syslog("posix_spawn({s}) = {d} ({d})", .{
- path, rc, pid,
+ path,
+ rc,
+ pid,
});
if (comptime bun.Environment.isLinux) {
diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig
index 614bff0ad..bb31f3dff 100644
--- a/src/bun.js/api/bun/subprocess.zig
+++ b/src/bun.js/api/bun/subprocess.zig
@@ -1119,8 +1119,9 @@ pub const Subprocess = struct {
};
if (key.eqlComptime("PATH")) {
- PATH = bun.span(line["PATH=".len..]);
+ PATH = bun.asByteSlice(line["PATH=".len..]);
}
+
env_array.append(allocator, line) catch {
globalThis.throw("out of memory", .{});
return .zero;
diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig
index 2e493cebe..89192dc85 100644
--- a/src/bun.js/api/ffi.zig
+++ b/src/bun.js/api/ffi.zig
@@ -217,7 +217,7 @@ pub const FFI = struct {
}
JSC.markBinding(@src());
var zig_strings = allocator.alloc(ZigString, symbols.count()) catch unreachable;
- for (symbols.values()) |*function, i| {
+ for (symbols.values(), 0..) |*function, i| {
var arraylist = std.ArrayList(u8).init(allocator);
var writer = arraylist.writer();
function.printSourceCode(&writer) catch {
@@ -330,9 +330,9 @@ pub const FFI = struct {
// optional if the user passed "ptr"
if (function.symbol_from_dynamic_library == null) {
var resolved_symbol = dylib.lookup(*anyopaque, function_name) orelse {
- const ret = JSC.toInvalidArguments("Symbol \"{s}\" not found in \"{s}\"", .{ std.mem.span(function_name), name_slice.slice() }, global);
+ const ret = JSC.toInvalidArguments("Symbol \"{s}\" not found in \"{s}\"", .{ bun.asByteSlice(function_name), name_slice.slice() }, global);
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
symbols.clearAndFree(allocator);
@@ -345,12 +345,12 @@ pub const FFI = struct {
function.compile(allocator) catch |err| {
const ret = JSC.toInvalidArguments("{s} when compiling symbol \"{s}\" in \"{s}\"", .{
- std.mem.span(@errorName(err)),
- std.mem.span(function_name),
+ bun.asByteSlice(@errorName(err)),
+ bun.asByteSlice(function_name),
name_slice.slice(),
}, global);
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
symbols.clearAndFree(allocator);
@@ -360,7 +360,7 @@ pub const FFI = struct {
switch (function.step) {
.failed => |err| {
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
@@ -372,7 +372,7 @@ pub const FFI = struct {
},
.pending => {
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
symbols.clearAndFree(allocator);
@@ -380,7 +380,7 @@ pub const FFI = struct {
return ZigString.init("Failed to compile (nothing happend!)").toErrorInstance(global);
},
.compiled => |*compiled| {
- const str = ZigString.init(std.mem.span(function_name));
+ const str = ZigString.init(bun.asByteSlice(function_name));
const cb = JSC.NewRuntimeFunction(
global,
&str,
@@ -433,9 +433,9 @@ pub const FFI = struct {
const function_name = function.base_name.?;
if (function.symbol_from_dynamic_library == null) {
- const ret = JSC.toInvalidArguments("Symbol for \"{s}\" not found", .{std.mem.span(function_name)}, global);
+ const ret = JSC.toInvalidArguments("Symbol for \"{s}\" not found", .{bun.asByteSlice(function_name)}, global);
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
symbols.clearAndFree(allocator);
@@ -444,11 +444,11 @@ pub const FFI = struct {
function.compile(allocator) catch |err| {
const ret = JSC.toInvalidArguments("{s} when compiling symbol \"{s}\"", .{
- std.mem.span(@errorName(err)),
- std.mem.span(function_name),
+ bun.asByteSlice(@errorName(err)),
+ bun.asByteSlice(function_name),
}, global);
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
symbols.clearAndFree(allocator);
@@ -457,7 +457,7 @@ pub const FFI = struct {
switch (function.step) {
.failed => |err| {
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
@@ -468,14 +468,14 @@ pub const FFI = struct {
},
.pending => {
for (symbols.values()) |*value| {
- allocator.free(bun.constStrToU8(std.mem.span(value.base_name.?)));
+ allocator.free(bun.constStrToU8(bun.asByteSlice(value.base_name.?)));
value.arg_types.clearAndFree(allocator);
}
symbols.clearAndFree(allocator);
return ZigString.static("Failed to compile (nothing happend!)").toErrorInstance(global);
},
.compiled => |*compiled| {
- const name = &ZigString.init(std.mem.span(function_name));
+ const name = &ZigString.init(bun.asByteSlice(function_name));
const cb = JSC.NewRuntimeFunction(
global,
@@ -632,7 +632,7 @@ pub const FFI = struct {
}
function.base_name = try prop.toOwnedSliceZ(allocator);
- symbols.putAssumeCapacity(std.mem.span(function.base_name.?), function);
+ symbols.putAssumeCapacity(bun.asByteSlice(function.base_name.?), function);
}
return null;
@@ -656,8 +656,8 @@ pub const FFI = struct {
JSC.markBinding(@src());
if (val.base_name) |base_name| {
- if (std.mem.span(base_name).len > 0) {
- allocator.free(bun.constStrToU8(std.mem.span(base_name)));
+ if (bun.asByteSlice(base_name).len > 0) {
+ allocator.free(bun.constStrToU8(bun.asByteSlice(base_name)));
}
}
@@ -1058,7 +1058,7 @@ pub const FFI = struct {
}
if (comptime Environment.isRelease) {
- try writer.writeAll(std.mem.span(FFI_HEADER));
+ try writer.writeAll(bun.asByteSlice(FFI_HEADER));
} else {
try writer.writeAll(ffiHeader());
}
@@ -1067,10 +1067,10 @@ pub const FFI = struct {
try writer.writeAll("/* --- The Function To Call */\n");
try this.return_type.typename(writer);
try writer.writeAll(" ");
- try writer.writeAll(std.mem.span(this.base_name.?));
+ try writer.writeAll(bun.asByteSlice(this.base_name.?));
try writer.writeAll("(");
var first = true;
- for (this.arg_types.items) |arg, i| {
+ for (this.arg_types.items, 0..) |arg, i| {
if (!first) {
try writer.writeAll(", ");
}
@@ -1092,7 +1092,7 @@ pub const FFI = struct {
\\ LOAD_ARGUMENTS_FROM_CALL_FRAME;
\\
);
- for (this.arg_types.items) |arg, i| {
+ for (this.arg_types.items, 0..) |arg, i| {
if (arg.needsACastInC()) {
if (i < this.arg_types.items.len - 1) {
try writer.print(
@@ -1152,10 +1152,10 @@ pub const FFI = struct {
try this.return_type.typename(writer);
try writer.writeAll(" return_value = ");
}
- try writer.print("{s}(", .{std.mem.span(this.base_name.?)});
+ try writer.print("{s}(", .{bun.asByteSlice(this.base_name.?)});
first = true;
arg_buf[0..3].* = "arg".*;
- for (this.arg_types.items) |arg, i| {
+ for (this.arg_types.items, 0..) |arg, i| {
if (!first) {
try writer.writeAll(", ");
}
@@ -1229,7 +1229,7 @@ pub const FFI = struct {
}
if (comptime Environment.isRelease) {
- try writer.writeAll(std.mem.span(FFI_HEADER));
+ try writer.writeAll(bun.asByteSlice(FFI_HEADER));
} else {
try writer.writeAll(ffiHeader());
}
@@ -1241,7 +1241,7 @@ pub const FFI = struct {
try writer.writeAll(" my_callback_function");
try writer.writeAll("(");
var first = true;
- for (this.arg_types.items) |arg, i| {
+ for (this.arg_types.items, 0..) |arg, i| {
if (!first) {
try writer.writeAll(", ");
}
@@ -1256,7 +1256,7 @@ pub const FFI = struct {
try writer.writeAll(" my_callback_function");
try writer.writeAll("(");
- for (this.arg_types.items) |arg, i| {
+ for (this.arg_types.items, 0..) |arg, i| {
if (!first) {
try writer.writeAll(", ");
}
@@ -1279,7 +1279,7 @@ pub const FFI = struct {
try writer.print(" ZIG_REPR_TYPE arguments[{d}];\n", .{this.arg_types.items.len});
arg_buf[0.."arg".len].* = "arg".*;
- for (this.arg_types.items) |arg, i| {
+ for (this.arg_types.items, 0..) |arg, i| {
const printed = std.fmt.bufPrintIntToSlice(arg_buf["arg".len..], i, 10, .lower, .{});
const arg_name = arg_buf[0 .. "arg".len + printed.len];
try writer.print("arguments[{d}] = {any}.asZigRepr;\n", .{ i, arg.toJS(arg_name) });
@@ -1424,7 +1424,7 @@ pub const FFI = struct {
};
pub const map_to_js_object = brk: {
var count: usize = 2;
- for (map) |item, i| {
+ for (map, 0..) |item, i| {
var fmt = EnumMapFormatter{ .name = item.@"0", .entry = item.@"1" };
count += std.fmt.count("{}", .{fmt});
count += @boolToInt(i > 0);
@@ -1434,7 +1434,7 @@ pub const FFI = struct {
buf[0] = '{';
buf[buf.len - 1] = '}';
var end: usize = 1;
- for (map) |item, i| {
+ for (map, 0..) |item, i| {
var fmt = EnumMapFormatter{ .name = item.@"0", .entry = item.@"1" };
if (i > 0) {
buf[end] = ',';
@@ -1470,7 +1470,7 @@ pub const FFI = struct {
},
.char, .int8_t, .uint8_t, .int16_t, .uint16_t, .int32_t, .uint32_t => {
if (self.exact)
- try writer.print("({s})", .{std.mem.span(@tagName(self.tag))});
+ try writer.print("({s})", .{bun.asByteSlice(@tagName(self.tag))});
try writer.writeAll("JSVALUE_TO_INT32(");
},
diff --git a/src/bun.js/api/filesystem_router.zig b/src/bun.js/api/filesystem_router.zig
index 7141b5f5e..6e5465055 100644
--- a/src/bun.js/api/filesystem_router.zig
+++ b/src/bun.js/api/filesystem_router.zig
@@ -424,7 +424,7 @@ pub const FileSystemRouter = struct {
var name_strings = bun.default_allocator.alloc(ZigString, names.len * 2) catch unreachable;
defer bun.default_allocator.free(name_strings);
var paths_strings = name_strings[names.len..];
- for (names) |name, i| {
+ for (names, 0..) |name, i| {
name_strings[i] = ZigString.init(name).withEncoding();
paths_strings[i] = ZigString.init(paths[i]).withEncoding();
}
@@ -610,7 +610,7 @@ pub const MatchedRoute = struct {
std.debug.assert(entry.values.len > 0);
if (entry.values.len > 1) {
var values = query_string_value_refs_buf[0..entry.values.len];
- for (entry.values) |value, i| {
+ for (entry.values, 0..) |value, i| {
values[i] = ZigString.init(value).withEncoding();
}
obj.putRecord(global, &str, values.ptr, values.len);
diff --git a/src/bun.js/api/transpiler.zig b/src/bun.js/api/transpiler.zig
index eb070b6bc..8562a3204 100644
--- a/src/bun.js/api/transpiler.zig
+++ b/src/bun.js/api/transpiler.zig
@@ -203,7 +203,7 @@ pub const TransformTask = struct {
this.global,
bun.default_allocator,
logger.Msg{
- .data = logger.Data{ .text = std.mem.span(@errorName(err)) },
+ .data = logger.Data{ .text = bun.asByteSlice(@errorName(err)) },
},
));
}
diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig
index bdb516836..044a04306 100644
--- a/src/bun.js/base.zig
+++ b/src/bun.js/base.zig
@@ -219,7 +219,7 @@ pub const To = struct {
var zig_strings = allocator.alloc(ZigString, value.len) catch unreachable;
defer if (stack_fallback.fixed_buffer_allocator.end_index >= 511) allocator.free(zig_strings);
- for (value) |path_string, i| {
+ for (value, 0..) |path_string, i| {
if (comptime Type == []const PathString) {
zig_strings[i] = ZigString.init(path_string.slice());
} else {
@@ -645,7 +645,7 @@ pub const d = struct {
comptime {
var args: string = "";
- for (func.args) |a, i| {
+ for (func.args, 0..) |a, i| {
if (i > 0) {
args = args ++ ", ";
}
@@ -680,7 +680,7 @@ pub const d = struct {
comptime {
var args: string = "";
- for (func.args) |a, i| {
+ for (func.args, 0..) |a, i| {
if (i > 0) {
args = args ++ ", ";
}
@@ -751,7 +751,7 @@ pub const d = struct {
indent += indent_level;
- for (klass.properties) |property, i| {
+ for (klass.properties, 0..) |property, i| {
if (i > 0) {
buf = buf ++ "\n";
}
@@ -761,7 +761,7 @@ pub const d = struct {
buf = buf ++ "\n";
- for (klass.functions) |func, i| {
+ for (klass.functions, 0..) |func, i| {
if (i > 0) {
buf = buf ++ "\n";
}
@@ -773,7 +773,7 @@ pub const d = struct {
);
}
- for (klass.classes) |func, i| {
+ for (klass.classes, 0..) |func, i| {
if (i > 0) {
buf = buf ++ "\n";
}
@@ -822,7 +822,7 @@ pub const d = struct {
);
}
- for (klass.properties) |property, i| {
+ for (klass.properties, 0..) |property, i| {
if (i > 0 or did_print_constructor) {
buf = buf ++ "\n";
}
@@ -832,7 +832,7 @@ pub const d = struct {
buf = buf ++ "\n";
- for (klass.functions) |func, i| {
+ for (klass.functions, 0..) |func, i| {
if (i > 0) {
buf = buf ++ "\n";
}
@@ -1294,7 +1294,7 @@ pub fn NewClassWithInstanceType(
.attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone,
},
);
- for (property_name_literals) |lit, i| {
+ for (property_name_literals, 0..) |lit, i| {
props[i] = brk2: {
var static_prop = JSC.C.JSStaticValue{
.name = lit.ptr[0..lit.len :0],
@@ -1338,7 +1338,7 @@ pub fn NewClassWithInstanceType(
.convertToType = null,
};
var __static_functions: [function_name_literals.len + 1]js.JSStaticFunction = undefined;
- for (__static_functions) |_, i| {
+ for (__static_functions, 0..) |_, i| {
__static_functions[i] = js.JSStaticFunction{
.name = "",
.callAsFunction = null,
@@ -1692,7 +1692,7 @@ pub fn toTypeError(
args: anytype,
ctx: js.JSContextRef,
) JSC.JSValue {
- return toTypeErrorWithCode(std.mem.span(@tagName(code)), fmt, args, ctx);
+ return toTypeErrorWithCode(@tagName(code), fmt, args, ctx);
}
pub fn throwInvalidArguments(
diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig
index 48cbe0887..05684902b 100644
--- a/src/bun.js/bindings/bindings.zig
+++ b/src/bun.js/bindings/bindings.zig
@@ -1677,7 +1677,7 @@ pub fn PromiseCallback(comptime Type: type, comptime CallbackFunction: fn (*Type
arguments_len: usize,
) callconv(.C) JSValue {
return CallbackFunction(@ptrCast(*Type, @alignCast(@alignOf(*Type), ctx.?)), globalThis, arguments[0..arguments_len]) catch |err| brk: {
- break :brk ZigString.init(std.mem.span(@errorName(err))).toErrorInstance(globalThis);
+ break :brk ZigString.init(bun.asByteSlice(@errorName(err))).toErrorInstance(globalThis);
};
}
}.callback;
@@ -2376,7 +2376,7 @@ pub const JSGlobalObject = extern struct {
const names = comptime std.meta.fieldNames(@TypeOf(module));
var export_names: [names.len]ZigString = undefined;
var export_values: [names.len]JSValue = undefined;
- inline for (comptime names) |export_name, i| {
+ inline for (comptime names, 0..) |export_name, i| {
export_names[i] = ZigString.init(export_name);
const function = @field(module, export_name).@"0";
const len = @field(module, export_name).@"1";
diff --git a/src/bun.js/bindings/exports.zig b/src/bun.js/bindings/exports.zig
index f17d7e221..c87a80571 100644
--- a/src/bun.js/bindings/exports.zig
+++ b/src/bun.js/bindings/exports.zig
@@ -481,7 +481,7 @@ pub const ZigStackTrace = extern struct {
var stack_frames = try allocator.alloc(Api.StackFrame, _frames.len);
stack_trace.frames = stack_frames;
- for (_frames) |frame, i| {
+ for (_frames, 0..) |frame, i| {
stack_frames[i] = try frame.toAPI(
root_path,
origin,
@@ -527,7 +527,7 @@ pub const ZigStackTrace = extern struct {
pub fn sourceLineIterator(this: *const ZigStackTrace) SourceLineIterator {
var i: usize = 0;
- for (this.source_lines_numbers[0..this.source_lines_len]) |num, j| {
+ for (this.source_lines_numbers[0..this.source_lines_len], 0..) |num, j| {
if (num > 0) {
i = j;
}
@@ -2125,7 +2125,7 @@ pub const ZigConsoleClient = struct {
timer.id,
});
}
-
+
return;
} else if (jsType != .DOMWrapper) {
if (CAPI.JSObjectGetPrivate(value.asRef())) |private_data_ptr| {
@@ -2607,7 +2607,7 @@ pub const ZigConsoleClient = struct {
const arrayBuffer = value.asArrayBuffer(this.globalThis).?;
const slice = arrayBuffer.byteSlice();
- writer.writeAll(std.mem.span(@tagName(arrayBuffer.typed_array_type)));
+ writer.writeAll(bun.asByteSlice(@tagName(arrayBuffer.typed_array_type)));
writer.print("({d}) [ ", .{arrayBuffer.len});
if (slice.len > 0) {
diff --git a/src/bun.js/bindings/header-gen.zig b/src/bun.js/bindings/header-gen.zig
index 294f0a095..179c884d5 100644
--- a/src/bun.js/bindings/header-gen.zig
+++ b/src/bun.js/bindings/header-gen.zig
@@ -147,7 +147,7 @@ pub const C_Generator = struct {
comptime var nonnull = std.BoundedArray(u8, 32).init(0) catch unreachable;
- inline for (meta.params) |arg, i| {
+ inline for (meta.params, 0..) |arg, i| {
const ArgType = comptime arg.type.?;
switch (comptime @typeInfo(ArgType)) {
@@ -188,7 +188,7 @@ pub const C_Generator = struct {
const nonnull_slice = comptime nonnull.slice();
if (comptime nonnull_slice.len > 0) {
self.write(" __attribute__((nonnull (");
- inline for (comptime nonnull_slice) |i, j| {
+ inline for (comptime nonnull_slice, 0..) |i, j| {
self.write(comptime std.fmt.comptimePrint("{d}", .{i}));
if (j != nonnull_slice.len - 1)
self.write(", ");
@@ -214,7 +214,7 @@ pub const C_Generator = struct {
const func: std.builtin.Type.Fn = @typeInfo(Function).Fn;
self.writeType(func.return_type orelse void);
self.write("(*" ++ name ++ ")(");
- inline for (func.params) |arg, i| {
+ inline for (func.params, 0..) |arg, i| {
self.writeType(arg.type.?);
// if (comptime func.arg_names.len > 0 and func.arg_names.len > i) {
// self.write(comptime arg_names[i]);
@@ -304,7 +304,7 @@ pub const C_Generator = struct {
self.write("enum " ++ name ++ " {\n");
comptime var last = 0;
- inline for (meta.fields) |field, i| {
+ inline for (meta.fields, 0..) |field, i| {
self.write(" " ++ field.name);
// if field value is unexpected/custom, manually define it
@@ -372,7 +372,7 @@ pub const C_Generator = struct {
_ = std.mem.replace(u8, TT.name, ":", "_", &original);
break :brk original;
};
- const formatted_name = comptime std.mem.span(&_formatted_name);
+ const formatted_name = comptime _formatted_name[0..];
if (@hasDecl(TT, "is_pointer") and !TT.is_pointer) {
if (@TypeOf(TT.Type) == type) {
@@ -524,11 +524,11 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
comptime var new_name = std.mem.zeroes([Type.include.len]u8);
comptime {
- _ = std.mem.replace(u8, Type.include, "/", "_", std.mem.span(&new_name));
- _ = std.mem.replace(u8, &new_name, ".", "_", std.mem.span(&new_name));
- _ = std.mem.replace(u8, &new_name, "<", "_", std.mem.span(&new_name));
- _ = std.mem.replace(u8, &new_name, ">", "_", std.mem.span(&new_name));
- _ = std.mem.replace(u8, &new_name, "\"", "_", std.mem.span(&new_name));
+ _ = std.mem.replace(u8, Type.include, "/", "_", &new_name);
+ _ = std.mem.replace(u8, &new_name, ".", "_", &new_name);
+ _ = std.mem.replace(u8, &new_name, "<", "_", &new_name);
+ _ = std.mem.replace(u8, &new_name, ">", "_", &new_name);
+ _ = std.mem.replace(u8, &new_name, "\"", "_", &new_name);
}
file.writeAll("\n#pragma mark - " ++ Type.name ++ "\n\n") catch unreachable;
@@ -797,7 +797,7 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
if (@hasDecl(Type, extern_decl)) {
const normalized_name = comptime brk: {
var _normalized_name: [Type.name.len]u8 = undefined;
- _ = std.mem.replace(u8, Type.name, ":", "_", std.mem.span(&_normalized_name));
+ _ = std.mem.replace(u8, Type.name, ":", "_", &_normalized_name);
break :brk _normalized_name;
};
@@ -808,7 +808,7 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
Type,
comptime std.meta.declarationInfo(Type, extern_decl),
comptime extern_decl,
- comptime std.mem.span(&normalized_name),
+ &normalized_name,
);
}
}
diff --git a/src/bun.js/bindings/headers-cpp.h b/src/bun.js/bindings/headers-cpp.h
index 3c53d5f99..b15dd8ba2 100644
--- a/src/bun.js/bindings/headers-cpp.h
+++ b/src/bun.js/bindings/headers-cpp.h
@@ -1,4 +1,4 @@
-//-- AUTOGENERATED FILE -- 1676922916
+//-- AUTOGENERATED FILE -- 1677221832
// clang-format off
#pragma once
diff --git a/src/bun.js/bindings/headers.h b/src/bun.js/bindings/headers.h
index 6b005216a..79a4ef24b 100644
--- a/src/bun.js/bindings/headers.h
+++ b/src/bun.js/bindings/headers.h
@@ -1,5 +1,5 @@
// clang-format off
-//-- AUTOGENERATED FILE -- 1676922916
+//-- AUTOGENERATED FILE -- 1677221832
#pragma once
#include <stddef.h>
diff --git a/src/bun.js/bindings/shimmer.zig b/src/bun.js/bindings/shimmer.zig
index cde7712c5..a90bfab87 100644
--- a/src/bun.js/bindings/shimmer.zig
+++ b/src/bun.js/bindings/shimmer.zig
@@ -105,7 +105,7 @@ pub fn Shimmer(comptime _namespace: []const u8, comptime _name: []const u8, comp
const FunctionsType = @TypeOf(Functions);
return comptime brk: {
var functions: [std.meta.fieldNames(FunctionsType).len]StaticExport = undefined;
- for (std.meta.fieldNames(FunctionsType)) |fn_name, i| {
+ for (std.meta.fieldNames(FunctionsType), 0..) |fn_name, i| {
const Function = @TypeOf(@field(Functions, fn_name));
if (@typeInfo(Function) != .Fn) {
@compileError("Expected " ++ @typeName(Parent) ++ "." ++ @typeName(Function) ++ " to be a function but received " ++ @tagName(@typeInfo(Function)));
diff --git a/src/bun.js/bindings/sizes.zig b/src/bun.js/bindings/sizes.zig
index b1b9c1679..795159e49 100644
--- a/src/bun.js/bindings/sizes.zig
+++ b/src/bun.js/bindings/sizes.zig
@@ -78,4 +78,4 @@ pub const Bun_CallFrame__argumentCountIncludingThis = 4;
pub const Bun_CallFrame__thisArgument = 5;
pub const Bun_CallFrame__firstArgument = 6;
pub const Bun_CallFrame__size = 8;
-pub const Bun_CallFrame__align = 8; \ No newline at end of file
+pub const Bun_CallFrame__align = 8;
diff --git a/src/bun.js/event_loop.zig b/src/bun.js/event_loop.zig
index 9c2627fda..8dbf5abfd 100644
--- a/src/bun.js/event_loop.zig
+++ b/src/bun.js/event_loop.zig
@@ -173,7 +173,6 @@ pub const AnyTask = struct {
}
};
-
pub const CppTask = opaque {
extern fn Bun__performTask(globalObject: *JSGlobalObject, task: *CppTask) void;
pub fn run(this: *CppTask, global: *JSGlobalObject) void {
diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig
index a5ef4a44a..efa42deb5 100644
--- a/src/bun.js/javascript.zig
+++ b/src/bun.js/javascript.zig
@@ -647,7 +647,7 @@ pub const VirtualMachine = struct {
if (is_bindgen)
return &[_]js.JSClassRef{};
var classes = default_allocator.alloc(js.JSClassRef, GlobalClasses.len) catch return &[_]js.JSClassRef{};
- inline for (GlobalClasses) |Class, i| {
+ inline for (GlobalClasses, 0..) |Class, i| {
classes[i] = Class.get().*;
}
@@ -668,7 +668,7 @@ pub const VirtualMachine = struct {
else
VirtualMachine.get().allocator.alloc(JSC.JSValue, GlobalConstructors.len) catch unreachable;
- inline for (GlobalConstructors) |Class, i| {
+ inline for (GlobalConstructors, 0..) |Class, i| {
var ref = Class.constructor(globalObject.ref()).?;
JSC.C.JSValueProtect(globalObject.ref(), ref);
slice[i] = JSC.JSValue.fromRef(
@@ -779,7 +779,7 @@ pub const VirtualMachine = struct {
}
var global_classes: [GlobalClasses.len]js.JSClassRef = undefined;
- inline for (GlobalClasses) |Class, i| {
+ inline for (GlobalClasses, 0..) |Class, i| {
global_classes[i] = Class.get().*;
}
vm.global = ZigGlobalObject.create(
@@ -1353,7 +1353,7 @@ pub const VirtualMachine = struct {
var errors = errors_stack[0..@min(log.msgs.items.len, errors_stack.len)];
- for (log.msgs.items) |msg, i| {
+ for (log.msgs.items, 0..) |msg, i| {
errors[i] = switch (msg.metadata) {
.build => BuildError.create(globalThis, globalThis.allocator(), msg).?,
.resolve => ResolveError.create(
@@ -1798,7 +1798,7 @@ pub const VirtualMachine = struct {
var frames: []JSC.ZigStackFrame = exception.stack.frames_ptr[0..exception.stack.frames_len];
if (this.hide_bun_stackframes) {
var start_index: ?usize = null;
- for (frames) |frame, i| {
+ for (frames, 0..) |frame, i| {
if (frame.source_url.eqlComptime("bun:wrap") or
frame.function_name.eqlComptime("::bunternal::"))
{
@@ -1859,7 +1859,7 @@ pub const VirtualMachine = struct {
std.mem.set(i32, source_line_numbers, 0);
var lines_ = lines[0..@min(lines.len, source_lines.len)];
- for (lines_) |line, j| {
+ for (lines_, 0..) |line, j| {
source_lines[(lines_.len - 1) - j] = ZigString.init(line);
source_line_numbers[j] = top.position.line - @intCast(i32, j) + 1;
}
@@ -2822,7 +2822,7 @@ pub const HotReloader = struct {
// if a file descriptor is stale, we need to close it
if (event.op.delete and entries_option != null) {
- for (parents) |parent_hash, entry_id| {
+ for (parents, 0..) |parent_hash, entry_id| {
if (parent_hash == id) {
const affected_path = file_paths[entry_id];
const was_deleted = check: {
@@ -2862,7 +2862,7 @@ pub const HotReloader = struct {
const changed_name: []const u8 = if (comptime Environment.isMac)
changed_name_
else
- std.mem.span(changed_name_.?);
+ bun.asByteSlice(changed_name_.?);
if (changed_name.len == 0 or changed_name[0] == '~' or changed_name[0] == '.') continue;
const loader = (bundler.options.loaders.get(Fs.PathName.init(changed_name).ext) orelse .file);
@@ -2877,7 +2877,7 @@ pub const HotReloader = struct {
file_ent.entry.need_stat = true;
path_string = file_ent.entry.abs_path;
file_hash = Watcher.getHash(path_string.slice());
- for (hashes) |hash, entry_id| {
+ for (hashes, 0..) |hash, entry_id| {
if (hash == file_hash) {
if (file_descriptors[entry_id] != 0) {
if (prev_entry_id != entry_id) {
diff --git a/src/bun.js/module_loader.zig b/src/bun.js/module_loader.zig
index 9d674486a..0a7fe2fb6 100644
--- a/src/bun.js/module_loader.zig
+++ b/src/bun.js/module_loader.zig
@@ -236,7 +236,7 @@ pub const ModuleLoader = struct {
outer: for (modules) |module_| {
var module = module_;
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
- for (root_dependency_ids) |dep, dep_i| {
+ for (root_dependency_ids, 0..) |dep, dep_i| {
if (dep != root_dependency_id) continue;
module.resolveError(
this.vm(),
@@ -328,7 +328,7 @@ pub const ModuleLoader = struct {
outer: for (modules) |module_| {
var module = module_;
var tags = module.parse_result.pending_imports.items(.tag);
- for (tags) |tag, tag_i| {
+ for (tags, 0..) |tag, tag_i| {
if (tag == .resolve) {
var esms = module.parse_result.pending_imports.items(.esm);
const esm = esms[tag_i];
@@ -375,7 +375,7 @@ pub const ModuleLoader = struct {
var module = module_;
const record_ids = module.parse_result.pending_imports.items(.import_record_id);
const root_dependency_ids = module.parse_result.pending_imports.items(.root_dependency_id);
- for (root_dependency_ids) |dependency_id, import_id| {
+ for (root_dependency_ids, 0..) |dependency_id, import_id| {
if (resolution_ids[dependency_id] != package_id) continue;
module.downloadError(
this.vm(),
@@ -410,7 +410,7 @@ pub const ModuleLoader = struct {
// var esms = module.parse_result.pending_imports.items(.esm);
// var versions = module.parse_result.pending_imports.items(.dependency);
var done_count: usize = 0;
- for (tags) |tag, tag_i| {
+ for (tags, 0..) |tag, tag_i| {
const root_id = root_dependency_ids[tag_i];
const resolution_ids = pm.lockfile.buffers.resolutions.items;
if (root_id >= resolution_ids.len) continue;
@@ -618,7 +618,7 @@ pub const ModuleLoader = struct {
else => |err| std.fmt.allocPrint(
bun.default_allocator,
"{s} resolving package '{s}' at '{s}'",
- .{ std.mem.span(@errorName(err)), result.name, result.url },
+ .{ bun.asByteSlice(@errorName(err)), result.name, result.url },
),
};
@@ -707,7 +707,7 @@ pub const ModuleLoader = struct {
bun.default_allocator,
"{s} downloading package '{s}@{any}'",
.{
- std.mem.span(@errorName(err)),
+ bun.asByteSlice(@errorName(err)),
result.name,
result.resolution.fmt(vm.packageManager().lockfile.buffers.string_bytes.items),
},
@@ -1559,8 +1559,8 @@ pub const ModuleLoader = struct {
return ResolvedSource{
.allocator = null,
.source_code = ZigString.init(jsc_vm.entry_point.source.contents),
- .specifier = ZigString.init(std.mem.span(JSC.VirtualMachine.main_file_name)),
- .source_url = ZigString.init(std.mem.span(JSC.VirtualMachine.main_file_name)),
+ .specifier = ZigString.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)),
+ .source_url = ZigString.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)),
.hash = 0,
};
}
@@ -1628,8 +1628,8 @@ pub const ModuleLoader = struct {
return ResolvedSource{
.allocator = null,
.source_code = ZigString.init(jsc_vm.allocator.dupe(u8, printer.ctx.written) catch unreachable),
- .specifier = ZigString.init(std.mem.span(JSC.VirtualMachine.main_file_name)),
- .source_url = ZigString.init(std.mem.span(JSC.VirtualMachine.main_file_name)),
+ .specifier = ZigString.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)),
+ .source_url = ZigString.init(bun.asByteSlice(JSC.VirtualMachine.main_file_name)),
.hash = 0,
};
},
diff --git a/src/bun.js/node/node_os.zig b/src/bun.js/node/node_os.zig
index 3a8f5a55b..ffe35ecd0 100644
--- a/src/bun.js/node/node_os.zig
+++ b/src/bun.js/node/node_os.zig
@@ -47,8 +47,8 @@ pub const Os = struct {
return module;
}
- pub const EOL = if (Environment.isWindows) "\r\n" else "\n";
- pub const devNull = if (Environment.isWindows) "\\\\.\nul" else "/dev/null";
+ pub const EOL: []const u8 = if (Environment.isWindows) "\r\n" else "\n";
+ pub const devNull: []const u8 = if (Environment.isWindows) "\\\\.\nul" else "/dev/null";
pub fn arch(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(.C) JSC.JSValue {
JSC.markBinding(@src());
@@ -65,7 +65,7 @@ pub const Os = struct {
sys: u64 = 0,
idle: u64 = 0,
irq: u64 = 0,
- } = .{}
+ } = .{},
};
pub fn cpus(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(.C) JSC.JSValue {
@@ -73,14 +73,14 @@ pub const Os = struct {
var cpu_buffer: [8192]CPU = undefined;
const cpus_or_error = if (comptime Environment.isLinux)
- cpusImplLinux(&cpu_buffer)
- else
- @as(anyerror![]CPU, cpu_buffer[0..0]); // unsupported platform -> empty array
+ cpusImplLinux(&cpu_buffer)
+ else
+ @as(anyerror![]CPU, cpu_buffer[0..0]); // unsupported platform -> empty array
if (cpus_or_error) |list| {
// Convert the CPU list to a JS Array
const values = JSC.JSValue.createEmptyArray(globalThis, list.len);
- for (list) |cpu, cpu_index| {
+ for (list, 0..) |cpu, cpu_index| {
const obj = JSC.JSValue.createEmptyObject(globalThis, 3);
obj.put(globalThis, JSC.ZigString.static("model"), cpu.model.withEncoding().toValueGC(globalThis));
obj.put(globalThis, JSC.ZigString.static("speed"), JSC.JSValue.jsNumberFromUint64(cpu.speed));
@@ -88,14 +88,12 @@ pub const Os = struct {
const timesFields = comptime std.meta.fieldNames(@TypeOf(cpu.times));
const times = JSC.JSValue.createEmptyObject(globalThis, 5);
inline for (timesFields) |fieldName| {
- times.put(globalThis, JSC.ZigString.static(fieldName),
- JSC.JSValue.jsNumberFromUint64(@field(cpu.times, fieldName)));
+ times.put(globalThis, JSC.ZigString.static(fieldName), JSC.JSValue.jsNumberFromUint64(@field(cpu.times, fieldName)));
}
obj.put(globalThis, JSC.ZigString.static("times"), times);
values.putIndex(globalThis, @intCast(u32, cpu_index), obj);
}
return values;
-
} else |zig_err| {
const msg = switch (zig_err) {
error.too_many_cpus => "Too many CPUs or malformed /proc/cpuinfo file",
@@ -113,7 +111,7 @@ pub const Os = struct {
fn cpusImplLinux(cpu_buffer: []CPU) ![]CPU {
// Use a large line buffer because the /proc/stat file can have a very long list of interrupts
- var line_buffer: [1024*8]u8 = undefined;
+ var line_buffer: [1024 * 8]u8 = undefined;
var num_cpus: usize = 0;
// Read /proc/stat to get number of CPUs and times
@@ -126,7 +124,6 @@ pub const Os = struct {
// Read each CPU line
while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| {
-
if (num_cpus >= cpu_buffer.len) return error.too_many_cpus;
// CPU lines are formatted as `cpu0 user nice sys idle iowait irq softirq`
@@ -141,10 +138,10 @@ pub const Os = struct {
const scale = 10;
cpu_buffer[num_cpus].times.user = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
cpu_buffer[num_cpus].times.nice = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
- cpu_buffer[num_cpus].times.sys = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
+ cpu_buffer[num_cpus].times.sys = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
cpu_buffer[num_cpus].times.idle = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
_ = try (toks.next() orelse error.eol); // skip iowait
- cpu_buffer[num_cpus].times.irq = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
+ cpu_buffer[num_cpus].times.irq = scale * try std.fmt.parseInt(u64, toks.next() orelse return error.eol, 10);
num_cpus += 1;
}
@@ -163,13 +160,11 @@ pub const Os = struct {
var cpu_index: usize = 0;
while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line| {
-
if (std.mem.startsWith(u8, line, key_processor)) {
// If this line starts a new processor, parse the index from the line
const digits = std.mem.trim(u8, line[key_processor.len..], " \t\n");
cpu_index = try std.fmt.parseInt(usize, digits, 10);
if (cpu_index >= slice.len) return error.too_may_cpus;
-
} else if (std.mem.startsWith(u8, line, key_model_name)) {
// If this is the model name, extract it and store on the current cpu
const model_name = line[key_model_name.len..];
@@ -182,7 +177,7 @@ pub const Os = struct {
}
// Read /sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq to get current frequency (optional)
- for (slice) |*cpu, cpu_index| {
+ for (slice, 0..) |*cpu, cpu_index| {
var path_buf: [128]u8 = undefined;
const path = try std.fmt.bufPrint(&path_buf, "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq", .{cpu_index});
if (std.fs.openFileAbsolute(path, .{})) |file| {
@@ -263,11 +258,17 @@ pub const Os = struct {
pub fn homedir(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(.C) JSC.JSValue {
JSC.markBinding(@src());
- var dir: string = "unknown";
- if (comptime Environment.isWindows)
- dir = bun.getenvZ("USERPROFILE") orelse "unknown"
- else
- dir = bun.getenvZ("HOME") orelse "unknown";
+ const dir: []const u8 = brk: {
+ if (comptime Environment.isWindows) {
+ if (bun.getenvZ("USERPROFILE")) |env|
+ break :brk bun.asByteSlice(env);
+ } else {
+ if (bun.getenvZ("HOME")) |env|
+ break :brk bun.asByteSlice(env);
+ }
+
+ break :brk "unknown";
+ };
return JSC.ZigString.init(dir).withEncoding().toValueGC(globalThis);
}
@@ -376,20 +377,21 @@ pub const Os = struct {
pub fn tmpdir(globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame) callconv(.C) JSC.JSValue {
JSC.markBinding(@src());
- var dir: string = "unknown";
- if (comptime Environment.isWindows) {
- if (bun.getenvZ("TEMP") orelse bun.getenvZ("TMP")) |tmpdir_| {
- dir = tmpdir_;
- }
+ const dir: []const u8 = brk: {
+ if (comptime Environment.isWindows) {
+ if (bun.getenvZ("TEMP") orelse bun.getenvZ("TMP")) |tmpdir_| {
+ break :brk tmpdir_;
+ }
- if (bun.getenvZ("SYSTEMROOT") orelse bun.getenvZ("WINDIR")) |systemdir_| {
- dir = systemdir_ + "\\temp";
+ if (bun.getenvZ("SYSTEMROOT") orelse bun.getenvZ("WINDIR")) |systemdir_| {
+ break :brk systemdir_ ++ "\\temp";
+ }
+ } else {
+ break :brk bun.asByteSlice(bun.getenvZ("TMPDIR") orelse bun.getenvZ("TMP") orelse bun.getenvZ("TEMP") orelse "/tmp");
}
- dir = "unknown";
- } else {
- dir = bun.getenvZ("TMPDIR") orelse bun.getenvZ("TMP") orelse bun.getenvZ("TEMP") orelse "/tmp";
- }
+ break :brk "unknown";
+ };
return JSC.ZigString.init(dir).withEncoding().toValueGC(globalThis);
}
diff --git a/src/bun.js/node/syscall.zig b/src/bun.js/node/syscall.zig
index 035a8738f..087bb06dd 100644
--- a/src/bun.js/node/syscall.zig
+++ b/src/bun.js/node/syscall.zig
@@ -141,7 +141,7 @@ pub fn stat(path: [:0]const u8) Maybe(os.Stat) {
const rc = statSym(path, &stat_);
if (comptime Environment.allow_assert)
- log("stat({s}) = {d}", .{ std.mem.span(path), rc });
+ log("stat({s}) = {d}", .{ bun.asByteSlice(path), rc });
if (Maybe(os.Stat).errnoSys(rc, .stat)) |err| return err;
return Maybe(os.Stat){ .result = stat_ };
diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig
index 591af3f09..b70ad9ea3 100644
--- a/src/bun.js/node/types.zig
+++ b/src/bun.js/node/types.zig
@@ -26,7 +26,7 @@ pub fn DeclEnum(comptime T: type) type {
const fieldInfos = std.meta.declarations(T);
var enumFields: [fieldInfos.len]std.builtin.Type.EnumField = undefined;
var decls = [_]std.builtin.Type.Declaration{};
- inline for (fieldInfos) |field, i| {
+ inline for (fieldInfos, 0..) |field, i| {
enumFields[i] = .{
.name = field.name,
.value = i,
@@ -105,7 +105,7 @@ pub fn Maybe(comptime ResultType: type) type {
if (ResultType == []u8) {
return JSC.ArrayBuffer.fromBytes(r, .ArrayBuffer).toJS(globalThis, null);
}
- return JSC.ZigString.init(std.mem.span(r)).withEncoding().toValueAuto(globalThis);
+ return JSC.ZigString.init(bun.asByteSlice(r)).withEncoding().toValueAuto(globalThis);
}
if (comptime @typeInfo(ReturnType) == .Bool) {
@@ -178,7 +178,7 @@ pub fn Maybe(comptime ResultType: type) type {
.SUCCESS => null,
else => |err| @This(){
// always truncate
- .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), .syscall = syscall, .path = std.mem.span(path) },
+ .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)), .syscall = syscall, .path = bun.asByteSlice(path) },
},
};
}
@@ -643,7 +643,7 @@ pub const PathLike = union(Tag) {
arguments.protectEat();
if (zig_str.is16Bit()) {
- var printed = std.mem.span(std.fmt.allocPrintZ(arguments.arena.allocator(), "{}", .{zig_str}) catch unreachable);
+ var printed = bun.asByteSlice(std.fmt.allocPrintZ(arguments.arena.allocator(), "{}", .{zig_str}) catch unreachable);
return PathLike{ .string = PathString.init(printed.ptr[0 .. printed.len + 1]) };
}
@@ -1426,7 +1426,7 @@ pub const Emitter = struct {
pub fn remove(this: *List, ctx: JSC.C.JSContextRef, callback: JSC.JSValue) bool {
const callbacks = this.list.items(.callback);
- for (callbacks) |item, i| {
+ for (callbacks, 0..) |item, i| {
if (callback.eqlValue(item)) {
JSC.C.JSValueUnprotect(ctx, callback.asObjectRef());
this.once_count -|= @as(u32, @boolToInt(this.list.items(.once)[i]));
@@ -1720,7 +1720,7 @@ pub const Path = struct {
var buf: [bun.MAX_PATH_BYTES]u8 = undefined;
var to_join = allocator.alloc(string, args_len) catch unreachable;
var possibly_utf16 = false;
- for (args_ptr[0..args_len]) |arg, i| {
+ for (args_ptr[0..args_len], 0..) |arg, i| {
const zig_str: JSC.ZigString = arg.getZigString(globalThis);
if (zig_str.is16Bit()) {
// TODO: remove this string conversion
diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig
index 23dd05e94..6281a3bda 100644
--- a/src/bun.js/test/jest.zig
+++ b/src/bun.js/test/jest.zig
@@ -435,28 +435,28 @@ pub const Jest = struct {
ctx: js.JSContextRef,
_: js.JSObjectRef,
_: js.JSObjectRef,
- arguments: []const js.JSValueRef,
+ arguments_: []const js.JSValueRef,
exception: js.ExceptionRef,
) js.JSValueRef {
var runner_ = runner orelse {
JSError(getAllocator(ctx), "Run bun wiptest to run a test", .{}, ctx, exception);
return js.JSValueMakeUndefined(ctx);
};
+ const arguments = @ptrCast([]const JSC.JSValue, arguments_);
- if (arguments.len < 1 or !js.JSValueIsString(ctx, arguments[0])) {
+ if (arguments.len < 1 or !arguments[0].isString()) {
JSError(getAllocator(ctx), "Bun.jest() expects a string filename", .{}, ctx, exception);
return js.JSValueMakeUndefined(ctx);
}
- var str = js.JSValueToStringCopy(ctx, arguments[0], exception);
- defer js.JSStringRelease(str);
- var ptr = js.JSStringGetCharacters8Ptr(str);
- const len = js.JSStringGetLength(str);
- if (len == 0 or ptr[0] != '/') {
+ var str = arguments[0].toSlice(ctx, bun.default_allocator);
+ defer str.deinit();
+ var slice = str.slice();
+
+ if (str.len == 0 or slice[0] != '/') {
JSError(getAllocator(ctx), "Bun.jest() expects an absolute file path", .{}, ctx, exception);
return js.JSValueMakeUndefined(ctx);
}
- var str_value = ptr[0..len];
- var filepath = Fs.FileSystem.instance.filename_store.append([]const u8, str_value) catch unreachable;
+ var filepath = Fs.FileSystem.instance.filename_store.append([]const u8, slice) catch unreachable;
var scope = runner_.getOrPutFile(filepath);
DescribeScope.active = scope;
@@ -2495,7 +2495,7 @@ pub const DescribeScope = struct {
pub fn execCallback(this: *DescribeScope, ctx: js.JSContextRef, comptime hook: LifecycleHook) JSValue {
const name = comptime @as(string, @tagName(hook));
var hooks: []JSC.JSValue = @field(this, name).items;
- for (hooks) |cb, i| {
+ for (hooks, 0..) |cb, i| {
if (cb.isEmpty()) continue;
const pending_test = Jest.runner.?.pending_test;
diff --git a/src/bun.js/uuid.zig b/src/bun.js/uuid.zig
index affd07a32..f172c6225 100644
--- a/src/bun.js/uuid.zig
+++ b/src/bun.js/uuid.zig
@@ -87,7 +87,7 @@ pub fn print(
buf[13] = '-';
buf[18] = '-';
buf[23] = '-';
- inline for (encoded_pos) |i, j| {
+ inline for (encoded_pos, 0..) |i, j| {
buf[comptime i + 0] = hex[bytes[j] >> 4];
buf[comptime i + 1] = hex[bytes[j] & 0x0f];
}
@@ -99,7 +99,7 @@ pub fn parse(buf: []const u8) Error!UUID {
if (buf.len != 36 or buf[8] != '-' or buf[13] != '-' or buf[18] != '-' or buf[23] != '-')
return Error.InvalidUUID;
- inline for (encoded_pos) |i, j| {
+ inline for (encoded_pos, 0..) |i, j| {
const hi = hex_to_nibble[buf[i + 0]];
const lo = hex_to_nibble[buf[i + 1]];
if (hi == 0xff or lo == 0xff) {
diff --git a/src/bun.js/webcore/base64.zig b/src/bun.js/webcore/base64.zig
index 50c1ac68d..aad1c471b 100644
--- a/src/bun.js/webcore/base64.zig
+++ b/src/bun.js/webcore/base64.zig
@@ -120,7 +120,7 @@ pub const Base64Encoder = struct {
out_idx += 1;
}
if (encoder.pad_char) |pad_char| {
- for (dest[out_idx..]) |*pad| {
+ for (&dest[out_idx..]) |*pad| {
pad.* = pad_char;
}
}
@@ -143,7 +143,7 @@ pub const Base64Decoder = struct {
};
var char_in_alphabet = [_]bool{false} ** 256;
- for (alphabet_chars) |c, i| {
+ for (alphabet_chars, 0..) |c, i| {
assert(!char_in_alphabet[c]);
assert(pad_char == null or c != pad_char.?);
@@ -188,7 +188,7 @@ pub const Base64Decoder = struct {
var acc_len: u4 = 0;
var dest_idx: usize = 0;
var leftover_idx: ?usize = null;
- for (source) |c, src_idx| {
+ for (source, 0..) |c, src_idx| {
const d = decoder.char_to_index[c];
if (d == invalid_char) {
if (decoder.pad_char == null or c != decoder.pad_char.?) return error.InvalidCharacter;
@@ -261,7 +261,7 @@ pub const Base64DecoderWithIgnore = struct {
var acc_len: u4 = 0;
var dest_idx: usize = 0;
var leftover_idx: ?usize = null;
- for (source) |c, src_idx| {
+ for (source, 0..) |c, src_idx| {
if (decoder_with_ignore.char_is_ignored[c]) continue;
const d = decoder.char_to_index[c];
if (d == Base64Decoder.invalid_char) {
diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig
index de0ec1cb2..9e5ad4ec2 100644
--- a/src/bun.js/webcore/blob.zig
+++ b/src/bun.js/webcore/blob.zig
@@ -391,7 +391,7 @@ pub const Blob = struct {
bun.default_allocator.destroy(handler);
var blob = blob_ catch |err| {
var error_string = ZigString.init(
- std.fmt.allocPrint(bun.default_allocator, "Failed to write file \"{s}\"", .{std.mem.span(@errorName(err))}) catch unreachable,
+ std.fmt.allocPrint(bun.default_allocator, "Failed to write file \"{s}\"", .{bun.asByteSlice(@errorName(err))}) catch unreachable,
);
error_string.mark();
@@ -1185,7 +1185,7 @@ pub const Blob = struct {
this.system_error = .{
.syscall = ZigString.init("open"),
- .code = ZigString.init(std.mem.span(@errorName(this.errno.?))),
+ .code = ZigString.init(bun.asByteSlice(@errorName(this.errno.?))),
.path = ZigString.init(path_string.slice()),
};
@@ -1391,7 +1391,7 @@ pub const Blob = struct {
}).toSystemError();
} else {
this.system_error = JSC.SystemError{
- .code = ZigString.init(std.mem.span(@errorName(err))),
+ .code = ZigString.init(bun.asByteSlice(@errorName(err))),
.path = if (this.file_store.pathlike == .path)
ZigString.init(this.file_store.pathlike.path.slice())
else
@@ -1630,7 +1630,7 @@ pub const Blob = struct {
this.wrote += @truncate(SizeType, result catch |errno| {
this.errno = errno;
this.system_error = this.system_error orelse JSC.SystemError{
- .code = ZigString.init(std.mem.span(@errorName(errno))),
+ .code = ZigString.init(bun.asByteSlice(@errorName(errno))),
.syscall = ZigString.init("write"),
};
diff --git a/src/bun.js/webcore/body.zig b/src/bun.js/webcore/body.zig
index c4e2e1324..ad40c56ff 100644
--- a/src/bun.js/webcore/body.zig
+++ b/src/bun.js/webcore/body.zig
@@ -950,20 +950,24 @@ pub fn BodyMixin(comptime Type: type) type {
return struct {
pub fn getText(
this: *Type,
- globalThis: *JSC.JSGlobalObject,
+ globalObject: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
var value: *Body.Value = this.getBodyValue();
if (value.* == .Used) {
- return handleBodyAlreadyUsed(globalThis);
+ return handleBodyAlreadyUsed(globalObject);
}
if (value.* == .Locked) {
- return value.Locked.setPromise(globalThis, .{ .getText = void{} });
+ if (value.Locked.promise != null) {
+ return handleBodyAlreadyUsed(globalObject);
+ }
+
+ return value.Locked.setPromise(globalObject, .{ .getText = void{} });
}
var blob = value.useAsAnyBlob();
- return JSC.JSPromise.wrap(globalThis, blob.toString(globalThis, .transfer));
+ return JSC.JSPromise.wrap(globalObject, blob.toString(globalObject, .transfer));
}
pub fn getBody(
@@ -998,6 +1002,9 @@ pub fn BodyMixin(comptime Type: type) type {
}
if (value.* == .Locked) {
+ if (value.Locked.promise != null) {
+ return handleBodyAlreadyUsed(globalObject);
+ }
return value.Locked.setPromise(globalObject, .{ .getJSON = void{} });
}
@@ -1024,6 +1031,9 @@ pub fn BodyMixin(comptime Type: type) type {
}
if (value.* == .Locked) {
+ if (value.Locked.promise != null) {
+ return handleBodyAlreadyUsed(globalObject);
+ }
return value.Locked.setPromise(globalObject, .{ .getArrayBuffer = void{} });
}
@@ -1042,6 +1052,12 @@ pub fn BodyMixin(comptime Type: type) type {
return handleBodyAlreadyUsed(globalObject);
}
+ if (value.* == .Locked) {
+ if (value.Locked.promise != null) {
+ return handleBodyAlreadyUsed(globalObject);
+ }
+ }
+
var encoder = this.getFormDataEncoding() orelse {
globalObject.throw("Invalid MIME type", .{});
return .zero;
@@ -1089,6 +1105,10 @@ pub fn BodyMixin(comptime Type: type) type {
}
if (value.* == .Locked) {
+ if (value.Locked.promise != null) {
+ return handleBodyAlreadyUsed(globalObject);
+ }
+
return value.Locked.setPromise(globalObject, .{ .getBlob = void{} });
}
diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig
index 8a6e3224b..deab624d0 100644
--- a/src/bun.js/webcore/encoding.zig
+++ b/src/bun.js/webcore/encoding.zig
@@ -1139,7 +1139,7 @@ pub const Encoder = struct {
var to = allocator.alloc(u8, len) catch return &[_]u8{};
var input_bytes = std.mem.sliceAsBytes(input[0..len]);
@memcpy(to.ptr, input_bytes.ptr, input_bytes.len);
- for (to[0..len]) |c, i| {
+ for (to[0..len], 0..) |c, i| {
to[i] = @as(u8, @truncate(u7, c));
}
diff --git a/src/bun.js/webcore/request.zig b/src/bun.js/webcore/request.zig
index b2ff43a5a..1a3bc1e4c 100644
--- a/src/bun.js/webcore/request.zig
+++ b/src/bun.js/webcore/request.zig
@@ -125,7 +125,7 @@ pub const Request = struct {
try formatter.writeIndent(Writer, writer);
try writer.writeAll("method: \"");
- try writer.writeAll(std.mem.span(@tagName(this.method)));
+ try writer.writeAll(bun.asByteSlice(@tagName(this.method)));
try writer.writeAll("\"");
formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable;
try writer.writeAll("\n");
@@ -163,7 +163,7 @@ pub const Request = struct {
pub fn fromRequestContext(ctx: *RequestContext) !Request {
var req = Request{
- .url = std.mem.span(ctx.getFullURL()),
+ .url = bun.asByteSlice(ctx.getFullURL()),
.body = .{ .Empty = {} },
.method = ctx.method,
.headers = FetchHeaders.createFromPicoHeaders(ctx.request.headers),
diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig
index cd4b1be4c..7ba7198c7 100644
--- a/src/bun.js/webcore/response.zig
+++ b/src/bun.js/webcore/response.zig
@@ -566,31 +566,31 @@ pub const Fetch = struct {
var errors = JSTypeErrorEnum.initUndefined();
errors.set(
JSType.kJSTypeUndefined,
- std.mem.span(fetch_type_error_string_values[0]),
+ bun.asByteSlice(fetch_type_error_string_values[0]),
);
errors.set(
JSType.kJSTypeNull,
- std.mem.span(fetch_type_error_string_values[1]),
+ bun.asByteSlice(fetch_type_error_string_values[1]),
);
errors.set(
JSType.kJSTypeBoolean,
- std.mem.span(fetch_type_error_string_values[2]),
+ bun.asByteSlice(fetch_type_error_string_values[2]),
);
errors.set(
JSType.kJSTypeNumber,
- std.mem.span(fetch_type_error_string_values[3]),
+ bun.asByteSlice(fetch_type_error_string_values[3]),
);
errors.set(
JSType.kJSTypeString,
- std.mem.span(fetch_type_error_string_values[4]),
+ bun.asByteSlice(fetch_type_error_string_values[4]),
);
errors.set(
JSType.kJSTypeObject,
- std.mem.span(fetch_type_error_string_values[5]),
+ bun.asByteSlice(fetch_type_error_string_values[5]),
);
errors.set(
JSType.kJSTypeSymbol,
- std.mem.span(fetch_type_error_string_values[6]),
+ bun.asByteSlice(fetch_type_error_string_values[6]),
);
break :brk errors;
};
diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig
index 868d0840d..0a38c7ed0 100644
--- a/src/bun.js/webcore/streams.zig
+++ b/src/bun.js/webcore/streams.zig
@@ -1892,8 +1892,8 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type {
const ThisSink = @This();
- pub const shim = JSC.Shimmer("", std.mem.span(name_), @This());
- pub const name = std.fmt.comptimePrint("{s}", .{std.mem.span(name_)});
+ pub const shim = JSC.Shimmer("", name_, @This());
+ pub const name = std.fmt.comptimePrint("{s}", .{name_});
// This attaches it to JS
pub const SinkSignal = extern struct {
@@ -2938,8 +2938,8 @@ pub fn ReadableStreamSource(
const supports_ref = setRefUnrefFn != null;
pub const JSReadableStreamSource = struct {
- pub const shim = JSC.Shimmer(std.mem.span(name_), "JSReadableStreamSource", @This());
- pub const name = std.fmt.comptimePrint("{s}_JSReadableStreamSource", .{std.mem.span(name_)});
+ pub const shim = JSC.Shimmer(name_, "JSReadableStreamSource", @This());
+ pub const name = std.fmt.comptimePrint("{s}_JSReadableStreamSource", .{name_});
pub fn pull(globalThis: *JSGlobalObject, callFrame: *JSC.CallFrame) callconv(.C) JSC.JSValue {
JSC.markBinding(@src());
diff --git a/src/bun.zig b/src/bun.zig
index 7659dd3fb..5d1aac9b5 100644
--- a/src/bun.zig
+++ b/src/bun.zig
@@ -282,7 +282,57 @@ pub fn len(value: anytype) usize {
};
}
-pub fn span(ptr: anytype) std.mem.Span(@TypeOf(ptr)) {
+fn Span(comptime T: type) type {
+ switch (@typeInfo(T)) {
+ .Optional => |optional_info| {
+ return ?Span(optional_info.child);
+ },
+ .Pointer => |ptr_info| {
+ var new_ptr_info = ptr_info;
+ switch (ptr_info.size) {
+ .One => switch (@typeInfo(ptr_info.child)) {
+ .Array => |info| {
+ new_ptr_info.child = info.child;
+ new_ptr_info.sentinel = info.sentinel;
+ },
+ else => @compileError("invalid type given to std.mem.Span"),
+ },
+ .C => {
+ new_ptr_info.sentinel = &@as(ptr_info.child, 0);
+ new_ptr_info.is_allowzero = false;
+ },
+ .Many, .Slice => {},
+ }
+ new_ptr_info.size = .Slice;
+ return @Type(.{ .Pointer = new_ptr_info });
+ },
+ else => @compileError("invalid type given to std.mem.Span"),
+ }
+}
+// fn Span(comptime T: type) type {
+// switch (@typeInfo(T)) {
+// .Optional => |optional_info| {
+// return ?Span(optional_info.child);
+// },
+// .Pointer => |ptr_info| {
+// var new_ptr_info = ptr_info;
+// switch (ptr_info.size) {
+// .C => {
+// new_ptr_info.sentinel = &@as(ptr_info.child, 0);
+// new_ptr_info.is_allowzero = false;
+// },
+// .Many => if (ptr_info.sentinel == null) @compileError("invalid type given to bun.span: " ++ @typeName(T)),
+// else => {},
+// }
+// new_ptr_info.size = .Slice;
+// return @Type(.{ .Pointer = new_ptr_info });
+// },
+// else => {},
+// }
+// @compileError("invalid type given to bun.span: " ++ @typeName(T));
+// }
+
+pub fn span(ptr: anytype) Span(@TypeOf(ptr)) {
if (@typeInfo(@TypeOf(ptr)) == .Optional) {
if (ptr) |non_null| {
return span(non_null);
@@ -290,7 +340,7 @@ pub fn span(ptr: anytype) std.mem.Span(@TypeOf(ptr)) {
return null;
}
}
- const Result = std.mem.Span(@TypeOf(ptr));
+ const Result = Span(@TypeOf(ptr));
const l = len(ptr);
const ptr_info = @typeInfo(Result).Pointer;
if (ptr_info.sentinel) |s_ptr| {
@@ -376,8 +426,8 @@ pub fn cloneWithType(comptime T: type, item: T, allocator: std.mem.Allocator) !T
assertDefined(item);
if (comptime hasCloneFn(Child)) {
- var slice = try allocator.alloc(Child, std.mem.len(item));
- for (slice) |*val, i| {
+ var slice = try allocator.alloc(Child, item.len);
+ for (slice, 0..) |*val, i| {
val.* = try item[i].clone(allocator);
}
return slice;
@@ -595,7 +645,7 @@ pub const MimallocArena = @import("./mimalloc_arena.zig").Arena;
/// Zig's sliceTo(0) is scalar
pub fn getenvZ(path_: [:0]const u8) ?[]const u8 {
const ptr = std.c.getenv(path_.ptr) orelse return null;
- return span(ptr);
+ return sliceTo(ptr, 0);
}
// These wrappers exist to use our strings.eqlLong function
@@ -691,7 +741,7 @@ pub const SignalCode = enum(u8) {
pub fn name(value: SignalCode) ?[]const u8 {
if (@enumToInt(value) <= @enumToInt(SignalCode.SIGSYS)) {
- return std.mem.span(@tagName(value));
+ return asByteSlice(@tagName(value));
}
return null;
@@ -947,3 +997,18 @@ pub fn cstring(input: []const u8) [:0]const u8 {
}
pub const Semver = @import("./install/semver.zig");
+
+pub fn asByteSlice(buffer: anytype) []const u8 {
+ return switch (@TypeOf(buffer)) {
+ []const u8, []u8, [:0]const u8, [:0]u8 => buffer.ptr[0..buffer.len],
+ [*:0]u8, [*:0]const u8 => buffer[0..len(buffer)],
+ [*c]const u8, [*c]u8 => span(buffer),
+ else => |T| {
+ if (comptime std.meta.trait.isPtrTo(.Array)(T)) {
+ return @as([]const u8, buffer);
+ }
+
+ @compileError("Unsupported type " ++ @typeName(T));
+ },
+ };
+}
diff --git a/src/bundler.zig b/src/bundler.zig
index 6b55c8037..e1b791b45 100644
--- a/src/bundler.zig
+++ b/src/bundler.zig
@@ -690,7 +690,7 @@ pub const Bundler = struct {
var dir_info = dir_info_ orelse return;
this.options.routes.dir = dir_info.abs_path;
- this.options.routes.extensions = std.mem.span(&options.RouteConfig.DefaultExtensions);
+ this.options.routes.extensions = options.RouteConfig.DefaultExtensions[0..];
this.options.routes.routes_enabled = true;
this.router = try Router.init(this.fs, this.allocator, this.options.routes);
try this.router.?.loadRoutes(
diff --git a/src/bundler/generate_node_modules_bundle.zig b/src/bundler/generate_node_modules_bundle.zig
index 8a965df08..321777a20 100644
--- a/src/bundler/generate_node_modules_bundle.zig
+++ b/src/bundler/generate_node_modules_bundle.zig
@@ -377,7 +377,7 @@ pub fn generate(
const tmpname = try bundler.fs.tmpname(
".bun",
- std.mem.span(&tmpname_buf),
+ tmpname_buf[0..64],
std.hash.Wyhash.hash(@intCast(usize, std.time.milliTimestamp()) % std.math.maxInt(u32), std.mem.span(destination)),
);
@@ -453,7 +453,7 @@ pub fn generate(
var always_bundled_booleans = bundler.allocator.alloc(bool, always_bundle_count) catch unreachable;
var i: u16 = 0;
- inner: for (bundle_keys) |name, k| {
+ inner: for (bundle_keys, 0..) |name, k| {
std.mem.copy(u8, &Bundler.tmp_buildfile_buf, name);
std.mem.copy(u8, Bundler.tmp_buildfile_buf[name.len..], "/package.json");
const package_json_import = Bundler.tmp_buildfile_buf[0 .. name.len + "/package.json".len];
@@ -516,7 +516,7 @@ pub fn generate(
if (framework.override_modules.keys.len > 0) {
bundler.options.framework.?.override_modules_hashes = allocator.alloc(u64, framework.override_modules.keys.len) catch unreachable;
- for (framework.override_modules.keys) |key, i| {
+ for (framework.override_modules.keys, 0..) |key, i| {
bundler.options.framework.?.override_modules_hashes[i] = std.hash.Wyhash.hash(0, key);
}
}
@@ -669,14 +669,14 @@ pub fn generate(
// }
if (this.log.errors > 0) {
- tmpfile.closeAndDelete(std.mem.span(tmpname));
+ tmpfile.closeAndDelete(tmpname);
// We stop here because if there are errors we don't know if the bundle is valid
// This manifests as a crash when sorting through the module list because we may have added files to the bundle which were never actually finished being added.
return null;
}
if (this.module_list.items.len == 0) {
- tmpfile.closeAndDelete(std.mem.span(tmpname));
+ tmpfile.closeAndDelete(tmpname);
Output.prettyErrorln(
\\<r><red>error<r>: no dependencies to bundle!
\\
@@ -1497,7 +1497,7 @@ pub fn processFile(this: *GenerateNodeModuleBundle, worker: *ThreadPool.Worker,
},
.loc = .{ .start = 0 },
},
- .args = js_ast.ExprNodeList.init(std.mem.span(&json_call_args)),
+ .args = js_ast.ExprNodeList.init(json_call_args[0..]),
},
.{ .start = 0 },
);
diff --git a/src/bunfig.zig b/src/bunfig.zig
index 5f9e1728c..4a341ef20 100644
--- a/src/bunfig.zig
+++ b/src/bunfig.zig
@@ -256,7 +256,7 @@ pub const Bunfig = struct {
if (name_.len == 0) continue;
const name = if (name_[0] == '@') name_[1..] else name_;
var index = names.items.len;
- for (names.items) |comparator, i| {
+ for (names.items, 0..) |comparator, i| {
if (strings.eql(name, comparator)) {
index = i;
break;
@@ -417,7 +417,7 @@ pub const Bunfig = struct {
try this.expect(entryPoints, .e_array);
const items = entryPoints.data.e_array.items.slice();
var names = try this.allocator.alloc(string, items.len);
- for (items) |item, i| {
+ for (items, 0..) |item, i| {
try this.expect(item, .e_string);
names[i] = try item.data.e_string.string(allocator);
}
@@ -560,7 +560,7 @@ pub const Bunfig = struct {
.e_array => |array| {
var externals = try allocator.alloc(string, array.items.len);
- for (array.items.slice()) |item, i| {
+ for (array.items.slice(), 0..) |item, i| {
try this.expect(item, .e_string);
externals[i] = try item.data.e_string.string(allocator);
}
@@ -584,7 +584,7 @@ pub const Bunfig = struct {
var loader_names = try this.allocator.alloc(string, properties.len);
var loader_values = try this.allocator.alloc(Api.Loader, properties.len);
- for (properties) |item, i| {
+ for (properties, 0..) |item, i| {
var key = item.key.?.asString(allocator).?;
if (key.len == 0) continue;
if (key[0] != '.') {
diff --git a/src/cli.zig b/src/cli.zig
index 3a7e79c14..33569c33e 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -227,7 +227,7 @@ pub const Arguments = struct {
if (auto_loaded) return;
Output.prettyErrorln("<r><red>error<r>: {s} opening config \"{s}\"", .{
@errorName(err),
- std.mem.span(config_path),
+ config_path,
});
Global.exit(1);
};
@@ -236,7 +236,7 @@ pub const Arguments = struct {
if (auto_loaded) return;
Output.prettyErrorln("<r><red>error<r>: {s} reading config \"{s}\"", .{
@errorName(err),
- std.mem.span(config_path),
+ config_path,
});
Global.exit(1);
};
@@ -252,7 +252,7 @@ pub const Arguments = struct {
ctx.log.level = original_level;
}
ctx.log.level = logger.Log.Level.warn;
- try Bunfig.parse(allocator, logger.Source.initPathString(std.mem.span(config_path), contents), ctx, cmd);
+ try Bunfig.parse(allocator, logger.Source.initPathString(bun.asByteSlice(config_path), contents), ctx, cmd);
}
fn getHomeConfigPath(buf: *[bun.MAX_PATH_BYTES]u8) ?[:0]const u8 {
@@ -391,7 +391,7 @@ pub const Arguments = struct {
if (args.options("--external").len > 0) {
var externals = try allocator.alloc([]u8, args.options("--external").len);
- for (args.options("--external")) |external, i| {
+ for (args.options("--external"), 0..) |external, i| {
externals[i] = constStrToU8(external);
}
opts.external = externals;
@@ -429,7 +429,7 @@ pub const Arguments = struct {
const print_help = args.flag("--help");
if (print_help) {
const params_len = if (cmd == .BuildCommand) build_params_public.len else public_params.len;
- clap.help(Output.writer(), std.mem.span(params_to_use[0..params_len])) catch {};
+ clap.help(Output.writer(), params_to_use[0..params_len]) catch {};
Output.prettyln("\n-------\n\n", .{});
Output.flush();
HelpCommand.printWithReason(.explicit);
@@ -912,7 +912,7 @@ pub const Command = struct {
next_arg = ((args_iter.next()) orelse return .AutoCommand);
}
- const first_arg_name = std.mem.span(next_arg);
+ const first_arg_name = next_arg;
const RootCommandMatcher = strings.ExactSizeMatcher(16);
return switch (RootCommandMatcher.match(first_arg_name)) {
@@ -1059,7 +1059,7 @@ pub const Command = struct {
const ctx = try Command.Context.create(allocator, log, .GetCompletionsCommand);
var filter = ctx.positionals;
- for (filter) |item, i| {
+ for (filter, 0..) |item, i| {
if (strings.eqlComptime(item, "getcompletes")) {
if (i + 1 < filter.len) {
filter = filter[i + 1 ..];
@@ -1152,7 +1152,7 @@ pub const Command = struct {
var remainder = args[2..];
var remainder_i: usize = 0;
while (remainder_i < remainder.len and positional_i < positionals.len) : (remainder_i += 1) {
- var slice = std.mem.trim(u8, std.mem.span(remainder[remainder_i]), " \t\n;");
+ var slice = std.mem.trim(u8, bun.asByteSlice(remainder[remainder_i]), " \t\n;");
if (slice.len > 0) {
positionals[positional_i] = slice;
positional_i += 1;
diff --git a/src/cli/build_command.zig b/src/cli/build_command.zig
index 233dd487f..c804316dc 100644
--- a/src/cli/build_command.zig
+++ b/src/cli/build_command.zig
@@ -62,7 +62,7 @@ pub const BuildCommand = struct {
var all_paths = try ctx.allocator.alloc([]const u8, result.output_files.len);
var max_path_len: usize = 0;
- for (result.output_files) |f, i| {
+ for (result.output_files, 0..) |f, i| {
all_paths[i] = f.input.text;
}
diff --git a/src/cli/bunx_command.zig b/src/cli/bunx_command.zig
index 3548702ee..ef1fc3c17 100644
--- a/src/cli/bunx_command.zig
+++ b/src/cli/bunx_command.zig
@@ -125,7 +125,7 @@ pub const BunxCommand = struct {
var passthrough_list = try std.ArrayList(string).initCapacity(ctx.allocator, std.os.argv.len -| 1);
var package_name_for_update_request = [1]string{""};
{
- var argv = std.mem.span(std.os.argv)[1..];
+ var argv = std.os.argv[1..];
var found_subcommand_name = false;
@@ -262,7 +262,7 @@ pub const BunxCommand = struct {
this_bundler.fs.top_level_dir,
absolute_in_cache_dir,
)) |destination| {
- const out = std.mem.span(destination);
+ const out = bun.asByteSlice(destination);
_ = try Run.runBinary(
ctx,
try this_bundler.fs.dirname_store.append(@TypeOf(out), out),
@@ -291,7 +291,7 @@ pub const BunxCommand = struct {
this_bundler.fs.top_level_dir,
absolute_in_cache_dir,
)) |destination| {
- const out = std.mem.span(destination);
+ const out = bun.asByteSlice(destination);
_ = try Run.runBinary(
ctx,
try this_bundler.fs.dirname_store.append(@TypeOf(out), out),
@@ -381,7 +381,7 @@ pub const BunxCommand = struct {
this_bundler.fs.top_level_dir,
absolute_in_cache_dir,
)) |destination| {
- const out = std.mem.span(destination);
+ const out = bun.asByteSlice(destination);
_ = try Run.runBinary(
ctx,
try this_bundler.fs.dirname_store.append(@TypeOf(out), out),
@@ -411,7 +411,7 @@ pub const BunxCommand = struct {
this_bundler.fs.top_level_dir,
absolute_in_cache_dir,
)) |destination| {
- const out = std.mem.span(destination);
+ const out = bun.asByteSlice(destination);
_ = try Run.runBinary(
ctx,
try this_bundler.fs.dirname_store.append(@TypeOf(out), out),
diff --git a/src/cli/colon_list_type.zig b/src/cli/colon_list_type.zig
index a76ba7fbf..1151d6a18 100644
--- a/src/cli/colon_list_type.zig
+++ b/src/cli/colon_list_type.zig
@@ -22,7 +22,7 @@ pub fn ColonListType(comptime t: type, comptime value_resolver: anytype) type {
values: []t,
pub fn load(self: *@This(), input: []const string) !void {
- for (input) |str, i| {
+ for (input, 0..) |str, i| {
// Support either ":" or "=" as the separator, preferring whichever is first.
// ":" is less confusing IMO because that syntax is used with flags
// but "=" is what esbuild uses and I want this to be somewhat familiar for people using esbuild
diff --git a/src/cli/create_command.zig b/src/cli/create_command.zig
index 95f53ffd3..af369fb8b 100644
--- a/src/cli/create_command.zig
+++ b/src/cli/create_command.zig
@@ -130,7 +130,7 @@ fn execTask(allocator: std.mem.Allocator, task_: string, cwd: string, _: string,
}
Output.pretty("\n<r><d>$<b>", .{});
- for (argv) |arg, i| {
+ for (argv, 0..) |arg, i| {
if (i > argv.len - 1) {
Output.print(" {s} ", .{arg});
} else {
@@ -165,7 +165,7 @@ pub const ProgressBuf = struct {
pub fn print(comptime fmt: string, args: anytype) !string {
buf_index += 1;
- return try std.fmt.bufPrint(std.mem.span(&bufs[buf_index % 2]), fmt, args);
+ return try std.fmt.bufPrint(&bufs[buf_index % 2], fmt, args);
}
pub fn pretty(comptime fmt: string, args: anytype) !string {
@@ -1109,7 +1109,7 @@ pub const CreateCommand = struct {
pub const bun_bun_for_nextjs_task: string = "bun bun --use next";
};
- InjectionPrefill.bun_macro_relay_object.properties = js_ast.G.Property.List.init(std.mem.span(&InjectionPrefill.bun_macro_relay_properties));
+ InjectionPrefill.bun_macro_relay_object.properties = js_ast.G.Property.List.init(InjectionPrefill.bun_macro_relay_properties[0..]);
InjectionPrefill.bun_macros_relay_object.properties = js_ast.G.Property.List.init(&InjectionPrefill.bun_macros_relay_object_properties);
InjectionPrefill.bun_macros_relay_only_object.properties = js_ast.G.Property.List.init(&InjectionPrefill.bun_macros_relay_only_object_properties);
@@ -1644,7 +1644,7 @@ pub const CreateCommand = struct {
if (create_options.open) {
if (which(&bun_path_buf, PATH, destination, "bun")) |bin| {
- var argv = [_]string{std.mem.span(bin)};
+ var argv = [_]string{bun.asByteSlice(bin)};
var child = std.ChildProcess.init(&argv, ctx.allocator);
child.cwd = destination;
child.stdin_behavior = .Inherit;
@@ -2076,7 +2076,7 @@ pub const Example = struct {
const count = q.expr.data.e_object.properties.len;
var list = try ctx.allocator.alloc(Example, count);
- for (q.expr.data.e_object.properties.slice()) |property, i| {
+ for (q.expr.data.e_object.properties.slice(), 0..) |property, i| {
const name = property.key.?.data.e_string.data;
list[i] = Example{
.name = if (std.mem.indexOfScalar(u8, name, '/')) |slash|
@@ -2204,9 +2204,9 @@ const GitHandler = struct {
if (which(&bun_path_buf, PATH, destination, "git")) |git| {
const git_commands = .{
- &[_]string{ std.mem.span(git), "init", "--quiet" },
- &[_]string{ std.mem.span(git), "add", destination, "--ignore-errors" },
- &[_]string{ std.mem.span(git), "commit", "-am", "Initial commit (via bun create)", "--quiet" },
+ &[_]string{ bun.asByteSlice(git), "init", "--quiet" },
+ &[_]string{ bun.asByteSlice(git), "add", destination, "--ignore-errors" },
+ &[_]string{ bun.asByteSlice(git), "commit", "-am", "Initial commit (via bun create)", "--quiet" },
};
if (comptime verbose) {
diff --git a/src/cli/init_command.zig b/src/cli/init_command.zig
index 9eb788dd0..33cf70caf 100644
--- a/src/cli/init_command.zig
+++ b/src/cli/init_command.zig
@@ -80,7 +80,7 @@ pub const InitCommand = struct {
}
var new = try allocator.alloc(u8, input.len);
- for (input) |c, i| {
+ for (input, 0..) |c, i| {
if (c == ' ' or c == '"' or c == '\'') {
new[i] = '-';
} else {
@@ -180,7 +180,7 @@ pub const InitCommand = struct {
for (paths_to_try) |path| {
if (exists(path)) {
- fields.entry_point = std.mem.span(path);
+ fields.entry_point = bun.asByteSlice(path);
break :infer;
}
}
diff --git a/src/cli/install_completions_command.zig b/src/cli/install_completions_command.zig
index a67a57f4f..392414686 100644
--- a/src/cli/install_completions_command.zig
+++ b/src/cli/install_completions_command.zig
@@ -133,7 +133,7 @@ pub const InstallCompletionsCommand = struct {
var completions_dir: string = "";
var output_dir: std.fs.IterableDir = found: {
- for (std.os.argv) |arg, i| {
+ for (std.os.argv, 0..) |arg, i| {
if (strings.eqlComptime(std.mem.span(arg), "completions")) {
if (std.os.argv.len > i + 1) {
const input = std.mem.span(std.os.argv[i + 1]);
@@ -167,7 +167,7 @@ pub const InstallCompletionsCommand = struct {
.fish => {
if (bun.getenvZ("XDG_CONFIG_HOME")) |config_dir| {
outer: {
- var paths = [_]string{ std.mem.span(config_dir), "./fish/completions" };
+ var paths = [_]string{ config_dir, "./fish/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
break :outer;
@@ -176,7 +176,7 @@ pub const InstallCompletionsCommand = struct {
if (bun.getenvZ("XDG_DATA_HOME")) |data_dir| {
outer: {
- var paths = [_]string{ std.mem.span(data_dir), "./fish/completions" };
+ var paths = [_]string{ data_dir, "./fish/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
@@ -186,7 +186,7 @@ pub const InstallCompletionsCommand = struct {
if (bun.getenvZ("HOME")) |home_dir| {
outer: {
- var paths = [_]string{ std.mem.span(home_dir), "./.config/fish/completions" };
+ var paths = [_]string{ home_dir, "./.config/fish/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
break :outer;
@@ -216,7 +216,7 @@ pub const InstallCompletionsCommand = struct {
},
.zsh => {
if (bun.getenvZ("fpath")) |fpath| {
- var splitter = std.mem.split(u8, std.mem.span(fpath), " ");
+ var splitter = std.mem.split(u8, fpath, " ");
while (splitter.next()) |dir| {
completions_dir = dir;
@@ -226,7 +226,7 @@ pub const InstallCompletionsCommand = struct {
if (bun.getenvZ("XDG_DATA_HOME")) |data_dir| {
outer: {
- var paths = [_]string{ std.mem.span(data_dir), "./zsh-completions" };
+ var paths = [_]string{ data_dir, "./zsh-completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
@@ -245,7 +245,7 @@ pub const InstallCompletionsCommand = struct {
if (bun.getenvZ("HOME")) |home_dir| {
{
outer: {
- var paths = [_]string{ std.mem.span(home_dir), "./.oh-my-zsh/completions" };
+ var paths = [_]string{ home_dir, "./.oh-my-zsh/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
break :outer;
@@ -254,7 +254,7 @@ pub const InstallCompletionsCommand = struct {
{
outer: {
- var paths = [_]string{ std.mem.span(home_dir), "./.bun" };
+ var paths = [_]string{ home_dir, "./.bun" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
break :outer;
@@ -277,7 +277,7 @@ pub const InstallCompletionsCommand = struct {
.bash => {
if (bun.getenvZ("XDG_DATA_HOME")) |data_dir| {
outer: {
- var paths = [_]string{ std.mem.span(data_dir), "./bash-completion/completions" };
+ var paths = [_]string{ data_dir, "./bash-completion/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
break :outer;
@@ -286,7 +286,7 @@ pub const InstallCompletionsCommand = struct {
if (bun.getenvZ("XDG_CONFIG_HOME")) |config_dir| {
outer: {
- var paths = [_]string{ std.mem.span(config_dir), "./bash-completion/completions" };
+ var paths = [_]string{ config_dir, "./bash-completion/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
@@ -297,7 +297,7 @@ pub const InstallCompletionsCommand = struct {
if (bun.getenvZ("HOME")) |home_dir| {
{
outer: {
- var paths = [_]string{ std.mem.span(home_dir), "./.oh-my-bash/custom/completions" };
+ var paths = [_]string{ home_dir, "./.oh-my-bash/custom/completions" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
@@ -306,7 +306,7 @@ pub const InstallCompletionsCommand = struct {
}
{
outer: {
- var paths = [_]string{ std.mem.span(home_dir), "./.bash_completion.d" };
+ var paths = [_]string{ home_dir, "./.bash_completion.d" };
completions_dir = resolve_path.joinAbsString(cwd, &paths, .auto);
break :found std.fs.openIterableDirAbsolute(completions_dir, .{}) catch
@@ -395,7 +395,7 @@ pub const InstallCompletionsCommand = struct {
// $ZDOTDIR/.zlogout
if (bun.getenvZ("ZDOTDIR")) |zdot_dir| {
- std.mem.copy(u8, &zshrc_filepath, std.mem.span(zdot_dir));
+ std.mem.copy(u8, &zshrc_filepath, zdot_dir);
std.mem.copy(u8, zshrc_filepath[zdot_dir.len..], "/.zshrc");
zshrc_filepath[zdot_dir.len + "/.zshrc".len] = 0;
var filepath = zshrc_filepath[0 .. zdot_dir.len + "/.zshrc".len :0];
@@ -405,7 +405,7 @@ pub const InstallCompletionsCommand = struct {
second: {
if (bun.getenvZ("HOME")) |zdot_dir| {
- std.mem.copy(u8, &zshrc_filepath, std.mem.span(zdot_dir));
+ std.mem.copy(u8, &zshrc_filepath, zdot_dir);
std.mem.copy(u8, zshrc_filepath[zdot_dir.len..], "/.zshrc");
zshrc_filepath[zdot_dir.len + "/.zshrc".len] = 0;
var filepath = zshrc_filepath[0 .. zdot_dir.len + "/.zshrc".len :0];
@@ -415,7 +415,7 @@ pub const InstallCompletionsCommand = struct {
third: {
if (bun.getenvZ("HOME")) |zdot_dir| {
- std.mem.copy(u8, &zshrc_filepath, std.mem.span(zdot_dir));
+ std.mem.copy(u8, &zshrc_filepath, zdot_dir);
std.mem.copy(u8, zshrc_filepath[zdot_dir.len..], "/.zshenv");
zshrc_filepath[zdot_dir.len + "/.zshenv".len] = 0;
var filepath = zshrc_filepath[0 .. zdot_dir.len + "/.zshenv".len :0];
diff --git a/src/cli/package_manager_command.zig b/src/cli/package_manager_command.zig
index d783b86c9..a3d3a4cb6 100644
--- a/src/cli/package_manager_command.zig
+++ b/src/cli/package_manager_command.zig
@@ -91,7 +91,7 @@ pub const PackageManagerCommand = struct {
}
if (strings.eqlComptime(subcommand, "bin")) {
- var output_path = Path.joinAbs(Fs.FileSystem.instance.top_level_dir, .auto, std.mem.span(pm.options.bin_path));
+ var output_path = Path.joinAbs(Fs.FileSystem.instance.top_level_dir, .auto, bun.asByteSlice(pm.options.bin_path));
Output.prettyln("{s}", .{output_path});
if (Output.stdout_descriptor_type == .terminal) {
Output.prettyln("\n", .{});
@@ -208,7 +208,7 @@ pub const PackageManagerCommand = struct {
const names = lockfile.packages.items(.name);
const string_bytes = lockfile.buffers.string_bytes.items;
- for (package_ids) |package_id, i| {
+ for (package_ids, 0..) |package_id, i| {
if (package_id >= lockfile.packages.len) continue;
if (i == package_ids.len - 1) {
@@ -308,7 +308,7 @@ fn printNodeModulesFolderStructure(
}
}
- for (directory.dependencies) |dependency_id, index| {
+ for (directory.dependencies, 0..) |dependency_id, index| {
const package_name_ = lockfile.buffers.dependencies.items[dependency_id].name.slice(string_bytes);
const package_name = allocator.alloc(u8, package_name_.len) catch unreachable;
defer allocator.free(package_name);
diff --git a/src/cli/run_command.zig b/src/cli/run_command.zig
index c266c8611..0da28b21a 100644
--- a/src/cli/run_command.zig
+++ b/src/cli/run_command.zig
@@ -1061,7 +1061,7 @@ pub const RunCommand = struct {
// // file.close();
- const out = std.mem.span(destination);
+ const out = bun.asByteSlice(destination);
return try runBinary(
ctx,
try this_bundler.fs.dirname_store.append(@TypeOf(out), out),
diff --git a/src/cli/shell_completions.zig b/src/cli/shell_completions.zig
index 6a4b2128f..1ac9cb2c3 100644
--- a/src/cli/shell_completions.zig
+++ b/src/cli/shell_completions.zig
@@ -22,9 +22,9 @@ pub const Shell = enum {
pub fn completions(this: Shell) []const u8 {
return switch (this) {
- .bash => std.mem.span(bash_completions),
- .zsh => std.mem.span(zsh_completions),
- .fish => std.mem.span(fish_completions),
+ .bash => bun.asByteSlice(bash_completions),
+ .zsh => bun.asByteSlice(zsh_completions),
+ .fish => bun.asByteSlice(fish_completions),
else => "",
};
}
@@ -63,7 +63,7 @@ pub fn print(this: @This()) void {
}
if (this.commands.len > 1) {
- for (this.commands[1..]) |cmd, i| {
+ for (this.commands[1..], 0..) |cmd, i| {
writer.writeAll(delimiter) catch return;
writer.writeAll(cmd) catch return;
diff --git a/src/cli/test_command.zig b/src/cli/test_command.zig
index f5760dfea..fbdf73ba3 100644
--- a/src/cli/test_command.zig
+++ b/src/cli/test_command.zig
@@ -113,7 +113,7 @@ pub const CommandLineReporter = struct {
const color_code = comptime if (skip) "<d>" else "";
if (Output.enable_ansi_colors_stderr) {
- for (scopes) |_, i| {
+ for (scopes, 0..) |_, i| {
const index = (scopes.len - 1) - i;
const scope = scopes[index];
if (scope.label.len == 0) continue;
@@ -125,7 +125,7 @@ pub const CommandLineReporter = struct {
writer.writeAll(" >") catch unreachable;
}
} else {
- for (scopes) |_, i| {
+ for (scopes, 0..) |_, i| {
const index = (scopes.len - 1) - i;
const scope = scopes[index];
if (scope.label.len == 0) continue;
diff --git a/src/cli/upgrade_command.zig b/src/cli/upgrade_command.zig
index 4880e8770..a9bf340b9 100644
--- a/src/cli/upgrade_command.zig
+++ b/src/cli/upgrade_command.zig
@@ -544,10 +544,10 @@ pub const UpgradeCommand = struct {
// xattrs are used for codesigning
// it'd be easy to mess that up
var unzip_argv = [_]string{
- std.mem.span(unzip_exe),
+ bun.asByteSlice(unzip_exe),
"-q",
"-o",
- std.mem.span(tmpname),
+ tmpname,
};
var unzip_process = std.ChildProcess.init(&unzip_argv, ctx.allocator);
diff --git a/src/comptime_string_map.zig b/src/comptime_string_map.zig
index bb2602ce3..ce29679ba 100644
--- a/src/comptime_string_map.zig
+++ b/src/comptime_string_map.zig
@@ -31,7 +31,7 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co
}
}).lenAsc;
if (KeyType == u8) {
- for (kvs_list) |kv, i| {
+ for (kvs_list, 0..) |kv, i| {
if (V != void) {
sorted_kvs[i] = .{ .key = kv.@"0", .value = kv.@"1" };
} else {
diff --git a/src/deps/c_ares.zig b/src/deps/c_ares.zig
index c3e452772..5f42000e2 100644
--- a/src/deps/c_ares.zig
+++ b/src/deps/c_ares.zig
@@ -186,7 +186,7 @@ pub const struct_hostent = extern struct {
// A cname lookup always returns a single record but we follow the common API here.
if (comptime strings.eqlComptime(lookup_name, "cname")) {
- if(this.h_name != null){
+ if (this.h_name != null) {
const array = JSC.JSValue.createEmptyArray(globalThis, 1);
const h_name_len = bun.len(this.h_name);
const h_name_slice = this.h_name[0..h_name_len];
@@ -195,10 +195,10 @@ pub const struct_hostent = extern struct {
}
return JSC.JSValue.createEmptyArray(globalThis, 0);
} else {
- if (this.h_aliases == null){
+ if (this.h_aliases == null) {
return JSC.JSValue.createEmptyArray(globalThis, 0);
}
-
+
var count: u32 = 0;
while (this.h_aliases[count] != null) {
count += 1;
@@ -502,7 +502,7 @@ pub const Channel = opaque {
};
var hints_buf: [3]AddrInfo_hints = bun.zero([3]AddrInfo_hints);
- for (hints[0..@min(hints.len, 2)]) |hint, i| {
+ for (hints[0..@min(hints.len, 2)], 0..) |hint, i| {
hints_buf[i] = hint;
}
var hints_: [*c]const AddrInfo_hints = if (hints.len > 0) &hints_buf else null;
diff --git a/src/deps/picohttp.zig b/src/deps/picohttp.zig
index 3ebd34e8a..e483df5fa 100644
--- a/src/deps/picohttp.zig
+++ b/src/deps/picohttp.zig
@@ -60,7 +60,7 @@ pub const Request = struct {
bytes_read: u32 = 0,
pub fn clone(this: *const Request, headers: []Header, builder: *StringBuilder) Request {
- for (this.headers) |header, i| {
+ for (this.headers, 0..) |header, i| {
headers[i] = header.clone(builder);
}
@@ -144,7 +144,7 @@ pub const Response = struct {
var that = this.*;
that.status = builder.append(this.status);
- for (this.headers) |header, i| {
+ for (this.headers, 0..) |header, i| {
headers[i] = header.clone(builder);
}
diff --git a/src/deps/zig-clap/clap/args.zig b/src/deps/zig-clap/clap/args.zig
index c53ca7ec6..a1fa3773a 100644
--- a/src/deps/zig-clap/clap/args.zig
+++ b/src/deps/zig-clap/clap/args.zig
@@ -113,7 +113,7 @@ pub const ShellIterator = struct {
after_quote,
} = .skip_whitespace;
- for (iter.str) |c, i| {
+ for (iter.str, 0..) |c, i| {
switch (state) {
// The state that skips the initial whitespace.
.skip_whitespace => switch (c) {
diff --git a/src/deps/zig-clap/clap/comptime.zig b/src/deps/zig-clap/clap/comptime.zig
index b4739d646..3dcd4f7d7 100644
--- a/src/deps/zig-clap/clap/comptime.zig
+++ b/src/deps/zig-clap/clap/comptime.zig
@@ -50,7 +50,7 @@ pub fn ComptimeClap(
pub fn parse(iter: anytype, opt: clap.ParseOptions) !@This() {
const allocator = opt.allocator;
var multis = [_]std.ArrayList([]const u8){undefined} ** multi_options;
- for (multis) |*multi| {
+ for (&multis) |*multi| {
multi.* = std.ArrayList([]const u8).init(allocator);
}
@@ -109,7 +109,7 @@ pub fn ComptimeClap(
}
}
- for (multis) |*multi, i|
+ for (&multis, 0..) |*multi, i|
res.multi_options[i] = try multi.toOwnedSlice();
res.pos = try pos.toOwnedSlice();
res.passthrough_positionals = try passthrough_positionals.toOwnedSlice();
diff --git a/src/deps/zig-datetime/src/datetime.zig b/src/deps/zig-datetime/src/datetime.zig
index 578356fa8..29a936630 100644
--- a/src/deps/zig-datetime/src/datetime.zig
+++ b/src/deps/zig-datetime/src/datetime.zig
@@ -187,7 +187,7 @@ test "iso-first-monday" {
// Created using python
const years = [20]u16{ 1816, 1823, 1839, 1849, 1849, 1870, 1879, 1882, 1909, 1910, 1917, 1934, 1948, 1965, 1989, 2008, 2064, 2072, 2091, 2096 };
const output = [20]u32{ 662915, 665470, 671315, 674969, 674969, 682641, 685924, 687023, 696886, 697250, 699805, 706014, 711124, 717340, 726104, 733041, 753495, 756421, 763358, 765185 };
- for (years) |year, i| {
+ for (years, 0..) |year, i| {
try testing.expectEqual(daysBeforeFirstMonday(year), output[i]);
}
}
@@ -785,7 +785,7 @@ test "date-isocalendar" {
ISOCalendar{ .year = 2024, .week = 3, .weekday = 2 },
};
- for (dates) |d, i| {
+ for (dates, 0..) |d, i| {
const date = try Date.parseIso(d);
const cal = date.isoCalendar();
try testing.expectEqual(cal, expect[i]);
diff --git a/src/env_loader.zig b/src/env_loader.zig
index e9c15fb3a..999ed9c12 100644
--- a/src/env_loader.zig
+++ b/src/env_loader.zig
@@ -483,7 +483,7 @@ pub const Loader = struct {
var node_path_to_use = override_node;
if (node_path_to_use.len == 0) {
var node = this.getNodePath(fs, &buf) orelse return false;
- node_path_to_use = try fs.dirname_store.append([]const u8, std.mem.span(node));
+ node_path_to_use = try fs.dirname_store.append([]const u8, bun.asByteSlice(node));
}
try this.map.put("NODE", node_path_to_use);
try this.map.put("npm_node_execpath", node_path_to_use);
@@ -533,7 +533,7 @@ pub const Loader = struct {
var key_buf: []u8 = "";
// Frameworks determine an allowlist of values
- for (framework_defaults.keys) |key, i| {
+ for (framework_defaults.keys, 0..) |key, i| {
if (key.len > "process.env.".len and strings.eqlComptime(key[0.."process.env.".len], "process.env.")) {
const hashable_segment = key["process.env.".len..];
string_map_hashes[i] = std.hash.Wyhash.hash(0, hashable_segment);
@@ -658,7 +658,7 @@ pub const Loader = struct {
}
}
- for (framework_defaults.keys) |key, i| {
+ for (framework_defaults.keys, 0..) |key, i| {
var value = framework_defaults.values[i];
if (!to_string.contains(key) and !to_json.contains(key)) {
@@ -768,7 +768,7 @@ pub const Loader = struct {
Output.printElapsed(elapsed);
Output.prettyError(" <d>", .{});
- for (loaded) |yes, i| {
+ for (loaded, 0..) |yes, i| {
if (yes) {
loaded_i += 1;
if (count == 1 or (loaded_i >= count and count > 1)) {
@@ -1136,8 +1136,8 @@ test "DotEnv Loader - copyForDefine" {
const framework_keys = [_]string{ "process.env.BACON", "process.env.HOSTNAME" };
const framework_values = [_]string{ "true", "\"localhost\"" };
const framework = Api.StringMap{
- .keys = std.mem.span(&framework_keys),
- .values = std.mem.span(&framework_values),
+ .keys = framework_keys[0..],
+ .value = framework_values[0..],
};
const user_overrides: string =
diff --git a/src/exact_size_matcher.zig b/src/exact_size_matcher.zig
index 961737a9d..176f8afb7 100644
--- a/src/exact_size_matcher.zig
+++ b/src/exact_size_matcher.zig
@@ -44,7 +44,7 @@ pub fn ExactSizeMatcher(comptime max_bytes: usize) type {
switch (str.len) {
1...max_bytes - 1 => {
var tmp: [max_bytes]u8 = undefined;
- for (str) |char, i| {
+ for (str, 0..) |char, i| {
tmp[i] = std.ascii.toLower(char);
}
@memset(tmp[str.len..].ptr, 0, tmp[str.len..].len);
diff --git a/src/fs.zig b/src/fs.zig
index 713e25ba8..c1cd6d061 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -295,7 +295,7 @@ pub const FileSystem = struct {
pub fn getComptimeQuery(entry: *const DirEntry, comptime query_str: anytype) ?Entry.Lookup {
comptime var query: [query_str.len]u8 = undefined;
- comptime for (query_str) |c, i| {
+ comptime for (query_str, 0..) |c, i| {
query[i] = std.ascii.toLower(c);
};
@@ -332,7 +332,7 @@ pub const FileSystem = struct {
pub fn hasComptimeQuery(entry: *const DirEntry, comptime query_str: anytype) bool {
comptime var query: [query_str.len]u8 = undefined;
- comptime for (query_str) |c, i| {
+ comptime for (query_str, 0..) |c, i| {
query[i] = std.ascii.toLower(c);
};
@@ -521,7 +521,7 @@ pub const FileSystem = struct {
const LIMITS = [_]std.os.rlimit_resource{ std.os.rlimit_resource.STACK, std.os.rlimit_resource.NOFILE };
Output.print("{{\n", .{});
- inline for (LIMITS) |limit_type, i| {
+ inline for (LIMITS, 0..) |limit_type, i| {
const limit = std.os.getrlimit(limit_type) catch return;
if (i == 0) {
@@ -664,7 +664,7 @@ pub const FileSystem = struct {
// Always try to max out how many files we can keep open
pub fn adjustUlimit() !usize {
const LIMITS = [_]std.os.rlimit_resource{ std.os.rlimit_resource.STACK, std.os.rlimit_resource.NOFILE };
- inline for (LIMITS) |limit_type, i| {
+ inline for (LIMITS, 0..) |limit_type, i| {
const limit = try std.os.getrlimit(limit_type);
if (limit.cur < limit.max) {
diff --git a/src/futex.zig b/src/futex.zig
index b826f1938..14c342321 100644
--- a/src/futex.zig
+++ b/src/futex.zig
@@ -559,7 +559,7 @@ test "Futex - Chain" {
};
var ctx = Context{};
- for (ctx.threads) |*entry, index| {
+ for (&ctx.threads, 0..) |*entry, index| {
entry.signal = .{};
entry.thread = try std.Thread.spawn(.{}, Context.run, .{ &ctx, index });
}
diff --git a/src/http.zig b/src/http.zig
index 8fcb078d1..5a2847357 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -478,7 +478,7 @@ pub const RequestContext = struct {
if (!this.bundler.options.routes.static_dir_enabled) return null;
const relative_path = this.url.path;
var extension = this.url.extname;
- var tmp_buildfile_buf = std.mem.span(&Bundler.tmp_buildfile_buf);
+ var tmp_buildfile_buf = Bundler.tmp_buildfile_buf[0..];
// On Windows, we don't keep the directory handle open forever because Windows doesn't like that.
const public_dir: std.fs.Dir = this.bundler.options.routes.static_dir_handle orelse std.fs.openDirAbsolute(this.bundler.options.routes.static_dir, .{}) catch |err| {
@@ -2387,7 +2387,7 @@ pub const RequestContext = struct {
if (send_sourcemap_info) {
// This will be cleared by the arena
- source_map_url = std.mem.span(chunky.rctx.getFullURLForSourceMap());
+ source_map_url = bun.asByteSlice(chunky.rctx.getFullURLForSourceMap());
chunky.rctx.appendHeader("SourceMap", source_map_url);
}
@@ -3362,7 +3362,7 @@ pub const Server = struct {
if (entries_option) |dir_ent| {
var last_file_hash: Watcher.HashType = std.math.maxInt(Watcher.HashType);
for (affected) |changed_name_ptr| {
- const changed_name: []const u8 = std.mem.span((changed_name_ptr orelse continue));
+ const changed_name: []u8 = (changed_name_ptr orelse continue)[0..];
if (changed_name.len == 0 or changed_name[0] == '~' or changed_name[0] == '.') continue;
const loader = (ctx.bundler.options.loaders.get(Fs.PathName.init(changed_name).ext) orelse .file);
@@ -3376,7 +3376,7 @@ pub const Server = struct {
file_ent.entry.need_stat = true;
path_string = file_ent.entry.abs_path;
file_hash = Watcher.getHash(path_string.slice());
- for (hashes) |hash, entry_id| {
+ for (hashes, 0..) |hash, entry_id| {
if (hash == file_hash) {
file_descriptors[entry_id] = 0;
break;
diff --git a/src/http/websocket.zig b/src/http/websocket.zig
index 5ab4fe690..8bc101abb 100644
--- a/src/http/websocket.zig
+++ b/src/http/websocket.zig
@@ -248,7 +248,7 @@ pub const Websocket = struct {
try stream.writeAll(mask);
// Encode
- for (dataframe.data) |c, i| {
+ for (dataframe.data, 0..) |c, i| {
try stream.writeByte(c ^ mask[i % 4]);
}
} else {
@@ -334,7 +334,7 @@ pub const Websocket = struct {
if (header.mask) {
const mask = buf[0..4];
// Decode data in place
- for (data) |_, i| {
+ for (data, 0..) |_, i| {
data[i] ^= mask[i % 4];
}
}
diff --git a/src/http/websocket_http_client.zig b/src/http/websocket_http_client.zig
index bc72f9e56..a4f9284d3 100644
--- a/src/http/websocket_http_client.zig
+++ b/src/http/websocket_http_client.zig
@@ -623,11 +623,11 @@ pub const Mask = struct {
}
if (comptime !skip_mask) {
- for (input) |c, i| {
+ for (input, 0..) |c, i| {
output[i] = c ^ mask[i % 4];
}
} else {
- for (input) |c, i| {
+ for (input, 0..) |c, i| {
output[i] = c;
}
}
diff --git a/src/http_client_async.zig b/src/http_client_async.zig
index 670bb2f7c..28a80700d 100644
--- a/src/http_client_async.zig
+++ b/src/http_client_async.zig
@@ -666,7 +666,7 @@ pub fn onOpen(
ssl.configureHTTPClient(hostname);
}
}
-
+
if (client.state.request_stage == .pending) {
client.onWritable(true, comptime is_ssl, socket);
}
@@ -920,7 +920,7 @@ pub const InternalState = struct {
body_out_str.list.expandToCapacity();
ZlibPool.decompress(buffer.list.items, body_out_str, default_allocator) catch |err| {
- Output.prettyErrorln("<r><red>Zlib error: {s}<r>", .{std.mem.span(@errorName(err))});
+ Output.prettyErrorln("<r><red>Zlib error: {s}<r>", .{bun.asByteSlice(@errorName(err))});
Output.flush();
return err;
};
@@ -939,7 +939,7 @@ pub const InternalState = struct {
else => {
if (!body_out_str.owns(buffer.list.items)) {
body_out_str.append(buffer.list.items) catch |err| {
- Output.prettyErrorln("<r><red>Failed to append to body buffer: {s}<r>", .{std.mem.span(@errorName(err))});
+ Output.prettyErrorln("<r><red>Failed to append to body buffer: {s}<r>", .{bun.asByteSlice(@errorName(err))});
Output.flush();
return err;
};
@@ -1053,12 +1053,12 @@ pub fn hashHeaderName(name: string) u64 {
var hasher = std.hash.Wyhash.init(0);
var remain: string = name;
var buf: [32]u8 = undefined;
- var buf_slice: []u8 = std.mem.span(&buf);
+ var buf_slice: []u8 = buf[0..32];
while (remain.len > 0) {
const end = @min(hasher.buf.len, remain.len);
- hasher.update(strings.copyLowercase(std.mem.span(remain[0..end]), buf_slice));
+ hasher.update(strings.copyLowercase(remain[0..end], buf_slice));
remain = remain[end..];
}
@@ -1386,7 +1386,7 @@ pub fn buildRequest(this: *HTTPClient, body_len: usize) picohttp.Request {
var override_user_agent = false;
- for (header_names) |head, i| {
+ for (header_names, 0..) |head, i| {
const name = this.headerStr(head);
// Hash it as lowercase
const hash = hashHeaderName(name);
@@ -1521,7 +1521,7 @@ pub fn start(this: *HTTPClient, body: []const u8, body_out_str: *MutableString)
fn start_(this: *HTTPClient, comptime is_ssl: bool) void {
// Aborted before connecting
- if (this.hasSignalAborted()){
+ if (this.hasSignalAborted()) {
this.fail(error.Aborted);
return;
}
@@ -1558,7 +1558,7 @@ fn printResponse(response: picohttp.Response) void {
}
pub fn onWritable(this: *HTTPClient, comptime is_first_call: bool, comptime is_ssl: bool, socket: NewHTTPContext(is_ssl).HTTPSocket) void {
- if (this.hasSignalAborted()) {
+ if (this.hasSignalAborted()) {
this.closeAndAbort(is_ssl, socket);
return;
}
@@ -2494,7 +2494,7 @@ pub fn handleResponseMetadata(
) !bool {
var location: string = "";
var pretend_304 = false;
- for (response.headers) |header, header_i| {
+ for (response.headers, 0..) |header, header_i| {
switch (hashHeaderName(header.name)) {
content_length_header_hash => {
const content_length = std.fmt.parseInt(@TypeOf(this.state.body_size), header.value, 10) catch 0;
diff --git a/src/install/bin.zig b/src/install/bin.zig
index dfd29c927..f19d8a6ad 100644
--- a/src/install/bin.zig
+++ b/src/install/bin.zig
@@ -85,7 +85,7 @@ pub const Bin = extern struct {
.value = .{ .dir = builder.append(String, this.value.dir.slice(buf)) },
},
.map => {
- for (this.value.map.get(prev_external_strings)) |extern_string, i| {
+ for (this.value.map.get(prev_external_strings), 0..) |extern_string, i| {
extern_strings_slice[i] = builder.append(ExternalString, extern_string.slice(buf));
}
diff --git a/src/install/bit_set.zig b/src/install/bit_set.zig
index bd6d71027..711c4603f 100644
--- a/src/install/bit_set.zig
+++ b/src/install/bit_set.zig
@@ -495,14 +495,14 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type {
/// in the toggles bit set.
pub fn toggleSet(self: *Self, toggles: *const Self) void {
const other = &toggles.masks;
- for (self.masks) |*mask, i| {
+ for (&self.masks, 0..) |*mask, i| {
mask.* ^= other[i];
}
}
/// Flips every bit in the bit set.
pub fn toggleAll(self: *Self) void {
- for (self.masks) |*mask| {
+ for (&self.masks) |*mask| {
mask.* = ~mask.*;
}
@@ -516,7 +516,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type {
/// result in the first one. Bits in the result are
/// set if the corresponding bits were set in either input.
pub fn setUnion(self: *Self, other: *const Self) void {
- for (self.masks) |*mask, i| {
+ for (&self.masks, 0..) |*mask, i| {
mask.* |= other.masks[i];
}
}
@@ -525,7 +525,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type {
/// the result in the first one. Bits in the result are
/// set if the corresponding bits were set in both inputs.
pub fn setIntersection(self: *Self, other: *const Self) void {
- for (self.masks) |*mask, i| {
+ for (&self.masks, 0..) |*mask, i| {
mask.* &= other.masks[i];
}
}
@@ -545,7 +545,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type {
/// If no bits are set, returns null.
pub fn toggleFirstSet(self: *Self) ?usize {
var offset: usize = 0;
- const mask = for (self.masks) |*mask| {
+ const mask = for (&self.masks) |*mask| {
if (mask.* != 0) break mask;
offset += @bitSizeOf(MaskInt);
} else return null;
@@ -870,7 +870,7 @@ pub const DynamicBitSetUnmanaged = struct {
pub fn toggleSet(self: *Self, toggles: Self) void {
assert(toggles.bit_length == self.bit_length);
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask, i| {
+ for (&self.masks[0..num_masks], 0..) |*mask, i| {
mask.* ^= toggles.masks[i];
}
}
@@ -882,7 +882,7 @@ pub const DynamicBitSetUnmanaged = struct {
if (bit_length == 0) return;
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask| {
+ for (&self.masks[0..num_masks]) |*mask| {
mask.* = ~mask.*;
}
@@ -897,7 +897,7 @@ pub const DynamicBitSetUnmanaged = struct {
if (bit_length == 0) return;
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask, i| {
+ for (&self.masks[0..num_masks], 0..) |*mask, i| {
mask.* = other.masks[i];
}
@@ -913,7 +913,7 @@ pub const DynamicBitSetUnmanaged = struct {
pub fn setUnion(self: *Self, other: Self) void {
assert(other.bit_length == self.bit_length);
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask, i| {
+ for (&self.masks[0..num_masks], 0..) |*mask, i| {
mask.* |= other.masks[i];
}
}
@@ -925,7 +925,7 @@ pub const DynamicBitSetUnmanaged = struct {
pub fn setIntersection(self: *Self, other: Self) void {
assert(other.bit_length == self.bit_length);
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask, i| {
+ for (&self.masks[0..num_masks], 0..) |*mask, i| {
mask.* &= other.masks[i];
}
}
@@ -933,7 +933,7 @@ pub const DynamicBitSetUnmanaged = struct {
pub fn setExcludeTwo(self: *Self, other: Self, third: Self) void {
assert(other.bit_length == self.bit_length);
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask, i| {
+ for (&self.masks[0..num_masks], 0..) |*mask, i| {
mask.* &= ~other.masks[i];
mask.* &= ~third.masks[i];
}
@@ -942,7 +942,7 @@ pub const DynamicBitSetUnmanaged = struct {
pub fn setExclude(self: *Self, other: Self) void {
assert(other.bit_length == self.bit_length);
const num_masks = numMasks(self.bit_length);
- for (self.masks[0..num_masks]) |*mask, i| {
+ for (&self.masks[0..num_masks], 0..) |*mask, i| {
mask.* &= ~other.masks[i];
}
}
diff --git a/src/install/dependency.zig b/src/install/dependency.zig
index 902195170..d93629a82 100644
--- a/src/install/dependency.zig
+++ b/src/install/dependency.zig
@@ -165,7 +165,7 @@ pub inline fn isSCPLikePath(dependency: string) bool {
var at_index: ?usize = null;
- for (dependency) |c, i| {
+ for (dependency, 0..) |c, i| {
switch (c) {
'@' => {
if (at_index == null) at_index = i;
@@ -189,7 +189,7 @@ pub inline fn isGitHubRepoPath(dependency: string) bool {
var hash_index: usize = 0;
var slash_index: usize = 0;
- for (dependency) |c, i| {
+ for (dependency, 0..) |c, i| {
switch (c) {
'/' => {
if (i == 0) return false;
@@ -492,7 +492,7 @@ pub const Version = struct {
'n' => {
if (strings.hasPrefixComptime(dependency, "npm:") and dependency.len > "npm:".len) {
const remain = dependency["npm:".len + @boolToInt(dependency["npm:".len] == '@') ..];
- for (remain) |c, i| {
+ for (remain, 0..) |c, i| {
if (c == '@') {
return infer(remain[i + 1 ..]);
}
@@ -772,7 +772,7 @@ pub fn parseWithTag(
var hash_index: usize = 0;
var slash_index: usize = 0;
- for (input) |c, i| {
+ for (input, 0..) |c, i| {
switch (c) {
'/' => {
slash_index = i;
diff --git a/src/install/install.zig b/src/install/install.zig
index c4de35fe9..07bd06692 100644
--- a/src/install/install.zig
+++ b/src/install/install.zig
@@ -1649,7 +1649,7 @@ pub const PackageManager = struct {
is_main: bool,
) DependencyToEnqueue {
const str_buf = this.lockfile.buffers.string_bytes.items;
- for (this.lockfile.buffers.dependencies.items) |dependency, dependency_id| {
+ for (this.lockfile.buffers.dependencies.items, 0..) |dependency, dependency_id| {
if (!strings.eqlLong(dependency.name.slice(str_buf), name, true)) continue;
if (!dependency.version.eql(version, str_buf, version_buf)) continue;
return switch (this.lockfile.buffers.resolutions.items[dependency_id]) {
@@ -4082,7 +4082,7 @@ pub const PackageManager = struct {
}
if (bun_install_) |bun_install| {
if (bun_install.scoped) |scoped| {
- for (scoped.scopes) |name, i| {
+ for (scoped.scopes, 0..) |name, i| {
var registry = scoped.registries[i];
if (registry.url.len == 0) registry.url = base.url;
try this.registries.put(allocator, Npm.Registry.Scope.hash(name), try Npm.Registry.Scope.fromAPI(name, registry, allocator, env));
@@ -4104,7 +4104,7 @@ pub const PackageManager = struct {
if (bun_install.native_bin_links.len > 0) {
var buf = try allocator.alloc(u64, bun_install.native_bin_links.len);
- for (bun_install.native_bin_links) |name, i| {
+ for (bun_install.native_bin_links, 0..) |name, i| {
buf[i] = String.Builder.stringHash(name);
}
this.native_bin_link_allowlist = buf;
@@ -4375,7 +4375,7 @@ pub const PackageManager = struct {
var all = try allocator.alloc(PackageNameHash, this.native_bin_link_allowlist.len + cli.link_native_bins.len);
std.mem.copy(PackageNameHash, all, this.native_bin_link_allowlist);
var remain = all[this.native_bin_link_allowlist.len..];
- for (cli.link_native_bins) |name, i| {
+ for (cli.link_native_bins, 0..) |name, i| {
remain[i] = String.Builder.stringHash(name);
}
this.native_bin_link_allowlist = all;
@@ -6901,7 +6901,7 @@ pub const PackageManager = struct {
manager.lockfile.buffers.dependencies.items = manager.lockfile.buffers.dependencies.items.ptr[0 .. off + len];
manager.lockfile.buffers.resolutions.items = manager.lockfile.buffers.resolutions.items.ptr[0 .. off + len];
- for (new_dependencies) |new_dep, i| {
+ for (new_dependencies, 0..) |new_dep, i| {
dependencies[i] = try new_dep.clone(lockfile.buffers.string_bytes.items, *Lockfile.StringBuilder, builder);
if (mapping[i] != invalid_package_id) {
resolutions[i] = old_resolutions[mapping[i]];
diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig
index ed60f55cd..80f95ac83 100644
--- a/src/install/lockfile.zig
+++ b/src/install/lockfile.zig
@@ -375,7 +375,7 @@ pub const Tree = struct {
var dependency_ids = try DependencyIDList.initCapacity(z_allocator, total);
var next = PackageIDSlice{};
- for (trees) |*tree, id| {
+ for (trees, 0..) |*tree, id| {
if (tree.dependencies.len > 0) {
var child = dependencies[id];
const len = @truncate(PackageID, child.items.len);
@@ -525,7 +525,7 @@ pub fn maybeCloneFilteringRootPackages(
var any_changes = false;
const end = @truncate(PackageID, old.packages.len);
- for (root_dependencies) |dependency, i| {
+ for (root_dependencies, 0..) |dependency, i| {
if (!dependency.behavior.isEnabled(features) and resolutions[i] < end) {
resolutions[i] = invalid_package_id;
any_changes = true;
@@ -550,7 +550,7 @@ fn preprocessUpdateRequests(old: *Lockfile, updates: []PackageManager.UpdateRequ
for (updates) |update| {
if (update.version.tag == .uninitialized) {
- for (root_deps) |dep, i| {
+ for (root_deps, 0..) |dep, i| {
if (dep.name_hash == String.Builder.stringHash(update.name)) {
const old_resolution = old_resolutions[i];
if (old_resolution > old.packages.len) continue;
@@ -577,9 +577,9 @@ fn preprocessUpdateRequests(old: *Lockfile, updates: []PackageManager.UpdateRequ
const old_resolutions: []const PackageID = old_resolutions_list.get(old.buffers.resolutions.items);
const resolutions_of_yore: []const Resolution = old.packages.items(.resolution);
- for (updates) |update, update_i| {
+ for (updates, 0..) |update, update_i| {
if (update.version.tag == .uninitialized) {
- for (root_deps) |*dep, i| {
+ for (root_deps, 0..) |*dep, i| {
if (dep.name_hash == String.Builder.stringHash(update.name)) {
const old_resolution = old_resolutions[i];
if (old_resolution > old.packages.len) continue;
@@ -702,7 +702,7 @@ pub fn clean(old: *Lockfile, updates: []PackageManager.UpdateRequest) !*Lockfile
for (updates) |*update| {
if (update.resolution.tag == .uninitialized) {
- for (root_deps) |dep, i| {
+ for (root_deps, 0..) |dep, i| {
if (update.matches(dep, string_buf)) {
const package_id = resolved_ids[i];
if (package_id > new.packages.len) continue;
@@ -893,7 +893,7 @@ pub const Printer = struct {
},
.not_found => {
Output.prettyErrorln("<r><red>lockfile not found:<r> {s}", .{
- std.mem.span(lockfile_path),
+ std.mem.sliceAsBytes(lockfile_path),
});
Global.crash();
},
@@ -988,7 +988,7 @@ pub const Printer = struct {
const package_name = dependency.name.slice(string_buf);
if (this.updates.len > 0) {
- for (this.updates) |update, update_id| {
+ for (this.updates, 0..) |update, update_id| {
if (update.failed) return;
if (update.matches(dependency, string_buf)) {
if (id_map[update_id] == invalid_package_id) {
@@ -1019,14 +1019,14 @@ pub const Printer = struct {
);
}
} else {
- outer: for (dependencies_buffer) |dependency, dep_id| {
+ outer: for (dependencies_buffer, 0..) |dependency, dep_id| {
if (dependency.behavior.isPeer()) continue;
const package_id = resolutions_buffer[dep_id];
if (package_id >= end) continue;
const package_name = dependency.name.slice(string_buf);
if (this.updates.len > 0) {
- for (this.updates) |update, update_id| {
+ for (this.updates, 0..) |update, update_id| {
if (update.failed) return;
if (update.matches(dependency, string_buf)) {
if (id_map[update_id] == invalid_package_id) {
@@ -1343,8 +1343,8 @@ pub fn verifyResolutions(this: *Lockfile, local_features: Features, remote_featu
const string_buf = this.buffers.string_bytes.items;
const root_list = resolutions_list[0];
- for (resolutions_list) |list, parent_id| {
- for (list.get(resolutions_buffer)) |package_id, j| {
+ for (resolutions_list, 0..) |list, parent_id| {
+ for (list.get(resolutions_buffer), 0..) |package_id, j| {
if (package_id >= end) {
const failed_dep: Dependency = dependency_lists[parent_id].get(dependencies_buffer)[j];
if (failed_dep.behavior.isPeer() or !failed_dep.behavior.isEnabled(
@@ -1878,7 +1878,7 @@ pub const Package = extern struct {
package_id_mapping[this.meta.id] = new_package.meta.id;
- for (old_dependencies) |dependency, i| {
+ for (old_dependencies, 0..) |dependency, i| {
dependencies[i] = try dependency.clone(
old_string_buf,
*Lockfile.StringBuilder,
@@ -1890,7 +1890,7 @@ pub const Package = extern struct {
cloner.trees_count += @as(u32, @boolToInt(old_resolutions.len > 0));
- for (old_resolutions) |old_resolution, i| {
+ for (old_resolutions, 0..) |old_resolution, i| {
if (old_resolution >= max_package_id) continue;
const mapped = package_id_mapping[old_resolution];
@@ -2065,7 +2065,7 @@ pub const Package = extern struct {
if (comptime Environment.isDebug) std.debug.assert(keys.len == version_strings.len);
- for (keys) |key, i| {
+ for (keys, 0..) |key, i| {
string_builder.count(key.slice(string_buf));
string_builder.count(version_strings[i].slice(string_buf));
}
@@ -2160,7 +2160,7 @@ pub const Package = extern struct {
// If a dependency appears in both "dependencies" and "optionalDependencies", it is considered optional!
if (comptime group.behavior.isOptional()) {
- for (start_dependencies[0 .. total_dependencies_count - dependencies.len]) |dep, j| {
+ for (start_dependencies[0 .. total_dependencies_count - dependencies.len], 0..) |dep, j| {
if (dep.name_hash == key.hash) {
// https://docs.npmjs.com/cli/v8/configuring-npm/package-json#optionaldependencies
// > Entries in optionalDependencies will override entries of the same name in dependencies, so it's usually best to only put in one place.
@@ -2236,13 +2236,13 @@ pub const Package = extern struct {
const to_deps = to.dependencies.get(to_lockfile.buffers.dependencies.items);
const from_deps = from.dependencies.get(from_lockfile.buffers.dependencies.items);
- for (from_deps) |*from_dep, i| {
+ for (from_deps, 0..) |*from_dep, i| {
// common case: dependency is present in both versions and in the same position
const to_i = if (to_deps.len > i and to_deps[i].name_hash == from_dep.name_hash)
i
else brk: {
// less common, o(n^2) case
- for (to_deps) |to_dep, j| {
+ for (to_deps, 0..) |to_dep, j| {
if (from_dep.name_hash == to_dep.name_hash) break :brk j;
}
@@ -2262,7 +2262,7 @@ pub const Package = extern struct {
summary.update += 1;
}
- outer: for (to_deps) |to_dep, i| {
+ outer: for (to_deps, 0..) |to_dep, i| {
if (from_deps.len > i and from_deps[i].name_hash == to_dep.name_hash) continue;
for (from_deps) |from_dep| {
@@ -2421,7 +2421,7 @@ pub const Package = extern struct {
if (entry.found_existing) {
// duplicate dependencies are allowed in optionalDependencies
if (comptime group.behavior.isOptional()) {
- for (package_dependencies[0 .. package_dependencies.len - dependencies.len]) |package_dep, j| {
+ for (package_dependencies[0 .. package_dependencies.len - dependencies.len], 0..) |package_dep, j| {
if (package_dep.name_hash == this_dep.name_hash) {
package_dependencies[j] = this_dep;
break;
@@ -2470,7 +2470,7 @@ pub const Package = extern struct {
const orig_msgs_len = log.msgs.items.len;
- for (arr.slice()) |item, i| {
+ for (arr.slice(), 0..) |item, i| {
defer fallback.fixed_buffer_allocator.reset();
const path = item.asString(allocator) orelse {
log.addErrorFmt(source, item.loc, allocator,
@@ -2962,7 +2962,7 @@ pub const Package = extern struct {
.e_array => |arr| {
if (arr.items.len == 0) break :brk;
- for (arr.slice()) |item, i| {
+ for (arr.slice(), 0..) |item, i| {
const name = workspace_names[i];
defer allocator.free(name);
@@ -3009,7 +3009,7 @@ pub const Package = extern struct {
var arr = packages_q.data.e_array;
if (arr.items.len == 0) break :brk;
- for (arr.slice()) |item, i| {
+ for (arr.slice(), 0..) |item, i| {
const name = workspace_names[i];
defer allocator.free(name);
@@ -3148,7 +3148,7 @@ pub const Package = extern struct {
Type: type,
};
var data: [fields.len]Data = undefined;
- for (fields) |field_info, i| {
+ for (fields, 0..) |field_info, i| {
data[i] = .{
.size = @sizeOf(field_info.type),
.size_index = i,
@@ -3167,7 +3167,7 @@ pub const Package = extern struct {
var sizes_bytes: [fields.len]usize = undefined;
var field_indexes: [fields.len]usize = undefined;
var Types: [fields.len]type = undefined;
- for (data) |elem, i| {
+ for (data, 0..) |elem, i| {
sizes_bytes[i] = elem.size;
field_indexes[i] = elem.size_index;
Types[i] = elem.Type;
@@ -3304,7 +3304,7 @@ const Buffers = struct {
alignment: usize,
};
var data: [fields.len]Data = undefined;
- for (fields) |field_info, i| {
+ for (fields, 0..) |field_info, i| {
data[i] = .{
.size = @sizeOf(field_info.type),
.name = field_info.name,
@@ -3323,7 +3323,7 @@ const Buffers = struct {
var sizes_bytes: [fields.len]usize = undefined;
var names: [fields.len][]const u8 = undefined;
var types: [fields.len]type = undefined;
- for (data) |elem, i| {
+ for (data, 0..) |elem, i| {
sizes_bytes[i] = elem.size;
names[i] = elem.name;
types[i] = elem.type;
@@ -3454,7 +3454,7 @@ const Buffers = struct {
switch (package_id) {
0 => return Tree.root_dep_id,
invalid_package_id => return invalid_package_id,
- else => for (this.resolutions.items) |pkg_id, dep_id| {
+ else => for (this.resolutions.items, 0..) |pkg_id, dep_id| {
if (pkg_id == package_id) return @truncate(DependencyID, dep_id);
},
}
@@ -3465,7 +3465,7 @@ const Buffers = struct {
var this = Buffers{};
var external_dependency_list_: std.ArrayListUnmanaged(Dependency.External) = std.ArrayListUnmanaged(Dependency.External){};
- inline for (sizes.names) |name, i| {
+ inline for (sizes.names, 0..) |name, i| {
const Type = @TypeOf(@field(this, name));
var pos: usize = 0;
@@ -3485,7 +3485,7 @@ const Buffers = struct {
this.trees = try Tree.List.initCapacity(allocator, tree_list.items.len);
this.trees.items.len = tree_list.items.len;
- for (tree_list.items) |tree, j| {
+ for (tree_list.items, 0..) |tree, j| {
this.trees.items[j] = Tree.toTree(tree);
}
} else {
@@ -3619,7 +3619,7 @@ pub const Serializer = struct {
const slice = lockfile.packages.slice();
const name_hashes = slice.items(.name_hash);
const resolutions = slice.items(.resolution);
- for (name_hashes) |name_hash, id| {
+ for (name_hashes, 0..) |name_hash, id| {
try lockfile.getOrPutID(@truncate(PackageID, id), name_hash);
const resolution = resolutions[id];
diff --git a/src/install/npm.zig b/src/install/npm.zig
index 71b892bef..66f9d02cb 100644
--- a/src/install/npm.zig
+++ b/src/install/npm.zig
@@ -229,7 +229,7 @@ const ExternVersionMap = extern struct {
values: PackageVersionList = PackageVersionList{},
pub fn findKeyIndex(this: ExternVersionMap, buf: []const Semver.Version, find: Semver.Version) ?u32 {
- for (this.keys.get(buf)) |key, i| {
+ for (this.keys.get(buf), 0..) |key, i| {
if (key.eql(find)) {
return @truncate(u32, i);
}
@@ -482,7 +482,7 @@ pub const PackageManifest = struct {
alignment: usize,
};
var data: [fields.len]Data = undefined;
- for (fields) |field_info, i| {
+ for (fields, 0..) |field_info, i| {
data[i] = .{
.size = @sizeOf(field_info.type),
.name = field_info.name,
@@ -499,7 +499,7 @@ pub const PackageManifest = struct {
std.sort.sort(Data, &data, &trash, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var names: [fields.len][]const u8 = undefined;
- for (data) |elem, i| {
+ for (data, 0..) |elem, i| {
sizes_bytes[i] = elem.size;
names[i] = elem.name;
}
@@ -717,7 +717,7 @@ pub const PackageManifest = struct {
pub fn findByDistTag(this: *const PackageManifest, tag: string) ?FindResult {
const versions = this.pkg.dist_tags.versions.get(this.versions);
- for (this.pkg.dist_tags.tags.get(this.external_strings)) |tag_str, i| {
+ for (this.pkg.dist_tags.tags.get(this.external_strings), 0..) |tag_str, i| {
if (strings.eql(tag_str.slice(this.string_buf), tag)) {
return this.findByVersion(versions[i]);
}
diff --git a/src/io/io_darwin.zig b/src/io/io_darwin.zig
index fd991bbf5..d9c597735 100644
--- a/src/io/io_darwin.zig
+++ b/src/io/io_darwin.zig
@@ -787,7 +787,7 @@ fn flush(self: *IO, comptime _: @Type(.EnumLiteral)) !void {
}
fn flush_io(_: *IO, events: []Kevent64, io_pending_top: *?*Completion) usize {
- for (events) |*kevent, flushed| {
+ for (events, 0..) |*kevent, flushed| {
const completion = io_pending_top.* orelse return flushed;
io_pending_top.* = completion.next;
const event_info = switch (completion.operation) {
diff --git a/src/js_ast.zig b/src/js_ast.zig
index a3225ccce..82032b058 100644
--- a/src/js_ast.zig
+++ b/src/js_ast.zig
@@ -1533,7 +1533,7 @@ pub const E = struct {
}
pub fn asProperty(obj: *const Object, name: string) ?Expr.Query {
- for (obj.properties.slice()) |prop, i| {
+ for (obj.properties.slice(), 0..) |prop, i| {
const value = prop.value orelse continue;
const key = prop.key orelse continue;
if (std.meta.activeTag(key.data) != .e_string) continue;
@@ -5248,7 +5248,7 @@ pub const Macro = struct {
0 => return js.JSObjectMakeArray(ctx, 0, null, exception),
1...255 => {
var slice = temporary_call_args_array[0..args.len];
- for (slice) |_, i| {
+ for (slice, 0..) |_, i| {
var node = JSCBase.getAllocator(ctx).create(JSNode) catch unreachable;
node.* = JSNode.initExpr(args.ptr[i]);
slice[i] = JSNode.Class.make(ctx, node);
@@ -5292,7 +5292,7 @@ pub const Macro = struct {
0 => return js.JSObjectMakeArray(ctx, 0, null, exception),
1...255 => {
var slice = temporary_call_args_array[0..args.len];
- for (slice) |_, i| {
+ for (slice, 0..) |_, i| {
var node = JSCBase.getAllocator(ctx).create(JSNode) catch unreachable;
node.* = JSNode{ .data = .{ .g_property = &args[i] }, .loc = this.loc };
slice[i] = JSNode.Class.make(ctx, node);
@@ -5355,7 +5355,7 @@ pub const Macro = struct {
return js.JSObjectMakeArray(ctx, 0, null, exception);
}
- for (items) |expr, i| {
+ for (items, 0..) |expr, i| {
var node = JSCBase.getAllocator(ctx).create(JSNode) catch unreachable;
node.* = JSNode.initExpr(expr);
temporary_call_args_array[i] = JSNode.Class.make(ctx, node);
@@ -5371,7 +5371,7 @@ pub const Macro = struct {
}
var node: JSNode = undefined;
- for (items) |expr, i| {
+ for (items, 0..) |expr, i| {
node = JSNode.initExpr(expr);
temporary_call_args_array[i] = toPrimitive(&node, ctx, exception);
}
@@ -5396,7 +5396,7 @@ pub const Macro = struct {
defer if (did_allocate) getAllocator(ctx).free(properties_list);
- for (obj.properties.slice()) |_, i| {
+ for (obj.properties.slice(), 0..) |_, i| {
var node = JSCBase.getAllocator(ctx).create(JSNode) catch unreachable;
node.* = JSNode{
.data = .{
@@ -6221,7 +6221,7 @@ pub const Macro = struct {
}
fn indexOfPropertyByName(props: []G.Property, comptime name: string) ?u32 {
- for (props) |prop, i| {
+ for (props, 0..) |prop, i| {
const key = prop.key orelse continue;
if (key.data != .e_string or !key.data.e_string.isUTF8()) continue;
if (strings.eqlComptime(key.data.e_string.data, name)) return @intCast(u32, i);
diff --git a/src/js_lexer/identifier_cache.zig b/src/js_lexer/identifier_cache.zig
index c03284c4b..5f34c9611 100644
--- a/src/js_lexer/identifier_cache.zig
+++ b/src/js_lexer/identifier_cache.zig
@@ -6,7 +6,7 @@ pub const CachedBitset = extern struct {
len: u32,
pub fn fromFile(comptime filename: anytype) CachedBitset {
- return comptime @bitCast(CachedBitset, std.mem.span(@embedFile(filename)).ptr[0..@sizeOf(CachedBitset)].*);
+ return comptime @bitCast(CachedBitset, bun.asByteSlice(@embedFile(filename)).ptr[0..@sizeOf(CachedBitset)].*);
}
};
diff --git a/src/js_parser.zig b/src/js_parser.zig
index a8861875a..4a6fdac35 100644
--- a/src/js_parser.zig
+++ b/src/js_parser.zig
@@ -3279,7 +3279,7 @@ pub const Parser = struct {
var import_records = try p.allocator.alloc(u32, p.cjs_import_stmts.items.len);
var declared_symbols = try p.allocator.alloc(js_ast.DeclaredSymbol, p.cjs_import_stmts.items.len);
- for (p.cjs_import_stmts.items) |entry, i| {
+ for (p.cjs_import_stmts.items, 0..) |entry, i| {
const import_statement: *S.Import = entry.data.s_import;
import_records[i] = import_statement.import_record_index;
declared_symbols[i] = .{
@@ -4075,7 +4075,7 @@ fn NewParser_(
if (merge and parts_.len > 1) {
var first_none_part: usize = parts_.len;
var stmts_count: usize = 0;
- for (parts_) |part, i| {
+ for (parts_, 0..) |part, i| {
if (part.tag == .none) {
stmts_count += part.stmts.len;
first_none_part = @min(i, first_none_part);
@@ -4213,7 +4213,7 @@ fn NewParser_(
var symbol_use_values = part.symbol_uses.values();
var symbols = p.symbols.items;
- for (symbol_use_refs) |ref, i| {
+ for (symbol_use_refs, 0..) |ref, i| {
symbols[ref.innerIndex()].use_count_estimate -|= symbol_use_values[i].count_estimate;
}
@@ -4591,7 +4591,7 @@ fn NewParser_(
const namespace_ref = try p.newSymbol(.other, namespace_identifier);
try p.module_scope.generated.append(allocator, namespace_ref);
- for (imports) |alias, i| {
+ for (imports, 0..) |alias, i| {
const ref = symbols.get(alias) orelse unreachable;
const alias_name = if (@TypeOf(symbols) == RuntimeImports) RuntimeImports.all[alias] else alias;
clause_items[i] = js_ast.ClauseItem{
@@ -5455,7 +5455,7 @@ fn NewParser_(
}
}
- for (scope.children.items) |_, i| {
+ for (scope.children.items, 0..) |_, i| {
p.hoistSymbols(scope.children.items[i]);
}
}
@@ -5575,7 +5575,7 @@ fn NewParser_(
// p.markSyntaxFeature(Destructing)
var items = List(js_ast.ArrayBinding).initCapacity(p.allocator, ex.items.len) catch unreachable;
var is_spread = false;
- for (ex.items.slice()) |_, i| {
+ for (ex.items.slice(), 0..) |_, i| {
var item = ex.items.ptr[i];
if (item.data == .e_spread) {
is_spread = true;
@@ -6625,7 +6625,7 @@ fn NewParser_(
if (p.options.features.hoist_bun_plugin and strings.eqlComptime(path.text, "bun")) {
var plugin_i: usize = std.math.maxInt(usize);
const items = stmt.items;
- for (items) |item, i| {
+ for (items, 0..) |item, i| {
// Mark Bun.plugin()
// TODO: remove if they have multiple imports of the same name?
if (strings.eqlComptime(item.alias, "plugin")) {
@@ -9805,7 +9805,7 @@ fn NewParser_(
},
.b_array => |bind| {
- for (bind.items) |_, i| {
+ for (bind.items, 0..) |_, i| {
p.declareBinding(kind, &bind.items[i].binding, opts) catch unreachable;
}
},
@@ -12847,7 +12847,7 @@ fn NewParser_(
if (bun_plugin_usage_count_after > bun_plugin_usage_count_before) {
var previous_parts: []js_ast.Part = parts.items;
- for (previous_parts) |*previous_part, j| {
+ for (previous_parts, 0..) |*previous_part, j| {
if (previous_part.stmts.len == 0) continue;
const declared_symbols = previous_part.declared_symbols;
@@ -13300,7 +13300,7 @@ fn NewParser_(
};
const jsx_props = e_.properties.slice();
- for (jsx_props) |property, i| {
+ for (jsx_props, 0..) |property, i| {
if (property.kind != .spread) {
e_.properties.ptr[i].key = p.visitExpr(e_.properties.ptr[i].key.?);
}
@@ -14618,7 +14618,7 @@ fn NewParser_(
if (is_macro_ref)
p.options.ignore_dce_annotations = true;
- for (e_.args.slice()) |_, i| {
+ for (e_.args.slice(), 0..) |_, i| {
const arg = e_.args.ptr[i];
e_.args.ptr[i] = p.visitExpr(arg);
}
@@ -16776,7 +16776,7 @@ fn NewParser_(
array.items.len = @min(array.items.len, @truncate(u32, bound_array.items.len));
var slice = array.items.slice();
- for (bound_array.items[0..array.items.len]) |item, item_i| {
+ for (bound_array.items[0..array.items.len], 0..) |item, item_i| {
const child_expr = slice[item_i];
if (item.binding.data == .b_missing) {
slice[item_i] = p.newExpr(E.Missing{}, expr.loc);
@@ -17065,7 +17065,7 @@ fn NewParser_(
if (is_constructor) constructor_function = func;
- for (func.func.args) |arg, i| {
+ for (func.func.args, 0..) |arg, i| {
for (arg.ts_decorators.ptr[0..arg.ts_decorators.len]) |arg_decorator| {
var decorators = if (is_constructor) class.ts_decorators.listManaged(p.allocator) else prop.ts_decorators.listManaged(p.allocator);
const args = p.allocator.alloc(Expr, 2) catch unreachable;
@@ -17194,7 +17194,7 @@ fn NewParser_(
var constructor_stmts = ListManaged(Stmt).fromOwnedSlice(p.allocator, constructor_function.?.func.body.stmts);
// statements coming from class body inserted after super call or beginning of constructor.
var super_index: ?usize = null;
- for (constructor_stmts.items) |item, index| {
+ for (constructor_stmts.items, 0..) |item, index| {
if (item.data != .s_expr or item.data.s_expr.value.data != .e_call or item.data.s_expr.value.data.e_call.target.data != .e_super) continue;
super_index = index;
break;
@@ -17695,7 +17695,7 @@ fn NewParser_(
// if this is an expression, we can move statements after super() because there will be 0 decorators
var super_index: ?usize = null;
if (class.extends != null) {
- for (constructor.func.body.stmts) |stmt, index| {
+ for (constructor.func.body.stmts, 0..) |stmt, index| {
if (stmt.data != .s_expr or stmt.data.s_expr.value.data != .e_call or stmt.data.s_expr.value.data.e_call.target.data != .e_super) continue;
super_index = index;
break;
@@ -18175,7 +18175,7 @@ fn NewParser_(
}
// First, try converting the expressions to bindings
- for (items) |_, i| {
+ for (items, 0..) |_, i| {
var is_spread = false;
switch (items[i].data) {
.e_spread => |v| {
@@ -18407,7 +18407,7 @@ fn NewParser_(
var imports_list_i: u32 = 0;
var exports_list_i: u32 = 0;
- for (part.stmts) |_, i| {
+ for (part.stmts, 0..) |_, i| {
switch (part.stmts[i].data) {
.s_import => {
imports_list[imports_list_i] = part.stmts[i];
diff --git a/src/js_printer.zig b/src/js_printer.zig
index ce4138cd4..bacf0d448 100644
--- a/src/js_printer.zig
+++ b/src/js_printer.zig
@@ -705,7 +705,7 @@ pub fn NewPrinter(
p.writer.print(StringType, str);
},
[6]u8 => {
- const span = std.mem.span(&str);
+ const span = str[0..6];
p.writer.print(@TypeOf(span), span);
},
else => {
@@ -819,7 +819,7 @@ pub fn NewPrinter(
p.printIndent();
}
- for (import.items) |item, i| {
+ for (import.items, 0..) |item, i| {
if (i > 0) {
p.print(",");
p.printSpace();
@@ -1013,7 +1013,7 @@ pub fn NewPrinter(
p.print("(");
}
- for (args) |arg, i| {
+ for (args, 0..) |arg, i| {
if (i != 0) {
p.print(",");
p.printSpace();
@@ -2065,7 +2065,7 @@ pub fn NewPrinter(
p.options.indent += 1;
}
- for (items) |item, i| {
+ for (items, 0..) |item, i| {
if (i != 0) {
p.print(",");
if (e.is_single_line) {
@@ -2966,7 +2966,7 @@ pub fn NewPrinter(
if (b.items.len > 0) {
p.options.indent += @as(usize, @boolToInt(!b.is_single_line));
- for (b.items) |*item, i| {
+ for (b.items, 0..) |*item, i| {
if (i != 0) {
p.print(",");
if (b.is_single_line) {
@@ -3009,7 +3009,7 @@ pub fn NewPrinter(
p.options.indent +=
@as(usize, @boolToInt(!b.is_single_line));
- for (b.properties) |*property, i| {
+ for (b.properties, 0..) |*property, i| {
if (i != 0) {
p.print(",");
}
@@ -3392,7 +3392,7 @@ pub fn NewPrinter(
p.print("{");
p.printSpace();
const last = s.items.len - 1;
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
const symbol = p.symbols.getWithLink(item.name.ref.?).?;
const name = symbol.original_name;
var did_print = false;
@@ -3509,7 +3509,7 @@ pub fn NewPrinter(
p.printSpace();
}
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
if (i != 0) {
p.print(",");
if (s.is_single_line) {
@@ -3566,7 +3566,7 @@ pub fn NewPrinter(
// Avoid initializing an entire component library because you imported one icon
p.printLoadFromBundleWithoutCall(s.import_record_index);
p.print(",{");
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
p.printClauseAlias(item.alias);
p.print(":");
p.printQuotedUTF8(p.renamer.nameForSymbol(item.name.ref.?), true);
@@ -3592,7 +3592,7 @@ pub fn NewPrinter(
p.print("var {");
var symbol_counter: u32 = p.symbol_counter;
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
if (i > 0) {
p.print(",");
}
@@ -3618,7 +3618,7 @@ pub fn NewPrinter(
// reset symbol counter back
symbol_counter = p.symbol_counter;
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
if (i > 0) {
p.print(",");
}
@@ -3649,7 +3649,7 @@ pub fn NewPrinter(
p.printSpace();
}
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
if (i != 0) {
p.print(",");
if (s.is_single_line) {
@@ -4047,7 +4047,7 @@ pub fn NewPrinter(
p.printSpace();
p.print(",");
p.printSpace();
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
p.printClauseItemAs(item, .@"var");
if (i < s.items.len - 1) {
@@ -4057,7 +4057,7 @@ pub fn NewPrinter(
}
}
} else {
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
p.printClauseItemAs(item, .@"var");
if (i < s.items.len - 1) {
@@ -4096,7 +4096,7 @@ pub fn NewPrinter(
var needs_comma = false;
// This might be a determinsim issue
// But, it's not random
- skip: for (p.import_records) |_record, i| {
+ skip: for (p.import_records, 0..) |_record, i| {
if (!_record.is_bundled or _record.module_id == 0) continue;
if (i < last) {
@@ -4158,7 +4158,7 @@ pub fn NewPrinter(
p.options.unindent();
}
- for (s.items) |item, i| {
+ for (s.items, 0..) |item, i| {
if (i != 0) {
p.print(",");
if (s.is_single_line) {
diff --git a/src/json_parser.zig b/src/json_parser.zig
index b420cbd43..4c6843be4 100644
--- a/src/json_parser.zig
+++ b/src/json_parser.zig
@@ -628,7 +628,7 @@ pub fn toAST(
return toAST(allocator, string, @as(string, @tagName(value)));
},
- .ErrorSet => return try toAST(allocator, []const u8, std.mem.span(@errorName(value))),
+ .ErrorSet => return try toAST(allocator, []const u8, bun.asByteSlice(@errorName(value))),
.Union => |Union| {
const info = Union;
if (info.tag_type) |UnionTagType| {
diff --git a/src/libarchive/libarchive.zig b/src/libarchive/libarchive.zig
index adf9cdb4a..8d0e86d76 100644
--- a/src/libarchive/libarchive.zig
+++ b/src/libarchive/libarchive.zig
@@ -424,7 +424,7 @@ pub const Archive = struct {
// it will require us to pull in libiconv
// though we should probably validate the utf8 here nonetheless
var pathname: [:0]const u8 = std.mem.sliceTo(lib.archive_entry_pathname(entry).?, 0);
- var tokenizer = std.mem.tokenize(u8, std.mem.span(pathname), std.fs.path.sep_str);
+ var tokenizer = std.mem.tokenize(u8, bun.asByteSlice(pathname), std.fs.path.sep_str);
comptime var depth_i: usize = 0;
inline while (depth_i < depth_to_skip) : (depth_i += 1) {
if (tokenizer.next() == null) continue :loop;
@@ -432,7 +432,7 @@ pub const Archive = struct {
var pathname_ = tokenizer.rest();
pathname = std.mem.sliceTo(pathname_.ptr[0..pathname_.len :0], 0);
- const dirname = std.mem.trim(u8, std.fs.path.dirname(std.mem.span(pathname)) orelse "", std.fs.path.sep_str);
+ const dirname = std.mem.trim(u8, std.fs.path.dirname(bun.asByteSlice(pathname)) orelse "", std.fs.path.sep_str);
const size = @intCast(usize, std.math.max(lib.archive_entry_size(entry), 0));
if (size > 0) {
@@ -442,7 +442,7 @@ pub const Archive = struct {
if (stat.size > 0) {
const is_already_top_level = dirname.len == 0;
const path_to_use_: string = brk: {
- const __pathname: string = std.mem.span(pathname);
+ const __pathname: string = bun.asByteSlice(pathname);
if (is_already_top_level) break :brk __pathname;
@@ -501,11 +501,11 @@ pub const Archive = struct {
if (comptime ContextType != void and @hasDecl(std.meta.Child(ContextType), "onFirstDirectoryName")) {
if (appender.needs_first_dirname) {
- appender.onFirstDirectoryName(strings.withoutTrailingSlash(std.mem.span(pathname)));
+ appender.onFirstDirectoryName(strings.withoutTrailingSlash(bun.asByteSlice(pathname)));
}
}
- var tokenizer = std.mem.tokenize(u8, std.mem.span(pathname), std.fs.path.sep_str);
+ var tokenizer = std.mem.tokenize(u8, bun.asByteSlice(pathname), std.fs.path.sep_str);
comptime var depth_i: usize = 0;
inline while (depth_i < depth_to_skip) : (depth_i += 1) {
@@ -518,7 +518,7 @@ pub const Archive = struct {
const kind = C.kindFromMode(lib.archive_entry_filetype(entry));
- const slice = std.mem.span(pathname);
+ const slice = bun.asByteSlice(pathname);
if (comptime log) {
Output.prettyln(" {s}", .{pathname});
@@ -623,13 +623,13 @@ pub const Archive = struct {
lib.ARCHIVE_OK => break :possibly_retry,
lib.ARCHIVE_RETRY => {
if (comptime log) {
- Output.prettyErrorln("[libarchive] Error extracting {s}, retry {d} / {d}", .{ std.mem.span(pathname_), retries_remaining, 5 });
+ Output.prettyErrorln("[libarchive] Error extracting {s}, retry {d} / {d}", .{ pathname_, retries_remaining, 5 });
}
},
else => {
if (comptime log) {
const archive_error = std.mem.span(lib.archive_error_string(archive));
- Output.prettyErrorln("[libarchive] Error extracting {s}: {s}", .{ std.mem.span(pathname_), archive_error });
+ Output.prettyErrorln("[libarchive] Error extracting {s}: {s}", .{ pathname_, archive_error });
}
return error.Fail;
},
diff --git a/src/logger.zig b/src/logger.zig
index bd2c81c31..da06487b9 100644
--- a/src/logger.zig
+++ b/src/logger.zig
@@ -428,7 +428,7 @@ pub const Msg = struct {
.data = this.data.cloneWithBuilder(builder),
.metadata = this.metadata,
.notes = if (this.notes != null and this.notes.?.len > 0) brk: {
- for (this.notes.?) |note, i| {
+ for (this.notes.?, 0..) |note, i| {
notes[i] = note.cloneWithBuilder(builder);
}
break :brk notes[0..this.notes.?.len];
@@ -469,7 +469,7 @@ pub const Msg = struct {
if (this.notes) |notes| {
if (notes.len > 0) {
- for (notes) |note, i| {
+ for (notes, 0..) |note, i| {
_notes[i] = note.toAPI();
}
}
@@ -480,7 +480,7 @@ pub const Msg = struct {
pub fn toAPIFromList(comptime ListType: type, list: ListType, allocator: std.mem.Allocator) ![]Api.Message {
var out_list = try allocator.alloc(Api.Message, list.items.len);
- for (list.items) |item, i| {
+ for (list.items, 0..) |item, i| {
out_list[i] = try item.toAPI(allocator);
}
@@ -671,7 +671,7 @@ pub const Log = struct {
return JSC.JSValue.fromRef(JSC.BuildError.create(global, allocator, msg));
},
else => {
- for (msgs[0..count]) |msg, i| {
+ for (msgs[0..count], 0..) |msg, i| {
switch (msg.metadata) {
.build => {
errors_stack[i] = JSC.BuildError.create(global, allocator, msg).?;
diff --git a/src/main.zig b/src/main.zig
index 61e202788..ba3fd97d9 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -43,8 +43,3 @@ test "panic" {
pub const build_options = @import("build_options");
pub const bun = @import("./bun.zig");
-
-comptime {
- if (!bun.Environment.isRelease)
- _ = @import("compiler_rt");
-}
diff --git a/src/mdx/mdx_parser.zig b/src/mdx/mdx_parser.zig
index 79ce04fbb..bd55eadd2 100644
--- a/src/mdx/mdx_parser.zig
+++ b/src/mdx/mdx_parser.zig
@@ -1474,7 +1474,7 @@ pub const MDParser = struct {
// level of lists.
this.containers.len = 0;
var blocks = this.blocks.slice();
- for (blocks) |*block| {}
+ for (&blocks) |*block| {}
}
fn isContainerCompatible(pivot: *const Container, container: *const Container) bool {
// Block quote has no "items" like lists.
diff --git a/src/napi/napi.zig b/src/napi/napi.zig
index f044e2b06..b06e25d7e 100644
--- a/src/napi/napi.zig
+++ b/src/napi/napi.zig
@@ -231,7 +231,7 @@ pub export fn napi_create_array(env: napi_env, result: *napi_value) napi_status
}
const prefilled_undefined_args_array: [128]JSC.JSValue = brk: {
var args: [128]JSC.JSValue = undefined;
- for (args) |_, i| {
+ for (args, 0..) |_, i| {
args[i] = JSValue.jsUndefined();
}
break :brk args;
diff --git a/src/node_module_bundle.zig b/src/node_module_bundle.zig
index 5a052da18..4506d9070 100644
--- a/src/node_module_bundle.zig
+++ b/src/node_module_bundle.zig
@@ -99,7 +99,7 @@ pub const NodeModuleBundle = struct {
);
var prev_package_ids_for_name: []u32 = &[_]u32{};
- for (this.bundle.packages) |package, _package_id| {
+ for (this.bundle.packages, 0..) |package, _package_id| {
const package_id = @truncate(u32, _package_id);
std.debug.assert(package.hash != 0);
this.package_id_map.putAssumeCapacityNoClobber(package.hash, @truncate(u32, package_id));
@@ -201,7 +201,7 @@ pub const NodeModuleBundle = struct {
package: *const Api.JavascriptBundledPackage,
_query: string,
) ?u32 {
- for (modulesIn(&this.bundle, package)) |mod, i| {
+ for (modulesIn(&this.bundle, package), 0..) |mod, i| {
if (strings.eql(this.str(mod.path), _query)) {
return @truncate(u32, i + package.modules_offset);
}
@@ -233,7 +233,7 @@ pub const NodeModuleBundle = struct {
const traversal_length = std.math.min(lhs_name.len, rhs_name.len);
- for (lhs_name[0..traversal_length]) |char, i| {
+ for (lhs_name[0..traversal_length], 0..) |char, i| {
switch (std.math.order(char, rhs_name[i])) {
.lt, .gt => |order| {
return order;
@@ -291,7 +291,7 @@ pub const NodeModuleBundle = struct {
const traversal_length = std.math.min(lhs_name.len, rhs_name.len);
- for (lhs_name[0..traversal_length]) |char, i| {
+ for (lhs_name[0..traversal_length], 0..) |char, i| {
switch (std.math.order(char, rhs_name[i])) {
.lt, .gt => |order| {
return order;
@@ -386,7 +386,7 @@ pub const NodeModuleBundle = struct {
.{ this.str(pkg.name), this.str(pkg.version) },
);
- for (modules) |module, module_i| {
+ for (modules, 0..) |module, module_i| {
const size_level: SizeLevel =
switch (module.code.length) {
0...5_000 => .good,
diff --git a/src/open.zig b/src/open.zig
index 3224207c9..a496e9138 100644
--- a/src/open.zig
+++ b/src/open.zig
@@ -96,7 +96,7 @@ pub const Editor = enum(u8) {
inline for (default_preference_list) |editor| {
if (bin_name.get(editor)) |path| {
if (which(buf, PATH, cwd, path)) |bin| {
- out.* = std.mem.span(bin);
+ out.* = bun.asByteSlice(bin);
return editor;
}
}
@@ -111,7 +111,7 @@ pub const Editor = enum(u8) {
if (bin_name.get(editor)) |path| {
if (path.len > 0) {
if (which(buf, PATH, cwd, path)) |bin| {
- out.* = std.mem.span(bin);
+ out.* = bun.asByteSlice(bin);
return true;
}
}
@@ -126,7 +126,7 @@ pub const Editor = enum(u8) {
if (std.os.open(path, 0, 0)) |opened| {
std.os.close(opened);
if (out != null) {
- out.?.* = std.mem.span(path);
+ out.?.* = bun.asByteSlice(path);
}
return true;
} else |_| {}
diff --git a/src/options.zig b/src/options.zig
index 2169e4263..bf0c21d6b 100644
--- a/src/options.zig
+++ b/src/options.zig
@@ -70,7 +70,7 @@ pub fn stringHashMapFromArrays(comptime t: type, allocator: std.mem.Allocator, k
var hash_map = t.init(allocator);
if (keys.len > 0) {
try hash_map.ensureTotalCapacity(@intCast(u32, keys.len));
- for (keys) |key, i| {
+ for (keys, 0..) |key, i| {
hash_map.putAssumeCapacity(key, values[i]);
}
}
@@ -117,7 +117,7 @@ pub const ExternalModules = struct {
var result = ExternalModules{
.node_modules = std.BufSet.init(allocator),
.abs_paths = std.BufSet.init(allocator),
- .patterns = std.mem.span(default_wildcard_patterns),
+ .patterns = default_wildcard_patterns[0..],
};
switch (platform) {
@@ -144,7 +144,7 @@ pub const ExternalModules = struct {
}
var patterns = std.ArrayList(WildcardPattern).initCapacity(allocator, default_wildcard_patterns.len) catch unreachable;
- patterns.appendSliceAssumeCapacity(std.mem.span(default_wildcard_patterns));
+ patterns.appendSliceAssumeCapacity(default_wildcard_patterns[0..]);
for (externals) |external| {
const path = external;
@@ -1097,7 +1097,7 @@ pub fn loadersFromTransformOptions(allocator: std.mem.Allocator, _loaders: ?Api.
var loader_values = try allocator.alloc(Loader, input_loaders.loaders.len);
if (platform.isBun()) {
- for (loader_values) |_, i| {
+ for (loader_values, 0..) |_, i| {
const loader = switch (input_loaders.loaders[i]) {
.jsx => Loader.jsx,
.js => Loader.js,
@@ -1114,7 +1114,7 @@ pub fn loadersFromTransformOptions(allocator: std.mem.Allocator, _loaders: ?Api.
loader_values[i] = loader;
}
} else {
- for (loader_values) |_, i| {
+ for (loader_values, 0..) |_, i| {
const loader = switch (input_loaders.loaders[i]) {
.jsx => Loader.jsx,
.js => Loader.js,
@@ -1934,7 +1934,7 @@ pub const Env = struct {
try this.defaults.ensureTotalCapacity(this.allocator, defaults.keys.len);
- for (defaults.keys) |key, i| {
+ for (defaults.keys, 0..) |key, i| {
this.defaults.appendAssumeCapacity(.{ .key = key, .value = defaults.values[i] });
}
}
@@ -2240,7 +2240,7 @@ pub const RouteConfig = struct {
pub inline fn zero() RouteConfig {
return RouteConfig{
.dir = DefaultDir,
- .extensions = std.mem.span(&DefaultExtensions),
+ .extensions = DefaultExtensions[0..],
.static_dir = DefaultStaticDir,
.routes_enabled = false,
};
diff --git a/src/report.zig b/src/report.zig
index 62b807f0e..b3724e1d2 100644
--- a/src/report.zig
+++ b/src/report.zig
@@ -72,12 +72,12 @@ pub const CrashReportWriter = struct {
.{ base_dir, Global.package_json_version, @intCast(u64, @max(std.time.milliTimestamp(), 0)) },
) catch return;
- std.fs.cwd().makeDir(std.fs.path.dirname(std.mem.span(file_path)).?) catch {};
+ std.fs.cwd().makeDir(std.fs.path.dirname(bun.asByteSlice(file_path)).?) catch {};
var file = std.fs.cwd().createFileZ(file_path, .{ .truncate = true }) catch return;
this.file = std.io.bufferedWriter(
file.writer(),
);
- this.file_path = std.mem.span(file_path);
+ this.file_path = bun.asByteSlice(file_path);
}
pub fn printPath(this: *CrashReportWriter) void {
diff --git a/src/resolver/package_json.zig b/src/resolver/package_json.zig
index fb0c91b86..25b2ca673 100644
--- a/src/resolver/package_json.zig
+++ b/src/resolver/package_json.zig
@@ -1002,7 +1002,7 @@ pub const ExportsMap = struct {
},
.e_array => |e_array| {
var array = this.allocator.alloc(Entry, e_array.items.len) catch unreachable;
- for (e_array.items.slice()) |item, i| {
+ for (e_array.items.slice(), 0..) |item, i| {
array[i] = this.visit(item);
}
return Entry{
@@ -1025,7 +1025,7 @@ pub const ExportsMap = struct {
var is_conditional_sugar = false;
first_token.loc = expr.loc;
first_token.len = 1;
- for (e_obj.properties.slice()) |prop, i| {
+ for (e_obj.properties.slice(), 0..) |prop, i| {
const key: string = prop.key.?.data.e_string.string(this.allocator) catch unreachable;
const key_range: logger.Range = this.source.rangeOfString(prop.key.?.loc);
@@ -1154,7 +1154,7 @@ pub const ExportsMap = struct {
.map => {
var slice = this.data.map.list.slice();
const keys = slice.items(.key);
- for (keys) |key, i| {
+ for (keys, 0..) |key, i| {
if (strings.eql(key, key_)) {
return slice.items(.value)[i];
}
@@ -1697,7 +1697,7 @@ pub const ESModule = struct {
const slice = object.list.slice();
const keys = slice.items(.key);
- for (keys) |key, i| {
+ for (keys, 0..) |key, i| {
if (strings.eqlComptime(key, "default") or r.conditions.contains(key)) {
if (r.debug_logs) |log| {
log.addNoteFmt("The key \"{s}\" matched", .{key});
@@ -1852,7 +1852,7 @@ pub const ESModule = struct {
var slices = map.list.slice();
var keys = slices.items(.key);
var values = slices.items(.value);
- for (keys) |key, i| {
+ for (keys, 0..) |key, i| {
if (r.resolveTargetReverse(query, key, values[i], .exact)) |result| {
return result;
}
@@ -1935,7 +1935,7 @@ pub const ESModule = struct {
.map => |map| {
const slice = map.list.slice();
const keys = slice.items(.key);
- for (keys) |map_key, i| {
+ for (keys, 0..) |map_key, i| {
if (strings.eqlComptime(map_key, "default") or r.conditions.contains(map_key)) {
if (r.resolveTargetReverse(query, key, slice.items(.value)[i], kind)) |result| {
return result;
diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig
index 7be97a291..45c0262fd 100644
--- a/src/resolver/resolver.zig
+++ b/src/resolver/resolver.zig
@@ -709,7 +709,7 @@ pub const Resolver = struct {
const original_order = r.extension_order;
defer r.extension_order = original_order;
r.extension_order = switch (kind) {
- .url, .at_conditional, .at => std.mem.span(&options.BundleOptions.Defaults.CSSExtensionOrder),
+ .url, .at_conditional, .at => options.BundleOptions.Defaults.CSSExtensionOrder[0..],
.entry_point, .stmt, .dynamic => r.opts.esm_extension_order,
else => r.opts.extension_order,
};
@@ -1577,7 +1577,7 @@ pub const Resolver = struct {
string_buf = package_json.dependencies.source_buf;
}
- for (dependencies_list) |dependency, dependency_id| {
+ for (dependencies_list, 0..) |dependency, dependency_id| {
const dep_name = dependency.name.slice(string_buf);
if (dep_name.len == esm.name.len) {
if (!strings.eqlLong(dep_name, esm.name, false)) {
@@ -1839,7 +1839,7 @@ pub const Resolver = struct {
error.FileNotFound => unreachable,
else => {
// TODO: handle this error better
- r.log.addErrorFmt(null, logger.Loc.Empty, r.allocator, "Unable to open directory: {s}", .{std.mem.span(@errorName(err))}) catch unreachable;
+ r.log.addErrorFmt(null, logger.Loc.Empty, r.allocator, "Unable to open directory: {s}", .{bun.asByteSlice(@errorName(err))}) catch unreachable;
return err;
},
}
diff --git a/src/router.zig b/src/router.zig
index e29df954d..c7dadcdd3 100644
--- a/src/router.zig
+++ b/src/router.zig
@@ -364,7 +364,7 @@ const RouteLoader = struct {
var dynamic_start: ?usize = null;
var index_id: ?usize = null;
- for (this.all_routes.items) |route, i| {
+ for (this.all_routes.items, 0..) |route, i| {
if (@enumToInt(route.kind) > @enumToInt(Pattern.Tag.static) and dynamic_start == null) {
dynamic_start = i;
}
@@ -926,7 +926,8 @@ fn makeTest(cwd_path: string, data: anytype) !void {
try cwd.makePath(dir);
}
var file = try cwd.createFile(field.name, .{ .truncate = true });
- try file.writeAll(std.mem.span(value));
+ try file.writeAll(value);
+
file.close();
}
}
@@ -1540,7 +1541,7 @@ test "Pattern Match" {
}
if (comptime entries.len > 0) {
- for (parameters.items(.name)) |entry_name, i| {
+ for (parameters.items(.name), 0..) |entry_name, i| {
if (!strings.eql(entry_name, entries[i].name)) {
failures += 1;
Output.prettyErrorln("{s} -- Expected name <b>\"{s}\"<r> but received <b>\"{s}\"<r> for path {s}", .{ pattern, entries[i].name, parameters.get(i).name, pathname });
diff --git a/src/runtime.zig b/src/runtime.zig
index 2e9e06dcf..cfc9574ed 100644
--- a/src/runtime.zig
+++ b/src/runtime.zig
@@ -38,7 +38,7 @@ pub const ErrorCSS = struct {
var dirname = std.fs.selfExeDirPath(&out_buffer) catch unreachable;
var paths = [_]string{ dirname, BUN_ROOT, content.error_css_path };
const file = std.fs.cwd().openFile(
- resolve_path.joinAbsString(dirname, std.mem.span(&paths), .auto),
+ resolve_path.joinAbsString(dirname, &paths, .auto),
.{ .mode = .read_only },
) catch return embedDebugFallback(
"Missing packages/bun-error/bun-error.css. Please run \"make bun_error\"",
@@ -61,7 +61,7 @@ pub const ErrorJS = struct {
var dirname = std.fs.selfExeDirPath(&out_buffer) catch unreachable;
var paths = [_]string{ dirname, BUN_ROOT, content.error_js_path };
const file = std.fs.cwd().openFile(
- resolve_path.joinAbsString(dirname, std.mem.span(&paths), .auto),
+ resolve_path.joinAbsString(dirname, &paths, .auto),
.{ .mode = .read_only },
) catch return embedDebugFallback(
"Missing " ++ content.error_js_path ++ ". Please run \"make bun_error\"",
diff --git a/src/sha.zig b/src/sha.zig
index ec58954de..cda850d1f 100644
--- a/src/sha.zig
+++ b/src/sha.zig
@@ -188,7 +188,7 @@ pub fn main() anyerror!void {
var engine = BoringSSL.ENGINE_new().?;
- inline for (boring) |BoringHasher, i| {
+ inline for (boring, 0..) |BoringHasher, i| {
const ZigHasher = zig[i];
std.debug.print(
comptime labels[i] ++ " - hashing {.3f}:\n",
diff --git a/src/sourcemap/sourcemap.zig b/src/sourcemap/sourcemap.zig
index 54d58fbe7..3fa063e74 100644
--- a/src/sourcemap/sourcemap.zig
+++ b/src/sourcemap/sourcemap.zig
@@ -531,7 +531,7 @@ const base64_lut: [std.math.maxInt(u7)]u7 = brk: {
@setEvalBranchQuota(9999);
var bytes = [_]u7{std.math.maxInt(u7)} ** std.math.maxInt(u7);
- for (base64) |c, i| {
+ for (base64, 0..) |c, i| {
bytes[c] = i;
}
diff --git a/src/sourcemap/vlq_bench.zig b/src/sourcemap/vlq_bench.zig
index 2116025f9..ca5b1ed8e 100644
--- a/src/sourcemap/vlq_bench.zig
+++ b/src/sourcemap/vlq_bench.zig
@@ -94,7 +94,7 @@ const SourceMap = struct {
@setEvalBranchQuota(9999);
var bytes = [_]u7{std.math.maxInt(u7)} ** std.math.maxInt(u7);
- for (base64) |c, i| {
+ for (base64, 0..) |c, i| {
bytes[c] = i;
}
@@ -146,14 +146,14 @@ pub fn main() anyerror!void {
std.debug.print("Random values:\n\n", .{});
- for (numbers) |_, i| {
+ for (numbers, 0..) |_, i| {
numbers[i] = rand.random().int(i32);
}
{
var timer = try std.time.Timer.start();
- for (numbers) |n, i| {
+ for (numbers, 0..) |n, i| {
results[i] = SourceMap.encodeVLQ(n);
}
const elapsed = timer.read();
@@ -163,7 +163,7 @@ pub fn main() anyerror!void {
{
var timer = try std.time.Timer.start();
- for (numbers) |n, i| {
+ for (numbers, 0..) |n, i| {
results[i] = SourceMap.encodeVLQWithLookupTable(n);
}
const elapsed = timer.read();
@@ -173,7 +173,7 @@ pub fn main() anyerror!void {
{
var timer = try std.time.Timer.start();
- for (results) |n, i| {
+ for (results, 0..) |n, i| {
numbers[i] = SourceMap.decodeVLQ(n.bytes[0..n.len], 0).value;
}
@@ -196,7 +196,7 @@ pub fn main() anyerror!void {
var timer = try std.time.Timer.start();
var stream = std.io.fixedBufferStream(leb_buf);
var reader = stream.reader();
- for (numbers) |_, i| {
+ for (numbers, 0..) |_, i| {
numbers[i] = std.leb.readILEB128(i32, reader) catch unreachable;
}
const elapsed = timer.read();
@@ -205,14 +205,14 @@ pub fn main() anyerror!void {
std.debug.print("\nNumbers between 0 - 8096:\n\n", .{});
- for (numbers) |_, i| {
+ for (numbers, 0..) |_, i| {
numbers[i] = rand.random().intRangeAtMost(i32, 0, 8096);
}
{
var timer = try std.time.Timer.start();
- for (numbers) |n, i| {
+ for (numbers, 0..) |n, i| {
results[i] = SourceMap.encodeVLQ(n);
}
const elapsed = timer.read();
@@ -222,7 +222,7 @@ pub fn main() anyerror!void {
{
var timer = try std.time.Timer.start();
- for (numbers) |n, i| {
+ for (numbers, 0..) |n, i| {
results[i] = SourceMap.encodeVLQWithLookupTable(n);
}
const elapsed = timer.read();
@@ -232,7 +232,7 @@ pub fn main() anyerror!void {
{
var timer = try std.time.Timer.start();
- for (results) |n, i| {
+ for (results, 0..) |n, i| {
numbers[i] = SourceMap.decodeVLQ(n.bytes[0..n.len], 0).value;
}
@@ -255,7 +255,7 @@ pub fn main() anyerror!void {
var timer = try std.time.Timer.start();
var stream = std.io.fixedBufferStream(leb_buf);
var reader = stream.reader();
- for (numbers) |_, i| {
+ for (numbers, 0..) |_, i| {
numbers[i] = std.leb.readILEB128(i32, reader) catch unreachable;
}
const elapsed = timer.read();
@@ -264,14 +264,14 @@ pub fn main() anyerror!void {
std.debug.print("\nNumbers between 0 - 255:\n\n", .{});
- for (numbers) |_, i| {
+ for (numbers, 0..) |_, i| {
numbers[i] = rand.random().intRangeAtMost(i32, 0, 255);
}
{
var timer = try std.time.Timer.start();
- for (numbers) |n, i| {
+ for (numbers, 0..) |n, i| {
results[i] = SourceMap.encodeVLQ(n);
}
const elapsed = timer.read();
@@ -281,7 +281,7 @@ pub fn main() anyerror!void {
{
var timer = try std.time.Timer.start();
- for (numbers) |n, i| {
+ for (numbers, 0..) |n, i| {
results[i] = SourceMap.encodeVLQWithLookupTable(n);
}
const elapsed = timer.read();
@@ -291,7 +291,7 @@ pub fn main() anyerror!void {
{
var timer = try std.time.Timer.start();
- for (results) |n, i| {
+ for (results, 0..) |n, i| {
numbers[i] = SourceMap.decodeVLQ(n.bytes[0..n.len], 0).value;
}
@@ -314,7 +314,7 @@ pub fn main() anyerror!void {
var timer = try std.time.Timer.start();
var stream = std.io.fixedBufferStream(leb_buf);
var reader = stream.reader();
- for (numbers) |_, i| {
+ for (numbers, 0..) |_, i| {
numbers[i] = std.leb.readILEB128(i32, reader) catch unreachable;
}
const elapsed = timer.read();
diff --git a/src/string_immutable.zig b/src/string_immutable.zig
index d899ef39d..2f9612c23 100644
--- a/src/string_immutable.zig
+++ b/src/string_immutable.zig
@@ -27,7 +27,7 @@ pub fn toUTF16Literal(comptime str: []const u8) []const u16 {
comptime {
comptime var output: [str.len]u16 = undefined;
- for (str) |c, i| {
+ for (str, 0..) |c, i| {
output[i] = c;
}
@@ -41,7 +41,7 @@ pub fn toUTF16Literal(comptime str: []const u8) []const u16 {
const OptionalUsize = std.meta.Int(.unsigned, @bitSizeOf(usize) - 1);
pub fn indexOfAny(self: string, comptime str: anytype) ?OptionalUsize {
- for (self) |c, i| {
+ for (self, 0..) |c, i| {
inline for (str) |a| {
if (c == a) {
return @intCast(OptionalUsize, i);
@@ -52,7 +52,7 @@ pub fn indexOfAny(self: string, comptime str: anytype) ?OptionalUsize {
return null;
}
pub fn indexOfAny16(self: []const u16, comptime str: anytype) ?OptionalUsize {
- for (self) |c, i| {
+ for (self, 0..) |c, i| {
inline for (str) |a| {
if (c == a) {
return @intCast(OptionalUsize, i);
@@ -100,7 +100,7 @@ pub inline fn isNPMPackageName(target: string) bool {
else => return false,
};
var slash_index: usize = 0;
- for (target[1..]) |c, i| {
+ for (target[1..], 0..) |c, i| {
switch (c) {
// Old packages may have capital letters
'A'...'Z', 'a'...'z', '0'...'9', '$', '-', '_', '.' => {},
@@ -117,12 +117,12 @@ pub inline fn isNPMPackageName(target: string) bool {
}
pub inline fn indexAny(in: anytype, target: string) ?usize {
- for (in) |str, i| if (indexOf(str, target) != null) return i;
+ for (in, 0..) |str, i| if (indexOf(str, target) != null) return i;
return null;
}
pub inline fn indexAnyComptime(target: string, comptime chars: string) ?usize {
- for (target) |parent, i| {
+ for (target, 0..) |parent, i| {
inline for (chars) |char| {
if (char == parent) return i;
}
@@ -371,7 +371,7 @@ pub fn copyLowercase(in: string, out: []u8) string {
var out_slice: []u8 = out[0..in.len];
begin: while (out_slice.len > 0) {
- for (in_slice) |c, i| {
+ for (in_slice, 0..) |c, i| {
switch (c) {
'A'...'Z' => {
// @memcpy(out_slice.ptr, in_slice.ptr, i);
@@ -401,7 +401,7 @@ pub fn copyLowercaseIfNeeded(in: string, out: []u8) string {
var any = false;
begin: while (out_slice.len > 0) {
- for (in_slice) |c, i| {
+ for (in_slice, 0..) |c, i| {
switch (c) {
'A'...'Z' => {
@memcpy(out_slice.ptr, in_slice.ptr, i);
@@ -711,7 +711,7 @@ pub fn eql(self: string, other: anytype) bool {
return eql(self, other.*);
}
- for (self) |c, i| {
+ for (self, 0..) |c, i| {
if (other[i] != c) return false;
}
return true;
@@ -752,7 +752,7 @@ inline fn eqlComptimeCheckLenWithKnownType(comptime Type: type, a: []const Type,
const len = comptime b.len;
comptime var dword_length = b.len >> 3;
- const slice = comptime if (@typeInfo(@TypeOf(b)) != .Pointer) b else std.mem.span(b);
+ const slice = b;
const divisor = comptime @sizeOf(Type);
comptime var b_ptr: usize = 0;
@@ -794,11 +794,7 @@ inline fn eqlComptimeCheckLenWithKnownType(comptime Type: type, a: []const Type,
/// strings.eqlComptime(input, "hello world");
/// strings.eqlComptime(input, "hai");
pub inline fn eqlComptimeCheckLenWithType(comptime Type: type, a: []const Type, comptime b: anytype, comptime check_len: bool) bool {
- if (@typeInfo(@TypeOf(b)) != .Pointer) {
- return eqlComptimeCheckLenWithKnownType(comptime Type, a, &b, comptime check_len);
- } else {
- return eqlComptimeCheckLenWithKnownType(comptime Type, a, b, comptime check_len);
- }
+ return eqlComptimeCheckLenWithKnownType(comptime Type, a, if (@typeInfo(@TypeOf(b)) != .Pointer) &b else b, comptime check_len);
}
pub fn eqlCaseInsensitiveASCII(a: string, comptime b: anytype, comptime check_len: bool) bool {
@@ -814,7 +810,7 @@ pub fn eqlCaseInsensitiveASCII(a: string, comptime b: anytype, comptime check_le
}
// pray to the auto vectorization gods
- inline for (b) |c, i| {
+ inline for (b, 0..) |c, i| {
const char = comptime std.ascii.toLower(c);
if (char != std.ascii.toLower(a[i])) return false;
}
@@ -980,7 +976,7 @@ pub fn copyU8IntoU16WithAlignment(comptime alignment: u21, output_: []align(alig
return;
}
- for (input) |c, i| {
+ for (input, 0..) |c, i| {
output[i] = c;
}
}
@@ -1845,7 +1841,7 @@ pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8
const Scalar = struct {
pub const lengths: [std.math.maxInt(u8)]u4 = brk: {
var values: [std.math.maxInt(u8)]u4 = undefined;
- for (values) |_, i| {
+ for (values, 0..) |_, i| {
switch (i) {
'"' => {
values[i] = "&quot;".len;
@@ -1990,7 +1986,7 @@ pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8
const vec_chars = "\"&'<>";
const vecs: [vec_chars.len]AsciiVector = comptime brk: {
var _vecs: [vec_chars.len]AsciiVector = undefined;
- for (vec_chars) |c, i| {
+ for (vec_chars, 0..) |c, i| {
_vecs[i] = @splat(ascii_vector_size, c);
}
break :brk _vecs;
@@ -2187,7 +2183,7 @@ pub fn escapeHTMLForUTF16Input(allocator: std.mem.Allocator, utf16: []const u16)
const Scalar = struct {
pub const lengths: [std.math.maxInt(u8)]u4 = brk: {
var values: [std.math.maxInt(u8)]u4 = undefined;
- for (values) |_, i| {
+ for (values, 0..) |_, i| {
values[i] = switch (i) {
'"' => "&quot;".len,
'&' => "&amp;".len,
@@ -2252,7 +2248,7 @@ pub fn escapeHTMLForUTF16Input(allocator: std.mem.Allocator, utf16: []const u16)
const vec_chars = "\"&'<>";
const vecs: [vec_chars.len]AsciiU16Vector = brk: {
var _vecs: [vec_chars.len]AsciiU16Vector = undefined;
- for (vec_chars) |c, i| {
+ for (vec_chars, 0..) |c, i| {
_vecs[i] = @splat(ascii_u16_vector_size, @as(u16, c));
}
break :brk _vecs;
@@ -3192,7 +3188,7 @@ pub fn indexOfChar(slice: []const u8, char: u8) ?u32 {
}
}
- for (remaining) |c, i| {
+ for (remaining, 0..) |c, i| {
if (c == char) {
return @truncate(u32, i + (slice.len - remaining.len));
}
@@ -3334,7 +3330,7 @@ pub fn encodeBytesToHex(destination: []u8, source: []const u8) usize {
test "decodeHexToBytes" {
var buffer = std.mem.zeroes([1024]u8);
- for (buffer) |_, i| {
+ for (buffer, 0..) |_, i| {
buffer[i] = @truncate(u8, i % 256);
}
var written: [2048]u8 = undefined;
@@ -3529,7 +3525,7 @@ pub fn @"nextUTF16NonASCIIOr$`\\"(
}
}
- for (remaining) |char, i| {
+ for (remaining, 0..) |char, i| {
switch (char) {
'$', '`', '\\', 0...0x20 - 1, 128...std.math.maxInt(u16) => {
return @truncate(u32, i + (slice.len - remaining.len));
@@ -3587,27 +3583,27 @@ test "firstNonASCII" {
test "firstNonASCII16" {
@setEvalBranchQuota(99999);
- const yes = std.mem.span(toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
+ const yes = std.mem.bytesAsSlice(u16, toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
try std.testing.expectEqual(true, firstNonASCII16(@TypeOf(yes), yes) == null);
{
@setEvalBranchQuota(99999);
- const no = std.mem.span(toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdoka🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
+ const no = std.mem.bytesAsSlice(u16, toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdoka🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
try std.testing.expectEqual(@as(u32, 50), firstNonASCII16(@TypeOf(no), no).?);
}
{
@setEvalBranchQuota(99999);
- const no = std.mem.span(toUTF16Literal("🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
+ const no = std.mem.bytesAsSlice(u16, toUTF16Literal("🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
try std.testing.expectEqual(@as(u32, 0), firstNonASCII16(@TypeOf(no), no).?);
}
{
@setEvalBranchQuota(99999);
- const no = std.mem.span(toUTF16Literal("a🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
+ const no = std.mem.bytesAsSlice(u16, toUTF16Literal("a🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"));
try std.testing.expectEqual(@as(u32, 1), firstNonASCII16(@TypeOf(no), no).?);
}
{
@setEvalBranchQuota(99999);
- const no = std.mem.span(toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd12312🙂3"));
+ const no = std.mem.bytesAsSlice(u16, toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd12312🙂3"));
try std.testing.expectEqual(@as(u32, 366), firstNonASCII16(@TypeOf(no), no).?);
}
}
diff --git a/src/string_mutable.zig b/src/string_mutable.zig
index 0d20fed6a..d7b0cf930 100644
--- a/src/string_mutable.zig
+++ b/src/string_mutable.zig
@@ -63,7 +63,7 @@ pub const MutableString = struct {
pub const ensureUnusedCapacity = growIfNeeded;
pub fn initCopy(allocator: std.mem.Allocator, str: anytype) !MutableString {
- var mutable = try MutableString.init(allocator, std.mem.len(str));
+ var mutable = try MutableString.init(allocator, str.len);
try mutable.copy(str);
return mutable;
}
@@ -145,12 +145,12 @@ pub const MutableString = struct {
}
pub fn copy(self: *MutableString, str: anytype) !void {
- try self.list.ensureTotalCapacity(self.allocator, std.mem.len(str[0..]));
+ try self.list.ensureTotalCapacity(self.allocator, str[0..].len);
if (self.list.items.len == 0) {
try self.list.insertSlice(self.allocator, 0, str);
} else {
- try self.list.replaceRange(self.allocator, 0, std.mem.len(str[0..]), str[0..]);
+ try self.list.replaceRange(self.allocator, 0, str[0..].len, str[0..]);
}
}
diff --git a/src/sync.zig b/src/sync.zig
index 0fad16736..ec3d57c5d 100644
--- a/src/sync.zig
+++ b/src/sync.zig
@@ -31,7 +31,7 @@ pub const ThreadPool = struct {
const num_workers = std.math.max(1, config.max_threads orelse std.Thread.cpuCount() catch 1);
self.workers = try self.allocator.alloc(Worker, num_workers);
- for (self.workers) |*worker| {
+ for (&self.workers) |*worker| {
try worker.init(self);
@atomicStore(usize, &self.spawned, self.spawned + 1, .SeqCst);
}
@@ -40,7 +40,7 @@ pub const ThreadPool = struct {
pub fn deinit(self: *ThreadPool) void {
self.shutdown();
- for (self.workers[0..self.spawned]) |*worker|
+ for (&self.workers[0..self.spawned]) |*worker|
worker.deinit();
while (self.run_queue.pop()) |run_node|
diff --git a/src/tagged_pointer.zig b/src/tagged_pointer.zig
index 99d8a0b4d..6a8f6defa 100644
--- a/src/tagged_pointer.zig
+++ b/src/tagged_pointer.zig
@@ -55,7 +55,7 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
var enumFields: [Types.len]std.builtin.Type.EnumField = undefined;
var decls = [_]std.builtin.Type.Declaration{};
- inline for (Types) |field, i| {
+ inline for (Types, 0..) |field, i| {
enumFields[i] = .{
.name = comptime typeBaseName(@typeName(field)),
.value = 1024 - i,
@@ -75,7 +75,7 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
var enumFields: [Fields.len]std.builtin.Type.EnumField = undefined;
var decls = [_]std.builtin.Type.Declaration{};
- inline for (Fields) |field, i| {
+ inline for (Fields, 0..) |field, i| {
enumFields[i] = .{
.name = comptime typeBaseName(@typeName(field.default_value.?)),
.value = 1024 - i,
diff --git a/src/url.zig b/src/url.zig
index eec4b5769..034a90ecf 100644
--- a/src/url.zig
+++ b/src/url.zig
@@ -1464,7 +1464,7 @@ test "QueryStringMap (full)" {
var target: [fixture.ext.len]string = undefined;
try expect((map.getAll("ext", &target)) == fixture.ext.len);
- for (target) |item, i| {
+ for (target, 0..) |item, i| {
try expectString(
fixture.ext[i],
item,
@@ -1478,7 +1478,7 @@ test "QueryStringMap not encoded" {
.hey = "1",
.wow = "true",
};
- const url_slice = std.mem.span(url);
+ const url_slice = bun.asByteSlice(url);
var map = (try QueryStringMap.init(std.testing.allocator, url_slice)) orelse return try std.testing.expect(false);
try expect(map.buffer.len == 0);
try expect(url_slice.ptr == map.slice.ptr);
@@ -1522,7 +1522,7 @@ test "QueryStringMap Iterator" {
var map = (try QueryStringMap.init(std.testing.allocator, url)) orelse return try std.testing.expect(false);
defer map.deinit();
var buf_: [48]string = undefined;
- var buf = std.mem.span(&buf_);
+ var buf = buf_[0..48];
var iter = map.iter();
var result: QueryStringMap.Iterator.Result = iter.next(buf) orelse return try expect(false);
@@ -1592,7 +1592,7 @@ test "QueryStringMap Iterator" {
result = iter.next(buf) orelse return try expect(false);
try expectString("ext", result.name);
try expectEqual(result.values.len, fixture.ext.len);
- for (fixture.ext) |ext, i| {
+ for (fixture.ext, 0..) |ext, i| {
try expectString(ext, result.values[i]);
}
diff --git a/src/walker_skippable.zig b/src/walker_skippable.zig
index 489a46d0b..880bed94d 100644
--- a/src/walker_skippable.zig
+++ b/src/walker_skippable.zig
@@ -149,7 +149,7 @@ pub fn walk(
var skip_filenames_ = skip_names[0..skip_name_i];
var skip_dirnames_ = skip_names[skip_name_i..];
- for (skip_dirnames) |name, i| {
+ for (skip_dirnames, 0..) |name, i| {
skip_dirnames_[i] = std.hash.Wyhash.hash(seed, name);
}
diff --git a/src/watcher.zig b/src/watcher.zig
index 5b3fa5778..f35c16bc0 100644
--- a/src/watcher.zig
+++ b/src/watcher.zig
@@ -582,7 +582,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
var last_event_index: usize = 0;
var last_event_id: INotify.EventListIndex = std.math.maxInt(INotify.EventListIndex);
- for (all_events) |_, i| {
+ for (all_events, 0..) |_, i| {
if (all_events[i].name_len > 0) {
this.changed_filepaths[name_off] = temp_name_list[all_events[i].name_off];
all_events[i].name_off = name_off;
@@ -609,7 +609,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
}
pub fn indexOf(this: *Watcher, hash: HashType) ?u32 {
- for (this.watchlist.items(.hash)) |other, i| {
+ for (this.watchlist.items(.hash), 0..) |other, i| {
if (hash == other) {
return @truncate(u32, i);
}
@@ -658,7 +658,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
const watchlist_id = this.watchlist.len;
const file_path_: string = if (comptime copy_file_path)
- std.mem.span(try this.allocator.dupeZ(u8, file_path))
+ bun.asByteSlice(try this.allocator.dupeZ(u8, file_path))
else
file_path;
@@ -704,7 +704,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
}
this.watchlist.appendAssumeCapacity(.{
- .file_path = std.mem.span(file_path_),
+ .file_path = file_path_,
.fd = fd,
.hash = hash,
.count = 0,
@@ -734,7 +734,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
var index: PlatformWatcher.EventListIndex = std.math.maxInt(PlatformWatcher.EventListIndex);
const file_path_: string = if (comptime copy_file_path)
- std.mem.span(try this.allocator.dupeZ(u8, file_path))
+ bun.asByteSlice(try this.allocator.dupeZ(u8, file_path))
else
file_path;
diff --git a/src/zlib.zig b/src/zlib.zig
index e161d4d79..5d94b02c5 100644
--- a/src/zlib.zig
+++ b/src/zlib.zig
@@ -1,10 +1,11 @@
// @link "deps/zlib/libz.a"
const std = @import("std");
+const bun = @import("bun");
test "Zlib Read" {
const expected_text = @embedFile("./zlib.test.txt");
- const input = std.mem.span(@embedFile("./zlib.test.gz"));
+ const input = bun.asByteSlice(@embedFile("./zlib.test.gz"));
std.debug.print("zStream Size: {d}", .{@sizeOf(zStream_struct)});
var output = std.ArrayList(u8).init(std.heap.c_allocator);
var writer = output.writer();
@@ -19,7 +20,7 @@ test "Zlib Read" {
test "ZlibArrayList Read" {
const expected_text = @embedFile("./zlib.test.txt");
- const input = std.mem.span(@embedFile("./zlib.test.gz"));
+ const input = bun.asByteSlice(@embedFile("./zlib.test.gz"));
std.debug.print("zStream Size: {d}", .{@sizeOf(zStream_struct)});
var list = std.ArrayListUnmanaged(u8){};
try list.ensureUnusedCapacity(std.heap.c_allocator, 4096);
diff --git a/test/bun.js/bunExe.ts b/test/bun.js/bunExe.ts
index 2f1a89cd2..a66f702de 100644
--- a/test/bun.js/bunExe.ts
+++ b/test/bun.js/bunExe.ts
@@ -1,7 +1,3 @@
export function bunExe() {
- if (Bun.version.includes("debug")) {
- return "bun-debug";
- }
-
- return "bun";
+ return process.execPath;
}
diff --git a/test/bun.js/test-test.test.ts b/test/bun.js/test-test.test.ts
index 06573cc7d..cc6d967c2 100644
--- a/test/bun.js/test-test.test.ts
+++ b/test/bun.js/test-test.test.ts
@@ -2069,12 +2069,12 @@ it("should return non-zero exit code for invalid syntax", async () => {
try {
await writeFile(join(test_dir, "bad.test.js"), "!!!");
const { stdout, stderr, exited } = spawn({
- cmd: [bunExe(), "wiptest", "bad.test.js"],
+ cmd: [bunExe(), "test", "bad.test.js"],
cwd: test_dir,
stdout: null,
stdin: "pipe",
stderr: "pipe",
- bunEnv,
+ env: bunEnv,
});
const err = await new Response(stderr).text();
expect(err).toContain("error: Unexpected end of file");