aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/zig-fmt.yml2
-rw-r--r--Dockerfile2
-rw-r--r--bench/hot-module-reloading/css-stress-test/color-looper.emotion.zig26
-rw-r--r--bench/hot-module-reloading/css-stress-test/color-looper.zig26
-rw-r--r--build.zig9
-rw-r--r--docs/project/development.md2
-rw-r--r--misctools/fetch.zig2
-rw-r--r--misctools/http_bench.zig8
-rw-r--r--src/ArenaAllocator.zig12
-rw-r--r--src/__global.zig2
-rw-r--r--src/allocators.zig16
-rw-r--r--src/analytics/analytics_schema.zig2
-rw-r--r--src/analytics/analytics_thread.zig10
-rw-r--r--src/api/demo/schema.zig46
-rw-r--r--src/api/schema.zig46
-rw-r--r--src/ast/base.zig2
-rw-r--r--src/baby_list.zig2
-rw-r--r--src/bench/string-handling.zig2
-rw-r--r--src/bit_set.zig8
-rw-r--r--src/blob.zig4
-rw-r--r--src/boringssl.zig3
-rw-r--r--src/bun.js/api/JSBundler.zig6
-rw-r--r--src/bun.js/api/JSTranspiler.zig10
-rw-r--r--src/bun.js/api/bun.zig92
-rw-r--r--src/bun.js/api/bun/dns_resolver.zig14
-rw-r--r--src/bun.js/api/bun/socket.zig18
-rw-r--r--src/bun.js/api/bun/subprocess.zig6
-rw-r--r--src/bun.js/api/ffi.zig30
-rw-r--r--src/bun.js/api/html_rewriter.zig4
-rw-r--r--src/bun.js/api/server.zig34
-rw-r--r--src/bun.js/base.zig68
-rw-r--r--src/bun.js/bindings/FFI.zig14
-rw-r--r--src/bun.js/bindings/bindings.zig118
-rw-r--r--src/bun.js/bindings/exports.zig44
-rw-r--r--src/bun.js/bindings/header-gen.zig6
-rw-r--r--src/bun.js/bindings/shimmer.zig2
-rw-r--r--src/bun.js/javascript.zig20
-rw-r--r--src/bun.js/javascript_core_c_api.zig54
-rw-r--r--src/bun.js/module_loader.zig2
-rw-r--r--src/bun.js/node/buffer.zig2
-rw-r--r--src/bun.js/node/dir_iterator.zig54
-rw-r--r--src/bun.js/node/node_fs.zig34
-rw-r--r--src/bun.js/node/node_fs_constant.zig6
-rw-r--r--src/bun.js/node/node_os.zig6
-rw-r--r--src/bun.js/node/os/constants.zig4
-rw-r--r--src/bun.js/node/syscall.zig30
-rw-r--r--src/bun.js/node/types.zig62
-rw-r--r--src/bun.js/test/jest.zig8
-rw-r--r--src/bun.js/test/pretty_format.zig10
-rw-r--r--src/bun.js/webcore.zig2
-rw-r--r--src/bun.js/webcore/blob.zig20
-rw-r--r--src/bun.js/webcore/encoding.zig57
-rw-r--r--src/bun.js/webcore/request.zig6
-rw-r--r--src/bun.js/webcore/response.zig14
-rw-r--r--src/bun.js/webcore/streams.zig43
-rw-r--r--src/bun.zig50
-rw-r--r--src/bun_js.zig2
-rw-r--r--src/bundler.zig2
-rw-r--r--src/bundler/bundle_v2.zig76
-rw-r--r--src/bundler/entry_points.zig4
-rw-r--r--src/c.zig50
-rw-r--r--src/cli.zig6
-rw-r--r--src/cli/add_completions.zig2
-rw-r--r--src/cli/build_command.zig16
-rw-r--r--src/cli/bunx_command.zig4
-rw-r--r--src/cli/create_command.zig32
-rw-r--r--src/cli/init_command.zig2
-rw-r--r--src/cli/list-of-yarn-commands.zig5
-rw-r--r--src/cli/package_manager_command.zig6
-rw-r--r--src/cli/run_command.zig2
-rw-r--r--src/cli/upgrade_command.zig6
-rw-r--r--src/comptime_string_map.zig8
-rw-r--r--src/copy_file.zig2
-rw-r--r--src/crash_reporter.zig10
-rw-r--r--src/css_scanner.zig4
-rw-r--r--src/darwin_c.zig14
-rw-r--r--src/defines-table.zig4
-rw-r--r--src/defines.zig4
-rw-r--r--src/deps/boringssl.translated.zig20
-rw-r--r--src/deps/c_ares.zig13
-rw-r--r--src/deps/diffz/DiffMatchPatch.zig16
-rw-r--r--src/deps/lol-html.zig4
-rw-r--r--src/deps/picohttp.zig4
-rw-r--r--src/deps/uws.zig44
-rw-r--r--src/deps/zig-clap/clap.zig2
-rw-r--r--src/deps/zig-datetime/src/datetime.zig26
-rw-r--r--src/env_loader.zig36
-rw-r--r--src/exact_size_matcher.zig11
-rw-r--r--src/fs.zig20
-rw-r--r--src/futex.zig8
-rw-r--r--src/hive_array.zig6
-rw-r--r--src/http.zig37
-rw-r--r--src/http/websocket.zig8
-rw-r--r--src/http/websocket_http_client.zig26
-rw-r--r--src/http_client_async.zig41
-rw-r--r--src/import_record.zig2
-rw-r--r--src/install/bin.zig30
-rw-r--r--src/install/dependency.zig48
-rw-r--r--src/install/install.zig86
-rw-r--r--src/install/integrity.zig4
-rw-r--r--src/install/lockfile.zig67
-rw-r--r--src/install/npm.zig52
-rw-r--r--src/install/resolution.zig2
-rw-r--r--src/install/resolvers/folder_resolver.zig6
-rw-r--r--src/install/semver.zig24
-rw-r--r--src/io/io_darwin.zig12
-rw-r--r--src/io/io_linux.zig60
-rw-r--r--src/js_ast.zig122
-rw-r--r--src/js_lexer.zig28
-rw-r--r--src/js_lexer/identifier.zig16
-rw-r--r--src/js_lexer_tables.zig7
-rw-r--r--src/js_parser.zig107
-rw-r--r--src/js_printer.zig24
-rw-r--r--src/json_parser.zig4
-rw-r--r--src/libarchive/libarchive.zig30
-rw-r--r--src/linear_fifo.zig18
-rw-r--r--src/linker.zig8
-rw-r--r--src/linux_c.zig12
-rw-r--r--src/lock.zig7
-rw-r--r--src/logger.zig16
-rw-r--r--src/main_wasm.zig10
-rw-r--r--src/multi_array_list.zig35
-rw-r--r--src/napi/napi.zig21
-rw-r--r--src/network_thread.zig9
-rw-r--r--src/node_fallbacks.zig55
-rw-r--r--src/node_module_bundle.zig20
-rw-r--r--src/options.zig4
-rw-r--r--src/output.zig18
-rw-r--r--src/renamer.zig12
-rw-r--r--src/report.zig10
-rw-r--r--src/resolver/package_json.zig18
-rw-r--r--src/resolver/resolve_path.zig4
-rw-r--r--src/resolver/resolver.zig13
-rw-r--r--src/resolver/tsconfig_json.zig2
-rw-r--r--src/router.zig32
-rw-r--r--src/runtime.zig2
-rw-r--r--src/sha.zig10
-rw-r--r--src/sourcemap/sourcemap.zig22
-rw-r--r--src/standalone_bun.zig4
-rw-r--r--src/string_immutable.zig179
-rw-r--r--src/string_joiner.zig11
-rw-r--r--src/string_mutable.zig4
-rw-r--r--src/string_types.zig12
-rw-r--r--src/sync.zig10
-rw-r--r--src/tagged_pointer.zig18
-rw-r--r--src/thread_pool.zig12
-rw-r--r--src/toml/toml_lexer.zig8
-rw-r--r--src/url.zig30
-rw-r--r--src/util.zig2
-rw-r--r--src/walker_skippable.zig19
-rw-r--r--src/watcher.zig14
-rw-r--r--src/wyhash.zig179
152 files changed, 1772 insertions, 1584 deletions
diff --git a/.github/workflows/zig-fmt.yml b/.github/workflows/zig-fmt.yml
index 4d65a935c..fa904a07e 100644
--- a/.github/workflows/zig-fmt.yml
+++ b/.github/workflows/zig-fmt.yml
@@ -1,7 +1,7 @@
name: zig-fmt
env:
- ZIG_VERSION: 0.11.0-dev.2571+31738de28
+ ZIG_VERSION: 0.11.0-dev.3737+9eb008717
on:
pull_request:
diff --git a/Dockerfile b/Dockerfile
index f76cc7811..19d071e93 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -12,7 +12,7 @@ ARG TRIPLET=${ARCH}-linux-gnu
ARG BUILDARCH=amd64
ARG WEBKIT_TAG=may20
ARG ZIG_TAG=jul1
-ARG ZIG_VERSION="0.11.0-dev.2571+31738de28"
+ARG ZIG_VERSION="0.11.0-dev.3737+9eb008717"
ARG WEBKIT_BASENAME="bun-webkit-linux-$BUILDARCH"
ARG ZIG_FOLDERNAME=zig-linux-${BUILD_MACHINE_ARCH}-${ZIG_VERSION}
diff --git a/bench/hot-module-reloading/css-stress-test/color-looper.emotion.zig b/bench/hot-module-reloading/css-stress-test/color-looper.emotion.zig
index 9b7a83cf3..02ab05c54 100644
--- a/bench/hot-module-reloading/css-stress-test/color-looper.emotion.zig
+++ b/bench/hot-module-reloading/css-stress-test/color-looper.emotion.zig
@@ -128,27 +128,27 @@ pub fn main() anyerror!void {
counters[counter].timestamp = @truncate(u64, @intCast(u128, std.time.nanoTimestamp()) / (std.time.ns_per_ms / 10));
counters[counter].rotate = rotate % 360;
counters[counter].percent = std.math.mod(f64, std.math.round(((progress_bar + 1.0) / destination_count) * 1000) / 1000, 100) catch 0;
- counters[counter].color_values[0] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[1] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[2] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[0] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[0][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[1] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[0][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[2] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[0][2] + 1) % 256)) * 0.8));
counters[counter].color_values[3] = (colors[0][0] + 1) % 256;
counters[counter].color_values[4] = (colors[0][1] + 1) % 256;
counters[counter].color_values[5] = (colors[0][2] + 1) % 256;
- counters[counter].color_values[6] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[7] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[8] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[6] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[1][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[7] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[1][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[8] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[1][2] + 1) % 256)) * 0.8));
counters[counter].color_values[9] = (colors[1][0] + 1) % 256;
counters[counter].color_values[10] = (colors[1][1] + 1) % 256;
counters[counter].color_values[11] = (colors[1][2] + 1) % 256;
- counters[counter].color_values[12] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[13] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[14] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[12] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[2][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[13] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[2][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[14] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[2][2] + 1) % 256)) * 0.8));
counters[counter].color_values[15] = (colors[2][0] + 1) % 256;
counters[counter].color_values[16] = (colors[2][1] + 1) % 256;
counters[counter].color_values[17] = (colors[2][2] + 1) % 256;
- counters[counter].color_values[18] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[19] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[20] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[18] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[3][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[19] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[3][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[20] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[3][2] + 1) % 256)) * 0.8));
counters[counter].color_values[21] = (colors[3][0] + 1) % 256;
counters[counter].color_values[22] = (colors[3][1] + 1) % 256;
counters[counter].color_values[23] = (colors[3][2] + 1) % 256;
@@ -203,7 +203,7 @@ pub fn main() anyerror!void {
_ = try recorder.wait();
all_timestamps[0] = wrote.len;
- for (counters) |count, i| {
+ for (counters, 0..) |count, i| {
all_timestamps[i + 1] = count.timestamp;
}
diff --git a/bench/hot-module-reloading/css-stress-test/color-looper.zig b/bench/hot-module-reloading/css-stress-test/color-looper.zig
index 87f08d32f..0509a525b 100644
--- a/bench/hot-module-reloading/css-stress-test/color-looper.zig
+++ b/bench/hot-module-reloading/css-stress-test/color-looper.zig
@@ -115,27 +115,27 @@ pub fn main() anyerror!void {
counters[counter].timestamp = @truncate(u64, @intCast(u128, std.time.nanoTimestamp()) / (std.time.ns_per_ms / 10));
counters[counter].rotate = rotate % 360;
counters[counter].percent = std.math.mod(f64, std.math.round(((progress_bar + 1.0) / destination_count) * 1000) / 1000, 100) catch 0;
- counters[counter].color_values[0] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[1] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[2] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[0][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[0] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[0][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[1] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[0][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[2] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[0][2] + 1) % 256)) * 0.8));
counters[counter].color_values[3] = (colors[0][0] + 1) % 256;
counters[counter].color_values[4] = (colors[0][1] + 1) % 256;
counters[counter].color_values[5] = (colors[0][2] + 1) % 256;
- counters[counter].color_values[6] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[7] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[8] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[1][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[6] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[1][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[7] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[1][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[8] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[1][2] + 1) % 256)) * 0.8));
counters[counter].color_values[9] = (colors[1][0] + 1) % 256;
counters[counter].color_values[10] = (colors[1][1] + 1) % 256;
counters[counter].color_values[11] = (colors[1][2] + 1) % 256;
- counters[counter].color_values[12] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[13] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[14] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[2][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[12] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[2][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[13] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[2][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[14] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[2][2] + 1) % 256)) * 0.8));
counters[counter].color_values[15] = (colors[2][0] + 1) % 256;
counters[counter].color_values[16] = (colors[2][1] + 1) % 256;
counters[counter].color_values[17] = (colors[2][2] + 1) % 256;
- counters[counter].color_values[18] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][0] + 1) % 256)) * 0.8));
- counters[counter].color_values[19] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][1] + 1) % 256)) * 0.8));
- counters[counter].color_values[20] = @floatToInt(u32, std.math.round(@intToFloat(f64, ((colors[3][2] + 1) % 256)) * 0.8));
+ counters[counter].color_values[18] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[3][0] + 1) % 256)) * 0.8));
+ counters[counter].color_values[19] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[3][1] + 1) % 256)) * 0.8));
+ counters[counter].color_values[20] = @intFromFloat(u32, std.math.round(@floatFromInt(f64, ((colors[3][2] + 1) % 256)) * 0.8));
counters[counter].color_values[21] = (colors[3][0] + 1) % 256;
counters[counter].color_values[22] = (colors[3][1] + 1) % 256;
counters[counter].color_values[23] = (colors[3][2] + 1) % 256;
@@ -190,7 +190,7 @@ pub fn main() anyerror!void {
_ = try recorder.wait();
all_timestamps[0] = wrote.len;
- for (counters) |count, i| {
+ for (counters, 0..) |count, i| {
all_timestamps[i + 1] = count.timestamp;
}
diff --git a/build.zig b/build.zig
index 72588f6f4..8993070b0 100644
--- a/build.zig
+++ b/build.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const Wyhash = @import("./src/wyhash.zig").Wyhash;
fn moduleSource(comptime out: []const u8) FileSource {
if (comptime std.fs.path.dirname(@src().file)) |base| {
@@ -76,13 +77,13 @@ const BunBuildOptions = struct {
pub fn updateRuntime(this: *BunBuildOptions) anyerror!void {
var runtime_out_file = try std.fs.cwd().openFile("src/runtime.out.js", .{ .mode = .read_only });
- const runtime_hash = std.hash.Wyhash.hash(
+ const runtime_hash = Wyhash.hash(
0,
try runtime_out_file.readToEndAlloc(std.heap.page_allocator, try runtime_out_file.getEndPos()),
);
this.runtime_js_version = runtime_hash;
var fallback_out_file = try std.fs.cwd().openFile("src/fallback.out.js", .{ .mode = .read_only });
- const fallback_hash = std.hash.Wyhash.hash(
+ const fallback_hash = Wyhash.hash(
0,
try fallback_out_file.readToEndAlloc(std.heap.page_allocator, try fallback_out_file.getEndPos()),
);
@@ -192,12 +193,12 @@ pub fn build(b: *Build) !void {
else
"root.zig";
- const min_version: std.builtin.Version = if (target.getOsTag() != .freestanding)
+ const min_version: std.SemanticVersion = if (target.getOsTag() != .freestanding)
target.getOsVersionMin().semver
else
.{ .major = 0, .minor = 0, .patch = 0 };
- const max_version: std.builtin.Version = if (target.getOsTag() != .freestanding)
+ const max_version: std.SemanticVersion = if (target.getOsTag() != .freestanding)
target.getOsVersionMax().semver
else
.{ .major = 0, .minor = 0, .patch = 0 };
diff --git a/docs/project/development.md b/docs/project/development.md
index 92a414c5f..d21641aff 100644
--- a/docs/project/development.md
+++ b/docs/project/development.md
@@ -102,7 +102,7 @@ Zig can be installed either with our npm package [`@oven/zig`](https://www.npmjs
```bash
$ bun install -g @oven/zig
-$ zigup 0.11.0-dev.2777+b95cdf0ae
+$ zigup 0.11.0-dev.3737+9eb008717
```
## Building
diff --git a/misctools/fetch.zig b/misctools/fetch.zig
index 38a948f52..5ac701250 100644
--- a/misctools/fetch.zig
+++ b/misctools/fetch.zig
@@ -91,7 +91,7 @@ pub const Arguments = struct {
var raw_args: std.ArrayListUnmanaged(string) = undefined;
if (positionals.len > 0) {
- raw_args = .{ .capacity = positionals.len, .items = @intToPtr([*][]const u8, @ptrToInt(positionals.ptr))[0..positionals.len] };
+ raw_args = .{ .capacity = positionals.len, .items = @ptrFromInt([*][]const u8, @intFromPtr(positionals.ptr))[0..positionals.len] };
} else {
raw_args = .{};
}
diff --git a/misctools/http_bench.zig b/misctools/http_bench.zig
index 4075daf49..5847399a1 100644
--- a/misctools/http_bench.zig
+++ b/misctools/http_bench.zig
@@ -95,7 +95,7 @@ pub const Arguments = struct {
var raw_args: std.ArrayListUnmanaged(string) = undefined;
if (positionals.len > 0) {
- raw_args = .{ .capacity = positionals.len, .items = @intToPtr([*][]const u8, @ptrToInt(positionals.ptr))[0..positionals.len] };
+ raw_args = .{ .capacity = positionals.len, .items = @ptrFromInt([*][]const u8, @intFromPtr(positionals.ptr))[0..positionals.len] };
} else {
raw_args = .{};
}
@@ -244,7 +244,7 @@ pub fn main() anyerror!void {
const http = channel.readItem() catch continue;
read_count += 1;
- Output.printElapsed(@floatCast(f64, @intToFloat(f128, http.elapsed) / std.time.ns_per_ms));
+ Output.printElapsed(@floatCast(f64, @floatFromInt(f128, http.elapsed) / std.time.ns_per_ms));
if (http.response) |resp| {
if (resp.status_code == 200) {
success_count += 1;
@@ -270,7 +270,7 @@ pub fn main() anyerror!void {
http.client.url.href,
http.response_buffer.list.items.len,
});
- Output.printElapsed(@floatCast(f64, @intToFloat(f128, http.gzip_elapsed) / std.time.ns_per_ms));
+ Output.printElapsed(@floatCast(f64, @floatFromInt(f128, http.gzip_elapsed) / std.time.ns_per_ms));
Output.prettyError("<d> gzip)<r>\n", .{});
} else {
Output.prettyError(" <d>{s}<r><d> - {s}<r> <d>({d} bytes)<r>\n", .{
@@ -295,7 +295,7 @@ pub fn main() anyerror!void {
fail_count,
});
- Output.printElapsed(@floatCast(f64, @intToFloat(f128, timer.read()) / std.time.ns_per_ms));
+ Output.printElapsed(@floatCast(f64, @floatFromInt(f128, timer.read()) / std.time.ns_per_ms));
Output.prettyErrorln(" {d} requests", .{
read_count,
});
diff --git a/src/ArenaAllocator.zig b/src/ArenaAllocator.zig
index 31e0cf5b9..999ea4142 100644
--- a/src/ArenaAllocator.zig
+++ b/src/ArenaAllocator.zig
@@ -111,7 +111,7 @@ pub const ArenaAllocator = struct {
// value.
const requested_capacity = switch (mode) {
.retain_capacity => self.queryCapacity(),
- .retain_with_limit => |limit| std.math.min(limit, self.queryCapacity()),
+ .retain_with_limit => |limit| @min(limit, self.queryCapacity()),
.free_all => 0,
};
if (requested_capacity == 0) {
@@ -186,8 +186,8 @@ pub const ArenaAllocator = struct {
while (true) {
const cur_alloc_buf = @ptrCast([*]u8, cur_node)[0..cur_node.data];
const cur_buf = cur_alloc_buf[@sizeOf(BufNode)..];
- const addr = @ptrToInt(cur_buf.ptr) + self.state.end_index;
- const adjusted_addr = mem.alignForward(addr, ptr_align);
+ const addr = @intFromPtr(cur_buf.ptr) + self.state.end_index;
+ const adjusted_addr = mem.alignForward(usize, addr, ptr_align);
const adjusted_index = self.state.end_index + (adjusted_addr - addr);
const new_end_index = adjusted_index + n;
@@ -215,7 +215,7 @@ pub const ArenaAllocator = struct {
const cur_node = self.state.buffer_list.first orelse return false;
const cur_buf = @ptrCast([*]u8, cur_node)[@sizeOf(BufNode)..cur_node.data];
- if (@ptrToInt(cur_buf.ptr) + self.state.end_index != @ptrToInt(buf.ptr) + buf.len) {
+ if (@intFromPtr(cur_buf.ptr) + self.state.end_index != @intFromPtr(buf.ptr) + buf.len) {
// It's not the most recent allocation, so it cannot be expanded,
// but it's fine if they want to make it smaller.
return new_len <= buf.len;
@@ -241,7 +241,7 @@ pub const ArenaAllocator = struct {
const cur_node = self.state.buffer_list.first orelse return;
const cur_buf = @ptrCast([*]u8, cur_node)[@sizeOf(BufNode)..cur_node.data];
- if (@ptrToInt(cur_buf.ptr) + self.state.end_index == @ptrToInt(buf.ptr) + buf.len) {
+ if (@intFromPtr(cur_buf.ptr) + self.state.end_index == @intFromPtr(buf.ptr) + buf.len) {
self.state.end_index -= buf.len;
}
}
@@ -263,7 +263,7 @@ test "ArenaAllocator (reset with preheating)" {
const size = random.intRangeAtMost(usize, 16, 256);
const alignment = 32;
const slice = try arena_allocator.allocator().alignedAlloc(u8, alignment, size);
- try std.testing.expect(std.mem.isAligned(@ptrToInt(slice.ptr), alignment));
+ try std.testing.expect(std.mem.isAligned(@intFromPtr(slice.ptr), alignment));
try std.testing.expectEqual(size, slice.len);
alloced_bytes += slice.len;
}
diff --git a/src/__global.zig b/src/__global.zig
index e426cd595..ed0fa08f5 100644
--- a/src/__global.zig
+++ b/src/__global.zig
@@ -55,7 +55,7 @@ pub const version: @import("./install/semver.zig").Version = .{
pub fn setThreadName(name: StringTypes.stringZ) void {
if (Environment.isLinux) {
- _ = std.os.prctl(.SET_NAME, .{@ptrToInt(name.ptr)}) catch 0;
+ _ = std.os.prctl(.SET_NAME, .{@intFromPtr(name.ptr)}) catch 0;
} else if (Environment.isMac) {
_ = std.c.pthread_setname_np(name);
}
diff --git a/src/allocators.zig b/src/allocators.zig
index 2827214af..1d3b30c0b 100644
--- a/src/allocators.zig
+++ b/src/allocators.zig
@@ -2,19 +2,18 @@ const std = @import("std");
const FeatureFlags = @import("./feature_flags.zig");
const Environment = @import("./env.zig");
-const Wyhash = std.hash.Wyhash;
const FixedBufferAllocator = std.heap.FixedBufferAllocator;
const constStrToU8 = @import("root").bun.constStrToU8;
const bun = @import("root").bun;
pub fn isSliceInBuffer(slice: anytype, buffer: anytype) bool {
- return (@ptrToInt(&buffer) <= @ptrToInt(slice.ptr) and (@ptrToInt(slice.ptr) + slice.len) <= (@ptrToInt(buffer) + buffer.len));
+ return (@intFromPtr(&buffer) <= @intFromPtr(slice.ptr) and (@intFromPtr(slice.ptr) + slice.len) <= (@intFromPtr(buffer) + buffer.len));
}
pub fn sliceRange(slice: []const u8, buffer: []const u8) ?[2]u32 {
- return if (@ptrToInt(buffer.ptr) <= @ptrToInt(slice.ptr) and
- (@ptrToInt(slice.ptr) + slice.len) <= (@ptrToInt(buffer.ptr) + buffer.len))
+ return if (@intFromPtr(buffer.ptr) <= @intFromPtr(slice.ptr) and
+ (@intFromPtr(slice.ptr) + slice.len) <= (@intFromPtr(buffer.ptr) + buffer.len))
[2]u32{
- @truncate(u32, @ptrToInt(slice.ptr) - @ptrToInt(buffer.ptr)),
+ @truncate(u32, @intFromPtr(slice.ptr) - @intFromPtr(buffer.ptr)),
@truncate(u32, slice.len),
}
else
@@ -53,7 +52,6 @@ pub const Result = struct {
return r.index >= count;
}
};
-const Seed = 999;
pub const NotFound = IndexType{
.index = std.math.maxInt(u31),
@@ -488,7 +486,7 @@ pub fn BSSMap(comptime ValueType: type, comptime count: anytype, comptime store_
pub fn getOrPut(self: *Self, denormalized_key: []const u8) !Result {
const key = if (comptime remove_trailing_slashes) std.mem.trimRight(u8, denormalized_key, "/") else denormalized_key;
- const _key = Wyhash.hash(Seed, key);
+ const _key = bun.hash(key);
self.mutex.lock();
defer self.mutex.unlock();
@@ -516,7 +514,7 @@ pub fn BSSMap(comptime ValueType: type, comptime count: anytype, comptime store_
pub fn get(self: *Self, denormalized_key: []const u8) ?*ValueType {
const key = if (comptime remove_trailing_slashes) std.mem.trimRight(u8, denormalized_key, "/") else denormalized_key;
- const _key = Wyhash.hash(Seed, key);
+ const _key = bun.hash(key);
self.mutex.lock();
defer self.mutex.unlock();
const index = self.index.get(_key) orelse return null;
@@ -577,7 +575,7 @@ pub fn BSSMap(comptime ValueType: type, comptime count: anytype, comptime store_
const key = if (comptime remove_trailing_slashes) std.mem.trimRight(u8, denormalized_key, "/") else denormalized_key;
- const _key = Wyhash.hash(Seed, key);
+ const _key = bun.hash(key);
_ = self.index.remove(_key);
// const index = self.index.get(_key) orelse return;
// switch (index) {
diff --git a/src/analytics/analytics_schema.zig b/src/analytics/analytics_schema.zig
index 825735331..5332a4837 100644
--- a/src/analytics/analytics_schema.zig
+++ b/src/analytics/analytics_schema.zig
@@ -201,7 +201,7 @@ pub fn Writer(comptime WritableStream: type) type {
}
pub inline fn writeEnum(this: *Self, val: anytype) !void {
- try this.writeInt(@enumToInt(val));
+ try this.writeInt(@intFromEnum(val));
}
pub fn writeValue(this: *Self, comptime SliceType: type, slice: SliceType) !void {
diff --git a/src/analytics/analytics_thread.zig b/src/analytics/analytics_thread.zig
index b6039d3a7..998f5cfc2 100644
--- a/src/analytics/analytics_thread.zig
+++ b/src/analytics/analytics_thread.zig
@@ -261,7 +261,7 @@ pub const GenerateHeader = struct {
pub const GeneratePlatform = struct {
var osversion_name: [32]u8 = undefined;
pub fn forMac() Analytics.Platform {
- @memset(&osversion_name, 0, osversion_name.len);
+ @memset(&osversion_name, 0);
var platform = Analytics.Platform{ .os = Analytics.OperatingSystem.macos, .version = &[_]u8{}, .arch = platform_arch };
var len = osversion_name.len - 1;
@@ -340,7 +340,7 @@ pub const GenerateHeader = struct {
offset = std.mem.indexOfScalar(u8, out, '"') orelse return Analytics.Uint64{};
out = out[0..offset];
- const hash = std.hash.Wyhash.hash(0, std.mem.trim(u8, out, "\n\r "));
+ const hash = bun.hash(std.mem.trim(u8, out, "\n\r "));
var hash_bytes = std.mem.asBytes(&hash);
return Analytics.Uint64{
.first = std.mem.readIntNative(u32, hash_bytes[0..4]),
@@ -357,7 +357,7 @@ pub const GenerateHeader = struct {
defer file.close();
var read_count = try file.read(&linux_machine_id);
- const hash = std.hash.Wyhash.hash(0, std.mem.trim(u8, linux_machine_id[0..read_count], "\n\r "));
+ const hash = bun.hash(std.mem.trim(u8, linux_machine_id[0..read_count], "\n\r "));
var hash_bytes = std.mem.asBytes(&hash);
return Analytics.Uint64{
.first = std.mem.readIntNative(u32, hash_bytes[0..4]),
@@ -540,8 +540,8 @@ pub const EventList = struct {
}
@atomicStore(bool, &is_stuck, retry_remaining == 0, .Release);
- stuck_count += @intCast(u8, @boolToInt(retry_remaining == 0));
- stuck_count *= @intCast(u8, @boolToInt(retry_remaining == 0));
+ stuck_count += @intCast(u8, @intFromBool(retry_remaining == 0));
+ stuck_count *= @intCast(u8, @intFromBool(retry_remaining == 0));
disabled = disabled or stuck_count > 4;
this.in_buffer.reset();
diff --git a/src/api/demo/schema.zig b/src/api/demo/schema.zig
index 748422ed8..d57a5c725 100644
--- a/src/api/demo/schema.zig
+++ b/src/api/demo/schema.zig
@@ -201,7 +201,7 @@ pub fn Writer(comptime WritableStream: type) type {
}
pub inline fn writeEnum(this: *Self, val: anytype) !void {
- try this.writeInt(@enumToInt(val));
+ try this.writeInt(@intFromEnum(val));
}
pub fn writeValue(this: *Self, comptime SliceType: type, slice: SliceType) !void {
@@ -881,9 +881,9 @@ pub const Api = struct {
try writer.writeValue(@TypeOf(this.factory), this.factory);
try writer.writeEnum(this.runtime);
try writer.writeValue(@TypeOf(this.fragment), this.fragment);
- try writer.writeInt(@as(u8, @boolToInt(this.development)));
+ try writer.writeInt(@as(u8, @intFromBool(this.development)));
try writer.writeValue(@TypeOf(this.import_source), this.import_source);
- try writer.writeInt(@as(u8, @boolToInt(this.react_fast_refresh)));
+ try writer.writeInt(@as(u8, @intFromBool(this.react_fast_refresh)));
}
};
@@ -1151,7 +1151,7 @@ pub const Api = struct {
pub fn encode(this: *const @This(), writer: anytype) anyerror!void {
try writer.writeEnum(this.kind);
try writer.writeValue(@TypeOf(this.path), this.path);
- try writer.writeInt(@as(u8, @boolToInt(this.dynamic)));
+ try writer.writeInt(@as(u8, @intFromBool(this.dynamic)));
}
};
@@ -1390,7 +1390,7 @@ pub const Api = struct {
}
if (this.development) |development| {
try writer.writeFieldID(5);
- try writer.writeInt(@as(u8, @boolToInt(development)));
+ try writer.writeInt(@as(u8, @intFromBool(development)));
}
if (this.client_css_in_js) |client_css_in_js| {
try writer.writeFieldID(6);
@@ -1564,7 +1564,7 @@ pub const Api = struct {
pub fn encode(this: *const @This(), writer: anytype) anyerror!void {
try writer.writeValue(@TypeOf(this.package), this.package);
try writer.writeValue(@TypeOf(this.display_name), this.display_name);
- try writer.writeInt(@as(u8, @boolToInt(this.development)));
+ try writer.writeInt(@as(u8, @intFromBool(this.development)));
try writer.writeValue(@TypeOf(this.entry_points), this.entry_points);
try writer.writeEnum(this.client_css_in_js);
try writer.writeValue(@TypeOf(this.override_modules), this.override_modules);
@@ -1866,7 +1866,7 @@ pub const Api = struct {
}
if (this.preserve_symlinks) |preserve_symlinks| {
try writer.writeFieldID(7);
- try writer.writeInt(@as(u8, @boolToInt(preserve_symlinks)));
+ try writer.writeInt(@as(u8, @intFromBool(preserve_symlinks)));
}
if (this.entry_points) |entry_points| {
try writer.writeFieldID(8);
@@ -1874,7 +1874,7 @@ pub const Api = struct {
}
if (this.write) |write| {
try writer.writeFieldID(9);
- try writer.writeInt(@as(u8, @boolToInt(write)));
+ try writer.writeInt(@as(u8, @intFromBool(write)));
}
if (this.inject) |inject| {
try writer.writeFieldID(10);
@@ -1902,7 +1902,7 @@ pub const Api = struct {
}
if (this.serve) |serve| {
try writer.writeFieldID(16);
- try writer.writeInt(@as(u8, @boolToInt(serve)));
+ try writer.writeInt(@as(u8, @intFromBool(serve)));
}
if (this.extension_order) |extension_order| {
try writer.writeFieldID(17);
@@ -1910,7 +1910,7 @@ pub const Api = struct {
}
if (this.generate_node_module_bundle) |generate_node_module_bundle| {
try writer.writeFieldID(18);
- try writer.writeInt(@as(u8, @boolToInt(generate_node_module_bundle)));
+ try writer.writeInt(@as(u8, @intFromBool(generate_node_module_bundle)));
}
if (this.node_modules_bundle_path) |node_modules_bundle_path| {
try writer.writeFieldID(19);
@@ -1930,11 +1930,11 @@ pub const Api = struct {
}
if (this.no_summary) |no_summary| {
try writer.writeFieldID(23);
- try writer.writeInt(@as(u8, @boolToInt(no_summary)));
+ try writer.writeInt(@as(u8, @intFromBool(no_summary)));
}
if (this.disable_hmr) |disable_hmr| {
try writer.writeFieldID(24);
- try writer.writeInt(@as(u8, @boolToInt(disable_hmr)));
+ try writer.writeInt(@as(u8, @intFromBool(disable_hmr)));
}
if (this.port) |port| {
try writer.writeFieldID(25);
@@ -2259,7 +2259,7 @@ pub const Api = struct {
}
if (this.build) |build| {
try writer.writeFieldID(2);
- try writer.writeInt(@as(u8, @boolToInt(build)));
+ try writer.writeInt(@as(u8, @intFromBool(build)));
}
try writer.endMessage();
}
@@ -2822,35 +2822,35 @@ pub const Api = struct {
}
if (this.dry_run) |dry_run| {
try writer.writeFieldID(6);
- try writer.writeInt(@as(u8, @boolToInt(dry_run)));
+ try writer.writeInt(@as(u8, @intFromBool(dry_run)));
}
if (this.force) |force| {
try writer.writeFieldID(7);
- try writer.writeInt(@as(u8, @boolToInt(force)));
+ try writer.writeInt(@as(u8, @intFromBool(force)));
}
if (this.save_dev) |save_dev| {
try writer.writeFieldID(8);
- try writer.writeInt(@as(u8, @boolToInt(save_dev)));
+ try writer.writeInt(@as(u8, @intFromBool(save_dev)));
}
if (this.save_optional) |save_optional| {
try writer.writeFieldID(9);
- try writer.writeInt(@as(u8, @boolToInt(save_optional)));
+ try writer.writeInt(@as(u8, @intFromBool(save_optional)));
}
if (this.save_peer) |save_peer| {
try writer.writeFieldID(10);
- try writer.writeInt(@as(u8, @boolToInt(save_peer)));
+ try writer.writeInt(@as(u8, @intFromBool(save_peer)));
}
if (this.save_lockfile) |save_lockfile| {
try writer.writeFieldID(11);
- try writer.writeInt(@as(u8, @boolToInt(save_lockfile)));
+ try writer.writeInt(@as(u8, @intFromBool(save_lockfile)));
}
if (this.production) |production| {
try writer.writeFieldID(12);
- try writer.writeInt(@as(u8, @boolToInt(production)));
+ try writer.writeInt(@as(u8, @intFromBool(production)));
}
if (this.save_yarn_lockfile) |save_yarn_lockfile| {
try writer.writeFieldID(13);
- try writer.writeInt(@as(u8, @boolToInt(save_yarn_lockfile)));
+ try writer.writeInt(@as(u8, @intFromBool(save_yarn_lockfile)));
}
if (this.native_bin_links) |native_bin_links| {
try writer.writeFieldID(14);
@@ -2858,11 +2858,11 @@ pub const Api = struct {
}
if (this.disable_cache) |disable_cache| {
try writer.writeFieldID(15);
- try writer.writeInt(@as(u8, @boolToInt(disable_cache)));
+ try writer.writeInt(@as(u8, @intFromBool(disable_cache)));
}
if (this.disable_manifest_cache) |disable_manifest_cache| {
try writer.writeFieldID(16);
- try writer.writeInt(@as(u8, @boolToInt(disable_manifest_cache)));
+ try writer.writeInt(@as(u8, @intFromBool(disable_manifest_cache)));
}
if (this.global_dir) |global_dir| {
try writer.writeFieldID(17);
diff --git a/src/api/schema.zig b/src/api/schema.zig
index 227d1296b..1012e6051 100644
--- a/src/api/schema.zig
+++ b/src/api/schema.zig
@@ -201,7 +201,7 @@ pub fn Writer(comptime WritableStream: type) type {
}
pub inline fn writeEnum(this: *Self, val: anytype) !void {
- try this.writeInt(@enumToInt(val));
+ try this.writeInt(@intFromEnum(val));
}
pub fn writeValue(this: *Self, comptime SliceType: type, slice: SliceType) !void {
@@ -896,9 +896,9 @@ pub const Api = struct {
try writer.writeValue(@TypeOf(this.factory), this.factory);
try writer.writeEnum(this.runtime);
try writer.writeValue(@TypeOf(this.fragment), this.fragment);
- try writer.writeInt(@as(u8, @boolToInt(this.development)));
+ try writer.writeInt(@as(u8, @intFromBool(this.development)));
try writer.writeValue(@TypeOf(this.import_source), this.import_source);
- try writer.writeInt(@as(u8, @boolToInt(this.react_fast_refresh)));
+ try writer.writeInt(@as(u8, @intFromBool(this.react_fast_refresh)));
}
};
@@ -1166,7 +1166,7 @@ pub const Api = struct {
pub fn encode(this: *const @This(), writer: anytype) anyerror!void {
try writer.writeEnum(this.kind);
try writer.writeValue(@TypeOf(this.path), this.path);
- try writer.writeInt(@as(u8, @boolToInt(this.dynamic)));
+ try writer.writeInt(@as(u8, @intFromBool(this.dynamic)));
}
};
@@ -1405,7 +1405,7 @@ pub const Api = struct {
}
if (this.development) |development| {
try writer.writeFieldID(5);
- try writer.writeInt(@as(u8, @boolToInt(development)));
+ try writer.writeInt(@as(u8, @intFromBool(development)));
}
if (this.client_css_in_js) |client_css_in_js| {
try writer.writeFieldID(6);
@@ -1579,7 +1579,7 @@ pub const Api = struct {
pub fn encode(this: *const @This(), writer: anytype) anyerror!void {
try writer.writeValue(@TypeOf(this.package), this.package);
try writer.writeValue(@TypeOf(this.display_name), this.display_name);
- try writer.writeInt(@as(u8, @boolToInt(this.development)));
+ try writer.writeInt(@as(u8, @intFromBool(this.development)));
try writer.writeValue(@TypeOf(this.entry_points), this.entry_points);
try writer.writeEnum(this.client_css_in_js);
try writer.writeValue(@TypeOf(this.override_modules), this.override_modules);
@@ -1887,7 +1887,7 @@ pub const Api = struct {
}
if (this.preserve_symlinks) |preserve_symlinks| {
try writer.writeFieldID(7);
- try writer.writeInt(@as(u8, @boolToInt(preserve_symlinks)));
+ try writer.writeInt(@as(u8, @intFromBool(preserve_symlinks)));
}
if (this.entry_points) |entry_points| {
try writer.writeFieldID(8);
@@ -1895,7 +1895,7 @@ pub const Api = struct {
}
if (this.write) |write| {
try writer.writeFieldID(9);
- try writer.writeInt(@as(u8, @boolToInt(write)));
+ try writer.writeInt(@as(u8, @intFromBool(write)));
}
if (this.inject) |inject| {
try writer.writeFieldID(10);
@@ -1923,7 +1923,7 @@ pub const Api = struct {
}
if (this.serve) |serve| {
try writer.writeFieldID(16);
- try writer.writeInt(@as(u8, @boolToInt(serve)));
+ try writer.writeInt(@as(u8, @intFromBool(serve)));
}
if (this.extension_order) |extension_order| {
try writer.writeFieldID(17);
@@ -1931,7 +1931,7 @@ pub const Api = struct {
}
if (this.generate_node_module_bundle) |generate_node_module_bundle| {
try writer.writeFieldID(18);
- try writer.writeInt(@as(u8, @boolToInt(generate_node_module_bundle)));
+ try writer.writeInt(@as(u8, @intFromBool(generate_node_module_bundle)));
}
if (this.node_modules_bundle_path) |node_modules_bundle_path| {
try writer.writeFieldID(19);
@@ -1951,11 +1951,11 @@ pub const Api = struct {
}
if (this.no_summary) |no_summary| {
try writer.writeFieldID(23);
- try writer.writeInt(@as(u8, @boolToInt(no_summary)));
+ try writer.writeInt(@as(u8, @intFromBool(no_summary)));
}
if (this.disable_hmr) |disable_hmr| {
try writer.writeFieldID(24);
- try writer.writeInt(@as(u8, @boolToInt(disable_hmr)));
+ try writer.writeInt(@as(u8, @intFromBool(disable_hmr)));
}
if (this.port) |port| {
try writer.writeFieldID(25);
@@ -2427,7 +2427,7 @@ pub const Api = struct {
}
if (this.build) |build| {
try writer.writeFieldID(2);
- try writer.writeInt(@as(u8, @boolToInt(build)));
+ try writer.writeInt(@as(u8, @intFromBool(build)));
}
try writer.endMessage();
}
@@ -2995,35 +2995,35 @@ pub const Api = struct {
}
if (this.dry_run) |dry_run| {
try writer.writeFieldID(6);
- try writer.writeInt(@as(u8, @boolToInt(dry_run)));
+ try writer.writeInt(@as(u8, @intFromBool(dry_run)));
}
if (this.force) |force| {
try writer.writeFieldID(7);
- try writer.writeInt(@as(u8, @boolToInt(force)));
+ try writer.writeInt(@as(u8, @intFromBool(force)));
}
if (this.save_dev) |save_dev| {
try writer.writeFieldID(8);
- try writer.writeInt(@as(u8, @boolToInt(save_dev)));
+ try writer.writeInt(@as(u8, @intFromBool(save_dev)));
}
if (this.save_optional) |save_optional| {
try writer.writeFieldID(9);
- try writer.writeInt(@as(u8, @boolToInt(save_optional)));
+ try writer.writeInt(@as(u8, @intFromBool(save_optional)));
}
if (this.save_peer) |save_peer| {
try writer.writeFieldID(10);
- try writer.writeInt(@as(u8, @boolToInt(save_peer)));
+ try writer.writeInt(@as(u8, @intFromBool(save_peer)));
}
if (this.save_lockfile) |save_lockfile| {
try writer.writeFieldID(11);
- try writer.writeInt(@as(u8, @boolToInt(save_lockfile)));
+ try writer.writeInt(@as(u8, @intFromBool(save_lockfile)));
}
if (this.production) |production| {
try writer.writeFieldID(12);
- try writer.writeInt(@as(u8, @boolToInt(production)));
+ try writer.writeInt(@as(u8, @intFromBool(production)));
}
if (this.save_yarn_lockfile) |save_yarn_lockfile| {
try writer.writeFieldID(13);
- try writer.writeInt(@as(u8, @boolToInt(save_yarn_lockfile)));
+ try writer.writeInt(@as(u8, @intFromBool(save_yarn_lockfile)));
}
if (this.native_bin_links) |native_bin_links| {
try writer.writeFieldID(14);
@@ -3031,11 +3031,11 @@ pub const Api = struct {
}
if (this.disable_cache) |disable_cache| {
try writer.writeFieldID(15);
- try writer.writeInt(@as(u8, @boolToInt(disable_cache)));
+ try writer.writeInt(@as(u8, @intFromBool(disable_cache)));
}
if (this.disable_manifest_cache) |disable_manifest_cache| {
try writer.writeFieldID(16);
- try writer.writeInt(@as(u8, @boolToInt(disable_manifest_cache)));
+ try writer.writeInt(@as(u8, @intFromBool(disable_manifest_cache)));
}
if (this.global_dir) |global_dir| {
try writer.writeFieldID(17);
diff --git a/src/ast/base.zig b/src/ast/base.zig
index d3e510ae6..ae544f8be 100644
--- a/src/ast/base.zig
+++ b/src/ast/base.zig
@@ -275,7 +275,7 @@ pub const Ref = packed struct(u64) {
}
pub inline fn hash64(key: Ref) u64 {
- return std.hash.Wyhash.hash(0, &@bitCast([8]u8, key.asU64()));
+ return bun.hash(&@bitCast([8]u8, key.asU64()));
}
pub fn eql(ref: Ref, b: Ref) bool {
diff --git a/src/baby_list.zig b/src/baby_list.zig
index 5227261e8..01ec819ec 100644
--- a/src/baby_list.zig
+++ b/src/baby_list.zig
@@ -30,7 +30,7 @@ pub fn BabyList(comptime Type: type) type {
}
pub fn contains(this: @This(), item: []const Type) bool {
- return this.len > 0 and @ptrToInt(item.ptr) >= @ptrToInt(this.ptr) and @ptrToInt(item.ptr) < @ptrToInt(this.ptr) + this.len;
+ return this.len > 0 and @intFromPtr(item.ptr) >= @intFromPtr(this.ptr) and @intFromPtr(item.ptr) < @intFromPtr(this.ptr) + this.len;
}
pub inline fn initConst(items: []const Type) ListType {
diff --git a/src/bench/string-handling.zig b/src/bench/string-handling.zig
index f9bee87e7..23f558eb8 100644
--- a/src/bench/string-handling.zig
+++ b/src/bench/string-handling.zig
@@ -34,7 +34,7 @@ pub fn main() anyerror!void {
var i: usize = 0;
while (j < amount) : (j += 1) {
i = 0;
- @memcpy(duped.ptr, contents.ptr, contents.len);
+ @memcpy(duped[0..contents.len], contents);
}
if (index == std.math.maxInt(usize)) {
diff --git a/src/bit_set.zig b/src/bit_set.zig
index 5f18eb32b..d40794473 100644
--- a/src/bit_set.zig
+++ b/src/bit_set.zig
@@ -308,7 +308,7 @@ pub fn IntegerBitSet(comptime size: u16) type {
}
fn boolMaskBit(index: usize, value: bool) MaskInt {
if (MaskInt == u0) return 0;
- return @as(MaskInt, @boolToInt(value)) << @intCast(ShiftInt, index);
+ return @as(MaskInt, @intFromBool(value)) << @intCast(ShiftInt, index);
}
};
}
@@ -653,7 +653,7 @@ pub fn ArrayBitSet(comptime MaskIntType: type, comptime size: usize) type {
return index >> @bitSizeOf(ShiftInt);
}
inline fn boolMaskBit(index: usize, value: bool) MaskInt {
- return @as(MaskInt, @boolToInt(value)) << @intCast(ShiftInt, index);
+ return @as(MaskInt, @intFromBool(value)) << @intCast(ShiftInt, index);
}
};
}
@@ -751,7 +751,7 @@ pub const DynamicBitSetUnmanaged = struct {
// fill in any new masks
if (new_masks > old_masks) {
const fill_value = std.math.boolMask(MaskInt, fill);
- std.mem.set(MaskInt, self.masks[old_masks..new_masks], fill_value);
+ @memset(self.masks[old_masks..new_masks], fill_value);
}
}
@@ -1088,7 +1088,7 @@ pub const DynamicBitSetUnmanaged = struct {
return index >> @bitSizeOf(ShiftInt);
}
fn boolMaskBit(index: usize, value: bool) MaskInt {
- return @as(MaskInt, @boolToInt(value)) << @intCast(ShiftInt, index);
+ return @as(MaskInt, @intFromBool(value)) << @intCast(ShiftInt, index);
}
fn numMasks(bit_length: usize) usize {
return (bit_length + (@bitSizeOf(MaskInt) - 1)) / @bitSizeOf(MaskInt);
diff --git a/src/blob.zig b/src/blob.zig
index a4a187530..96a6c7783 100644
--- a/src/blob.zig
+++ b/src/blob.zig
@@ -42,14 +42,14 @@ pub const Map = struct {
pub fn get(this: *Map, key: string) ?Blob {
this.lock.lock();
defer this.lock.unlock();
- return this.map.get(std.hash.Wyhash.hash(0, key));
+ return this.map.get(bun.hash(key));
}
pub fn put(this: *Map, key: string, blob: Blob) !void {
this.lock.lock();
defer this.lock.unlock();
- return try this.map.put(std.hash.Wyhash.hash(0, key), blob);
+ return try this.map.put(bun.hash(key), blob);
}
pub fn reset(this: *Map) !void {
diff --git a/src/boringssl.zig b/src/boringssl.zig
index b2ab55229..cdcd24577 100644
--- a/src/boringssl.zig
+++ b/src/boringssl.zig
@@ -65,7 +65,8 @@ export fn OPENSSL_memory_alloc(size: usize) ?*anyopaque {
// BoringSSL always expects memory to be zero'd
export fn OPENSSL_memory_free(ptr: *anyopaque) void {
- @memset(@ptrCast([*]u8, ptr), 0, bun.Mimalloc.mi_usable_size(ptr));
+ const len = bun.Mimalloc.mi_usable_size(ptr);
+ @memset(@ptrCast([*]u8, ptr)[0..len], 0);
bun.Mimalloc.mi_free(ptr);
}
diff --git a/src/bun.js/api/JSBundler.zig b/src/bun.js/api/JSBundler.zig
index 8e85f1190..e3b540da1 100644
--- a/src/bun.js/api/JSBundler.zig
+++ b/src/bun.js/api/JSBundler.zig
@@ -844,7 +844,7 @@ pub const JSBundler = struct {
this.value = .{
.success = .{
- .loader = @intToEnum(options.Loader, @intCast(u8, loader_as_int.to(i32))),
+ .loader = @enumFromInt(options.Loader, @intCast(u8, loader_as_int.to(i32))),
.source_code = source_code,
},
};
@@ -928,7 +928,7 @@ pub const JSBundler = struct {
else
ZigString.fromUTF8(namespace);
const path_string = ZigString.fromUTF8(path);
- JSBundlerPlugin__matchOnLoad(globalThis, this, &namespace_string, &path_string, context, @enumToInt(default_loader));
+ JSBundlerPlugin__matchOnLoad(globalThis, this, &namespace_string, &path_string, context, @intFromEnum(default_loader));
}
pub fn matchOnResolve(
@@ -949,7 +949,7 @@ pub const JSBundler = struct {
ZigString.fromUTF8(namespace);
const path_string = ZigString.fromUTF8(path);
const importer_string = ZigString.fromUTF8(importer);
- JSBundlerPlugin__matchOnResolve(globalThis, this, &namespace_string, &path_string, &importer_string, context, @enumToInt(import_record_kind));
+ JSBundlerPlugin__matchOnResolve(globalThis, this, &namespace_string, &path_string, &importer_string, context, @intFromEnum(import_record_kind));
}
pub fn addPlugin(
diff --git a/src/bun.js/api/JSTranspiler.zig b/src/bun.js/api/JSTranspiler.zig
index a1e1cfa36..308738abf 100644
--- a/src/bun.js/api/JSTranspiler.zig
+++ b/src/bun.js/api/JSTranspiler.zig
@@ -85,7 +85,7 @@ const TranspilerOptions = struct {
// This is going to be hard to not leak
pub const TransformTask = struct {
input_code: ZigString = ZigString.init(""),
- protected_input_value: JSC.JSValue = @intToEnum(JSC.JSValue, 0),
+ protected_input_value: JSC.JSValue = @enumFromInt(JSC.JSValue, 0),
output_code: ZigString = ZigString.init(""),
bundler: Bundler.Bundler = undefined,
log: logger.Log,
@@ -220,8 +220,8 @@ pub const TransformTask = struct {
finish(this.output_code, this.global, promise);
- if (@enumToInt(this.protected_input_value) != 0) {
- this.protected_input_value = @intToEnum(JSC.JSValue, 0);
+ if (@intFromEnum(this.protected_input_value) != 0) {
+ this.protected_input_value = @enumFromInt(JSC.JSValue, 0);
}
this.deinit();
}
@@ -611,7 +611,7 @@ fn transformOptionsFromJSC(globalObject: JSC.C.JSContextRef, temp_allocator: std
while (length_iter.next()) |value| {
if (value.isString()) {
const length = @truncate(u32, value.getLength(globalThis));
- string_count += @as(u32, @boolToInt(length > 0));
+ string_count += @as(u32, @intFromBool(length > 0));
total_name_buf_len += length;
}
}
@@ -877,7 +877,7 @@ fn getParseResult(this: *Transpiler, allocator: std.mem.Allocator, code: []const
for (res.ast.import_records.slice()) |*import| {
if (import.kind.isCommonJS()) {
import.do_commonjs_transform_in_printer = true;
- import.module_id = @truncate(u32, std.hash.Wyhash.hash(0, import.path.pretty));
+ import.module_id = @truncate(u32, bun.hash(import.path.pretty));
}
}
}
diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig
index 5580e8840..9df125a58 100644
--- a/src/bun.js/api/bun.zig
+++ b/src/bun.js/api/bun.zig
@@ -303,7 +303,7 @@ pub fn registerMacro(
return js.JSValueMakeUndefined(ctx);
}
// TODO: make this faster
- const id = @truncate(i32, @floatToInt(i64, js.JSValueToNumber(ctx, arguments[0], exception)));
+ const id = @truncate(i32, @intFromFloat(i64, js.JSValueToNumber(ctx, arguments[0], exception)));
if (id == -1 or id == 0) {
JSError(getAllocator(ctx), "Internal error registering macros: invalid id", .{}, ctx, exception);
return js.JSValueMakeUndefined(ctx);
@@ -523,7 +523,7 @@ pub fn getFilePath(ctx: js.JSContextRef, arguments: []const js.JSValueRef, buf:
temp_strings_list[temp_strings_list_len] = out_slice;
// The dots are kind of unnecessary. They'll be normalized.
- if (out.len == 0 or @ptrToInt(out.ptr) == 0 or std.mem.eql(u8, out_slice, ".") or std.mem.eql(u8, out_slice, "..") or std.mem.eql(u8, out_slice, "../")) {
+ if (out.len == 0 or @intFromPtr(out.ptr) == 0 or std.mem.eql(u8, out_slice, ".") or std.mem.eql(u8, out_slice, "..") or std.mem.eql(u8, out_slice, "../")) {
JSError(getAllocator(ctx), "Expected a file path as a string or an array of strings to be part of a file path.", .{}, ctx, exception);
return null;
}
@@ -600,7 +600,7 @@ pub fn readFileAsStringCallback(
return js.JSValueMakeUndefined(ctx);
};
- if (stat.kind != .File) {
+ if (stat.kind != .file) {
JSError(getAllocator(ctx), "Can't read a {s} as a string (\"{s}\")", .{ @tagName(stat.kind), path }, ctx, exception);
return js.JSValueMakeUndefined(ctx);
}
@@ -641,7 +641,7 @@ pub fn readFileAsBytesCallback(
return js.JSValueMakeUndefined(ctx);
};
- if (stat.kind != .File) {
+ if (stat.kind != .file) {
JSError(allocator, "Can't read a {s} as a string (\"{s}\")", .{ @tagName(stat.kind), path }, ctx, exception);
return js.JSValueMakeUndefined(ctx);
}
@@ -1612,7 +1612,7 @@ pub const Crypto = struct {
fn createCryptoError(globalThis: *JSC.JSGlobalObject, err_code: u32) JSValue {
var outbuf: [128 + 1 + "BoringSSL error: ".len]u8 = undefined;
- @memset(&outbuf, 0, outbuf.len);
+ @memset(&outbuf, 0);
outbuf[0.."BoringSSL error: ".len].* = "BoringSSL error: ".*;
var message_buf = outbuf["BoringSSL error: ".len..];
@@ -3171,9 +3171,9 @@ pub fn mmapFile(
return JSC.C.JSObjectMakeTypedArrayWithBytesNoCopy(ctx, JSC.C.JSTypedArrayType.kJSTypedArrayTypeUint8Array, @ptrCast(?*anyopaque, map.ptr), map.len, struct {
pub fn x(ptr: ?*anyopaque, size: ?*anyopaque) callconv(.C) void {
- _ = JSC.Node.Syscall.munmap(@ptrCast([*]align(std.mem.page_size) u8, @alignCast(std.mem.page_size, ptr))[0..@ptrToInt(size)]);
+ _ = JSC.Node.Syscall.munmap(@ptrCast([*]align(std.mem.page_size) u8, @alignCast(std.mem.page_size, ptr))[0..@intFromPtr(size)]);
}
- }.x, @intToPtr(?*anyopaque, map.len), exception);
+ }.x, @ptrFromInt(?*anyopaque, map.len), exception);
}
pub fn getTranspilerConstructor(
@@ -3401,7 +3401,7 @@ pub const Unsafe = struct {
globalThis: *JSC.JSGlobalObject,
value_: ?JSValue,
) JSValue {
- const ret = JSValue.jsNumber(@as(i32, @enumToInt(globalThis.bunVM().aggressive_garbage_collection)));
+ const ret = JSValue.jsNumber(@as(i32, @intFromEnum(globalThis.bunVM().aggressive_garbage_collection)));
if (value_) |value| {
switch (value.coerce(i32, globalThis)) {
@@ -3912,7 +3912,7 @@ pub const Timer = struct {
id,
Timeout.run,
this.interval,
- @as(i32, @boolToInt(this.kind == .setInterval)) * this.interval,
+ @as(i32, @intFromBool(this.kind == .setInterval)) * this.interval,
);
return this_value;
}
@@ -4130,7 +4130,7 @@ pub const Timer = struct {
},
Timeout.run,
interval,
- @as(i32, @boolToInt(kind == .setInterval)) * interval,
+ @as(i32, @intFromBool(kind == .setInterval)) * interval,
);
}
@@ -4318,7 +4318,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) u8, addr).*;
+ const value = @ptrFromInt(*align(1) u8, addr).*;
return JSValue.jsNumber(value);
}
pub fn @"u16"(
@@ -4327,7 +4327,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) u16, addr).*;
+ const value = @ptrFromInt(*align(1) u16, addr).*;
return JSValue.jsNumber(value);
}
pub fn @"u32"(
@@ -4336,7 +4336,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) u32, addr).*;
+ const value = @ptrFromInt(*align(1) u32, addr).*;
return JSValue.jsNumber(value);
}
pub fn ptr(
@@ -4345,7 +4345,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) u64, addr).*;
+ const value = @ptrFromInt(*align(1) u64, addr).*;
return JSValue.jsNumber(value);
}
pub fn @"i8"(
@@ -4354,7 +4354,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) i8, addr).*;
+ const value = @ptrFromInt(*align(1) i8, addr).*;
return JSValue.jsNumber(value);
}
pub fn @"i16"(
@@ -4363,7 +4363,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) i16, addr).*;
+ const value = @ptrFromInt(*align(1) i16, addr).*;
return JSValue.jsNumber(value);
}
pub fn @"i32"(
@@ -4372,7 +4372,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) i32, addr).*;
+ const value = @ptrFromInt(*align(1) i32, addr).*;
return JSValue.jsNumber(value);
}
pub fn intptr(
@@ -4381,7 +4381,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) i64, addr).*;
+ const value = @ptrFromInt(*align(1) i64, addr).*;
return JSValue.jsNumber(value);
}
@@ -4391,7 +4391,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) f32, addr).*;
+ const value = @ptrFromInt(*align(1) f32, addr).*;
return JSValue.jsNumber(value);
}
@@ -4401,7 +4401,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) f64, addr).*;
+ const value = @ptrFromInt(*align(1) f64, addr).*;
return JSValue.jsNumber(value);
}
@@ -4411,7 +4411,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) i64, addr).*;
+ const value = @ptrFromInt(*align(1) i64, addr).*;
return JSValue.fromInt64NoTruncate(global, value);
}
@@ -4421,7 +4421,7 @@ pub const FFI = struct {
arguments: []const JSValue,
) JSValue {
const addr = arguments[0].asPtrAddress() + if (arguments.len > 1) @intCast(usize, arguments[1].to(i32)) else @as(usize, 0);
- const value = @intToPtr(*align(1) u64, addr).*;
+ const value = @ptrFromInt(*align(1) u64, addr).*;
return JSValue.fromUInt64NoTruncate(global, value);
}
@@ -4432,7 +4432,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) u8, addr).*;
+ const value = @ptrFromInt(*align(1) u8, addr).*;
return JSValue.jsNumber(value);
}
pub fn u16WithoutTypeChecks(
@@ -4442,7 +4442,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) u16, addr).*;
+ const value = @ptrFromInt(*align(1) u16, addr).*;
return JSValue.jsNumber(value);
}
pub fn u32WithoutTypeChecks(
@@ -4452,7 +4452,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) u32, addr).*;
+ const value = @ptrFromInt(*align(1) u32, addr).*;
return JSValue.jsNumber(value);
}
pub fn ptrWithoutTypeChecks(
@@ -4462,7 +4462,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) u64, addr).*;
+ const value = @ptrFromInt(*align(1) u64, addr).*;
return JSValue.jsNumber(value);
}
pub fn i8WithoutTypeChecks(
@@ -4472,7 +4472,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) i8, addr).*;
+ const value = @ptrFromInt(*align(1) i8, addr).*;
return JSValue.jsNumber(value);
}
pub fn i16WithoutTypeChecks(
@@ -4482,7 +4482,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) i16, addr).*;
+ const value = @ptrFromInt(*align(1) i16, addr).*;
return JSValue.jsNumber(value);
}
pub fn i32WithoutTypeChecks(
@@ -4492,7 +4492,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) i32, addr).*;
+ const value = @ptrFromInt(*align(1) i32, addr).*;
return JSValue.jsNumber(value);
}
pub fn intptrWithoutTypeChecks(
@@ -4502,7 +4502,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) i64, addr).*;
+ const value = @ptrFromInt(*align(1) i64, addr).*;
return JSValue.jsNumber(value);
}
@@ -4513,7 +4513,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) f32, addr).*;
+ const value = @ptrFromInt(*align(1) f32, addr).*;
return JSValue.jsNumber(value);
}
@@ -4524,7 +4524,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) f64, addr).*;
+ const value = @ptrFromInt(*align(1) f64, addr).*;
return JSValue.jsNumber(value);
}
@@ -4535,7 +4535,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) u64, addr).*;
+ const value = @ptrFromInt(*align(1) u64, addr).*;
return JSValue.fromUInt64NoTruncate(global, value);
}
@@ -4546,7 +4546,7 @@ pub const FFI = struct {
offset: i32,
) callconv(.C) JSValue {
const addr = @intCast(usize, raw_addr) + @intCast(usize, offset);
- const value = @intToPtr(*align(1) i64, addr).*;
+ const value = @ptrFromInt(*align(1) i64, addr).*;
return JSValue.fromInt64NoTruncate(global, value);
}
@@ -4590,7 +4590,7 @@ pub const FFI = struct {
_: *anyopaque,
array: *JSC.JSUint8Array,
) callconv(.C) JSValue {
- return JSValue.fromPtrAddress(@ptrToInt(array.ptr()));
+ return JSValue.fromPtrAddress(@intFromPtr(array.ptr()));
}
fn ptr_(
@@ -4610,9 +4610,9 @@ pub const FFI = struct {
return JSC.toInvalidArguments("ArrayBufferView must have a length > 0. A pointer to empty memory doesn't work", .{}, globalThis);
}
- var addr: usize = @ptrToInt(array_buffer.ptr);
+ var addr: usize = @intFromPtr(array_buffer.ptr);
// const Sizes = @import("../bindings/sizes.zig");
- // std.debug.assert(addr == @ptrToInt(value.asEncoded().ptr) + Sizes.Bun_FFI_PointerOffsetToTypedArrayVector);
+ // std.debug.assert(addr == @intFromPtr(value.asEncoded().ptr) + Sizes.Bun_FFI_PointerOffsetToTypedArrayVector);
if (byteOffset) |off| {
if (!off.isEmptyOrUndefinedOrNull()) {
@@ -4628,7 +4628,7 @@ pub const FFI = struct {
addr += @intCast(usize, bytei64);
}
- if (addr > @ptrToInt(array_buffer.ptr) + @as(usize, array_buffer.byte_len)) {
+ if (addr > @intFromPtr(array_buffer.ptr) + @as(usize, array_buffer.byte_len)) {
return JSC.toInvalidArguments("byteOffset out of bounds", .{}, globalThis);
}
}
@@ -4720,11 +4720,11 @@ pub const FFI = struct {
}
const length = @intCast(usize, length_i);
- return .{ .slice = @intToPtr([*]u8, addr)[0..length] };
+ return .{ .slice = @ptrFromInt([*]u8, addr)[0..length] };
}
}
- return .{ .slice = bun.span(@intToPtr([*:0]u8, addr)) };
+ return .{ .slice = bun.span(@ptrFromInt([*:0]u8, addr)) };
}
fn getCPtr(value: JSValue) ?usize {
@@ -4759,11 +4759,11 @@ pub const FFI = struct {
var ctx: ?*anyopaque = null;
if (finalizationCallback) |callback_value| {
if (getCPtr(callback_value)) |callback_ptr| {
- callback = @intToPtr(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
+ callback = @ptrFromInt(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
if (finalizationCtxOrPtr) |ctx_value| {
if (getCPtr(ctx_value)) |ctx_ptr| {
- ctx = @intToPtr(*anyopaque, ctx_ptr);
+ ctx = @ptrFromInt(*anyopaque, ctx_ptr);
} else if (!ctx_value.isUndefinedOrNull()) {
return JSC.toInvalidArguments("Expected user data to be a C pointer (number or BigInt)", .{}, globalThis);
}
@@ -4773,7 +4773,7 @@ pub const FFI = struct {
}
} else if (finalizationCtxOrPtr) |callback_value| {
if (getCPtr(callback_value)) |callback_ptr| {
- callback = @intToPtr(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
+ callback = @ptrFromInt(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
} else if (!callback_value.isEmptyOrUndefinedOrNull()) {
return JSC.toInvalidArguments("Expected callback to be a C pointer (number or BigInt)", .{}, globalThis);
}
@@ -4801,11 +4801,11 @@ pub const FFI = struct {
var ctx: ?*anyopaque = null;
if (finalizationCallback) |callback_value| {
if (getCPtr(callback_value)) |callback_ptr| {
- callback = @intToPtr(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
+ callback = @ptrFromInt(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
if (finalizationCtxOrPtr) |ctx_value| {
if (getCPtr(ctx_value)) |ctx_ptr| {
- ctx = @intToPtr(*anyopaque, ctx_ptr);
+ ctx = @ptrFromInt(*anyopaque, ctx_ptr);
} else if (!ctx_value.isEmptyOrUndefinedOrNull()) {
return JSC.toInvalidArguments("Expected user data to be a C pointer (number or BigInt)", .{}, globalThis);
}
@@ -4815,7 +4815,7 @@ pub const FFI = struct {
}
} else if (finalizationCtxOrPtr) |callback_value| {
if (getCPtr(callback_value)) |callback_ptr| {
- callback = @intToPtr(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
+ callback = @ptrFromInt(JSC.C.JSTypedArrayBytesDeallocator, callback_ptr);
} else if (!callback_value.isEmptyOrUndefinedOrNull()) {
return JSC.toInvalidArguments("Expected callback to be a C pointer (number or BigInt)", .{}, globalThis);
}
diff --git a/src/bun.js/api/bun/dns_resolver.zig b/src/bun.js/api/bun/dns_resolver.zig
index aec295056..fee834e5e 100644
--- a/src/bun.js/api/bun/dns_resolver.zig
+++ b/src/bun.js/api/bun/dns_resolver.zig
@@ -123,7 +123,7 @@ const LibInfo = struct {
this.vm.uws_event_loop.?,
.machport,
true,
- @ptrToInt(request.backend.libinfo.machport),
+ @intFromPtr(request.backend.libinfo.machport),
) == .result,
);
@@ -230,7 +230,7 @@ fn addrInfoCount(addrinfo: *std.c.addrinfo) u32 {
var count: u32 = 1;
var current: ?*std.c.addrinfo = addrinfo.next;
while (current != null) : (current = current.?.next) {
- count += @boolToInt(current.?.addr != null);
+ count += @intFromBool(current.?.addr != null);
}
return count;
}
@@ -285,7 +285,7 @@ pub const GetAddrInfo = struct {
pub fn toCAres(this: GetAddrInfo) bun.c_ares.AddrInfo_hints {
var hints: bun.c_ares.AddrInfo_hints = undefined;
- @memset(std.mem.asBytes(&hints), 0, @sizeOf(bun.c_ares.AddrInfo_hints));
+ @memset(std.mem.asBytes(&hints)[0..@sizeOf(bun.c_ares.AddrInfo_hints)], 0);
hints.ai_family = this.options.family.toLibC();
hints.ai_socktype = this.options.socktype.toLibC();
@@ -320,7 +320,7 @@ pub const GetAddrInfo = struct {
}
var hints: std.c.addrinfo = undefined;
- @memset(std.mem.asBytes(&hints), 0, @sizeOf(std.c.addrinfo));
+ @memset(std.mem.asBytes(&hints)[0..@sizeOf(std.c.addrinfo)], 0);
hints.family = this.family.toLibC();
hints.socktype = this.socktype.toLibC();
@@ -793,7 +793,7 @@ pub const GetAddrInfoRequest = struct {
addr_info: ?*std.c.addrinfo,
arg: ?*anyopaque,
) callconv(.C) void {
- const this = @intToPtr(*GetAddrInfoRequest, @ptrToInt(arg));
+ const this = @ptrFromInt(*GetAddrInfoRequest, @intFromPtr(arg));
log("getAddrInfoAsyncCallback: status={d}", .{status});
if (this.backend == .libinfo) {
@@ -846,8 +846,8 @@ pub const GetAddrInfoRequest = struct {
err,
debug_timer,
});
- if (@enumToInt(err) != 0 or addrinfo == null) {
- this.* = .{ .err = @enumToInt(err) };
+ if (@intFromEnum(err) != 0 or addrinfo == null) {
+ this.* = .{ .err = @intFromEnum(err) };
return;
}
diff --git a/src/bun.js/api/bun/socket.zig b/src/bun.js/api/bun/socket.zig
index 48bfe4218..00e34a77d 100644
--- a/src/bun.js/api/bun/socket.zig
+++ b/src/bun.js/api/bun/socket.zig
@@ -398,10 +398,10 @@ pub const Listener = struct {
pub fn deinit(this: UnixOrHost) void {
switch (this) {
.unix => |u| {
- bun.default_allocator.destroy(@intToPtr([*]u8, @ptrToInt(u.ptr)));
+ bun.default_allocator.destroy(@ptrFromInt([*]u8, @intFromPtr(u.ptr)));
},
.host => |h| {
- bun.default_allocator.destroy(@intToPtr([*]u8, @ptrToInt(h.host.ptr)));
+ bun.default_allocator.destroy(@ptrFromInt([*]u8, @intFromPtr(h.host.ptr)));
},
}
}
@@ -472,7 +472,7 @@ pub const Listener = struct {
globalObject.bunVM().eventLoop().ensureWaker();
var socket_context = uws.us_create_bun_socket_context(
- @boolToInt(ssl_enabled),
+ @intFromBool(ssl_enabled),
uws.Loop.get().?,
@sizeOf(usize),
ctx_opts,
@@ -483,7 +483,7 @@ pub const Listener = struct {
hostname_or_unix.deinit();
}
- const errno = @enumToInt(std.c.getErrno(-1));
+ const errno = @intFromEnum(std.c.getErrno(-1));
if (errno != 0) {
err.put(globalObject, ZigString.static("errno"), JSValue.jsNumber(errno));
if (bun.C.SystemErrno.init(errno)) |str| {
@@ -544,7 +544,7 @@ pub const Listener = struct {
defer bun.default_allocator.free(host);
const socket = uws.us_socket_context_listen(
- @boolToInt(ssl_enabled),
+ @intFromBool(ssl_enabled),
socket_context,
normalizeHost(@as([:0]const u8, host)),
c.port,
@@ -560,13 +560,13 @@ pub const Listener = struct {
.unix => |u| {
var host = bun.default_allocator.dupeZ(u8, u) catch unreachable;
defer bun.default_allocator.free(host);
- break :brk uws.us_socket_context_listen_unix(@boolToInt(ssl_enabled), socket_context, host, socket_flags, 8);
+ break :brk uws.us_socket_context_listen_unix(@intFromBool(ssl_enabled), socket_context, host, socket_flags, 8);
},
}
} orelse {
defer {
hostname_or_unix.deinit();
- uws.us_socket_context_free(@boolToInt(ssl_enabled), socket_context);
+ uws.us_socket_context_free(@intFromBool(ssl_enabled), socket_context);
}
const err = globalObject.createErrorInstance(
@@ -575,7 +575,7 @@ pub const Listener = struct {
bun.span(hostname_or_unix.slice()),
},
);
- const errno = @enumToInt(std.c.getErrno(-1));
+ const errno = @intFromEnum(std.c.getErrno(-1));
if (errno != 0) {
err.put(globalObject, ZigString.static("errno"), JSValue.jsNumber(errno));
if (bun.C.SystemErrno.init(errno)) |str| {
@@ -789,7 +789,7 @@ pub const Listener = struct {
globalObject.bunVM().eventLoop().ensureWaker();
- var socket_context = uws.us_create_bun_socket_context(@boolToInt(ssl_enabled), uws.Loop.get().?, @sizeOf(usize), ctx_opts).?;
+ var socket_context = uws.us_create_bun_socket_context(@intFromBool(ssl_enabled), uws.Loop.get().?, @sizeOf(usize), ctx_opts).?;
var connection: Listener.UnixOrHost = if (port) |port_| .{
.host = .{ .host = (hostname_or_unix.cloneIfNeeded(bun.default_allocator) catch unreachable).slice(), .port = port_ },
} else .{
diff --git a/src/bun.js/api/bun/subprocess.zig b/src/bun.js/api/bun/subprocess.zig
index 832afac78..ba813c463 100644
--- a/src/bun.js/api/bun/subprocess.zig
+++ b/src/bun.js/api/bun/subprocess.zig
@@ -1011,7 +1011,7 @@ pub const Subprocess = struct {
if (signal.name()) |name|
return JSC.ZigString.init(name).toValueGC(global)
else
- return JSC.JSValue.jsNumber(@enumToInt(signal));
+ return JSC.JSValue.jsNumber(@intFromEnum(signal));
}
return JSC.JSValue.jsNull();
@@ -1535,9 +1535,9 @@ pub const Subprocess = struct {
}
if (std.os.W.IFSIGNALED(result.status)) {
- this.signal_code = @intToEnum(SignalCode, @truncate(u8, std.os.W.TERMSIG(result.status)));
+ this.signal_code = @enumFromInt(SignalCode, @truncate(u8, std.os.W.TERMSIG(result.status)));
} else if (std.os.W.IFSTOPPED(result.status)) {
- this.signal_code = @intToEnum(SignalCode, @truncate(u8, std.os.W.STOPSIG(result.status)));
+ this.signal_code = @enumFromInt(SignalCode, @truncate(u8, std.os.W.STOPSIG(result.status)));
}
if (!this.hasExited()) {
diff --git a/src/bun.js/api/ffi.zig b/src/bun.js/api/ffi.zig
index fe2b50955..e46e054ec 100644
--- a/src/bun.js/api/ffi.zig
+++ b/src/bun.js/api/ffi.zig
@@ -137,8 +137,8 @@ pub const FFI = struct {
globalThis,
ZigString.static("ptr"),
ZigString.static("ctx"),
- JSC.JSValue.fromPtrAddress(@ptrToInt(function_.step.compiled.ptr)),
- JSC.JSValue.fromPtrAddress(@ptrToInt(function_)),
+ JSC.JSValue.fromPtrAddress(@intFromPtr(function_.step.compiled.ptr)),
+ JSC.JSValue.fromPtrAddress(@intFromPtr(function_)),
);
},
}
@@ -523,7 +523,7 @@ pub const FFI = struct {
const int = val.to(i32);
switch (int) {
0...ABIType.max => {
- abi_types.appendAssumeCapacity(@intToEnum(ABIType, int));
+ abi_types.appendAssumeCapacity(@enumFromInt(ABIType, int));
continue;
},
else => {
@@ -560,7 +560,7 @@ pub const FFI = struct {
const int = ret_value.toInt32();
switch (int) {
0...ABIType.max => {
- return_type = @intToEnum(ABIType, int);
+ return_type = @enumFromInt(ABIType, int);
break :brk;
},
else => {
@@ -594,11 +594,11 @@ pub const FFI = struct {
if (ptr.isNumber()) {
const num = ptr.asPtrAddress();
if (num > 0)
- function.symbol_from_dynamic_library = @intToPtr(*anyopaque, num);
+ function.symbol_from_dynamic_library = @ptrFromInt(*anyopaque, num);
} else {
const num = ptr.toUInt64NoTruncate();
if (num > 0) {
- function.symbol_from_dynamic_library = @intToPtr(*anyopaque, num);
+ function.symbol_from_dynamic_library = @ptrFromInt(*anyopaque, num);
}
}
}
@@ -866,7 +866,7 @@ pub const FFI = struct {
c: u8,
byte_count: usize,
) callconv(.C) void {
- @memset(dest, c, byte_count);
+ @memset(dest[0..byte_count], c);
}
noinline fn memcpy(
@@ -874,7 +874,7 @@ pub const FFI = struct {
noalias source: [*]const u8,
byte_count: usize,
) callconv(.C) void {
- @memcpy(dest, source, byte_count);
+ @memcpy(dest[0..byte_count], source[0..byte_count]);
}
pub fn define(state: *TCC.TCCState) void {
@@ -1205,7 +1205,7 @@ pub const FFI = struct {
writer: anytype,
) !void {
{
- const ptr = @ptrToInt(globalObject);
+ const ptr = @intFromPtr(globalObject);
const fmt = bun.fmt.hexIntUpper(ptr);
try writer.print("#define JS_GLOBAL_OBJECT (void*)0x{any}ULL\n", .{fmt});
}
@@ -1290,7 +1290,7 @@ pub const FFI = struct {
var inner_buf: []u8 = &.{};
{
- const ptr = @ptrToInt(context_ptr);
+ const ptr = @intFromPtr(context_ptr);
const fmt = bun.fmt.hexIntUpper(ptr);
if (this.arg_types.items.len > 0) {
@@ -1355,7 +1355,7 @@ pub const FFI = struct {
function = 17,
- pub const max = @enumToInt(ABIType.function);
+ pub const max = @intFromEnum(ABIType.function);
/// Types that we can directly pass through as an `int64_t`
pub fn needsACastInC(this: ABIType) bool {
@@ -1414,11 +1414,11 @@ pub const FFI = struct {
// these are not all valid identifiers
try writer.writeAll(self.name);
try writer.writeAll("']:");
- try std.fmt.formatInt(@enumToInt(self.entry), 10, .lower, .{}, writer);
+ try std.fmt.formatInt(@intFromEnum(self.entry), 10, .lower, .{}, writer);
try writer.writeAll(",'");
- try std.fmt.formatInt(@enumToInt(self.entry), 10, .lower, .{}, writer);
+ try std.fmt.formatInt(@intFromEnum(self.entry), 10, .lower, .{}, writer);
try writer.writeAll("':");
- try std.fmt.formatInt(@enumToInt(self.entry), 10, .lower, .{}, writer);
+ try std.fmt.formatInt(@intFromEnum(self.entry), 10, .lower, .{}, writer);
}
};
pub const map_to_js_object = brk: {
@@ -1426,7 +1426,7 @@ pub const FFI = struct {
for (map, 0..) |item, i| {
var fmt = EnumMapFormatter{ .name = item.@"0", .entry = item.@"1" };
count += std.fmt.count("{}", .{fmt});
- count += @boolToInt(i > 0);
+ count += @intFromBool(i > 0);
}
var buf: [count]u8 = undefined;
diff --git a/src/bun.js/api/html_rewriter.zig b/src/bun.js/api/html_rewriter.zig
index bfbdb9a37..93a41b095 100644
--- a/src/bun.js/api/html_rewriter.zig
+++ b/src/bun.js/api/html_rewriter.zig
@@ -472,13 +472,13 @@ pub const HTMLRewriter = struct {
pub fn onFinishedLoading(sink: *BufferOutputSink, bytes: JSC.WebCore.Blob.Store.ReadFile.ResultType) void {
switch (bytes) {
.err => |err| {
- if (sink.response.body.value == .Locked and @ptrToInt(sink.response.body.value.Locked.task) == @ptrToInt(sink) and
+ if (sink.response.body.value == .Locked and @intFromPtr(sink.response.body.value.Locked.task) == @intFromPtr(sink) and
sink.response.body.value.Locked.promise == null)
{
sink.response.body.value = .{ .Empty = {} };
// is there a pending promise?
// we will need to reject it
- } else if (sink.response.body.value == .Locked and @ptrToInt(sink.response.body.value.Locked.task) == @ptrToInt(sink) and
+ } else if (sink.response.body.value == .Locked and @intFromPtr(sink.response.body.value.Locked.task) == @intFromPtr(sink) and
sink.response.body.value.Locked.promise != null)
{
sink.response.body.value.Locked.onReceiveValue = null;
diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig
index 37bc601a5..a56ff971f 100644
--- a/src/bun.js/api/server.zig
+++ b/src/bun.js/api/server.zig
@@ -168,7 +168,7 @@ pub const ServerConfig = struct {
pub fn asUSockets(this_: ?SSLConfig) uws.us_bun_socket_context_options_t {
var ctx_opts: uws.us_bun_socket_context_options_t = undefined;
- @memset(@ptrCast([*]u8, &ctx_opts), 0, @sizeOf(uws.us_bun_socket_context_options_t));
+ @memset(@ptrCast([*]u8, &ctx_opts)[0..@sizeOf(uws.us_bun_socket_context_options_t)], 0);
if (this_) |ssl_config| {
if (ssl_config.key_file_name != null)
@@ -181,7 +181,7 @@ pub const ServerConfig = struct {
ctx_opts.dh_params_file_name = ssl_config.dh_params_file_name;
if (ssl_config.passphrase != null)
ctx_opts.passphrase = ssl_config.passphrase;
- ctx_opts.ssl_prefer_low_memory_usage = @boolToInt(ssl_config.low_memory_mode);
+ ctx_opts.ssl_prefer_low_memory_usage = @intFromBool(ssl_config.low_memory_mode);
if (ssl_config.key) |key| {
ctx_opts.key = key.ptr;
@@ -1240,7 +1240,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
.reason = .fetch_event_handler,
.cwd = VirtualMachine.get().bundler.fs.top_level_dir,
.problems = Api.Problems{
- .code = @truncate(u16, @errorToInt(err)),
+ .code = @truncate(u16, @intFromError(err)),
.name = @errorName(err),
.exceptions = exceptions,
.build = log.toAPI(allocator) catch unreachable,
@@ -1790,7 +1790,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
}
var err = JSC.Node.Syscall.Error{
- .errno = @intCast(JSC.Node.Syscall.Error.Int, @enumToInt(std.os.E.INVAL)),
+ .errno = @intCast(JSC.Node.Syscall.Error.Int, @intFromEnum(std.os.E.INVAL)),
.syscall = .sendfile,
};
var sys = err.withPathLike(file.pathlike).toSystemError();
@@ -1809,7 +1809,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
}
var err = JSC.Node.Syscall.Error{
- .errno = @intCast(JSC.Node.Syscall.Error.Int, @enumToInt(std.os.E.INVAL)),
+ .errno = @intCast(JSC.Node.Syscall.Error.Int, @intFromEnum(std.os.E.INVAL)),
.syscall = .sendfile,
};
var sys = err.withPathLike(file.pathlike).toSystemError();
@@ -2113,7 +2113,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
const streamLog = Output.scoped(.ReadableStream, false);
pub fn didUpgradeWebSocket(this: *RequestContext) bool {
- return @ptrToInt(this.upgrade_context) == std.math.maxInt(usize);
+ return @intFromPtr(this.upgrade_context) == std.math.maxInt(usize);
}
pub fn onResponse(
@@ -2874,7 +2874,7 @@ fn NewRequestContext(comptime ssl_enabled: bool, comptime debug_mode: bool, comp
const prev_len = bytes.items.len;
bytes.items.len = total;
var slice = bytes.items[prev_len..];
- @memcpy(slice.ptr, chunk.ptr, chunk.len);
+ @memcpy(slice[0..chunk.len], chunk);
body.value = .{
.InternalBlob = .{
.bytes = bytes.toManaged(this.allocator),
@@ -3200,7 +3200,7 @@ pub const WebSocketServer = struct {
globalObject.throwInvalidArguments("websocket expects maxPayloadLength to be an integer", .{});
return null;
}
- server.maxPayloadLength = @intCast(u32, @truncate(i33, @max(value.toInt64(), 0)));
+ server.maxPayloadLength = @intCast(u32, @max(value.toInt64(), 0));
}
}
if (object.get(globalObject, "idleTimeout")) |value| {
@@ -3220,7 +3220,7 @@ pub const WebSocketServer = struct {
return null;
}
- server.backpressureLimit = @intCast(u32, @truncate(i33, @max(value.toInt64(), 0)));
+ server.backpressureLimit = @intCast(u32, @max(value.toInt64(), 0));
}
}
// if (object.get(globalObject, "sendPings")) |value| {
@@ -3366,7 +3366,7 @@ pub const ServerWebSocket = struct {
opcode: uws.Opcode,
) void {
log("onMessage({d}): {s}", .{
- @enumToInt(opcode),
+ @intFromEnum(opcode),
message,
});
const onMessageHandler = this.handler.onMessage;
@@ -4436,7 +4436,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
return JSValue.jsNumber(
// if 0, return 0
// else return number of bytes sent
- @as(i32, @boolToInt(uws.AnyWebSocket.publishWithOptions(ssl_enabled, app, topic_slice.slice(), buffer.slice(), .binary, compress))) * @intCast(i32, @truncate(u31, buffer.len)),
+ @as(i32, @intFromBool(uws.AnyWebSocket.publishWithOptions(ssl_enabled, app, topic_slice.slice(), buffer.slice(), .binary, compress))) * @intCast(i32, @truncate(u31, buffer.len)),
);
}
@@ -4451,7 +4451,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
return JSValue.jsNumber(
// if 0, return 0
// else return number of bytes sent
- @as(i32, @boolToInt(uws.AnyWebSocket.publishWithOptions(ssl_enabled, app, topic_slice.slice(), buffer, .text, compress))) * @intCast(i32, @truncate(u31, buffer.len)),
+ @as(i32, @intFromBool(uws.AnyWebSocket.publishWithOptions(ssl_enabled, app, topic_slice.slice(), buffer, .text, compress))) * @intCast(i32, @truncate(u31, buffer.len)),
);
}
@@ -4488,7 +4488,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
return JSC.jsBoolean(false);
}
- if (upgrader.upgrade_context == null or @ptrToInt(upgrader.upgrade_context) == std.math.maxInt(usize)) {
+ if (upgrader.upgrade_context == null or @intFromPtr(upgrader.upgrade_context) == std.math.maxInt(usize)) {
return JSC.jsBoolean(false);
}
const resp = upgrader.resp.?;
@@ -4582,7 +4582,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
// See https://github.com/oven-sh/bun/issues/1339
// obviously invalid pointer marks it as used
- upgrader.upgrade_context = @intToPtr(*uws.uws_socket_context_s, std.math.maxInt(usize));
+ upgrader.upgrade_context = @ptrFromInt(*uws.uws_socket_context_s, std.math.maxInt(usize));
request.upgrader = null;
resp.clearAborted();
@@ -4947,7 +4947,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
if (reason.len == 0) {
break;
}
- @memcpy(output_buf[written..].ptr, reason.ptr, reason.len);
+ @memcpy(output_buf[written..][0..reason.len], reason);
written += reason.len;
}
@@ -4958,7 +4958,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
if (reason.len > 0) {
output_buf[written..][0.." via ".len].* = " via ".*;
written += " via ".len;
- @memcpy(output_buf[written..].ptr, reason.ptr, reason.len);
+ @memcpy(output_buf[written..][0..reason.len], reason);
written += reason.len;
}
}
@@ -4970,7 +4970,7 @@ pub fn NewServer(comptime ssl_enabled_: bool, comptime debug_mode_: bool) type {
if (reason.len > 0) {
output_buf[written..][0] = ' ';
written += 1;
- @memcpy(output_buf[written..].ptr, reason.ptr, reason.len);
+ @memcpy(output_buf[written..][0..reason.len], reason);
written += reason.len;
}
}
diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig
index 038f7f38b..4a1249b5d 100644
--- a/src/bun.js/base.zig
+++ b/src/bun.js/base.zig
@@ -1291,23 +1291,27 @@ pub fn NewClassWithInstanceType(
const static_properties: [property_names.len + 1]js.JSStaticValue = brk: {
var props: [property_names.len + 1]js.JSStaticValue = undefined;
- std.mem.set(
- js.JSStaticValue,
+ @memset(
&props,
js.JSStaticValue{
- .name = @intToPtr([*c]const u8, 0),
+ .name = @ptrFromInt([*c]const u8, 0),
.getProperty = null,
.setProperty = null,
.attributes = js.JSPropertyAttributes.kJSPropertyAttributeNone,
},
);
+ if (property_name_literals.len > 0 and @TypeOf(property_name_literals[0]) == [:0]const u8) {
+ @compileError("@typeInfo() struct field names are null-terminated");
+ }
for (property_name_literals, 0..) |lit, i| {
props[i] = brk2: {
var static_prop = JSC.C.JSStaticValue{
- .name = lit.ptr[0..lit.len :0],
+ // TODO: update when @typeInfo struct field names are sentinel terminated
+ // https://github.com/ziglang/zig/issues/16072
+ .name = lit ++ .{0},
.getProperty = null,
.setProperty = null,
- .attributes = @intToEnum(js.JSPropertyAttributes, 0),
+ .attributes = @enumFromInt(js.JSPropertyAttributes, 0),
};
static_prop.getProperty = StaticProperty(i).getter;
@@ -1396,14 +1400,14 @@ pub fn NewClassWithInstanceType(
const ctxfn = CtxField.rfn;
const Func: std.builtin.Type.Fn = @typeInfo(@TypeOf(if (@typeInfo(@TypeOf(ctxfn)) == .Pointer) ctxfn.* else ctxfn)).Fn;
- var attributes: c_uint = @enumToInt(js.JSPropertyAttributes.kJSPropertyAttributeNone);
+ var attributes: c_uint = @intFromEnum(js.JSPropertyAttributes.kJSPropertyAttributeNone);
if (comptime is_read_only or hasReadOnly(@TypeOf(CtxField))) {
- attributes |= @enumToInt(js.JSPropertyAttributes.kJSPropertyAttributeReadOnly);
+ attributes |= @intFromEnum(js.JSPropertyAttributes.kJSPropertyAttributeReadOnly);
}
if (comptime hasEnumerable(@TypeOf(CtxField)) and !CtxField.enumerable) {
- attributes |= @enumToInt(js.JSPropertyAttributes.kJSPropertyAttributeDontEnum);
+ attributes |= @intFromEnum(js.JSPropertyAttributes.kJSPropertyAttributeDontEnum);
}
const PointerType = comptime brk: {
@@ -1419,7 +1423,7 @@ pub fn NewClassWithInstanceType(
PointerType,
if (@typeInfo(@TypeOf(ctxfn)) == .Pointer) ctxfn.* else ctxfn,
).rfn,
- .attributes = @intToEnum(js.JSPropertyAttributes, attributes),
+ .attributes = @enumFromInt(js.JSPropertyAttributes, attributes),
};
count += 1;
@@ -1438,12 +1442,12 @@ pub fn NewClassWithInstanceType(
def.hasInstance = &staticFunctions.hasInstance;
} else {
const attributes: js.JSPropertyAttributes = brk: {
- var base = @enumToInt(js.JSPropertyAttributes.kJSPropertyAttributeNone);
+ var base = @intFromEnum(js.JSPropertyAttributes.kJSPropertyAttributeNone);
if (is_read_only)
- base |= @enumToInt(js.JSPropertyAttributes.kJSPropertyAttributeReadOnly);
+ base |= @intFromEnum(js.JSPropertyAttributes.kJSPropertyAttributeReadOnly);
- break :brk @intToEnum(js.JSPropertyAttributes, base);
+ break :brk @enumFromInt(js.JSPropertyAttributes, base);
};
__static_functions[count] = js.JSStaticFunction{
@@ -1834,7 +1838,7 @@ pub const ArrayBuffer = extern struct {
this.ptr,
this.byte_len,
MarkedArrayBuffer_deallocator,
- @intToPtr(*anyopaque, @ptrToInt(&bun.default_allocator)),
+ @ptrFromInt(*anyopaque, @intFromPtr(&bun.default_allocator)),
exception,
));
}
@@ -1845,7 +1849,7 @@ pub const ArrayBuffer = extern struct {
this.ptr,
this.byte_len,
MarkedArrayBuffer_deallocator,
- @intToPtr(*anyopaque, @ptrToInt(&bun.default_allocator)),
+ @ptrFromInt(*anyopaque, @intFromPtr(&bun.default_allocator)),
exception,
));
}
@@ -2068,7 +2072,7 @@ pub const RefString = struct {
pub const Callback = fn (ctx: *anyopaque, str: *RefString) void;
pub fn computeHash(input: []const u8) u32 {
- return std.hash.XxHash32.hash(input);
+ return std.hash.XxHash32.hash(0, input);
}
pub fn slice(this: *RefString) []const u8 {
@@ -3355,7 +3359,7 @@ pub const FilePoll = struct {
const DNSResolver = JSC.DNS.DNSResolver;
const GetAddrInfoRequest = JSC.DNS.GetAddrInfoRequest;
const Deactivated = opaque {
- pub var owner: Owner = Owner.init(@intToPtr(*Deactivated, @as(usize, 0xDEADBEEF)));
+ pub var owner: Owner = Owner.init(@ptrFromInt(*Deactivated, @as(usize, 0xDEADBEEF)));
};
pub const Owner = bun.TaggedPointerUnion(.{
@@ -3610,7 +3614,7 @@ pub const FilePoll = struct {
return;
this.flags.insert(.disable);
- vm.uws_event_loop.?.active -= @as(u32, @boolToInt(this.flags.contains(.has_incremented_poll_count)));
+ vm.uws_event_loop.?.active -= @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn enableKeepingProcessAlive(this: *FilePoll, vm: *JSC.VirtualMachine) void {
@@ -3618,7 +3622,7 @@ pub const FilePoll = struct {
return;
this.flags.remove(.disable);
- vm.uws_event_loop.?.active += @as(u32, @boolToInt(this.flags.contains(.has_incremented_poll_count)));
+ vm.uws_event_loop.?.active += @as(u32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
}
pub fn canActivate(this: *const FilePoll) bool {
@@ -3628,16 +3632,16 @@ pub const FilePoll = struct {
/// Only intended to be used from EventLoop.Pollable
pub fn deactivate(this: *FilePoll, loop: *uws.Loop) void {
std.debug.assert(this.flags.contains(.has_incremented_poll_count));
- loop.num_polls -= @as(i32, @boolToInt(this.flags.contains(.has_incremented_poll_count)));
- loop.active -|= @as(u32, @boolToInt(!this.flags.contains(.disable) and this.flags.contains(.has_incremented_poll_count)));
+ loop.num_polls -= @as(i32, @intFromBool(this.flags.contains(.has_incremented_poll_count)));
+ loop.active -|= @as(u32, @intFromBool(!this.flags.contains(.disable) and this.flags.contains(.has_incremented_poll_count)));
this.flags.remove(.has_incremented_poll_count);
}
/// Only intended to be used from EventLoop.Pollable
pub fn activate(this: *FilePoll, loop: *uws.Loop) void {
- loop.num_polls += @as(i32, @boolToInt(!this.flags.contains(.has_incremented_poll_count)));
- loop.active += @as(u32, @boolToInt(!this.flags.contains(.disable) and !this.flags.contains(.has_incremented_poll_count)));
+ loop.num_polls += @as(i32, @intFromBool(!this.flags.contains(.has_incremented_poll_count)));
+ loop.active += @as(u32, @intFromBool(!this.flags.contains(.disable) and !this.flags.contains(.has_incremented_poll_count)));
this.flags.insert(.has_incremented_poll_count);
}
@@ -3738,7 +3742,7 @@ pub const FilePoll = struct {
else => unreachable,
};
- var event = linux.epoll_event{ .events = flags, .data = .{ .u64 = @ptrToInt(Pollable.init(this).ptr()) } };
+ var event = linux.epoll_event{ .events = flags, .data = .{ .u64 = @intFromPtr(Pollable.init(this).ptr()) } };
const ctl = linux.epoll_ctl(
watcher_fd,
@@ -3759,7 +3763,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_READ,
.data = 0,
.fflags = 0,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
@@ -3768,7 +3772,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_WRITE,
.data = 0,
.fflags = 0,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
@@ -3777,7 +3781,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_PROC,
.data = 0,
.fflags = std.c.NOTE_EXIT,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
@@ -3786,7 +3790,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_MACHPORT,
.data = 0,
.fflags = 0,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_ADD | one_shot_flag,
.ext = .{ this.generation_number, 0 },
},
@@ -3911,7 +3915,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_READ,
.data = 0,
.fflags = 0,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
@@ -3920,7 +3924,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_MACHPORT,
.data = 0,
.fflags = 0,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
@@ -3929,7 +3933,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_WRITE,
.data = 0,
.fflags = 0,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
@@ -3938,7 +3942,7 @@ pub const FilePoll = struct {
.filter = std.os.system.EVFILT_PROC,
.data = 0,
.fflags = std.c.NOTE_EXIT,
- .udata = @ptrToInt(Pollable.init(this).ptr()),
+ .udata = @intFromPtr(Pollable.init(this).ptr()),
.flags = std.c.EV_DELETE,
.ext = .{ 0, 0 },
},
@@ -3973,7 +3977,7 @@ pub const FilePoll = struct {
const errno = std.c.getErrno(rc);
switch (rc) {
- std.math.minInt(@TypeOf(rc))...-1 => return JSC.Maybe(void).errnoSys(@enumToInt(errno), .kevent).?,
+ std.math.minInt(@TypeOf(rc))...-1 => return JSC.Maybe(void).errnoSys(@intFromEnum(errno), .kevent).?,
else => {},
}
} else {
diff --git a/src/bun.js/bindings/FFI.zig b/src/bun.js/bindings/FFI.zig
index 087d8308c..fde4a8d30 100644
--- a/src/bun.js/bindings/FFI.zig
+++ b/src/bun.js/bindings/FFI.zig
@@ -42,7 +42,7 @@ pub inline fn JSVALUE_TO_UINT64(arg_value: EncodedJSValue) u64 {
return @bitCast(u64, @as(c_longlong, JSVALUE_TO_INT32(value)));
}
if (JSVALUE_IS_NUMBER(value)) {
- return @floatToInt(u64, JSVALUE_TO_DOUBLE(value));
+ return @intFromFloat(u64, JSVALUE_TO_DOUBLE(value));
}
return JSVALUE_TO_UINT64_SLOW(value);
}
@@ -52,7 +52,7 @@ pub inline fn JSVALUE_TO_INT64(arg_value: EncodedJSValue) i64 {
return @bitCast(i64, @as(c_longlong, JSVALUE_TO_INT32(value)));
}
if (JSVALUE_IS_NUMBER(value)) {
- return @floatToInt(i64, JSVALUE_TO_DOUBLE(value));
+ return @intFromFloat(i64, JSVALUE_TO_DOUBLE(value));
}
return JSVALUE_TO_INT64_SLOW(value);
}
@@ -67,7 +67,7 @@ pub inline fn UINT64_TO_JSVALUE(arg_globalObject: ?*anyopaque, arg_val: u64) Enc
return INT32_TO_JSVALUE(@bitCast(i32, @truncate(c_uint, val)));
}
if (val < @bitCast(c_ulonglong, @as(c_longlong, @as(c_long, 9007199254740991)))) {
- return DOUBLE_TO_JSVALUE(@intToFloat(f64, val));
+ return DOUBLE_TO_JSVALUE(@floatFromInt(f64, val));
}
return UINT64_TO_JSVALUE_SLOW(@ptrCast(*@import("./bindings.zig").JSGlobalObject, globalObject.?), val).asEncoded();
}
@@ -78,7 +78,7 @@ pub inline fn INT64_TO_JSVALUE(arg_globalObject: ?*anyopaque, arg_val: i64) Enco
return INT32_TO_JSVALUE(@bitCast(i32, @truncate(c_int, val)));
}
if ((val >= @bitCast(c_longlong, @as(c_longlong, -@as(c_long, 9007199254740991)))) and (val <= @bitCast(c_longlong, @as(c_longlong, @as(c_long, 9007199254740991))))) {
- return DOUBLE_TO_JSVALUE(@intToFloat(f64, val));
+ return DOUBLE_TO_JSVALUE(@floatFromInt(f64, val));
}
return INT64_TO_JSVALUE_SLOW(@ptrCast(*@import("./bindings.zig").JSGlobalObject, globalObject.?), val).asEncoded();
}
@@ -97,18 +97,18 @@ pub inline fn FLOAT_TO_JSVALUE(arg_val: f32) EncodedJSValue {
pub inline fn BOOLEAN_TO_JSVALUE(arg_val: @"bool") EncodedJSValue {
var val = arg_val;
var res: EncodedJSValue = undefined;
- res.asInt64 = @bitCast(i64, @as(c_longlong, if (@as(c_int, @boolToInt(val)) != 0) (@as(c_int, 2) | @as(c_int, 4)) | @as(c_int, 1) else (@as(c_int, 2) | @as(c_int, 4)) | @as(c_int, 0)));
+ res.asInt64 = @bitCast(i64, @as(c_longlong, if (@as(c_int, @intFromBool(val)) != 0) (@as(c_int, 2) | @as(c_int, 4)) | @as(c_int, 1) else (@as(c_int, 2) | @as(c_int, 4)) | @as(c_int, 0)));
return res;
}
pub inline fn PTR_TO_JSVALUE(arg_ptr: ?*anyopaque) EncodedJSValue {
var ptr = arg_ptr;
var val: EncodedJSValue = undefined;
- val.asInt64 = @intCast(i64, @ptrToInt(ptr)) + (@as(c_longlong, 1) << @intCast(@import("std").math.Log2Int(c_longlong), 49));
+ val.asInt64 = @intCast(i64, @intFromPtr(ptr)) + (@as(c_longlong, 1) << @intCast(@import("std").math.Log2Int(c_longlong), 49));
return val;
}
pub inline fn JSVALUE_TO_PTR(arg_val: EncodedJSValue) ?*anyopaque {
var val = arg_val;
- return @intToPtr(?*anyopaque, val.asInt64 - (@as(c_longlong, 1) << @intCast(@import("std").math.Log2Int(c_longlong), 49)));
+ return @ptrFromInt(?*anyopaque, val.asInt64 - (@as(c_longlong, 1) << @intCast(@import("std").math.Log2Int(c_longlong), 49)));
}
pub inline fn JSVALUE_TO_INT32(arg_val: EncodedJSValue) i32 {
var val = arg_val;
diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig
index 35c9d26fa..581fc6f85 100644
--- a/src/bun.js/bindings/bindings.zig
+++ b/src/bun.js/bindings/bindings.zig
@@ -370,11 +370,11 @@ pub const ZigString = extern struct {
}
pub fn markStatic(this: *ZigString) void {
- this.ptr = @intToPtr([*]const u8, @ptrToInt(this.ptr) | (1 << 60));
+ this.ptr = @ptrFromInt([*]const u8, @intFromPtr(this.ptr) | (1 << 60));
}
pub fn isStatic(this: *const ZigString) bool {
- return @ptrToInt(this.ptr) & (1 << 60) != 0;
+ return @intFromPtr(this.ptr) & (1 << 60) != 0;
}
pub const Slice = struct {
@@ -483,7 +483,7 @@ pub const ZigString = extern struct {
}
pub fn mut(this: Slice) []u8 {
- return @intToPtr([*]u8, @ptrToInt(this.ptr))[0..this.len];
+ return @ptrFromInt([*]u8, @intFromPtr(this.ptr))[0..this.len];
}
/// Does nothing if the slice is not allocated
@@ -504,7 +504,7 @@ pub const ZigString = extern struct {
pub const namespace = "";
pub inline fn is16Bit(this: *const ZigString) bool {
- return (@ptrToInt(this._unsafe_ptr_do_not_use) & (1 << 63)) != 0;
+ return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 63)) != 0;
}
pub inline fn utf16Slice(this: *const ZigString) []align(1) const u16 {
@@ -539,7 +539,7 @@ pub const ZigString = extern struct {
}
pub fn sortDesc(slice_: []ZigString) void {
- std.sort.sort(ZigString, slice_, {}, cmpDesc);
+ std.sort.block(ZigString, slice_, {}, cmpDesc);
}
pub fn cmpDesc(_: void, a: ZigString, b: ZigString) bool {
@@ -547,7 +547,7 @@ pub const ZigString = extern struct {
}
pub fn sortAsc(slice_: []ZigString) void {
- std.sort.sort(ZigString, slice_, {}, cmpAsc);
+ std.sort.block(ZigString, slice_, {}, cmpAsc);
}
pub fn cmpAsc(_: void, a: ZigString, b: ZigString) bool {
@@ -641,15 +641,15 @@ pub const ZigString = extern struct {
}
pub fn isUTF8(this: ZigString) bool {
- return (@ptrToInt(this._unsafe_ptr_do_not_use) & (1 << 61)) != 0;
+ return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 61)) != 0;
}
pub fn markUTF8(this: *ZigString) void {
- this._unsafe_ptr_do_not_use = @intToPtr([*]const u8, @ptrToInt(this._unsafe_ptr_do_not_use) | (1 << 61));
+ this._unsafe_ptr_do_not_use = @ptrFromInt([*]const u8, @intFromPtr(this._unsafe_ptr_do_not_use) | (1 << 61));
}
pub fn markUTF16(this: *ZigString) void {
- this._unsafe_ptr_do_not_use = @intToPtr([*]const u8, @ptrToInt(this._unsafe_ptr_do_not_use) | (1 << 63));
+ this._unsafe_ptr_do_not_use = @ptrFromInt([*]const u8, @intFromPtr(this._unsafe_ptr_do_not_use) | (1 << 63));
}
pub fn setOutputEncoding(this: *ZigString) void {
@@ -658,7 +658,7 @@ pub const ZigString = extern struct {
}
pub inline fn isGloballyAllocated(this: ZigString) bool {
- return (@ptrToInt(this._unsafe_ptr_do_not_use) & (1 << 62)) != 0;
+ return (@intFromPtr(this._unsafe_ptr_do_not_use) & (1 << 62)) != 0;
}
pub inline fn deinitGlobal(this: ZigString) void {
@@ -668,7 +668,7 @@ pub const ZigString = extern struct {
pub const mark = markGlobal;
pub inline fn markGlobal(this: *ZigString) void {
- this._unsafe_ptr_do_not_use = @intToPtr([*]const u8, @ptrToInt(this._unsafe_ptr_do_not_use) | (1 << 62));
+ this._unsafe_ptr_do_not_use = @ptrFromInt([*]const u8, @intFromPtr(this._unsafe_ptr_do_not_use) | (1 << 62));
}
pub fn format(self: ZigString, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void {
@@ -694,7 +694,7 @@ pub const ZigString = extern struct {
inline fn untagged(ptr: [*]const u8) [*]const u8 {
// this can be null ptr, so long as it's also a 0 length string
@setRuntimeSafety(false);
- return @intToPtr([*]const u8, @truncate(u53, @ptrToInt(ptr)));
+ return @ptrFromInt([*]const u8, @truncate(u53, @intFromPtr(ptr)));
}
pub fn slice(this: *const ZigString) []const u8 {
@@ -1303,7 +1303,7 @@ pub const FetchHeaders = opaque {
this: *FetchHeaders,
name_: HTTPHeaderName,
) bool {
- return fastHas_(this, @enumToInt(name_));
+ return fastHas_(this, @intFromEnum(name_));
}
pub fn fastGet(
@@ -1311,7 +1311,7 @@ pub const FetchHeaders = opaque {
name_: HTTPHeaderName,
) ?ZigString {
var str = ZigString.init("");
- fastGet_(this, @enumToInt(name_), &str);
+ fastGet_(this, @intFromEnum(name_), &str);
if (str.len == 0) {
return null;
}
@@ -1441,7 +1441,7 @@ pub const FetchHeaders = opaque {
this: *FetchHeaders,
header: HTTPHeaderName,
) void {
- return fastRemove_(this, @enumToInt(header));
+ return fastRemove_(this, @intFromEnum(header));
}
pub fn fastRemove_(
@@ -1611,11 +1611,11 @@ pub const Sizes = @import("../bindings/sizes.zig");
pub const JSUint8Array = opaque {
pub const name = "Uint8Array_alias";
pub fn ptr(this: *JSUint8Array) [*]u8 {
- return @intToPtr(*[*]u8, @ptrToInt(this) + Sizes.Bun_FFI_PointerOffsetToTypedArrayVector).*;
+ return @ptrFromInt(*[*]u8, @intFromPtr(this) + Sizes.Bun_FFI_PointerOffsetToTypedArrayVector).*;
}
pub fn len(this: *JSUint8Array) usize {
- return @intToPtr(*usize, @ptrToInt(this) + Sizes.Bun_FFI_PointerOffsetToTypedArrayLength).*;
+ return @ptrFromInt(*usize, @intFromPtr(this) + Sizes.Bun_FFI_PointerOffsetToTypedArrayLength).*;
}
pub fn slice(this: *JSUint8Array) []u8 {
@@ -3156,7 +3156,7 @@ pub const JSValue = enum(JSValueReprInt) {
pub fn isObject(this: JSType) bool {
// inline constexpr bool isObjectType(JSType type) { return type >= ObjectType; }
- return @enumToInt(this) >= @enumToInt(JSType.Object);
+ return @intFromEnum(this) >= @intFromEnum(JSType.Object);
}
pub fn isFunction(this: JSType) bool {
@@ -3311,7 +3311,7 @@ pub const JSValue = enum(JSValueReprInt) {
};
pub inline fn cast(ptr: anytype) JSValue {
- return @intToEnum(JSValue, @bitCast(i64, @ptrToInt(ptr)));
+ return @enumFromInt(JSValue, @bitCast(i64, @intFromPtr(ptr)));
}
pub fn coerceToInt32(this: JSValue, globalThis: *JSC.JSGlobalObject) i32 {
@@ -3808,7 +3808,7 @@ pub const JSValue = enum(JSValueReprInt) {
return jsNumberFromInt32(@intCast(i32, i));
}
- return jsNumberFromDouble(@intToFloat(f64, @truncate(i52, i)));
+ return jsNumberFromDouble(@floatFromInt(f64, @truncate(i52, i)));
}
pub inline fn toJS(this: JSValue, _: *const JSGlobalObject) JSValue {
@@ -3820,7 +3820,7 @@ pub const JSValue = enum(JSValueReprInt) {
return jsNumberFromInt32(@intCast(i32, i));
}
- return jsNumberFromDouble(@intToFloat(f64, @intCast(i52, @truncate(u51, i))));
+ return jsNumberFromDouble(@floatFromInt(f64, @intCast(i52, @truncate(u51, i))));
}
pub fn coerceDoubleTruncatingIntoInt64(this: JSValue) i64 {
@@ -3834,7 +3834,7 @@ pub const JSValue = enum(JSValueReprInt) {
return if (double_value < 0) @as(i64, std.math.minInt(i64)) else @as(i64, std.math.maxInt(i64));
}
- return @floatToInt(
+ return @intFromFloat(
i64,
double_value,
);
@@ -3871,26 +3871,26 @@ pub const JSValue = enum(JSValueReprInt) {
}
pub inline fn isUndefined(this: JSValue) bool {
- return @enumToInt(this) == 0xa;
+ return @intFromEnum(this) == 0xa;
}
pub inline fn isNull(this: JSValue) bool {
- return @enumToInt(this) == 0x2;
+ return @intFromEnum(this) == 0x2;
}
pub inline fn isEmptyOrUndefinedOrNull(this: JSValue) bool {
- return switch (@enumToInt(this)) {
+ return switch (@intFromEnum(this)) {
0, 0xa, 0x2 => true,
else => false,
};
}
pub fn isUndefinedOrNull(this: JSValue) bool {
- return switch (@enumToInt(this)) {
+ return switch (@intFromEnum(this)) {
0xa, 0x2 => true,
else => false,
};
}
/// Empty as in "JSValue {}" rather than an empty string
pub inline fn isEmpty(this: JSValue) bool {
- return switch (@enumToInt(this)) {
+ return switch (@intFromEnum(this)) {
0 => true,
else => false,
};
@@ -4016,7 +4016,7 @@ pub const JSValue = enum(JSValueReprInt) {
pub inline fn isCell(this: JSValue) bool {
return switch (this) {
.zero, .undefined, .null, .true, .false => false,
- else => (@bitCast(u64, @enumToInt(this)) & FFI.NotCellMask) == 0,
+ else => (@bitCast(u64, @intFromEnum(this)) & FFI.NotCellMask) == 0,
};
}
@@ -4179,7 +4179,7 @@ pub const JSValue = enum(JSValueReprInt) {
// intended to be more lightweight than ZigString
pub fn fastGet(this: JSValue, global: *JSGlobalObject, builtin_name: BuiltinName) ?JSValue {
- const result = fastGet_(this, global, @enumToInt(builtin_name));
+ const result = fastGet_(this, global, @intFromEnum(builtin_name));
if (result == .zero) {
return null;
}
@@ -4188,7 +4188,7 @@ pub const JSValue = enum(JSValueReprInt) {
}
pub fn fastGetDirect(this: JSValue, global: *JSGlobalObject, builtin_name: BuiltinName) ?JSValue {
- const result = fastGetDirect_(this, global, @enumToInt(builtin_name));
+ const result = fastGetDirect_(this, global, @intFromEnum(builtin_name));
if (result == .zero) {
return null;
}
@@ -4243,7 +4243,7 @@ pub const JSValue = enum(JSValueReprInt) {
pub fn get(this: JSValue, global: *JSGlobalObject, property: []const u8) ?JSValue {
const value = getIfPropertyExistsImpl(this, global, property.ptr, @intCast(u32, property.len));
- return if (@enumToInt(value) != 0) value else return null;
+ return if (@intFromEnum(value) != 0) value else return null;
}
pub fn implementsToString(this: JSValue, global: *JSGlobalObject) bool {
@@ -4407,7 +4407,7 @@ pub const JSValue = enum(JSValueReprInt) {
/// This algorithm differs from the IsStrictlyEqual Algorithm by treating all NaN values as equivalent and by differentiating +0𝔽 from -0𝔽.
/// https://tc39.es/ecma262/#sec-samevalue
pub fn isSameValue(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
- return @enumToInt(this) == @enumToInt(other) or cppFn("isSameValue", .{ this, other, global });
+ return @intFromEnum(this) == @intFromEnum(other) or cppFn("isSameValue", .{ this, other, global });
}
pub fn deepEquals(this: JSValue, other: JSValue, global: *JSGlobalObject) bool {
@@ -4460,7 +4460,7 @@ pub const JSValue = enum(JSValueReprInt) {
/// Get the internal number of the `JSC::DateInstance` object
/// Returns NaN if the value is not a `JSC::DateInstance` (`Date` in JS)
- pub fn getUnixTimestamp(this: JSValue) f64 {
+ pub fn getUnixTimestamp(this: JSValue) f64 {
return cppFn("getUnixTimestamp", .{
this,
});
@@ -4492,7 +4492,7 @@ pub const JSValue = enum(JSValueReprInt) {
pub fn asNumber(this: JSValue) f64 {
if (this.isInt32()) {
- return @intToFloat(f64, this.asInt32());
+ return @floatFromInt(f64, this.asInt32());
}
if (isNumber(this)) {
@@ -4515,19 +4515,19 @@ pub const JSValue = enum(JSValueReprInt) {
}
pub fn asPtr(this: JSValue, comptime Pointer: type) *Pointer {
- return @intToPtr(*Pointer, this.asPtrAddress());
+ return @ptrFromInt(*Pointer, this.asPtrAddress());
}
pub fn fromPtrAddress(addr: anytype) JSValue {
- return jsNumber(@intToFloat(f64, @bitCast(usize, @as(usize, addr))));
+ return jsNumber(@floatFromInt(f64, @bitCast(usize, @as(usize, addr))));
}
pub fn asPtrAddress(this: JSValue) usize {
- return @bitCast(usize, @floatToInt(usize, this.asDouble()));
+ return @bitCast(usize, @intFromFloat(usize, this.asDouble()));
}
pub fn fromPtr(addr: anytype) JSValue {
- return fromPtrAddress(@ptrToInt(addr));
+ return fromPtrAddress(@intFromPtr(addr));
}
pub fn toBooleanSlow(this: JSValue, global: *JSGlobalObject) bool {
@@ -4552,7 +4552,7 @@ pub const JSValue = enum(JSValueReprInt) {
}
if (this.isNumber()) {
- return @truncate(i32, @floatToInt(i64, asDouble(this)));
+ return @truncate(i32, @intFromFloat(i64, asDouble(this)));
}
if (comptime bun.Environment.allow_assert) {
@@ -4591,11 +4591,11 @@ pub const JSValue = enum(JSValueReprInt) {
/// If the "length" property does not exist, this function will return 0.
pub fn getLength(this: JSValue, globalThis: *JSGlobalObject) u64 {
const len = this.getLengthIfPropertyExistsInternal(globalThis);
- if (len == std.math.f64_max) {
+ if (len == std.math.floatMax(f64)) {
return 0;
}
- return @floatToInt(u64, @max(len, 0));
+ return @intFromFloat(u64, @max(len, 0));
}
/// This function supports:
@@ -4612,11 +4612,11 @@ pub const JSValue = enum(JSValueReprInt) {
/// If the "length" property does not exist, this function will return null.
pub fn tryGetLength(this: JSValue, globalThis: *JSGlobalObject) ?f64 {
const len = this.getLengthIfPropertyExistsInternal(globalThis);
- if (len == std.math.f64_max) {
+ if (len == std.math.floatMax(f64)) {
return null;
}
- return @floatToInt(u64, @max(len, 0));
+ return @intFromFloat(u64, @max(len, 0));
}
/// Do not use this directly!
@@ -4661,15 +4661,15 @@ pub const JSValue = enum(JSValueReprInt) {
}
pub inline fn asRef(this: JSValue) C_API.JSValueRef {
- return @intToPtr(C_API.JSValueRef, @bitCast(usize, @enumToInt(this)));
+ return @ptrFromInt(C_API.JSValueRef, @bitCast(usize, @intFromEnum(this)));
}
pub inline fn c(this: C_API.JSValueRef) JSValue {
- return @intToEnum(JSValue, @bitCast(JSValue.Type, @ptrToInt(this)));
+ return @enumFromInt(JSValue, @bitCast(JSValue.Type, @intFromPtr(this)));
}
pub inline fn fromRef(this: C_API.JSValueRef) JSValue {
- return @intToEnum(JSValue, @bitCast(JSValue.Type, @ptrToInt(this)));
+ return @enumFromInt(JSValue, @bitCast(JSValue.Type, @intFromPtr(this)));
}
pub inline fn asObjectRef(this: JSValue) C_API.JSObjectRef {
@@ -4685,12 +4685,12 @@ pub const JSValue = enum(JSValueReprInt) {
}
pub inline fn asNullableVoid(this: JSValue) ?*anyopaque {
- return @intToPtr(?*anyopaque, @bitCast(usize, @enumToInt(this)));
+ return @ptrFromInt(?*anyopaque, @bitCast(usize, @intFromEnum(this)));
}
pub inline fn asVoid(this: JSValue) *anyopaque {
if (comptime bun.Environment.allow_assert) {
- if (@enumToInt(this) == 0) {
+ if (@intFromEnum(this) == 0) {
@panic("JSValue is null");
}
}
@@ -4857,7 +4857,7 @@ pub const Exception = extern struct {
pub fn create(globalObject: *JSGlobalObject, object: *JSObject, stack_capture: StackCaptureAction) *Exception {
return cppFn(
"create",
- .{ globalObject, object, @enumToInt(stack_capture) },
+ .{ globalObject, object, @intFromEnum(stack_capture) },
);
}
@@ -4893,7 +4893,7 @@ pub const VM = extern struct {
LargeHeap = 1,
};
pub fn create(heap_type: HeapType) *VM {
- return cppFn("create", .{@enumToInt(heap_type)});
+ return cppFn("create", .{@intFromEnum(heap_type)});
}
pub fn deinit(vm: *VM, global_object: *JSGlobalObject) void {
@@ -5157,16 +5157,16 @@ pub const CallFrame = opaque {
pub fn arguments(self: *const CallFrame, comptime max: usize) Arguments(max) {
const len = self.argumentsCount();
var ptr = self.argumentsPtr();
- return switch (@min(len, max)) {
+ return switch (@as(u4, @min(len, max))) {
0 => .{ .ptr = undefined, .len = 0 },
- 1 => Arguments(max).init(1, ptr),
- 2 => Arguments(max).init(@min(2, max), ptr),
- 3 => Arguments(max).init(@min(3, max), ptr),
- 4 => Arguments(max).init(@min(4, max), ptr),
- 5 => Arguments(max).init(@min(5, max), ptr),
- 6 => Arguments(max).init(@min(6, max), ptr),
- 7 => Arguments(max).init(@min(7, max), ptr),
- 8 => Arguments(max).init(@min(8, max), ptr),
+ 4 => Arguments(max).init(comptime @min(4, max), ptr),
+ 2 => Arguments(max).init(comptime @min(2, max), ptr),
+ 6 => Arguments(max).init(comptime @min(6, max), ptr),
+ 3 => Arguments(max).init(comptime @min(3, max), ptr),
+ 8 => Arguments(max).init(comptime @min(8, max), ptr),
+ 5 => Arguments(max).init(comptime @min(5, max), ptr),
+ 1 => Arguments(max).init(comptime @min(1, max), ptr),
+ 7 => Arguments(max).init(comptime @min(7, max), ptr),
else => unreachable,
};
}
diff --git a/src/bun.js/bindings/exports.zig b/src/bun.js/bindings/exports.zig
index 6ea1eba60..de3f819b7 100644
--- a/src/bun.js/bindings/exports.zig
+++ b/src/bun.js/bindings/exports.zig
@@ -112,11 +112,11 @@ pub const ErrorCode = enum(ErrorCodeInt) {
_,
pub inline fn from(code: anyerror) ErrorCode {
- return @intToEnum(ErrorCode, @errorToInt(code));
+ return @enumFromInt(ErrorCode, @intFromError(code));
}
- pub const ParserError = @enumToInt(ErrorCode.from(error.ParserError));
- pub const JSErrorObject = @enumToInt(ErrorCode.from(error.JSErrorObject));
+ pub const ParserError = @intFromEnum(ErrorCode.from(error.ParserError));
+ pub const JSErrorObject = @intFromEnum(ErrorCode.from(error.JSErrorObject));
pub const Type = ErrorCodeInt;
};
@@ -244,7 +244,7 @@ export fn ZigString__free(raw: [*]const u8, len: usize, allocator_: ?*anyopaque)
}
export fn ZigString__free_global(ptr: [*]const u8, len: usize) void {
- var untagged = @intToPtr(*anyopaque, @ptrToInt(ZigString.init(ptr[0..len]).slice().ptr));
+ var untagged = @ptrFromInt(*anyopaque, @intFromPtr(ZigString.init(ptr[0..len]).slice().ptr));
if (comptime Environment.allow_assert) {
std.debug.assert(Mimalloc.mi_is_in_heap_region(ptr));
}
@@ -561,7 +561,7 @@ pub const ZigStackFrame = extern struct {
frame.position.source_offset = this.position.source_offset;
// For remapped code, we add 1 to the line number
- frame.position.line = this.position.line + @as(i32, @boolToInt(this.remapped));
+ frame.position.line = this.position.line + @as(i32, @intFromBool(this.remapped));
frame.position.line_start = this.position.line_start;
frame.position.line_stop = this.position.line_stop;
@@ -569,7 +569,7 @@ pub const ZigStackFrame = extern struct {
frame.position.column_stop = this.position.column_stop;
frame.position.expression_start = this.position.expression_start;
frame.position.expression_stop = this.position.expression_stop;
- frame.scope = @intToEnum(Api.StackFrameScope, @enumToInt(this.code_type));
+ frame.scope = @enumFromInt(Api.StackFrameScope, @intFromEnum(this.code_type));
return frame;
}
@@ -775,18 +775,18 @@ pub const ZigException = extern struct {
pub const Zero: Holder = Holder{
.frames = brk: {
var _frames: [frame_count]ZigStackFrame = undefined;
- std.mem.set(ZigStackFrame, &_frames, ZigStackFrame.Zero);
+ @memset(&_frames, ZigStackFrame.Zero);
break :brk _frames;
},
.source_line_numbers = brk: {
var lines: [source_lines_count]i32 = undefined;
- std.mem.set(i32, &lines, -1);
+ @memset(&lines, -1);
break :brk lines;
},
.source_lines = brk: {
var lines: [source_lines_count]ZigString = undefined;
- std.mem.set(ZigString, &lines, ZigString.Empty);
+ @memset(&lines, ZigString.Empty);
break :brk lines;
},
.zig_exception = undefined,
@@ -800,7 +800,7 @@ pub const ZigException = extern struct {
pub fn zigException(this: *Holder) *ZigException {
if (!this.loaded) {
this.zig_exception = ZigException{
- .code = @intToEnum(JSErrorCode, 255),
+ .code = @enumFromInt(JSErrorCode, 255),
.runtime_type = JSRuntimeType.Nothing,
.name = ZigString.Empty,
.message = ZigString.Empty,
@@ -836,8 +836,8 @@ pub const ZigException = extern struct {
var is_empty = true;
var api_exception = Api.JsException{
- .runtime_type = @enumToInt(this.runtime_type),
- .code = @enumToInt(this.code),
+ .runtime_type = @intFromEnum(this.runtime_type),
+ .code = @intFromEnum(this.code),
};
if (_name.len > 0) {
@@ -1314,7 +1314,7 @@ pub const ZigConsoleClient = struct {
};
pub fn getAdvanced(value: JSValue, globalThis: *JSGlobalObject, opts: Options) Result {
- switch (@enumToInt(value)) {
+ switch (@intFromEnum(value)) {
0, 0xa => return Result{
.tag = .Undefined,
},
@@ -1878,7 +1878,7 @@ pub const ZigConsoleClient = struct {
this.map = this.map_node.?.data;
}
- var entry = this.map.getOrPut(@enumToInt(value)) catch unreachable;
+ var entry = this.map.getOrPut(@intFromEnum(value)) catch unreachable;
if (entry.found_existing) {
writer.writeAll(comptime Output.prettyFmt("<r><cyan>[Circular]<r>", enable_ansi_colors));
return;
@@ -1887,7 +1887,7 @@ pub const ZigConsoleClient = struct {
defer {
if (comptime Format.canHaveCircularReferences()) {
- _ = this.map.remove(@enumToInt(value));
+ _ = this.map.remove(@intFromEnum(value));
}
}
@@ -1959,7 +1959,7 @@ pub const ZigConsoleClient = struct {
i = -i;
}
const digits = if (i != 0)
- bun.fmt.fastDigitCount(@intCast(usize, i)) + @as(usize, @boolToInt(is_negative))
+ bun.fmt.fastDigitCount(@intCast(usize, i)) + @as(usize, @intFromBool(is_negative))
else
1;
this.addForNewLine(digits);
@@ -2559,7 +2559,7 @@ pub const ZigConsoleClient = struct {
{
this.indent += 1;
defer this.indent -|= 1;
- const count_without_children = props_iter.len - @as(usize, @boolToInt(children_prop != null));
+ const count_without_children = props_iter.len - @as(usize, @intFromBool(children_prop != null));
while (props_iter.next()) |prop| {
if (prop.eqlComptime("children"))
@@ -3002,7 +3002,7 @@ pub const ZigConsoleClient = struct {
chars: [*]const u8,
len: usize,
) callconv(.C) void {
- const id = std.hash.Wyhash.hash(0, chars[0..len]);
+ const id = bun.hash(chars[0..len]);
if (!pending_time_logs_loaded) {
pending_time_logs = PendingTimers.init(default_allocator);
pending_time_logs_loaded = true;
@@ -3026,12 +3026,12 @@ pub const ZigConsoleClient = struct {
return;
}
- const id = std.hash.Wyhash.hash(0, chars[0..len]);
+ const id = bun.hash(chars[0..len]);
var result = (pending_time_logs.fetchPut(id, null) catch null) orelse return;
var value: std.time.Timer = result.value orelse return;
// get the duration in microseconds
// then display it in milliseconds
- Output.printElapsed(@intToFloat(f64, value.read() / std.time.ns_per_us) / std.time.us_per_ms);
+ Output.printElapsed(@floatFromInt(f64, value.read() / std.time.ns_per_us) / std.time.us_per_ms);
switch (len) {
0 => Output.printErrorln("\n", .{}),
else => Output.printErrorln(" {s}", .{chars[0..len]}),
@@ -3056,11 +3056,11 @@ pub const ZigConsoleClient = struct {
return;
}
- const id = std.hash.Wyhash.hash(0, chars[0..len]);
+ const id = bun.hash(chars[0..len]);
var value: std.time.Timer = (pending_time_logs.get(id) orelse return) orelse return;
// get the duration in microseconds
// then display it in milliseconds
- Output.printElapsed(@intToFloat(f64, value.read() / std.time.ns_per_us) / std.time.us_per_ms);
+ Output.printElapsed(@floatFromInt(f64, value.read() / std.time.ns_per_us) / std.time.us_per_ms);
switch (len) {
0 => Output.printErrorln("\n", .{}),
else => Output.printErrorln(" {s}", .{chars[0..len]}),
diff --git a/src/bun.js/bindings/header-gen.zig b/src/bun.js/bindings/header-gen.zig
index 089506a8f..eb0de1c09 100644
--- a/src/bun.js/bindings/header-gen.zig
+++ b/src/bun.js/bindings/header-gen.zig
@@ -807,7 +807,7 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
}
};
var extern_list = Type.Extern;
- std.sort.sort([]const u8, &extern_list, Sorder{}, Sorder.lessThan);
+ std.sort.block([]const u8, &extern_list, Sorder{}, Sorder.lessThan);
break :brk extern_list;
};
// impl_writer.print(" #include {s}\n", .{Type.include}) catch unreachable;
@@ -840,7 +840,7 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
}
};
var extern_list = Type.Export;
- std.sort.sort(StaticExport, &extern_list, Sorder{}, Sorder.lessThan);
+ std.sort.block(StaticExport, &extern_list, Sorder{}, Sorder.lessThan);
break :brk extern_list;
};
@@ -867,7 +867,7 @@ pub fn HeaderGen(comptime first_import: type, comptime second_import: type, comp
// }
// };
// var extern_list = Type.lazy_static_functions;
- // std.sort.sort(StaticExport, &extern_list, Sorder{}, Sorder.lessThan);
+ // std.sort.block(StaticExport, &extern_list, Sorder{}, Sorder.lessThan);
// break :brk extern_list;
// };
diff --git a/src/bun.js/bindings/shimmer.zig b/src/bun.js/bindings/shimmer.zig
index a90bfab87..3a6242000 100644
--- a/src/bun.js/bindings/shimmer.zig
+++ b/src/bun.js/bindings/shimmer.zig
@@ -163,7 +163,7 @@ pub fn Shimmer(comptime _namespace: []const u8, comptime _name: []const u8, comp
if (comptime isNullableType(ExpectedReturnType) != isNullableType(ExternReturnType)) {
return value.?;
} else if (comptime (@typeInfo(ExpectedReturnType) == .Enum) and (@typeInfo(ExternReturnType) != .Enum)) {
- return @intToEnum(ExpectedReturnType, value);
+ return @enumFromInt(ExpectedReturnType, value);
} else {
return value;
}
diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig
index d458b6e7e..545f41f19 100644
--- a/src/bun.js/javascript.zig
+++ b/src/bun.js/javascript.zig
@@ -196,7 +196,7 @@ pub const SavedSourceMap = struct {
pub const SourceMapHandler = js_printer.SourceMapHandler.For(SavedSourceMap, onSourceMapChunk);
pub fn putMappings(this: *SavedSourceMap, source: logger.Source, mappings: MutableString) !void {
- var entry = try this.map.getOrPut(std.hash.Wyhash.hash(0, source.path.text));
+ var entry = try this.map.getOrPut(bun.hash(source.path.text));
if (entry.found_existing) {
var value = Value.from(entry.value_ptr.*);
if (value.get(MappingList)) |source_map_| {
@@ -213,7 +213,7 @@ pub const SavedSourceMap = struct {
}
pub fn get(this: *SavedSourceMap, path: string) ?MappingList {
- var mapping = this.map.getEntry(std.hash.Wyhash.hash(0, path)) orelse return null;
+ var mapping = this.map.getEntry(bun.hash(path)) orelse return null;
switch (Value.from(mapping.value_ptr.*).tag()) {
(@field(Value.Tag, @typeName(MappingList))) => {
return Value.from(mapping.value_ptr.*).as(MappingList).*;
@@ -264,7 +264,7 @@ export fn Bun__readOriginTimer(vm: *JSC.VirtualMachine) u64 {
export fn Bun__readOriginTimerStart(vm: *JSC.VirtualMachine) f64 {
// timespce to milliseconds
- return @floatCast(f64, (@intToFloat(f64, vm.origin_timestamp) + JSC.VirtualMachine.origin_relative_epoch) / 1_000_000.0);
+ return @floatCast(f64, (@floatFromInt(f64, vm.origin_timestamp) + JSC.VirtualMachine.origin_relative_epoch) / 1_000_000.0);
}
// comptime {
@@ -1382,7 +1382,7 @@ pub const VirtualMachine = struct {
// // This double prints
// pub fn promiseRejectionTracker(global: *JSGlobalObject, promise: *JSPromise, _: JSPromiseRejectionOperation) callconv(.C) JSValue {
// const result = promise.result(global.vm());
- // if (@enumToInt(VirtualMachine.get().last_error_jsvalue) != @enumToInt(result)) {
+ // if (@intFromEnum(VirtualMachine.get().last_error_jsvalue) != @intFromEnum(result)) {
// VirtualMachine.get().runErrorHandler(result, null);
// }
@@ -1823,7 +1823,7 @@ pub const VirtualMachine = struct {
iterator(_vm, globalObject, nextValue, ctx.?, false);
}
inline fn iterator(_: [*c]VM, _: [*c]JSGlobalObject, nextValue: JSValue, ctx: ?*anyopaque, comptime color: bool) void {
- var this_ = @intToPtr(*@This(), @ptrToInt(ctx));
+ var this_ = @ptrFromInt(*@This(), @intFromPtr(ctx));
VirtualMachine.get().printErrorlikeObject(nextValue, null, this_.current_exception_list, Writer, this_.writer, color, allow_side_effects);
}
};
@@ -2066,8 +2066,8 @@ pub const VirtualMachine = struct {
)) |lines| {
var source_lines = exception.stack.source_lines_ptr[0..JSC.ZigException.Holder.source_lines_count];
var source_line_numbers = exception.stack.source_lines_numbers[0..JSC.ZigException.Holder.source_lines_count];
- std.mem.set(ZigString, source_lines, ZigString.Empty);
- std.mem.set(i32, source_line_numbers, 0);
+ @memset(source_lines, ZigString.Empty);
+ @memset(source_line_numbers, 0);
var lines_ = lines[0..@min(lines.len, source_lines.len)];
for (lines_, 0..) |line, j| {
@@ -2374,7 +2374,7 @@ pub const EventListenerMixin = struct {
const FetchEventRejectionHandler = struct {
pub fn onRejection(_ctx: *anyopaque, err: anyerror, fetch_event: *FetchEvent, value: JSValue) void {
onError(
- @intToPtr(*CtxType, @ptrToInt(_ctx)),
+ @ptrFromInt(*CtxType, @intFromPtr(_ctx)),
err,
value,
fetch_event.request_context.?,
@@ -2763,10 +2763,10 @@ pub fn NewHotReloader(comptime Ctx: type, comptime EventLoopType: type, comptime
break :brk path_string.slice();
} else {
var file_path_without_trailing_slash = std.mem.trimRight(u8, file_path, std.fs.path.sep_str);
- @memcpy(&_on_file_update_path_buf, file_path_without_trailing_slash.ptr, file_path_without_trailing_slash.len);
+ @memcpy(_on_file_update_path_buf[0..file_path_without_trailing_slash.len], file_path_without_trailing_slash);
_on_file_update_path_buf[file_path_without_trailing_slash.len] = std.fs.path.sep;
- @memcpy(_on_file_update_path_buf[file_path_without_trailing_slash.len + 1 ..].ptr, changed_name.ptr, changed_name.len);
+ @memcpy(_on_file_update_path_buf[file_path_without_trailing_slash.len..][0..changed_name.len], changed_name);
const path_slice = _on_file_update_path_buf[0 .. file_path_without_trailing_slash.len + changed_name.len + 1];
file_hash = @This().Watcher.getHash(path_slice);
break :brk path_slice;
diff --git a/src/bun.js/javascript_core_c_api.zig b/src/bun.js/javascript_core_c_api.zig
index 37f9df15d..aba143a81 100644
--- a/src/bun.js/javascript_core_c_api.zig
+++ b/src/bun.js/javascript_core_c_api.zig
@@ -9,7 +9,7 @@ const std = @import("std");
const cpp = @import("./bindings/bindings.zig");
const generic = opaque {
pub fn value(this: *const @This()) cpp.JSValue {
- return @intToEnum(cpp.JSValue, @bitCast(cpp.JSValue.Type, @ptrToInt(this)));
+ return @enumFromInt(cpp.JSValue, @bitCast(cpp.JSValue.Type, @intFromPtr(this)));
}
pub inline fn bunVM(this: *@This()) *@import("root").bun.JSC.VirtualMachine {
@@ -120,13 +120,13 @@ pub const JSType = enum(c_uint) {
kJSTypeObject,
kJSTypeSymbol,
};
-pub const kJSTypeUndefined = @enumToInt(JSType.kJSTypeUndefined);
-pub const kJSTypeNull = @enumToInt(JSType.kJSTypeNull);
-pub const kJSTypeBoolean = @enumToInt(JSType.kJSTypeBoolean);
-pub const kJSTypeNumber = @enumToInt(JSType.kJSTypeNumber);
-pub const kJSTypeString = @enumToInt(JSType.kJSTypeString);
-pub const kJSTypeObject = @enumToInt(JSType.kJSTypeObject);
-pub const kJSTypeSymbol = @enumToInt(JSType.kJSTypeSymbol);
+pub const kJSTypeUndefined = @intFromEnum(JSType.kJSTypeUndefined);
+pub const kJSTypeNull = @intFromEnum(JSType.kJSTypeNull);
+pub const kJSTypeBoolean = @intFromEnum(JSType.kJSTypeBoolean);
+pub const kJSTypeNumber = @intFromEnum(JSType.kJSTypeNumber);
+pub const kJSTypeString = @intFromEnum(JSType.kJSTypeString);
+pub const kJSTypeObject = @intFromEnum(JSType.kJSTypeObject);
+pub const kJSTypeSymbol = @intFromEnum(JSType.kJSTypeSymbol);
pub const JSTypedArrayType = enum(c_uint) {
kJSTypedArrayTypeInt8Array,
kJSTypedArrayTypeInt16Array,
@@ -141,17 +141,17 @@ pub const JSTypedArrayType = enum(c_uint) {
kJSTypedArrayTypeNone,
_,
};
-pub const kJSTypedArrayTypeInt8Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeInt8Array);
-pub const kJSTypedArrayTypeInt16Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeInt16Array);
-pub const kJSTypedArrayTypeInt32Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeInt32Array);
-pub const kJSTypedArrayTypeUint8Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeUint8Array);
-pub const kJSTypedArrayTypeUint8ClampedArray = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeUint8ClampedArray);
-pub const kJSTypedArrayTypeUint16Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeUint16Array);
-pub const kJSTypedArrayTypeUint32Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeUint32Array);
-pub const kJSTypedArrayTypeFloat32Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeFloat32Array);
-pub const kJSTypedArrayTypeFloat64Array = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeFloat64Array);
-pub const kJSTypedArrayTypeArrayBuffer = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeArrayBuffer);
-pub const kJSTypedArrayTypeNone = @enumToInt(JSTypedArrayType.kJSTypedArrayTypeNone);
+pub const kJSTypedArrayTypeInt8Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeInt8Array);
+pub const kJSTypedArrayTypeInt16Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeInt16Array);
+pub const kJSTypedArrayTypeInt32Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeInt32Array);
+pub const kJSTypedArrayTypeUint8Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeUint8Array);
+pub const kJSTypedArrayTypeUint8ClampedArray = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeUint8ClampedArray);
+pub const kJSTypedArrayTypeUint16Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeUint16Array);
+pub const kJSTypedArrayTypeUint32Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeUint32Array);
+pub const kJSTypedArrayTypeFloat32Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeFloat32Array);
+pub const kJSTypedArrayTypeFloat64Array = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeFloat64Array);
+pub const kJSTypedArrayTypeArrayBuffer = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeArrayBuffer);
+pub const kJSTypedArrayTypeNone = @intFromEnum(JSTypedArrayType.kJSTypedArrayTypeNone);
pub extern fn JSValueGetType(ctx: JSContextRef, value: JSValueRef) JSType;
pub extern fn JSValueIsUndefined(ctx: JSContextRef, value: JSValueRef) bool;
pub extern fn JSValueIsNull(ctx: JSContextRef, value: JSValueRef) bool;
@@ -187,7 +187,7 @@ pub inline fn JSValueUnprotect(ctx: JSContextRef, value: JSValueRef) void {
};
if (comptime log_protection) {
const Output = @import("root").bun.Output;
- Output.debug("[unprotect] {d}\n", .{@ptrToInt(value)});
+ Output.debug("[unprotect] {d}\n", .{@intFromPtr(value)});
}
// wrapper exists to make it easier to set a breakpoint
Wrapped.JSValueUnprotect(ctx, value);
@@ -199,7 +199,7 @@ pub inline fn JSValueProtect(ctx: JSContextRef, value: JSValueRef) void {
};
if (comptime log_protection) {
const Output = @import("root").bun.Output;
- Output.debug("[protect] {d}\n", .{@ptrToInt(value)});
+ Output.debug("[protect] {d}\n", .{@intFromPtr(value)});
}
// wrapper exists to make it easier to set a breakpoint
Wrapped.JSValueProtect(ctx, value);
@@ -212,18 +212,18 @@ pub const JSPropertyAttributes = enum(c_uint) {
kJSPropertyAttributeDontDelete = 8,
_,
};
-pub const kJSPropertyAttributeNone = @enumToInt(JSPropertyAttributes.kJSPropertyAttributeNone);
-pub const kJSPropertyAttributeReadOnly = @enumToInt(JSPropertyAttributes.kJSPropertyAttributeReadOnly);
-pub const kJSPropertyAttributeDontEnum = @enumToInt(JSPropertyAttributes.kJSPropertyAttributeDontEnum);
-pub const kJSPropertyAttributeDontDelete = @enumToInt(JSPropertyAttributes.kJSPropertyAttributeDontDelete);
+pub const kJSPropertyAttributeNone = @intFromEnum(JSPropertyAttributes.kJSPropertyAttributeNone);
+pub const kJSPropertyAttributeReadOnly = @intFromEnum(JSPropertyAttributes.kJSPropertyAttributeReadOnly);
+pub const kJSPropertyAttributeDontEnum = @intFromEnum(JSPropertyAttributes.kJSPropertyAttributeDontEnum);
+pub const kJSPropertyAttributeDontDelete = @intFromEnum(JSPropertyAttributes.kJSPropertyAttributeDontDelete);
pub const JSClassAttributes = enum(c_uint) {
kJSClassAttributeNone = 0,
kJSClassAttributeNoAutomaticPrototype = 2,
_,
};
-pub const kJSClassAttributeNone = @enumToInt(JSClassAttributes.kJSClassAttributeNone);
-pub const kJSClassAttributeNoAutomaticPrototype = @enumToInt(JSClassAttributes.kJSClassAttributeNoAutomaticPrototype);
+pub const kJSClassAttributeNone = @intFromEnum(JSClassAttributes.kJSClassAttributeNone);
+pub const kJSClassAttributeNoAutomaticPrototype = @intFromEnum(JSClassAttributes.kJSClassAttributeNoAutomaticPrototype);
pub const JSObjectInitializeCallback = *const fn (JSContextRef, JSObjectRef) callconv(.C) void;
pub const JSObjectFinalizeCallback = *const fn (JSObjectRef) callconv(.C) void;
pub const JSObjectHasPropertyCallback = *const fn (JSContextRef, JSObjectRef, JSStringRef) callconv(.C) bool;
diff --git a/src/bun.js/module_loader.zig b/src/bun.js/module_loader.zig
index d115573be..e249bba8b 100644
--- a/src/bun.js/module_loader.zig
+++ b/src/bun.js/module_loader.zig
@@ -1298,7 +1298,7 @@ pub const ModuleLoader = struct {
var encoded = JSC.EncodedJSValue{
.asPtr = globalThis,
};
- const globalValue = @intToEnum(JSC.JSValue, encoded.asInt64);
+ const globalValue = @enumFromInt(JSC.JSValue, encoded.asInt64);
globalValue.put(
globalThis,
JSC.ZigString.static("wasmSourceBytes"),
diff --git a/src/bun.js/node/buffer.zig b/src/bun.js/node/buffer.zig
index f73498069..3a0750f05 100644
--- a/src/bun.js/node/buffer.zig
+++ b/src/bun.js/node/buffer.zig
@@ -50,7 +50,7 @@ pub const BufferVectorized = struct {
switch (written) {
0 => {},
- 1 => @memset(buf.ptr, buf[0], buf.len),
+ 1 => @memset(buf, buf[0]),
else => {
var contents = buf[0..written];
buf = buf[written..];
diff --git a/src/bun.js/node/dir_iterator.zig b/src/bun.js/node/dir_iterator.zig
index aa939679c..dac78e5e2 100644
--- a/src/bun.js/node/dir_iterator.zig
+++ b/src/bun.js/node/dir_iterator.zig
@@ -78,15 +78,15 @@ pub const Iterator = switch (builtin.os.tag) {
}
const entry_kind = switch (darwin_entry.d_type) {
- os.DT.BLK => Entry.Kind.BlockDevice,
- os.DT.CHR => Entry.Kind.CharacterDevice,
- os.DT.DIR => Entry.Kind.Directory,
- os.DT.FIFO => Entry.Kind.NamedPipe,
- os.DT.LNK => Entry.Kind.SymLink,
- os.DT.REG => Entry.Kind.File,
- os.DT.SOCK => Entry.Kind.UnixDomainSocket,
- os.DT.WHT => Entry.Kind.Whiteout,
- else => Entry.Kind.Unknown,
+ os.DT.BLK => Entry.Kind.block_device,
+ os.DT.CHR => Entry.Kind.character_device,
+ os.DT.DIR => Entry.Kind.directory,
+ os.DT.FIFO => Entry.Kind.named_pipe,
+ os.DT.LNK => Entry.Kind.sym_link,
+ os.DT.REG => Entry.Kind.file,
+ os.DT.SOCK => Entry.Kind.unix_domain_socket,
+ os.DT.WHT => Entry.Kind.whiteout,
+ else => Entry.Kind.unknown,
};
return .{
.result = IteratorResult{
@@ -134,14 +134,14 @@ pub const Iterator = switch (builtin.os.tag) {
}
const entry_kind = switch (linux_entry.d_type) {
- linux.DT.BLK => Entry.Kind.BlockDevice,
- linux.DT.CHR => Entry.Kind.CharacterDevice,
- linux.DT.DIR => Entry.Kind.Directory,
- linux.DT.FIFO => Entry.Kind.NamedPipe,
- linux.DT.LNK => Entry.Kind.SymLink,
- linux.DT.REG => Entry.Kind.File,
- linux.DT.SOCK => Entry.Kind.UnixDomainSocket,
- else => Entry.Kind.Unknown,
+ linux.DT.BLK => Entry.Kind.block_device,
+ linux.DT.CHR => Entry.Kind.character_device,
+ linux.DT.DIR => Entry.Kind.directory,
+ linux.DT.FIFO => Entry.Kind.named_pipe,
+ linux.DT.LNK => Entry.Kind.sym_link,
+ linux.DT.REG => Entry.Kind.file,
+ linux.DT.SOCK => Entry.Kind.unix_domain_socket,
+ else => Entry.Kind.unknown,
};
return .{
.result = IteratorResult{
@@ -213,9 +213,9 @@ pub const Iterator = switch (builtin.os.tag) {
const name_utf8 = self.name_data[0..name_utf8_len];
const kind = blk: {
const attrs = dir_info.FileAttributes;
- if (attrs & w.FILE_ATTRIBUTE_DIRECTORY != 0) break :blk Entry.Kind.Directory;
- if (attrs & w.FILE_ATTRIBUTE_REPARSE_POINT != 0) break :blk Entry.Kind.SymLink;
- break :blk Entry.Kind.File;
+ if (attrs & w.FILE_ATTRIBUTE_DIRECTORY != 0) break :blk Entry.Kind.directory;
+ if (attrs & w.FILE_ATTRIBUTE_REPARSE_POINT != 0) break :blk Entry.Kind.sym_link;
+ break :blk Entry.Kind.file;
};
return .{
.result = IteratorResult{
@@ -275,13 +275,13 @@ pub const Iterator = switch (builtin.os.tag) {
}
const entry_kind = switch (entry.d_type) {
- .BLOCK_DEVICE => Entry.Kind.BlockDevice,
- .CHARACTER_DEVICE => Entry.Kind.CharacterDevice,
- .DIRECTORY => Entry.Kind.Directory,
- .SYMBOLIC_LINK => Entry.Kind.SymLink,
- .REGULAR_FILE => Entry.Kind.File,
- .SOCKET_STREAM, .SOCKET_DGRAM => Entry.Kind.UnixDomainSocket,
- else => Entry.Kind.Unknown,
+ .BLOCK_DEVICE => Entry.Kind.block_device,
+ .CHARACTER_DEVICE => Entry.Kind.character_device,
+ .DIRECTORY => Entry.Kind.directory,
+ .SYMBOLIC_LINK => Entry.Kind.sym_link,
+ .REGULAR_FILE => Entry.Kind.file,
+ .SOCKET_STREAM, .SOCKET_DGRAM => Entry.Kind.unix_domain_socket,
+ else => Entry.Kind.unknown,
};
return IteratorResult{
.name = name,
diff --git a/src/bun.js/node/node_fs.zig b/src/bun.js/node/node_fs.zig
index 254d58455..3ea0822e6 100644
--- a/src/bun.js/node/node_fs.zig
+++ b/src/bun.js/node/node_fs.zig
@@ -2264,7 +2264,7 @@ pub const Arguments = struct {
return CopyFile{
.src = src,
.dest = dest,
- .mode = @intToEnum(Constants.Copyfile, mode),
+ .mode = @enumFromInt(Constants.Copyfile, mode),
};
}
};
@@ -2498,7 +2498,7 @@ pub const NodeFS = struct {
pub fn access(this: *NodeFS, args: Arguments.Access, comptime _: Flavor) Maybe(Return.Access) {
var path = args.path.sliceZ(&this.sync_error_buf);
- const rc = Syscall.system.access(path, @enumToInt(args.mode));
+ const rc = Syscall.system.access(path, @intFromEnum(args.mode));
return Maybe(Return.Access).errnoSysP(rc, .access, path) orelse Maybe(Return.Access).success;
}
@@ -2528,7 +2528,7 @@ pub const NodeFS = struct {
const path = path_.sliceZ(&this.sync_error_buf);
switch (comptime flavor) {
.sync => {
- const fd = switch (Syscall.open(path, @enumToInt(FileSystemFlags.a), 0o000666)) {
+ const fd = switch (Syscall.open(path, @intFromEnum(FileSystemFlags.a), 0o000666)) {
.result => |result| result,
.err => |err| return .{ .err = err },
};
@@ -2594,7 +2594,7 @@ pub const NodeFS = struct {
};
if (!os.S.ISREG(stat_.mode)) {
- return Maybe(Return.CopyFile){ .err = .{ .errno = @enumToInt(C.SystemErrno.ENOTSUP) } };
+ return Maybe(Return.CopyFile){ .err = .{ .errno = @intFromEnum(C.SystemErrno.ENOTSUP) } };
}
// 64 KB is about the break-even point for clonefile() to be worth it
@@ -2723,7 +2723,7 @@ pub const NodeFS = struct {
};
if (!os.S.ISREG(stat_.mode)) {
- return Maybe(Return.CopyFile){ .err = .{ .errno = @enumToInt(C.SystemErrno.ENOTSUP) } };
+ return Maybe(Return.CopyFile){ .err = .{ .errno = @intFromEnum(C.SystemErrno.ENOTSUP) } };
}
var flags: Mode = std.os.O.CREAT | std.os.O.WRONLY;
@@ -3026,7 +3026,7 @@ pub const NodeFS = struct {
.err => |err| {
switch (err.getErrno()) {
else => {
- @memcpy(&this.sync_error_buf, path.ptr, len);
+ @memcpy(this.sync_error_buf[0..len], path[0..len]);
return .{ .err = err.withPath(this.sync_error_buf[0..len]) };
},
@@ -3043,7 +3043,7 @@ pub const NodeFS = struct {
}
var working_mem = &this.sync_error_buf;
- @memcpy(working_mem, path.ptr, len);
+ @memcpy(working_mem[0..len], path[0..len]);
var i: u16 = len - 1;
@@ -3146,7 +3146,7 @@ pub const NodeFS = struct {
const prefix_slice = args.prefix.slice();
const len = @min(prefix_slice.len, prefix_buf.len -| 7);
if (len > 0) {
- @memcpy(prefix_buf, prefix_slice.ptr, len);
+ @memcpy(prefix_buf[0..len], prefix_slice[0..len]);
}
prefix_buf[len..][0..6].* = "XXXXXX".*;
prefix_buf[len..][6] = 0;
@@ -3162,15 +3162,15 @@ pub const NodeFS = struct {
};
}
// std.c.getErrno(rc) returns SUCCESS if rc is null so we call std.c._errno() directly
- const errno = @intToEnum(std.c.E, std.c._errno().*);
- return .{ .err = Syscall.Error{ .errno = @truncate(Syscall.Error.Int, @enumToInt(errno)), .syscall = .mkdtemp } };
+ const errno = @enumFromInt(std.c.E, std.c._errno().*);
+ return .{ .err = Syscall.Error{ .errno = @truncate(Syscall.Error.Int, @intFromEnum(errno)), .syscall = .mkdtemp } };
}
pub fn open(this: *NodeFS, args: Arguments.Open, comptime flavor: Flavor) Maybe(Return.Open) {
switch (comptime flavor) {
// The sync version does no allocation except when returning the path
.sync => {
const path = args.path.sliceZ(&this.sync_error_buf);
- return switch (Syscall.open(path, @enumToInt(args.flags), args.mode)) {
+ return switch (Syscall.open(path, @intFromEnum(args.flags), args.mode)) {
.err => |err| .{
.err = err.withPath(args.path.slice()),
},
@@ -3605,7 +3605,7 @@ pub const NodeFS = struct {
break :brk switch (Syscall.openat(
args.dirfd,
path,
- @enumToInt(args.flag) | os.O.NOCTTY,
+ @intFromEnum(args.flag) | os.O.NOCTTY,
args.mode,
)) {
.err => |err| return .{
@@ -3672,7 +3672,7 @@ pub const NodeFS = struct {
}
// https://github.com/oven-sh/bun/issues/2931
- if ((@enumToInt(args.flag) & std.os.O.APPEND) == 0) {
+ if ((@intFromEnum(args.flag) & std.os.O.APPEND) == 0) {
_ = ftruncateSync(.{ .fd = fd, .len = @truncate(JSC.WebCore.Blob.SizeType, written) });
}
@@ -3819,12 +3819,12 @@ pub const NodeFS = struct {
while (true) {
if (Maybe(Return.Rmdir).errnoSys(bun.C.darwin.removefileat(std.os.AT.FDCWD, dest, null, flags), .rmdir)) |errno| {
- switch (@intToEnum(os.E, errno.err.errno)) {
+ switch (@enumFromInt(os.E, errno.err.errno)) {
.AGAIN, .INTR => continue,
.NOENT => return Maybe(Return.Rmdir).success,
.MLINK => {
var copy: [bun.MAX_PATH_BYTES]u8 = undefined;
- @memcpy(&copy, dest.ptr, dest.len);
+ @memcpy(copy[0..dest.len], dest);
copy[dest.len] = 0;
var dest_copy = copy[0..dest.len :0];
switch (Syscall.unlink(dest_copy).getErrno()) {
@@ -3906,7 +3906,7 @@ pub const NodeFS = struct {
}
if (Maybe(Return.Rm).errnoSys(bun.C.darwin.removefileat(std.os.AT.FDCWD, dest, null, flags), .unlink)) |errno| {
- switch (@intToEnum(os.E, errno.err.errno)) {
+ switch (@enumFromInt(os.E, errno.err.errno)) {
.AGAIN, .INTR => continue,
.NOENT => {
if (args.force) {
@@ -3918,7 +3918,7 @@ pub const NodeFS = struct {
.MLINK => {
var copy: [bun.MAX_PATH_BYTES]u8 = undefined;
- @memcpy(&copy, dest.ptr, dest.len);
+ @memcpy(copy[0..dest.len], dest);
copy[dest.len] = 0;
var dest_copy = copy[0..dest.len :0];
switch (Syscall.unlink(dest_copy).getErrno()) {
diff --git a/src/bun.js/node/node_fs_constant.zig b/src/bun.js/node/node_fs_constant.zig
index 378f332c6..8e642ebad 100644
--- a/src/bun.js/node/node_fs_constant.zig
+++ b/src/bun.js/node/node_fs_constant.zig
@@ -26,17 +26,17 @@ pub const Constants = struct {
pub const force = 4;
pub inline fn isForceClone(this: Copyfile) bool {
- return (@enumToInt(this) & COPYFILE_FICLONE_FORCE) != 0;
+ return (@intFromEnum(this) & COPYFILE_FICLONE_FORCE) != 0;
}
pub inline fn shouldntOverwrite(this: Copyfile) bool {
- return (@enumToInt(this) & COPYFILE_EXCL) != 0;
+ return (@intFromEnum(this) & COPYFILE_EXCL) != 0;
}
pub inline fn canUseClone(this: Copyfile) bool {
_ = this;
return Environment.isMac;
- // return (@enumToInt(this) | COPYFILE_FICLONE) != 0;
+ // return (@intFromEnum(this) | COPYFILE_FICLONE) != 0;
}
};
diff --git a/src/bun.js/node/node_os.zig b/src/bun.js/node/node_os.zig
index 4b37640cf..7f9ea2e28 100644
--- a/src/bun.js/node/node_os.zig
+++ b/src/bun.js/node/node_os.zig
@@ -211,7 +211,7 @@ pub const Os = struct {
if (local_bindings.host_processor_info(std.c.mach_host_self(), local_bindings.PROCESSOR_CPU_LOAD_INFO, &num_cpus, @ptrCast(*local_bindings.processor_info_array_t, &info), &info_size) != .SUCCESS) {
return error.no_processor_info;
}
- defer _ = std.c.vm_deallocate(std.c.mach_task_self(), @ptrToInt(info), info_size);
+ defer _ = std.c.vm_deallocate(std.c.mach_task_self(), @intFromPtr(info), info_size);
// Ensure we got the amount of data we expected to guard against buffer overruns
if (info_size != C.PROCESSOR_CPU_LOAD_INFO_COUNT * num_cpus) {
@@ -380,7 +380,7 @@ pub const Os = struct {
const err = JSC.SystemError{
.message = JSC.ZigString.init("A system error occurred: getifaddrs returned an error"),
.code = JSC.ZigString.init(@as(string, @tagName(JSC.Node.ErrorCode.ERR_SYSTEM_ERROR))),
- .errno = @enumToInt(std.os.errno(rc)),
+ .errno = @intFromEnum(std.os.errno(rc)),
.syscall = JSC.ZigString.init("getifaddrs"),
};
@@ -461,7 +461,7 @@ pub const Os = struct {
var cidr = JSC.JSValue.null;
if (maybe_suffix) |suffix| {
//NOTE addr_str might not start at buf[0] due to slicing in formatIp
- const start = @ptrToInt(addr_str.ptr) - @ptrToInt(&buf[0]);
+ const start = @intFromPtr(addr_str.ptr) - @intFromPtr(&buf[0]);
// Start writing the suffix immediately after the address
const suffix_str = std.fmt.bufPrint(buf[start + addr_str.len ..], "/{}", .{suffix}) catch unreachable;
// The full cidr value is the address + the suffix
diff --git a/src/bun.js/node/os/constants.zig b/src/bun.js/node/os/constants.zig
index a3508d383..9cf754e03 100644
--- a/src/bun.js/node/os/constants.zig
+++ b/src/bun.js/node/os/constants.zig
@@ -8,14 +8,14 @@ const ConstantType = enum { ERRNO, ERRNO_WIN, SIG, DLOPEN, OTHER };
fn getErrnoConstant(comptime name: []const u8) ?comptime_int {
return if (@hasField(std.os.E, name))
- return @enumToInt(@field(std.os.E, name))
+ return @intFromEnum(@field(std.os.E, name))
else
return null;
}
fn getWindowsErrnoConstant(comptime name: []const u8) ?comptime_int {
return if (@hasField(std.os.E, name))
- return @enumToInt(@field(std.os.windows.ws2_32.WinsockError, name))
+ return @intFromEnum(@field(std.os.windows.ws2_32.WinsockError, name))
else
return null;
}
diff --git a/src/bun.js/node/syscall.zig b/src/bun.js/node/syscall.zig
index 7b10a3028..77bd5b13d 100644
--- a/src/bun.js/node/syscall.zig
+++ b/src/bun.js/node/syscall.zig
@@ -202,7 +202,7 @@ pub fn openat(dirfd: bun.FileDescriptor, file_path: [:0]const u8, flags: JSC.Nod
.SUCCESS => .{ .result = @intCast(bun.FileDescriptor, rc) },
else => |err| .{
.err = .{
- .errno = @truncate(Syscall.Error.Int, @enumToInt(err)),
+ .errno = @truncate(Syscall.Error.Int, @intFromEnum(err)),
.syscall = .open,
},
},
@@ -218,7 +218,7 @@ pub fn openat(dirfd: bun.FileDescriptor, file_path: [:0]const u8, flags: JSC.Nod
else => |err| {
return Maybe(std.os.fd_t){
.err = .{
- .errno = @truncate(Syscall.Error.Int, @enumToInt(err)),
+ .errno = @truncate(Syscall.Error.Int, @intFromEnum(err)),
.syscall = .open,
},
};
@@ -253,14 +253,14 @@ pub fn closeAllowingStdoutAndStderr(fd: std.os.fd_t) ?Syscall.Error {
if (comptime Environment.isMac) {
// This avoids the EINTR problem.
return switch (system.getErrno(system.@"close$NOCANCEL"(fd))) {
- .BADF => Syscall.Error{ .errno = @enumToInt(os.E.BADF), .syscall = .close },
+ .BADF => Syscall.Error{ .errno = @intFromEnum(os.E.BADF), .syscall = .close },
else => null,
};
}
if (comptime Environment.isLinux) {
return switch (linux.getErrno(linux.close(fd))) {
- .BADF => Syscall.Error{ .errno = @enumToInt(os.E.BADF), .syscall = .close },
+ .BADF => Syscall.Error{ .errno = @intFromEnum(os.E.BADF), .syscall = .close },
else => null,
};
}
@@ -546,7 +546,7 @@ pub fn getFdPath(fd: fd_t, out_buffer: *[MAX_PATH_BYTES]u8) Maybe([]u8) {
.macos, .ios, .watchos, .tvos => {
// On macOS, we can use F.GETPATH fcntl command to query the OS for
// the path to the file descriptor.
- @memset(out_buffer, 0, MAX_PATH_BYTES);
+ @memset(out_buffer[0..MAX_PATH_BYTES], 0);
if (Maybe([]u8).errnoSys(system.fcntl(fd, os.F.GETPATH, out_buffer), .fcntl)) |err| {
return err;
}
@@ -594,7 +594,7 @@ fn mmap(
const fail = std.c.MAP.FAILED;
if (rc == fail) {
return Maybe([]align(mem.page_size) u8){
- .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(std.c.getErrno(@bitCast(i64, @ptrToInt(fail))))), .syscall = .mmap },
+ .err = .{ .errno = @truncate(Syscall.Error.Int, @intFromEnum(std.c.getErrno(@bitCast(i64, @intFromPtr(fail))))), .syscall = .mmap },
};
}
@@ -643,16 +643,16 @@ pub fn munmap(memory: []align(mem.page_size) const u8) Maybe(void) {
pub const Error = struct {
const max_errno_value = brk: {
const errno_values = std.enums.values(os.E);
- var err = @enumToInt(os.E.SUCCESS);
+ var err = @intFromEnum(os.E.SUCCESS);
for (errno_values) |errn| {
- err = @max(err, @enumToInt(errn));
+ err = @max(err, @intFromEnum(errn));
}
break :brk err;
};
pub const Int: type = std.math.IntFittingRange(0, max_errno_value + 5);
errno: Int,
- syscall: Syscall.Tag = @intToEnum(Syscall.Tag, 0),
+ syscall: Syscall.Tag = @enumFromInt(Syscall.Tag, 0),
path: []const u8 = "",
fd: i32 = -1,
@@ -661,7 +661,7 @@ pub const Error = struct {
}
pub fn fromCode(errno: os.E, syscall: Syscall.Tag) Error {
- return .{ .errno = @truncate(Int, @enumToInt(errno)), .syscall = syscall };
+ return .{ .errno = @truncate(Int, @intFromEnum(errno)), .syscall = syscall };
}
pub fn format(self: Error, comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void {
@@ -672,16 +672,16 @@ pub const Error = struct {
pub const retry = Error{
.errno = if (Environment.isLinux)
- @intCast(Int, @enumToInt(os.E.AGAIN))
+ @intCast(Int, @intFromEnum(os.E.AGAIN))
else if (Environment.isMac)
- @intCast(Int, @enumToInt(os.E.WOULDBLOCK))
+ @intCast(Int, @intFromEnum(os.E.WOULDBLOCK))
else
- @intCast(Int, @enumToInt(os.E.INTR)),
+ @intCast(Int, @intFromEnum(os.E.INTR)),
.syscall = .retry,
};
pub inline fn getErrno(this: Error) os.E {
- return @intToEnum(os.E, this.errno);
+ return @enumFromInt(os.E, this.errno);
}
pub inline fn withPath(this: Error, path: anytype) Error {
@@ -726,7 +726,7 @@ pub const Error = struct {
// errno label
if (this.errno > 0 and this.errno < C.SystemErrno.max) {
- const system_errno = @intToEnum(C.SystemErrno, this.errno);
+ const system_errno = @enumFromInt(C.SystemErrno, this.errno);
err.code = JSC.ZigString.init(@tagName(system_errno));
if (C.SystemErrno.labels.get(system_errno)) |label| {
err.message = JSC.ZigString.init(label);
diff --git a/src/bun.js/node/types.zig b/src/bun.js/node/types.zig
index 1fe378a84..e2de35706 100644
--- a/src/bun.js/node/types.zig
+++ b/src/bun.js/node/types.zig
@@ -135,7 +135,7 @@ pub fn Maybe(comptime ResultType: type) type {
pub inline fn getErrno(this: @This()) os.E {
return switch (this) {
.result => os.E.SUCCESS,
- .err => |err| @intToEnum(os.E, err.errno),
+ .err => |err| @enumFromInt(os.E, err.errno),
};
}
@@ -144,7 +144,7 @@ pub fn Maybe(comptime ResultType: type) type {
.SUCCESS => null,
else => |err| @This(){
// always truncate
- .err = .{ .errno = @truncate(Syscall.Error.Int, @enumToInt(err)) },
+ .err = .{ .errno = @truncate(Syscall.Error.Int, @intFromEnum(err)) },
},
};
}
@@ -154,7 +154,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 },
+ .err = .{ .errno = @truncate(Syscall.Error.Int, @intFromEnum(err)), .syscall = syscall },
},
};
}
@@ -165,7 +165,7 @@ pub fn Maybe(comptime ResultType: type) type {
else => |err| @This(){
// always truncate
.err = .{
- .errno = @truncate(Syscall.Error.Int, @enumToInt(err)),
+ .errno = @truncate(Syscall.Error.Int, @intFromEnum(err)),
.syscall = syscall,
.fd = @intCast(i32, fd),
},
@@ -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 = bun.asByteSlice(path) },
+ .err = .{ .errno = @truncate(Syscall.Error.Int, @intFromEnum(err)), .syscall = syscall, .path = bun.asByteSlice(path) },
},
};
}
@@ -632,7 +632,7 @@ pub const PathLike = union(Tag) {
}
}
- @memcpy(buf, sliced.ptr, sliced.len);
+ @memcpy(buf[0..sliced.len], sliced);
buf[sliced.len] = 0;
return buf[0..sliced.len :0];
}
@@ -904,7 +904,7 @@ pub fn timeLikeFromJS(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue, _: JS
return null;
}
- return @truncate(TimeLike, @floatToInt(i64, milliseconds / @as(f64, std.time.ms_per_s)));
+ return @truncate(TimeLike, @intFromFloat(i64, milliseconds / @as(f64, std.time.ms_per_s)));
}
if (!value.isNumber() and !value.isString()) {
@@ -916,7 +916,7 @@ pub fn timeLikeFromJS(globalThis: *JSC.JSGlobalObject, value: JSC.JSValue, _: JS
return null;
}
- return @truncate(TimeLike, @floatToInt(i64, seconds));
+ return @truncate(TimeLike, @intFromFloat(i64, seconds));
}
pub fn modeFromJS(ctx: JSC.C.JSContextRef, value: JSC.JSValue, exception: JSC.C.ExceptionRef) ?Mode {
@@ -968,8 +968,8 @@ pub const PathOrFileDescriptor = union(Tag) {
pub fn hash(this: JSC.Node.PathOrFileDescriptor) u64 {
return switch (this) {
- .path => std.hash.Wyhash.hash(0, this.path.slice()),
- .fd => std.hash.Wyhash.hash(0, std.mem.asBytes(&this.fd)),
+ .path => bun.hash(this.path.slice()),
+ .fd => bun.hash(std.mem.asBytes(&this.fd)),
};
}
@@ -1104,7 +1104,7 @@ pub const FileSystemFlags = enum(Mode) {
pub fn fromJS(ctx: JSC.C.JSContextRef, val: JSC.JSValue, exception: JSC.C.ExceptionRef) ?FileSystemFlags {
if (val.isNumber()) {
const number = val.coerce(i32, ctx);
- return @intToEnum(FileSystemFlags, @intCast(Mode, @max(number, 0)));
+ return @enumFromInt(FileSystemFlags, @intCast(Mode, @max(number, 0)));
}
const jsType = val.jsType();
@@ -1160,7 +1160,7 @@ pub const FileSystemFlags = enum(Mode) {
return null;
};
- return @intToEnum(FileSystemFlags, @intCast(Mode, flags));
+ return @enumFromInt(FileSystemFlags, @intCast(Mode, flags));
}
return null;
@@ -1172,7 +1172,7 @@ pub const Date = enum(u64) {
_,
pub fn toJS(this: Date, ctx: JSC.C.JSContextRef, exception: JSC.C.ExceptionRef) JSC.C.JSValueRef {
- const seconds = @floatCast(f64, @intToFloat(f64, @enumToInt(this)) * 1000.0);
+ const seconds = @floatCast(f64, @floatFromInt(f64, @intFromEnum(this)) * 1000.0);
const unix_timestamp = JSC.JSValue.jsNumber(seconds);
const array: [1]JSC.C.JSValueRef = .{unix_timestamp.asObjectRef()};
const obj = JSC.C.JSObjectMakeDate(ctx, 1, &array, exception);
@@ -1219,12 +1219,12 @@ fn StatsDataType(comptime T: type) type {
.size = @truncate(T, @intCast(i64, stat_.size)),
.blksize = @truncate(T, @intCast(i64, stat_.blksize)),
.blocks = @truncate(T, @intCast(i64, stat_.blocks)),
- .atime_ms = (@intToFloat(f64, @max(atime.tv_sec, 0)) * std.time.ms_per_s) + (@intToFloat(f64, @intCast(usize, @max(atime.tv_nsec, 0))) / std.time.ns_per_ms),
- .mtime_ms = (@intToFloat(f64, @max(mtime.tv_sec, 0)) * std.time.ms_per_s) + (@intToFloat(f64, @intCast(usize, @max(mtime.tv_nsec, 0))) / std.time.ns_per_ms),
- .ctime_ms = (@intToFloat(f64, @max(ctime.tv_sec, 0)) * std.time.ms_per_s) + (@intToFloat(f64, @intCast(usize, @max(ctime.tv_nsec, 0))) / std.time.ns_per_ms),
- .atime = @intToEnum(Date, @intCast(u64, @max(atime.tv_sec, 0))),
- .mtime = @intToEnum(Date, @intCast(u64, @max(mtime.tv_sec, 0))),
- .ctime = @intToEnum(Date, @intCast(u64, @max(ctime.tv_sec, 0))),
+ .atime_ms = (@floatFromInt(f64, @max(atime.tv_sec, 0)) * std.time.ms_per_s) + (@floatFromInt(f64, @intCast(usize, @max(atime.tv_nsec, 0))) / std.time.ns_per_ms),
+ .mtime_ms = (@floatFromInt(f64, @max(mtime.tv_sec, 0)) * std.time.ms_per_s) + (@floatFromInt(f64, @intCast(usize, @max(mtime.tv_nsec, 0))) / std.time.ns_per_ms),
+ .ctime_ms = (@floatFromInt(f64, @max(ctime.tv_sec, 0)) * std.time.ms_per_s) + (@floatFromInt(f64, @intCast(usize, @max(ctime.tv_nsec, 0))) / std.time.ns_per_ms),
+ .atime = @enumFromInt(Date, @intCast(u64, @max(atime.tv_sec, 0))),
+ .mtime = @enumFromInt(Date, @intCast(u64, @max(mtime.tv_sec, 0))),
+ .ctime = @enumFromInt(Date, @intCast(u64, @max(ctime.tv_sec, 0))),
// Linux doesn't include this info in stat
// maybe it does in statx, but do you really need birthtime? If you do please file an issue.
@@ -1234,9 +1234,9 @@ fn StatsDataType(comptime T: type) type {
@truncate(T, @intCast(i64, if (stat_.birthtime().tv_nsec > 0) (@intCast(usize, stat_.birthtime().tv_nsec) / std.time.ns_per_ms) else 0)),
.birthtime = if (Environment.isLinux)
- @intToEnum(Date, 0)
+ @enumFromInt(Date, 0)
else
- @intToEnum(Date, @intCast(u64, @max(stat_.birthtime().tv_sec, 0))),
+ @enumFromInt(Date, @intCast(u64, @max(stat_.birthtime().tv_sec, 0))),
};
}
};
@@ -1426,49 +1426,49 @@ pub const Dirent = struct {
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.BlockDevice);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.block_device);
}
pub fn isCharacterDevice(
this: *Dirent,
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.CharacterDevice);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.character_device);
}
pub fn isDirectory(
this: *Dirent,
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.Directory);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.directory);
}
pub fn isFIFO(
this: *Dirent,
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.NamedPipe or this.kind == std.fs.File.Kind.EventPort);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.named_pipe or this.kind == std.fs.File.Kind.event_port);
}
pub fn isFile(
this: *Dirent,
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.File);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.file);
}
pub fn isSocket(
this: *Dirent,
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.UnixDomainSocket);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.unix_domain_socket);
}
pub fn isSymbolicLink(
this: *Dirent,
_: *JSC.JSGlobalObject,
_: *JSC.CallFrame,
) callconv(.C) JSC.JSValue {
- return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.SymLink);
+ return JSC.JSValue.jsBoolean(this.kind == std.fs.File.Kind.sym_link);
}
pub fn finalize(this: *Dirent) callconv(.C) void {
@@ -1490,14 +1490,14 @@ pub const Emitter = struct {
pub fn append(this: *List, allocator: std.mem.Allocator, ctx: JSC.C.JSContextRef, listener: Listener) !void {
JSC.C.JSValueProtect(ctx, listener.callback.asObjectRef());
try this.list.append(allocator, listener);
- this.once_count +|= @as(u32, @boolToInt(listener.once));
+ this.once_count +|= @as(u32, @intFromBool(listener.once));
}
pub fn prepend(this: *List, allocator: std.mem.Allocator, ctx: JSC.C.JSContextRef, listener: Listener) !void {
JSC.C.JSValueProtect(ctx, listener.callback.asObjectRef());
try this.list.ensureUnusedCapacity(allocator, 1);
this.list.insertAssumeCapacity(0, listener);
- this.once_count +|= @as(u32, @boolToInt(listener.once));
+ this.once_count +|= @as(u32, @intFromBool(listener.once));
}
// removeListener() will remove, at most, one instance of a listener from the
@@ -1510,7 +1510,7 @@ pub const Emitter = struct {
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]));
+ this.once_count -|= @as(u32, @intFromBool(this.list.items(.once)[i]));
this.list.orderedRemove(i);
return true;
}
diff --git a/src/bun.js/test/jest.zig b/src/bun.js/test/jest.zig
index 00cc954ad..2dc4ae1c4 100644
--- a/src/bun.js/test/jest.zig
+++ b/src/bun.js/test/jest.zig
@@ -210,13 +210,13 @@ pub const TestRunner = struct {
const start = @truncate(Test.ID, this.tests.len);
this.tests.len += count;
var statuses = this.tests.items(.status)[start..][0..count];
- std.mem.set(Test.Status, statuses, Test.Status.pending);
+ @memset(statuses, Test.Status.pending);
this.callback.onUpdateCount(this.callback, count, count + start);
return start;
}
pub fn getOrPutFile(this: *TestRunner, file_path: string) *DescribeScope {
- var entry = this.index.getOrPut(this.allocator, @truncate(u32, std.hash.Wyhash.hash(0, file_path))) catch unreachable;
+ var entry = this.index.getOrPut(this.allocator, @truncate(u32, bun.hash(file_path))) catch unreachable;
if (entry.found_existing) {
return this.files.items(.module_scope)[entry.value_ptr.*];
}
@@ -317,7 +317,7 @@ pub const Snapshots = struct {
name_with_counter[name.len] = ' ';
bun.copy(u8, name_with_counter[name.len + 1 ..], counter_string);
- const name_hash = std.hash.Wyhash.hash(0, name_with_counter);
+ const name_hash = bun.hash(name_with_counter);
if (this.values.get(name_hash)) |expected| {
return expected;
}
@@ -416,7 +416,7 @@ pub const Snapshots = struct {
}
const value_clone = try this.allocator.alloc(u8, value.len);
bun.copy(u8, value_clone, value);
- const name_hash = std.hash.Wyhash.hash(0, key);
+ const name_hash = bun.hash(key);
try this.values.put(name_hash, value_clone);
}
}
diff --git a/src/bun.js/test/pretty_format.zig b/src/bun.js/test/pretty_format.zig
index 15ab88799..29e330a04 100644
--- a/src/bun.js/test/pretty_format.zig
+++ b/src/bun.js/test/pretty_format.zig
@@ -362,7 +362,7 @@ pub const JestPrettyFormat = struct {
};
pub fn get(value: JSValue, globalThis: *JSGlobalObject) Result {
- switch (@enumToInt(value)) {
+ switch (@intFromEnum(value)) {
0, 0xa => return Result{
.tag = .Undefined,
},
@@ -921,7 +921,7 @@ pub const JestPrettyFormat = struct {
this.map = this.map_node.?.data;
}
- var entry = this.map.getOrPut(@enumToInt(value)) catch unreachable;
+ var entry = this.map.getOrPut(@intFromEnum(value)) catch unreachable;
if (entry.found_existing) {
writer.writeAll(comptime Output.prettyFmt("<r><cyan>[Circular]<r>", enable_ansi_colors));
return;
@@ -930,7 +930,7 @@ pub const JestPrettyFormat = struct {
defer {
if (comptime Format.canHaveCircularReferences()) {
- _ = this.map.remove(@enumToInt(value));
+ _ = this.map.remove(@intFromEnum(value));
}
}
@@ -1049,7 +1049,7 @@ pub const JestPrettyFormat = struct {
i = -i;
}
const digits = if (i != 0)
- bun.fmt.fastDigitCount(@intCast(usize, i)) + @as(usize, @boolToInt(is_negative))
+ bun.fmt.fastDigitCount(@intCast(usize, i)) + @as(usize, @intFromBool(is_negative))
else
1;
this.addForNewLine(digits);
@@ -1553,7 +1553,7 @@ pub const JestPrettyFormat = struct {
{
this.indent += 1;
defer this.indent -|= 1;
- const count_without_children = props_iter.len - @as(usize, @boolToInt(children_prop != null));
+ const count_without_children = props_iter.len - @as(usize, @intFromBool(children_prop != null));
while (props_iter.next()) |prop| {
if (prop.eqlComptime("children"))
diff --git a/src/bun.js/webcore.zig b/src/bun.js/webcore.zig
index e7357e4ca..a5009e09e 100644
--- a/src/bun.js/webcore.zig
+++ b/src/bun.js/webcore.zig
@@ -663,7 +663,7 @@ pub const Crypto = struct {
) callconv(.C) JSC.JSValue {
var slice = array.slice();
randomData(globalThis, slice.ptr, slice.len);
- return @intToEnum(JSC.JSValue, @bitCast(i64, @ptrToInt(array)));
+ return @enumFromInt(JSC.JSValue, @bitCast(i64, @intFromPtr(array)));
}
fn randomData(
diff --git a/src/bun.js/webcore/blob.zig b/src/bun.js/webcore/blob.zig
index 9b3ddb8df..d19a2da26 100644
--- a/src/bun.js/webcore/blob.zig
+++ b/src/bun.js/webcore/blob.zig
@@ -546,7 +546,7 @@ pub const Blob = struct {
return JSPromise.resolvedPromiseValue(ctx.ptr(), cloned.toJS(ctx)).asObjectRef();
} else if (destination_type == .bytes and source_type == .file) {
var fake_call_frame: [8]JSC.JSValue = undefined;
- @memset(@ptrCast([*]u8, &fake_call_frame), 0, @sizeOf(@TypeOf(fake_call_frame)));
+ @memset(@ptrCast([*]u8, &fake_call_frame)[0..@sizeOf(@TypeOf(fake_call_frame))], 0);
const blob_value =
source_blob.getSlice(ctx, @ptrCast(*JSC.CallFrame, &fake_call_frame));
@@ -1232,7 +1232,7 @@ pub const Blob = struct {
}).toSystemError();
// assert we never end up reusing the memory
- std.debug.assert(@ptrToInt(this.system_error.?.path.slice().ptr) != @ptrToInt(path_buffer));
+ std.debug.assert(@intFromPtr(this.system_error.?.path.slice().ptr) != @intFromPtr(path_buffer));
callback(this, null_fd);
return;
@@ -1739,12 +1739,12 @@ pub const Blob = struct {
};
const unsupported_directory_error = SystemError{
- .errno = @intCast(c_int, @enumToInt(bun.C.SystemErrno.EISDIR)),
+ .errno = @intCast(c_int, @intFromEnum(bun.C.SystemErrno.EISDIR)),
.message = ZigString.init("That doesn't work on folders"),
.syscall = ZigString.init("fstat"),
};
const unsupported_non_regular_file_error = SystemError{
- .errno = @intCast(c_int, @enumToInt(bun.C.SystemErrno.ENOTSUP)),
+ .errno = @intCast(c_int, @intFromEnum(bun.C.SystemErrno.ENOTSUP)),
.message = ZigString.init("Non-regular files aren't supported yet"),
.syscall = ZigString.init("fstat"),
};
@@ -1978,14 +1978,14 @@ pub const Blob = struct {
}
this.system_error = (JSC.Node.Syscall.Error{
- .errno = @intCast(JSC.Node.Syscall.Error.Int, @enumToInt(linux.E.INVAL)),
+ .errno = @intCast(JSC.Node.Syscall.Error.Int, @intFromEnum(linux.E.INVAL)),
.syscall = TryWith.tag.get(use).?,
}).toSystemError();
return AsyncIO.asError(linux.E.INVAL);
},
else => |errno| {
this.system_error = (JSC.Node.Syscall.Error{
- .errno = @intCast(JSC.Node.Syscall.Error.Int, @enumToInt(errno)),
+ .errno = @intCast(JSC.Node.Syscall.Error.Int, @intFromEnum(errno)),
.syscall = TryWith.tag.get(use).?,
}).toSystemError();
return AsyncIO.asError(errno);
@@ -2000,7 +2000,7 @@ pub const Blob = struct {
}
pub fn doFCopyFile(this: *CopyFile) anyerror!void {
- switch (JSC.Node.Syscall.fcopyfile(this.source_fd, this.destination_fd, os.system.COPYFILE_DATA)) {
+ switch (JSC.Node.Syscall.fcopyfile(this.source_fd, this.destination_fd, os.system.COPYFILE.DATA)) {
.err => |errno| {
this.system_error = errno.toSystemError();
@@ -3816,10 +3816,10 @@ pub const InlineBlob = extern struct {
var bytes_slice = inline_blob.bytes[0..total];
if (first.len > 0)
- @memcpy(bytes_slice.ptr, first.ptr, first.len);
+ @memcpy(bytes_slice[0..first.len], first);
if (second.len > 0)
- @memcpy(bytes_slice.ptr + first.len, second.ptr, second.len);
+ @memcpy(bytes_slice[first.len..][0..second.len], second);
inline_blob.len = @truncate(@TypeOf(inline_blob.len), total);
return inline_blob;
@@ -3834,7 +3834,7 @@ pub const InlineBlob = extern struct {
};
if (data.len > 0)
- @memcpy(&blob.bytes, data.ptr, data.len);
+ @memcpy(blob.bytes[0..data.len], data);
return blob;
}
diff --git a/src/bun.js/webcore/encoding.zig b/src/bun.js/webcore/encoding.zig
index e4b8a4b95..5c8221128 100644
--- a/src/bun.js/webcore/encoding.zig
+++ b/src/bun.js/webcore/encoding.zig
@@ -68,7 +68,7 @@ pub const TextEncoder = struct {
std.debug.assert(result.read == slice.len);
const array_buffer = uint8array.asArrayBuffer(globalThis).?;
std.debug.assert(result.written == array_buffer.len);
- @memcpy(array_buffer.byteSlice().ptr, &buf, result.written);
+ @memcpy(array_buffer.byteSlice()[0..result.written], buf[0..result.written]);
return uint8array;
} else {
const bytes = strings.allocateLatin1IntoUTF8(globalThis.bunVM().allocator, []const u8, slice) catch {
@@ -103,7 +103,7 @@ pub const TextEncoder = struct {
const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, 3);
const array_buffer = uint8array.asArrayBuffer(globalThis).?;
const replacement_char = [_]u8{ 239, 191, 189 };
- @memcpy(array_buffer.slice().ptr, &replacement_char, replacement_char.len);
+ @memcpy(array_buffer.slice()[0..replacement_char.len], &replacement_char);
return uint8array;
}
const uint8array = JSC.JSValue.createUninitializedUint8Array(globalThis, result.written);
@@ -111,7 +111,7 @@ pub const TextEncoder = struct {
std.debug.assert(result.read == slice.len);
const array_buffer = uint8array.asArrayBuffer(globalThis).?;
std.debug.assert(result.written == array_buffer.len);
- @memcpy(array_buffer.slice().ptr, &buf, result.written);
+ @memcpy(array_buffer.slice()[0..result.written], buf[0..result.written]);
return uint8array;
} else {
var bytes = strings.toUTF8AllocWithType(
@@ -207,7 +207,7 @@ pub const TextEncoder = struct {
if (array.isEmpty()) {
array = JSC.JSValue.createUninitializedUint8Array(globalThis, length);
array.ensureStillAlive();
- @memcpy(array.asArrayBuffer(globalThis).?.ptr, buf_to_use.ptr, length);
+ @memcpy(array.asArrayBuffer(globalThis).?.ptr[0..length], buf_to_use[0..length]);
}
return array;
@@ -224,7 +224,7 @@ pub const TextEncoder = struct {
var result: strings.EncodeIntoResult = strings.copyUTF16IntoUTF8(output, []const u16, input, false);
if (output.len >= 3 and (result.read == 0 or result.written == 0)) {
const replacement_char = [_]u8{ 239, 191, 189 };
- @memcpy(buf_ptr, &replacement_char, replacement_char.len);
+ @memcpy(buf_ptr[0..replacement_char.len], &replacement_char);
result.read = 1;
result.written = 3;
}
@@ -515,10 +515,10 @@ pub const TextDecoder = struct {
buffer.ensureTotalCapacity(allocator, slice.len) catch unreachable;
buffer.items.len = i;
+ var len = std.mem.sliceAsBytes(slice[0..i]).len;
@memcpy(
- std.mem.sliceAsBytes(buffer.items).ptr,
- std.mem.sliceAsBytes(slice).ptr,
- std.mem.sliceAsBytes(slice[0..i]).len,
+ std.mem.sliceAsBytes(buffer.items)[0..len],
+ std.mem.sliceAsBytes(slice)[0..len],
);
const first_high_surrogate = 0xD800;
@@ -537,10 +537,10 @@ pub const TextDecoder = struct {
const prev = buffer.items.len;
buffer.items.len += count;
// Since this string is freshly allocated, we know it's not going to overlap
+ len = std.mem.sliceAsBytes(remainder[0..count]).len;
@memcpy(
- std.mem.sliceAsBytes(buffer.items[prev..]).ptr,
- std.mem.sliceAsBytes(remainder).ptr,
- std.mem.sliceAsBytes(remainder[0..count]).len,
+ std.mem.sliceAsBytes(buffer.items[prev..])[0..len],
+ std.mem.sliceAsBytes(remainder)[0..len],
);
remainder = remainder[count..];
},
@@ -659,7 +659,7 @@ pub const TextDecoder = struct {
},
EncodingLabel.@"UTF-16LE" => {
- if (std.mem.isAligned(@ptrToInt(buffer_slice.ptr), @alignOf([*]const u16))) {
+ if (std.mem.isAligned(@intFromPtr(buffer_slice.ptr), @alignOf([*]const u16))) {
return this.decodeUTF16WithAlignment([]const u16, @alignCast(2, std.mem.bytesAsSlice(u16, buffer_slice)), globalThis);
}
@@ -701,7 +701,7 @@ pub const TextDecoder = struct {
pub const Encoder = struct {
export fn Bun__encoding__writeLatin1(input: [*]const u8, len: usize, to: [*]u8, to_len: usize, encoding: u8) usize {
- return switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ return switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.utf8 => writeU8(input, len, to, to_len, .utf8),
.latin1 => writeU8(input, len, to, to_len, .ascii),
.ascii => writeU8(input, len, to, to_len, .ascii),
@@ -714,7 +714,7 @@ pub const Encoder = struct {
} catch 0;
}
export fn Bun__encoding__writeUTF16(input: [*]const u16, len: usize, to: [*]u8, to_len: usize, encoding: u8) usize {
- return switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ return switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.utf8 => writeU16(input, len, to, to_len, .utf8, false),
.latin1 => writeU16(input, len, to, to_len, .ascii, false),
.ascii => writeU16(input, len, to, to_len, .ascii, false),
@@ -727,7 +727,7 @@ pub const Encoder = struct {
} catch 0;
}
export fn Bun__encoding__byteLengthLatin1(input: [*]const u8, len: usize, encoding: u8) usize {
- return switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ return switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.utf8 => byteLengthU8(input, len, .utf8),
.latin1 => byteLengthU8(input, len, .ascii),
.ascii => byteLengthU8(input, len, .ascii),
@@ -740,7 +740,7 @@ pub const Encoder = struct {
};
}
export fn Bun__encoding__byteLengthUTF16(input: [*]const u16, len: usize, encoding: u8) usize {
- return switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ return switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.utf8 => byteLengthU16(input, len, .utf8),
.latin1 => byteLengthU16(input, len, .ascii),
.ascii => byteLengthU16(input, len, .ascii),
@@ -753,7 +753,7 @@ pub const Encoder = struct {
};
}
export fn Bun__encoding__constructFromLatin1(globalObject: *JSGlobalObject, input: [*]const u8, len: usize, encoding: u8) JSValue {
- var slice = switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ var slice = switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.hex => constructFromU8(input, len, .hex),
.ascii => constructFromU8(input, len, .ascii),
.base64url => constructFromU8(input, len, .base64url),
@@ -766,7 +766,7 @@ pub const Encoder = struct {
return JSC.JSValue.createBuffer(globalObject, slice, globalObject.bunVM().allocator);
}
export fn Bun__encoding__constructFromUTF16(globalObject: *JSGlobalObject, input: [*]const u16, len: usize, encoding: u8) JSValue {
- var slice = switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ var slice = switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.base64 => constructFromU16(input, len, .base64),
.hex => constructFromU16(input, len, .hex),
.base64url => constructFromU16(input, len, .base64url),
@@ -785,7 +785,7 @@ pub const Encoder = struct {
}
export fn Bun__encoding__toString(input: [*]const u8, len: usize, globalObject: *JSC.JSGlobalObject, encoding: u8) JSValue {
- return switch (@intToEnum(JSC.Node.Encoding, encoding)) {
+ return switch (@enumFromInt(JSC.Node.Encoding, encoding)) {
.ucs2 => toString(input, len, globalObject, .utf16le),
.utf16le => toString(input, len, globalObject, .utf16le),
.utf8 => toString(input, len, globalObject, .utf8),
@@ -830,7 +830,7 @@ pub const Encoder = struct {
.latin1 => {
var to = allocator.alloc(u8, len) catch return ZigString.init("Out of memory").toErrorInstance(global);
- @memcpy(to.ptr, input_ptr, to.len);
+ @memcpy(to, input_ptr[0..to.len]);
return ZigString.init(to).toExternalValue(global);
},
@@ -852,7 +852,7 @@ pub const Encoder = struct {
var output_bytes = std.mem.sliceAsBytes(output);
output_bytes[output_bytes.len - 1] = 0;
- @memcpy(output_bytes.ptr, input_ptr, output_bytes.len);
+ @memcpy(output_bytes, input_ptr[0..output_bytes.len]);
return ZigString.toExternalU16(output.ptr, output.len, global);
},
@@ -892,7 +892,7 @@ pub const Encoder = struct {
switch (comptime encoding) {
.buffer => {
const written = @min(len, to_len);
- @memcpy(to_ptr, input, written);
+ @memcpy(to_ptr[0..written], input[0..written]);
return written;
},
@@ -903,7 +903,7 @@ pub const Encoder = struct {
var remain = input[0..written];
if (bun.simdutf.validate.ascii(remain)) {
- @memcpy(to.ptr, remain.ptr, written);
+ @memcpy(to_ptr[0..written], remain[0..written]);
} else {
strings.copyLatin1IntoASCII(to, remain);
}
@@ -919,7 +919,7 @@ pub const Encoder = struct {
if (to_len < 2)
return 0;
- if (std.mem.isAligned(@ptrToInt(to_ptr), @alignOf([*]u16))) {
+ if (std.mem.isAligned(@intFromPtr(to_ptr), @alignOf([*]u16))) {
var buf = input[0..len];
var output = @ptrCast([*]u16, @alignCast(@alignOf(u16), to_ptr))[0 .. to_len / 2];
@@ -1065,14 +1065,14 @@ pub const Encoder = struct {
switch (comptime encoding) {
.buffer => {
var to = allocator.alloc(u8, len) catch return &[_]u8{};
- @memcpy(to.ptr, input, len);
+ @memcpy(to[0..len], input[0..len]);
return to;
},
.latin1, .ascii => {
var to = allocator.alloc(u8, len) catch return &[_]u8{};
- @memcpy(to.ptr, input, len);
+ @memcpy(to[0..len], input[0..len]);
return to;
},
@@ -1121,7 +1121,7 @@ pub const Encoder = struct {
.latin1, .buffer, .ascii => {
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);
+ @memcpy(to[0..input_bytes.len], input_bytes);
for (to[0..len], 0..) |c, i| {
to[i] = @as(u8, @truncate(u7, c));
}
@@ -1131,7 +1131,8 @@ pub const Encoder = struct {
// string is already encoded, just need to copy the data
.ucs2, .utf16le => {
var to = std.mem.sliceAsBytes(allocator.alloc(u16, len * 2) catch return &[_]u8{});
- @memcpy(to.ptr, std.mem.sliceAsBytes(input[0..len]).ptr, std.mem.sliceAsBytes(input[0..len]).len);
+ const bytes = std.mem.sliceAsBytes(input[0..len]);
+ @memcpy(to[0..bytes.len], bytes);
return to;
},
diff --git a/src/bun.js/webcore/request.zig b/src/bun.js/webcore/request.zig
index a8c648212..231f0deed 100644
--- a/src/bun.js/webcore/request.zig
+++ b/src/bun.js/webcore/request.zig
@@ -472,8 +472,8 @@ pub const Request = struct {
url_or_object,
if (is_first_argument_a_url) JSValue.undefined else url_or_object,
};
- const values_to_try = values_to_try_[0 .. @as(usize, @boolToInt(!is_first_argument_a_url)) +
- @as(usize, @boolToInt(arguments.len > 1 and arguments[1].isObject()))];
+ const values_to_try = values_to_try_[0 .. @as(usize, @intFromBool(!is_first_argument_a_url)) +
+ @as(usize, @intFromBool(arguments.len > 1 and arguments[1].isObject()))];
for (values_to_try) |value| {
const value_type = value.jsType();
@@ -564,7 +564,7 @@ pub const Request = struct {
fields.insert(.url);
// first value
- } else if (@enumToInt(value) == @enumToInt(values_to_try[values_to_try.len - 1]) and !is_first_argument_a_url and
+ } else if (@intFromEnum(value) == @intFromEnum(values_to_try[values_to_try.len - 1]) and !is_first_argument_a_url and
value.implementsToString(globalThis))
{
const slice = value.toSliceOrNull(globalThis) orelse {
diff --git a/src/bun.js/webcore/response.zig b/src/bun.js/webcore/response.zig
index beae4d182..b4ea08579 100644
--- a/src/bun.js/webcore/response.zig
+++ b/src/bun.js/webcore/response.zig
@@ -386,7 +386,7 @@ pub const Response = struct {
const json_value = args.nextEat() orelse JSC.JSValue.zero;
- if (@enumToInt(json_value) != 0) {
+ if (@intFromEnum(json_value) != 0) {
var zig_str = JSC.ZigString.init("");
// calling JSON.stringify on an empty string adds extra quotes
// so this is correct
@@ -448,7 +448,7 @@ pub const Response = struct {
const url_string_value = args.nextEat() orelse JSC.JSValue.zero;
var url_string = ZigString.init("");
- if (@enumToInt(url_string_value) != 0) {
+ if (@intFromEnum(url_string_value) != 0) {
url_string = url_string_value.getZigString(globalThis.ptr());
}
var url_string_slice = url_string.toSlice(getAllocator(globalThis));
@@ -1147,9 +1147,9 @@ pub const Fetch = struct {
JSC.JSError(bun.default_allocator, "Out of memory", .{}, ctx, exception);
return .zero;
};
- @memcpy(buffer.ptr, url_slice.ptr, url_slice.len);
+ @memcpy(buffer[0..url_slice.len], url_slice);
var proxy_url_slice = buffer[url_slice.len..];
- @memcpy(proxy_url_slice.ptr, proxy_url_zig.ptr, proxy_url_zig.len);
+ @memcpy(proxy_url_slice[0..proxy_url_zig.len], proxy_url_zig.ptr[0..proxy_url_zig.len]);
url = ZigURL.parse(buffer[0..url_slice.len]);
proxy = ZigURL.parse(proxy_url_slice);
@@ -1283,9 +1283,9 @@ pub const Fetch = struct {
JSC.JSError(bun.default_allocator, "Out of memory", .{}, ctx, exception);
return .zero;
};
- @memcpy(buffer.ptr, url_slice.ptr, url_slice.len);
+ @memcpy(buffer[0..url_slice.len], url_slice.ptr[0..url_slice.len]);
var proxy_url_slice = buffer[url_slice.len..];
- @memcpy(proxy_url_slice.ptr, proxy_url_zig.ptr, proxy_url_zig.len);
+ @memcpy(proxy_url_slice[0..proxy_url_zig.len], proxy_url_zig.ptr[0..proxy_url_zig.len]);
url = ZigURL.parse(buffer[0..url_slice.len]);
proxy = ZigURL.parse(proxy_url_slice);
@@ -1695,7 +1695,7 @@ pub const FetchEvent = struct {
defer {
if (!VirtualMachine.get().had_errors) {
- Output.printElapsed(@intToFloat(f64, (request_context.timer.lap())) / std.time.ns_per_ms);
+ Output.printElapsed(@floatFromInt(f64, (request_context.timer.lap())) / std.time.ns_per_ms);
Output.prettyError(
" <b>{s}<r><d> - <b>{d}<r> <d>transpiled, <d><b>{d}<r> <d>imports<r>\n",
diff --git a/src/bun.js/webcore/streams.zig b/src/bun.js/webcore/streams.zig
index dddfcbaf5..5986afac7 100644
--- a/src/bun.js/webcore/streams.zig
+++ b/src/bun.js/webcore/streams.zig
@@ -247,7 +247,7 @@ pub const ReadableStream = struct {
pub fn fromNative(globalThis: *JSGlobalObject, id: Tag, ptr: *anyopaque) JSC.JSValue {
JSC.markBinding(@src());
- return ZigGlobalObject__createNativeReadableStream(globalThis, JSValue.fromPtr(ptr), JSValue.jsNumber(@enumToInt(id)));
+ return ZigGlobalObject__createNativeReadableStream(globalThis, JSValue.fromPtr(ptr), JSValue.jsNumber(@intFromEnum(id)));
}
pub fn fromBlob(globalThis: *JSGlobalObject, blob: *const Blob, recommended_chunk_size: Blob.SizeType) JSC.JSValue {
@@ -329,11 +329,11 @@ pub const ReadableStream = struct {
const filedes_ = @bitCast([8]u8, @as(usize, @truncate(u56, @intCast(usize, filedes))));
bytes[1..8].* = filedes_[0..7].*;
- return @intToEnum(StreamTag, @bitCast(u64, bytes));
+ return @enumFromInt(StreamTag, @bitCast(u64, bytes));
}
pub fn fd(this: StreamTag) bun.FileDescriptor {
- var bytes = @bitCast([8]u8, @enumToInt(this));
+ var bytes = @bitCast([8]u8, @intFromEnum(this));
if (bytes[0] != 1) {
return bun.invalid_fd;
}
@@ -780,13 +780,15 @@ pub const StreamResult = union(Tag) {
.temporary => |temp| {
var array = JSC.JSValue.createUninitializedUint8Array(globalThis, temp.len);
var slice_ = array.asArrayBuffer(globalThis).?.slice();
- @memcpy(slice_.ptr, temp.ptr, temp.len);
+ const temp_slice = temp.slice();
+ @memcpy(slice_[0..temp_slice.len], temp_slice);
return array;
},
.temporary_and_done => |temp| {
var array = JSC.JSValue.createUninitializedUint8Array(globalThis, temp.len);
var slice_ = array.asArrayBuffer(globalThis).?.slice();
- @memcpy(slice_.ptr, temp.ptr, temp.len);
+ const temp_slice = temp.slice();
+ @memcpy(slice_[0..temp_slice.len], temp_slice);
return array;
},
.into_array => |array| {
@@ -818,7 +820,7 @@ pub const Signal = struct {
ptr: *anyopaque = dead,
vtable: VTable = VTable.Dead,
- pub const dead = @intToPtr(*anyopaque, 0xaaaaaaaa);
+ pub const dead = @ptrFromInt(*anyopaque, 0xaaaaaaaa);
pub fn clear(this: *Signal) void {
this.ptr = dead;
@@ -920,7 +922,7 @@ pub const Sink = struct {
used: bool = false,
pub const pending = Sink{
- .ptr = @intToPtr(*anyopaque, 0xaaaaaaaa),
+ .ptr = @ptrFromInt(*anyopaque, 0xaaaaaaaa),
.vtable = undefined,
};
@@ -961,7 +963,8 @@ pub const Sink = struct {
if (stack_size >= str.len) {
var buf: [stack_size]u8 = undefined;
- @memcpy(&buf, str.ptr, str.len);
+ @memcpy(buf[0..str.len], str);
+
strings.replaceLatin1WithUTF8(buf[0..str.len]);
if (input.isDone()) {
const result = writeFn(ctx, .{ .temporary_and_done = bun.ByteList.init(buf[0..str.len]) });
@@ -974,7 +977,8 @@ pub const Sink = struct {
{
var slice = bun.default_allocator.alloc(u8, str.len) catch return .{ .err = Syscall.Error.oom };
- @memcpy(slice.ptr, str.ptr, str.len);
+ @memcpy(slice[0..str.len], str);
+
strings.replaceLatin1WithUTF8(slice[0..str.len]);
if (input.isDone()) {
return writeFn(ctx, .{ .owned_and_done = bun.ByteList.init(slice) });
@@ -1262,7 +1266,7 @@ pub const FileSink = struct {
const initial_remain = remain;
defer {
- std.debug.assert(total - initial == @ptrToInt(remain.ptr) - @ptrToInt(initial_remain.ptr));
+ std.debug.assert(total - initial == @intFromPtr(remain.ptr) - @intFromPtr(initial_remain.ptr));
if (remain.len == 0) {
this.head = 0;
@@ -1908,15 +1912,15 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type {
pub fn init(cpp: JSValue) Signal {
// this one can be null
@setRuntimeSafety(false);
- return Signal.initWithType(SinkSignal, @intToPtr(*SinkSignal, @bitCast(usize, @enumToInt(cpp))));
+ return Signal.initWithType(SinkSignal, @ptrFromInt(*SinkSignal, @bitCast(usize, @intFromEnum(cpp))));
}
pub fn close(this: *@This(), _: ?Syscall.Error) void {
- onClose(@bitCast(SinkSignal, @ptrToInt(this)).cpp, JSValue.jsUndefined());
+ onClose(@bitCast(SinkSignal, @intFromPtr(this)).cpp, JSValue.jsUndefined());
}
pub fn ready(this: *@This(), _: ?Blob.SizeType, _: ?Blob.SizeType) void {
- onReady(@bitCast(SinkSignal, @ptrToInt(this)).cpp, JSValue.jsUndefined(), JSValue.jsUndefined());
+ onReady(@bitCast(SinkSignal, @intFromPtr(this)).cpp, JSValue.jsUndefined(), JSValue.jsUndefined());
}
pub fn start(_: *@This()) void {}
@@ -1992,7 +1996,7 @@ pub fn NewJSSink(comptime SinkType: type, comptime name_: []const u8) type {
if (this.sink.signal.isDead())
return;
this.sink.signal.clear();
- const value = @intToEnum(JSValue, @bitCast(JSC.JSValueReprInt, @ptrToInt(ptr)));
+ const value = @enumFromInt(JSValue, @bitCast(JSC.JSValueReprInt, @intFromPtr(ptr)));
value.unprotect();
detachPtr(value);
}
@@ -3127,7 +3131,7 @@ pub const ByteBlobLoader = struct {
this.remain -|= copied;
this.offset +|= copied;
std.debug.assert(buffer.ptr != temporary.ptr);
- @memcpy(buffer.ptr, temporary.ptr, temporary.len);
+ @memcpy(buffer[0..temporary.len], temporary);
if (this.remain == 0) {
return .{ .into_array_and_done = .{ .value = array, .len = copied } };
}
@@ -3231,7 +3235,7 @@ pub const ByteStream = struct {
}
if (this.has_received_last_chunk) {
- return .{ .chunk_size = @truncate(Blob.SizeType, @min(1024 * 1024 * 2, this.buffer.items.len)) };
+ return .{ .chunk_size = @min(1024 * 1024 * 2, this.buffer.items.len) };
}
if (this.highWaterMark == 0) {
@@ -3292,7 +3296,7 @@ pub const ByteStream = struct {
var to_copy = this.pending_buffer[0..@min(chunk.len, this.pending_buffer.len)];
const pending_buffer_len = this.pending_buffer.len;
std.debug.assert(to_copy.ptr != chunk.ptr);
- @memcpy(to_copy.ptr, chunk.ptr, to_copy.len);
+ @memcpy(to_copy, chunk[0..to_copy.len]);
this.pending_buffer = &.{};
const is_really_done = this.has_received_last_chunk and to_copy.len <= pending_buffer_len;
@@ -3382,7 +3386,7 @@ pub const ByteStream = struct {
);
var remaining_in_buffer = this.buffer.items[this.offset..][0..to_write];
- @memcpy(buffer.ptr, this.buffer.items.ptr + this.offset, to_write);
+ @memcpy(buffer[0..to_write], this.buffer.items[this.offset..][0..to_write]);
if (this.offset + to_write == this.buffer.items.len) {
this.offset = 0;
@@ -4071,7 +4075,7 @@ pub const File = struct {
this.pending.result = .{
.err = Syscall.Error{
// this is too hacky
- .errno = @truncate(Syscall.Error.Int, @intCast(u16, @max(1, @errorToInt(err)))),
+ .errno = @truncate(Syscall.Error.Int, @intCast(u16, @max(1, @intFromError(err)))),
.syscall = .read,
},
};
@@ -4655,4 +4659,3 @@ pub fn NewReadyWatcher(
// pub fn onError(this: *Streamer): anytype,
// };
// }
-
diff --git a/src/bun.zig b/src/bun.zig
index f2d76df53..bd50af6f6 100644
--- a/src/bun.zig
+++ b/src/bun.zig
@@ -149,7 +149,7 @@ pub const fmt = struct {
const mags_iec = " KMGTPEZY";
const log2 = math.log2(value);
- const magnitude = math.min(log2 / comptime math.log2(1000), mags_si.len - 1);
+ const magnitude = @min(log2 / comptime math.log2(1000), mags_si.len - 1);
const new_value = math.lossyCast(f64, value) / math.pow(f64, 1000, math.lossyCast(f64, magnitude));
const suffix = switch (1000) {
1000 => mags_si[magnitude],
@@ -176,7 +176,7 @@ pub const fmt = struct {
pub fn size(value: anytype) SizeFormatter {
return switch (@TypeOf(value)) {
f64, f32, f128 => SizeFormatter{
- .value = @floatToInt(u64, value),
+ .value = @intFromFloat(u64, value),
},
else => SizeFormatter{ .value = @intCast(u64, value) },
};
@@ -288,7 +288,7 @@ pub const MAX_PATH_BYTES: usize = if (Environment.isWasm) 1024 else std.fs.MAX_P
pub inline fn cast(comptime To: type, value: anytype) To {
if (comptime std.meta.trait.isIntegral(@TypeOf(value))) {
- return @intToPtr(To, @bitCast(usize, value));
+ return @ptrFromInt(To, @bitCast(usize, value));
}
// TODO: file issue about why std.meta.Child only is necessary on Linux aarch64
@@ -471,7 +471,7 @@ pub inline fn range(comptime min: anytype, comptime max: anytype) [max - min]usi
pub fn copy(comptime Type: type, dest: []Type, src: []const Type) void {
if (comptime Environment.allow_assert) std.debug.assert(dest.len >= src.len);
- if (@ptrToInt(src.ptr) == @ptrToInt(dest.ptr) or src.len == 0) return;
+ if (@intFromPtr(src.ptr) == @intFromPtr(dest.ptr) or src.len == 0) return;
const input: []const u8 = std.mem.sliceAsBytes(src);
const output: []u8 = std.mem.sliceAsBytes(dest);
@@ -479,13 +479,13 @@ pub fn copy(comptime Type: type, dest: []Type, src: []const Type) void {
std.debug.assert(input.len > 0);
std.debug.assert(output.len > 0);
- const does_input_or_output_overlap = (@ptrToInt(input.ptr) < @ptrToInt(output.ptr) and
- @ptrToInt(input.ptr) + input.len > @ptrToInt(output.ptr)) or
- (@ptrToInt(output.ptr) < @ptrToInt(input.ptr) and
- @ptrToInt(output.ptr) + output.len > @ptrToInt(input.ptr));
+ const does_input_or_output_overlap = (@intFromPtr(input.ptr) < @intFromPtr(output.ptr) and
+ @intFromPtr(input.ptr) + input.len > @intFromPtr(output.ptr)) or
+ (@intFromPtr(output.ptr) < @intFromPtr(input.ptr) and
+ @intFromPtr(output.ptr) + output.len > @intFromPtr(input.ptr));
if (!does_input_or_output_overlap) {
- @memcpy(output.ptr, input.ptr, input.len);
+ @memcpy(output[0..input.len], input);
} else {
C.memmove(output.ptr, input.ptr, input.len);
}
@@ -541,14 +541,14 @@ pub fn assertDefined(val: anytype) void {
std.debug.assert(val.len < std.math.maxInt(u32) + 1);
var slice: []Type = undefined;
if (val.len > 0) {
- std.debug.assert(@ptrToInt(val.ptr) != @ptrToInt(slice.ptr));
+ std.debug.assert(@intFromPtr(val.ptr) != @intFromPtr(slice.ptr));
}
return;
}
if (comptime @typeInfo(Type) == .Pointer) {
var slice: *Type = undefined;
- std.debug.assert(@ptrToInt(val) != @ptrToInt(slice));
+ std.debug.assert(@intFromPtr(val) != @intFromPtr(slice));
return;
}
@@ -566,6 +566,10 @@ pub fn hash(content: []const u8) u64 {
return std.hash.Wyhash.hash(0, content);
}
+pub fn hashWithSeed(seed: u64, content: []const u8) u64 {
+ return std.hash.Wyhash.hash(seed, content);
+}
+
pub fn hash32(content: []const u8) u32 {
const res = hash(content);
return @truncate(u32, res);
@@ -592,7 +596,7 @@ pub fn ensureNonBlocking(fd: anytype) void {
const global_scope_log = Output.scoped(.bun, false);
pub fn isReadable(fd: std.os.fd_t) PollFlag {
- var polls = &[_]std.os.pollfd{
+ var polls = [_]std.os.pollfd{
.{
.fd = fd,
.events = std.os.POLL.IN | std.os.POLL.ERR,
@@ -600,7 +604,7 @@ pub fn isReadable(fd: std.os.fd_t) PollFlag {
},
};
- const result = (std.os.poll(polls, 0) catch 0) != 0;
+ const result = (std.os.poll(&polls, 0) catch 0) != 0;
global_scope_log("poll({d}) readable: {any} ({d})", .{ fd, result, polls[0].revents });
return if (result and polls[0].revents & std.os.POLL.HUP != 0)
PollFlag.hup
@@ -612,7 +616,7 @@ pub fn isReadable(fd: std.os.fd_t) PollFlag {
pub const PollFlag = enum { ready, not_ready, hup };
pub fn isWritable(fd: std.os.fd_t) PollFlag {
- var polls = &[_]std.os.pollfd{
+ var polls = [_]std.os.pollfd{
.{
.fd = fd,
.events = std.os.POLL.OUT,
@@ -620,7 +624,7 @@ pub fn isWritable(fd: std.os.fd_t) PollFlag {
},
};
- const result = (std.os.poll(polls, 0) catch 0) != 0;
+ const result = (std.os.poll(&polls, 0) catch 0) != 0;
global_scope_log("poll({d}) writable: {any} ({d})", .{ fd, result, polls[0].revents });
if (result and polls[0].revents & std.os.POLL.HUP != 0) {
return PollFlag.hup;
@@ -678,13 +682,13 @@ pub fn isHeapMemory(memory: anytype) bool {
pub const Mimalloc = @import("./allocators/mimalloc.zig");
pub inline fn isSliceInBuffer(slice: []const u8, buffer: []const u8) bool {
- return slice.len > 0 and @ptrToInt(buffer.ptr) <= @ptrToInt(slice.ptr) and ((@ptrToInt(slice.ptr) + slice.len) <= (@ptrToInt(buffer.ptr) + buffer.len));
+ return slice.len > 0 and @intFromPtr(buffer.ptr) <= @intFromPtr(slice.ptr) and ((@intFromPtr(slice.ptr) + slice.len) <= (@intFromPtr(buffer.ptr) + buffer.len));
}
pub fn rangeOfSliceInBuffer(slice: []const u8, buffer: []const u8) ?[2]u32 {
if (!isSliceInBuffer(slice, buffer)) return null;
const r = [_]u32{
- @truncate(u32, @ptrToInt(slice.ptr) -| @ptrToInt(buffer.ptr)),
+ @truncate(u32, @intFromPtr(slice.ptr) -| @intFromPtr(buffer.ptr)),
@truncate(u32, slice.len),
};
if (comptime Environment.allow_assert)
@@ -870,7 +874,7 @@ pub const SignalCode = enum(u8) {
_,
pub fn name(value: SignalCode) ?[]const u8 {
- if (@enumToInt(value) <= @enumToInt(SignalCode.SIGSYS)) {
+ if (@intFromEnum(value) <= @intFromEnum(SignalCode.SIGSYS)) {
return asByteSlice(@tagName(value));
}
@@ -878,14 +882,14 @@ pub const SignalCode = enum(u8) {
}
pub fn from(value: anytype) SignalCode {
- return @intToEnum(SignalCode, @truncate(u7, std.mem.asBytes(&value)[0]));
+ return @enumFromInt(SignalCode, @truncate(u7, std.mem.asBytes(&value)[0]));
}
pub fn format(self: SignalCode, comptime _: []const u8, _: fmt.FormatOptions, writer: anytype) !void {
if (self.name()) |str| {
- try std.fmt.format(writer, "code {d} ({s})", .{ @enumToInt(self), str });
+ try std.fmt.format(writer, "code {d} ({s})", .{ @intFromEnum(self), str });
} else {
- try std.fmt.format(writer, "code {d}", .{@enumToInt(self)});
+ try std.fmt.format(writer, "code {d}", .{@intFromEnum(self)});
}
}
};
@@ -961,7 +965,7 @@ pub fn ComptimeEnumMap(comptime T: type) type {
/// Ignores default struct values.
pub fn zero(comptime Type: type) Type {
var out: [@sizeOf(Type)]u8 align(@alignOf(Type)) = undefined;
- @memset(@ptrCast([*]u8, &out), 0, out.len);
+ @memset(@ptrCast([*]u8, &out)[0..out.len], 0);
return @bitCast(Type, out);
}
pub const c_ares = @import("./deps/c_ares.zig");
@@ -1533,3 +1537,5 @@ pub const WTF = struct {
};
pub const ArenaAllocator = @import("./ArenaAllocator.zig").ArenaAllocator;
+
+pub const Wyhash = @import("./wyhash.zig").Wyhash;
diff --git a/src/bun_js.zig b/src/bun_js.zig
index fd124a8ac..63ffe0611 100644
--- a/src/bun_js.zig
+++ b/src/bun_js.zig
@@ -351,6 +351,6 @@ pub const Run = struct {
vm.onExit();
if (!JSC.is_bindgen) JSC.napi.fixDeadCodeElimination();
- Global.exit(@boolToInt(this.any_unhandled));
+ Global.exit(@intFromBool(this.any_unhandled));
}
};
diff --git a/src/bundler.zig b/src/bundler.zig
index fb0a11be7..ec8f6b5df 100644
--- a/src/bundler.zig
+++ b/src/bundler.zig
@@ -1601,7 +1601,7 @@ pub const Bundler = struct {
// All non-absolute paths are ./paths
if (path_to_use[0] != '/' and path_to_use[0] != '.') {
tmp_buildfile_buf3[0..2].* = "./".*;
- @memcpy(tmp_buildfile_buf3[2..], path_to_use.ptr, path_to_use.len);
+ @memcpy(tmp_buildfile_buf3[2..][0..path_to_use.len], path_to_use);
path_to_use = tmp_buildfile_buf3[0 .. 2 + path_to_use.len];
}
diff --git a/src/bundler/bundle_v2.zig b/src/bundler/bundle_v2.zig
index a03847079..231a4bde8 100644
--- a/src/bundler/bundle_v2.zig
+++ b/src/bundler/bundle_v2.zig
@@ -103,7 +103,6 @@ const Resolver = _resolver.Resolver;
const TOML = @import("../toml/toml_parser.zig").TOML;
const EntryPoints = @import("./entry_points.zig");
const ThisBundler = @import("../bundler.zig").Bundler;
-const wyhash = std.hash.Wyhash.hash;
const Dependency = js_ast.Dependency;
const JSAst = js_ast.BundledAst;
const Loader = options.Loader;
@@ -1364,8 +1363,8 @@ pub const BundleV2 = struct {
},
.err => |err| {
log.msgs.append(err) catch unreachable;
- log.errors += @as(usize, @boolToInt(err.kind == .err));
- log.warnings += @as(usize, @boolToInt(err.kind == .warn));
+ log.errors += @as(usize, @intFromBool(err.kind == .err));
+ log.warnings += @as(usize, @intFromBool(err.kind == .warn));
// An error ocurred, prevent spinning the event loop forever
_ = @atomicRmw(usize, &this.graph.parse_pending, .Sub, 1, .Monotonic);
@@ -1520,8 +1519,8 @@ pub const BundleV2 = struct {
},
.err => |err| {
log.msgs.append(err) catch unreachable;
- log.errors += @as(usize, @boolToInt(err.kind == .err));
- log.warnings += @as(usize, @boolToInt(err.kind == .warn));
+ log.errors += @as(usize, @intFromBool(err.kind == .err));
+ log.warnings += @as(usize, @intFromBool(err.kind == .warn));
},
.pending, .consumed => unreachable,
}
@@ -1819,7 +1818,7 @@ pub const BundleV2 = struct {
import_record.source_index = Index.invalid;
}
- estimated_resolve_queue_count += @as(usize, @boolToInt(!(import_record.is_internal or import_record.is_unused or import_record.source_index.isValid())));
+ estimated_resolve_queue_count += @as(usize, @intFromBool(!(import_record.is_internal or import_record.is_unused or import_record.source_index.isValid())));
}
var resolve_queue = ResolveQueue.init(this.graph.allocator);
resolve_queue.ensureTotalCapacity(estimated_resolve_queue_count) catch @panic("OOM");
@@ -2464,7 +2463,7 @@ pub const ParseTask = struct {
defer trace.end();
if (bundler.options.framework) |framework| {
if (framework.override_modules_hashes.len > 0) {
- const package_relative_path_hash = wyhash(0, file_path.pretty);
+ const package_relative_path_hash = bun.hash(file_path.pretty);
if (std.mem.indexOfScalar(
u64,
framework.override_modules_hashes,
@@ -3264,7 +3263,7 @@ const LinkerGraph = struct {
var entry_point_kinds = files.items(.entry_point_kind);
{
var kinds = std.mem.sliceAsBytes(entry_point_kinds);
- @memset(kinds.ptr, 0, kinds.len);
+ @memset(kinds, 0);
}
// Setup entry points
@@ -3276,7 +3275,7 @@ const LinkerGraph = struct {
var path_strings: []bun.PathString = this.entry_points.items(.output_path);
{
var output_was_auto_generated = std.mem.sliceAsBytes(this.entry_points.items(.output_path_was_auto_generated));
- @memset(output_was_auto_generated.ptr, 0, output_was_auto_generated.len);
+ @memset(output_was_auto_generated, 0);
}
for (entry_points, path_strings, source_indices) |i, *path_string, *source_index| {
@@ -3397,7 +3396,7 @@ const LinkerGraph = struct {
var stable_source_indices = try this.allocator.alloc(Index, sources.len + 1);
// set it to max value so that if we access an invalid one, it crashes
- @memset(std.mem.sliceAsBytes(stable_source_indices).ptr, 255, std.mem.sliceAsBytes(stable_source_indices).len);
+ @memset(std.mem.sliceAsBytes(stable_source_indices), 255);
for (this.reachable_files, 0..) |source_index, i| {
stable_source_indices[source_index.get()] = Index.source(i);
@@ -3405,8 +3404,7 @@ const LinkerGraph = struct {
const file = LinkerGraph.File{};
// TODO: verify this outputs efficient code
- std.mem.set(
- @TypeOf(file.distance_from_entry_point),
+ @memset(
files.items(.distance_from_entry_point),
file.distance_from_entry_point,
);
@@ -4449,13 +4447,13 @@ const LinkerContext = struct {
var wrap_cjs_count: usize = 0;
var wrap_esm_count: usize = 0;
for (exports_kind) |kind| {
- cjs_count += @boolToInt(kind == .cjs);
- esm_count += @boolToInt(kind == .esm);
+ cjs_count += @intFromBool(kind == .cjs);
+ esm_count += @intFromBool(kind == .esm);
}
for (flags) |flag| {
- wrap_cjs_count += @boolToInt(flag.wrap == .cjs);
- wrap_esm_count += @boolToInt(flag.wrap == .esm);
+ wrap_cjs_count += @intFromBool(flag.wrap == .cjs);
+ wrap_esm_count += @intFromBool(flag.wrap == .esm);
}
debug("Step 1: {d} CommonJS modules (+ {d} wrapped), {d} ES modules (+ {d} wrapped)", .{
@@ -4844,7 +4842,7 @@ const LinkerContext = struct {
const add_wrapper = wrap != .none;
var dependencies = std.ArrayList(js_ast.Dependency).initCapacity(
this.allocator,
- @as(usize, @boolToInt(force_include_exports)) + @as(usize, @boolToInt(add_wrapper)),
+ @as(usize, @intFromBool(force_include_exports)) + @as(usize, @intFromBool(add_wrapper)),
) catch unreachable;
var resolved_exports_list: *ResolvedExports = &this.graph.meta.items(.resolved_exports)[id];
for (aliases) |alias| {
@@ -4875,7 +4873,7 @@ const LinkerContext = struct {
}
}
- dependencies.ensureUnusedCapacity(@as(usize, @boolToInt(force_include_exports)) + @as(usize, @boolToInt(add_wrapper))) catch unreachable;
+ dependencies.ensureUnusedCapacity(@as(usize, @intFromBool(force_include_exports)) + @as(usize, @intFromBool(add_wrapper))) catch unreachable;
// Ensure "exports" is included if the current output format needs it
if (force_include_exports) {
@@ -5171,9 +5169,9 @@ const LinkerContext = struct {
// 2 statements for every export
export_aliases.len * 2 +
// + 1 if there are non-zero exports
- @as(usize, @boolToInt(export_aliases.len > 0)) +
+ @as(usize, @intFromBool(export_aliases.len > 0)) +
// + 1 if we need to inject the exports variable
- @as(usize, @boolToInt(needs_exports_variable));
+ @as(usize, @intFromBool(needs_exports_variable));
var stmts = js_ast.Stmt.Batcher.init(allocator_, stmts_count) catch unreachable;
defer stmts.done();
@@ -5275,7 +5273,7 @@ const LinkerContext = struct {
var declared_symbols = js_ast.DeclaredSymbol.List{};
var exports_ref = c.graph.ast.items(.exports_ref)[id];
- var all_export_stmts: []js_ast.Stmt = stmts.head[0 .. @as(usize, @boolToInt(needs_exports_variable)) + @as(usize, @boolToInt(properties.items.len > 0))];
+ var all_export_stmts: []js_ast.Stmt = stmts.head[0 .. @as(usize, @intFromBool(needs_exports_variable)) + @as(usize, @intFromBool(properties.items.len > 0))];
stmts.head = stmts.head[all_export_stmts.len..];
var remaining_stmts = all_export_stmts;
defer std.debug.assert(remaining_stmts.len == 0); // all must be used
@@ -5862,7 +5860,7 @@ const LinkerContext = struct {
// of hash calculation.
if (chunk_meta.dynamic_imports.count() > 0) {
var dynamic_chunk_indices = chunk_meta.dynamic_imports.keys();
- std.sort.sort(Index.Int, dynamic_chunk_indices, {}, std.sort.asc(Index.Int));
+ std.sort.block(Index.Int, dynamic_chunk_indices, {}, std.sort.asc(Index.Int));
var imports = chunk.cross_chunk_imports.listManaged(c.allocator);
defer chunk.cross_chunk_imports.update(imports);
@@ -6121,7 +6119,7 @@ const LinkerContext = struct {
}
}
- std.sort.sort(StableRef, list.items, {}, StableRef.isLessThan);
+ std.sort.block(StableRef, list.items, {}, StableRef.isLessThan);
break :brk list;
};
defer sorted_imports_from_other_chunks.deinit();
@@ -6193,7 +6191,7 @@ const LinkerContext = struct {
}
}
- std.sort.sort(renamer.StableSymbolCount, top_level_symbols.items, {}, StableSymbolCount.lessThan);
+ std.sort.block(renamer.StableSymbolCount, top_level_symbols.items, {}, StableSymbolCount.lessThan);
capacity += top_level_symbols.items.len;
top_level_symbols_all.appendSlice(top_level_symbols.items) catch unreachable;
}
@@ -7703,7 +7701,7 @@ const LinkerContext = struct {
// Prefix this module with "__reExport(exports, ns, module.exports)"
const export_star_ref = c.runtimeFunction("__reExport");
- var args = try allocator.alloc(Expr, 2 + @as(usize, @boolToInt(module_exports_for_export != null)));
+ var args = try allocator.alloc(Expr, 2 + @as(usize, @intFromBool(module_exports_for_export != null)));
args[0..2].* = .{
Expr.init(
E.Identifier,
@@ -7801,7 +7799,7 @@ const LinkerContext = struct {
// Prefix this module with "__reExport(exports, require(path), module.exports)"
const export_star_ref = c.runtimeFunction("__reExport");
- var args = try allocator.alloc(Expr, 2 + @as(usize, @boolToInt(module_exports_for_export != null)));
+ var args = try allocator.alloc(Expr, 2 + @as(usize, @intFromBool(module_exports_for_export != null)));
args[0..2].* = .{
Expr.init(
E.Identifier,
@@ -8786,8 +8784,8 @@ const LinkerContext = struct {
return strings.order(a, b) == .lt;
}
};
- std.sort.sort(u32, sorted_client_component_ids.items, Sorter{ .sources = all_sources }, Sorter.isLessThan);
- std.sort.sort(u32, sorted_server_component_ids.items, Sorter{ .sources = all_sources }, Sorter.isLessThan);
+ std.sort.block(u32, sorted_client_component_ids.items, Sorter{ .sources = all_sources }, Sorter.isLessThan);
+ std.sort.block(u32, sorted_server_component_ids.items, Sorter{ .sources = all_sources }, Sorter.isLessThan);
inline for (.{
sorted_client_component_ids.items,
@@ -8892,7 +8890,7 @@ const LinkerContext = struct {
bun.default_allocator,
(if (c.options.source_maps == .external) chunks.len * 2 else chunks.len) + @as(
usize,
- @boolToInt(react_client_components_manifest.len > 0) + c.parse_graph.additional_output_files.items.len,
+ @intFromBool(react_client_components_manifest.len > 0) + c.parse_graph.additional_output_files.items.len,
),
) catch unreachable;
@@ -9412,7 +9410,7 @@ const LinkerContext = struct {
.ref = export_ref,
};
}
- std.sort.sort(StableRef, result.items, {}, StableRef.isLessThan);
+ std.sort.block(StableRef, result.items, {}, StableRef.isLessThan);
}
pub fn markFileReachableForCodeSplitting(
@@ -10701,7 +10699,7 @@ pub const Chunk = struct {
/// equidistant to an entry point, then break the tie by sorting on the
/// stable source index derived from the DFS over all entry points.
pub fn sort(a: []Order) void {
- std.sort.sort(Order, a, Order{}, lessThan);
+ std.sort.block(Order, a, Order{}, lessThan);
}
};
@@ -10806,7 +10804,7 @@ pub const Chunk = struct {
shift.after.add(data_offset);
if (data.len > 0)
- @memcpy(remain.ptr, data.ptr, data.len);
+ @memcpy(remain[0..data.len], data);
remain = remain[data.len..];
@@ -10838,13 +10836,13 @@ pub const Chunk = struct {
);
if (cheap_normalizer[0].len > 0) {
- @memcpy(remain.ptr, cheap_normalizer[0].ptr, cheap_normalizer[0].len);
+ @memcpy(remain[0..cheap_normalizer[0].len], cheap_normalizer[0]);
remain = remain[cheap_normalizer[0].len..];
shift.after.advance(cheap_normalizer[0]);
}
if (cheap_normalizer[1].len > 0) {
- @memcpy(remain.ptr, cheap_normalizer[1].ptr, cheap_normalizer[1].len);
+ @memcpy(remain[0..cheap_normalizer[1].len], cheap_normalizer[1]);
remain = remain[cheap_normalizer[1].len..];
shift.after.advance(cheap_normalizer[1]);
}
@@ -10970,7 +10968,7 @@ pub const Chunk = struct {
const data = piece.data();
if (data.len > 0)
- @memcpy(remain.ptr, data.ptr, data.len);
+ @memcpy(remain[0..data.len], data);
remain = remain[data.len..];
@@ -10998,12 +10996,12 @@ pub const Chunk = struct {
);
if (cheap_normalizer[0].len > 0) {
- @memcpy(remain.ptr, cheap_normalizer[0].ptr, cheap_normalizer[0].len);
+ @memcpy(remain[0..cheap_normalizer[0].len], cheap_normalizer[0]);
remain = remain[cheap_normalizer[0].len..];
}
if (cheap_normalizer[1].len > 0) {
- @memcpy(remain.ptr, cheap_normalizer[1].ptr, cheap_normalizer[1].len);
+ @memcpy(remain[0..cheap_normalizer[1].len], cheap_normalizer[1]);
remain = remain[cheap_normalizer[1].len..];
}
},
@@ -11144,7 +11142,7 @@ pub const CrossChunkImport = struct {
item.export_alias = exports_to_other_chunks.get(item.ref).?;
std.debug.assert(item.export_alias.len > 0);
}
- std.sort.sort(CrossChunkImport.Item, import_items.slice(), {}, CrossChunkImport.Item.lessThan);
+ std.sort.block(CrossChunkImport.Item, import_items.slice(), {}, CrossChunkImport.Item.lessThan);
result.append(CrossChunkImport{
.chunk_index = chunk_index,
@@ -11152,7 +11150,7 @@ pub const CrossChunkImport = struct {
}) catch unreachable;
}
- std.sort.sort(CrossChunkImport, result.items, {}, CrossChunkImport.lessThan);
+ std.sort.block(CrossChunkImport, result.items, {}, CrossChunkImport.lessThan);
}
};
diff --git a/src/bundler/entry_points.zig b/src/bundler/entry_points.zig
index 34afcb491..abc7eb602 100644
--- a/src/bundler/entry_points.zig
+++ b/src/bundler/entry_points.zig
@@ -256,7 +256,7 @@ pub const MacroEntryPoint = struct {
source: logger.Source = undefined,
pub fn generateID(entry_path: string, function_name: string, buf: []u8, len: *u32) i32 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(js_ast.Macro.namespaceWithColon);
hasher.update(entry_path);
hasher.update(function_name);
@@ -270,7 +270,7 @@ pub const MacroEntryPoint = struct {
}
pub fn generateIDFromSpecifier(specifier: string) i32 {
- return @bitCast(i32, @truncate(u32, std.hash.Wyhash.hash(0, specifier)));
+ return @bitCast(i32, @truncate(u32, bun.hash(specifier)));
}
pub fn generate(
diff --git a/src/c.zig b/src/c.zig
index d43f1b887..d4d243499 100644
--- a/src/c.zig
+++ b/src/c.zig
@@ -72,23 +72,23 @@ pub fn lstat_absolute(path: [:0]const u8) !Stat {
.mode = st.mode,
.kind = switch (builtin.os.tag) {
.wasi => switch (st.filetype) {
- os.FILETYPE_BLOCK_DEVICE => Kind.BlockDevice,
- os.FILETYPE_CHARACTER_DEVICE => Kind.CharacterDevice,
- os.FILETYPE_DIRECTORY => Kind.Directory,
- os.FILETYPE_SYMBOLIC_LINK => Kind.SymLink,
- os.FILETYPE_REGULAR_FILE => Kind.File,
- os.FILETYPE_SOCKET_STREAM, os.FILETYPE_SOCKET_DGRAM => Kind.UnixDomainSocket,
- else => Kind.Unknown,
+ os.FILETYPE_BLOCK_DEVICE => Kind.block_device,
+ os.FILETYPE_CHARACTER_DEVICE => Kind.character_device,
+ os.FILETYPE_DIRECTORY => Kind.directory,
+ os.FILETYPE_SYMBOLIC_LINK => Kind.sym_link,
+ os.FILETYPE_REGULAR_FILE => Kind.file,
+ os.FILETYPE_SOCKET_STREAM, os.FILETYPE_SOCKET_DGRAM => Kind.unix_domain_socket,
+ else => Kind.unknown,
},
else => switch (st.mode & os.S.IFMT) {
- os.S.IFBLK => Kind.BlockDevice,
- os.S.IFCHR => Kind.CharacterDevice,
- os.S.IFDIR => Kind.Directory,
- os.S.IFIFO => Kind.NamedPipe,
- os.S.IFLNK => Kind.SymLink,
- os.S.IFREG => Kind.File,
- os.S.IFSOCK => Kind.UnixDomainSocket,
- else => Kind.Unknown,
+ os.S.IFBLK => Kind.block_device,
+ os.S.IFCHR => Kind.character_device,
+ os.S.IFDIR => Kind.directory,
+ os.S.IFIFO => Kind.named_pipe,
+ os.S.IFLNK => Kind.sym_link,
+ os.S.IFREG => Kind.file,
+ os.S.IFSOCK => Kind.unix_domain_socket,
+ else => Kind.unknown,
},
},
.atime = @as(i128, atime.tv_sec) * std.time.ns_per_s + atime.tv_nsec,
@@ -173,14 +173,14 @@ pub fn moveFileZSlowWithHandle(in_handle: std.os.fd_t, to_dir: std.os.fd_t, dest
pub fn kindFromMode(mode: os.mode_t) std.fs.File.Kind {
return switch (mode & os.S.IFMT) {
- os.S.IFBLK => std.fs.File.Kind.BlockDevice,
- os.S.IFCHR => std.fs.File.Kind.CharacterDevice,
- os.S.IFDIR => std.fs.File.Kind.Directory,
- os.S.IFIFO => std.fs.File.Kind.NamedPipe,
- os.S.IFLNK => std.fs.File.Kind.SymLink,
- os.S.IFREG => std.fs.File.Kind.File,
- os.S.IFSOCK => std.fs.File.Kind.UnixDomainSocket,
- else => .Unknown,
+ os.S.IFBLK => std.fs.File.Kind.block_device,
+ os.S.IFCHR => std.fs.File.Kind.character_device,
+ os.S.IFDIR => std.fs.File.Kind.directory,
+ os.S.IFIFO => std.fs.File.Kind.named_pipe,
+ os.S.IFLNK => std.fs.File.Kind.sym_link,
+ os.S.IFREG => std.fs.File.Kind.file,
+ os.S.IFSOCK => std.fs.File.Kind.unix_domain_socket,
+ else => .unknown,
};
}
@@ -431,9 +431,9 @@ pub fn dlsymWithHandle(comptime Type: type, comptime name: [:0]const u8, comptim
pub fn dlsym(comptime Type: type, comptime name: [:0]const u8) ?Type {
const handle_getter = struct {
const RTLD_DEFAULT = if (bun.Environment.isMac)
- @intToPtr(?*anyopaque, @bitCast(usize, @as(isize, -2)))
+ @ptrFromInt(?*anyopaque, @bitCast(usize, @as(isize, -2)))
else
- @intToPtr(?*anyopaque, @as(usize, 0));
+ @ptrFromInt(?*anyopaque, @as(usize, 0));
pub fn getter() ?*anyopaque {
return RTLD_DEFAULT;
diff --git a/src/cli.zig b/src/cli.zig
index 0d4c32cdf..3d0fb5b37 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -305,7 +305,7 @@ pub const Arguments = struct {
defer ctx.debug.loaded_bunfig = true;
var config_path: [:0]u8 = undefined;
if (config_path_[0] == '/') {
- @memcpy(&config_buf, config_path_.ptr, config_path_.len);
+ @memcpy(config_buf[0..config_path.len], config_path);
config_buf[config_path_.len] = 0;
config_path = config_buf[0..config_path_.len :0];
} else {
@@ -1497,11 +1497,11 @@ pub const Command = struct {
const file_pathZ = brk2: {
if (!strings.hasPrefix(file_path, "./")) {
script_name_buf[0..2].* = "./".*;
- @memcpy(script_name_buf[2..], file_path.ptr, file_path.len);
+ @memcpy(script_name_buf[2..][0..file_path.len], file_path);
script_name_buf[file_path.len + 2] = 0;
break :brk2 script_name_buf[0 .. file_path.len + 2 :0];
} else {
- @memcpy(&script_name_buf, file_path.ptr, file_path.len);
+ @memcpy(script_name_buf[0..file_path.len], file_path);
script_name_buf[file_path.len] = 0;
break :brk2 script_name_buf[0..file_path.len :0];
}
diff --git a/src/cli/add_completions.zig b/src/cli/add_completions.zig
index 95201659d..2e7d6b4ea 100644
--- a/src/cli/add_completions.zig
+++ b/src/cli/add_completions.zig
@@ -66,7 +66,7 @@ pub const index: Index = if (Environment.isDebug) Index.initFill(&.{"OOMWorkArou
break;
}
}
- array.set(@intToEnum(FirstLetter, i), &record);
+ array.set(@enumFromInt(FirstLetter, i), &record);
@setEvalBranchQuota(999999);
i = next_i;
diff --git a/src/cli/build_command.zig b/src/cli/build_command.zig
index 14414c7de..44e512996 100644
--- a/src/cli/build_command.zig
+++ b/src/cli/build_command.zig
@@ -320,8 +320,8 @@ pub const BuildCommand = struct {
var from_path = resolve_path.longestCommonPath(all_paths);
for (output_files) |f| {
- max_path_len = std.math.max(
- std.math.max(from_path.len, f.dest_path.len) + 2 - from_path.len,
+ max_path_len = @max(
+ @max(from_path.len, f.dest_path.len) + 2 - from_path.len,
max_path_len,
);
}
@@ -356,7 +356,7 @@ pub const BuildCommand = struct {
Output.pretty("{s}", .{padding_buf[0..@intCast(usize, compiled_elapsed_digit_count)]});
- Output.printElapsedStdoutTrim(@intToFloat(f64, compiled_elapsed));
+ Output.printElapsedStdoutTrim(@floatFromInt(f64, compiled_elapsed));
Output.prettyln(" <green>compile<r> <b><blue>{s}<r>", .{
outfile,
@@ -446,11 +446,11 @@ pub const BuildCommand = struct {
// Print summary
_ = try writer.write("\n");
- const padding_count = 2 + (std.math.max(rel_path.len, max_path_len) - rel_path.len);
+ const padding_count = 2 + (@max(rel_path.len, max_path_len) - rel_path.len);
try writer.writeByteNTimes(' ', 2);
try writer.writeAll(rel_path);
try writer.writeByteNTimes(' ', padding_count);
- const size = @intToFloat(f64, f.size) / 1000.0;
+ const size = @floatFromInt(f64, f.size) / 1000.0;
try std.fmt.formatFloatDecimal(size, .{ .precision = 2 }, writer);
try writer.writeAll(" KB\n");
}
@@ -460,7 +460,7 @@ pub const BuildCommand = struct {
if (write_summary and log.errors == 0) {
Output.prettyln("\n", .{});
Output.printElapsedStdoutTrim(
- @intToFloat(f64, (@divTrunc(@truncate(i64, std.time.nanoTimestamp() - bun.CLI.start_time), @as(i64, std.time.ns_per_ms)))),
+ @floatFromInt(f64, (@divTrunc(@truncate(i64, std.time.nanoTimestamp() - bun.CLI.start_time), @as(i64, std.time.ns_per_ms)))),
);
if (this_bundler.options.transform_only) {
Output.prettyln(" <green>transpile<r>", .{});
@@ -505,7 +505,7 @@ fn printSummary(bundled_end: i128, minify_duration: u64, minified: bool, input_c
};
if (minified) {
Output.pretty("{s}", .{padding_buf[0..@intCast(usize, minified_digit_count)]});
- Output.printElapsedStdoutTrim(@intToFloat(f64, minify_duration));
+ Output.printElapsedStdoutTrim(@floatFromInt(f64, minify_duration));
const output_size = brk: {
var total_size: u64 = 0;
for (output_files) |f| {
@@ -547,7 +547,7 @@ fn printSummary(bundled_end: i128, minify_duration: u64, minified: bool, input_c
};
Output.pretty("{s}", .{padding_buf[0..@intCast(usize, bundle_elapsed_digit_count)]});
- Output.printElapsedStdoutTrim(@intToFloat(f64, bundle_elapsed));
+ Output.printElapsedStdoutTrim(@floatFromInt(f64, bundle_elapsed));
Output.prettyln(
" <green>bundle<r> {d} modules",
.{
diff --git a/src/cli/bunx_command.zig b/src/cli/bunx_command.zig
index 7fb028b68..365f2c9ed 100644
--- a/src/cli/bunx_command.zig
+++ b/src/cli/bunx_command.zig
@@ -66,7 +66,7 @@ pub const BunxCommand = struct {
.result => |result| result,
} orelse break;
- if (current.kind == .File) {
+ if (current.kind == .file) {
if (current.name.len == 0) continue;
return try bundler.allocator.dupe(u8, current.name.slice());
}
@@ -81,7 +81,7 @@ pub const BunxCommand = struct {
fn getBinNameFromProjectDirectory(bundler: *bun.Bundler, dir_fd: std.os.fd_t, package_name: []const u8) ![]const u8 {
var subpath: [bun.MAX_PATH_BYTES]u8 = undefined;
subpath[0.."node_modules/".len].* = "node_modules/".*;
- @memcpy(subpath["node_modules/".len..], package_name.ptr, package_name.len);
+ @memcpy(subpath["node_modules/".len..][0..package_name.len], package_name);
subpath["node_modules/".len + package_name.len] = std.fs.path.sep;
subpath["node_modules/".len + package_name.len + 1 ..][0.."package.json".len].* = "package.json".*;
subpath["node_modules/".len + package_name.len + 1 + "package.json".len] = 0;
diff --git a/src/cli/create_command.zig b/src/cli/create_command.zig
index fcbee9dbb..d536c4750 100644
--- a/src/cli/create_command.zig
+++ b/src/cli/create_command.zig
@@ -104,7 +104,7 @@ fn execTask(allocator: std.mem.Allocator, task_: string, cwd: string, _: string,
count += 1;
}
- const npm_args = 2 * @intCast(usize, @boolToInt(npm_client != null));
+ const npm_args = 2 * @intCast(usize, @intFromBool(npm_client != null));
const total = count + npm_args;
var argv = allocator.alloc(string, total) catch return;
var proc: std.ChildProcess = undefined;
@@ -491,7 +491,7 @@ pub const CreateCommand = struct {
[1]Archive.Plucker{undefined};
var archive_context = Archive.Context{
- .pluckers = pluckers[0..@intCast(usize, @boolToInt(!create_options.skip_package_json))],
+ .pluckers = pluckers[0..@intCast(usize, @intFromBool(!create_options.skip_package_json))],
.all_files = undefined,
.overwrite_list = bun.StringArrayHashMap(void).init(ctx.allocator),
};
@@ -523,7 +523,7 @@ pub const CreateCommand = struct {
);
for (archive_context.overwrite_list.keys()) |path| {
if (strings.endsWith(path, std.fs.path.sep_str)) {
- Output.prettyError("<r> <blue>{s}<r>", .{path[0 .. std.math.max(path.len, 1) - 1]});
+ Output.prettyError("<r> <blue>{s}<r>", .{path[0 .. @max(path.len, 1) - 1]});
Output.prettyErrorln(std.fs.path.sep_str, .{});
} else {
Output.prettyErrorln("<r> {s}", .{path});
@@ -594,7 +594,7 @@ pub const CreateCommand = struct {
progress_: *std.Progress,
) !void {
while (try walker.next()) |entry| {
- if (entry.kind != .File) continue;
+ if (entry.kind != .file) continue;
var outfile = destination_dir_.createFile(entry.path, .{}) catch brk: {
if (std.fs.path.dirname(entry.path)) |entry_dirname| {
@@ -643,7 +643,7 @@ pub const CreateCommand = struct {
break :read_package_json;
};
- if (stat.kind != .File or stat.size == 0) {
+ if (stat.kind != .file or stat.size == 0) {
package_json_file = null;
node.end();
@@ -736,7 +736,7 @@ pub const CreateCommand = struct {
if (package_json_expr.asProperty("name")) |name_expr| {
if (name_expr.expr.data == .e_string) {
var basename = std.fs.path.basename(destination);
- name_expr.expr.data.e_string.data = @intToPtr([*]u8, @ptrToInt(basename.ptr))[0..basename.len];
+ name_expr.expr.data.e_string.data = @ptrFromInt([*]u8, @intFromPtr(basename.ptr))[0..basename.len];
}
}
@@ -778,7 +778,7 @@ pub const CreateCommand = struct {
const key = list[i].key.?.data.e_string.data;
const do_prune = packages.has(key);
- prune_count += @intCast(u16, @boolToInt(do_prune));
+ prune_count += @intCast(u16, @intFromBool(do_prune));
if (!do_prune) {
list[out_i] = list[i];
@@ -902,14 +902,14 @@ pub const CreateCommand = struct {
var needs_to_inject_dev_dependency = needs.react_refresh or needs.bun_macro_relay;
var needs_to_inject_dependency = needs.bun_framework_next;
- const dependencies_to_inject_count = @intCast(usize, @boolToInt(needs.bun_framework_next));
+ const dependencies_to_inject_count = @intCast(usize, @intFromBool(needs.bun_framework_next));
- const dev_dependencies_to_inject_count = @intCast(usize, @boolToInt(needs.react_refresh)) +
- @intCast(usize, @boolToInt(needs.bun_macro_relay));
+ const dev_dependencies_to_inject_count = @intCast(usize, @intFromBool(needs.react_refresh)) +
+ @intCast(usize, @intFromBool(needs.bun_macro_relay));
- const new_properties_count = @intCast(usize, @boolToInt(needs_to_inject_dev_dependency and dev_dependencies == null)) +
- @intCast(usize, @boolToInt(needs_to_inject_dependency and dependencies == null)) +
- @intCast(usize, @boolToInt(needs_bun_prop));
+ const new_properties_count = @intCast(usize, @intFromBool(needs_to_inject_dev_dependency and dev_dependencies == null)) +
+ @intCast(usize, @intFromBool(needs_to_inject_dependency and dependencies == null)) +
+ @intCast(usize, @intFromBool(needs_bun_prop));
if (new_properties_count != 0) {
try properties_list.ensureUnusedCapacity(new_properties_count);
@@ -1463,7 +1463,7 @@ pub const CreateCommand = struct {
}
if (create_options.verbose) {
- Output.prettyErrorln("Has dependencies? {d}", .{@boolToInt(has_dependencies)});
+ Output.prettyErrorln("Has dependencies? {d}", .{@intFromBool(has_dependencies)});
}
var npm_client_: ?NPMClient = null;
@@ -1692,7 +1692,7 @@ pub const Example = struct {
var app_name_buf: [512]u8 = undefined;
pub fn print(examples: []const Example, default_app_name: ?string) void {
for (examples) |example| {
- var app_name = default_app_name orelse (std.fmt.bufPrint(&app_name_buf, "./{s}-app", .{example.name[0..std.math.min(example.name.len, 492)]}) catch unreachable);
+ var app_name = default_app_name orelse (std.fmt.bufPrint(&app_name_buf, "./{s}-app", .{example.name[0..@min(example.name.len, 492)]}) catch unreachable);
if (example.description.len > 0) {
Output.pretty(" <r># {s}<r>\n <b>bun create <cyan>{s}<r><b> {s}<r>\n<d> \n\n", .{
@@ -1754,7 +1754,7 @@ pub const Example = struct {
const entry: std.fs.IterableDir.Entry = entry_;
switch (entry.kind) {
- .Directory => {
+ .directory => {
inline for (skip_dirs) |skip_dir| {
if (strings.eqlComptime(entry.name, skip_dir)) {
continue :loop;
diff --git a/src/cli/init_command.zig b/src/cli/init_command.zig
index c7f566836..9b5ad7144 100644
--- a/src/cli/init_command.zig
+++ b/src/cli/init_command.zig
@@ -112,7 +112,7 @@ pub const InitCommand = struct {
if (package_json_file) |pkg| {
const stat = pkg.stat() catch break :read_package_json;
- if (stat.kind != .File or stat.size == 0) {
+ if (stat.kind != .file or stat.size == 0) {
break :read_package_json;
}
package_json_contents = try MutableString.init(alloc, stat.size);
diff --git a/src/cli/list-of-yarn-commands.zig b/src/cli/list-of-yarn-commands.zig
index 250541360..4109ed727 100644
--- a/src/cli/list-of-yarn-commands.zig
+++ b/src/cli/list-of-yarn-commands.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const bun = @import("root").bun;
// yarn v2.3 commands
const yarn_v2 = [_][]const u8{
@@ -82,7 +83,7 @@ pub const all_yarn_commands = brk: {
var array: [yarn_v2.len + yarn_v1.len]u64 = undefined;
var array_i: usize = 0;
for (yarn_v2) |yarn| {
- const hash = std.hash.Wyhash.hash(0, yarn);
+ const hash = bun.hash(yarn);
@setEvalBranchQuota(9999);
if (std.mem.indexOfScalar(u64, array[0..array_i], hash) == null) {
@setEvalBranchQuota(9999);
@@ -94,7 +95,7 @@ pub const all_yarn_commands = brk: {
for (yarn_v1) |yarn| {
@setEvalBranchQuota(9999);
- const hash = std.hash.Wyhash.hash(0, yarn);
+ const hash = bun.hash(yarn);
if (std.mem.indexOfScalar(u64, array[0..array_i], hash) == null) {
@setEvalBranchQuota(9999);
diff --git a/src/cli/package_manager_command.zig b/src/cli/package_manager_command.zig
index 83d3dd023..0d92c4232 100644
--- a/src/cli/package_manager_command.zig
+++ b/src/cli/package_manager_command.zig
@@ -48,7 +48,7 @@ pub const PackageManagerCommand = struct {
pub fn printHash(ctx: Command.Context, lockfile_: []const u8) !void {
@setCold(true);
var lockfile_buffer: [bun.MAX_PATH_BYTES]u8 = undefined;
- @memcpy(&lockfile_buffer, lockfile_.ptr, lockfile_.len);
+ @memcpy(lockfile_buffer[0..lockfile_.len], lockfile_);
lockfile_buffer[lockfile_.len] = 0;
var lockfile = lockfile_buffer[0..lockfile_.len :0];
var pm = try PackageManager.init(ctx, null, PackageManager.Subcommand.pm);
@@ -224,7 +224,7 @@ pub const PackageManagerCommand = struct {
for (sorted_dependencies, 0..) |*dep, i| {
dep.* = @truncate(DependencyID, root_deps.off + i);
}
- std.sort.sort(DependencyID, sorted_dependencies, ByName{
+ std.sort.block(DependencyID, sorted_dependencies, ByName{
.dependencies = dependencies,
.buf = string_bytes,
}, ByName.isLessThan);
@@ -336,7 +336,7 @@ fn printNodeModulesFolderStructure(
const sorted_dependencies = try allocator.alloc(DependencyID, directory.dependencies.len);
defer allocator.free(sorted_dependencies);
bun.copy(DependencyID, sorted_dependencies, directory.dependencies);
- std.sort.sort(DependencyID, sorted_dependencies, ByName{
+ std.sort.block(DependencyID, sorted_dependencies, ByName{
.dependencies = dependencies,
.buf = string_bytes,
}, ByName.isLessThan);
diff --git a/src/cli/run_command.zig b/src/cli/run_command.zig
index 0c9145db1..48bbd36d2 100644
--- a/src/cli/run_command.zig
+++ b/src/cli/run_command.zig
@@ -135,7 +135,7 @@ pub const RunCommand = struct {
}
// implicit yarn commands
- if (std.mem.indexOfScalar(u64, yarn_commands, std.hash.Wyhash.hash(0, yarn_cmd)) == null) {
+ if (std.mem.indexOfScalar(u64, yarn_commands, bun.hash(yarn_cmd)) == null) {
try copy_script.appendSlice(BUN_RUN);
try copy_script.append(' ');
try copy_script.appendSlice(yarn_cmd);
diff --git a/src/cli/upgrade_command.zig b/src/cli/upgrade_command.zig
index 2f06fe674..e9d16999d 100644
--- a/src/cli/upgrade_command.zig
+++ b/src/cli/upgrade_command.zig
@@ -344,7 +344,7 @@ pub const UpgradeCommand = struct {
if (asset.asProperty("size")) |size_| {
if (size_.expr.data == .e_number) {
- version.size = @intCast(u32, @max(@floatToInt(i32, std.math.ceil(size_.expr.data.e_number.value)), 0));
+ version.size = @intCast(u32, @max(@intFromFloat(i32, std.math.ceil(size_.expr.data.e_number.value)), 0));
}
}
return version;
@@ -648,13 +648,13 @@ pub const UpgradeCommand = struct {
if (target_stat.size == dest_stat.size and target_stat.size > 0) {
var input_buf = try ctx.allocator.alloc(u8, target_stat.size);
- const target_hash = std.hash.Wyhash.hash(0, target_dir.readFile(target_filename, input_buf) catch |err| {
+ const target_hash = bun.hash(target_dir.readFile(target_filename, input_buf) catch |err| {
save_dir_.deleteTree(version_name) catch {};
Output.prettyErrorln("<r><red>error:<r> Failed to read target bun {s}", .{@errorName(err)});
Global.exit(1);
});
- const source_hash = std.hash.Wyhash.hash(0, save_dir.readFile(exe, input_buf) catch |err| {
+ const source_hash = bun.hash(save_dir.readFile(exe, input_buf) catch |err| {
save_dir_.deleteTree(version_name) catch {};
Output.prettyErrorln("<r><red>error:<r> Failed to read source bun {s}", .{@errorName(err)});
Global.exit(1);
diff --git a/src/comptime_string_map.zig b/src/comptime_string_map.zig
index e60fcb1cb..87881263b 100644
--- a/src/comptime_string_map.zig
+++ b/src/comptime_string_map.zig
@@ -41,7 +41,7 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co
} else {
@compileError("Not implemented for this key type");
}
- std.sort.sort(KV, &sorted_kvs, {}, lenAsc);
+ std.sort.block(KV, &sorted_kvs, {}, lenAsc);
const min_len = sorted_kvs[0].key.len;
const max_len = sorted_kvs[sorted_kvs.len - 1].key.len;
var len_indexes: [max_len + 1]usize = undefined;
@@ -443,12 +443,12 @@ pub fn compareString(input: []const u8) !void {
if (TestEnum2.map.has(str) != TestEnum2.official.has(str)) {
std.debug.panic("{s} - TestEnum2.map.has(str) ({d}) != TestEnum2.official.has(str) ({d})", .{
str,
- @boolToInt(TestEnum2.map.has(str)),
- @boolToInt(TestEnum2.official.has(str)),
+ @intFromBool(TestEnum2.map.has(str)),
+ @intFromBool(TestEnum2.official.has(str)),
});
}
- std.debug.print("For string: \"{s}\" (has a match? {d})\n", .{ str, @boolToInt(TestEnum2.map.has(str)) });
+ std.debug.print("For string: \"{s}\" (has a match? {d})\n", .{ str, @intFromBool(TestEnum2.map.has(str)) });
var i: usize = 0;
var is_eql = false;
diff --git a/src/copy_file.zig b/src/copy_file.zig
index 29c74c5aa..7c68791b2 100644
--- a/src/copy_file.zig
+++ b/src/copy_file.zig
@@ -24,7 +24,7 @@ const CopyFileError = error{SystemResources} || CopyFileRangeError || os.SendFil
// No metadata is transferred over.
pub fn copyFile(fd_in: os.fd_t, fd_out: os.fd_t) CopyFileError!void {
if (comptime bun.Environment.isMac) {
- const rc = os.system.fcopyfile(fd_in, fd_out, null, os.system.COPYFILE_DATA);
+ const rc = os.system.fcopyfile(fd_in, fd_out, null, os.system.COPYFILE.DATA);
switch (os.errno(rc)) {
.SUCCESS => return,
.INVAL => unreachable,
diff --git a/src/crash_reporter.zig b/src/crash_reporter.zig
index b583db248..882ec0ba6 100644
--- a/src/crash_reporter.zig
+++ b/src/crash_reporter.zig
@@ -17,11 +17,11 @@ noinline fn sigaction_handler(sig: i32, info: *const std.os.siginfo_t, _: ?*cons
setup_sigactions(null) catch unreachable;
const addr = switch (comptime builtin.target.os.tag) {
- .linux => @ptrToInt(info.fields.sigfault.addr),
- .macos, .freebsd => @ptrToInt(info.addr),
- .netbsd => @ptrToInt(info.info.reason.fault.addr),
- .openbsd => @ptrToInt(info.data.fault.addr),
- .solaris => @ptrToInt(info.reason.fault.addr),
+ .linux => @intFromPtr(info.fields.sigfault.addr),
+ .macos, .freebsd => @intFromPtr(info.addr),
+ .netbsd => @intFromPtr(info.info.reason.fault.addr),
+ .openbsd => @intFromPtr(info.data.fault.addr),
+ .solaris => @intFromPtr(info.reason.fault.addr),
else => unreachable,
};
if (on_error) |handle| handle(sig, addr);
diff --git a/src/css_scanner.zig b/src/css_scanner.zig
index 0a733a6c6..6edf8b310 100644
--- a/src/css_scanner.zig
+++ b/src/css_scanner.zig
@@ -139,7 +139,7 @@ pub const Scanner = struct {
pub fn step(scanner: *Scanner) void {
scanner.codepoint = scanner.nextCodepoint();
- scanner.approximate_newline_count += @boolToInt(scanner.codepoint == '\n');
+ scanner.approximate_newline_count += @intFromBool(scanner.codepoint == '\n');
}
pub fn raw(_: *Scanner) string {}
@@ -698,7 +698,7 @@ pub const Scanner = struct {
scanner.step();
}
if (import_behavior == .scan or import_behavior == .keep) {
- chunk.range.len = @intCast(i32, scanner.end) - std.math.max(chunk.range.loc.start, 0);
+ chunk.range.len = @intCast(i32, scanner.end) - @max(chunk.range.loc.start, 0);
chunk.content = .{ .t_import = import };
try writeChunk(writer, chunk);
}
diff --git a/src/darwin_c.zig b/src/darwin_c.zig
index bd6c3c9ef..2d7e98e58 100644
--- a/src/darwin_c.zig
+++ b/src/darwin_c.zig
@@ -294,7 +294,7 @@ pub const SystemErrno = enum(u8) {
}
if (code >= max) return null;
- return @intToEnum(SystemErrno, code);
+ return @enumFromInt(SystemErrno, code);
}
pub fn label(this: SystemErrno) ?[]const u8 {
@@ -543,11 +543,11 @@ pub fn get_system_loadavg() [3]f64 {
};
const loadavg = loadavg_[0];
- const scale = @intToFloat(f64, loadavg.fscale);
+ const scale = @floatFromInt(f64, loadavg.fscale);
return [3]f64{
- @intToFloat(f64, loadavg.ldavg[0]) / scale,
- @intToFloat(f64, loadavg.ldavg[1]) / scale,
- @intToFloat(f64, loadavg.ldavg[2]) / scale,
+ @floatFromInt(f64, loadavg.ldavg[0]) / scale,
+ @floatFromInt(f64, loadavg.ldavg[1]) / scale,
+ @floatFromInt(f64, loadavg.ldavg[2]) / scale,
};
}
@@ -573,7 +573,7 @@ pub extern fn get_process_priority(pid: c_uint) i32;
pub extern fn set_process_priority(pid: c_uint, priority: c_int) i32;
pub fn get_version(buf: []u8) []const u8 {
- @memset(buf.ptr, 0, buf.len);
+ @memset(buf, 0);
var size: usize = buf.len;
@@ -589,7 +589,7 @@ pub fn get_version(buf: []u8) []const u8 {
}
pub fn get_release(buf: []u8) []const u8 {
- @memset(buf.ptr, 0, buf.len);
+ @memset(buf, 0);
var size: usize = buf.len;
diff --git a/src/defines-table.zig b/src/defines-table.zig
index 7c3d4f8d0..e7528a825 100644
--- a/src/defines-table.zig
+++ b/src/defines-table.zig
@@ -164,9 +164,9 @@ const pure_global_identifier_define = defines.IdentifierDefine{
const js_ast = bun.JSAst;
const identifiers = struct {
- const nan_val = js_ast.E.Number{ .value = std.math.nan_f64 };
+ const nan_val = js_ast.E.Number{ .value = std.math.nan(f64) };
- const inf_val = js_ast.E.Number{ .value = std.math.inf_f64 };
+ const inf_val = js_ast.E.Number{ .value = std.math.inf(f64) };
// Step 2. Swap in certain literal values because those can be constant folded
pub const @"undefined" = defines.IdentifierDefine{
diff --git a/src/defines.zig b/src/defines.zig
index 45ebffe05..ca6edf3a4 100644
--- a/src/defines.zig
+++ b/src/defines.zig
@@ -188,8 +188,8 @@ pub const DotDefine = struct {
};
// var nan_val = try allocator.create(js_ast.E.Number);
-const nan_val = js_ast.E.Number{ .value = std.math.nan_f64 };
-const inf_val = js_ast.E.Number{ .value = std.math.inf_f64 };
+const nan_val = js_ast.E.Number{ .value = std.math.nan(f64) };
+const inf_val = js_ast.E.Number{ .value = std.math.inf(f64) };
pub const Define = struct {
identifiers: bun.StringHashMap(IdentifierDefine),
diff --git a/src/deps/boringssl.translated.zig b/src/deps/boringssl.translated.zig
index 32fdb704b..ee4f76260 100644
--- a/src/deps/boringssl.translated.zig
+++ b/src/deps/boringssl.translated.zig
@@ -887,8 +887,8 @@ pub fn sk_OPENSSL_STRING_call_cmp_func(arg_cmp_func: stack_cmp_func, arg_a: [*c]
var cmp_func = arg_cmp_func;
var a = arg_a;
var b = arg_b;
- const a_ptr: OPENSSL_STRING = @intToPtr(OPENSSL_STRING, @ptrToInt(a.*));
- const b_ptr: OPENSSL_STRING = @intToPtr(OPENSSL_STRING, @ptrToInt(b.*));
+ const a_ptr: OPENSSL_STRING = @ptrFromInt(OPENSSL_STRING, @intFromPtr(a.*));
+ const b_ptr: OPENSSL_STRING = @ptrFromInt(OPENSSL_STRING, @intFromPtr(b.*));
return @ptrCast(stack_OPENSSL_STRING_cmp_func, @alignCast(@import("std").meta.alignment(fn ([*c]const OPENSSL_STRING, [*c]const OPENSSL_STRING) callconv(.C) c_int), cmp_func)).?(&a_ptr, &b_ptr);
}
pub fn sk_OPENSSL_STRING_new(arg_comp: stack_OPENSSL_STRING_cmp_func) callconv(.C) ?*struct_stack_st_OPENSSL_STRING {
@@ -5237,7 +5237,7 @@ pub fn sk_SSL_CIPHER_call_free_func(arg_free_func: stack_free_func, arg_ptr: ?*a
pub fn sk_SSL_CIPHER_call_copy_func(arg_copy_func: stack_copy_func, arg_ptr: ?*anyopaque) callconv(.C) ?*anyopaque {
var copy_func = arg_copy_func;
var ptr = arg_ptr;
- return @intToPtr(?*anyopaque, @ptrToInt(@ptrCast(stack_SSL_CIPHER_copy_func, @alignCast(@import("std").meta.alignment(fn (?*const SSL_CIPHER) callconv(.C) ?*const SSL_CIPHER), copy_func)).?(@ptrCast(?*const SSL_CIPHER, ptr))));
+ return @ptrFromInt(?*anyopaque, @intFromPtr(@ptrCast(stack_SSL_CIPHER_copy_func, @alignCast(@import("std").meta.alignment(fn (?*const SSL_CIPHER) callconv(.C) ?*const SSL_CIPHER), copy_func)).?(@ptrCast(?*const SSL_CIPHER, ptr))));
}
pub fn sk_SSL_CIPHER_call_cmp_func(arg_cmp_func: stack_cmp_func, arg_a: [*c]?*const anyopaque, arg_b: [*c]?*const anyopaque) callconv(.C) c_int {
var cmp_func = arg_cmp_func;
@@ -5271,7 +5271,7 @@ pub fn sk_SSL_CIPHER_set(arg_sk: ?*struct_stack_st_SSL_CIPHER, arg_i: usize, arg
var sk = arg_sk;
var i = arg_i;
var p = arg_p;
- return @ptrCast(?*const SSL_CIPHER, sk_set(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), i, @intToPtr(?*anyopaque, @ptrToInt(p))));
+ return @ptrCast(?*const SSL_CIPHER, sk_set(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), i, @ptrFromInt(?*anyopaque, @intFromPtr(p))));
}
pub fn sk_SSL_CIPHER_free(arg_sk: ?*struct_stack_st_SSL_CIPHER) callconv(.C) void {
var sk = arg_sk;
@@ -5286,7 +5286,7 @@ pub fn sk_SSL_CIPHER_insert(arg_sk: ?*struct_stack_st_SSL_CIPHER, arg_p: ?*const
var sk = arg_sk;
var p = arg_p;
var where = arg_where;
- return sk_insert(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @intToPtr(?*anyopaque, @ptrToInt(p)), where);
+ return sk_insert(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @ptrFromInt(?*anyopaque, @intFromPtr(p)), where);
}
pub fn sk_SSL_CIPHER_delete(arg_sk: ?*struct_stack_st_SSL_CIPHER, arg_where: usize) callconv(.C) ?*const SSL_CIPHER {
var sk = arg_sk;
@@ -5311,7 +5311,7 @@ pub fn sk_SSL_CIPHER_shift(arg_sk: ?*struct_stack_st_SSL_CIPHER) callconv(.C) ?*
pub fn sk_SSL_CIPHER_push(arg_sk: ?*struct_stack_st_SSL_CIPHER, arg_p: ?*const SSL_CIPHER) callconv(.C) usize {
var sk = arg_sk;
var p = arg_p;
- return sk_push(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @intToPtr(?*anyopaque, @ptrToInt(p)));
+ return sk_push(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @ptrFromInt(?*anyopaque, @intFromPtr(p)));
}
pub fn sk_SSL_CIPHER_pop(arg_sk: ?*struct_stack_st_SSL_CIPHER) callconv(.C) ?*const SSL_CIPHER {
var sk = arg_sk;
@@ -5545,7 +5545,7 @@ pub fn sk_SRTP_PROTECTION_PROFILE_call_free_func(arg_free_func: stack_free_func,
pub fn sk_SRTP_PROTECTION_PROFILE_call_copy_func(arg_copy_func: stack_copy_func, arg_ptr: ?*anyopaque) callconv(.C) ?*anyopaque {
var copy_func = arg_copy_func;
var ptr = arg_ptr;
- return @intToPtr(?*anyopaque, @ptrToInt(@ptrCast(stack_SRTP_PROTECTION_PROFILE_copy_func, @alignCast(@import("std").meta.alignment(fn ([*c]const SRTP_PROTECTION_PROFILE) callconv(.C) [*c]const SRTP_PROTECTION_PROFILE), copy_func)).?(@ptrCast([*c]const SRTP_PROTECTION_PROFILE, @alignCast(@import("std").meta.alignment(SRTP_PROTECTION_PROFILE), ptr)))));
+ return @ptrFromInt(?*anyopaque, @intFromPtr(@ptrCast(stack_SRTP_PROTECTION_PROFILE_copy_func, @alignCast(@import("std").meta.alignment(fn ([*c]const SRTP_PROTECTION_PROFILE) callconv(.C) [*c]const SRTP_PROTECTION_PROFILE), copy_func)).?(@ptrCast([*c]const SRTP_PROTECTION_PROFILE, @alignCast(@import("std").meta.alignment(SRTP_PROTECTION_PROFILE), ptr)))));
}
pub fn sk_SRTP_PROTECTION_PROFILE_call_cmp_func(arg_cmp_func: stack_cmp_func, arg_a: [*c]?*const anyopaque, arg_b: [*c]?*const anyopaque) callconv(.C) c_int {
var cmp_func = arg_cmp_func;
@@ -5579,7 +5579,7 @@ pub fn sk_SRTP_PROTECTION_PROFILE_set(arg_sk: ?*struct_stack_st_SRTP_PROTECTION_
var sk = arg_sk;
var i = arg_i;
var p = arg_p;
- return @ptrCast([*c]const SRTP_PROTECTION_PROFILE, @alignCast(@import("std").meta.alignment(SRTP_PROTECTION_PROFILE), sk_set(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), i, @intToPtr(?*anyopaque, @ptrToInt(p)))));
+ return @ptrCast([*c]const SRTP_PROTECTION_PROFILE, @alignCast(@import("std").meta.alignment(SRTP_PROTECTION_PROFILE), sk_set(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), i, @ptrFromInt(?*anyopaque, @intFromPtr(p)))));
}
pub fn sk_SRTP_PROTECTION_PROFILE_free(arg_sk: ?*struct_stack_st_SRTP_PROTECTION_PROFILE) callconv(.C) void {
var sk = arg_sk;
@@ -5594,7 +5594,7 @@ pub fn sk_SRTP_PROTECTION_PROFILE_insert(arg_sk: ?*struct_stack_st_SRTP_PROTECTI
var sk = arg_sk;
var p = arg_p;
var where = arg_where;
- return sk_insert(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @intToPtr(?*anyopaque, @ptrToInt(p)), where);
+ return sk_insert(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @ptrFromInt(?*anyopaque, @intFromPtr(p)), where);
}
pub fn sk_SRTP_PROTECTION_PROFILE_delete(arg_sk: ?*struct_stack_st_SRTP_PROTECTION_PROFILE, arg_where: usize) callconv(.C) [*c]const SRTP_PROTECTION_PROFILE {
var sk = arg_sk;
@@ -5619,7 +5619,7 @@ pub fn sk_SRTP_PROTECTION_PROFILE_shift(arg_sk: ?*struct_stack_st_SRTP_PROTECTIO
pub fn sk_SRTP_PROTECTION_PROFILE_push(arg_sk: ?*struct_stack_st_SRTP_PROTECTION_PROFILE, arg_p: [*c]const SRTP_PROTECTION_PROFILE) callconv(.C) usize {
var sk = arg_sk;
var p = arg_p;
- return sk_push(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @intToPtr(?*anyopaque, @ptrToInt(p)));
+ return sk_push(@ptrCast([*c]_STACK, @alignCast(@import("std").meta.alignment(_STACK), sk)), @ptrFromInt(?*anyopaque, @intFromPtr(p)));
}
pub fn sk_SRTP_PROTECTION_PROFILE_pop(arg_sk: ?*struct_stack_st_SRTP_PROTECTION_PROFILE) callconv(.C) [*c]const SRTP_PROTECTION_PROFILE {
var sk = arg_sk;
diff --git a/src/deps/c_ares.zig b/src/deps/c_ares.zig
index 4539358d0..79591899e 100644
--- a/src/deps/c_ares.zig
+++ b/src/deps/c_ares.zig
@@ -488,7 +488,7 @@ pub const Channel = opaque {
break :brk null;
}
const len = @min(host.len, host_buf.len - 1);
- @memcpy(&host_buf, host.ptr, len);
+ @memcpy(host_buf[0..len], host[0..len]);
host_buf[len] = 0;
break :brk host_buf[0..len :0].ptr;
};
@@ -516,7 +516,8 @@ pub const Channel = opaque {
break :brk null;
}
const len = @min(name_buf.len, name_buf.len - 1);
- @memcpy(&name_buf, name.ptr, len);
+ @memcpy(name_buf[0..len], name[0..len]);
+
name_buf[len] = 0;
break :brk name_buf[0..len :0];
};
@@ -1209,8 +1210,8 @@ pub const Error = enum(i32) {
ESERVICE = ARES_ESERVICE,
pub fn initEAI(rc: i32) ?Error {
- return switch (@intToEnum(std.os.system.EAI, rc)) {
- @intToEnum(std.os.system.EAI, 0) => return null,
+ return switch (@enumFromInt(std.os.system.EAI, rc)) {
+ @enumFromInt(std.os.system.EAI, 0) => return null,
.ADDRFAMILY => Error.EBADFAMILY,
.BADFLAGS => Error.EBADFLAGS, // Invalid hints
.FAIL => Error.EBADRESP,
@@ -1283,8 +1284,8 @@ pub const Error = enum(i32) {
pub fn get(rc: i32) ?Error {
return switch (rc) {
0 => null,
- 1...ARES_ESERVICE => @intToEnum(Error, rc),
- -ARES_ESERVICE...-1 => @intToEnum(Error, -rc),
+ 1...ARES_ESERVICE => @enumFromInt(Error, rc),
+ -ARES_ESERVICE...-1 => @enumFromInt(Error, -rc),
else => unreachable,
};
}
diff --git a/src/deps/diffz/DiffMatchPatch.zig b/src/deps/diffz/DiffMatchPatch.zig
index 7e545f364..a5cc02af4 100644
--- a/src/deps/diffz/DiffMatchPatch.zig
+++ b/src/deps/diffz/DiffMatchPatch.zig
@@ -178,7 +178,7 @@ fn diffInternal(
}
fn diffCommonPrefix(before: []const u8, after: []const u8) usize {
- const n = std.math.min(before.len, after.len);
+ const n = @min(before.len, after.len);
var i: usize = 0;
while (i < n) : (i += 1) {
@@ -191,7 +191,7 @@ fn diffCommonPrefix(before: []const u8, after: []const u8) usize {
}
fn diffCommonSuffix(before: []const u8, after: []const u8) usize {
- const n = std.math.min(before.len, after.len);
+ const n = @min(before.len, after.len);
var i: usize = 1;
while (i <= n) : (i += 1) {
@@ -996,8 +996,8 @@ fn diffCleanupSemantic(allocator: std.mem.Allocator, diffs: *DiffList) DiffError
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (last_equality != null and
- (last_equality.?.len <= std.math.max(length_insertions1, length_deletions1)) and
- (last_equality.?.len <= std.math.max(length_insertions2, length_deletions2)))
+ (last_equality.?.len <= @max(length_insertions1, length_deletions1)) and
+ (last_equality.?.len <= @max(length_insertions2, length_deletions2)))
{
// Duplicate record.
try diffs.insert(
@@ -1046,8 +1046,8 @@ fn diffCleanupSemantic(allocator: std.mem.Allocator, diffs: *DiffList) DiffError
var overlap_length1: usize = diffCommonOverlap(deletion, insertion);
var overlap_length2: usize = diffCommonOverlap(insertion, deletion);
if (overlap_length1 >= overlap_length2) {
- if (@intToFloat(f32, overlap_length1) >= @intToFloat(f32, deletion.len) / 2.0 or
- @intToFloat(f32, overlap_length1) >= @intToFloat(f32, insertion.len) / 2.0)
+ if (@floatFromInt(f32, overlap_length1) >= @floatFromInt(f32, deletion.len) / 2.0 or
+ @floatFromInt(f32, overlap_length1) >= @floatFromInt(f32, insertion.len) / 2.0)
{
// Overlap found.
// Insert an equality and trim the surrounding edits.
@@ -1063,8 +1063,8 @@ fn diffCleanupSemantic(allocator: std.mem.Allocator, diffs: *DiffList) DiffError
pointer += 1;
}
} else {
- if (@intToFloat(f32, overlap_length2) >= @intToFloat(f32, deletion.len) / 2.0 or
- @intToFloat(f32, overlap_length2) >= @intToFloat(f32, insertion.len) / 2.0)
+ if (@floatFromInt(f32, overlap_length2) >= @floatFromInt(f32, deletion.len) / 2.0 or
+ @floatFromInt(f32, overlap_length2) >= @floatFromInt(f32, insertion.len) / 2.0)
{
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
diff --git a/src/deps/lol-html.zig b/src/deps/lol-html.zig
index 975aac2b3..1d71e6aa6 100644
--- a/src/deps/lol-html.zig
+++ b/src/deps/lol-html.zig
@@ -727,11 +727,11 @@ pub fn DirectiveHandler(comptime Container: type, comptime UserDataType: type, c
return struct {
pub fn callback(this: *Container, user_data: ?*anyopaque) callconv(.C) Directive {
auto_disable();
- return @intToEnum(
+ return @enumFromInt(
Directive,
@as(
c_uint,
- @boolToInt(
+ @intFromBool(
Callback(
@ptrCast(
*UserDataType,
diff --git a/src/deps/picohttp.zig b/src/deps/picohttp.zig
index d18cb7fa0..722475bb5 100644
--- a/src/deps/picohttp.zig
+++ b/src/deps/picohttp.zig
@@ -15,7 +15,7 @@ pub const Header = struct {
value: []const u8,
pub fn isMultiline(self: Header) bool {
- return @ptrToInt(self.name.ptr) == 0;
+ return @intFromPtr(self.name.ptr) == 0;
}
pub fn format(self: Header, comptime _: []const u8, _: fmt.FormatOptions, writer: anytype) !void {
@@ -101,7 +101,7 @@ pub const Request = struct {
);
// Leave a sentinel value, for JavaScriptCore support.
- if (rc > -1) @intToPtr([*]u8, @ptrToInt(path.ptr))[path.len] = 0;
+ if (rc > -1) @ptrFromInt([*]u8, @intFromPtr(path.ptr))[path.len] = 0;
return switch (rc) {
-1 => error.BadRequest,
diff --git a/src/deps/uws.zig b/src/deps/uws.zig
index 538756b71..8ebe04ac0 100644
--- a/src/deps/uws.zig
+++ b/src/deps/uws.zig
@@ -23,7 +23,7 @@ fn NativeSocketHandleType(comptime ssl: bool) type {
}
pub fn NewSocketHandler(comptime ssl: bool) type {
return struct {
- const ssl_int: i32 = @boolToInt(ssl);
+ const ssl_int: i32 = @intFromBool(ssl);
socket: *Socket,
const ThisSocket = @This();
@@ -49,7 +49,7 @@ pub fn NewSocketHandler(comptime ssl: bool) type {
@compileError("SSL sockets do not have a file descriptor accessible this way");
}
- return @intCast(i32, @ptrToInt(us_socket_get_native_handle(0, this.socket)));
+ return @intCast(i32, @intFromPtr(us_socket_get_native_handle(0, this.socket)));
}
pub fn markNeedsMoreForSendfile(this: ThisSocket) void {
@@ -92,18 +92,18 @@ pub fn NewSocketHandler(comptime ssl: bool) type {
data.ptr,
// truncate to 31 bits since sign bit exists
@intCast(i32, @truncate(u31, data.len)),
- @as(i32, @boolToInt(msg_more)),
+ @as(i32, @intFromBool(msg_more)),
);
}
pub fn shutdown(this: ThisSocket) void {
- debug("us_socket_shutdown({d})", .{@ptrToInt(this.socket)});
+ debug("us_socket_shutdown({d})", .{@intFromPtr(this.socket)});
return us_socket_shutdown(
comptime ssl_int,
this.socket,
);
}
pub fn shutdownRead(this: ThisSocket) void {
- debug("us_socket_shutdown_read({d})", .{@ptrToInt(this.socket)});
+ debug("us_socket_shutdown_read({d})", .{@intFromPtr(this.socket)});
return us_socket_shutdown_read(
comptime ssl_int,
this.socket,
@@ -122,7 +122,7 @@ pub fn NewSocketHandler(comptime ssl: bool) type {
) > 0;
}
pub fn close(this: ThisSocket, code: i32, reason: ?*anyopaque) void {
- debug("us_socket_close({d})", .{@ptrToInt(this.socket)});
+ debug("us_socket_close({d})", .{@intFromPtr(this.socket)});
_ = us_socket_close(
comptime ssl_int,
this.socket,
@@ -421,7 +421,7 @@ pub const Timer = opaque {
pub const SocketContext = opaque {
pub fn getNativeHandle(this: *SocketContext, comptime ssl: bool) *anyopaque {
- return us_socket_context_get_native_handle(comptime @as(i32, @boolToInt(ssl)), this).?;
+ return us_socket_context_get_native_handle(comptime @as(i32, @intFromBool(ssl)), this).?;
}
fn _deinit_ssl(this: *SocketContext) void {
@@ -446,8 +446,8 @@ pub const SocketContext = opaque {
}
pub fn close(this: *SocketContext, ssl: bool) void {
- debug("us_socket_context_close({d})", .{@ptrToInt(this)});
- us_socket_context_close(@as(i32, @boolToInt(ssl)), this);
+ debug("us_socket_context_close({d})", .{@intFromPtr(this)});
+ us_socket_context_close(@as(i32, @intFromBool(ssl)), this);
}
pub fn ext(this: *SocketContext, ssl: bool, comptime ContextType: type) ?*ContextType {
@@ -457,7 +457,7 @@ pub const SocketContext = opaque {
std.meta.alignment(ContextType);
var ptr = us_socket_context_ext(
- @boolToInt(ssl),
+ @intFromBool(ssl),
this,
) orelse return null;
@@ -700,7 +700,7 @@ pub const Poll = opaque {
fallthrough: bool,
flags: Flags,
) ?*Poll {
- var poll = us_create_poll(loop, @as(i32, @boolToInt(fallthrough)), @sizeOf(Data));
+ var poll = us_create_poll(loop, @as(i32, @intFromBool(fallthrough)), @sizeOf(Data));
if (comptime Data != void) {
poll.data(Data).* = val;
}
@@ -810,7 +810,7 @@ pub const AnyWebSocket = union(enum) {
}
pub fn close(this: AnyWebSocket) void {
- const ssl_flag = @boolToInt(this == .ssl);
+ const ssl_flag = @intFromBool(this == .ssl);
return uws_ws_close(ssl_flag, this.raw());
}
@@ -874,7 +874,7 @@ pub const AnyWebSocket = union(enum) {
}
pub fn publishWithOptions(ssl: bool, app: *anyopaque, topic: []const u8, message: []const u8, opcode: Opcode, compress: bool) bool {
return uws_publish(
- @boolToInt(ssl),
+ @intFromBool(ssl),
@ptrCast(*uws_app_t, app),
topic.ptr,
topic.len,
@@ -1073,10 +1073,10 @@ pub const Request = opaque {
pub const ListenSocket = opaque {
pub fn close(this: *ListenSocket, ssl: bool) void {
- us_listen_socket_close(@boolToInt(ssl), this);
+ us_listen_socket_close(@intFromBool(ssl), this);
}
pub fn getLocalPort(this: *ListenSocket, ssl: bool) i32 {
- return us_socket_local_port(@boolToInt(ssl), @ptrCast(*uws.Socket, this));
+ return us_socket_local_port(@intFromBool(ssl), @ptrCast(*uws.Socket, this));
}
};
extern fn us_listen_socket_close(ssl: i32, ls: *ListenSocket) void;
@@ -1085,7 +1085,7 @@ extern fn us_socket_context_close(ssl: i32, ctx: *anyopaque) void;
pub fn NewApp(comptime ssl: bool) type {
return opaque {
- const ssl_flag = @as(i32, @boolToInt(ssl));
+ const ssl_flag = @as(i32, @intFromBool(ssl));
const ThisApp = @This();
pub fn close(this: *ThisApp) void {
@@ -1428,7 +1428,7 @@ pub fn NewApp(comptime ssl: bool) type {
}
pub fn getNativeHandle(res: *Response) i32 {
- return @intCast(i32, @ptrToInt(uws_res_get_native_handle(ssl_flag, res.downcast())));
+ return @intCast(i32, @intFromPtr(uws_res_get_native_handle(ssl_flag, res.downcast())));
}
pub fn onWritable(
res: *Response,
@@ -1880,23 +1880,23 @@ pub const State = enum(i32) {
_,
pub inline fn isResponsePending(this: State) bool {
- return @enumToInt(this) & @enumToInt(State.HTTP_RESPONSE_PENDING) != 0;
+ return @intFromEnum(this) & @intFromEnum(State.HTTP_RESPONSE_PENDING) != 0;
}
pub inline fn isHttpEndCalled(this: State) bool {
- return @enumToInt(this) & @enumToInt(State.HTTP_END_CALLED) != 0;
+ return @intFromEnum(this) & @intFromEnum(State.HTTP_END_CALLED) != 0;
}
pub inline fn isHttpWriteCalled(this: State) bool {
- return @enumToInt(this) & @enumToInt(State.HTTP_WRITE_CALLED) != 0;
+ return @intFromEnum(this) & @intFromEnum(State.HTTP_WRITE_CALLED) != 0;
}
pub inline fn isHttpStatusCalled(this: State) bool {
- return @enumToInt(this) & @enumToInt(State.HTTP_STATUS_CALLED) != 0;
+ return @intFromEnum(this) & @intFromEnum(State.HTTP_STATUS_CALLED) != 0;
}
pub inline fn isHttpConnectionClose(this: State) bool {
- return @enumToInt(this) & @enumToInt(State.HTTP_CONNECTION_CLOSE) != 0;
+ return @intFromEnum(this) & @intFromEnum(State.HTTP_CONNECTION_CLOSE) != 0;
}
};
diff --git a/src/deps/zig-clap/clap.zig b/src/deps/zig-clap/clap.zig
index 16824e788..68cd2451c 100644
--- a/src/deps/zig-clap/clap.zig
+++ b/src/deps/zig-clap/clap.zig
@@ -111,7 +111,7 @@ fn parseParamRest(line: []const u8) Param(Help) {
const len = mem.indexOfScalar(u8, line, '>') orelse break :blk;
const takes_many = mem.startsWith(u8, line[len + 1 ..], "...");
const takes_one_optional = mem.startsWith(u8, line[len + 1 ..], "?");
- const help_start = len + 1 + @as(usize, 3) * @boolToInt(takes_many) + (@as(usize, 1) * @boolToInt(takes_one_optional));
+ const help_start = len + 1 + @as(usize, 3) * @intFromBool(takes_many) + (@as(usize, 1) * @intFromBool(takes_one_optional));
return .{
.takes_value = if (takes_many) Values.many else if (takes_one_optional) Values.one_optional else Values.one,
.id = .{
diff --git a/src/deps/zig-datetime/src/datetime.zig b/src/deps/zig-datetime/src/datetime.zig
index 29a936630..1014863b8 100644
--- a/src/deps/zig-datetime/src/datetime.zig
+++ b/src/deps/zig-datetime/src/datetime.zig
@@ -47,7 +47,7 @@ pub const Month = enum(u4) {
if (month.len == 3) {
inline for (std.meta.fields(Month)) |f| {
if (ascii.eqlIgnoreCase(f.name[0..3], month)) {
- return @intToEnum(Month, f.value);
+ return @enumFromInt(Month, f.value);
}
}
}
@@ -57,7 +57,7 @@ pub const Month = enum(u4) {
pub fn parseName(month: []const u8) !Month {
inline for (std.meta.fields(Month)) |f| {
if (ascii.eqlIgnoreCase(f.name, month)) {
- return @intToEnum(Month, f.value);
+ return @enumFromInt(Month, f.value);
}
}
return error.InvalidFormat;
@@ -313,7 +313,7 @@ pub const Date = struct {
// Create a date from the number of seconds since 1 Jan 1970
pub fn fromSeconds(seconds: f64) Date {
const r = math.modf(seconds);
- const timestamp = @floatToInt(i64, r.ipart); // Seconds
+ const timestamp = @intFromFloat(i64, r.ipart); // Seconds
const days = @divFloor(timestamp, time.s_per_day) + @as(i64, EPOCH);
assert(days >= 0 and days <= MAX_ORDINAL);
return Date.fromOrdinal(@intCast(u32, days));
@@ -322,7 +322,7 @@ pub const Date = struct {
// Return the number of seconds since 1 Jan 1970
pub fn toSeconds(self: Date) f64 {
const days = @intCast(i64, self.toOrdinal()) - @as(i64, EPOCH);
- return @intToFloat(f64, days * time.s_per_day);
+ return @floatFromInt(f64, days * time.s_per_day);
}
// Create a date from a UTC timestamp in milliseconds relative to Jan 1st 1970
@@ -445,7 +445,7 @@ pub const Date = struct {
// Return day of week starting with Monday = 1 and Sunday = 7
pub fn dayOfWeek(self: Date) Weekday {
const dow = @intCast(u3, self.toOrdinal() % 7);
- return @intToEnum(Weekday, if (dow == 0) 7 else dow);
+ return @enumFromInt(Weekday, if (dow == 0) 7 else dow);
}
// Return the ISO calendar based week of year. With 1 being the first week.
@@ -455,7 +455,7 @@ pub const Date = struct {
// Return day of week starting with Monday = 0 and Sunday = 6
pub fn weekday(self: Date) u4 {
- return @enumToInt(self.dayOfWeek()) - 1;
+ return @intFromEnum(self.dayOfWeek()) - 1;
}
// Return whether the date is a weekend (Saturday or Sunday)
@@ -471,7 +471,7 @@ pub const Date = struct {
// Return the name of the day of the month, eg "January"
pub fn monthName(self: Date) []const u8 {
assert(self.month >= 1 and self.month <= 12);
- return @tagName(@intToEnum(Month, self.month));
+ return @tagName(@enumFromInt(Month, self.month));
}
// ------------------------------------------------------------------------
@@ -596,7 +596,7 @@ test "date-from-seconds" {
//
// Max check
// var max_date = try Date.create(9999, 12, 31);
- // const tmax: f64 = @intToFloat(f64, MAX_ORDINAL-1) * time.s_per_day;
+ // const tmax: f64 = @floatFromInt(f64, MAX_ORDINAL-1) * time.s_per_day;
// date = Date.fromSeconds(tmax);
// try testing.expect(date.eql(max_date));
// try testing.expectEqual(date.toSeconds(), tmax);
@@ -859,7 +859,7 @@ pub const Time = struct {
assert(seconds >= 0);
// Convert to s and us
const r = math.modf(seconds);
- var s = @floatToInt(u32, @mod(r.ipart, time.s_per_day)); // s
+ var s = @intFromFloat(u32, @mod(r.ipart, time.s_per_day)); // s
const h = @divFloor(s, time.s_per_hour);
s -= h * time.s_per_hour;
const m = @divFloor(s, time.s_per_min);
@@ -875,15 +875,15 @@ pub const Time = struct {
s -= 1;
frac += time.ns_per_s;
}
- const ns = @floatToInt(u32, frac);
+ const ns = @intFromFloat(u32, frac);
return Time.create(h, m, s, ns) catch unreachable; // If this fails it's a bug
}
// Convert to a time in seconds relative to the UTC timezones
// including the nanosecond component
pub fn toSeconds(self: Time) f64 {
- const s = @intToFloat(f64, self.totalSeconds());
- const ns = @intToFloat(f64, self.nanosecond) / time.ns_per_s;
+ const s = @floatFromInt(f64, self.totalSeconds());
+ const ns = @floatFromInt(f64, self.nanosecond) / time.ns_per_s;
return s + ns;
}
@@ -1393,7 +1393,7 @@ pub const Datetime = struct {
const value = std.mem.trim(u8, ims, " ");
if (value.len < 29) return error.InvalidFormat;
const day = std.fmt.parseInt(u8, value[5..7], 10) catch return error.InvalidFormat;
- const month = @enumToInt(try Month.parseAbbr(value[8..11]));
+ const month = @intFromEnum(try Month.parseAbbr(value[8..11]));
const year = std.fmt.parseInt(u16, value[12..16], 10) catch return error.InvalidFormat;
const hour = std.fmt.parseInt(u8, value[17..19], 10) catch return error.InvalidFormat;
const minute = std.fmt.parseInt(u8, value[20..22], 10) catch return error.InvalidFormat;
diff --git a/src/env_loader.zig b/src/env_loader.zig
index 8a3838101..14e1196b6 100644
--- a/src/env_loader.zig
+++ b/src/env_loader.zig
@@ -52,7 +52,7 @@ pub const Lexer = struct {
pub inline fn step(this: *Lexer) void {
const ended = !this.iter.next(&this.cursor);
if (ended) this.cursor.c = -1;
- this.current = this.cursor.i + @as(usize, @boolToInt(ended));
+ this.current = this.cursor.i + @as(usize, @intFromBool(ended));
}
pub fn eatNestedValue(
@@ -73,7 +73,7 @@ pub const Lexer = struct {
i += 1;
const start = i;
- const curly_braces_offset = @as(usize, @boolToInt(variable.value[i] == '{'));
+ const curly_braces_offset = @as(usize, @intFromBool(variable.value[i] == '{'));
i += curly_braces_offset;
while (i < variable.value.len) {
@@ -422,7 +422,7 @@ pub const Loader = struct {
pub fn getNodePath(this: *Loader, fs: *Fs.FileSystem, buf: *Fs.PathBuffer) ?[:0]const u8 {
if (this.get("NODE") orelse this.get("npm_node_execpath")) |node| {
- @memcpy(buf, node.ptr, node.len);
+ @memcpy(buf[0..node.len], node);
buf[node.len] = 0;
return buf[0..node.len :0];
}
@@ -556,7 +556,7 @@ pub const Loader = struct {
var string_map_hashes = try allocator.alloc(u64, framework_defaults.keys.len);
defer allocator.free(string_map_hashes);
const invalid_hash = std.math.maxInt(u64) - 1;
- std.mem.set(u64, string_map_hashes, invalid_hash);
+ @memset(string_map_hashes, invalid_hash);
var key_buf: []u8 = "";
// Frameworks determine an allowlist of values
@@ -564,7 +564,7 @@ pub const Loader = struct {
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);
+ string_map_hashes[i] = bun.hash(hashable_segment);
}
}
@@ -616,7 +616,7 @@ pub const Loader = struct {
e_strings[0] = js_ast.E.String{
.data = if (value.len > 0)
- @intToPtr([*]u8, @ptrToInt(value.ptr))[0..value.len]
+ @ptrFromInt([*]u8, @intFromPtr(value.ptr))[0..value.len]
else
&[_]u8{},
};
@@ -632,14 +632,14 @@ pub const Loader = struct {
);
e_strings = e_strings[1..];
} else {
- const hash = std.hash.Wyhash.hash(0, entry.key_ptr.*);
+ const hash = bun.hash(entry.key_ptr.*);
std.debug.assert(hash != invalid_hash);
if (std.mem.indexOfScalar(u64, string_map_hashes, hash)) |key_i| {
e_strings[0] = js_ast.E.String{
.data = if (value.len > 0)
- @intToPtr([*]u8, @ptrToInt(value.ptr))[0..value.len]
+ @ptrFromInt([*]u8, @intFromPtr(value.ptr))[0..value.len]
else
&[_]u8{},
};
@@ -665,7 +665,7 @@ pub const Loader = struct {
e_strings[0] = js_ast.E.String{
.data = if (entry.value_ptr.*.len > 0)
- @intToPtr([*]u8, @ptrToInt(entry.value_ptr.*.ptr))[0..value.len]
+ @ptrFromInt([*]u8, @intFromPtr(entry.value_ptr.*.ptr))[0..value.len]
else
&[_]u8{},
};
@@ -803,17 +803,17 @@ pub const Loader = struct {
pub fn printLoaded(this: *Loader, start: i128) void {
const count =
- @intCast(u8, @boolToInt(this.@".env.development.local" != null)) +
- @intCast(u8, @boolToInt(this.@".env.production.local" != null)) +
- @intCast(u8, @boolToInt(this.@".env.test.local" != null)) +
- @intCast(u8, @boolToInt(this.@".env.local" != null)) +
- @intCast(u8, @boolToInt(this.@".env.development" != null)) +
- @intCast(u8, @boolToInt(this.@".env.production" != null)) +
- @intCast(u8, @boolToInt(this.@".env.test" != null)) +
- @intCast(u8, @boolToInt(this.@".env" != null));
+ @intCast(u8, @intFromBool(this.@".env.development.local" != null)) +
+ @intCast(u8, @intFromBool(this.@".env.production.local" != null)) +
+ @intCast(u8, @intFromBool(this.@".env.test.local" != null)) +
+ @intCast(u8, @intFromBool(this.@".env.local" != null)) +
+ @intCast(u8, @intFromBool(this.@".env.development" != null)) +
+ @intCast(u8, @intFromBool(this.@".env.production" != null)) +
+ @intCast(u8, @intFromBool(this.@".env.test" != null)) +
+ @intCast(u8, @intFromBool(this.@".env" != null));
if (count == 0) return;
- const elapsed = @intToFloat(f64, (std.time.nanoTimestamp() - start)) / std.time.ns_per_ms;
+ const elapsed = @floatFromInt(f64, (std.time.nanoTimestamp() - start)) / std.time.ns_per_ms;
const all = [_]string{
".env.development.local",
diff --git a/src/exact_size_matcher.zig b/src/exact_size_matcher.zig
index 5d47cee98..67d0b8fe8 100644
--- a/src/exact_size_matcher.zig
+++ b/src/exact_size_matcher.zig
@@ -1,4 +1,5 @@
const std = @import("std");
+const bun = @import("root").bun;
pub fn ExactSizeMatcher(comptime max_bytes: usize) type {
switch (max_bytes) {
@@ -19,11 +20,11 @@ pub fn ExactSizeMatcher(comptime max_bytes: usize) type {
1...max_bytes - 1 => {
var tmp: [max_bytes]u8 = undefined;
if (comptime std.meta.trait.isSlice(@TypeOf(str))) {
- @memcpy(&tmp, str.ptr, str.len);
- @memset(tmp[str.len..].ptr, 0, tmp[str.len..].len);
+ @memcpy(tmp[0..str.len], str);
+ @memset(tmp[str.len..], 0);
} else {
- @memcpy(&tmp, str, str.len);
- @memset(tmp[str.len..], 0, tmp[str.len..].len);
+ @memcpy(tmp[0..str.len], str);
+ @memset(tmp[str.len..], 0);
}
return std.mem.readIntNative(T, &tmp);
@@ -47,7 +48,7 @@ pub fn ExactSizeMatcher(comptime max_bytes: usize) type {
for (str, 0..) |char, i| {
tmp[i] = std.ascii.toLower(char);
}
- @memset(tmp[str.len..].ptr, 0, tmp[str.len..].len);
+ @memset(tmp[str.len..], 0);
return std.mem.readIntNative(T, &tmp);
},
max_bytes => {
diff --git a/src/fs.zig b/src/fs.zig
index 2dca8169c..e87d931df 100644
--- a/src/fs.zig
+++ b/src/fs.zig
@@ -157,10 +157,10 @@ pub const FileSystem = struct {
pub fn addEntry(dir: *DirEntry, prev_map: ?*EntryMap, entry: std.fs.IterableDir.Entry, allocator: std.mem.Allocator, comptime Iterator: type, iterator: Iterator) !void {
const _kind: Entry.Kind = switch (entry.kind) {
- .Directory => .dir,
+ .directory => .dir,
// This might be wrong!
- .SymLink => .file,
- .File => .file,
+ .sym_link => .file,
+ .file => .file,
else => return,
};
@@ -207,7 +207,7 @@ pub const FileSystem = struct {
// Call "stat" lazily for performance. The "@material-ui/icons" package
// contains a directory with over 11,000 entries in it and running "stat"
// for each entry was a big performance issue for that package.
- .need_stat = entry.kind == .SymLink,
+ .need_stat = entry.kind == .sym_link,
.cache = .{
.symlink = PathString.empty,
.kind = _kind,
@@ -768,7 +768,7 @@ pub const FileSystem = struct {
hash_bytes_remain = hash_bytes_remain[@sizeOf(@TypeOf(this.mtime))..];
std.debug.assert(hash_bytes_remain.len == 8);
hash_bytes_remain[0..8].* = @bitCast([8]u8, @as(u64, 0));
- return std.hash.Wyhash.hash(0, &hash_bytes);
+ return bun.hash(&hash_bytes);
}
pub fn generate(_: *RealFS, _: string, file: std.fs.File) anyerror!ModKey {
@@ -1127,7 +1127,7 @@ pub const FileSystem = struct {
const absolute_path_c: [:0]const u8 = outpath[0..entry_path.len :0];
var stat = try C.lstat_absolute(absolute_path_c);
- const is_symlink = stat.kind == std.fs.File.Kind.SymLink;
+ const is_symlink = stat.kind == std.fs.File.Kind.sym_link;
var _kind = stat.kind;
var cache = Entry.Cache{
.kind = Entry.Kind.file,
@@ -1158,9 +1158,9 @@ pub const FileSystem = struct {
_kind = _stat.kind;
}
- std.debug.assert(_kind != .SymLink);
+ std.debug.assert(_kind != .sym_link);
- if (_kind == .Directory) {
+ if (_kind == .directory) {
cache.kind = .dir;
} else {
cache.kind = .file;
@@ -1318,8 +1318,8 @@ pub const PathName = struct {
// so we extend the original slice's length by one
return if (this.dir.len == 0) "./" else this.dir.ptr[0 .. this.dir.len + @intCast(
usize,
- @boolToInt(
- this.dir[this.dir.len - 1] != std.fs.path.sep_posix and (@ptrToInt(this.dir.ptr) + this.dir.len + 1) == @ptrToInt(this.base.ptr),
+ @intFromBool(
+ this.dir[this.dir.len - 1] != std.fs.path.sep_posix and (@intFromPtr(this.dir.ptr) + this.dir.len + 1) == @intFromPtr(this.base.ptr),
),
)];
}
diff --git a/src/futex.zig b/src/futex.zig
index 14c342321..9741032d2 100644
--- a/src/futex.zig
+++ b/src/futex.zig
@@ -209,7 +209,7 @@ const DarwinFutex = struct {
};
if (status >= 0) return;
- switch (@intToEnum(std.os.E, -status)) {
+ switch (@enumFromInt(std.os.E, -status)) {
.INTR => {},
// Address of the futex is paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
@@ -231,7 +231,7 @@ const DarwinFutex = struct {
const status = darwin.__ulock_wake(flags, addr, 0);
if (status >= 0) return;
- switch (@intToEnum(std.os.E, -status)) {
+ switch (@enumFromInt(std.os.E, -status)) {
.INTR => continue, // spurious wake()
.FAULT => continue, // address of the lock was paged out
.NOENT => return, // nothing was woken up
@@ -244,7 +244,7 @@ const DarwinFutex = struct {
const PosixFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
- const address = @ptrToInt(ptr);
+ const address = @intFromPtr(ptr);
const bucket = Bucket.from(address);
var waiter: List.Node = undefined;
@@ -282,7 +282,7 @@ const PosixFutex = struct {
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
- const address = @ptrToInt(ptr);
+ const address = @intFromPtr(ptr);
const bucket = Bucket.from(address);
var can_notify = num_waiters;
diff --git a/src/hive_array.zig b/src/hive_array.zig
index a29fe6842..0213156fd 100644
--- a/src/hive_array.zig
+++ b/src/hive_array.zig
@@ -37,11 +37,11 @@ pub fn HiveArray(comptime T: type, comptime capacity: u16) type {
pub fn indexOf(self: *const Self, value: *const T) ?u32 {
const start = &self.buffer;
const end = @ptrCast([*]const T, start) + capacity;
- if (!(@ptrToInt(value) >= @ptrToInt(start) and @ptrToInt(value) < @ptrToInt(end)))
+ if (!(@intFromPtr(value) >= @intFromPtr(start) and @intFromPtr(value) < @intFromPtr(end)))
return null;
// aligned to the size of T
- const index = (@ptrToInt(value) - @ptrToInt(start)) / @sizeOf(T);
+ const index = (@intFromPtr(value) - @intFromPtr(start)) / @sizeOf(T);
assert(index < capacity);
assert(&self.buffer[index] == value);
return @intCast(u32, index);
@@ -50,7 +50,7 @@ pub fn HiveArray(comptime T: type, comptime capacity: u16) type {
pub fn in(self: *const Self, value: *const T) bool {
const start = &self.buffer;
const end = @ptrCast([*]const T, start) + capacity;
- return (@ptrToInt(value) >= @ptrToInt(start) and @ptrToInt(value) < @ptrToInt(end));
+ return (@intFromPtr(value) >= @intFromPtr(start) and @intFromPtr(value) < @intFromPtr(end));
}
pub fn put(self: *Self, value: *T) bool {
diff --git a/src/http.zig b/src/http.zig
index d2924b804..827bfa6de 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -437,7 +437,7 @@ pub const RequestContext = struct {
.reason = step,
.cwd = this.bundler.fs.top_level_dir,
.problems = Api.Problems{
- .code = @truncate(u16, @errorToInt(err)),
+ .code = @truncate(u16, @intFromError(err)),
.name = @errorName(err),
.exceptions = exceptions,
.build = try log.toAPI(allocator),
@@ -559,7 +559,7 @@ pub const RequestContext = struct {
var stat = file.stat() catch return null;
var absolute_path = resolve_path.joinAbs(this.bundler.options.routes.static_dir, .auto, relative_unrooted_path);
- if (stat.kind == .SymLink) {
+ if (stat.kind == .sym_link) {
file.* = std.fs.openFileAbsolute(absolute_path, .{ .mode = .read_only }) catch return null;
absolute_path = bun.getFdPath(
@@ -570,7 +570,7 @@ pub const RequestContext = struct {
stat = file.stat() catch return null;
}
- if (stat.kind != .File) {
+ if (stat.kind != .file) {
file.close();
return null;
}
@@ -1431,7 +1431,7 @@ pub const RequestContext = struct {
JavaScript.API.Bun.flushCSSImports();
vm.flush();
- Output.printElapsed(@intToFloat(f64, (handler.start_timer.read())) / std.time.ns_per_ms);
+ Output.printElapsed(@floatFromInt(f64, (handler.start_timer.read())) / std.time.ns_per_ms);
if (vm.bundler.options.framework.?.display_name.len > 0) {
Output.prettyError(
@@ -2000,11 +2000,7 @@ pub const RequestContext = struct {
// sometimes the final byte has incorrect data
// we never end up using all those bytes
if (handler.message_buffer.list.items.len > 0) {
- @memset(
- handler.message_buffer.list.items.ptr,
- 0,
- @min(handler.message_buffer.list.items.len, 128),
- );
+ @memset(handler.message_buffer.list.items[0..@min(handler.message_buffer.list.items.len, 128)], 0);
}
const build_result = handler.builder.build(request_id, cmd.timestamp, arena.allocator()) catch |err| {
if (err == error.MissingWatchID) {
@@ -2087,7 +2083,7 @@ pub const RequestContext = struct {
socket_buffers[2] = iovec(build_result.bytes);
// we reuse the accept key buffer
// so we have a pointer that is not stack memory
- handler.accept_key[0..@sizeOf(usize)].* = @bitCast([@sizeOf(usize)]u8, std.hash.Wyhash.hash(0, build_result.bytes));
+ handler.accept_key[0..@sizeOf(usize)].* = @bitCast([@sizeOf(usize)]u8, bun.hash(build_result.bytes));
socket_buffers[3] = iovec(handler.accept_key[0..4]);
socket_buffer_count = 4;
}
@@ -2110,7 +2106,7 @@ pub const RequestContext = struct {
else => {
Output.prettyErrorln(
"<r>[Websocket]: Unknown cmd: <b>{d}<r>. This might be a version mismatch. Try updating your node_modules.bun",
- .{@enumToInt(cmd.kind)},
+ .{@intFromEnum(cmd.kind)},
);
},
}
@@ -2187,7 +2183,7 @@ pub const RequestContext = struct {
};
pub fn writeETag(this: *RequestContext, buffer: anytype) !bool {
- const strong_etag = std.hash.Wyhash.hash(0, buffer);
+ const strong_etag = bun.hash(buffer);
const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
this.appendHeader("ETag", etag_content_slice);
@@ -2404,7 +2400,7 @@ pub const RequestContext = struct {
// Always cache css & json files, even big ones
// css is especially important because we want to try and skip having the browser parse it whenever we can
if (buf.len < 16 * 16 * 16 * 16 or chunky._loader == .css or chunky._loader == .json) {
- const strong_etag = std.hash.Wyhash.hash(0, buf);
+ const strong_etag = bun.hash(buf);
const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
chunky.rctx.appendHeader("ETag", etag_content_slice);
@@ -2538,7 +2534,7 @@ pub const RequestContext = struct {
.css => try ctx.sendNoContent(),
.toml, .js, .jsx, .ts, .tsx, .json => {
const buf = "export default {};";
- const strong_etag = comptime std.hash.Wyhash.hash(0, buf);
+ const strong_etag = comptime bun.hash(buf);
const etag_content_slice = std.fmt.bufPrintIntToSlice(strong_etag_buffer[0..49], strong_etag, 16, .upper, .{});
ctx.appendHeader("ETag", etag_content_slice);
@@ -3388,10 +3384,10 @@ pub const Server = struct {
break :brk path_string.slice();
} else {
var file_path_without_trailing_slash = std.mem.trimRight(u8, file_path, std.fs.path.sep_str);
- @memcpy(&_on_file_update_path_buf, file_path_without_trailing_slash.ptr, file_path_without_trailing_slash.len);
+ @memcpy(_on_file_update_path_buf[0..file_path_without_trailing_slash.len], file_path_without_trailing_slash);
_on_file_update_path_buf[file_path_without_trailing_slash.len] = std.fs.path.sep;
- @memcpy(_on_file_update_path_buf[file_path_without_trailing_slash.len + 1 ..].ptr, changed_name.ptr, changed_name.len);
+ @memcpy(_on_file_update_path_buf[file_path_without_trailing_slash.len + 1 .. changed_name.len], changed_name);
const path_slice = _on_file_update_path_buf[0 .. file_path_without_trailing_slash.len + changed_name.len + 1];
file_hash = Watcher.getHash(path_slice);
break :brk path_slice;
@@ -3445,12 +3441,9 @@ pub const Server = struct {
.kernel_backlog = 1280,
});
defer listener.deinit();
- server.websocket_threadpool.stack_size = @truncate(
- u32,
- @min(
- @max(128_000, Fs.FileSystem.RealFS.Limit.stack),
- 4_000_000,
- ),
+ server.websocket_threadpool.stack_size = @min(
+ @max(128_000, Fs.FileSystem.RealFS.Limit.stack),
+ 4_000_000,
);
// listener.setFastOpen(true) catch {};
diff --git a/src/http/websocket.zig b/src/http/websocket.zig
index 98410d57c..48a4cebf5 100644
--- a/src/http/websocket.zig
+++ b/src/http/websocket.zig
@@ -34,7 +34,7 @@ pub const Opcode = enum(u4) {
ResF = 0xF,
pub fn isControl(opcode: Opcode) bool {
- return @enumToInt(opcode) & 0x8 != 0;
+ return @intFromEnum(opcode) & 0x8 != 0;
}
};
@@ -261,7 +261,7 @@ pub const Websocket = struct {
}
pub fn read(self: *Websocket) !WebsocketDataFrame {
- @memset(&self.buf, 0, self.buf.len);
+ @memset(&self.buf, 0);
// Read and retry if we hit the end of the stream buffer
var start = try self.stream.read(&self.buf);
@@ -274,7 +274,7 @@ pub const Websocket = struct {
}
pub fn eatAt(self: *Websocket, offset: usize, _len: usize) []u8 {
- const len = std.math.min(self.read_stream.buffer.len, _len);
+ const len = @min(self.read_stream.buffer.len, _len);
self.read_stream.pos = len;
return self.read_stream.buffer[offset..len];
}
@@ -292,7 +292,7 @@ pub const Websocket = struct {
// header.rsv1 = header_bytes[0] & 0x40 == 0x40;
// header.rsv2 = header_bytes[0] & 0x20;
// header.rsv3 = header_bytes[0] & 0x10;
- header.opcode = @intToEnum(Opcode, @truncate(u4, header_bytes[0]));
+ header.opcode = @enumFromInt(Opcode, @truncate(u4, header_bytes[0]));
header.mask = header_bytes[1] & 0x80 == 0x80;
header.len = @truncate(u7, header_bytes[1]);
diff --git a/src/http/websocket_http_client.zig b/src/http/websocket_http_client.zig
index e1bd42984..e79c353e3 100644
--- a/src/http/websocket_http_client.zig
+++ b/src/http/websocket_http_client.zig
@@ -77,9 +77,9 @@ fn buildRequestBody(
};
if (client_protocol.len > 0)
- client_protocol_hash.* = std.hash.Wyhash.hash(0, static_headers[1].value);
+ client_protocol_hash.* = bun.hash(static_headers[1].value);
- const headers_ = static_headers[0 .. 1 + @as(usize, @boolToInt(client_protocol.len > 0))];
+ const headers_ = static_headers[0 .. 1 + @as(usize, @intFromBool(client_protocol.len > 0))];
const pathname_ = pathname.slice();
const host_ = host.slice();
@@ -289,7 +289,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type {
this.clearData();
if (!this.tcp.isEstablished()) {
- _ = uws.us_socket_close_connecting(comptime @as(c_int, @boolToInt(ssl)), this.tcp.socket);
+ _ = uws.us_socket_close_connecting(comptime @as(c_int, @intFromBool(ssl)), this.tcp.socket);
} else {
this.tcp.close(0, null);
}
@@ -387,7 +387,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type {
const to_write = remain[0..@min(remain.len, data.len)];
if (data.len > 0 and to_write.len > 0) {
- @memcpy(remain.ptr, data.ptr, to_write.len);
+ @memcpy(remain[0..to_write.len], data[0..to_write.len]);
this.body_written += to_write.len;
}
@@ -465,7 +465,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type {
},
"Sec-WebSocket-Protocol".len => {
if (strings.eqlCaseInsensitiveASCII(header.name, "Sec-WebSocket-Protocol", false)) {
- if (this.websocket_protocol == 0 or std.hash.Wyhash.hash(0, header.value) != this.websocket_protocol) {
+ if (this.websocket_protocol == 0 or bun.hash(header.value) != this.websocket_protocol) {
this.terminate(ErrorCode.mismatch_client_protocol);
return;
}
@@ -524,7 +524,7 @@ pub fn NewHTTPUpgradeClient(comptime ssl: bool) type {
this.terminate(ErrorCode.invalid_response);
return;
};
- if (remain_buf.len > 0) @memcpy(overflow.ptr, remain_buf.ptr, remain_buf.len);
+ if (remain_buf.len > 0) @memcpy(overflow[0..remain_buf.len], remain_buf);
}
this.clearData();
@@ -775,7 +775,7 @@ const Copy = union(enum) {
if (this == .raw) {
std.debug.assert(buf.len >= this.raw.len);
std.debug.assert(buf.ptr != this.raw.ptr);
- @memcpy(buf.ptr, this.raw.ptr, this.raw.len);
+ @memcpy(buf[0..this.raw.len], this.raw);
return;
}
@@ -914,7 +914,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type {
return;
if (!this.tcp.isEstablished()) {
- _ = uws.us_socket_close_connecting(comptime @as(c_int, @boolToInt(ssl)), this.tcp.socket);
+ _ = uws.us_socket_close_connecting(comptime @as(c_int, @intFromBool(ssl)), this.tcp.socket);
} else {
this.tcp.close(0, null);
}
@@ -1027,7 +1027,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type {
std.debug.assert(data_.len > 0);
var writable = this.receive_buffer.writableWithSize(data_.len) catch unreachable;
- @memcpy(writable.ptr, data_.ptr, data_.len);
+ @memcpy(writable[0..data_.len], data_);
this.receive_buffer.update(data_.len);
if (left_in_fragment >= data_.len and left_in_fragment - data_.len - this.receive_pending_chunk_len == 0) {
@@ -1177,10 +1177,10 @@ pub fn NewWebSocketClient(comptime ssl: bool) type {
.ping => {
const ping_len = @min(data.len, @min(receive_body_remain, 125));
- this.ping_len = @truncate(u8, ping_len);
+ this.ping_len = ping_len;
if (ping_len > 0) {
- @memcpy(this.ping_frame_bytes[6..], data.ptr, ping_len);
+ @memcpy(this.ping_frame_bytes[6..][0..ping_len], data[0..ping_len]);
data = data[ping_len..];
}
@@ -1379,7 +1379,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type {
std.mem.writeIntSliceBig(u16, final_body_bytes[6..8], code);
if (body) |data| {
- if (body_len > 0) @memcpy(final_body_bytes[8..], data, body_len);
+ if (body_len > 0) @memcpy(final_body_bytes[8..][0..body_len], data[0..body_len]);
}
// we must mask the code
@@ -1565,7 +1565,7 @@ pub fn NewWebSocketClient(comptime ssl: bool) type {
this.adopted.receive_buffer.ensureUnusedCapacity(this.slice.len) catch return;
var writable = this.adopted.receive_buffer.writableSlice(0);
- @memcpy(writable.ptr, this.slice.ptr, this.slice.len);
+ @memcpy(writable[0..this.slice.len], this.slice);
this.adopted.handleData(this.adopted.tcp, writable);
}
diff --git a/src/http_client_async.zig b/src/http_client_async.zig
index fe5f34f48..a1962a8b9 100644
--- a/src/http_client_async.zig
+++ b/src/http_client_async.zig
@@ -42,7 +42,7 @@ const HiveArray = @import("./hive_array.zig").HiveArray;
const Batch = NetworkThread.Batch;
const TaggedPointerUnion = @import("./tagged_pointer.zig").TaggedPointerUnion;
const DeadSocket = opaque {};
-var dead_socket = @intToPtr(*DeadSocket, 1);
+var dead_socket = @ptrFromInt(*DeadSocket, 1);
//TODO: this needs to be freed when Worker Threads are implemented
var socket_async_http_abort_tracker = std.AutoArrayHashMap(u32, *uws.Socket).init(bun.default_allocator);
var async_http_id: std.atomic.Atomic(u32) = std.atomic.Atomic(u32).init(0);
@@ -208,7 +208,7 @@ const ProxyTunnel = struct {
_ = BoringSSL.BIO_push(out_bio, proxy_bio);
} else {
// socket output bio for non-TLS -> TLS
- var fd = @intCast(c_int, @ptrToInt(socket.getNativeHandle()));
+ var fd = @intCast(c_int, @intFromPtr(socket.getNativeHandle()));
out_bio = BoringSSL.BIO_new_fd(fd, BoringSSL.BIO_NOCLOSE);
}
@@ -306,7 +306,7 @@ fn NewHTTPContext(comptime ssl: bool) type {
HTTPClient,
PooledSocket,
});
- const ssl_int = @as(c_int, @boolToInt(ssl));
+ const ssl_int = @as(c_int, @intFromBool(ssl));
const MAX_KEEPALIVE_HOSTNAME = 128;
@@ -320,7 +320,8 @@ fn NewHTTPContext(comptime ssl: bool) type {
pub fn init(this: *@This()) !void {
var opts: uws.us_socket_context_options_t = undefined;
- @memset(@ptrCast([*]u8, &opts), 0, @sizeOf(uws.us_socket_context_options_t));
+ const size = @sizeOf(uws.us_socket_context_options_t);
+ @memset(@ptrCast([*]u8, &opts)[0..size], 0);
this.us_socket_context = uws.us_create_socket_context(ssl_int, http_thread.loop, @sizeOf(usize), opts).?;
if (comptime ssl) {
this.sslCtx().setup();
@@ -337,7 +338,7 @@ fn NewHTTPContext(comptime ssl: bool) type {
/// Attempt to keep the socket alive by reusing it for another request.
/// If no space is available, close the socket.
pub fn releaseSocket(this: *@This(), socket: HTTPSocket, hostname: []const u8, port: u16) void {
- log("releaseSocket(0x{})", .{bun.fmt.hexIntUpper(@ptrToInt(socket.socket))});
+ log("releaseSocket(0x{})", .{bun.fmt.hexIntUpper(@intFromPtr(socket.socket))});
if (comptime Environment.allow_assert) {
std.debug.assert(!socket.isClosed());
@@ -354,11 +355,11 @@ fn NewHTTPContext(comptime ssl: bool) type {
socket.timeout(300);
pending.http_socket = socket;
- @memcpy(&pending.hostname_buf, hostname.ptr, hostname.len);
+ @memcpy(pending.hostname_buf[0..hostname.len], hostname);
pending.hostname_len = @truncate(u8, hostname.len);
pending.port = port;
- log("Keep-Alive release {s}:{d} (0x{})", .{ hostname, port, @ptrToInt(socket.socket) });
+ log("Keep-Alive release {s}:{d} (0x{})", .{ hostname, port, @intFromPtr(socket.socket) });
return;
}
}
@@ -778,7 +779,7 @@ pub fn onOpen(
var hostname_needs_free = false;
if (!strings.isIPAddress(_hostname)) {
if (_hostname.len < temp_hostname.len) {
- @memcpy(&temp_hostname, _hostname.ptr, _hostname.len);
+ @memcpy(temp_hostname[0.._hostname.len], _hostname);
temp_hostname[_hostname.len] = 0;
hostname = temp_hostname[0.._hostname.len :0];
} else {
@@ -1393,7 +1394,7 @@ pub const AsyncHTTP = struct {
if (proxy.password.len > 0 and proxy.password.len < 4096) {
// decode password
var password_buffer: [4096]u8 = undefined;
- std.mem.set(u8, &password_buffer, 0);
+ @memset(&password_buffer, 0);
var password_stream = std.io.fixedBufferStream(&password_buffer);
var password_writer = password_stream.writer();
const PassWriter = @TypeOf(password_writer);
@@ -1405,7 +1406,7 @@ pub const AsyncHTTP = struct {
// Decode username
var username_buffer: [4096]u8 = undefined;
- std.mem.set(u8, &username_buffer, 0);
+ @memset(&username_buffer, 0);
var username_stream = std.io.fixedBufferStream(&username_buffer);
var username_writer = username_stream.writer();
const UserWriter = @TypeOf(username_writer);
@@ -1426,7 +1427,7 @@ pub const AsyncHTTP = struct {
} else {
//Decode username
var username_buffer: [4096]u8 = undefined;
- std.mem.set(u8, &username_buffer, 0);
+ @memset(&username_buffer, 0);
var username_stream = std.io.fixedBufferStream(&username_buffer);
var username_writer = username_stream.writer();
const UserWriter = @TypeOf(username_writer);
@@ -1469,7 +1470,7 @@ pub const AsyncHTTP = struct {
if (proxy.password.len > 0 and proxy.password.len < 4096) {
// decode password
var password_buffer: [4096]u8 = undefined;
- std.mem.set(u8, &password_buffer, 0);
+ @memset(&password_buffer, 0);
var password_stream = std.io.fixedBufferStream(&password_buffer);
var password_writer = password_stream.writer();
const PassWriter = @TypeOf(password_writer);
@@ -1481,7 +1482,7 @@ pub const AsyncHTTP = struct {
// Decode username
var username_buffer: [4096]u8 = undefined;
- std.mem.set(u8, &username_buffer, 0);
+ @memset(&username_buffer, 0);
var username_stream = std.io.fixedBufferStream(&username_buffer);
var username_writer = username_stream.writer();
const UserWriter = @TypeOf(username_writer);
@@ -1503,7 +1504,7 @@ pub const AsyncHTTP = struct {
} else {
//Decode username
var username_buffer: [4096]u8 = undefined;
- std.mem.set(u8, &username_buffer, 0);
+ @memset(&username_buffer, 0);
var username_stream = std.io.fixedBufferStream(&username_buffer);
var username_writer = username_stream.writer();
const UserWriter = @TypeOf(username_writer);
@@ -1872,7 +1873,7 @@ pub fn onWritable(this: *HTTPClient, comptime is_first_call: bool, comptime is_s
var remain = list.items.ptr[list.items.len..list.capacity];
const wrote = @min(remain.len, this.state.request_body.len);
std.debug.assert(wrote > 0);
- @memcpy(remain.ptr, this.state.request_body.ptr, wrote);
+ @memcpy(remain[0..wrote], this.state.request_body[0..wrote]);
list.items.len += wrote;
}
@@ -2021,7 +2022,7 @@ pub fn onWritable(this: *HTTPClient, comptime is_first_call: bool, comptime is_s
var remain = list.items.ptr[list.items.len..list.capacity];
const wrote = @min(remain.len, this.state.request_body.len);
std.debug.assert(wrote > 0);
- @memcpy(remain.ptr, this.state.request_body.ptr, wrote);
+ @memcpy(remain[0..wrote], this.state.request_body[0..wrote]);
list.items.len += wrote;
}
@@ -2582,8 +2583,8 @@ fn handleResponseBodyFromSinglePacket(this: *HTTPClient, incoming_data: []const
if (this.state.encoding.isCompressed()) {
var body_buffer = this.state.body_out_str.?;
if (body_buffer.list.capacity == 0) {
- const min = @min(@ceil(@intToFloat(f64, incoming_data.len) * 1.5), @as(f64, 1024 * 1024 * 2));
- try body_buffer.growBy(@max(@floatToInt(usize, min), 32));
+ const min = @min(@ceil(@floatFromInt(f64, incoming_data.len) * 1.5), @as(f64, 1024 * 1024 * 2));
+ try body_buffer.growBy(@max(@intFromFloat(usize, min), 32));
}
try ZlibPool.decompress(incoming_data, body_buffer, default_allocator);
@@ -2737,7 +2738,7 @@ fn handleResponseBodyChunkedEncodingFromSinglePacket(
buffer = bun.constStrToU8(incoming_data);
} else {
buffer = single_packet_small_buffer[0..incoming_data.len];
- @memcpy(buffer.ptr, incoming_data.ptr, incoming_data.len);
+ @memcpy(buffer[0..incoming_data.len], incoming_data);
}
var bytes_decoded = incoming_data.len;
@@ -2871,7 +2872,7 @@ pub fn handleResponseMetadata(
return error.UnsupportedRedirectProtocol;
}
- if ((protocol_name.len * @as(usize, @boolToInt(is_protocol_relative))) + location.len > url_buf.data.len) {
+ if ((protocol_name.len * @as(usize, @intFromBool(is_protocol_relative))) + location.len > url_buf.data.len) {
return error.RedirectURLTooLong;
}
diff --git a/src/import_record.zig b/src/import_record.zig
index 16e3fcde6..d0df147db 100644
--- a/src/import_record.zig
+++ b/src/import_record.zig
@@ -207,7 +207,7 @@ pub const ImportRecord = struct {
}
pub inline fn isInternal(this: Tag) bool {
- return @enumToInt(this) >= @enumToInt(Tag.runtime);
+ return @intFromEnum(this) >= @intFromEnum(Tag.runtime);
}
pub fn useDirective(this: Tag) bun.JSAst.UseDirective {
diff --git a/src/install/bin.zig b/src/install/bin.zig
index 371ce0dde..b0e988269 100644
--- a/src/install/bin.zig
+++ b/src/install/bin.zig
@@ -382,7 +382,7 @@ pub const Bin = extern struct {
bun.copy(u8, remain, target);
remain = remain[target.len..];
remain[0] = 0;
- const target_len = @ptrToInt(remain.ptr) - @ptrToInt(&dest_buf);
+ const target_len = @intFromPtr(remain.ptr) - @intFromPtr(&dest_buf);
remain = remain[1..];
var target_path: [:0]u8 = dest_buf[0..target_len :0];
@@ -392,7 +392,7 @@ pub const Bin = extern struct {
bun.copy(u8, from_remain, unscoped_name);
from_remain = from_remain[unscoped_name.len..];
from_remain[0] = 0;
- var dest_path: [:0]u8 = target_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var dest_path: [:0]u8 = target_buf[0 .. @intFromPtr(from_remain.ptr) - @intFromPtr(&target_buf) :0];
this.setSimlinkAndPermissions(target_path, dest_path);
},
@@ -404,7 +404,7 @@ pub const Bin = extern struct {
bun.copy(u8, remain, target);
remain = remain[target.len..];
remain[0] = 0;
- const target_len = @ptrToInt(remain.ptr) - @ptrToInt(&dest_buf);
+ const target_len = @intFromPtr(remain.ptr) - @intFromPtr(&dest_buf);
remain = remain[1..];
var target_path: [:0]u8 = dest_buf[0..target_len :0];
@@ -412,7 +412,7 @@ pub const Bin = extern struct {
bun.copy(u8, from_remain, name_to_use);
from_remain = from_remain[name_to_use.len..];
from_remain[0] = 0;
- var dest_path: [:0]u8 = target_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var dest_path: [:0]u8 = target_buf[0 .. @intFromPtr(from_remain.ptr) - @intFromPtr(&target_buf) :0];
this.setSimlinkAndPermissions(target_path, dest_path);
},
@@ -434,7 +434,7 @@ pub const Bin = extern struct {
bun.copy(u8, remain, target);
remain = remain[target.len..];
remain[0] = 0;
- const target_len = @ptrToInt(remain.ptr) - @ptrToInt(&dest_buf);
+ const target_len = @intFromPtr(remain.ptr) - @intFromPtr(&dest_buf);
remain = remain[1..];
var target_path: [:0]u8 = dest_buf[0..target_len :0];
@@ -442,7 +442,7 @@ pub const Bin = extern struct {
bun.copy(u8, from_remain, name_to_use);
from_remain = from_remain[name_to_use.len..];
from_remain[0] = 0;
- var dest_path: [:0]u8 = target_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var dest_path: [:0]u8 = target_buf[0 .. @intFromPtr(from_remain.ptr) - @intFromPtr(&target_buf) :0];
this.setSimlinkAndPermissions(target_path, dest_path);
}
@@ -461,7 +461,7 @@ pub const Bin = extern struct {
var dir = std.fs.Dir{ .fd = this.package_installed_node_modules };
var joined = Path.joinStringBuf(&target_buf, &parts, .auto);
- @intToPtr([*]u8, @ptrToInt(joined.ptr))[joined.len] = 0;
+ @ptrFromInt([*]u8, @intFromPtr(joined.ptr))[joined.len] = 0;
var joined_: [:0]const u8 = joined.ptr[0..joined.len :0];
var child_dir = bun.openDir(dir, joined_) catch |err| {
this.err = err;
@@ -482,12 +482,12 @@ pub const Bin = extern struct {
while (iter.next() catch null) |entry_| {
const entry: std.fs.IterableDir.Entry = entry_;
switch (entry.kind) {
- std.fs.IterableDir.Entry.Kind.SymLink, std.fs.IterableDir.Entry.Kind.File => {
+ std.fs.IterableDir.Entry.Kind.sym_link, std.fs.IterableDir.Entry.Kind.file => {
target_buf_remain = prev_target_buf_remain;
bun.copy(u8, target_buf_remain, entry.name);
target_buf_remain = target_buf_remain[entry.name.len..];
target_buf_remain[0] = 0;
- var from_path: [:0]u8 = target_buf[0 .. @ptrToInt(target_buf_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var from_path: [:0]u8 = target_buf[0 .. @intFromPtr(target_buf_remain.ptr) - @intFromPtr(&target_buf) :0];
var to_path = if (!link_global)
std.fmt.bufPrintZ(&dest_buf, dot_bin ++ "{s}", .{entry.name}) catch continue
else
@@ -519,7 +519,7 @@ pub const Bin = extern struct {
return;
}
- @memcpy(&target_buf, this.global_bin_path.ptr, this.global_bin_path.len);
+ @memcpy(target_buf[0..this.global_bin_path.len], this.global_bin_path);
from_remain = target_buf[this.global_bin_path.len..];
from_remain[0] = std.fs.path.sep;
from_remain = from_remain[1..];
@@ -557,7 +557,7 @@ pub const Bin = extern struct {
bun.copy(u8, from_remain, unscoped_name);
from_remain = from_remain[unscoped_name.len..];
from_remain[0] = 0;
- var dest_path: [:0]u8 = target_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var dest_path: [:0]u8 = target_buf[0 .. @intFromPtr(from_remain.ptr) - @intFromPtr(&target_buf) :0];
std.os.unlinkatZ(this.root_node_modules_folder, dest_path, 0) catch {};
},
@@ -566,7 +566,7 @@ pub const Bin = extern struct {
bun.copy(u8, from_remain, name_to_use);
from_remain = from_remain[name_to_use.len..];
from_remain[0] = 0;
- var dest_path: [:0]u8 = target_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var dest_path: [:0]u8 = target_buf[0 .. @intFromPtr(from_remain.ptr) - @intFromPtr(&target_buf) :0];
std.os.unlinkatZ(this.root_node_modules_folder, dest_path, 0) catch {};
},
@@ -594,7 +594,7 @@ pub const Bin = extern struct {
bun.copy(u8, from_remain, name_to_use);
from_remain = from_remain[name_to_use.len..];
from_remain[0] = 0;
- var dest_path: [:0]u8 = target_buf[0 .. @ptrToInt(from_remain.ptr) - @ptrToInt(&target_buf) :0];
+ var dest_path: [:0]u8 = target_buf[0 .. @intFromPtr(from_remain.ptr) - @intFromPtr(&target_buf) :0];
std.os.unlinkatZ(this.root_node_modules_folder, dest_path, 0) catch {};
}
@@ -613,7 +613,7 @@ pub const Bin = extern struct {
var dir = std.fs.Dir{ .fd = this.package_installed_node_modules };
var joined = Path.joinStringBuf(&target_buf, &parts, .auto);
- @intToPtr([*]u8, @ptrToInt(joined.ptr))[joined.len] = 0;
+ @ptrFromInt([*]u8, @intFromPtr(joined.ptr))[joined.len] = 0;
var joined_: [:0]const u8 = joined.ptr[0..joined.len :0];
var child_dir = bun.openDir(dir, joined_) catch |err| {
this.err = err;
@@ -634,7 +634,7 @@ pub const Bin = extern struct {
while (iter.next() catch null) |entry_| {
const entry: std.fs.IterableDir.Entry = entry_;
switch (entry.kind) {
- std.fs.IterableDir.Entry.Kind.SymLink, std.fs.IterableDir.Entry.Kind.File => {
+ std.fs.IterableDir.Entry.Kind.sym_link, std.fs.IterableDir.Entry.Kind.file => {
target_buf_remain = prev_target_buf_remain;
bun.copy(u8, target_buf_remain, entry.name);
target_buf_remain = target_buf_remain[entry.name.len..];
diff --git a/src/install/dependency.zig b/src/install/dependency.zig
index 0480dd9d8..6ef02bbfc 100644
--- a/src/install/dependency.zig
+++ b/src/install/dependency.zig
@@ -147,7 +147,7 @@ pub fn toDependency(
return Dependency{
.name = name,
.name_hash = @bitCast(u64, this[8..16].*),
- .behavior = @intToEnum(Dependency.Behavior, this[16]),
+ .behavior = @enumFromInt(Dependency.Behavior, this[16]),
.version = Dependency.Version.toVersion(name, this[17..this.len].*, ctx),
};
}
@@ -156,7 +156,7 @@ pub fn toExternal(this: Dependency) External {
var bytes: External = undefined;
bytes[0..this.name.bytes.len].* = this.name.bytes;
bytes[8..16].* = @bitCast([8]u8, this.name_hash);
- bytes[16] = @enumToInt(this.behavior);
+ bytes[16] = @intFromEnum(this.behavior);
bytes[17..bytes.len].* = this.version.toExternal();
return bytes;
}
@@ -265,7 +265,7 @@ pub const Version = struct {
ctx: Dependency.Context,
) Dependency.Version {
const slice = String{ .bytes = bytes[1..9].* };
- const tag = @intToEnum(Dependency.Version.Tag, bytes[0]);
+ const tag = @enumFromInt(Dependency.Version.Tag, bytes[0]);
const sliced = &slice.sliced(ctx.buffer);
return Dependency.parseWithTag(
ctx.allocator,
@@ -279,7 +279,7 @@ pub const Version = struct {
pub inline fn toExternal(this: Version) Version.External {
var bytes: Version.External = undefined;
- bytes[0] = @enumToInt(this.tag);
+ bytes[0] = @intFromEnum(this.tag);
bytes[1..9].* = this.literal.bytes;
return bytes;
}
@@ -339,7 +339,7 @@ pub const Version = struct {
github = 8,
pub inline fn isNPM(this: Tag) bool {
- return @enumToInt(this) < 3;
+ return @intFromEnum(this) < 3;
}
pub fn infer(dependency: string) Tag {
@@ -493,7 +493,7 @@ pub const Version = struct {
// npm:package@1.2.3
'n' => {
if (strings.hasPrefixComptime(dependency, "npm:") and dependency.len > "npm:".len) {
- const remain = dependency["npm:".len + @boolToInt(dependency["npm:".len] == '@') ..];
+ const remain = dependency["npm:".len + @intFromBool(dependency["npm:".len] == '@') ..];
for (remain, 0..) |c, i| {
if (c == '@') {
return infer(remain[i + 1 ..]);
@@ -645,7 +645,7 @@ pub fn parseWithTag(
var input = dependency;
const name = if (strings.hasPrefixComptime(input, "npm:")) sliced.sub(brk: {
var str = input["npm:".len..];
- var i: usize = @boolToInt(str.len > 0 and str[0] == '@');
+ var i: usize = @intFromBool(str.len > 0 and str[0] == '@');
while (i < str.len) : (i += 1) {
if (str[i] == '@') {
@@ -694,7 +694,7 @@ pub fn parseWithTag(
// npm:@foo/bar@latest
// ^
- i += @boolToInt(dependency[i] == '@');
+ i += @intFromBool(dependency[i] == '@');
while (i < dependency.len) : (i += 1) {
// npm:@foo/bar@latest
@@ -899,67 +899,67 @@ pub const Behavior = enum(u8) {
pub const workspace: u8 = 1 << 5;
pub inline fn isNormal(this: Behavior) bool {
- return (@enumToInt(this) & Behavior.normal) != 0;
+ return (@intFromEnum(this) & Behavior.normal) != 0;
}
pub inline fn isOptional(this: Behavior) bool {
- return (@enumToInt(this) & Behavior.optional) != 0 and !this.isPeer();
+ return (@intFromEnum(this) & Behavior.optional) != 0 and !this.isPeer();
}
pub inline fn isDev(this: Behavior) bool {
- return (@enumToInt(this) & Behavior.dev) != 0;
+ return (@intFromEnum(this) & Behavior.dev) != 0;
}
pub inline fn isPeer(this: Behavior) bool {
- return (@enumToInt(this) & Behavior.peer) != 0;
+ return (@intFromEnum(this) & Behavior.peer) != 0;
}
pub inline fn isWorkspace(this: Behavior) bool {
- return (@enumToInt(this) & Behavior.workspace) != 0;
+ return (@intFromEnum(this) & Behavior.workspace) != 0;
}
pub inline fn setNormal(this: Behavior, value: bool) Behavior {
if (value) {
- return @intToEnum(Behavior, @enumToInt(this) | Behavior.normal);
+ return @enumFromInt(Behavior, @intFromEnum(this) | Behavior.normal);
} else {
- return @intToEnum(Behavior, @enumToInt(this) & ~Behavior.normal);
+ return @enumFromInt(Behavior, @intFromEnum(this) & ~Behavior.normal);
}
}
pub inline fn setOptional(this: Behavior, value: bool) Behavior {
if (value) {
- return @intToEnum(Behavior, @enumToInt(this) | Behavior.optional);
+ return @enumFromInt(Behavior, @intFromEnum(this) | Behavior.optional);
} else {
- return @intToEnum(Behavior, @enumToInt(this) & ~Behavior.optional);
+ return @enumFromInt(Behavior, @intFromEnum(this) & ~Behavior.optional);
}
}
pub inline fn setDev(this: Behavior, value: bool) Behavior {
if (value) {
- return @intToEnum(Behavior, @enumToInt(this) | Behavior.dev);
+ return @enumFromInt(Behavior, @intFromEnum(this) | Behavior.dev);
} else {
- return @intToEnum(Behavior, @enumToInt(this) & ~Behavior.dev);
+ return @enumFromInt(Behavior, @intFromEnum(this) & ~Behavior.dev);
}
}
pub inline fn setPeer(this: Behavior, value: bool) Behavior {
if (value) {
- return @intToEnum(Behavior, @enumToInt(this) | Behavior.peer);
+ return @enumFromInt(Behavior, @intFromEnum(this) | Behavior.peer);
} else {
- return @intToEnum(Behavior, @enumToInt(this) & ~Behavior.peer);
+ return @enumFromInt(Behavior, @intFromEnum(this) & ~Behavior.peer);
}
}
pub inline fn setWorkspace(this: Behavior, value: bool) Behavior {
if (value) {
- return @intToEnum(Behavior, @enumToInt(this) | Behavior.workspace);
+ return @enumFromInt(Behavior, @intFromEnum(this) | Behavior.workspace);
} else {
- return @intToEnum(Behavior, @enumToInt(this) & ~Behavior.workspace);
+ return @enumFromInt(Behavior, @intFromEnum(this) & ~Behavior.workspace);
}
}
pub inline fn cmp(lhs: Behavior, rhs: Behavior) std.math.Order {
- if (@enumToInt(lhs) == @enumToInt(rhs)) {
+ if (@intFromEnum(lhs) == @intFromEnum(rhs)) {
return .eq;
}
diff --git a/src/install/install.zig b/src/install/install.zig
index 88c8f653f..32c24548c 100644
--- a/src/install/install.zig
+++ b/src/install/install.zig
@@ -146,12 +146,12 @@ pub fn ExternalSliceAligned(comptime Type: type, comptime alignment_: ?u29) type
pub fn init(buf: []const Type, in: []const Type) Slice {
// if (comptime Environment.allow_assert) {
- // std.debug.assert(@ptrToInt(buf.ptr) <= @ptrToInt(in.ptr));
- // std.debug.assert((@ptrToInt(in.ptr) + in.len) <= (@ptrToInt(buf.ptr) + buf.len));
+ // std.debug.assert(@intFromPtr(buf.ptr) <= @intFromPtr(in.ptr));
+ // std.debug.assert((@intFromPtr(in.ptr) + in.len) <= (@intFromPtr(buf.ptr) + buf.len));
// }
return Slice{
- .off = @truncate(u32, (@ptrToInt(in.ptr) - @ptrToInt(buf.ptr)) / @sizeOf(Type)),
+ .off = @truncate(u32, (@intFromPtr(in.ptr) - @intFromPtr(buf.ptr)) / @sizeOf(Type)),
.len = @truncate(u32, in.len),
};
}
@@ -183,7 +183,7 @@ pub const Aligner = struct {
}
pub inline fn skipAmount(comptime Type: type, pos: usize) usize {
- return std.mem.alignForward(pos, @alignOf(Type)) - pos;
+ return std.mem.alignForward(usize, pos, @alignOf(Type)) - pos;
}
};
@@ -351,7 +351,7 @@ const NetworkTask = struct {
},
);
header_builder.header_count = 1;
- header_builder.content = GlobalStringBuilder{ .ptr = @intToPtr([*]u8, @ptrToInt(bun.span(default_headers_buf).ptr)), .len = default_headers_buf.len, .cap = default_headers_buf.len };
+ header_builder.content = GlobalStringBuilder{ .ptr = @ptrFromInt([*]u8, @intFromPtr(bun.span(default_headers_buf).ptr)), .len = default_headers_buf.len, .cap = default_headers_buf.len };
}
this.response_buffer = try MutableString.init(allocator, 0);
@@ -474,12 +474,12 @@ pub const Features = struct {
pub fn behavior(this: Features) Behavior {
var out: u8 = 0;
- out |= @as(u8, @boolToInt(this.dependencies)) << 1;
- out |= @as(u8, @boolToInt(this.optional_dependencies)) << 2;
- out |= @as(u8, @boolToInt(this.dev_dependencies)) << 3;
- out |= @as(u8, @boolToInt(this.peer_dependencies)) << 4;
- out |= @as(u8, @boolToInt(this.workspaces)) << 5;
- return @intToEnum(Behavior, out);
+ out |= @as(u8, @intFromBool(this.dependencies)) << 1;
+ out |= @as(u8, @intFromBool(this.optional_dependencies)) << 2;
+ out |= @as(u8, @intFromBool(this.dev_dependencies)) << 3;
+ out |= @as(u8, @intFromBool(this.peer_dependencies)) << 4;
+ out |= @as(u8, @intFromBool(this.workspaces)) << 5;
+ return @enumFromInt(Behavior, out);
}
pub const main = Features{
@@ -541,7 +541,7 @@ const Task = struct {
/// An ID that lets us register a callback without keeping the same pointer around
pub const Id = struct {
pub fn forNPMPackage(package_name: string, package_version: Semver.Version) u64 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(package_name);
hasher.update("@");
hasher.update(std.mem.asBytes(&package_version));
@@ -549,28 +549,28 @@ const Task = struct {
}
pub fn forBinLink(package_id: PackageID) u64 {
- const hash = std.hash.Wyhash.hash(0, std.mem.asBytes(&package_id));
+ const hash = bun.Wyhash.hash(0, std.mem.asBytes(&package_id));
return @as(u64, 1 << 61) | @as(u64, @truncate(u61, hash));
}
pub fn forManifest(name: string) u64 {
- return @as(u64, 2 << 61) | @as(u64, @truncate(u61, std.hash.Wyhash.hash(0, name)));
+ return @as(u64, 2 << 61) | @as(u64, @truncate(u61, bun.Wyhash.hash(0, name)));
}
pub fn forTarball(url: string) u64 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(url);
return @as(u64, 3 << 61) | @as(u64, @truncate(u61, hasher.final()));
}
pub fn forGitClone(url: string) u64 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(url);
return @as(u64, 4 << 61) | @as(u64, @truncate(u61, hasher.final()));
}
pub fn forGitCheckout(url: string, resolved: string) u64 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(url);
hasher.update("@");
hasher.update(resolved);
@@ -1079,10 +1079,10 @@ const PackageInstall = struct {
var stackpath: [bun.MAX_PATH_BYTES]u8 = undefined;
while (try walker.next()) |entry| {
switch (entry.kind) {
- .Directory => {
+ .directory => {
std.os.mkdirat(destination_dir_.dir.fd, entry.path, 0o755) catch {};
},
- .File => {
+ .file => {
bun.copy(u8, &stackpath, entry.path);
stackpath[entry.path.len] = 0;
var path: [:0]u8 = stackpath[0..entry.path.len :0];
@@ -1190,7 +1190,7 @@ const PackageInstall = struct {
) !u32 {
var real_file_count: u32 = 0;
while (try walker.next()) |entry| {
- if (entry.kind != .File) continue;
+ if (entry.kind != .file) continue;
real_file_count += 1;
var outfile = destination_dir_.createFile(entry.path, .{}) catch brk: {
@@ -1268,10 +1268,10 @@ const PackageInstall = struct {
var real_file_count: u32 = 0;
while (try walker.next()) |entry| {
switch (entry.kind) {
- .Directory => {
+ .directory => {
std.os.mkdirat(destination_dir_.dir.fd, entry.path, 0o755) catch {};
},
- .File => {
+ .file => {
try std.os.linkat(entry.dir.dir.fd, entry.basename, destination_dir_.dir.fd, entry.path, 0);
real_file_count += 1;
},
@@ -1351,16 +1351,16 @@ const PackageInstall = struct {
while (try walker.next()) |entry| {
switch (entry.kind) {
// directories are created
- .Directory => {
+ .directory => {
std.os.mkdirat(dest_dir_fd, entry.path, 0o755) catch {};
},
// but each file in the directory is a symlink
- .File => {
- @memcpy(remain.ptr, entry.path.ptr, entry.path.len);
+ .file => {
+ @memcpy(remain[0..entry.path.len], entry.path);
remain[entry.path.len] = 0;
var from_path = buf[0 .. cache_dir_offset + entry.path.len :0];
- @memcpy(dest_remaining.ptr, entry.path.ptr, entry.path.len);
+ @memcpy(dest_remaining[0..entry.path.len], entry.path);
dest_remaining[entry.path.len] = 0;
var to_path = dest_buf[0 .. dest_dir_offset + entry.path.len :0];
@@ -1830,7 +1830,7 @@ pub const PackageManager = struct {
const offset = this.preinstall_state.items.len;
try this.preinstall_state.ensureTotalCapacity(this.allocator, count);
this.preinstall_state.expandToCapacity();
- std.mem.set(PreinstallState, this.preinstall_state.items[offset..], PreinstallState.unknown);
+ @memset(this.preinstall_state.items[offset..], PreinstallState.unknown);
}
pub fn setPreinstallState(this: *PackageManager, package_id: PackageID, lockfile: *Lockfile, value: PreinstallState) void {
@@ -2263,7 +2263,7 @@ pub const PackageManager = struct {
var iter = dir.iterate();
while (try iter.next()) |entry| {
- if (entry.kind != .Directory and entry.kind != .SymLink) continue;
+ if (entry.kind != .directory and entry.kind != .sym_link) continue;
const name = entry.name;
const sliced = SlicedString.init(name, name);
const parsed = Semver.Version.parse(sliced, allocator);
@@ -2305,7 +2305,7 @@ pub const PackageManager = struct {
};
// TODO: make this fewer passes
- std.sort.sort(
+ std.sort.block(
Semver.Version,
installed_versions.items,
@as([]const u8, tags_buf.items),
@@ -3752,7 +3752,7 @@ pub const PackageManager = struct {
if (comptime log_level.isVerbose()) {
Output.prettyError(" ", .{});
- Output.printElapsed(@intToFloat(f64, task.http.elapsed) / std.time.ns_per_ms);
+ Output.printElapsed(@floatFromInt(f64, task.http.elapsed) / std.time.ns_per_ms);
Output.prettyError("\n <d>Downloaded <r><green>{s}<r> versions\n", .{name.slice()});
Output.flush();
}
@@ -3886,7 +3886,7 @@ pub const PackageManager = struct {
if (comptime log_level.isVerbose()) {
Output.prettyError(" ", .{});
- Output.printElapsed(@floatCast(f64, @intToFloat(f64, task.http.elapsed) / std.time.ns_per_ms));
+ Output.printElapsed(@floatCast(f64, @floatFromInt(f64, task.http.elapsed) / std.time.ns_per_ms));
Output.prettyError(" <d>Downloaded <r><green>{s}<r> tarball\n", .{extract.name.slice()});
Output.flush();
}
@@ -4814,7 +4814,7 @@ pub const PackageManager = struct {
var new_dependencies = try allocator.alloc(G.Property, dependencies.len + remaining - replacing);
bun.copy(G.Property, new_dependencies, dependencies);
- std.mem.set(G.Property, new_dependencies[dependencies.len..], G.Property{});
+ @memset(new_dependencies[dependencies.len..], G.Property{});
outer: for (updates) |*update| {
if (update.e_string != null) continue;
@@ -6372,7 +6372,7 @@ pub const PackageManager = struct {
var iter: std.fs.IterableDir.Iterator = node_modules_bin.iterate();
iterator: while (iter.next() catch null) |entry| {
switch (entry.kind) {
- std.fs.IterableDir.Entry.Kind.SymLink => {
+ std.fs.IterableDir.Entry.Kind.sym_link => {
// any symlinks which we are unable to open are assumed to be dangling
// note that using access won't work here, because access doesn't resolve symlinks
@@ -6547,7 +6547,7 @@ pub const PackageManager = struct {
if (folder.len == 0 or (folder.len == 1 and folder[0] == '.')) {
installer.cache_dir_subpath = ".";
} else {
- @memcpy(&this.folder_path_buf, folder.ptr, folder.len);
+ @memcpy(this.folder_path_buf[0..folder.len], folder);
this.folder_path_buf[folder.len] = 0;
installer.cache_dir_subpath = this.folder_path_buf[0..folder.len :0];
}
@@ -6567,7 +6567,7 @@ pub const PackageManager = struct {
if (folder.len == 0 or (folder.len == 1 and folder[0] == '.')) {
installer.cache_dir_subpath = ".";
} else {
- @memcpy(&this.folder_path_buf, folder.ptr, folder.len);
+ @memcpy(this.folder_path_buf[0..folder.len], folder);
this.folder_path_buf[folder.len] = 0;
installer.cache_dir_subpath = this.folder_path_buf[0..folder.len :0];
}
@@ -6608,16 +6608,16 @@ pub const PackageManager = struct {
const global_link_dir = this.manager.globalLinkDirPath() catch unreachable;
var ptr = &this.folder_path_buf;
var remain: []u8 = this.folder_path_buf[0..];
- @memcpy(ptr, global_link_dir.ptr, global_link_dir.len);
+ @memcpy(ptr[0..global_link_dir.len], global_link_dir);
remain = remain[global_link_dir.len..];
if (global_link_dir[global_link_dir.len - 1] != std.fs.path.sep) {
remain[0] = std.fs.path.sep;
remain = remain[1..];
}
- @memcpy(remain.ptr, folder.ptr, folder.len);
+ @memcpy(remain[0..folder.len], folder);
remain = remain[folder.len..];
remain[0] = 0;
- const len = @ptrToInt(remain.ptr) - @ptrToInt(ptr);
+ const len = @intFromPtr(remain.ptr) - @intFromPtr(ptr);
installer.cache_dir_subpath = this.folder_path_buf[0..len :0];
installer.cache_dir = directory;
}
@@ -6626,7 +6626,7 @@ pub const PackageManager = struct {
}
const needs_install = this.force_install or this.skip_verify_installed_version_number or !installer.verify(resolution, buf);
- this.summary.skipped += @as(u32, @boolToInt(!needs_install));
+ this.summary.skipped += @as(u32, @intFromBool(!needs_install));
if (needs_install) {
const result: PackageInstall.Result = switch (resolution.tag) {
@@ -6637,7 +6637,7 @@ pub const PackageManager = struct {
switch (result) {
.success => {
const is_duplicate = this.successfully_installed.isSet(package_id);
- this.summary.success += @as(u32, @boolToInt(!is_duplicate));
+ this.summary.success += @as(u32, @intFromBool(!is_duplicate));
this.successfully_installed.set(package_id);
if (comptime log_level.showProgress()) {
@@ -7390,7 +7390,7 @@ pub const PackageManager = struct {
);
}
var mapping = try manager.lockfile.allocator.alloc(PackageID, maybe_root.dependencies.len);
- std.mem.set(PackageID, mapping, invalid_package_id);
+ @memset(mapping, invalid_package_id);
manager.summary = try Package.Diff.generate(
ctx.allocator,
@@ -7443,8 +7443,8 @@ pub const PackageManager = struct {
var resolutions = manager.lockfile.buffers.resolutions.items.ptr[off .. off + len];
// It is too easy to accidentally undefined memory
- std.mem.set(PackageID, resolutions, invalid_package_id);
- std.mem.set(Dependency, dependencies, Dependency{});
+ @memset(resolutions, invalid_package_id);
+ @memset(dependencies, Dependency{});
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];
diff --git a/src/install/integrity.zig b/src/install/integrity.zig
index e54d9b7e1..19e55c223 100644
--- a/src/install/integrity.zig
+++ b/src/install/integrity.zig
@@ -41,7 +41,7 @@ pub const Integrity = extern struct {
var i: usize = 0;
{
- std.mem.set(u8, &integrity.value, 0);
+ @memset(&integrity.value, 0);
}
while (i < end) {
@@ -111,7 +111,7 @@ pub const Integrity = extern struct {
_,
pub inline fn isSupported(this: Tag) bool {
- return @enumToInt(this) >= @enumToInt(Tag.sha1) and @enumToInt(this) <= @enumToInt(Tag.sha512);
+ return @intFromEnum(this) >= @intFromEnum(Tag.sha1) and @intFromEnum(this) <= @intFromEnum(Tag.sha512);
}
pub fn parse(buf: []const u8) Tag {
diff --git a/src/install/lockfile.zig b/src/install/lockfile.zig
index 5c27c1a69..04c6ccec1 100644
--- a/src/install/lockfile.zig
+++ b/src/install/lockfile.zig
@@ -693,8 +693,7 @@ pub fn cleanWithLogger(old: *Lockfile, updates: []PackageManager.UpdateRequest,
const root = old.rootPackage() orelse return error.NoPackage;
var package_id_mapping = try old.allocator.alloc(PackageID, old.packages.len);
- std.mem.set(
- PackageID,
+ @memset(
package_id_mapping,
invalid_package_id,
);
@@ -998,7 +997,7 @@ pub const Printer = struct {
const dependencies_buffer: []const Dependency = this.lockfile.buffers.dependencies.items;
const string_buf = this.lockfile.buffers.string_bytes.items;
var id_map = try default_allocator.alloc(DependencyID, this.updates.len);
- std.mem.set(DependencyID, id_map, invalid_package_id);
+ @memset(id_map, invalid_package_id);
defer if (id_map.len > 0) default_allocator.free(id_map);
visited.set(0);
@@ -1211,12 +1210,12 @@ pub const Printer = struct {
}
var dependency_versions = requested_version_start[0..j];
- if (dependency_versions.len > 1) std.sort.insertionSort(Dependency.Version, dependency_versions, string_buf, Dependency.Version.isLessThan);
+ if (dependency_versions.len > 1) std.sort.insertion(Dependency.Version, dependency_versions, string_buf, Dependency.Version.isLessThan);
try requested_versions.put(i, dependency_versions);
}
}
- std.sort.sort(
+ std.sort.block(
PackageID,
alphabetized_names,
Lockfile.Package.Alphabetizer{
@@ -1908,11 +1907,11 @@ pub const Package = extern struct {
field: string,
behavior: Behavior,
- pub const dependencies = DependencyGroup{ .prop = "dependencies", .field = "dependencies", .behavior = @intToEnum(Behavior, Behavior.normal) };
- pub const dev = DependencyGroup{ .prop = "devDependencies", .field = "dev_dependencies", .behavior = @intToEnum(Behavior, Behavior.dev) };
- pub const optional = DependencyGroup{ .prop = "optionalDependencies", .field = "optional_dependencies", .behavior = @intToEnum(Behavior, Behavior.optional) };
- pub const peer = DependencyGroup{ .prop = "peerDependencies", .field = "peer_dependencies", .behavior = @intToEnum(Behavior, Behavior.peer) };
- pub const workspaces = DependencyGroup{ .prop = "workspaces", .field = "workspaces", .behavior = @intToEnum(Behavior, Behavior.workspace) };
+ pub const dependencies = DependencyGroup{ .prop = "dependencies", .field = "dependencies", .behavior = @enumFromInt(Behavior, Behavior.normal) };
+ pub const dev = DependencyGroup{ .prop = "devDependencies", .field = "dev_dependencies", .behavior = @enumFromInt(Behavior, Behavior.dev) };
+ pub const optional = DependencyGroup{ .prop = "optionalDependencies", .field = "optional_dependencies", .behavior = @enumFromInt(Behavior, Behavior.optional) };
+ pub const peer = DependencyGroup{ .prop = "peerDependencies", .field = "peer_dependencies", .behavior = @enumFromInt(Behavior, Behavior.peer) };
+ pub const workspaces = DependencyGroup{ .prop = "workspaces", .field = "workspaces", .behavior = @enumFromInt(Behavior, Behavior.workspace) };
};
pub inline fn isDisabled(this: *const Lockfile.Package) bool {
@@ -2032,7 +2031,7 @@ pub const Package = extern struct {
builder.clamp();
- cloner.trees_count += @as(u32, @boolToInt(old_resolutions.len > 0));
+ cloner.trees_count += @as(u32, @intFromBool(old_resolutions.len > 0));
for (old_resolutions, 0..) |old_resolution, i| {
if (old_resolution >= max_package_id) continue;
@@ -2108,7 +2107,7 @@ pub const Package = extern struct {
if (comptime Environment.allow_assert) std.debug.assert(dependencies_list.items.len == resolutions_list.items.len);
var dependencies: []Dependency = dependencies_list.items.ptr[dependencies_list.items.len..total_len];
- std.mem.set(Dependency, dependencies, Dependency{});
+ @memset(dependencies, Dependency{});
const package_dependencies = package_json.dependencies.map.values();
const source_buf = package_json.dependencies.source_buf;
@@ -2135,7 +2134,7 @@ pub const Package = extern struct {
const new_length = package.dependencies.len + dependencies_list.items.len;
- std.mem.set(PackageID, resolutions_list.items.ptr[package.dependencies.off .. package.dependencies.off + package.dependencies.len], invalid_package_id);
+ @memset(resolutions_list.items.ptr[package.dependencies.off .. package.dependencies.off + package.dependencies.len], invalid_package_id);
dependencies_list.items = dependencies_list.items.ptr[0..new_length];
resolutions_list.items = resolutions_list.items.ptr[0..new_length];
@@ -2160,10 +2159,10 @@ pub const Package = extern struct {
const dependency_groups = comptime brk: {
var out_groups: [
- @as(usize, @boolToInt(features.dependencies)) +
- @as(usize, @boolToInt(features.dev_dependencies)) +
- @as(usize, @boolToInt(features.optional_dependencies)) +
- @as(usize, @boolToInt(features.peer_dependencies))
+ @as(usize, @intFromBool(features.dependencies)) +
+ @as(usize, @intFromBool(features.dev_dependencies)) +
+ @as(usize, @intFromBool(features.optional_dependencies)) +
+ @as(usize, @intFromBool(features.peer_dependencies))
]DependencyGroup = undefined;
var out_group_i: usize = 0;
@@ -2252,7 +2251,7 @@ pub const Package = extern struct {
if (comptime Environment.allow_assert) std.debug.assert(dependencies_list.items.len == resolutions_list.items.len);
var dependencies = dependencies_list.items.ptr[dependencies_list.items.len..total_len];
- std.mem.set(Dependency, dependencies, .{});
+ @memset(dependencies, .{});
total_dependencies_count = 0;
inline for (dependency_groups) |group| {
@@ -2323,7 +2322,7 @@ pub const Package = extern struct {
const new_length = package.dependencies.len + dependencies_list.items.len;
- std.mem.set(PackageID, resolutions_list.items.ptr[package.dependencies.off .. package.dependencies.off + package.dependencies.len], invalid_package_id);
+ @memset(resolutions_list.items.ptr[package.dependencies.off .. package.dependencies.off + package.dependencies.len], invalid_package_id);
dependencies_list.items = dependencies_list.items.ptr[0..new_length];
resolutions_list.items = resolutions_list.items.ptr[0..new_length];
@@ -2408,7 +2407,7 @@ pub const Package = extern struct {
};
pub fn hash(name: string, version: Semver.Version) u64 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(name);
hasher.update(std.mem.asBytes(&version));
return hasher.final();
@@ -2966,11 +2965,11 @@ pub const Package = extern struct {
const dependency_groups = comptime brk: {
var out_groups: [
- @as(usize, @boolToInt(features.dependencies)) +
- @as(usize, @boolToInt(features.dev_dependencies)) +
- @as(usize, @boolToInt(features.optional_dependencies)) +
- @as(usize, @boolToInt(features.peer_dependencies)) +
- @as(usize, @boolToInt(features.workspaces))
+ @as(usize, @intFromBool(features.dependencies)) +
+ @as(usize, @intFromBool(features.dev_dependencies)) +
+ @as(usize, @intFromBool(features.optional_dependencies)) +
+ @as(usize, @intFromBool(features.peer_dependencies)) +
+ @as(usize, @intFromBool(features.workspaces))
]DependencyGroup = undefined;
var out_group_i: usize = 0;
@@ -3320,7 +3319,7 @@ pub const Package = extern struct {
}
}
- std.sort.sort(
+ std.sort.block(
Dependency,
package_dependencies[0..total_dependencies_count],
lockfile.buffers.string_bytes.items,
@@ -3332,7 +3331,7 @@ pub const Package = extern struct {
package.resolutions = @bitCast(@TypeOf(package.resolutions), package.dependencies);
- std.mem.set(PackageID, lockfile.buffers.resolutions.items.ptr[off..total_len], invalid_package_id);
+ @memset(lockfile.buffers.resolutions.items.ptr[off..total_len], invalid_package_id);
const new_len = off + total_dependencies_count;
lockfile.buffers.dependencies.items = lockfile.buffers.dependencies.items.ptr[0..new_len];
@@ -3397,7 +3396,7 @@ pub const Package = extern struct {
}
};
var trash: i32 = undefined; // workaround for stage1 compiler bug
- std.sort.sort(Data, &data, &trash, Sort.lessThan);
+ std.sort.block(Data, &data, &trash, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var field_indexes: [fields.len]usize = undefined;
var Types: [fields.len]type = undefined;
@@ -3492,10 +3491,10 @@ pub const Package = extern struct {
var bytes = std.mem.sliceAsBytes(sliced.items(@field(Lockfile.Package.List.Field, field.name)));
const end_pos = stream.pos + bytes.len;
if (end_pos <= end_at) {
- @memcpy(bytes.ptr, stream.buffer[stream.pos..].ptr, bytes.len);
+ @memcpy(bytes, stream.buffer[stream.pos..][0..bytes.len]);
stream.pos = end_pos;
} else if (comptime strings.eqlComptime(field.name, "scripts")) {
- @memset(bytes.ptr, 0, bytes.len);
+ @memset(bytes, 0);
} else {
return error.@"Lockfile validation failed: invalid package list range";
}
@@ -3564,7 +3563,7 @@ const Buffers = struct {
}
};
var trash: i32 = undefined; // workaround for stage1 compiler bug
- std.sort.sort(Data, &data, &trash, Sort.lessThan);
+ std.sort.block(Data, &data, &trash, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var names: [fields.len][]const u8 = undefined;
var types: [fields.len]type = undefined;
@@ -3808,7 +3807,7 @@ pub const Serializer = struct {
var writer = stream.writer();
try writer.writeAll(header_bytes);
- try writer.writeIntLittle(u32, @enumToInt(this.format));
+ try writer.writeIntLittle(u32, @intFromEnum(this.format));
try writer.writeAll(&this.meta_hash);
@@ -3840,7 +3839,7 @@ pub const Serializer = struct {
}
var format = try reader.readIntLittle(u32);
- if (format != @enumToInt(Lockfile.FormatVersion.current)) {
+ if (format != @intFromEnum(Lockfile.FormatVersion.current)) {
return error.@"Outdated lockfile version";
}
@@ -3928,7 +3927,7 @@ fn generateMetaHash(this: *Lockfile, print_name_version_string: bool) !MetaHash
}
}
- std.sort.sort(
+ std.sort.block(
PackageID,
alphabetized_names,
Lockfile.Package.Alphabetizer{
diff --git a/src/install/npm.zig b/src/install/npm.zig
index c01e6ee1f..074041056 100644
--- a/src/install/npm.zig
+++ b/src/install/npm.zig
@@ -121,9 +121,9 @@ pub const Registry = struct {
if (registry.username.len > 0 and registry.password.len > 0 and auth.len == 0) {
var output_buf = try allocator.alloc(u8, registry.username.len + registry.password.len + 1 + std.base64.standard.Encoder.calcSize(registry.username.len + registry.password.len + 1));
var input_buf = output_buf[0 .. registry.username.len + registry.password.len + 1];
- @memcpy(input_buf.ptr, registry.username.ptr, registry.username.len);
+ @memcpy(input_buf[0..registry.username.len], registry.username);
input_buf[registry.username.len] = ':';
- @memcpy(input_buf[registry.username.len + 1 ..].ptr, registry.password.ptr, registry.password.len);
+ @memcpy(input_buf[registry.username.len + 1 ..][0..registry.password.len], registry.password);
output_buf = output_buf[input_buf.len..];
auth = std.base64.standard.Encoder.encode(output_buf, input_buf);
break :outer;
@@ -259,9 +259,9 @@ pub const OperatingSystem = enum(u16) {
pub fn isMatch(this: OperatingSystem) bool {
if (comptime Environment.isLinux) {
- return (@enumToInt(this) & linux) != 0;
+ return (@intFromEnum(this) & linux) != 0;
} else if (comptime Environment.isMac) {
- return (@enumToInt(this) & darwin) != 0;
+ return (@intFromEnum(this) & darwin) != 0;
} else {
return false;
}
@@ -282,7 +282,7 @@ pub const OperatingSystem = enum(u16) {
if (str.len == 0) {
return this_;
}
- const this = @enumToInt(this_);
+ const this = @intFromEnum(this_);
const is_not = str[0] == '!';
const offset: usize = if (str[0] == '!') 1 else 0;
@@ -290,9 +290,9 @@ pub const OperatingSystem = enum(u16) {
const field: u16 = NameMap.get(str[offset..]) orelse return this_;
if (is_not) {
- return @intToEnum(OperatingSystem, this & ~field);
+ return @enumFromInt(OperatingSystem, this & ~field);
} else {
- return @intToEnum(OperatingSystem, this | field);
+ return @enumFromInt(OperatingSystem, this | field);
}
}
};
@@ -334,9 +334,9 @@ pub const Architecture = enum(u16) {
pub fn isMatch(this: Architecture) bool {
if (comptime Environment.isAarch64) {
- return (@enumToInt(this) & arm64) != 0;
+ return (@intFromEnum(this) & arm64) != 0;
} else if (comptime Environment.isX64) {
- return (@enumToInt(this) & x64) != 0;
+ return (@intFromEnum(this) & x64) != 0;
} else {
return false;
}
@@ -346,7 +346,7 @@ pub const Architecture = enum(u16) {
if (str.len == 0) {
return this_;
}
- const this = @enumToInt(this_);
+ const this = @intFromEnum(this_);
const is_not = str[0] == '!';
const offset: usize = if (str[0] == '!') 1 else 0;
@@ -355,9 +355,9 @@ pub const Architecture = enum(u16) {
const field: u16 = NameMap.get(input) orelse return this_;
if (is_not) {
- return @intToEnum(Architecture, this & ~field);
+ return @enumFromInt(Architecture, this & ~field);
} else {
- return @intToEnum(Architecture, this | field);
+ return @enumFromInt(Architecture, this | field);
}
}
};
@@ -496,7 +496,7 @@ pub const PackageManifest = struct {
}
};
var trash: i32 = undefined; // workaround for stage1 compiler bug
- std.sort.sort(Data, &data, &trash, Sort.lessThan);
+ std.sort.block(Data, &data, &trash, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var names: [fields.len][]const u8 = undefined;
for (data, 0..) |elem, i| {
@@ -571,7 +571,7 @@ pub const PackageManifest = struct {
}
pub fn save(this: *const PackageManifest, tmpdir: std.fs.IterableDir, cache_dir: std.fs.IterableDir) !void {
- const file_id = std.hash.Wyhash.hash(0, this.name());
+ const file_id = bun.Wyhash.hash(0, this.name());
var dest_path_buf: [512 + 64]u8 = undefined;
var out_path_buf: ["-18446744073709551615".len + ".npm".len + 1]u8 = undefined;
var dest_path_stream = std.io.fixedBufferStream(&dest_path_buf);
@@ -588,7 +588,7 @@ pub const PackageManifest = struct {
}
pub fn load(allocator: std.mem.Allocator, cache_dir: std.fs.IterableDir, package_name: string) !?PackageManifest {
- const file_id = std.hash.Wyhash.hash(0, package_name);
+ const file_id = bun.Wyhash.hash(0, package_name);
var file_path_buf: [512 + 64]u8 = undefined;
const hex_fmt = bun.fmt.hexIntLower(file_id);
var file_path = try std.fmt.bufPrintZ(&file_path_buf, "{any}.npm", .{hex_fmt});
@@ -630,7 +630,7 @@ pub const PackageManifest = struct {
inline for (sizes.fields) |field_name| {
if (comptime strings.eqlComptime(field_name, "pkg")) {
- pkg_stream.pos = std.mem.alignForward(pkg_stream.pos, @alignOf(Npm.NpmPackage));
+ pkg_stream.pos = std.mem.alignForward(usize, pkg_stream.pos, @alignOf(Npm.NpmPackage));
var reader = pkg_stream.reader();
package_manifest.pkg = try reader.readStruct(NpmPackage);
} else {
@@ -851,7 +851,7 @@ pub const PackageManifest = struct {
pre_versions_len += 1;
extern_string_count += 1;
} else {
- extern_string_count += @as(usize, @boolToInt(std.mem.indexOfScalar(u8, version_name, '+') != null));
+ extern_string_count += @as(usize, @intFromBool(std.mem.indexOfScalar(u8, version_name, '+') != null));
release_versions_len += 1;
}
@@ -862,7 +862,7 @@ pub const PackageManifest = struct {
if (tarball_prop.data == .e_string) {
const tarball = tarball_prop.data.e_string.slice(allocator);
string_builder.count(tarball);
- tarball_urls_count += @as(usize, @boolToInt(tarball.len > 0));
+ tarball_urls_count += @as(usize, @intFromBool(tarball.len > 0));
}
}
}
@@ -961,19 +961,19 @@ pub const PackageManifest = struct {
if (versioned_packages.len > 0) {
var versioned_packages_bytes = std.mem.sliceAsBytes(versioned_packages);
- @memset(versioned_packages_bytes.ptr, 0, versioned_packages_bytes.len);
+ @memset(versioned_packages_bytes, 0);
}
if (all_semver_versions.len > 0) {
var all_semver_versions_bytes = std.mem.sliceAsBytes(all_semver_versions);
- @memset(all_semver_versions_bytes.ptr, 0, all_semver_versions_bytes.len);
+ @memset(all_semver_versions_bytes, 0);
}
if (all_extern_strings.len > 0) {
var all_extern_strings_bytes = std.mem.sliceAsBytes(all_extern_strings);
- @memset(all_extern_strings_bytes.ptr, 0, all_extern_strings_bytes.len);
+ @memset(all_extern_strings_bytes, 0);
}
if (version_extern_strings.len > 0) {
var version_extern_strings_bytes = std.mem.sliceAsBytes(version_extern_strings);
- @memset(version_extern_strings_bytes.ptr, 0, version_extern_strings_bytes.len);
+ @memset(version_extern_strings_bytes, 0);
}
var versioned_package_releases = versioned_packages[0..release_versions_len];
@@ -998,7 +998,7 @@ pub const PackageManifest = struct {
var string_buf: string = "";
if (string_builder.ptr) |ptr| {
// 0 it out for better determinism
- @memset(ptr, 0, string_builder.cap);
+ @memset(ptr[0..string_builder.cap], 0);
string_buf = ptr[0..string_builder.cap];
}
@@ -1253,8 +1253,8 @@ pub const PackageManifest = struct {
var this_names = dependency_names[0..count];
var this_versions = dependency_values[0..count];
- var name_hasher = std.hash.Wyhash.init(0);
- var version_hasher = std.hash.Wyhash.init(0);
+ var name_hasher = bun.Wyhash.init(0);
+ var version_hasher = bun.Wyhash.init(0);
const is_peer = comptime strings.eqlComptime(pair.prop, "peerDependencies");
@@ -1495,7 +1495,7 @@ pub const PackageManifest = struct {
if (src.len > 0) {
var dst = std.mem.sliceAsBytes(all_extern_strings[all_extern_strings.len - extern_strings.len ..]);
std.debug.assert(dst.len >= src.len);
- @memcpy(dst.ptr, src.ptr, src.len);
+ @memcpy(dst[0..src.len], src);
}
all_extern_strings = all_extern_strings[0 .. all_extern_strings.len - extern_strings.len];
diff --git a/src/install/resolution.zig b/src/install/resolution.zig
index 1bd88e78d..b1adb3d80 100644
--- a/src/install/resolution.zig
+++ b/src/install/resolution.zig
@@ -20,7 +20,7 @@ pub const Resolution = extern struct {
rhs_buf: []const u8,
) std.math.Order {
if (lhs.tag != rhs.tag) {
- return std.math.order(@enumToInt(lhs.tag), @enumToInt(rhs.tag));
+ return std.math.order(@intFromEnum(lhs.tag), @intFromEnum(rhs.tag));
}
return switch (lhs.tag) {
diff --git a/src/install/resolvers/folder_resolver.zig b/src/install/resolvers/folder_resolver.zig
index 90a2a414c..0ece2be7f 100644
--- a/src/install/resolvers/folder_resolver.zig
+++ b/src/install/resolvers/folder_resolver.zig
@@ -30,7 +30,7 @@ pub const FolderResolution = union(Tag) {
}
pub fn hash(normalized_path: string) u64 {
- return std.hash.Wyhash.hash(0, normalized_path);
+ return bun.hash(normalized_path);
}
fn NewResolver(comptime tag: Resolution.Tag) type {
@@ -95,9 +95,9 @@ pub const FolderResolution = union(Tag) {
.global, .cache_folder => {
const path = if (global_or_relative == .global) global_or_relative.global else global_or_relative.cache_folder;
if (path.len > 0) {
- const offset = path.len -| @as(usize, @boolToInt(path[path.len -| 1] == std.fs.path.sep));
+ const offset = path.len -| @as(usize, @intFromBool(path[path.len -| 1] == std.fs.path.sep));
if (offset > 0)
- @memcpy(remain.ptr, path.ptr, offset);
+ @memcpy(remain[0..offset], path[0..offset]);
remain = remain[offset..];
if (normalized.len > 0) {
if ((path[path.len - 1] != std.fs.path.sep) and (normalized[0] != std.fs.path.sep)) {
diff --git a/src/install/semver.zig b/src/install/semver.zig
index 9fd6b9c8d..c2730e7c7 100644
--- a/src/install/semver.zig
+++ b/src/install/semver.zig
@@ -263,7 +263,7 @@ pub const String = extern struct {
std.debug.assert(bun.isSliceInBuffer(in, buf));
return Pointer{
- .off = @truncate(u32, @ptrToInt(in.ptr) - @ptrToInt(buf.ptr)),
+ .off = @truncate(u32, @intFromPtr(in.ptr) - @intFromPtr(buf.ptr)),
.len = @truncate(u32, in.len),
};
}
@@ -311,7 +311,7 @@ pub const String = extern struct {
pub const StringPool = std.HashMap(u64, String, IdentityContext(u64), 80);
pub inline fn stringHash(buf: []const u8) u64 {
- return std.hash.Wyhash.hash(0, buf);
+ return bun.Wyhash.hash(0, buf);
}
pub inline fn count(this: *Builder, slice_: string) void {
@@ -515,7 +515,7 @@ pub const ExternalString = extern struct {
pub inline fn from(in: string) ExternalString {
return ExternalString{
.value = String.init(in, in),
- .hash = std.hash.Wyhash.hash(0, in),
+ .hash = bun.Wyhash.hash(0, in),
};
}
@@ -552,15 +552,15 @@ pub const BigExternalString = extern struct {
return BigExternalString{
.off = 0,
.len = @truncate(u32, in.len),
- .hash = std.hash.Wyhash.hash(0, in),
+ .hash = bun.Wyhash.hash(0, in),
};
}
pub inline fn init(buf: string, in: string, hash: u64) BigExternalString {
- std.debug.assert(@ptrToInt(buf.ptr) <= @ptrToInt(in.ptr) and ((@ptrToInt(in.ptr) + in.len) <= (@ptrToInt(buf.ptr) + buf.len)));
+ std.debug.assert(@intFromPtr(buf.ptr) <= @intFromPtr(in.ptr) and ((@intFromPtr(in.ptr) + in.len) <= (@intFromPtr(buf.ptr) + buf.len)));
return BigExternalString{
- .off = @truncate(u32, @ptrToInt(in.ptr) - @ptrToInt(buf.ptr)),
+ .off = @truncate(u32, @intFromPtr(in.ptr) - @intFromPtr(buf.ptr)),
.len = @truncate(u32, in.len),
.hash = hash,
};
@@ -580,19 +580,19 @@ pub const SlicedString = struct {
}
pub inline fn external(this: SlicedString) ExternalString {
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(this.buf.ptr) <= @ptrToInt(this.slice.ptr) and ((@ptrToInt(this.slice.ptr) + this.slice.len) <= (@ptrToInt(this.buf.ptr) + this.buf.len)));
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(this.buf.ptr) <= @intFromPtr(this.slice.ptr) and ((@intFromPtr(this.slice.ptr) + this.slice.len) <= (@intFromPtr(this.buf.ptr) + this.buf.len)));
- return ExternalString.init(this.buf, this.slice, std.hash.Wyhash.hash(0, this.slice));
+ return ExternalString.init(this.buf, this.slice, bun.Wyhash.hash(0, this.slice));
}
pub inline fn value(this: SlicedString) String {
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(this.buf.ptr) <= @ptrToInt(this.slice.ptr) and ((@ptrToInt(this.slice.ptr) + this.slice.len) <= (@ptrToInt(this.buf.ptr) + this.buf.len)));
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(this.buf.ptr) <= @intFromPtr(this.slice.ptr) and ((@intFromPtr(this.slice.ptr) + this.slice.len) <= (@intFromPtr(this.buf.ptr) + this.buf.len)));
return String.init(this.buf, this.slice);
}
pub inline fn sub(this: SlicedString, input: string) SlicedString {
- std.debug.assert(@ptrToInt(this.buf.ptr) <= @ptrToInt(this.buf.ptr) and ((@ptrToInt(input.ptr) + input.len) <= (@ptrToInt(this.buf.ptr) + this.buf.len)));
+ std.debug.assert(@intFromPtr(this.buf.ptr) <= @intFromPtr(this.buf.ptr) and ((@intFromPtr(input.ptr) + input.len) <= (@intFromPtr(this.buf.ptr) + this.buf.len)));
return SlicedString{ .buf = this.buf, .slice = input };
}
};
@@ -678,7 +678,7 @@ pub const Version = extern struct {
.build = this.tag.build.hash,
};
const bytes = std.mem.asBytes(&hashable);
- return std.hash.Wyhash.hash(0, bytes);
+ return bun.Wyhash.hash(0, bytes);
}
pub const Formatter = struct {
@@ -1814,7 +1814,7 @@ pub const Query = struct {
};
if (!hyphenate) i = rollback;
- i += @as(usize, @boolToInt(!hyphenate));
+ i += @as(usize, @intFromBool(!hyphenate));
if (hyphenate) {
const second_parsed = Version.parse(sliced.sub(input[i..]), allocator);
diff --git a/src/io/io_darwin.zig b/src/io/io_darwin.zig
index 902ae2ae4..8045cbdf6 100644
--- a/src/io/io_darwin.zig
+++ b/src/io/io_darwin.zig
@@ -245,7 +245,7 @@ const system = darwin;
pub fn asError(err: anytype) Errno {
const int = if (@typeInfo(@TypeOf(err)) == .Enum)
- @enumToInt(err)
+ @intFromEnum(err)
else
err;
@@ -772,7 +772,7 @@ fn flush(self: *IO, comptime _: @Type(.EnumLiteral)) !void {
continue;
}
- const completion = @intToPtr(*Completion, kevent.udata);
+ const completion = @ptrFromInt(*Completion, kevent.udata);
completion.next = null;
self.completed.push(completion);
}
@@ -837,7 +837,7 @@ fn flush_io(_: *IO, events: []Kevent64, io_pending_top: *?*Completion) usize {
.flags = @intCast(u16, event_info[2]),
.fflags = 0,
.data = 0,
- .udata = @ptrToInt(completion),
+ .udata = @intFromPtr(completion),
};
}
@@ -995,7 +995,7 @@ fn submitWithIncrementPending(
// Complete the Completion
return callback(
- @intToPtr(Context, @ptrToInt(_completion.context)),
+ @ptrFromInt(Context, @intFromPtr(_completion.context)),
_completion,
result,
);
@@ -1203,7 +1203,7 @@ pub fn connect(
const rc = system.getsockopt(op.socket, os.SOL.SOCKET, os.SO.ERROR, @ptrCast([*]u8, &err_code), &size);
assert(size == 4);
break :brk switch (darwin.getErrno(rc)) {
- .SUCCESS => switch (@intToEnum(os.E, err_code)) {
+ .SUCCESS => switch (@enumFromInt(os.E, err_code)) {
.SUCCESS => {},
.ACCES => error.PermissionDenied,
.PERM => error.PermissionDenied,
@@ -1351,7 +1351,7 @@ pub fn read(
op.buf,
op.len,
);
- return switch (@enumToInt(os.errno(rc))) {
+ return switch (@intFromEnum(os.errno(rc))) {
0 => @intCast(usize, rc),
os.EINTR => continue,
os.EAGAIN => error.WouldBlock,
diff --git a/src/io/io_linux.zig b/src/io/io_linux.zig
index 10e1ede0c..7603eabfd 100644
--- a/src/io/io_linux.zig
+++ b/src/io/io_linux.zig
@@ -428,7 +428,7 @@ pub const errno_map: [135]Errno = brk: {
};
pub fn asError(err: anytype) Errno {
const errnum = if (@typeInfo(@TypeOf(err)) == .Enum)
- @enumToInt(err)
+ @intFromEnum(err)
else
err;
return switch (errnum) {
@@ -463,7 +463,7 @@ has_queued: usize = 0,
wakeup_completion: Completion = undefined,
fn queueForWakeup(this: *@This(), comptime Type: type, ctx: Type, comptime cb: anytype) void {
- @memset(&this.eventfd_buf, 0, this.eventfd_buf.len);
+ @memset(&this.eventfd_buf, 0);
const Callback = struct {
pub fn callback(that: Type, completion: *Completion, _: ReadError!usize) void {
var io = @fieldParentPtr(IO, "wakeup_completion", completion);
@@ -640,7 +640,7 @@ fn flush(self: *IO, wait_nr: u32, timeouts: *usize, etime: *bool) !void {
fn flush_completions(self: *IO, wait_nr: u32, timeouts: *usize, etime: *bool) !void {
var cqes: [256]std.os.linux.io_uring_cqe = undefined;
var completion_byttes = std.mem.asBytes(&cqes);
- @memset(completion_byttes, 0, completion_byttes.len);
+ @memset(completion_byttes[0..completion_byttes.len], 0);
var wait_remaining = wait_nr;
while (true) {
// Guard against waiting indefinitely (if there are too few requests inflight),
@@ -660,7 +660,7 @@ fn flush_completions(self: *IO, wait_nr: u32, timeouts: *usize, etime: *bool) !v
if (-cqe.res == os.ETIME) etime.* = true;
continue;
}
- const completion = @intToPtr(*Completion, @intCast(usize, cqe.user_data));
+ const completion = @ptrFromInt(*Completion, @intCast(usize, cqe.user_data));
completion.result = cqe.res;
// We do not run the completion here (instead appending to a linked list) to avoid:
// * recursion through `flush_submissions()` and `flush_completions()`,
@@ -780,7 +780,7 @@ pub const Completion = struct {
);
},
}
- sqe.user_data = @ptrToInt(completion);
+ sqe.user_data = @intFromPtr(completion);
}
fn complete(completion: *Completion) void {
@@ -1107,9 +1107,9 @@ pub fn accept(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const AcceptError!os.socket_t, @ptrToInt(res)).*,
+ @ptrFromInt(*const AcceptError!os.socket_t, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1149,9 +1149,9 @@ pub fn close(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const CloseError!void, @ptrToInt(res)).*,
+ @ptrFromInt(*const CloseError!void, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1206,9 +1206,9 @@ pub fn connect(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const ConnectError!void, @ptrToInt(res)).*,
+ @ptrFromInt(*const ConnectError!void, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1257,9 +1257,9 @@ pub fn fsync(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const FsyncError!void, @ptrToInt(res)).*,
+ @ptrFromInt(*const FsyncError!void, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1303,9 +1303,9 @@ pub fn read(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const ReadError!usize, @ptrToInt(res)).*,
+ @ptrFromInt(*const ReadError!usize, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1355,9 +1355,9 @@ pub fn recv(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const RecvError!usize, @ptrToInt(res)).*,
+ @ptrFromInt(*const RecvError!usize, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1390,9 +1390,9 @@ pub fn readev(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const RecvError!usize, @ptrToInt(res)).*,
+ @ptrFromInt(*const RecvError!usize, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1446,9 +1446,9 @@ pub fn send(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const SendError!usize, @ptrToInt(res)).*,
+ @ptrFromInt(*const SendError!usize, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1538,9 +1538,9 @@ pub fn open(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const OpenError!linux.fd_t, @ptrToInt(res)).*,
+ @ptrFromInt(*const OpenError!linux.fd_t, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1575,9 +1575,9 @@ pub fn writev(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const SendError!usize, @ptrToInt(res)).*,
+ @ptrFromInt(*const SendError!usize, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1613,9 +1613,9 @@ pub fn timeout(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const TimeoutError!void, @ptrToInt(res)).*,
+ @ptrFromInt(*const TimeoutError!void, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1662,9 +1662,9 @@ pub fn write(
.callback = struct {
fn wrapper(ctx: ?*anyopaque, comp: *Completion, res: *const anyopaque) void {
callback(
- @intToPtr(Context, @ptrToInt(ctx)),
+ @ptrFromInt(Context, @intFromPtr(ctx)),
comp,
- @intToPtr(*const WriteError!usize, @ptrToInt(res)).*,
+ @ptrFromInt(*const WriteError!usize, @intFromPtr(res)).*,
);
}
}.wrapper,
@@ -1712,7 +1712,7 @@ const Syscall = struct {
.NOMEM => return error.SystemResources,
.PROTONOSUPPORT => return error.ProtocolNotSupported,
.PROTOTYPE => return error.SocketTypeNotSupported,
- else => |err| return asError(@enumToInt(err)),
+ else => |err| return asError(@intFromEnum(err)),
};
}
};
diff --git a/src/js_ast.zig b/src/js_ast.zig
index 707e83fa0..bd06ca6dc 100644
--- a/src/js_ast.zig
+++ b/src/js_ast.zig
@@ -38,8 +38,8 @@ pub fn NewBaseStore(comptime Union: anytype, comptime count: usize) type {
var max_size = 0;
var max_align = 1;
for (Union) |kind| {
- max_size = std.math.max(@sizeOf(kind), max_size);
- max_align = if (@sizeOf(kind) == 0) max_align else std.math.max(@alignOf(kind), max_align);
+ max_size = @max(@sizeOf(kind), max_size);
+ max_align = if (@sizeOf(kind) == 0) max_align else @max(@alignOf(kind), max_align);
}
const UnionValueType = [max_size]u8;
@@ -156,7 +156,7 @@ pub fn NewBaseStore(comptime Union: anytype, comptime count: usize) type {
if (comptime Environment.isDebug) {
// ensure we crash if we use a freed value
var bytes = std.mem.asBytes(&b.items);
- @memset(bytes, undefined, bytes.len);
+ @memset(bytes, undefined);
}
b.used = 0;
}
@@ -666,7 +666,7 @@ pub const CharFreq = struct {
break :brk _array;
};
- std.sort.sort(CharAndCount, &array, {}, CharAndCount.lessThan);
+ std.sort.block(CharAndCount, &array, {}, CharAndCount.lessThan);
var minifier = NameMinifier.init(allocator);
minifier.head.ensureTotalCapacityPrecise(NameMinifier.default_head.len) catch unreachable;
@@ -1158,7 +1158,7 @@ pub const Symbol = struct {
}
pub inline fn isPrivate(kind: Symbol.Kind) bool {
- return @enumToInt(kind) >= @enumToInt(Symbol.Kind.private_field) and @enumToInt(kind) <= @enumToInt(Symbol.Kind.private_static_get_set_pair);
+ return @intFromEnum(kind) >= @intFromEnum(Symbol.Kind.private_field) and @intFromEnum(kind) <= @intFromEnum(Symbol.Kind.private_static_get_set_pair);
}
pub inline fn isHoisted(kind: Symbol.Kind) bool {
@@ -1706,7 +1706,7 @@ pub const E = struct {
pub fn toStringFromF64Safe(value: f64, allocator: std.mem.Allocator) ?string {
if (value == @trunc(value) and (value < std.math.maxInt(i32) and value > std.math.minInt(i32))) {
- const int_value = @floatToInt(i64, value);
+ const int_value = @intFromFloat(i64, value);
const abs = @intCast(u64, std.math.absInt(int_value) catch return null);
if (abs < double_digit.len) {
return if (int_value < 0)
@@ -1735,22 +1735,22 @@ pub const E = struct {
pub inline fn toU64(self: Number) u64 {
@setRuntimeSafety(false);
- return @floatToInt(u64, @max(@trunc(self.value), 0));
+ return @intFromFloat(u64, @max(@trunc(self.value), 0));
}
pub inline fn toUsize(self: Number) usize {
@setRuntimeSafety(false);
- return @floatToInt(usize, @max(@trunc(self.value), 0));
+ return @intFromFloat(usize, @max(@trunc(self.value), 0));
}
pub inline fn toU32(self: Number) u32 {
@setRuntimeSafety(false);
- return @floatToInt(u32, @max(@trunc(self.value), 0));
+ return @intFromFloat(u32, @max(@trunc(self.value), 0));
}
pub inline fn toU16(self: Number) u16 {
@setRuntimeSafety(false);
- return @floatToInt(u16, @max(@trunc(self.value), 0));
+ return @intFromFloat(u16, @max(@trunc(self.value), 0));
}
pub fn jsonStringify(self: *const Number, opts: anytype, o: anytype) !void {
@@ -2057,11 +2057,11 @@ pub const E = struct {
}
pub fn alphabetizeProperties(this: *Object) void {
- std.sort.sort(G.Property, this.properties.slice(), {}, Sorter.isLessThan);
+ std.sort.block(G.Property, this.properties.slice(), {}, Sorter.isLessThan);
}
pub fn packageJSONSort(this: *Object) void {
- std.sort.sort(G.Property, this.properties.slice(), {}, PackageJSONSort.Fields.isLessThan);
+ std.sort.block(G.Property, this.properties.slice(), {}, PackageJSONSort.Fields.isLessThan);
}
const PackageJSONSort = struct {
@@ -2096,15 +2096,15 @@ pub const E = struct {
});
pub fn isLessThan(ctx: void, lhs: G.Property, rhs: G.Property) bool {
- var lhs_key_size: u8 = @enumToInt(Fields.__fake);
- var rhs_key_size: u8 = @enumToInt(Fields.__fake);
+ var lhs_key_size: u8 = @intFromEnum(Fields.__fake);
+ var rhs_key_size: u8 = @intFromEnum(Fields.__fake);
if (lhs.key != null and lhs.key.?.data == .e_string) {
- lhs_key_size = @enumToInt(Map.get(lhs.key.?.data.e_string.data) orelse Fields.__fake);
+ lhs_key_size = @intFromEnum(Map.get(lhs.key.?.data.e_string.data) orelse Fields.__fake);
}
if (rhs.key != null and rhs.key.?.data == .e_string) {
- rhs_key_size = @enumToInt(Map.get(rhs.key.?.data.e_string.data) orelse Fields.__fake);
+ rhs_key_size = @intFromEnum(Map.get(rhs.key.?.data.e_string.data) orelse Fields.__fake);
}
return switch (std.math.order(lhs_key_size, rhs_key_size)) {
@@ -2343,10 +2343,10 @@ pub const E = struct {
if (s.isUTF8()) {
// hash utf-8
- return std.hash.Wyhash.hash(0, s.data);
+ return bun.hash(s.data);
} else {
// hash utf-16
- return std.hash.Wyhash.hash(0, @ptrCast([*]const u8, s.slice16().ptr)[0 .. s.slice16().len * 2]);
+ return bun.hash(@ptrCast([*]const u8, s.slice16().ptr)[0 .. s.slice16().len * 2]);
}
}
@@ -3100,7 +3100,7 @@ pub const Expr = struct {
pub fn hasAnyPropertyNamed(expr: *const Expr, comptime names: []const string) bool {
if (std.meta.activeTag(expr.data) != .e_object) return false;
const obj = expr.data.e_object;
- if (@ptrToInt(obj.properties.ptr) == 0) return false;
+ if (@intFromPtr(obj.properties.ptr) == 0) return false;
for (obj.properties.slice()) |prop| {
if (prop.value == null) continue;
@@ -3162,7 +3162,7 @@ pub const Expr = struct {
pub fn asProperty(expr: *const Expr, name: string) ?Query {
if (std.meta.activeTag(expr.data) != .e_object) return null;
const obj = expr.data.e_object;
- if (@ptrToInt(obj.properties.ptr) == 0) return null;
+ if (@intFromPtr(obj.properties.ptr) == 0) return null;
return obj.asProperty(name);
}
@@ -3183,7 +3183,7 @@ pub const Expr = struct {
pub fn asArray(expr: *const Expr) ?ArrayIterator {
if (std.meta.activeTag(expr.data) != .e_array) return null;
const array = expr.data.e_array;
- if (array.items.len == 0 or @ptrToInt(array.items.ptr) == 0) return null;
+ if (array.items.len == 0 or @intFromPtr(array.items.ptr) == 0) return null;
return ArrayIterator{ .array = array, .index = 0 };
}
@@ -3290,7 +3290,7 @@ pub const Expr = struct {
}
}
- pub fn joinAllWithCommaCallback(all: []Expr, comptime Context: type, ctx: Context, callback: (fn (ctx: anytype, expr: anytype) ?Expr), allocator: std.mem.Allocator) ?Expr {
+ pub fn joinAllWithCommaCallback(all: []Expr, comptime Context: type, ctx: Context, comptime callback: (fn (ctx: anytype, expr: Expr) ?Expr), allocator: std.mem.Allocator) ?Expr {
switch (all.len) {
0 => return null,
1 => {
@@ -3637,7 +3637,7 @@ pub const Expr = struct {
if (comptime Environment.isDebug) {
// Sanity check: assert string is not a null ptr
if (st.data.len > 0 and st.isUTF8()) {
- std.debug.assert(@ptrToInt(st.data.ptr) > 0);
+ std.debug.assert(@intFromPtr(st.data.ptr) > 0);
}
}
return Expr{
@@ -4002,7 +4002,7 @@ pub const Expr = struct {
if (comptime Environment.isDebug) {
// Sanity check: assert string is not a null ptr
if (st.data.len > 0 and st.isUTF8()) {
- std.debug.assert(@ptrToInt(st.data.ptr) > 0);
+ std.debug.assert(@intFromPtr(st.data.ptr) > 0);
}
}
return Expr{
@@ -5692,9 +5692,9 @@ pub const Op = struct {
}
pub fn unaryAssignTarget(code: Op.Code) AssignTarget {
- if (@enumToInt(code) >=
- @enumToInt(Op.Code.un_pre_dec) and @enumToInt(code) <=
- @enumToInt(Op.Code.un_post_inc))
+ if (@intFromEnum(code) >=
+ @intFromEnum(Op.Code.un_pre_dec) and @intFromEnum(code) <=
+ @intFromEnum(Op.Code.un_post_inc))
{
return AssignTarget.update;
}
@@ -5702,19 +5702,19 @@ pub const Op = struct {
return AssignTarget.none;
}
pub fn isLeftAssociative(code: Op.Code) bool {
- return @enumToInt(code) >=
- @enumToInt(Op.Code.bin_add) and
- @enumToInt(code) < @enumToInt(Op.Code.bin_comma) and code != .bin_pow;
+ return @intFromEnum(code) >=
+ @intFromEnum(Op.Code.bin_add) and
+ @intFromEnum(code) < @intFromEnum(Op.Code.bin_comma) and code != .bin_pow;
}
pub fn isRightAssociative(code: Op.Code) bool {
- return @enumToInt(code) >= @enumToInt(Op.Code.bin_assign) or code == .bin_pow;
+ return @intFromEnum(code) >= @intFromEnum(Op.Code.bin_assign) or code == .bin_pow;
}
pub fn binaryAssignTarget(code: Op.Code) AssignTarget {
if (code == .bin_assign) {
return AssignTarget.replace;
}
- if (@enumToInt(code) > @enumToInt(Op.Code.bin_assign)) {
+ if (@intFromEnum(code) > @intFromEnum(Op.Code.bin_assign)) {
return AssignTarget.update;
}
@@ -5722,7 +5722,7 @@ pub const Op = struct {
}
pub fn isPrefix(code: Op.Code) bool {
- return @enumToInt(code) < @enumToInt(Op.Code.un_post_dec);
+ return @intFromEnum(code) < @intFromEnum(Op.Code.un_post_dec);
}
};
@@ -5752,27 +5752,27 @@ pub const Op = struct {
member,
pub inline fn lt(self: Level, b: Level) bool {
- return @enumToInt(self) < @enumToInt(b);
+ return @intFromEnum(self) < @intFromEnum(b);
}
pub inline fn gt(self: Level, b: Level) bool {
- return @enumToInt(self) > @enumToInt(b);
+ return @intFromEnum(self) > @intFromEnum(b);
}
pub inline fn gte(self: Level, b: Level) bool {
- return @enumToInt(self) >= @enumToInt(b);
+ return @intFromEnum(self) >= @intFromEnum(b);
}
pub inline fn lte(self: Level, b: Level) bool {
- return @enumToInt(self) <= @enumToInt(b);
+ return @intFromEnum(self) <= @intFromEnum(b);
}
pub inline fn eql(self: Level, b: Level) bool {
- return @enumToInt(self) == @enumToInt(b);
+ return @intFromEnum(self) == @intFromEnum(b);
}
pub inline fn sub(self: Level, i: anytype) Level {
- return @intToEnum(Level, @enumToInt(self) - i);
+ return @enumFromInt(Level, @intFromEnum(self) - i);
}
pub inline fn addF(self: Level, i: anytype) Level {
- return @intToEnum(Level, @enumToInt(self) + i);
+ return @enumFromInt(Level, @intFromEnum(self) + i);
}
};
@@ -6647,7 +6647,7 @@ pub const Scope = struct {
}
pub inline fn kindStopsHoisting(s: *const Scope) bool {
- return @enumToInt(s.kind) >= @enumToInt(Kind.entry);
+ return @intFromEnum(s.kind) >= @intFromEnum(Kind.entry);
}
};
@@ -7284,7 +7284,7 @@ pub const Macro = struct {
_: js.JSStringRef,
_: js.ExceptionRef,
) js.JSObjectRef {
- return JSC.JSValue.jsNumberFromU16(@intCast(u16, @enumToInt(std.meta.activeTag(this.data)))).asRef();
+ return JSC.JSValue.jsNumberFromU16(@intCast(u16, @intFromEnum(std.meta.activeTag(this.data)))).asRef();
}
pub fn getTagName(
this: *JSNode,
@@ -7691,7 +7691,7 @@ pub const Macro = struct {
var list = std.EnumArray(Tag, Expr.Data).initFill(Expr.Data{ .e_number = E.Number{ .value = 0.0 } });
const fields: []const std.builtin.Type.EnumField = @typeInfo(Tag).Enum.fields;
for (fields) |field| {
- list.set(@intToEnum(Tag, field.value), Expr.Data{ .e_number = E.Number{ .value = @intToFloat(f64, field.value) } });
+ list.set(@enumFromInt(Tag, field.value), Expr.Data{ .e_number = E.Number{ .value = @floatFromInt(f64, field.value) } });
}
break :brk list;
@@ -7868,7 +7868,7 @@ pub const Macro = struct {
const Enum: std.builtin.Type.Enum = @typeInfo(Tag).Enum;
var max_value: u8 = 0;
for (Enum.fields) |field| {
- max_value = std.math.max(@as(u8, field.value), max_value);
+ max_value = @max(@as(u8, field.value), max_value);
}
break :brk max_value;
};
@@ -7877,7 +7877,7 @@ pub const Macro = struct {
const Enum: std.builtin.Type.Enum = @typeInfo(Tag).Enum;
var min: u8 = 255;
for (Enum.fields) |field| {
- min = std.math.min(@as(u8, field.value), min);
+ min = @min(@as(u8, field.value), min);
}
break :brk min;
};
@@ -8007,7 +8007,7 @@ pub const Macro = struct {
Expr{
.data = .{
.e_number = E.Number{
- .value = @intToFloat(f64, @boolToInt(value.data.e_boolean.value)),
+ .value = @floatFromInt(f64, @intFromBool(value.data.e_boolean.value)),
},
},
.loc = value.loc,
@@ -8084,7 +8084,7 @@ pub const Macro = struct {
self.args.ensureUnusedCapacity(2 + children.len) catch unreachable;
self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = comptime Tag.ids.get(Tag.e_array) });
const children_count = @truncate(u16, children.len);
- self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = .{ .e_number = E.Number{ .value = @intToFloat(f64, children_count) } } });
+ self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = .{ .e_number = E.Number{ .value = @floatFromInt(f64, children_count) } } });
var old_parent = self.parent_tag;
self.parent_tag = Tag.e_array;
@@ -8123,7 +8123,7 @@ pub const Macro = struct {
self.args.ensureUnusedCapacity(2 + children.len) catch unreachable;
self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = comptime Tag.ids.get(Tag.e_object) });
const children_count = @truncate(u16, children.len);
- self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = .{ .e_number = E.Number{ .value = @intToFloat(f64, children_count) } } });
+ self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = .{ .e_number = E.Number{ .value = @floatFromInt(f64, children_count) } } });
var old_parent = self.parent_tag;
self.parent_tag = Tag.e_object;
@@ -8328,7 +8328,7 @@ pub const Macro = struct {
}
self.args.ensureUnusedCapacity(2 + count) catch unreachable;
self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = comptime Tag.ids.get(Tag.inline_inject) });
- self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = .{ .e_number = .{ .value = @intToFloat(f64, @intCast(u32, children.len)) } } });
+ self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = .{ .e_number = .{ .value = @floatFromInt(f64, @intCast(u32, children.len)) } } });
const old_parent_tag = self.parent_tag;
self.parent_tag = Tag.inline_inject;
@@ -8393,7 +8393,7 @@ pub const Macro = struct {
const namespace_ = propertyValueNamed(props, "namespace");
const items_count: u32 = 1 +
- @intCast(u32, @boolToInt(namespace_ != null));
+ @intCast(u32, @intFromBool(namespace_ != null));
self.args.ensureUnusedCapacity(items_count) catch unreachable;
self.args.appendAssumeCapacity(Expr{ .loc = loc, .data = comptime Tag.ids.get(Tag.s_import) });
@@ -8504,7 +8504,7 @@ pub const Macro = struct {
.loc = loc,
.data = .{
.e_number = E.Number{
- .value = @intToFloat(f64, children.len),
+ .value = @floatFromInt(f64, children.len),
},
},
});
@@ -8742,11 +8742,11 @@ pub const Macro = struct {
pub fn fromJSValueRefNoValidate(ctx: js.JSContextRef, value: js.JSValueRef) TagOrJSNode {
switch (js.JSValueGetType(ctx, value)) {
js.JSType.kJSTypeNumber => {
- const tag_int = @floatToInt(u8, JSC.JSValue.fromRef(value).asNumber());
+ const tag_int = @intFromFloat(u8, JSC.JSValue.fromRef(value).asNumber());
if (tag_int < Tag.min_tag or tag_int > Tag.max_tag) {
return TagOrJSNode{ .invalid = {} };
}
- return TagOrJSNode{ .tag = @intToEnum(JSNode.Tag, tag_int) };
+ return TagOrJSNode{ .tag = @enumFromInt(JSNode.Tag, tag_int) };
},
js.JSType.kJSTypeObject => {
if (JSCBase.GetJSPrivateData(JSNode, value)) |node| {
@@ -8764,13 +8764,13 @@ pub const Macro = struct {
pub fn fromJSValueRef(writer: *Writer, ctx: js.JSContextRef, value: js.JSValueRef) TagOrJSNode {
switch (js.JSValueGetType(ctx, value)) {
js.JSType.kJSTypeNumber => {
- const tag_int = @floatToInt(u8, JSC.JSValue.fromRef(value).asNumber());
+ const tag_int = @intFromFloat(u8, JSC.JSValue.fromRef(value).asNumber());
if (tag_int < Tag.min_tag or tag_int > Tag.max_tag) {
throwTypeError(ctx, "Node type has invalid value", writer.exception);
writer.errored = true;
return TagOrJSNode{ .invalid = {} };
}
- return TagOrJSNode{ .tag = @intToEnum(JSNode.Tag, tag_int) };
+ return TagOrJSNode{ .tag = @enumFromInt(JSNode.Tag, tag_int) };
},
js.JSType.kJSTypeObject => {
if (JSCBase.GetJSPrivateData(JSNode, value)) |node| {
@@ -8932,7 +8932,7 @@ pub const Macro = struct {
import.import.items = writer.allocator.alloc(
ClauseItem,
- @intCast(u32, @boolToInt(has_default)) + array_iter.len,
+ @intCast(u32, @intFromBool(has_default)) + array_iter.len,
) catch return false;
while (array_iter.next()) |name| {
@@ -8961,7 +8961,7 @@ pub const Macro = struct {
} else {
import.import.items = writer.allocator.alloc(
ClauseItem,
- @intCast(u32, @boolToInt(has_default)),
+ @intCast(u32, @intFromBool(has_default)),
) catch return false;
}
@@ -9000,7 +9000,7 @@ pub const Macro = struct {
var nextArg = writer.eatArg() orelse return false;
if (js.JSValueIsArray(writer.ctx, nextArg.asRef())) {
const extras = @truncate(u32, nextArg.getLength(writer.ctx.ptr()));
- count += std.math.max(@truncate(@TypeOf(count), extras), 1) - 1;
+ count += @max(@truncate(@TypeOf(count), extras), 1) - 1;
items.ensureUnusedCapacity(extras) catch unreachable;
items.expandToCapacity();
var new_writer = writer.*;
@@ -9919,7 +9919,7 @@ pub const Macro = struct {
},
.Integer => {
- return Expr.init(E.Number, E.Number{ .value = @intToFloat(f64, value.toInt32()) }, this.caller.loc);
+ return Expr.init(E.Number, E.Number{ .value = @floatFromInt(f64, value.toInt32()) }, this.caller.loc);
},
.Double => {
return Expr.init(E.Number, E.Number{ .value = value.asNumber() }, this.caller.loc);
@@ -9992,7 +9992,7 @@ pub const Macro = struct {
exception_holder = Zig.ZigException.Holder.init();
var js_args: []JSC.JSValue = &.{};
defer {
- for (js_args[0 .. js_args.len - @as(usize, @boolToInt(!javascript_object.isEmpty()))]) |arg| {
+ for (js_args[0 .. js_args.len - @as(usize, @intFromBool(!javascript_object.isEmpty()))]) |arg| {
arg.unprotect();
}
@@ -10004,7 +10004,7 @@ pub const Macro = struct {
switch (caller.data) {
.e_call => |call| {
const call_args: []Expr = call.args.slice();
- js_args = try allocator.alloc(JSC.JSValue, call_args.len + @as(usize, @boolToInt(!javascript_object.isEmpty())));
+ js_args = try allocator.alloc(JSC.JSValue, call_args.len + @as(usize, @intFromBool(!javascript_object.isEmpty())));
for (call_args, js_args[0..call_args.len]) |in, *out| {
const value = try in.toJS(
diff --git a/src/js_lexer.zig b/src/js_lexer.zig
index f87d28694..5d41aec4b 100644
--- a/src/js_lexer.zig
+++ b/src/js_lexer.zig
@@ -274,7 +274,7 @@ fn NewLexer_(
}
pub inline fn isIdentifierOrKeyword(lexer: LexerType) bool {
- return @enumToInt(lexer.token) >= @enumToInt(T.t_identifier);
+ return @intFromEnum(lexer.token) >= @intFromEnum(T.t_identifier);
}
pub fn deinit(this: *LexerType) void {
@@ -304,7 +304,7 @@ fn NewLexer_(
// Convert '\r\n' into '\n'
const next_i: usize = iter.i + 1;
- iter.i += @as(u32, @boolToInt(next_i < text.len and text[next_i] == '\n'));
+ iter.i += @as(u32, @intFromBool(next_i < text.len and text[next_i] == '\n'));
// Convert '\r' into '\n'
buf.append('\n') catch unreachable;
@@ -572,7 +572,7 @@ fn NewLexer_(
// Make sure Windows CRLF counts as a single newline
const next_i: usize = iter.i + 1;
- iter.i += @as(u32, @boolToInt(next_i < text.len and text[next_i] == '\n'));
+ iter.i += @as(u32, @intFromBool(next_i < text.len and text[next_i] == '\n'));
// Ignore line continuations. A line continuation is not an escaped newline.
continue;
@@ -819,7 +819,7 @@ fn NewLexer_(
// This count is approximate because it handles "\n" and "\r\n" (the common
// cases) but not "\r" or "\u2028" or "\u2029". Getting this wrong is harmless
// because it's only a preallocation. The array will just grow if it's too small.
- lexer.approximate_newline_count += @boolToInt(lexer.code_point == '\n');
+ lexer.approximate_newline_count += @intFromBool(lexer.code_point == '\n');
}
pub inline fn expect(self: *LexerType, comptime token: T) !void {
@@ -1784,7 +1784,7 @@ fn NewLexer_(
pub fn unexpected(lexer: *LexerType) !void {
const found = finder: {
- lexer.start = std.math.min(lexer.start, lexer.end);
+ lexer.start = @min(lexer.start, lexer.end);
if (lexer.start == lexer.source.contents.len) {
break :finder "end of file";
@@ -1868,7 +1868,7 @@ fn NewLexer_(
const at = @bitCast(strings.AsciiVectorU1, vec == @splat(strings.ascii_vector_size, @as(u8, '@')));
if (@reduce(.Max, hashtag + at) == 1) {
- rest.len = @ptrToInt(end) - @ptrToInt(rest.ptr);
+ rest.len = @intFromPtr(end) - @intFromPtr(rest.ptr);
if (comptime Environment.allow_assert) {
std.debug.assert(
strings.containsChar(&@as([strings.ascii_vector_size]u8, vec), '#') or
@@ -1918,7 +1918,7 @@ fn NewLexer_(
rest.ptr += strings.ascii_vector_size;
}
- rest.len = @ptrToInt(end) - @ptrToInt(rest.ptr);
+ rest.len = @intFromPtr(end) - @intFromPtr(rest.ptr);
}
if (comptime Environment.allow_assert)
@@ -1930,7 +1930,7 @@ fn NewLexer_(
switch (c) {
'@', '#' => {
const chunk = rest;
- const i = @ptrToInt(chunk.ptr) - @ptrToInt(text.ptr);
+ const i = @intFromPtr(chunk.ptr) - @intFromPtr(text.ptr);
if (!lexer.has_pure_comment_before) {
if (strings.hasPrefixWithWordBoundary(chunk, "__PURE__")) {
lexer.has_pure_comment_before = true;
@@ -2952,7 +2952,7 @@ fn NewLexer_(
for (text) |c| {
number = number * 10 + @intCast(u32, c - '0');
}
- lexer.number = @intToFloat(f64, number);
+ lexer.number = @floatFromInt(f64, number);
} else {
// Parse a double-precision floating-point number
if (bun.parseDouble(text)) |num| {
@@ -3155,7 +3155,7 @@ pub fn rangeOfIdentifier(source: *const Source, loc: logger.Loc) logger.Range {
}
inline fn float64(num: anytype) f64 {
- return @intToFloat(f64, num);
+ return @floatFromInt(f64, num);
}
pub fn isLatin1Identifier(comptime Buffer: type, name: Buffer) bool {
@@ -3226,7 +3226,7 @@ fn latin1IdentifierContinueLength(name: []const u8) usize {
}
return @as(usize, first) +
- @ptrToInt(wrapped.ptr) - @ptrToInt(name.ptr);
+ @intFromPtr(wrapped.ptr) - @intFromPtr(name.ptr);
}
}
}
@@ -3330,12 +3330,12 @@ fn skipToInterestingCharacterInMultilineComment(text_: []const u8) ?u32 {
const first = @ctz(bitmask);
std.debug.assert(first < strings.ascii_vector_size);
std.debug.assert(text.ptr[first] == '*' or text.ptr[first] == '\r' or text.ptr[first] == '\n' or text.ptr[first] > 127);
- return @truncate(u32, first + (@ptrToInt(text.ptr) - @ptrToInt(text_.ptr)));
+ return @truncate(u32, first + (@intFromPtr(text.ptr) - @intFromPtr(text_.ptr)));
}
text.ptr += strings.ascii_vector_size;
}
- return @truncate(u32, @ptrToInt(text.ptr) - @ptrToInt(text_.ptr));
+ return @truncate(u32, @intFromPtr(text.ptr) - @intFromPtr(text_.ptr));
}
fn indexOfInterestingCharacterInStringLiteral(text_: []const u8, quote: u8) ?usize {
@@ -3357,7 +3357,7 @@ fn indexOfInterestingCharacterInStringLiteral(text_: []const u8, quote: u8) ?usi
const bitmask = @bitCast(u16, any_significant);
const first = @ctz(bitmask);
std.debug.assert(first < strings.ascii_vector_size);
- return first + (@ptrToInt(text.ptr) - @ptrToInt(text_.ptr));
+ return first + (@intFromPtr(text.ptr) - @intFromPtr(text_.ptr));
}
text = text[strings.ascii_vector_size..];
}
diff --git a/src/js_lexer/identifier.zig b/src/js_lexer/identifier.zig
index 4a48b5d17..8c1a59c2b 100644
--- a/src/js_lexer/identifier.zig
+++ b/src/js_lexer/identifier.zig
@@ -1800,7 +1800,7 @@ pub const JumpTableInline = struct {
// iter = std.unicode.Utf8Iterator{ .bytes = code, .i = 0 };
// hash_table_count = 0;
// while (iter.nextCodepoint()) |cp| {
-// hash_table_count += @as(usize, @boolToInt(HashTable.isIdentifierStart(cp) or HashTable.isIdentifierPart(cp)));
+// hash_table_count += @as(usize, @intFromBool(HashTable.isIdentifierStart(cp) or HashTable.isIdentifierPart(cp)));
// }
// }
// hash_table_elapsed += timer.read();
@@ -1816,7 +1816,7 @@ pub const JumpTableInline = struct {
// while (iter.nextCodepoint()) |cp| {
// jump_table_count += @as(
// usize,
-// @boolToInt(JumpTable.isIdentifierStart(cp) or JumpTable.isIdentifierPart(cp)),
+// @intFromBool(JumpTable.isIdentifierStart(cp) or JumpTable.isIdentifierPart(cp)),
// );
// }
// }
@@ -1833,7 +1833,7 @@ pub const JumpTableInline = struct {
// while (iter.nextCodepoint()) |cp| {
// binary_search_count += @as(
// usize,
-// @boolToInt(
+// @intFromBool(
// BinarySearch.isIdentifierStart(
// cp,
// ) or BinarySearch.isIdentifierPart(
@@ -1856,7 +1856,7 @@ pub const JumpTableInline = struct {
// while (iter.nextCodepoint()) |cp| {
// bitset_count += @as(
// usize,
-// @boolToInt(
+// @intFromBool(
// Bitset.isIdentifierStart(
// cp,
// ) or Bitset.isIdentifierPart(
@@ -1930,7 +1930,7 @@ pub const JumpTableInline = struct {
// iter = std.unicode.Utf8Iterator{ .bytes = code, .i = 0 };
// hash_table_count = 0;
// while (iter.nextCodepoint()) |cp| {
-// hash_table_count += @as(usize, @boolToInt(HashTable.isIdentifierStart(cp) or HashTable.isIdentifierPart(cp)));
+// hash_table_count += @as(usize, @intFromBool(HashTable.isIdentifierStart(cp) or HashTable.isIdentifierPart(cp)));
// }
// }
// hash_table_elapsed += timer.read();
@@ -1946,7 +1946,7 @@ pub const JumpTableInline = struct {
// while (iter.nextCodepoint()) |cp| {
// jump_table_count += @as(
// usize,
-// @boolToInt(JumpTable.isIdentifierStart(cp) or JumpTable.isIdentifierPart(cp)),
+// @intFromBool(JumpTable.isIdentifierStart(cp) or JumpTable.isIdentifierPart(cp)),
// );
// }
// }
@@ -1963,7 +1963,7 @@ pub const JumpTableInline = struct {
// while (iter.nextCodepoint()) |cp| {
// binary_search_count += @as(
// usize,
-// @boolToInt(
+// @intFromBool(
// BinarySearch.isIdentifierStart(
// cp,
// ) or BinarySearch.isIdentifierPart(
@@ -1986,7 +1986,7 @@ pub const JumpTableInline = struct {
// while (iter.nextCodepoint()) |cp| {
// bitset_count += @as(
// usize,
-// @boolToInt(
+// @intFromBool(
// Bitset.isIdentifierStart(
// cp,
// ) or Bitset.isIdentifierPart(
diff --git a/src/js_lexer_tables.zig b/src/js_lexer_tables.zig
index dcf04573f..8256ff79d 100644
--- a/src/js_lexer_tables.zig
+++ b/src/js_lexer_tables.zig
@@ -136,11 +136,11 @@ pub const T = enum(u8) {
t_with,
pub fn isAssign(self: T) bool {
- return @enumToInt(self) >= @enumToInt(T.t_ampersand_ampersand_equals) and @enumToInt(self) <= @enumToInt(T.t_slash_equals);
+ return @intFromEnum(self) >= @intFromEnum(T.t_ampersand_ampersand_equals) and @intFromEnum(self) <= @intFromEnum(T.t_slash_equals);
}
pub fn isReservedWord(self: T) bool {
- return @enumToInt(self) >= @enumToInt(T.t_break) and @enumToInt(self) <= @enumToInt(T.t_with);
+ return @intFromEnum(self) >= @intFromEnum(T.t_break) and @intFromEnum(self) <= @intFromEnum(T.t_with);
}
pub fn isString(self: T) bool {
@@ -155,7 +155,7 @@ pub const T = enum(u8) {
}
pub fn isCloseBraceOrEOF(self: T) bool {
- return @enumToInt(self) <= @enumToInt(T.t_close_brace);
+ return @intFromEnum(self) <= @intFromEnum(T.t_close_brace);
}
};
@@ -842,4 +842,3 @@ test "tokenToString" {
// expect(v == 0x223C);
// }
// }
-
diff --git a/src/js_parser.zig b/src/js_parser.zig
index 33a8cef6d..28bd4aa0b 100644
--- a/src/js_parser.zig
+++ b/src/js_parser.zig
@@ -965,7 +965,7 @@ pub const ImportScanner = struct {
}
p.named_imports.ensureUnusedCapacity(
- st.items.len + @as(usize, @boolToInt(st.default_name != null)) + @as(usize, @boolToInt(st.star_name_loc != null)),
+ st.items.len + @as(usize, @intFromBool(st.default_name != null)) + @as(usize, @intFromBool(st.star_name_loc != null)),
) catch unreachable;
if (st.star_name_loc) |loc| {
@@ -1354,7 +1354,7 @@ const StaticSymbolName = struct {
pub const List = struct {
fn NewStaticSymbol(comptime basename: string) StaticSymbolName {
- const hash_value = std.hash.Wyhash.hash(0, basename);
+ const hash_value = bun.hash(basename);
return comptime StaticSymbolName{
.internal = basename ++ "_" ++ std.fmt.comptimePrint("{any}", .{bun.fmt.hexIntLower(hash_value)}),
.primary = basename,
@@ -1363,7 +1363,7 @@ const StaticSymbolName = struct {
}
fn NewStaticSymbolWithBackup(comptime basename: string, comptime backup: string) StaticSymbolName {
- const hash_value = std.hash.Wyhash.hash(0, basename);
+ const hash_value = bun.hash(basename);
return comptime StaticSymbolName{
.internal = basename ++ "_" ++ std.fmt.comptimePrint("{any}", .{bun.fmt.hexIntLower(hash_value)}),
.primary = basename,
@@ -1555,7 +1555,7 @@ pub const SideEffects = enum(u1) {
// can be removed. The annotation causes us to ignore the target.
if (call.can_be_unwrapped_if_unused) {
if (call.args.len > 0) {
- return Expr.joinAllWithCommaCallback(call.args.slice(), @TypeOf(p), p, simpifyUnusedExpr, p.allocator);
+ return Expr.joinAllWithCommaCallback(call.args.slice(), @TypeOf(p), p, comptime simpifyUnusedExpr, p.allocator);
}
}
},
@@ -1683,7 +1683,7 @@ pub const SideEffects = enum(u1) {
items,
@TypeOf(p),
p,
- simpifyUnusedExpr,
+ comptime simpifyUnusedExpr,
p.allocator,
);
},
@@ -1697,7 +1697,7 @@ pub const SideEffects = enum(u1) {
call.args.slice(),
@TypeOf(p),
p,
- simpifyUnusedExpr,
+ comptime simpifyUnusedExpr,
p.allocator,
);
}
@@ -3022,7 +3022,7 @@ pub const Parser = struct {
const uses_filename = p.symbols.items[p.filename_ref.innerIndex()].use_count_estimate > 0;
if (uses_dirname or uses_filename) {
- const count = @as(usize, @boolToInt(uses_dirname)) + @as(usize, @boolToInt(uses_filename));
+ const count = @as(usize, @intFromBool(uses_dirname)) + @as(usize, @intFromBool(uses_filename));
var declared_symbols = DeclaredSymbol.List.initCapacity(p.allocator, count) catch unreachable;
var decls = p.allocator.alloc(G.Decl, count) catch unreachable;
if (uses_dirname) {
@@ -3037,7 +3037,7 @@ pub const Parser = struct {
declared_symbols.appendAssumeCapacity(.{ .ref = p.dirname_ref, .is_top_level = true });
}
if (uses_filename) {
- decls[@as(usize, @boolToInt(uses_dirname))] = .{
+ decls[@as(usize, @intFromBool(uses_dirname))] = .{
.binding = p.b(B.Identifier{ .ref = p.filename_ref }, logger.Loc.Empty),
.value = p.newExpr(
E.String.init(p.source.path.text),
@@ -3113,7 +3113,7 @@ pub const Parser = struct {
if (p.options.module_type == .esm and p.has_es_module_syntax) {
var needs_decl_count: usize = 0;
for (export_refs) |*export_ref| {
- needs_decl_count += @as(usize, @boolToInt(export_ref.needs_decl));
+ needs_decl_count += @as(usize, @intFromBool(export_ref.needs_decl));
}
if (needs_decl_count == export_names.len) {
@@ -3483,7 +3483,7 @@ pub const Parser = struct {
const items_count = brk: {
var count: usize = 0;
inline for (comptime std.meta.fieldNames(Jest)) |symbol_name| {
- count += @boolToInt(p.symbols.items[@field(jest, symbol_name).innerIndex()].use_count_estimate > 0);
+ count += @intFromBool(p.symbols.items[@field(jest, symbol_name).innerIndex()].use_count_estimate > 0);
}
break :brk count;
@@ -3611,21 +3611,21 @@ pub const Parser = struct {
// const decls_count: u32 =
// // "REACT_ELEMENT_TYPE"
// // "Symbol.for('react.element')"
- // @intCast(u32, @boolToInt(react_element_symbol.use_count_estimate > 0)) * 2 +
+ // @intCast(u32, @intFromBool(react_element_symbol.use_count_estimate > 0)) * 2 +
// // "JSX"
- // @intCast(u32, @boolToInt(jsx_symbol.use_count_estimate > 0)) * 2 +
- // @intCast(u32, @boolToInt(FeatureFlags.support_jsxs_in_jsx_transform and jsx_static_symbol.use_count_estimate > 0)) * 2 +
- // @intCast(u32, @boolToInt(jsx_factory_symbol.use_count_estimate > 0)) +
- // @intCast(u32, @boolToInt(jsx_fragment_symbol.use_count_estimate > 0));
- // // @intCast(u32, @boolToInt(jsx_filename_symbol.use_count_estimate > 0));
+ // @intCast(u32, @intFromBool(jsx_symbol.use_count_estimate > 0)) * 2 +
+ // @intCast(u32, @intFromBool(FeatureFlags.support_jsxs_in_jsx_transform and jsx_static_symbol.use_count_estimate > 0)) * 2 +
+ // @intCast(u32, @intFromBool(jsx_factory_symbol.use_count_estimate > 0)) +
+ // @intCast(u32, @intFromBool(jsx_fragment_symbol.use_count_estimate > 0));
+ // // @intCast(u32, @intFromBool(jsx_filename_symbol.use_count_estimate > 0));
// const imports_count =
- // @intCast(u32, @boolToInt(jsx_symbol.use_count_estimate > 0)) +
- // @intCast(u32, @boolToInt(jsx_classic_symbol.use_count_estimate > 0)) +
- // @intCast(u32, @boolToInt(jsx_fragment_symbol.use_count_estimate > 0)) +
- // @intCast(u32, @boolToInt(p.options.features.react_fast_refresh)) +
- // @intCast(u32, @boolToInt(FeatureFlags.support_jsxs_in_jsx_transform and jsx_static_symbol.use_count_estimate > 0));
+ // @intCast(u32, @intFromBool(jsx_symbol.use_count_estimate > 0)) +
+ // @intCast(u32, @intFromBool(jsx_classic_symbol.use_count_estimate > 0)) +
+ // @intCast(u32, @intFromBool(jsx_fragment_symbol.use_count_estimate > 0)) +
+ // @intCast(u32, @intFromBool(p.options.features.react_fast_refresh)) +
+ // @intCast(u32, @intFromBool(FeatureFlags.support_jsxs_in_jsx_transform and jsx_static_symbol.use_count_estimate > 0));
// const stmts_count = imports_count + 1;
// const symbols_count: u32 = imports_count + decls_count;
// const loc = logger.Loc{ .start = 0 };
@@ -3989,7 +3989,7 @@ pub const Parser = struct {
// // inject
// // var jsxFrag =
// if (jsx_fragment_symbol.use_count_estimate + jsx_factory_symbol.use_count_estimate > 0) {
- // const total = @as(usize, @boolToInt(jsx_fragment_symbol.use_count_estimate > 0)) + @as(usize, @boolToInt(jsx_factory_symbol.use_count_estimate > 0));
+ // const total = @as(usize, @intFromBool(jsx_fragment_symbol.use_count_estimate > 0)) + @as(usize, @intFromBool(jsx_factory_symbol.use_count_estimate > 0));
// var declared_symbols = DeclaredSymbol.List{};
// try declared_symbols.ensureTotalCapacity(p.allocator, total);
// var decls = try std.ArrayList(G.Decl).initCapacity(p.allocator, total);
@@ -4206,7 +4206,7 @@ pub const Parser = struct {
i += 1;
}
- std.sort.sort(
+ std.sort.block(
u8,
runtime_imports[0..i],
{},
@@ -5214,10 +5214,7 @@ fn NewParser_(
const symbol_name = p.import_records.items[import_record_index].path.name.nonUniqueNameString(p.allocator) catch unreachable;
const hash_value = @truncate(
u16,
- std.hash.Wyhash.hash(
- 0,
- p.import_records.items[import_record_index].path.text,
- ),
+ bun.hash(p.import_records.items[import_record_index].path.text),
);
const cjs_import_name = std.fmt.allocPrint(
@@ -6901,7 +6898,7 @@ fn NewParser_(
// Output.print("\n+Loc: {d}\n", .{loc.start});
// for (p.scopes_in_order.items[p.scopes_in_order_visitor_index..p.scopes_in_order.items.len]) |scope_order, i| {
// if (scope_order) |ord| {
- // Output.print("Scope ({d}, {d})\n", .{ @enumToInt(ord.scope.kind), ord.loc.start });
+ // Output.print("Scope ({d}, {d})\n", .{ @intFromEnum(ord.scope.kind), ord.loc.start });
// }
// }
const order = p.nextScopeInOrderForVisitPass();
@@ -8217,7 +8214,7 @@ fn NewParser_(
var item_refs = ImportItemForNamespaceMap.init(p.allocator);
const count_excluding_namespace = @intCast(u16, stmt.items.len) +
- @intCast(u16, @boolToInt(stmt.default_name != null));
+ @intCast(u16, @intFromBool(stmt.default_name != null));
try item_refs.ensureUnusedCapacity(count_excluding_namespace);
// Even though we allocate ahead of time here
@@ -8328,7 +8325,7 @@ fn NewParser_(
return p.s(S.Empty{}, loc);
} else if (remap_count > 0) {
- item_refs.shrinkAndFree(stmt.items.len + @as(usize, @boolToInt(stmt.default_name != null)));
+ item_refs.shrinkAndFree(stmt.items.len + @as(usize, @intFromBool(stmt.default_name != null)));
}
// Track the items for this namespace
@@ -11518,8 +11515,8 @@ fn NewParser_(
}
}
- if (@ptrToInt(p.source.contents.ptr) <= @ptrToInt(name.ptr) and (@ptrToInt(name.ptr) + name.len) <= (@ptrToInt(p.source.contents.ptr) + p.source.contents.len)) {
- const start = Ref.toInt(@ptrToInt(name.ptr) - @ptrToInt(p.source.contents.ptr));
+ if (@intFromPtr(p.source.contents.ptr) <= @intFromPtr(name.ptr) and (@intFromPtr(name.ptr) + name.len) <= (@intFromPtr(p.source.contents.ptr) + p.source.contents.len)) {
+ const start = Ref.toInt(@intFromPtr(name.ptr) - @intFromPtr(p.source.contents.ptr));
const end = Ref.toInt(name.len);
return Ref.initSourceEnd(.{ .source_index = start, .inner_index = end, .tag = .source_contents_slice });
} else {
@@ -11805,7 +11802,7 @@ fn NewParser_(
// to the expression "a().b()".
if (had_pure_comment_before and level.lt(.call)) {
- expr = try p.parseSuffix(expr, @intToEnum(Level, @enumToInt(Level.call) - 1), errors, flags);
+ expr = try p.parseSuffix(expr, @enumFromInt(Level, @intFromEnum(Level.call) - 1), errors, flags);
switch (expr.data) {
.e_call => |ex| {
ex.can_be_unwrapped_if_unused = true;
@@ -12996,7 +12993,7 @@ fn NewParser_(
}
try p.lexer.next();
- left = p.newExpr(E.Binary{ .op = .bin_add_assign, .left = left, .right = try p.parseExpr(@intToEnum(Op.Level, @enumToInt(Op.Level.assign) - 1)) }, left.loc);
+ left = p.newExpr(E.Binary{ .op = .bin_add_assign, .left = left, .right = try p.parseExpr(@enumFromInt(Op.Level, @intFromEnum(Op.Level.assign) - 1)) }, left.loc);
},
.t_minus => {
if (level.gte(.add)) {
@@ -13474,7 +13471,7 @@ fn NewParser_(
pub fn parsePrefix(p: *P, level: Level, errors: ?*DeferredErrors, flags: Expr.EFlags) anyerror!Expr {
const loc = p.lexer.loc();
- const l = @enumToInt(level);
+ const l = @intFromEnum(level);
// Output.print("Parse Prefix {s}:{s} @{s} ", .{ p.lexer.token, p.lexer.raw(), @tagName(level) });
switch (p.lexer.token) {
@@ -13484,7 +13481,7 @@ fn NewParser_(
switch (p.lexer.token) {
.t_open_paren => {
- if (l < @enumToInt(Level.call) and p.fn_or_arrow_data_parse.allow_super_call) {
+ if (l < @intFromEnum(Level.call) and p.fn_or_arrow_data_parse.allow_super_call) {
return p.newExpr(E.Super{}, loc);
}
},
@@ -14239,7 +14236,7 @@ fn NewParser_(
// Use NextInsideJSXElement() not Next() so we can parse a JSX-style string literal
try p.lexer.nextInsideJSXElement();
if (p.lexer.token == .t_string_literal) {
- previous_string_with_backslash_loc.start = std.math.max(p.lexer.loc().start, p.lexer.previous_backslash_quote_in_jsx.loc.start);
+ previous_string_with_backslash_loc.start = @max(p.lexer.loc().start, p.lexer.previous_backslash_quote_in_jsx.loc.start);
const expr = p.newExpr(p.lexer.toEString(), previous_string_with_backslash_loc.*);
try p.lexer.nextInsideJSXElement();
@@ -15155,7 +15152,7 @@ fn NewParser_(
var i: usize = 2;
args[0] = tag;
- const num_props = e_.properties.len + @boolToInt(e_.key != null);
+ const num_props = e_.properties.len + @intFromBool(e_.key != null);
if (num_props > 0) {
var props = p.allocator.alloc(G.Property, num_props) catch unreachable;
bun.copy(G.Property, props, e_.properties.slice());
@@ -15170,7 +15167,7 @@ fn NewParser_(
const children_elements = e_.children.slice()[0..children_count];
for (children_elements) |child| {
args[i] = p.visitExpr(child);
- i += @intCast(usize, @boolToInt(args[i].data != .e_missing));
+ i += @intCast(usize, @intFromBool(args[i].data != .e_missing));
}
const target = p.jsxStringsToMemberExpression(expr.loc, p.options.jsx.factory) catch unreachable;
@@ -15201,7 +15198,7 @@ fn NewParser_(
for (children) |child| {
e_.children.ptr[last_child] = p.visitExpr(child);
// if tree-shaking removes the element, we must also remove it here.
- last_child += @intCast(u32, @boolToInt(e_.children.ptr[last_child].data != .e_missing));
+ last_child += @intCast(u32, @intFromBool(e_.children.ptr[last_child].data != .e_missing));
}
e_.children.len = last_child;
}
@@ -15374,7 +15371,7 @@ fn NewParser_(
// Either:
// jsxDEV(type, arguments, key, isStaticChildren, source, self)
// jsx(type, arguments, key)
- const args = p.allocator.alloc(Expr, if (p.options.jsx.development) @as(usize, 6) else @as(usize, 2) + @as(usize, @boolToInt(e_.key != null))) catch unreachable;
+ const args = p.allocator.alloc(Expr, if (p.options.jsx.development) @as(usize, 6) else @as(usize, 2) + @as(usize, @intFromBool(e_.key != null))) catch unreachable;
args[0] = tag;
args[1] = p.newExpr(E.Object{
@@ -15838,7 +15835,7 @@ fn NewParser_(
// TODO:
// if (p.should_fold_typescript_constant_expressions) {
// if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| {
- // return p.newExpr(E.Number{ .value = ((@floatToInt(i32, vals[0]) << @floatToInt(u32, vals[1])) & 31) }, expr.loc);
+ // return p.newExpr(E.Number{ .value = ((@intFromFloat(i32, vals[0]) << @intFromFloat(u32, vals[1])) & 31) }, expr.loc);
// }
// }
},
@@ -15846,7 +15843,7 @@ fn NewParser_(
// TODO:
// if (p.should_fold_typescript_constant_expressions) {
// if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| {
- // return p.newExpr(E.Number{ .value = ((@floatToInt(i32, vals[0]) >> @floatToInt(u32, vals[1])) & 31) }, expr.loc);
+ // return p.newExpr(E.Number{ .value = ((@intFromFloat(i32, vals[0]) >> @intFromFloat(u32, vals[1])) & 31) }, expr.loc);
// }
// }
},
@@ -15854,7 +15851,7 @@ fn NewParser_(
// TODO:
// if (p.should_fold_typescript_constant_expressions) {
// if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| {
- // return p.newExpr(E.Number{ .value = ((@floatToInt(i32, vals[0]) >> @floatToInt(u32, vals[1])) & 31) }, expr.loc);
+ // return p.newExpr(E.Number{ .value = ((@intFromFloat(i32, vals[0]) >> @intFromFloat(u32, vals[1])) & 31) }, expr.loc);
// }
// }
},
@@ -15862,7 +15859,7 @@ fn NewParser_(
// TODO:
// if (p.should_fold_typescript_constant_expressions) {
// if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| {
- // return p.newExpr(E.Number{ .value = ((@floatToInt(i32, vals[0]) >> @floatToInt(u32, vals[1])) & 31) }, expr.loc);
+ // return p.newExpr(E.Number{ .value = ((@intFromFloat(i32, vals[0]) >> @intFromFloat(u32, vals[1])) & 31) }, expr.loc);
// }
// }
},
@@ -15870,7 +15867,7 @@ fn NewParser_(
// TODO:
// if (p.should_fold_typescript_constant_expressions) {
// if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| {
- // return p.newExpr(E.Number{ .value = ((@floatToInt(i32, vals[0]) >> @floatToInt(u32, vals[1])) & 31) }, expr.loc);
+ // return p.newExpr(E.Number{ .value = ((@intFromFloat(i32, vals[0]) >> @intFromFloat(u32, vals[1])) & 31) }, expr.loc);
// }
// }
},
@@ -15878,7 +15875,7 @@ fn NewParser_(
// TODO:
// if (p.should_fold_typescript_constant_expressions) {
// if (Expr.extractNumericValues(e_.left.data, e_.right.data)) |vals| {
- // return p.newExpr(E.Number{ .value = ((@floatToInt(i32, vals[0]) >> @floatToInt(u32, vals[1])) & 31) }, expr.loc);
+ // return p.newExpr(E.Number{ .value = ((@intFromFloat(i32, vals[0]) >> @intFromFloat(u32, vals[1])) & 31) }, expr.loc);
// }
// }
},
@@ -17757,7 +17754,7 @@ fn NewParser_(
if (p.options.features.minify_syntax) {
// minify "long-string".length to 11
if (strings.eqlComptime(name, "length")) {
- return p.newExpr(E.Number{ .value = @intToFloat(f64, str.javascriptLength()) }, loc);
+ return p.newExpr(E.Number{ .value = @floatFromInt(f64, str.javascriptLength()) }, loc);
}
}
},
@@ -19457,7 +19454,7 @@ fn NewParser_(
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;
- args[0] = p.newExpr(E.Number{ .value = @intToFloat(f64, i) }, arg_decorator.loc);
+ args[0] = p.newExpr(E.Number{ .value = @floatFromInt(f64, i) }, arg_decorator.loc);
args[1] = arg_decorator;
decorators.append(p.callRuntime(arg_decorator.loc, "__decorateParam", args)) catch unreachable;
if (is_constructor) {
@@ -20088,7 +20085,7 @@ fn NewParser_(
if (constructor_function) |constructor| {
var to_add: usize = 0;
for (constructor.func.args) |arg| {
- to_add += @boolToInt(arg.is_typescript_ctor_field and arg.binding.data == .b_identifier);
+ to_add += @intFromBool(arg.is_typescript_ctor_field and arg.binding.data == .b_identifier);
}
// if this is an expression, we can move statements after super() because there will be 0 decorators
@@ -20368,7 +20365,7 @@ fn NewParser_(
}
before.items.len = 0;
- before.ensureUnusedCapacity(@as(usize, @boolToInt(let_decls.items.len > 0)) + @as(usize, @boolToInt(var_decls.items.len > 0)) + non_fn_stmts.items.len) catch unreachable;
+ before.ensureUnusedCapacity(@as(usize, @intFromBool(let_decls.items.len > 0)) + @as(usize, @intFromBool(var_decls.items.len > 0)) + non_fn_stmts.items.len) catch unreachable;
if (let_decls.items.len > 0) {
before.appendAssumeCapacity(p.s(
@@ -20994,7 +20991,7 @@ fn NewParser_(
// }
const bundling = p.options.bundle;
- var parts_end: usize = @as(usize, @boolToInt(bundling));
+ var parts_end: usize = @as(usize, @intFromBool(bundling));
// Handle import paths after the whole file has been visited because we need
// symbol usage counts to be able to remove unused type-only imports in
// TypeScript code.
@@ -21371,7 +21368,7 @@ fn NewParser_(
// We still call exportAll just with an empty object.
const has_any_exports = named_exports_count > 0;
- const toplevel_stmts_count = 3 + (@intCast(usize, @boolToInt(has_any_exports)) * 2);
+ const toplevel_stmts_count = 3 + (@intCast(usize, @intFromBool(has_any_exports)) * 2);
var _stmts = allocator.alloc(
Stmt,
end_iife_stmts_count + toplevel_stmts_count + (named_exports_count * 2) + imports_count + exports_from_count,
@@ -21384,7 +21381,7 @@ fn NewParser_(
// in release: print ";" instead.
// this should never happen regardless, but i'm just being cautious here.
if (comptime !Environment.isDebug) {
- std.mem.set(Stmt, _stmts, Stmt.empty());
+ @memset(_stmts, Stmt.empty());
}
// Second pass: move any imports from the part's stmts array to the new stmts
@@ -21430,7 +21427,7 @@ fn NewParser_(
var new_call_args = call_args[0..new_call_args_count];
var hmr_module_ident = p.newExpr(E.Identifier{ .ref = p.hmr_module.ref }, logger.Loc.Empty);
- new_call_args[0] = p.newExpr(E.Number{ .value = @intToFloat(f64, p.options.filepath_hash_for_hmr) }, logger.Loc.Empty);
+ new_call_args[0] = p.newExpr(E.Number{ .value = @floatFromInt(f64, p.options.filepath_hash_for_hmr) }, logger.Loc.Empty);
// This helps us provide better error messages
new_call_args[1] = p.newExpr(E.String{ .data = p.source.path.pretty }, logger.Loc.Empty);
if (p.options.features.react_fast_refresh) {
diff --git a/src/js_printer.zig b/src/js_printer.zig
index 1613500a1..913aaded3 100644
--- a/src/js_printer.zig
+++ b/src/js_printer.zig
@@ -741,7 +741,7 @@ fn NewPrinter(
pub fn writeByteNTimes(self: *Printer, byte: u8, n: usize) !void {
var bytes: [256]u8 = undefined;
- std.mem.set(u8, bytes[0..], byte);
+ @memset(bytes[0..], byte);
var remaining: usize = n;
while (remaining > 0) {
@@ -1333,7 +1333,7 @@ fn NewPrinter(
// In JavaScript, numbers are represented as 64 bit floats
// However, they could also be signed or unsigned int 32 (when doing bit shifts)
// In this case, it's always going to unsigned since that conversion has already happened.
- const val = @floatToInt(u64, float);
+ const val = @intFromFloat(u64, float);
switch (val) {
0 => {
p.print("0");
@@ -2395,7 +2395,7 @@ fn NewPrinter(
// This is more efficient than creating a new Part just for the JSX auto imports when bundling
if (comptime rewrite_esm_to_cjs) {
- if (@ptrToInt(p.options.prepend_part_key) > 0 and @ptrToInt(e.body.stmts.ptr) == @ptrToInt(p.options.prepend_part_key)) {
+ if (@intFromPtr(p.options.prepend_part_key) > 0 and @intFromPtr(e.body.stmts.ptr) == @intFromPtr(p.options.prepend_part_key)) {
p.printTwoBlocksInOne(e.body.loc, e.body.stmts, p.options.prepend_part_value.?.stmts);
wasPrinted = true;
}
@@ -2527,7 +2527,7 @@ fn NewPrinter(
p.print("{");
const props = expr.data.e_object.properties.slice();
if (props.len > 0) {
- p.options.indent += @as(usize, @boolToInt(!e.is_single_line));
+ p.options.indent += @as(usize, @intFromBool(!e.is_single_line));
if (e.is_single_line) {
p.printSpace();
@@ -3465,7 +3465,7 @@ fn NewPrinter(
.b_array => |b| {
p.print("[");
if (b.items.len > 0) {
- p.options.indent += @as(usize, @boolToInt(!b.is_single_line));
+ p.options.indent += @as(usize, @intFromBool(!b.is_single_line));
for (b.items, 0..) |*item, i| {
if (i != 0) {
@@ -3508,7 +3508,7 @@ fn NewPrinter(
p.print("{");
if (b.properties.len > 0) {
p.options.indent +=
- @as(usize, @boolToInt(!b.is_single_line));
+ @as(usize, @intFromBool(!b.is_single_line));
for (b.properties, 0..) |*property, i| {
if (i != 0) {
@@ -5561,13 +5561,13 @@ pub const BufferWriter = struct {
}
pub fn writeByte(ctx: *BufferWriter, byte: u8) anyerror!usize {
try ctx.buffer.appendChar(byte);
- ctx.approximate_newline_count += @boolToInt(byte == '\n');
+ ctx.approximate_newline_count += @intFromBool(byte == '\n');
ctx.last_bytes = .{ ctx.last_bytes[1], byte };
return 1;
}
pub fn writeAll(ctx: *BufferWriter, bytes: anytype) anyerror!usize {
try ctx.buffer.append(bytes);
- ctx.approximate_newline_count += @boolToInt(bytes.len > 0 and bytes[bytes.len - 1] == '\n');
+ ctx.approximate_newline_count += @intFromBool(bytes.len > 0 and bytes[bytes.len - 1] == '\n');
if (bytes.len >= 2) {
ctx.last_bytes = bytes[bytes.len - 2 ..][0..2].*;
@@ -5779,7 +5779,7 @@ pub fn printAst(
}
}
- std.sort.sort(rename.StableSymbolCount, top_level_symbols.items, {}, rename.StableSymbolCount.lessThan);
+ std.sort.block(rename.StableSymbolCount, top_level_symbols.items, {}, rename.StableSymbolCount.lessThan);
try minify_renamer.allocateTopLevelSymbolSlots(top_level_symbols);
var minifier = tree.char_freq.?.compile(allocator);
@@ -5861,9 +5861,9 @@ pub fn printJSON(
var stmt = Stmt{ .loc = logger.Loc.Empty, .data = .{
.s_expr = &s_expr,
} };
- var stmts = &[_]js_ast.Stmt{stmt};
- var parts = &[_]js_ast.Part{.{ .stmts = stmts }};
- const ast = Ast.initTest(parts);
+ var stmts = [_]js_ast.Stmt{stmt};
+ var parts = [_]js_ast.Part{.{ .stmts = &stmts }};
+ const ast = Ast.initTest(&parts);
var list = js_ast.Symbol.List.init(ast.symbols.slice());
var nested_list = js_ast.Symbol.NestedList.init(&[_]js_ast.Symbol.List{list});
var renamer = rename.NoOpRenamer.init(js_ast.Symbol.Map.initList(nested_list), source);
diff --git a/src/json_parser.zig b/src/json_parser.zig
index 913a16bd6..c7dd74943 100644
--- a/src/json_parser.zig
+++ b/src/json_parser.zig
@@ -542,7 +542,7 @@ pub fn toAST(
return Expr{
.data = .{
.e_number = .{
- .value = @intToFloat(f64, value),
+ .value = @floatFromInt(f64, value),
},
},
.loc = logger.Loc{},
@@ -626,7 +626,7 @@ pub fn toAST(
}
},
.Enum => {
- _ = std.meta.intToEnum(Type, @enumToInt(value)) catch {
+ _ = std.meta.intToEnum(Type, @intFromEnum(value)) catch {
return Expr{ .data = .{ .e_null = .{} }, .loc = logger.Loc{} };
};
diff --git a/src/libarchive/libarchive.zig b/src/libarchive/libarchive.zig
index ebaec7dd7..c2948fd28 100644
--- a/src/libarchive/libarchive.zig
+++ b/src/libarchive/libarchive.zig
@@ -264,7 +264,7 @@ pub const BufferReadStream = struct {
const remaining = this.bufLeft();
if (remaining.len == 0) return 0;
- const diff = std.math.min(remaining.len, this.block_size);
+ const diff = @min(remaining.len, this.block_size);
buffer.* = remaining[0..diff].ptr;
this.pos += diff;
return @intCast(isize, diff);
@@ -281,7 +281,7 @@ pub const BufferReadStream = struct {
const pos = @intCast(isize, this.pos);
const proposed = pos + offset;
- const new_pos = std.math.min(std.math.max(proposed, 0), buflen - 1);
+ const new_pos = @min(@max(proposed, 0), buflen - 1);
this.pos = @intCast(usize, this.pos);
return new_pos - pos;
}
@@ -297,19 +297,19 @@ pub const BufferReadStream = struct {
const buflen = @intCast(isize, this.buf.len);
const pos = @intCast(isize, this.pos);
- switch (@intToEnum(Seek, whence)) {
+ switch (@enumFromInt(Seek, whence)) {
Seek.current => {
- const new_pos = std.math.max(std.math.min(pos + offset, buflen - 1), 0);
+ const new_pos = @max(@min(pos + offset, buflen - 1), 0);
this.pos = @intCast(usize, new_pos);
return new_pos;
},
Seek.end => {
- const new_pos = std.math.max(std.math.min(buflen - offset, buflen), 0);
+ const new_pos = @max(@min(buflen - offset, buflen), 0);
this.pos = @intCast(usize, new_pos);
return new_pos;
},
Seek.set => {
- const new_pos = std.math.max(std.math.min(offset, buflen - 1), 0);
+ const new_pos = @max(@min(offset, buflen - 1), 0);
this.pos = @intCast(usize, new_pos);
return new_pos;
},
@@ -379,7 +379,7 @@ pub const Archive = struct {
pub fn init(filepath: string, estimated_size: usize, allocator: std.mem.Allocator) !Plucker {
return Plucker{
.contents = try MutableString.init(allocator, estimated_size),
- .filename_hash = std.hash.Wyhash.hash(0, filepath),
+ .filename_hash = bun.hash(filepath),
.fd = 0,
.found = false,
};
@@ -413,7 +413,7 @@ pub const Archive = struct {
};
loop: while (true) {
- const r = @intToEnum(Status, lib.archive_read_next_header(archive, &entry));
+ const r = @enumFromInt(Status, lib.archive_read_next_header(archive, &entry));
switch (r) {
Status.eof => break :loop,
@@ -434,7 +434,7 @@ pub const Archive = struct {
pathname = std.mem.sliceTo(pathname_.ptr[0..pathname_.len :0], 0);
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));
+ const size = @intCast(usize, @max(lib.archive_entry_size(entry), 0));
if (size > 0) {
var opened = dir.dir.openFileZ(pathname, .{ .mode = .write_only }) catch continue :loop;
var stat = try opened.stat();
@@ -490,7 +490,7 @@ pub const Archive = struct {
const dir_fd = dir.fd;
loop: while (true) {
- const r = @intToEnum(Status, lib.archive_read_next_header(archive, &entry));
+ const r = @enumFromInt(Status, lib.archive_read_next_header(archive, &entry));
switch (r) {
Status.eof => break :loop,
@@ -513,7 +513,7 @@ pub const Archive = struct {
}
var pathname_ = tokenizer.rest();
- pathname = @intToPtr([*]const u8, @ptrToInt(pathname_.ptr))[0..pathname_.len :0];
+ pathname = @ptrFromInt([*]const u8, @intFromPtr(pathname_.ptr))[0..pathname_.len :0];
if (pathname.len == 0) continue;
const kind = C.kindFromMode(lib.archive_entry_filetype(entry));
@@ -527,7 +527,7 @@ pub const Archive = struct {
count += 1;
switch (kind) {
- Kind.Directory => {
+ Kind.directory => {
var mode = @intCast(i32, lib.archive_entry_perm(entry));
// if dirs are readable, then they should be listable
@@ -545,7 +545,7 @@ pub const Archive = struct {
try std.os.mkdiratZ(dir_fd, pathname, 0o777);
};
},
- Kind.SymLink => {
+ Kind.sym_link => {
const link_target = lib.archive_entry_symlink(entry).?;
std.os.symlinkatZ(link_target, dir_fd, pathname) catch |err| brk: {
@@ -560,7 +560,7 @@ pub const Archive = struct {
}
};
},
- Kind.File => {
+ Kind.file => {
const mode = @intCast(std.os.mode_t, lib.archive_entry_perm(entry));
const file = dir.createFileZ(pathname, .{ .truncate = true, .mode = mode }) catch |err| brk: {
switch (err) {
@@ -583,7 +583,7 @@ pub const Archive = struct {
if (size > 0) {
if (ctx) |ctx_| {
const hash: u64 = if (ctx_.pluckers.len > 0)
- std.hash.Wyhash.hash(0, slice)
+ bun.hash(slice)
else
@as(u64, 0);
diff --git a/src/linear_fifo.zig b/src/linear_fifo.zig
index 66d579fdc..b73f21ce9 100644
--- a/src/linear_fifo.zig
+++ b/src/linear_fifo.zig
@@ -100,7 +100,7 @@ pub fn LinearFifo(
var tmp: [mem.page_size / 2 / @sizeOf(T)]T = undefined;
while (self.head != 0) {
- const n = math.min(self.head, tmp.len);
+ const n = @min(self.head, tmp.len);
const m = self.buf.len - n;
bun.copy(T, tmp[0..n], self.buf[0..n]);
// this middle copy overlaps; the others here don't
@@ -111,7 +111,7 @@ pub fn LinearFifo(
}
{ // set unused area to undefined
const unused = mem.sliceAsBytes(self.buf[self.count..]);
- @memset(unused.ptr, undefined, unused.len);
+ @memset(unused, undefined);
}
}
@@ -137,7 +137,7 @@ pub fn LinearFifo(
if (self.count > 0) {
var new_bytes = std.mem.sliceAsBytes(buf);
var old_bytes = std.mem.sliceAsBytes(self.readableSlice(0));
- @memcpy(new_bytes.ptr, old_bytes.ptr, old_bytes.len);
+ @memcpy(new_bytes[0..old_bytes.len], old_bytes);
self.allocator.free(self.buf);
}
self.head = 0;
@@ -168,7 +168,7 @@ pub fn LinearFifo(
start -= self.buf.len;
return self.buf[start .. start + (self.count - offset)];
} else {
- const end = math.min(self.head + self.count, self.buf.len);
+ const end = @min(self.head + self.count, self.buf.len);
return self.buf[start..end];
}
}
@@ -187,12 +187,12 @@ pub fn LinearFifo(
const slice = self.readableSliceMut(0);
if (slice.len >= count) {
const unused = mem.sliceAsBytes(slice[0..count]);
- @memset(unused.ptr, undefined, unused.len);
+ @memset(unused, undefined);
} else {
const unused = mem.sliceAsBytes(slice[0..]);
- @memset(unused.ptr, undefined, unused.len);
+ @memset(unused, undefined);
const unused2 = mem.sliceAsBytes(self.readableSliceMut(slice.len)[0 .. count - slice.len]);
- @memset(unused2.ptr, undefined, unused2.len);
+ @memset(unused2, undefined);
}
}
@@ -224,7 +224,7 @@ pub fn LinearFifo(
while (dst_left.len > 0) {
const slice = self.readableSlice(0);
if (slice.len == 0) break;
- const n = math.min(slice.len, dst_left.len);
+ const n = @min(slice.len, dst_left.len);
bun.copy(T, dst_left, slice[0..n]);
self.discard(n);
dst_left = dst_left[n..];
@@ -293,7 +293,7 @@ pub fn LinearFifo(
while (src_left.len > 0) {
const writable_slice = self.writableSlice(0);
assert(writable_slice.len != 0);
- const n = math.min(writable_slice.len, src_left.len);
+ const n = @min(writable_slice.len, src_left.len);
bun.copy(T, writable_slice, src_left[0..n]);
self.update(n);
src_left = src_left[n..];
diff --git a/src/linker.zig b/src/linker.zig
index 461bcf808..fa1c504d7 100644
--- a/src/linker.zig
+++ b/src/linker.zig
@@ -119,7 +119,7 @@ pub const Linker = struct {
fd: ?FileDescriptorType,
) !string {
if (Bundler.isCacheEnabled) {
- var hashed = std.hash.Wyhash.hash(0, file_path.text);
+ var hashed = bun.hash(file_path.text);
var hashed_result = try this.hashed_filenames.getOrPut(hashed);
if (hashed_result.found_existing) {
return hashed_result.value_ptr.*;
@@ -130,7 +130,7 @@ pub const Linker = struct {
const hash_name = modkey.hashName(file_path.text);
if (Bundler.isCacheEnabled) {
- var hashed = std.hash.Wyhash.hash(0, file_path.text);
+ var hashed = bun.hash(file_path.text);
try this.hashed_filenames.put(hashed, try this.allocator.dupe(u8, hash_name));
}
@@ -569,7 +569,7 @@ pub const Linker = struct {
// But we need to at least tell the printer that this needs to happen.
if (loader != .napi and resolved_import.shouldAssumeCommonJS(import_record.kind) and !is_bun) {
import_record.do_commonjs_transform_in_printer = true;
- import_record.module_id = @truncate(u32, std.hash.Wyhash.hash(0, path.pretty));
+ import_record.module_id = @truncate(u32, bun.hash(path.pretty));
}
} else |err| {
switch (err) {
@@ -1043,7 +1043,7 @@ pub const Linker = struct {
hash_key = path.text[linker.fs.top_level_dir.len..];
}
- return std.hash.Wyhash.hash(0, hash_key);
+ return bun.hash(hash_key);
}
pub fn enqueueResolveResult(linker: *ThisLinker, resolve_result: *const Resolver.Result) !bool {
diff --git a/src/linux_c.zig b/src/linux_c.zig
index dade43a32..12e3c9b73 100644
--- a/src/linux_c.zig
+++ b/src/linux_c.zig
@@ -148,7 +148,7 @@ pub const SystemErrno = enum(u8) {
}
if (code >= max) return null;
- return @intToEnum(SystemErrno, code);
+ return @enumFromInt(SystemErrno, code);
}
pub fn label(this: SystemErrno) ?[]const u8 {
@@ -385,9 +385,9 @@ pub fn splice(fd_in: std.os.fd_t, off_in: ?*i64, fd_out: std.os.fd_t, off_out: ?
return std.os.linux.syscall6(
.splice,
@bitCast(usize, @as(isize, fd_in)),
- @ptrToInt(off_in),
+ @intFromPtr(off_in),
@bitCast(usize, @as(isize, fd_out)),
- @ptrToInt(off_out),
+ @intFromPtr(off_out),
len,
flags,
);
@@ -438,9 +438,9 @@ pub fn get_system_loadavg() [3]f64 {
var info: struct_sysinfo = undefined;
if (sysinfo(&info) == @as(c_int, 0)) {
return [3]f64{
- std.math.ceil((@intToFloat(f64, info.loads[0]) / 65536.0) * 100.0) / 100.0,
- std.math.ceil((@intToFloat(f64, info.loads[1]) / 65536.0) * 100.0) / 100.0,
- std.math.ceil((@intToFloat(f64, info.loads[2]) / 65536.0) * 100.0) / 100.0,
+ std.math.ceil((@floatFromInt(f64, info.loads[0]) / 65536.0) * 100.0) / 100.0,
+ std.math.ceil((@floatFromInt(f64, info.loads[1]) / 65536.0) * 100.0) / 100.0,
+ std.math.ceil((@floatFromInt(f64, info.loads[2]) / 65536.0) * 100.0) / 100.0,
};
}
return [3]f64{ 0, 0, 0 };
diff --git a/src/lock.zig b/src/lock.zig
index 66d64cff2..3e07945c8 100644
--- a/src/lock.zig
+++ b/src/lock.zig
@@ -28,11 +28,12 @@ pub const Mutex = struct {
}
const cas_fn = comptime switch (strong) {
- true => "compareAndSwap",
- else => "tryCompareAndSwap",
+ true => Atomic(u32).compareAndSwap,
+ else => Atomic(u32).tryCompareAndSwap,
};
- return @field(self.state, cas_fn)(
+ return cas_fn(
+ &self.state,
UNLOCKED,
LOCKED,
.Acquire,
diff --git a/src/logger.zig b/src/logger.zig
index ad7a9b333..621e643b5 100644
--- a/src/logger.zig
+++ b/src/logger.zig
@@ -180,7 +180,7 @@ pub const Location = struct {
var data = source.initErrorPosition(r.loc);
var full_line = source.contents[data.line_start..data.line_end];
if (full_line.len > 80 + data.column_count) {
- full_line = full_line[std.math.max(data.column_count, 40) - 40 .. std.math.min(data.column_count + 40, full_line.len - 40) + 40];
+ full_line = full_line[@max(data.column_count, 40) - 40 .. @min(data.column_count + 40, full_line.len - 40) + 40];
}
bun.assertDefined(source.path.text);
@@ -194,7 +194,7 @@ pub const Location = struct {
.column = usize2Loc(data.column_count).start,
.length = full_line.len,
.line_text = full_line,
- .offset = @intCast(usize, std.math.max(r.loc.start, 0)),
+ .offset = @intCast(usize, @max(r.loc.start, 0)),
};
} else {
return null;
@@ -293,7 +293,7 @@ pub const Data = struct {
if (location.line_text) |line_text_| {
const line_text = std.mem.trimRight(u8, line_text_, "\r\n\t");
- const location_in_line_text = @intCast(u32, std.math.max(location.column, 1) - 1);
+ const location_in_line_text = @intCast(u32, @max(location.column, 1) - 1);
const has_position = location.column > -1 and line_text.len > 0 and location_in_line_text < line_text.len;
if (has_position) {
@@ -650,8 +650,8 @@ pub const Log = struct {
var warnings: u32 = 0;
var errors: u32 = 0;
for (this.msgs.items) |msg| {
- errors += @intCast(u32, @boolToInt(msg.kind == .err));
- warnings += @intCast(u32, @boolToInt(msg.kind == .warn));
+ errors += @intCast(u32, @intFromBool(msg.kind == .err));
+ warnings += @intCast(u32, @intFromBool(msg.kind == .warn));
}
return Api.Log{
@@ -669,7 +669,7 @@ pub const Log = struct {
err,
pub fn atLeast(this: Level, other: Level) bool {
- return @enumToInt(this) <= @enumToInt(other);
+ return @intFromEnum(this) <= @intFromEnum(other);
}
pub const label: std.EnumArray(Level, string) = brk: {
@@ -760,7 +760,7 @@ pub const Log = struct {
const msg: Msg = msg_;
if (msg.notes) |notes| {
for (notes) |note| {
- notes_count += @intCast(usize, @boolToInt(note.text.len > 0));
+ notes_count += @intCast(usize, @intFromBool(note.text.len > 0));
}
}
}
@@ -1372,7 +1372,7 @@ pub const Source = struct {
pub fn initErrorPosition(self: *const Source, _offset: Loc) ErrorPosition {
var prev_code_point: i32 = 0;
- var offset: usize = std.math.min(if (_offset.start < 0) 0 else @intCast(usize, _offset.start), @max(self.contents.len, 1) - 1);
+ var offset: usize = @min(if (_offset.start < 0) 0 else @intCast(usize, _offset.start), @max(self.contents.len, 1) - 1);
const contents = self.contents;
diff --git a/src/main_wasm.zig b/src/main_wasm.zig
index 8958d7cd4..c9e4666e8 100644
--- a/src/main_wasm.zig
+++ b/src/main_wasm.zig
@@ -31,14 +31,14 @@ pub const Uint8Array = extern struct {
pub fn fromSlice(slice: []const u8) u64 {
return @bitCast(u64, [2]u32{
- @ptrToInt(slice.ptr),
+ @intFromPtr(slice.ptr),
slice.len,
});
}
pub fn fromJS(data: u64) []u8 {
const ptrs = @bitCast([2]u32, data);
- return @intToPtr([*]u8, ptrs[0])[0..ptrs[1]];
+ return @ptrFromInt([*]u8, ptrs[0])[0..ptrs[1]];
}
};
@@ -167,7 +167,7 @@ var writer: JSPrinter.BufferPrinter = undefined;
var define: *Define.Define = undefined;
export fn bun_malloc(size: usize) u64 {
return @bitCast(u64, [2]u32{
- @ptrToInt((default_allocator.alloc(u8, size) catch unreachable).ptr),
+ @intFromPtr((default_allocator.alloc(u8, size) catch unreachable).ptr),
size,
});
}
@@ -270,7 +270,7 @@ export fn transform(opts_array: u64) u64 {
const Encoder = ApiWriter(@TypeOf(output_writer));
var encoder = Encoder.init(output_writer);
transform_response.encode(&encoder) catch unreachable;
- return @bitCast(u64, [2]u32{ @ptrToInt(output.items.ptr), output.items.len });
+ return @bitCast(u64, [2]u32{ @intFromPtr(output.items.ptr), output.items.len });
}
export fn scan(opts_array: u64) u64 {
@@ -325,7 +325,7 @@ export fn scan(opts_array: u64) u64 {
var encoder = Encoder.init(output_writer);
scan_result.encode(&encoder) catch unreachable;
- return @bitCast(u64, [2]u32{ @ptrToInt(output.items.ptr), output.items.len });
+ return @bitCast(u64, [2]u32{ @intFromPtr(output.items.ptr), output.items.len });
}
// pub fn main() anyerror!void {}
diff --git a/src/multi_array_list.zig b/src/multi_array_list.zig
index d7e3c98e6..cff601bb8 100644
--- a/src/multi_array_list.zig
+++ b/src/multi_array_list.zig
@@ -33,7 +33,7 @@ pub fn MultiArrayList(comptime S: type) type {
/// and then get the field arrays from the slice.
pub const Slice = struct {
/// This array is indexed by the field index which can be obtained
- /// by using @enumToInt() on the Field enum
+ /// by using @intFromEnum() on the Field enum
ptrs: [fields.len][*]u8,
len: usize,
capacity: usize,
@@ -43,7 +43,7 @@ pub fn MultiArrayList(comptime S: type) type {
if (self.capacity == 0) {
return &[_]F{};
}
- const byte_ptr = self.ptrs[@enumToInt(field)];
+ const byte_ptr = self.ptrs[@intFromEnum(field)];
const casted_ptr: [*]F = if (@sizeOf(F) == 0)
undefined
else
@@ -97,7 +97,7 @@ pub fn MultiArrayList(comptime S: type) type {
return lhs.alignment > rhs.alignment;
}
};
- std.sort.sort(Data, &data, {}, Sort.lessThan);
+ std.sort.block(Data, &data, {}, Sort.lessThan);
var sizes_bytes: [fields.len]usize = undefined;
var field_indexes: [fields.len]usize = undefined;
for (data, 0..) |elem, i| {
@@ -151,7 +151,7 @@ pub fn MultiArrayList(comptime S: type) type {
pub fn set(self: *Self, index: usize, elem: S) void {
const slices = self.slice();
inline for (fields, 0..) |field_info, i| {
- slices.items(@intToEnum(Field, i))[index] = @field(elem, field_info.name);
+ slices.items(@enumFromInt(Field, i))[index] = @field(elem, field_info.name);
}
}
@@ -160,7 +160,7 @@ pub fn MultiArrayList(comptime S: type) type {
const slices = self.slice();
var result: S = undefined;
inline for (fields, 0..) |field_info, i| {
- @field(result, field_info.name) = slices.items(@intToEnum(Field, i))[index];
+ @field(result, field_info.name) = slices.items(@enumFromInt(Field, i))[index];
}
return result;
}
@@ -233,7 +233,7 @@ pub fn MultiArrayList(comptime S: type) type {
self.len += 1;
const slices = self.slice();
inline for (fields, 0..) |field_info, field_index| {
- const field_slice = slices.items(@intToEnum(Field, field_index));
+ const field_slice = slices.items(@enumFromInt(Field, field_index));
var i: usize = self.len - 1;
while (i > index) : (i -= 1) {
field_slice[i] = field_slice[i - 1];
@@ -248,7 +248,7 @@ pub fn MultiArrayList(comptime S: type) type {
pub fn swapRemove(self: *Self, index: usize) void {
const slices = self.slice();
inline for (fields, 0..) |_, i| {
- const field_slice = slices.items(@intToEnum(Field, i));
+ const field_slice = slices.items(@enumFromInt(Field, i));
field_slice[index] = field_slice[self.len - 1];
field_slice[self.len - 1] = undefined;
}
@@ -260,7 +260,7 @@ pub fn MultiArrayList(comptime S: type) type {
pub fn orderedRemove(self: *Self, index: usize) void {
const slices = self.slice();
inline for (fields, 0..) |_, field_index| {
- const field_slice = slices.items(@intToEnum(Field, field_index));
+ const field_slice = slices.items(@enumFromInt(Field, field_index));
var i = index;
while (i < self.len - 1) : (i += 1) {
field_slice[i] = field_slice[i + 1];
@@ -297,13 +297,12 @@ pub fn MultiArrayList(comptime S: type) type {
const self_slice = self.slice();
inline for (fields, 0..) |field_info, i| {
if (@sizeOf(field_info.type) != 0) {
- const field = @intToEnum(Field, i);
+ const field = @enumFromInt(Field, i);
const dest_slice = self_slice.items(field)[new_len..];
- const byte_count = dest_slice.len * @sizeOf(field_info.type);
// We use memset here for more efficient codegen in safety-checked,
// valgrind-enabled builds. Otherwise the valgrind client request
// will be repeated for every element.
- @memset(@ptrCast([*]u8, dest_slice.ptr), undefined, byte_count);
+ @memset(dest_slice, undefined);
}
}
self.len = new_len;
@@ -319,7 +318,7 @@ pub fn MultiArrayList(comptime S: type) type {
const other_slice = other.slice();
inline for (fields, 0..) |field_info, i| {
if (@sizeOf(field_info.type) != 0) {
- const field = @intToEnum(Field, i);
+ const field = @enumFromInt(Field, i);
mem.copy(field_info.type, other_slice.items(field), self_slice.items(field));
}
}
@@ -380,7 +379,7 @@ pub fn MultiArrayList(comptime S: type) type {
const other_slice = other.slice();
inline for (fields, 0..) |field_info, i| {
if (@sizeOf(field_info.type) != 0) {
- const field = @intToEnum(Field, i);
+ const field = @enumFromInt(Field, i);
mem.copy(field_info.type, other_slice.items(field), self_slice.items(field));
}
}
@@ -399,7 +398,7 @@ pub fn MultiArrayList(comptime S: type) type {
const result_slice = result.slice();
inline for (fields, 0..) |field_info, i| {
if (@sizeOf(field_info.type) != 0) {
- const field = @intToEnum(Field, i);
+ const field = @enumFromInt(Field, i);
mem.copy(field_info.type, result_slice.items(field), self_slice.items(field));
}
}
@@ -420,7 +419,7 @@ pub fn MultiArrayList(comptime S: type) type {
pub fn swap(sc: @This(), a_index: usize, b_index: usize) void {
inline for (fields, 0..) |field_info, i| {
if (@sizeOf(field_info.type) != 0) {
- const field = @intToEnum(Field, i);
+ const field = @enumFromInt(Field, i);
const ptr = sc.slice.items(field);
mem.swap(field_info.type, &ptr[a_index], &ptr[b_index]);
}
@@ -432,7 +431,7 @@ pub fn MultiArrayList(comptime S: type) type {
}
};
- std.sort.sortContext(self.len, SortContext{
+ std.sort.blockContext(0, self.len, SortContext{
.sub_ctx = ctx,
.slice = self.slice(),
});
@@ -457,7 +456,7 @@ pub fn MultiArrayList(comptime S: type) type {
const this_slice = this.slice();
inline for (fields, 0..) |field_info, i| {
if (@sizeOf(field_info.type) != 0) {
- const field = @intToEnum(Field, i);
+ const field = @enumFromInt(Field, i);
mem.copy(field_info.type, this_slice.items(field)[offset..], other_slice.items(field));
}
}
@@ -475,7 +474,7 @@ pub fn MultiArrayList(comptime S: type) type {
pub fn zero(this: *Self) void {
var allocated = this.allocatedBytes();
if (allocated.len > 0) {
- @memset(allocated.ptr, 0, allocated.len);
+ @memset(allocated, 0);
}
}
diff --git a/src/napi/napi.zig b/src/napi/napi.zig
index 5f94dac90..0973ca559 100644
--- a/src/napi/napi.zig
+++ b/src/napi/napi.zig
@@ -386,7 +386,7 @@ pub export fn napi_get_value_string_latin1(env: napi_env, value: napi_value, buf
return .ok;
}
const to_copy = @min(zig_str.len, buf_.len);
- @memcpy(buf, zig_str.slice().ptr, to_copy);
+ @memcpy(buf[0..to_copy], zig_str.slice().ptr[0..to_copy]);
buf[to_copy] = 0;
// if zero terminated, report the length of the string without the null
result.* = to_copy;
@@ -451,7 +451,7 @@ pub export fn napi_get_value_string_utf8(env: napi_env, value: napi_value, buf_p
}
const to_copy = @min(zig_str.len, buf_.len);
- @memcpy(buf, zig_str.slice().ptr, to_copy);
+ @memcpy(buf[0..to_copy], zig_str.slice().ptr[0..to_copy]);
buf[to_copy] = 0;
if (result_ptr) |result| {
result.* = @intCast(@TypeOf(result.*), to_copy);
@@ -509,7 +509,7 @@ pub export fn napi_get_value_string_utf16(env: napi_env, value: napi_value, buf_
}
const to_copy = @min(zig_str.len, buf_.len) * 2;
- @memcpy(std.mem.sliceAsBytes(buf_).ptr, std.mem.sliceAsBytes(zig_str.utf16SliceAligned()).ptr, to_copy);
+ @memcpy(std.mem.sliceAsBytes(buf_)[0..to_copy], std.mem.sliceAsBytes(zig_str.utf16SliceAligned())[0..to_copy]);
buf[to_copy] = 0;
// if zero terminated, report the length of the string without the null
if (result_ptr) |result| {
@@ -787,7 +787,8 @@ pub export fn napi_create_arraybuffer(env: napi_env, byte_length: usize, data: [
log("napi_create_arraybuffer", .{});
var typed_array = JSC.C.JSObjectMakeTypedArray(env.ref(), .kJSTypedArrayTypeArrayBuffer, byte_length, TODO_EXCEPTION);
var array_buffer = JSValue.c(typed_array).asArrayBuffer(env) orelse return genericFailure();
- @memcpy(array_buffer.ptr, data, @min(array_buffer.len, @truncate(u32, byte_length)));
+ const len = @min(array_buffer.len, @truncate(u32, byte_length));
+ @memcpy(array_buffer.ptr[0..len], data[0..len]);
result.* = JSValue.c(typed_array);
return .ok;
}
@@ -1035,8 +1036,8 @@ pub const napi_async_work = struct {
this.run();
}
pub fn run(this: *napi_async_work) void {
- if (this.status.compareAndSwap(@enumToInt(Status.pending), @enumToInt(Status.started), .SeqCst, .SeqCst)) |state| {
- if (state == @enumToInt(Status.cancelled)) {
+ if (this.status.compareAndSwap(@intFromEnum(Status.pending), @intFromEnum(Status.started), .SeqCst, .SeqCst)) |state| {
+ if (state == @intFromEnum(Status.cancelled)) {
if (this.wait_for_deinit) {
// this might cause a segfault due to Task using a linked list!
bun.default_allocator.destroy(this);
@@ -1045,7 +1046,7 @@ pub const napi_async_work = struct {
return;
}
this.execute.?(this.global, this.ctx);
- this.status.store(@enumToInt(Status.completed), .SeqCst);
+ this.status.store(@intFromEnum(Status.completed), .SeqCst);
this.event_loop.enqueueTaskConcurrent(this.concurrent_task.from(this));
}
@@ -1059,7 +1060,7 @@ pub const napi_async_work = struct {
pub fn cancel(this: *napi_async_work) bool {
this.ref.unref(this.global.bunVM());
- return this.status.compareAndSwap(@enumToInt(Status.cancelled), @enumToInt(Status.pending), .SeqCst, .SeqCst) != null;
+ return this.status.compareAndSwap(@intFromEnum(Status.cancelled), @intFromEnum(Status.pending), .SeqCst, .SeqCst) != null;
}
pub fn deinit(this: *napi_async_work) void {
@@ -1075,7 +1076,7 @@ pub const napi_async_work = struct {
pub fn runFromJS(this: *napi_async_work) void {
this.complete.?(
this.global,
- if (this.status.load(.SeqCst) == @enumToInt(Status.cancelled))
+ if (this.status.load(.SeqCst) == @intFromEnum(Status.cancelled))
napi_status.cancelled
else
napi_status.ok,
@@ -1171,7 +1172,7 @@ pub export fn napi_create_buffer_copy(env: napi_env, length: usize, data: [*]u8,
var buffer = JSC.JSValue.createBufferFromLength(env, length);
if (buffer.asArrayBuffer(env)) |array_buf| {
if (length > 0) {
- @memcpy(array_buf.slice().ptr, data, length);
+ @memcpy(array_buf.slice()[0..length], data[0..length]);
}
if (result_data) |ptr| {
ptr.* = if (length > 0) array_buf.ptr else null;
diff --git a/src/network_thread.zig b/src/network_thread.zig
index 969269c76..49711c469 100644
--- a/src/network_thread.zig
+++ b/src/network_thread.zig
@@ -1,15 +1,16 @@
-const ThreadPool = @import("root").bun.ThreadPool;
+const bun = @import("root").bun;
+const ThreadPool = bun.ThreadPool;
pub const Batch = ThreadPool.Batch;
pub const Task = ThreadPool.Task;
const Node = ThreadPool.Node;
pub const Completion = AsyncIO.Completion;
const std = @import("std");
-pub const AsyncIO = @import("root").bun.AsyncIO;
-const Output = @import("root").bun.Output;
+pub const AsyncIO = bun.AsyncIO;
+const Output = bun.Output;
const IdentityContext = @import("./identity_context.zig").IdentityContext;
const HTTP = @import("./http_client_async.zig");
const NetworkThread = @This();
-const Environment = @import("root").bun.Environment;
+const Environment = bun.Environment;
const Lock = @import("./lock.zig").Lock;
/// Single-thread in this pool
diff --git a/src/node_fallbacks.zig b/src/node_fallbacks.zig
index fc0dc3bef..170907e58 100644
--- a/src/node_fallbacks.zig
+++ b/src/node_fallbacks.zig
@@ -3,6 +3,7 @@ const string = @import("./string_types.zig").string;
const PackageJSON = @import("./resolver/package_json.zig").PackageJSON;
const logger = @import("root").bun.logger;
const Fs = @import("./fs.zig");
+const bun = @import("root").bun;
const ComptimeStringMap = @import("./comptime_string_map.zig").ComptimeStringMap;
const assert_code: string = @embedFile("./node-fallbacks/out/assert.js");
@@ -67,7 +68,7 @@ const assert_package_json = PackageJSON{
.name = "assert",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "assert@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("assert@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/assert/package.json", ""),
@@ -76,7 +77,7 @@ const buffer_package_json = PackageJSON{
.name = "buffer",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "buffer@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("buffer@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/buffer/package.json", ""),
@@ -85,7 +86,7 @@ const console_package_json = PackageJSON{
.name = "console",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "console@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("console@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/console/package.json", ""),
@@ -94,7 +95,7 @@ const constants_package_json = PackageJSON{
.name = "constants",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "constants@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("constants@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/constants/package.json", ""),
@@ -103,7 +104,7 @@ const crypto_package_json = PackageJSON{
.name = "crypto",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "crypto@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("crypto@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/crypto/package.json", ""),
@@ -112,7 +113,7 @@ const domain_package_json = PackageJSON{
.name = "domain",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "domain@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("domain@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/domain/package.json", ""),
@@ -121,7 +122,7 @@ const events_package_json = PackageJSON{
.name = "events",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "events@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("events@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/events/package.json", ""),
@@ -130,7 +131,7 @@ const http_package_json = PackageJSON{
.name = "http",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "http@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("http@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/http/package.json", ""),
@@ -139,7 +140,7 @@ const https_package_json = PackageJSON{
.name = "https",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "https@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("https@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/https/package.json", ""),
@@ -148,7 +149,7 @@ const net_package_json = PackageJSON{
.name = "net",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "net@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("net@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/net/package.json", ""),
@@ -157,7 +158,7 @@ const os_package_json = PackageJSON{
.name = "os",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "os@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("os@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/os/package.json", ""),
@@ -166,7 +167,7 @@ const path_package_json = PackageJSON{
.name = "path",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "path@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("path@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/path/package.json", ""),
@@ -175,7 +176,7 @@ const process_package_json = PackageJSON{
.name = "process",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "process@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("process@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/process/package.json", ""),
@@ -184,7 +185,7 @@ const punycode_package_json = PackageJSON{
.name = "punycode",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "punycode@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("punycode@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/punycode/package.json", ""),
@@ -193,7 +194,7 @@ const querystring_package_json = PackageJSON{
.name = "querystring",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "querystring@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("querystring@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/querystring/package.json", ""),
@@ -202,7 +203,7 @@ const stream_package_json = PackageJSON{
.name = "stream",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "stream@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("stream@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/stream/package.json", ""),
@@ -213,7 +214,7 @@ const string_decoder_package_json = PackageJSON{
.module_type = .cjs,
.hash = brk: {
@setEvalBranchQuota(9999);
- break :brk @truncate(u32, std.hash.Wyhash.hash(0, "string_decoder@0.0.0-polyfill"));
+ break :brk @truncate(u32, bun.hash("string_decoder@0.0.0-polyfill"));
},
.main_fields = undefined,
@@ -225,7 +226,7 @@ const sys_package_json = PackageJSON{
.name = "sys",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "sys@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("sys@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/sys/package.json", ""),
@@ -234,7 +235,7 @@ const timers_package_json = PackageJSON{
.name = "timers",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "timers@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("timers@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/timers/package.json", ""),
@@ -243,7 +244,7 @@ const tty_package_json = PackageJSON{
.name = "tty",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "tty@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("tty@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/tty/package.json", ""),
@@ -252,7 +253,7 @@ const url_package_json = PackageJSON{
.name = "url",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "url@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("url@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/url/package.json", ""),
@@ -261,7 +262,7 @@ const util_package_json = PackageJSON{
.name = "util",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "util@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("util@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/util/package.json", ""),
@@ -270,7 +271,7 @@ const zlib_package_json = PackageJSON{
.name = "zlib",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "zlib@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("zlib@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/zlib/package.json", ""),
@@ -280,7 +281,7 @@ const node_fetch_package_json = PackageJSON{
.name = "node-fetch",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "node-fetch@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("node-fetch@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/node-fetch/package.json", ""),
@@ -289,7 +290,7 @@ const isomorphic_fetch_package_json = PackageJSON{
.name = "isomorphic-fetch",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "isomorphic-fetch@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("isomorphic-fetch@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/isomorphic-fetch/package.json", ""),
@@ -298,7 +299,7 @@ const supports_color_package_json = PackageJSON{
.name = "supports-color",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "supports-color@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("supports-color@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/supports-color/package.json", ""),
@@ -308,7 +309,7 @@ const vercel_fetch_package_json = PackageJSON{
.name = "@vercel/fetch",
.version = "0.0.0-polyfill",
.module_type = .cjs,
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, "@vercel/fetch@0.0.0-polyfill")),
+ .hash = @truncate(u32, bun.hash("@vercel/fetch@0.0.0-polyfill")),
.main_fields = undefined,
.browser_map = undefined,
.source = logger.Source.initPathString("/bun-vfs/node_modules/@vercel/fetch/package.json", ""),
diff --git a/src/node_module_bundle.zig b/src/node_module_bundle.zig
index c70a58419..6682e2dff 100644
--- a/src/node_module_bundle.zig
+++ b/src/node_module_bundle.zig
@@ -107,7 +107,7 @@ pub const NodeModuleBundle = struct {
// This catches any issues with the sorting order, which would cause all sorts of weird bugs
// This also allows us to simply extend the length of the previous slice to the new length
// Saving us an allocation
- if (@ptrToInt(prev_package_ids_for_name.ptr) != @ptrToInt(entry.value_ptr.ptr)) {
+ if (@intFromPtr(prev_package_ids_for_name.ptr) != @intFromPtr(entry.value_ptr.ptr)) {
Output.prettyErrorln(
\\<r><red>Fatal<r>: incorrect package sorting order detected in .bun file.\n
\\This is a bug! Please create an issue.\n
@@ -225,7 +225,7 @@ pub const NodeModuleBundle = struct {
const lhs_name = context.moduleName(&lhs);
const rhs_name = context.moduleName(&rhs);
- const traversal_length = std.math.min(lhs_name.len, rhs_name.len);
+ const traversal_length = @min(lhs_name.len, rhs_name.len);
for (lhs_name[0..traversal_length], 0..) |char, i| {
switch (std.math.order(char, rhs_name[i])) {
@@ -283,7 +283,7 @@ pub const NodeModuleBundle = struct {
const lhs_name = context.moduleName(&lhs);
const rhs_name = context.moduleName(&rhs);
- const traversal_length = std.math.min(lhs_name.len, rhs_name.len);
+ const traversal_length = @min(lhs_name.len, rhs_name.len);
for (lhs_name[0..traversal_length], 0..) |char, i| {
switch (std.math.order(char, rhs_name[i])) {
@@ -431,16 +431,16 @@ pub const NodeModuleBundle = struct {
switch (size) {
0...1024 * 1024 => {
switch (level) {
- .bad => Output.pretty("<red>{d: " ++ align_char ++ "6.2} KB</r>", .{@intToFloat(f64, size) / 1024.0}),
- .neutral => Output.pretty("{d: " ++ align_char ++ "6.2} KB</r>", .{@intToFloat(f64, size) / 1024.0}),
- .good => Output.pretty("<green>{d: " ++ align_char ++ "6.2} KB</r>", .{@intToFloat(f64, size) / 1024.0}),
+ .bad => Output.pretty("<red>{d: " ++ align_char ++ "6.2} KB</r>", .{@floatFromInt(f64, size) / 1024.0}),
+ .neutral => Output.pretty("{d: " ++ align_char ++ "6.2} KB</r>", .{@floatFromInt(f64, size) / 1024.0}),
+ .good => Output.pretty("<green>{d: " ++ align_char ++ "6.2} KB</r>", .{@floatFromInt(f64, size) / 1024.0}),
}
},
else => {
switch (level) {
- .bad => Output.pretty("<red>{d: " ++ align_char ++ "6.2} MB</r>", .{@intToFloat(f64, size) / (1024 * 1024.0)}),
- .neutral => Output.pretty("{d: " ++ align_char ++ "6.2} MB</r>", .{@intToFloat(f64, size) / (1024 * 1024.0)}),
- .good => Output.pretty("<green>{d: " ++ align_char ++ "6.2} MB</r>", .{@intToFloat(f64, size) / (1024 * 1024.0)}),
+ .bad => Output.pretty("<red>{d: " ++ align_char ++ "6.2} MB</r>", .{@floatFromInt(f64, size) / (1024 * 1024.0)}),
+ .neutral => Output.pretty("{d: " ++ align_char ++ "6.2} MB</r>", .{@floatFromInt(f64, size) / (1024 * 1024.0)}),
+ .good => Output.pretty("<green>{d: " ++ align_char ++ "6.2} MB</r>", .{@floatFromInt(f64, size) / (1024 * 1024.0)}),
}
},
}
@@ -459,7 +459,7 @@ pub const NodeModuleBundle = struct {
var read_amount: i64 = 99999;
while (remain > 0 and read_amount > 0) {
read_amount = @intCast(i64, in.read(&buf) catch 0);
- remain -= @intCast(i64, try out.write(buf[0..@intCast(usize, std.math.min(read_amount, remain))]));
+ remain -= @intCast(i64, try out.write(buf[0..@intCast(usize, @min(read_amount, remain))]));
}
}
};
diff --git a/src/options.zig b/src/options.zig
index 08eb7b4b7..3a4eaa9eb 100644
--- a/src/options.zig
+++ b/src/options.zig
@@ -1699,7 +1699,7 @@ pub const BundleOptions = struct {
opts.node_modules_bundle_pretty_path = try allocator.dupe(u8, pretty_path);
}
- const elapsed = @intToFloat(f64, (std.time.nanoTimestamp() - time_start)) / std.time.ns_per_ms;
+ const elapsed = @floatFromInt(f64, (std.time.nanoTimestamp() - time_start)) / std.time.ns_per_ms;
Output.printElapsed(elapsed);
Output.prettyErrorln(
" <b><d>\"{s}\"<r><d> - {d} modules, {d} packages<r>",
@@ -2779,7 +2779,7 @@ pub const PathTemplate = struct {
};
if (count == 0) {
- end_len = @ptrToInt(c) - @ptrToInt(remain.ptr);
+ end_len = @intFromPtr(c) - @intFromPtr(remain.ptr);
std.debug.assert(end_len <= remain.len);
break;
}
diff --git a/src/output.zig b/src/output.zig
index 683e39164..cf58cbccf 100644
--- a/src/output.zig
+++ b/src/output.zig
@@ -270,21 +270,21 @@ pub const ElapsedFormatter = struct {
0...std.time.ns_per_ms * 10 => {
const fmt_str = "<r><d>[{d:>.2}ms<r><d>]<r>";
switch (self.colors) {
- inline else => |colors| try writer_.print(comptime prettyFmt(fmt_str, colors), .{@intToFloat(f64, self.duration_ns) / std.time.ns_per_ms}),
+ inline else => |colors| try writer_.print(comptime prettyFmt(fmt_str, colors), .{@floatFromInt(f64, self.duration_ns) / std.time.ns_per_ms}),
}
},
std.time.ns_per_ms * 8_000...std.math.maxInt(u64) => {
const fmt_str = "<r><d>[<r><yellow>{d:>.2}ms<r><d>]<r>";
switch (self.colors) {
- inline else => |colors| try writer_.print(comptime prettyFmt(fmt_str, colors), .{@intToFloat(f64, self.duration_ns) / std.time.ns_per_ms}),
+ inline else => |colors| try writer_.print(comptime prettyFmt(fmt_str, colors), .{@floatFromInt(f64, self.duration_ns) / std.time.ns_per_ms}),
}
},
else => {
const fmt_str = "<r><d>[<b>{d:>.2}ms<r><d>]<r>";
switch (self.colors) {
- inline else => |colors| try writer_.print(comptime prettyFmt(fmt_str, colors), .{@intToFloat(f64, self.duration_ns) / std.time.ns_per_ms}),
+ inline else => |colors| try writer_.print(comptime prettyFmt(fmt_str, colors), .{@floatFromInt(f64, self.duration_ns) / std.time.ns_per_ms}),
}
},
}
@@ -292,7 +292,7 @@ pub const ElapsedFormatter = struct {
};
inline fn printElapsedToWithCtx(elapsed: f64, comptime printerFn: anytype, comptime has_ctx: bool, ctx: anytype) void {
- switch (@floatToInt(i64, @round(elapsed))) {
+ switch (@intFromFloat(i64, @round(elapsed))) {
0...1500 => {
const fmt = "<r><d>[<b>{d:>.2}ms<r><d>]<r>";
const args = .{elapsed};
@@ -328,7 +328,7 @@ pub fn printElapsedStdout(elapsed: f64) void {
}
pub fn printElapsedStdoutTrim(elapsed: f64) void {
- switch (@floatToInt(i64, @round(elapsed))) {
+ switch (@intFromFloat(i64, @round(elapsed))) {
0...1500 => {
const fmt = "<r><d>[<b>{d:>}ms<r><d>]<r>";
const args = .{elapsed};
@@ -345,18 +345,18 @@ pub fn printElapsedStdoutTrim(elapsed: f64) void {
pub fn printStartEnd(start: i128, end: i128) void {
const elapsed = @divTrunc(@truncate(i64, end - start), @as(i64, std.time.ns_per_ms));
- printElapsed(@intToFloat(f64, elapsed));
+ printElapsed(@floatFromInt(f64, elapsed));
}
pub fn printStartEndStdout(start: i128, end: i128) void {
const elapsed = @divTrunc(@truncate(i64, end - start), @as(i64, std.time.ns_per_ms));
- printElapsedStdout(@intToFloat(f64, elapsed));
+ printElapsedStdout(@floatFromInt(f64, elapsed));
}
pub fn printTimer(timer: *SystemTimer) void {
if (comptime Environment.isWasm) return;
const elapsed = @divTrunc(timer.read(), @as(u64, std.time.ns_per_ms));
- printElapsed(@intToFloat(f64, elapsed));
+ printElapsed(@floatFromInt(f64, elapsed));
}
pub noinline fn printErrorable(comptime fmt: string, args: anytype) !void {
@@ -692,7 +692,7 @@ pub const DebugTimer = struct {
var _opts = opts;
_opts.precision = 3;
std.fmt.formatFloatDecimal(
- @floatCast(f64, @intToFloat(f64, timer.read()) / std.time.ns_per_ms),
+ @floatCast(f64, @floatFromInt(f64, timer.read()) / std.time.ns_per_ms),
_opts,
writer_,
) catch unreachable;
diff --git a/src/renamer.zig b/src/renamer.zig
index 0177725c6..8f6af149f 100644
--- a/src/renamer.zig
+++ b/src/renamer.zig
@@ -156,7 +156,7 @@ pub const MinifyRenamer = struct {
for (first_top_level_slots.slots.values, 0..) |count, ns| {
slots.values[ns] = try std.ArrayList(SymbolSlot).initCapacity(allocator, count);
slots.values[ns].items.len = count;
- std.mem.set(SymbolSlot, slots.values[ns].items[0..count], SymbolSlot{});
+ @memset(slots.values[ns].items[0..count], SymbolSlot{});
}
renamer.* = MinifyRenamer{
@@ -297,7 +297,7 @@ pub const MinifyRenamer = struct {
.count = slot.count,
};
}
- std.sort.sort(SlotAndCount, sorted.items, {}, SlotAndCount.lessThan);
+ std.sort.block(SlotAndCount, sorted.items, {}, SlotAndCount.lessThan);
var next_name: isize = 0;
@@ -395,7 +395,7 @@ pub fn assignNestedScopeSlotsHelper(sorted_members: *std.ArrayList(u32), scope:
sorted_members_buf[i] = member.ref.innerIndex();
i += 1;
}
- std.sort.sort(u32, sorted_members_buf, {}, std.sort.asc(u32));
+ std.sort.block(u32, sorted_members_buf, {}, std.sort.asc(u32));
// Assign slots for this scope's symbols. Only do this if the slot is
// not already assigned. Nested scopes have copies of symbols from parent
@@ -519,7 +519,7 @@ pub const NumberRenamer = struct {
const prev_cap = inner.len;
inner.ensureUnusedCapacity(r.allocator, new_len - prev_cap) catch unreachable;
const to_write = inner.ptr[prev_cap..inner.cap];
- @memset(std.mem.sliceAsBytes(to_write).ptr, 0, std.mem.sliceAsBytes(to_write).len);
+ @memset(std.mem.sliceAsBytes(to_write), 0);
}
inner.len = new_len;
inner.mut(ref.innerIndex()).* = name;
@@ -553,7 +553,7 @@ pub const NumberRenamer = struct {
symbols.dump();
}
- @memset(std.mem.sliceAsBytes(renamer.names).ptr, 0, std.mem.sliceAsBytes(renamer.names).len);
+ @memset(std.mem.sliceAsBytes(renamer.names), 0);
return renamer;
}
@@ -593,7 +593,7 @@ pub const NumberRenamer = struct {
remaining = remaining[1..];
}
std.debug.assert(remaining.len == 0);
- std.sort.sort(u32, sorted.items, {}, std.sort.asc(u32));
+ std.sort.block(u32, sorted.items, {}, std.sort.asc(u32));
for (sorted.items) |inner_index| {
r.assignName(s, Ref.init(@intCast(Ref.Int, inner_index), source_index, false));
diff --git a/src/report.zig b/src/report.zig
index 92f051427..c2f466b03 100644
--- a/src/report.zig
+++ b/src/report.zig
@@ -190,7 +190,7 @@ pub fn fatal(err_: ?anyerror, msg_: ?string) void {
}
if (msg_) |msg| {
- const msg_ptr = @ptrToInt(msg.ptr);
+ const msg_ptr = @intFromPtr(msg.ptr);
if (msg_ptr > 0) {
const len = @max(@min(msg.len, 1024), 0);
@@ -470,7 +470,7 @@ pub noinline fn globalError(err: anyerror, trace_: @TypeOf(@errorReturnTrace()))
print_stacktrace: {
var debug_info = std.debug.getSelfDebugInfo() catch break :print_stacktrace;
Output.disableBuffering();
- std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.debug.detectTTYConfig(std.io.getStdErr())) catch break :print_stacktrace;
+ std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.io.tty.detectConfig(std.io.getStdErr())) catch break :print_stacktrace;
}
}
@@ -539,7 +539,7 @@ pub noinline fn globalError(err: anyerror, trace_: @TypeOf(@errorReturnTrace()))
print_stacktrace: {
var debug_info = std.debug.getSelfDebugInfo() catch break :print_stacktrace;
Output.disableBuffering();
- std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.debug.detectTTYConfig(std.io.getStdErr())) catch break :print_stacktrace;
+ std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.io.tty.detectConfig(std.io.getStdErr())) catch break :print_stacktrace;
}
}
@@ -555,7 +555,7 @@ pub noinline fn globalError(err: anyerror, trace_: @TypeOf(@errorReturnTrace()))
print_stacktrace: {
var debug_info = std.debug.getSelfDebugInfo() catch break :print_stacktrace;
Output.disableBuffering();
- std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.debug.detectTTYConfig(std.io.getStdErr())) catch break :print_stacktrace;
+ std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.io.tty.detectConfig(std.io.getStdErr())) catch break :print_stacktrace;
}
}
@@ -572,7 +572,7 @@ pub noinline fn globalError(err: anyerror, trace_: @TypeOf(@errorReturnTrace()))
print_stacktrace: {
var debug_info = std.debug.getSelfDebugInfo() catch break :print_stacktrace;
Output.disableBuffering();
- std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.debug.detectTTYConfig(std.io.getStdErr())) catch break :print_stacktrace;
+ std.debug.writeStackTrace(trace.*, Output.errorWriter(), default_allocator, debug_info, std.io.tty.detectConfig(std.io.getStdErr())) catch break :print_stacktrace;
}
}
diff --git a/src/resolver/package_json.zig b/src/resolver/package_json.zig
index 63bc5b20b..e759374e7 100644
--- a/src/resolver/package_json.zig
+++ b/src/resolver/package_json.zig
@@ -59,7 +59,7 @@ pub const PackageJSON = struct {
pub fn generateHash(package_json: *PackageJSON) void {
var hashy: [1024]u8 = undefined;
- std.mem.set(u8, &hashy, 0);
+ @memset(&hashy, 0);
var used: usize = 0;
bun.copy(u8, &hashy, package_json.name);
used = package_json.name.len;
@@ -390,7 +390,7 @@ pub const PackageJSON = struct {
var count: usize = 0;
const items = array.items.slice();
for (items) |item| {
- count += @boolToInt(item.data == .e_string and item.data.e_string.data.len > 0);
+ count += @intFromBool(item.data == .e_string and item.data.e_string.data.len > 0);
}
switch (count) {
0 => {},
@@ -888,10 +888,10 @@ pub const PackageJSON = struct {
const dependency_groups = comptime brk: {
var out_groups: [
- @as(usize, @boolToInt(features.dependencies)) +
- @as(usize, @boolToInt(features.dev_dependencies)) +
- @as(usize, @boolToInt(features.optional_dependencies)) +
- @as(usize, @boolToInt(features.peer_dependencies))
+ @as(usize, @intFromBool(features.dependencies)) +
+ @as(usize, @intFromBool(features.dev_dependencies)) +
+ @as(usize, @intFromBool(features.optional_dependencies)) +
+ @as(usize, @intFromBool(features.peer_dependencies))
]DependencyGroup = undefined;
var out_group_i: usize = 0;
if (features.dependencies) {
@@ -989,7 +989,7 @@ pub const PackageJSON = struct {
const key = prop.key.?.asString(allocator) orelse continue;
const value = prop.value.?.asString(allocator) orelse continue;
- count += @as(usize, @boolToInt(key.len > 0 and value.len > 0));
+ count += @as(usize, @intFromBool(key.len > 0 and value.len > 0));
}
if (count == 0) break :read_scripts;
@@ -1022,7 +1022,7 @@ pub const PackageJSON = struct {
}
pub fn hashModule(this: *const PackageJSON, module: string) u32 {
- var hasher = std.hash.Wyhash.init(0);
+ var hasher = bun.Wyhash.init(0);
hasher.update(std.mem.asBytes(&this.hash));
hasher.update(module);
@@ -1148,7 +1148,7 @@ pub const ExportsMap = struct {
// PATTERN_KEY_COMPARE which orders in descending order of specificity.
const GlobLengthSorter: type = strings.NewGlobLengthSorter(Entry.Data.Map.MapEntry, "key");
var sorter = GlobLengthSorter{};
- std.sort.sort(Entry.Data.Map.MapEntry, expansion_keys, sorter, GlobLengthSorter.lessThan);
+ std.sort.block(Entry.Data.Map.MapEntry, expansion_keys, sorter, GlobLengthSorter.lessThan);
return Entry{
.data = .{
diff --git a/src/resolver/resolve_path.zig b/src/resolver/resolve_path.zig
index c5ffdc626..e63318887 100644
--- a/src/resolver/resolve_path.zig
+++ b/src/resolver/resolve_path.zig
@@ -376,7 +376,7 @@ pub fn relativeToCommonPath(
var out_slice: []u8 = buf[0..0];
if (normalized_from.len > 0) {
- var i: usize = @intCast(usize, @boolToInt(normalized_from[0] == separator)) + 1 + last_common_separator;
+ var i: usize = @intCast(usize, @intFromBool(normalized_from[0] == separator)) + 1 + last_common_separator;
while (i <= normalized_from.len) : (i += 1) {
if (i == normalized_from.len or (normalized_from[i] == separator and i + 1 < normalized_from.len)) {
@@ -549,7 +549,7 @@ pub fn normalizeStringGeneric(path: []const u8, buf: []u8, comptime allow_above_
const from = r;
while (r < n and !isSeparator(path[r])) : (r += 1) {}
const count = r - from;
- @memcpy(buf[buf_i..].ptr, path[from..].ptr, count);
+ @memcpy(buf[buf_i..][0..count], path[from..][0..count]);
buf_i += count;
}
diff --git a/src/resolver/resolver.zig b/src/resolver/resolver.zig
index 8a6a2bc5e..14bc358d0 100644
--- a/src/resolver/resolver.zig
+++ b/src/resolver/resolver.zig
@@ -27,7 +27,6 @@ const CacheSet = cache.Set;
const DataURL = @import("./data_url.zig").DataURL;
pub const DirInfo = @import("./dir_info.zig");
const HTTPWatcher = if (Environment.isTest or Environment.isWasm) void else @import("../http.zig").Watcher;
-const Wyhash = std.hash.Wyhash;
const ResolvePath = @import("./resolve_path.zig");
const NodeFallbackModules = @import("../node_fallbacks.zig");
const Mutex = @import("../lock.zig").Lock;
@@ -283,10 +282,10 @@ pub const Result = struct {
if (strings.lastIndexOf(module, node_module_root)) |end_| {
var end: usize = end_ + node_module_root.len;
- return @truncate(u32, std.hash.Wyhash.hash(0, module[end..]));
+ return @truncate(u32, bun.hash(module[end..]));
}
- return @truncate(u32, std.hash.Wyhash.hash(0, this.path_pair.primary.text));
+ return @truncate(u32, bun.hash(this.path_pair.primary.text));
}
};
@@ -609,7 +608,7 @@ pub const Resolver = struct {
if (r.debug_logs) |*debug| {
if (flush_mode == DebugLogs.FlushMode.fail) {
try r.log.addRangeDebugWithNotes(null, logger.Range{ .loc = logger.Loc{} }, debug.what, try debug.notes.toOwnedSlice());
- } else if (@enumToInt(r.log.level) <= @enumToInt(logger.Log.Level.verbose)) {
+ } else if (@intFromEnum(r.log.level) <= @intFromEnum(logger.Log.Level.verbose)) {
try r.log.addVerboseWithNotes(null, logger.Loc.Empty, debug.what, try debug.notes.toOwnedSlice());
}
}
@@ -1265,7 +1264,7 @@ pub const Resolver = struct {
if (NodeFallbackModules.Map.get(import_path_without_node_prefix)) |*fallback_module| {
result.path_pair.primary = fallback_module.path;
result.module_type = .cjs;
- result.package_json = @intToPtr(*PackageJSON, @ptrToInt(fallback_module.package_json));
+ result.package_json = @ptrFromInt(*PackageJSON, @intFromPtr(fallback_module.package_json));
result.is_from_node_modules = true;
return .{ .success = result };
// "node:*
@@ -1696,7 +1695,7 @@ pub const Resolver = struct {
// check the global cache directory for a package.json file.
var manager = r.getPackageManager();
var dependency_version: Dependency.Version = .{};
- var dependency_behavior = @intToEnum(Dependency.Behavior, Dependency.Behavior.normal);
+ var dependency_behavior = @enumFromInt(Dependency.Behavior, Dependency.Behavior.normal);
// const initial_pending_tasks = manager.pending_tasks;
var resolved_package_id: Install.PackageID = brk: {
@@ -2629,7 +2628,7 @@ pub const Resolver = struct {
// Directories must always end in a trailing slash or else various bugs can occur.
// This covers "what happens when the trailing"
- end += @intCast(usize, @boolToInt(safe_path.len > end and end > 0 and safe_path[end - 1] != std.fs.path.sep and safe_path[end] == std.fs.path.sep));
+ end += @intCast(usize, @intFromBool(safe_path.len > end and end > 0 and safe_path[end - 1] != std.fs.path.sep and safe_path[end] == std.fs.path.sep));
break :brk safe_path[dir_path_i..end];
};
diff --git a/src/resolver/tsconfig_json.zig b/src/resolver/tsconfig_json.zig
index 4f04c39ca..2ec402fd2 100644
--- a/src/resolver/tsconfig_json.zig
+++ b/src/resolver/tsconfig_json.zig
@@ -344,7 +344,7 @@ pub const TSConfigJSON = struct {
// foo == 1
// foo.bar.baz == 3
// foo.bar.baz.bun == 4
- const parts_count = std.mem.count(u8, text, ".") + @as(usize, @boolToInt(text[text.len - 1] != '.'));
+ const parts_count = std.mem.count(u8, text, ".") + @as(usize, @intFromBool(text[text.len - 1] != '.'));
var parts = std.ArrayList(string).initCapacity(allocator, parts_count) catch unreachable;
if (parts_count == 1) {
diff --git a/src/router.zig b/src/router.zig
index 3e0dc0dba..8ed16f102 100644
--- a/src/router.zig
+++ b/src/router.zig
@@ -28,7 +28,7 @@ const URLPath = @import("./http/url_path.zig");
const PathnameScanner = @import("./url.zig").PathnameScanner;
const CodepointIterator = @import("./string_immutable.zig").CodepointIterator;
-const index_route_hash = @truncate(u32, std.hash.Wyhash.hash(0, "$$/index-route$$-!(@*@#&*%-901823098123"));
+const index_route_hash = @truncate(u32, bun.hash("$$/index-route$$-!(@*@#&*%-901823098123"));
const arbitrary_max_route = 4096;
pub const Param = struct {
@@ -335,7 +335,7 @@ const RouteLoader = struct {
const relative_dir = FileSystem.instance.relative(base_dir, config.dir);
if (!strings.hasPrefixComptime(relative_dir, "..")) {
- route_dirname_len = @truncate(u16, relative_dir.len + @as(usize, @boolToInt(config.dir[config.dir.len - 1] != std.fs.path.sep)));
+ route_dirname_len = @truncate(u16, relative_dir.len + @as(usize, @intFromBool(config.dir[config.dir.len - 1] != std.fs.path.sep)));
}
var this = RouteLoader{
@@ -356,7 +356,7 @@ const RouteLoader = struct {
.allocator = allocator,
};
- std.sort.sort(*Route, this.all_routes.items, Route.Sorter{}, Route.Sorter.sortByName);
+ std.sort.block(*Route, this.all_routes.items, Route.Sorter{}, Route.Sorter.sortByName);
var route_list = RouteIndex.List{};
route_list.setCapacity(allocator, this.all_routes.items.len) catch unreachable;
@@ -365,7 +365,7 @@ const RouteLoader = struct {
var index_id: ?usize = null;
for (this.all_routes.items, 0..) |route, i| {
- if (@enumToInt(route.kind) > @enumToInt(Pattern.Tag.static) and dynamic_start == null) {
+ if (@intFromEnum(route.kind) > @intFromEnum(Pattern.Tag.static) and dynamic_start == null) {
dynamic_start = i;
}
@@ -521,14 +521,14 @@ pub const TinyPtr = packed struct {
pub fn from(parent: string, in: string) TinyPtr {
if (in.len == 0 or parent.len == 0) return TinyPtr{};
- const right = @ptrToInt(in.ptr) + in.len;
- const end = @ptrToInt(parent.ptr) + parent.len;
+ const right = @intFromPtr(in.ptr) + in.len;
+ const end = @intFromPtr(parent.ptr) + parent.len;
if (comptime Environment.isDebug) {
std.debug.assert(end < right);
}
const length = @max(end, right) - right;
- const offset = @max(@ptrToInt(in.ptr), @ptrToInt(parent.ptr)) - @ptrToInt(parent.ptr);
+ const offset = @max(@intFromPtr(in.ptr), @intFromPtr(parent.ptr)) - @intFromPtr(parent.ptr);
return TinyPtr{ .offset = @truncate(u16, offset), .len = @truncate(u16, length) };
}
};
@@ -605,7 +605,7 @@ pub const Route = struct {
// - static routes go first because we match those first
// - dynamic, catch-all, and optional catch all routes are sorted lexicographically, except "[", "]" appear last so that deepest routes are tested first
// - catch-all & optional catch-all appear at the end because we want to test those at the end.
- return switch (std.math.order(@enumToInt(a.kind), @enumToInt(b.kind))) {
+ return switch (std.math.order(@intFromEnum(a.kind), @intFromEnum(b.kind))) {
.eq => switch (a.kind) {
// static + dynamic are sorted alphabetically
.static, .dynamic => @call(
@@ -676,7 +676,7 @@ pub const Route = struct {
buf = buf[base.len..];
bun.copy(u8, buf, extname);
buf = buf[extname.len..];
- break :brk route_file_buf[0 .. @ptrToInt(buf.ptr) - @ptrToInt(&route_file_buf)];
+ break :brk route_file_buf[0 .. @intFromPtr(buf.ptr) - @intFromPtr(&route_file_buf)];
};
var name = public_path[0 .. public_path.len - extname.len];
@@ -711,7 +711,7 @@ pub const Route = struct {
has_uppercase = public_path[name_i] >= 'A' and public_path[name_i] <= 'Z';
}
- const name_offset = @ptrToInt(name.ptr) - @ptrToInt(public_path.ptr);
+ const name_offset = @intFromPtr(name.ptr) - @intFromPtr(public_path.ptr);
if (has_uppercase) {
public_path = FileSystem.DirnameStore.instance.append(@TypeOf(public_path), public_path) catch unreachable;
@@ -770,7 +770,7 @@ pub const Route = struct {
.full_hash = if (is_index)
index_route_hash
else
- @truncate(u32, std.hash.Wyhash.hash(0, name)),
+ @truncate(u32, bun.hash(name)),
.param_count = validation_result.param_count,
.kind = validation_result.kind,
.abs_path = entry.abs_path,
@@ -1183,7 +1183,7 @@ const Pattern = struct {
var count: u16 = 0;
var offset: RoutePathInt = 0;
std.debug.assert(input.len > 0);
- var kind: u4 = @enumToInt(Tag.static);
+ var kind: u4 = @intFromEnum(Tag.static);
const end = @truncate(u32, input.len - 1);
while (offset < end) {
const pattern: Pattern = Pattern.initUnhashed(input, offset) catch |err| {
@@ -1247,11 +1247,11 @@ const Pattern = struct {
return null;
};
offset = pattern.len;
- kind = @max(@enumToInt(@as(Pattern.Tag, pattern.value)), kind);
- count += @intCast(u16, @boolToInt(@enumToInt(@as(Pattern.Tag, pattern.value)) > @enumToInt(Pattern.Tag.static)));
+ kind = @max(@intFromEnum(@as(Pattern.Tag, pattern.value)), kind);
+ count += @intCast(u16, @intFromBool(@intFromEnum(@as(Pattern.Tag, pattern.value)) > @intFromEnum(Pattern.Tag.static)));
}
- return ValidationResult{ .param_count = count, .kind = @intToEnum(Tag, kind) };
+ return ValidationResult{ .param_count = count, .kind = @enumFromInt(Tag, kind) };
}
pub fn eql(a: Pattern, b: Pattern) bool {
@@ -1369,7 +1369,7 @@ const Pattern = struct {
i += 1;
}
- if (@enumToInt(tag) > @enumToInt(Tag.dynamic) and i <= end) return error.CatchAllMustBeAtTheEnd;
+ if (@intFromEnum(tag) > @intFromEnum(Tag.dynamic) and i <= end) return error.CatchAllMustBeAtTheEnd;
return Pattern{
.len = @min(i + 1, end),
diff --git a/src/runtime.zig b/src/runtime.zig
index 6916df6b1..072258747 100644
--- a/src/runtime.zig
+++ b/src/runtime.zig
@@ -406,7 +406,7 @@ pub const Runtime = struct {
return std.mem.order(u8, a, b) == .lt;
}
};
- std.sort.sort(string, &list, {}, Sorter.compare);
+ std.sort.block(string, &list, {}, Sorter.compare);
break :brk list;
};
diff --git a/src/sha.zig b/src/sha.zig
index cd9fd0f0a..8faf9fbb2 100644
--- a/src/sha.zig
+++ b/src/sha.zig
@@ -212,7 +212,7 @@ pub fn main() anyerror!void {
{
var clock1 = try std.time.Timer.start();
- std.mem.doNotOptimizeAway(std.hash.Wyhash.hash(0, bytes));
+ std.mem.doNotOptimizeAway(bun.hash(bytes));
const zig_time = clock1.read();
std.debug.print(
"Wyhash:\n\n zig: {any}\n\n",
@@ -251,10 +251,10 @@ pub fn main() anyerror!void {
var digest2: DigestType = undefined;
var digest3: DigestType = undefined;
var digest4: DigestType = undefined;
- @memset(&digest1, 0, @sizeOf(DigestType));
- @memset(&digest2, 0, @sizeOf(DigestType));
- @memset(&digest3, 0, @sizeOf(DigestType));
- @memset(&digest4, 0, @sizeOf(DigestType));
+ @memset(@ptrCast([*]u8, &digest1)[0..@sizeOf(DigestType)], 0);
+ @memset(@ptrCast([*]u8, &digest2)[0..@sizeOf(DigestType)], 0);
+ @memset(@ptrCast([*]u8, &digest3)[0..@sizeOf(DigestType)], 0);
+ @memset(@ptrCast([*]u8, &digest4)[0..@sizeOf(DigestType)], 0);
defer {
std.mem.doNotOptimizeAway(&digest1);
std.mem.doNotOptimizeAway(&digest2);
diff --git a/src/sourcemap/sourcemap.zig b/src/sourcemap/sourcemap.zig
index f1bbcc4c1..0b245d8c7 100644
--- a/src/sourcemap/sourcemap.zig
+++ b/src/sourcemap/sourcemap.zig
@@ -871,14 +871,14 @@ pub const LineOffsetTable = struct {
if (column == 0) {
line_byte_offset = @truncate(
u32,
- @ptrToInt(remaining.ptr) - @ptrToInt(contents.ptr),
+ @intFromPtr(remaining.ptr) - @intFromPtr(contents.ptr),
);
}
if (c > 0x7F and columns_for_non_ascii.items.len == 0) {
- std.debug.assert(@ptrToInt(
+ std.debug.assert(@intFromPtr(
remaining.ptr,
- ) >= @ptrToInt(
+ ) >= @intFromPtr(
contents.ptr,
));
// we have a non-ASCII character, so we need to keep track of the
@@ -886,9 +886,9 @@ pub const LineOffsetTable = struct {
columns_for_non_ascii.appendAssumeCapacity(column);
column_byte_offset = @intCast(
u32,
- (@ptrToInt(
+ (@intFromPtr(
remaining.ptr,
- ) - @ptrToInt(
+ ) - @intFromPtr(
contents.ptr,
)) - line_byte_offset,
);
@@ -899,7 +899,7 @@ pub const LineOffsetTable = struct {
if (columns_for_non_ascii.items.len > 0) {
const line_bytes_so_far = @intCast(u32, @truncate(
u32,
- @ptrToInt(remaining.ptr) - @ptrToInt(contents.ptr),
+ @intFromPtr(remaining.ptr) - @intFromPtr(contents.ptr),
)) - line_byte_offset;
columns_for_non_ascii.ensureUnusedCapacity((line_bytes_so_far - column_byte_offset) + 1) catch unreachable;
while (column_byte_offset <= line_bytes_so_far) : (column_byte_offset += 1) {
@@ -956,7 +956,7 @@ pub const LineOffsetTable = struct {
},
else => {
// Mozilla's "source-map" library counts columns using UTF-16 code units
- column += @as(i32, @boolToInt(c > 0xFFFF)) + 1;
+ column += @as(i32, @intFromBool(c > 0xFFFF)) + 1;
},
}
@@ -1032,7 +1032,7 @@ pub fn appendMappingToBuffer(buffer_: MutableString, last_byte: u8, prev_state:
@as(u32, vlq[1].len) +
@as(u32, vlq[2].len) +
@as(u32, vlq[3].len);
- buffer.growIfNeeded(total_len + @as(u32, @boolToInt(needs_comma))) catch unreachable;
+ buffer.growIfNeeded(total_len + @as(u32, @intFromBool(needs_comma))) catch unreachable;
// Put commas in between mappings
if (needs_comma) {
@@ -1081,12 +1081,12 @@ pub const Chunk = struct {
filename = filename[FileSystem.instance.top_level_dir.len - 1 ..];
} else if (filename.len > 0 and filename[0] != '/') {
filename_buf[0] = '/';
- @memcpy(filename_buf[1..], filename.ptr, filename.len);
+ @memcpy(filename_buf[1..][0..filename.len], filename);
filename = filename_buf[0 .. filename.len + 1];
}
output.growIfNeeded(
- filename.len + 2 + (source.contents.len * @as(usize, @boolToInt(include_sources_contents))) + chunk.buffer.list.items.len + 32 + 39 + 29 + 22 + 20,
+ filename.len + 2 + (source.contents.len * @as(usize, @intFromBool(include_sources_contents))) + chunk.buffer.list.items.len + 32 + 39 + 29 + 22 + 20,
) catch unreachable;
try output.append("{\n \"version\":3,\n \"sources\": [");
@@ -1288,7 +1288,7 @@ pub const Chunk = struct {
else => {
// Mozilla's "source-map" library counts columns using UTF-16 code units
- b.generated_column += @as(i32, @boolToInt(c > 0xFFFF)) + 1;
+ b.generated_column += @as(i32, @intFromBool(c > 0xFFFF)) + 1;
},
}
}
diff --git a/src/standalone_bun.zig b/src/standalone_bun.zig
index 85a689ded..e7363fb58 100644
--- a/src/standalone_bun.zig
+++ b/src/standalone_bun.zig
@@ -468,7 +468,7 @@ pub const StandaloneModuleGraph = struct {
// at the very least
// if you have not a ton of code, we only do a single read() call
if (Environment.allow_assert or offsets.byte_count > 1024 * 3) {
- const offset_from_end = trailer_bytes.len - (@ptrToInt(end) - @ptrToInt(@as([]u8, &trailer_bytes).ptr));
+ const offset_from_end = trailer_bytes.len - (@intFromPtr(end) - @intFromPtr(@as([]u8, &trailer_bytes).ptr));
std.os.lseek_END(self_exe, -@intCast(i64, offset_from_end + offsets.byte_count)) catch return null;
if (comptime Environment.allow_assert) {
@@ -497,7 +497,7 @@ pub const StandaloneModuleGraph = struct {
if (offsets.byte_count <= 1024 * 3) {
// we already have the bytes
end -= offsets.byte_count;
- @memcpy(to_read.ptr, end, offsets.byte_count);
+ @memcpy(to_read[0..offsets.byte_count], end[0..offsets.byte_count]);
if (comptime Environment.allow_assert) {
std.debug.assert(bun.strings.eqlLong(to_read, end[0..offsets.byte_count], true));
}
diff --git a/src/string_immutable.zig b/src/string_immutable.zig
index 9e069bb99..0c90b03ff 100644
--- a/src/string_immutable.zig
+++ b/src/string_immutable.zig
@@ -143,7 +143,7 @@ pub fn repeatingAlloc(allocator: std.mem.Allocator, count: usize, char: u8) ![]u
}
pub fn repeatingBuf(self: []u8, char: u8) void {
- @memset(self.ptr, char, self.len);
+ @memset(self, char);
}
pub fn indexOfCharNeg(self: string, char: u8) i32 {
@@ -259,7 +259,7 @@ pub inline fn indexOf(self: string, str: string) ?usize {
const start = bun.C.memmem(self_ptr, self_len, str_ptr, str_len) orelse return null;
- const i = @ptrToInt(start) - @ptrToInt(self_ptr);
+ const i = @intFromPtr(start) - @intFromPtr(self_ptr);
std.debug.assert(i < self_len);
return @intCast(usize, i);
}
@@ -370,7 +370,7 @@ pub const StringOrTinyString = struct {
// This is a switch expression instead of a statement to make sure it uses the faster assembly
return switch (this.is_tiny_string) {
1 => this.remainder_buf[0..this.remainder_len],
- 0 => @intToPtr([*]const u8, std.mem.readIntNative(usize, this.remainder_buf[0..@sizeOf(usize)]))[0..std.mem.readIntNative(usize, this.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2])],
+ 0 => @ptrFromInt([*]const u8, std.mem.readIntNative(usize, this.remainder_buf[0..@sizeOf(usize)]))[0..std.mem.readIntNative(usize, this.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2])],
};
}
@@ -408,7 +408,7 @@ pub const StringOrTinyString = struct {
.is_tiny_string = 1,
.remainder_len = @truncate(u7, stringy.len),
};
- @memcpy(&tiny.remainder_buf, stringy.ptr, tiny.remainder_len);
+ @memcpy(tiny.remainder_buf[0..tiny.remainder_len], stringy[0..tiny.remainder_len]);
return tiny;
},
else => {
@@ -416,7 +416,7 @@ pub const StringOrTinyString = struct {
.is_tiny_string = 0,
.remainder_len = 0,
};
- std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @ptrToInt(stringy.ptr));
+ std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr));
std.mem.writeIntNative(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len);
return tiny;
},
@@ -442,7 +442,7 @@ pub const StringOrTinyString = struct {
.is_tiny_string = 0,
.remainder_len = 0,
};
- std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @ptrToInt(stringy.ptr));
+ std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr));
std.mem.writeIntNative(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len);
return tiny;
},
@@ -545,21 +545,21 @@ test "eqlComptimeCheckLen" {
const sizes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 22, 24 };
inline for (sizes) |size| {
var buf: [size]u8 = undefined;
- std.mem.set(u8, &buf, 'a');
+ @memset(&buf, 'a');
var buf_copy: [size]u8 = undefined;
- std.mem.set(u8, &buf_copy, 'a');
+ @memset(&buf_copy, 'a');
var bad: [size]u8 = undefined;
- std.mem.set(u8, &bad, 'b');
+ @memset(&bad, 'b');
try std.testing.expectEqual(std.mem.eql(u8, &buf, &buf_copy), eqlComptime(&buf, comptime brk: {
var buf_copy_: [size]u8 = undefined;
- std.mem.set(u8, &buf_copy_, 'a');
+ @memset(&buf_copy_, 'a');
break :brk buf_copy_;
}));
try std.testing.expectEqual(std.mem.eql(u8, &buf, &bad), eqlComptime(&bad, comptime brk: {
var buf_copy_: [size]u8 = undefined;
- std.mem.set(u8, &buf_copy_, 'a');
+ @memset(&buf_copy_, 'a');
break :brk buf_copy_;
}));
}
@@ -570,21 +570,21 @@ test "eqlComptimeUTF16" {
const sizes = [_]u16{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 22, 24 };
inline for (sizes) |size| {
var buf: [size]u16 = undefined;
- std.mem.set(u16, &buf, @as(u8, 'a'));
+ @memset(&buf, @as(u8, 'a'));
var buf_copy: [size]u16 = undefined;
- std.mem.set(u16, &buf_copy, @as(u8, 'a'));
+ @memset(&buf_copy, @as(u8, 'a'));
var bad: [size]u16 = undefined;
- std.mem.set(u16, &bad, @as(u16, 'b'));
+ @memset(&bad, @as(u16, 'b'));
try std.testing.expectEqual(std.mem.eql(u16, &buf, &buf_copy), eqlComptimeUTF16(&buf, comptime &brk: {
var buf_copy_: [size]u8 = undefined;
- std.mem.set(u8, &buf_copy_, @as(u8, 'a'));
+ @memset(&buf_copy_, @as(u8, 'a'));
break :brk buf_copy_;
}));
try std.testing.expectEqual(std.mem.eql(u16, &buf, &bad), eqlComptimeUTF16(&bad, comptime &brk: {
var buf_copy_: [size]u8 = undefined;
- std.mem.set(u8, &buf_copy_, @as(u8, 'a'));
+ @memset(&buf_copy_, @as(u8, 'a'));
break :brk buf_copy_;
}));
}
@@ -628,7 +628,7 @@ test "StringOrTinyString Lowercase" {
pub fn copy(buf: []u8, src: []const u8) []const u8 {
const len = @min(buf.len, src.len);
if (len > 0)
- @memcpy(buf.ptr, src.ptr, len);
+ @memcpy(buf[0..len], src[0..len]);
return buf[0..len];
}
@@ -777,7 +777,7 @@ pub const QuotedFormatter = struct {
pub fn quotedAlloc(allocator: std.mem.Allocator, self: string) !string {
var count: usize = 0;
for (self) |char| {
- count += @boolToInt(char == '"');
+ count += @intFromBool(char == '"');
}
if (count == 0) {
@@ -822,7 +822,7 @@ pub fn countChar(self: string, char: u8) usize {
}
while (remaining.len > 0) {
- total += @as(usize, @boolToInt(remaining[0] == char));
+ total += @as(usize, @intFromBool(remaining[0] == char));
remaining = remaining[1..];
}
@@ -1035,20 +1035,20 @@ pub fn eqlLong(a_str: string, b_str: string, comptime check_len: bool) bool {
pub inline fn append(allocator: std.mem.Allocator, self: string, other: string) ![]u8 {
var buf = try allocator.alloc(u8, self.len + other.len);
if (self.len > 0)
- @memcpy(buf.ptr, self.ptr, self.len);
+ @memcpy(buf[0..self.len], self);
if (other.len > 0)
- @memcpy(buf.ptr + self.len, other.ptr, other.len);
+ @memcpy(buf[self.len..][0..other.len], other);
return buf;
}
pub inline fn append3(allocator: std.mem.Allocator, self: string, other: string, third: string) ![]u8 {
var buf = try allocator.alloc(u8, self.len + other.len + third.len);
if (self.len > 0)
- @memcpy(buf.ptr, self.ptr, self.len);
+ @memcpy(buf[0..self.len], self);
if (other.len > 0)
- @memcpy(buf.ptr + self.len, other.ptr, other.len);
+ @memcpy(buf[self.len..][0..other.len], other);
if (third.len > 0)
- @memcpy(buf.ptr + self.len + other.len, third.ptr, third.len);
+ @memcpy(buf[self.len + other.len ..][0..third.len], third);
return buf;
}
@@ -1123,13 +1123,13 @@ pub fn copyU8IntoU16WithAlignment(comptime alignment: u21, output_: []align(alig
// un-aligned data access is slow
// so we attempt to align the data
- while (!std.mem.isAligned(@ptrToInt(output.ptr), @alignOf(u16)) and input.len >= word) {
+ while (!std.mem.isAligned(@intFromPtr(output.ptr), @alignOf(u16)) and input.len >= word) {
output[0] = input[0];
output = output[1..];
input = input[1..];
}
- if (std.mem.isAligned(@ptrToInt(output.ptr), @alignOf(u16)) and input.len > 0) {
+ if (std.mem.isAligned(@intFromPtr(output.ptr), @alignOf(u16)) and input.len > 0) {
copyU8IntoU16(@alignCast(@alignOf(u16), output.ptr)[0..output.len], input);
return;
}
@@ -1211,7 +1211,7 @@ pub fn copyLatin1IntoASCII(dest: []u8, src: []const u8) void {
const non_ascii_offset = strings.firstNonASCII(remain) orelse @truncate(u32, remain.len);
if (non_ascii_offset > 0) {
- @memcpy(to.ptr, remain.ptr, non_ascii_offset);
+ @memcpy(to[0..non_ascii_offset], remain[0..non_ascii_offset]);
remain = remain[non_ascii_offset..];
to = to[non_ascii_offset..];
@@ -1498,7 +1498,7 @@ pub fn toUTF8ListWithTypeBun(list_: std.ArrayList(u8), comptime Type: type, utf1
utf16_remaining = utf16_remaining[replacement.len..];
const count: usize = replacement.utf8Width();
- try list.ensureTotalCapacityPrecise(i + count + list.items.len + @floatToInt(usize, (@intToFloat(f64, @truncate(u52, utf16_remaining.len)) * 1.2)));
+ try list.ensureTotalCapacityPrecise(i + count + list.items.len + @intFromFloat(usize, (@floatFromInt(f64, @truncate(u52, utf16_remaining.len)) * 1.2)));
list.items.len += i;
copyU16IntoU8(
@@ -1535,7 +1535,7 @@ pub const EncodeIntoResult = struct {
pub fn allocateLatin1IntoUTF8(allocator: std.mem.Allocator, comptime Type: type, latin1_: Type) ![]u8 {
if (comptime bun.FeatureFlags.latin1_is_now_ascii) {
var out = try allocator.alloc(u8, latin1_.len);
- @memcpy(out.ptr, latin1_.ptr, latin1_.len);
+ @memcpy(out[0..latin1_.len], latin1_);
return out;
}
@@ -1644,7 +1644,7 @@ pub fn allocateLatin1IntoUTF8WithList(list_: std.ArrayList(u8), offset_into_list
}
while (latin1.len > 0 and latin1[0] > 127) {
- i = @ptrToInt(buf.ptr) - @ptrToInt(list.items.ptr);
+ i = @intFromPtr(buf.ptr) - @intFromPtr(list.items.ptr);
list.items.len = i;
try list.ensureUnusedCapacity(2 + latin1.len);
buf = list.items.ptr[i..list.capacity];
@@ -1653,7 +1653,7 @@ pub fn allocateLatin1IntoUTF8WithList(list_: std.ArrayList(u8), offset_into_list
buf = buf[2..];
}
- i = @ptrToInt(buf.ptr) - @ptrToInt(list.items.ptr);
+ i = @intFromPtr(buf.ptr) - @intFromPtr(list.items.ptr);
list.items.len = i;
}
@@ -1778,7 +1778,8 @@ pub fn copyLatin1IntoUTF8(buf_: []u8, comptime Type: type, latin1_: Type) Encode
pub fn copyLatin1IntoUTF8StopOnNonASCII(buf_: []u8, comptime Type: type, latin1_: Type, comptime stop: bool) EncodeIntoResult {
if (comptime bun.FeatureFlags.latin1_is_now_ascii) {
const to_copy = @truncate(u32, @min(buf_.len, latin1_.len));
- @memcpy(buf_.ptr, latin1_.ptr, to_copy);
+ @memcpy(buf_[0..to_copy], latin1_[0..to_copy]);
+
return .{ .written = to_copy, .read = to_copy };
}
@@ -1874,9 +1875,9 @@ pub fn copyLatin1IntoUTF8StopOnNonASCII(buf_: []u8, comptime Type: type, latin1_
{
const end = latin1.ptr + @min(buf.len, latin1.len);
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(latin1.ptr + 8) > @ptrToInt(end));
- const start_ptr = @ptrToInt(buf.ptr);
- const start_ptr_latin1 = @ptrToInt(latin1.ptr);
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(latin1.ptr + 8) > @intFromPtr(end));
+ const start_ptr = @intFromPtr(buf.ptr);
+ const start_ptr_latin1 = @intFromPtr(latin1.ptr);
while (latin1.ptr != end and latin1.ptr[0] <= 127) {
buf.ptr[0] = latin1.ptr[0];
@@ -1884,8 +1885,8 @@ pub fn copyLatin1IntoUTF8StopOnNonASCII(buf_: []u8, comptime Type: type, latin1_
latin1.ptr += 1;
}
- buf.len -= @ptrToInt(buf.ptr) - start_ptr;
- latin1.len -= @ptrToInt(latin1.ptr) - start_ptr_latin1;
+ buf.len -= @intFromPtr(buf.ptr) - start_ptr;
+ latin1.len -= @intFromPtr(latin1.ptr) - start_ptr_latin1;
}
}
@@ -1933,22 +1934,22 @@ pub fn elementLengthLatin1IntoUTF8(comptime Type: type, latin1_: Type) usize {
ptr += ascii_vector_size;
}
} else {
- while (@ptrToInt(ptr + 8) < @ptrToInt(latin1_last)) {
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(ptr) <= @ptrToInt(latin1_last) and @ptrToInt(ptr) >= @ptrToInt(latin1_.ptr));
+ while (@intFromPtr(ptr + 8) < @intFromPtr(latin1_last)) {
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) <= @intFromPtr(latin1_last) and @intFromPtr(ptr) >= @intFromPtr(latin1_.ptr));
const bytes = @bitCast(u64, ptr[0..8].*) & 0x8080808080808080;
total_non_ascii_count += @popCount(bytes);
ptr += 8;
}
- if (@ptrToInt(ptr + 4) < @ptrToInt(latin1_last)) {
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(ptr) <= @ptrToInt(latin1_last) and @ptrToInt(ptr) >= @ptrToInt(latin1_.ptr));
+ if (@intFromPtr(ptr + 4) < @intFromPtr(latin1_last)) {
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) <= @intFromPtr(latin1_last) and @intFromPtr(ptr) >= @intFromPtr(latin1_.ptr));
const bytes = @bitCast(u32, ptr[0..4].*) & 0x80808080;
total_non_ascii_count += @popCount(bytes);
ptr += 4;
}
- if (@ptrToInt(ptr + 2) < @ptrToInt(latin1_last)) {
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(ptr) <= @ptrToInt(latin1_last) and @ptrToInt(ptr) >= @ptrToInt(latin1_.ptr));
+ if (@intFromPtr(ptr + 2) < @intFromPtr(latin1_last)) {
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) <= @intFromPtr(latin1_last) and @intFromPtr(ptr) >= @intFromPtr(latin1_.ptr));
const bytes = @bitCast(u16, ptr[0..2].*) & 0x8080;
total_non_ascii_count += @popCount(bytes);
ptr += 2;
@@ -1956,14 +1957,14 @@ pub fn elementLengthLatin1IntoUTF8(comptime Type: type, latin1_: Type) usize {
}
while (ptr != latin1_last) {
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(ptr) < @ptrToInt(latin1_last));
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) < @intFromPtr(latin1_last));
- total_non_ascii_count += @as(usize, @boolToInt(ptr[0] > 127));
+ total_non_ascii_count += @as(usize, @intFromBool(ptr[0] > 127));
ptr += 1;
}
// assert we never go out of bounds
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(ptr) <= @ptrToInt(latin1_last) and @ptrToInt(ptr) >= @ptrToInt(latin1_.ptr));
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) <= @intFromPtr(latin1_last) and @intFromPtr(ptr) >= @intFromPtr(latin1_.ptr));
}
// each non-ascii latin1 character becomes 2 UTF8 characters
@@ -2198,8 +2199,8 @@ pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8
if (comptime Environment.allow_assert) std.debug.assert(buf.capacity == 0);
buf = try std.ArrayList(u8).initCapacity(allocator, latin1.len + 6);
- const copy_len = @ptrToInt(remaining.ptr) - @ptrToInt(latin1.ptr);
- @memcpy(buf.items.ptr, latin1.ptr, copy_len);
+ const copy_len = @intFromPtr(remaining.ptr) - @intFromPtr(latin1.ptr);
+ @memcpy(buf.items[0..copy_len], latin1[0..copy_len]);
buf.items.len = copy_len;
any_needs_escape = true;
comptime var i: usize = 0;
@@ -2311,8 +2312,8 @@ pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8
if (comptime Environment.allow_assert) std.debug.assert(buf.capacity == 0);
buf = try std.ArrayList(u8).initCapacity(allocator, latin1.len + @as(usize, Scalar.lengths[c]));
- const copy_len = @ptrToInt(ptr) - @ptrToInt(latin1.ptr);
- @memcpy(buf.items.ptr, latin1.ptr, copy_len);
+ const copy_len = @intFromPtr(ptr) - @intFromPtr(latin1.ptr);
+ @memcpy(buf.items[0..copy_len], latin1[0..copy_len]);
buf.items.len = copy_len;
any_needs_escape = true;
break :scan_and_allocate_lazily;
@@ -2474,9 +2475,9 @@ pub fn escapeHTMLForUTF16Input(allocator: std.mem.Allocator, utf16: []const u16)
}
buf = try std.ArrayList(u16).initCapacity(allocator, utf16.len + 6);
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(remaining.ptr + i) >= @ptrToInt(utf16.ptr));
- const to_copy = std.mem.sliceAsBytes(utf16)[0 .. @ptrToInt(remaining.ptr + i) - @ptrToInt(utf16.ptr)];
- @memcpy(@ptrCast([*]align(2) u8, buf.items.ptr), to_copy.ptr, to_copy.len);
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(remaining.ptr + i) >= @intFromPtr(utf16.ptr));
+ const to_copy = std.mem.sliceAsBytes(utf16)[0 .. @intFromPtr(remaining.ptr + i) - @intFromPtr(utf16.ptr)];
+ @memcpy(@ptrCast([*]align(2) u8, buf.items[0..to_copy.len]), to_copy);
buf.items.len = std.mem.bytesAsSlice(u16, to_copy).len;
while (i < ascii_u16_vector_size) {
@@ -2585,14 +2586,13 @@ pub fn escapeHTMLForUTF16Input(allocator: std.mem.Allocator, utf16: []const u16)
switch (ptr[0]) {
'"', '&', '\'', '<', '>' => |c| {
buf = try std.ArrayList(u16).initCapacity(allocator, utf16.len + @as(usize, Scalar.lengths[c]));
- if (comptime Environment.allow_assert) std.debug.assert(@ptrToInt(ptr) >= @ptrToInt(utf16.ptr));
+ if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) >= @intFromPtr(utf16.ptr));
- const to_copy = std.mem.sliceAsBytes(utf16)[0 .. @ptrToInt(ptr) - @ptrToInt(utf16.ptr)];
+ const to_copy = std.mem.sliceAsBytes(utf16)[0 .. @intFromPtr(ptr) - @intFromPtr(utf16.ptr)];
@memcpy(
- @ptrCast([*]align(2) u8, buf.items.ptr),
- to_copy.ptr,
- to_copy.len,
+ @ptrCast([*]align(2) u8, buf.items[0..to_copy.len]),
+ to_copy,
);
buf.items.len = std.mem.bytesAsSlice(u16, to_copy).len;
@@ -3159,7 +3159,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 {
if (@reduce(.Max, vec) > 127) {
const Int = u64;
const size = @sizeOf(Int);
- remaining.len -= @ptrToInt(remaining.ptr) - @ptrToInt(remaining_start);
+ remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start);
{
const bytes = @bitCast(Int, remaining[0..size].*);
@@ -3206,7 +3206,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 {
// we only need to subtract the length once at the very end
remaining.ptr += ascii_vector_size;
}
- remaining.len -= @ptrToInt(remaining.ptr) - @ptrToInt(remaining_start);
+ remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start);
}
}
@@ -3219,7 +3219,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 {
if (comptime Environment.enableSIMD) {
// these assertions exist more so for LLVM
std.debug.assert(remaining.len < ascii_vector_size);
- std.debug.assert(@ptrToInt(remaining.ptr + ascii_vector_size) > @ptrToInt(remaining_end));
+ std.debug.assert(@intFromPtr(remaining.ptr + ascii_vector_size) > @intFromPtr(remaining_end));
}
if (remaining.len >= size) {
@@ -3229,7 +3229,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 {
const mask = bytes & 0x8080808080808080;
if (mask > 0) {
- remaining.len -= @ptrToInt(remaining.ptr) - @ptrToInt(remaining_start);
+ remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start);
const first_set_byte = @ctz(mask) / 8;
if (comptime Environment.allow_assert) {
std.debug.assert(remaining[first_set_byte] > 127);
@@ -3244,7 +3244,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 {
remaining.ptr += size;
}
- remaining.len -= @ptrToInt(remaining.ptr) - @ptrToInt(remaining_start);
+ remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start);
}
}
@@ -3253,7 +3253,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 {
for (remaining) |*char| {
if (char.* > 127) {
// try to prevent it from reading the length of the slice
- return @truncate(u32, @ptrToInt(char) - @ptrToInt(slice.ptr));
+ return @truncate(u32, @intFromPtr(char) - @intFromPtr(slice.ptr));
}
}
@@ -3291,7 +3291,7 @@ pub fn indexOfNewlineOrNonASCIIOrANSI(slice_: []const u8, offset: u32) ?u32 {
for (remaining) |*char_| {
const char = char_.*;
if (char > 127 or char < 0x20 or char == '\n' or char == '\r' or char == '\x1b') {
- return @truncate(u32, (@ptrToInt(char_) - @ptrToInt(slice.ptr))) + offset;
+ return @truncate(u32, (@intFromPtr(char_) - @intFromPtr(slice.ptr))) + offset;
}
}
@@ -3339,7 +3339,7 @@ pub fn indexOfNewlineOrNonASCIICheckStart(slice_: []const u8, offset: u32, compt
for (remaining) |*char_| {
const char = char_.*;
if (char > 127 or char < 0x20 or char == '\n' or char == '\r') {
- return @truncate(u32, (@ptrToInt(char_) - @ptrToInt(slice.ptr))) + offset;
+ return @truncate(u32, (@intFromPtr(char_) - @intFromPtr(slice.ptr))) + offset;
}
}
@@ -3401,7 +3401,7 @@ pub fn indexOfNeedsEscape(slice: []const u8) ?u32 {
const bitmask = @bitCast(AsciiVectorInt, cmp);
const first = @ctz(bitmask);
- return @as(u32, first) + @truncate(u32, @ptrToInt(remaining.ptr) - @ptrToInt(slice.ptr));
+ return @as(u32, first) + @truncate(u32, @intFromPtr(remaining.ptr) - @intFromPtr(slice.ptr));
}
remaining = remaining[ascii_vector_size..];
@@ -3411,7 +3411,7 @@ pub fn indexOfNeedsEscape(slice: []const u8) ?u32 {
for (remaining) |*char_| {
const char = char_.*;
if (char > 127 or char < 0x20 or char == '\\' or char == '"') {
- return @truncate(u32, @ptrToInt(char_) - @ptrToInt(slice.ptr));
+ return @truncate(u32, @intFromPtr(char_) - @intFromPtr(slice.ptr));
}
}
@@ -3428,11 +3428,11 @@ test "indexOfNeedsEscape" {
pub fn indexOfCharZ(sliceZ: [:0]const u8, char: u8) ?u63 {
const ptr = bun.C.strchr(sliceZ.ptr, char) orelse return null;
- const pos = @ptrToInt(ptr) - @ptrToInt(sliceZ.ptr);
+ const pos = @intFromPtr(ptr) - @intFromPtr(sliceZ.ptr);
if (comptime Environment.allow_assert)
- std.debug.assert(@ptrToInt(sliceZ.ptr) <= @ptrToInt(ptr) and
- @ptrToInt(ptr) < @ptrToInt(sliceZ.ptr + sliceZ.len) and
+ std.debug.assert(@intFromPtr(sliceZ.ptr) <= @intFromPtr(ptr) and
+ @intFromPtr(ptr) < @intFromPtr(sliceZ.ptr + sliceZ.len) and
pos <= sliceZ.len);
return @truncate(u63, pos);
@@ -3447,7 +3447,7 @@ pub fn indexOfCharUsize(slice: []const u8, char: u8) ?usize {
return null;
const ptr = bun.C.memchr(slice.ptr, char, slice.len) orelse return null;
- const i = @ptrToInt(ptr) - @ptrToInt(slice.ptr);
+ const i = @intFromPtr(ptr) - @intFromPtr(slice.ptr);
std.debug.assert(i < slice.len);
std.debug.assert(slice[i] == char);
@@ -3513,7 +3513,7 @@ pub fn indexOfNotChar(slice: []const u8, char: u8) ?u32 {
for (remaining) |*current| {
if (current.* != char) {
- return @truncate(u32, @ptrToInt(current) - @ptrToInt(slice.ptr));
+ return @truncate(u32, @intFromPtr(current) - @intFromPtr(slice.ptr));
}
}
@@ -3718,7 +3718,7 @@ pub fn firstNonASCII16CheckMin(comptime Slice: type, slice: Slice, comptime chec
// @reduce doesn't tell us the index though
const min_value = @reduce(.Min, vec);
if (min_value < 0x20 or max_value > 127) {
- remaining.len -= (@ptrToInt(remaining.ptr) - @ptrToInt(remaining_start)) / 2;
+ remaining.len -= (@intFromPtr(remaining.ptr) - @intFromPtr(remaining_start)) / 2;
// this is really slow
// it does it element-wise for every single u8 on the vector
@@ -3734,7 +3734,7 @@ pub fn firstNonASCII16CheckMin(comptime Slice: type, slice: Slice, comptime chec
}
} else if (comptime !check_min) {
if (max_value > 127) {
- remaining.len -= (@ptrToInt(remaining.ptr) - @ptrToInt(remaining_start)) / 2;
+ remaining.len -= (@intFromPtr(remaining.ptr) - @intFromPtr(remaining_start)) / 2;
const cmp = vec > max_u16_ascii;
const bitmask: u8 = @bitCast(u8, cmp);
@@ -3747,7 +3747,7 @@ pub fn firstNonASCII16CheckMin(comptime Slice: type, slice: Slice, comptime chec
remaining.ptr += ascii_u16_vector_size;
}
- remaining.len -= (@ptrToInt(remaining.ptr) - @ptrToInt(remaining_start)) / 2;
+ remaining.len -= (@intFromPtr(remaining.ptr) - @intFromPtr(remaining_start)) / 2;
}
}
@@ -3820,7 +3820,7 @@ test "indexOfNotChar" {
var yes: [312]u8 = undefined;
var i: usize = 0;
while (i < yes.len) {
- @memset(&yes, 'a', yes.len);
+ @memset(yes, 'a');
yes[i] = 'b';
if (comptime Environment.allow_assert) std.debug.assert(indexOfNotChar(&yes, 'a').? == i);
i += 1;
@@ -4077,12 +4077,12 @@ const sort_desc = std.sort.desc(u8);
pub fn sortAsc(in: []string) void {
// TODO: experiment with simd to see if it's faster
- std.sort.sort([]const u8, in, {}, cmpStringsAsc);
+ std.sort.block([]const u8, in, {}, cmpStringsAsc);
}
pub fn sortDesc(in: []string) void {
// TODO: experiment with simd to see if it's faster
- std.sort.sort([]const u8, in, {}, cmpStringsDesc);
+ std.sort.block([]const u8, in, {}, cmpStringsDesc);
}
pub const StringArrayByIndexSorter = struct {
@@ -4331,8 +4331,8 @@ pub fn moveAllSlices(comptime Type: type, container: *Type, from: string, to: st
inline for (fields_we_care_about) |name| {
const slice = @field(container, name);
- if ((@ptrToInt(from.ptr) + from.len) >= @ptrToInt(slice.ptr) + slice.len and
- (@ptrToInt(from.ptr) <= @ptrToInt(slice.ptr)))
+ if ((@intFromPtr(from.ptr) + from.len) >= @intFromPtr(slice.ptr) + slice.len and
+ (@intFromPtr(from.ptr) <= @intFromPtr(slice.ptr)))
{
@field(container, name) = moveSlice(slice, from, to);
}
@@ -4344,14 +4344,14 @@ pub fn moveSlice(slice: string, from: string, to: string) string {
std.debug.assert(from.len <= to.len and from.len >= slice.len);
// assert we are in bounds
std.debug.assert(
- (@ptrToInt(from.ptr) + from.len) >=
- @ptrToInt(slice.ptr) + slice.len and
- (@ptrToInt(from.ptr) <= @ptrToInt(slice.ptr)),
+ (@intFromPtr(from.ptr) + from.len) >=
+ @intFromPtr(slice.ptr) + slice.len and
+ (@intFromPtr(from.ptr) <= @intFromPtr(slice.ptr)),
);
std.debug.assert(eqlLong(from, to[0..from.len], false)); // data should be identical
}
- const ptr_offset = @ptrToInt(slice.ptr) - @ptrToInt(from.ptr);
+ const ptr_offset = @intFromPtr(slice.ptr) - @intFromPtr(from.ptr);
const result = to[ptr_offset..][0..slice.len];
if (comptime Environment.allow_assert) std.debug.assert(eqlLong(slice, result, false)); // data should be identical
@@ -4463,7 +4463,7 @@ pub fn cloneNormalizingSeparators(
if (base[0] == std.fs.path.sep) {
buf[0] = std.fs.path.sep;
}
- var remain = buf[@as(usize, @boolToInt(base[0] == std.fs.path.sep))..];
+ var remain = buf[@as(usize, @intFromBool(base[0] == std.fs.path.sep))..];
while (tokenized.next()) |token| {
if (token.len == 0) continue;
@@ -4477,7 +4477,7 @@ pub fn cloneNormalizingSeparators(
}
remain[0] = 0;
- return buf[0 .. @ptrToInt(remain.ptr) - @ptrToInt(buf.ptr)];
+ return buf[0 .. @intFromPtr(remain.ptr) - @intFromPtr(buf.ptr)];
}
pub fn leftHasAnyInRight(to_check: []const string, against: []const string) bool {
@@ -4517,7 +4517,7 @@ pub fn concatWithLength(
var out = try allocator.alloc(u8, length);
var remain = out;
for (args) |arg| {
- @memcpy(remain.ptr, arg.ptr, arg.len);
+ @memcpy(remain[0..arg.len], arg);
remain = remain[arg.len..];
}
std.debug.assert(remain.len == 0); // all bytes should be used
@@ -4590,7 +4590,8 @@ pub fn concatIfNeeded(
dest.* = buf;
var remain = buf[0..];
for (args) |arg| {
- @memcpy(remain.ptr, arg.ptr, arg.len);
+ @memcpy(remain[0..arg.len], arg);
+
remain = remain[arg.len..];
}
std.debug.assert(remain.len == 0);
diff --git a/src/string_joiner.zig b/src/string_joiner.zig
index c1b42dee7..9abdc8a58 100644
--- a/src/string_joiner.zig
+++ b/src/string_joiner.zig
@@ -43,7 +43,7 @@ pub fn done(this: *Joiner, allocator: Allocator) ![]u8 {
var el_ = this.head;
while (el_) |join| {
const to_join = join.data.slice[join.data.offset..];
- @memcpy(remaining.ptr, to_join.ptr, to_join.len);
+ @memcpy(remaining[0..to_join.len], to_join);
remaining = remaining[@min(remaining.len, to_join.len)..];
@@ -67,7 +67,8 @@ pub fn doneWithEnd(this: *Joiner, allocator: Allocator, end: []const u8) ![]u8 {
if (this.head == null) {
var slice = try allocator.alloc(u8, end.len);
- @memcpy(slice.ptr, end.ptr, end.len);
+ @memcpy(slice[0..end.len], end);
+
return slice;
}
@@ -76,7 +77,7 @@ pub fn doneWithEnd(this: *Joiner, allocator: Allocator, end: []const u8) ![]u8 {
var el_ = this.head;
while (el_) |join| {
const to_join = join.data.slice[join.data.offset..];
- @memcpy(remaining.ptr, to_join.ptr, to_join.len);
+ @memcpy(remaining[0..to_join.len], to_join);
remaining = remaining[@min(remaining.len, to_join.len)..];
@@ -90,7 +91,7 @@ pub fn doneWithEnd(this: *Joiner, allocator: Allocator, end: []const u8) ![]u8 {
if (this.use_pool) prev.release();
}
- @memcpy(remaining.ptr, end.ptr, end.len);
+ @memcpy(remaining[0..end.len], end);
remaining = remaining[@min(remaining.len, end.len)..];
@@ -126,7 +127,7 @@ pub fn append(this: *Joiner, slice: string, offset: u32, allocator: ?Allocator)
else
(this.node_allocator.create(Joinable.Pool.Node) catch unreachable);
- this.watcher.estimated_count += @boolToInt(
+ this.watcher.estimated_count += @intFromBool(
this.watcher.input.len > 0 and
bun.strings.contains(data, this.watcher.input),
);
diff --git a/src/string_mutable.zig b/src/string_mutable.zig
index cb8e1633e..103f03aa3 100644
--- a/src/string_mutable.zig
+++ b/src/string_mutable.zig
@@ -180,7 +180,7 @@ pub const MutableString = struct {
try self.list.ensureTotalCapacityPrecise(self.allocator, self.list.items.len + slice.len);
var end = self.list.items.ptr + self.list.items.len;
self.list.items.len += slice.len;
- @memcpy(end, slice.ptr, slice.len);
+ @memcpy(end[0..slice.len], slice);
}
pub inline fn reset(
@@ -329,7 +329,7 @@ pub const MutableString = struct {
if (pending.len + this.pos > max) {
try this.flush();
}
- @memcpy(this.remain().ptr, pending.ptr, pending.len);
+ @memcpy(this.remain()[0..pending.len], pending);
this.pos += pending.len;
}
diff --git a/src/string_types.zig b/src/string_types.zig
index 5063eada6..c091e2a86 100644
--- a/src/string_types.zig
+++ b/src/string_types.zig
@@ -40,19 +40,19 @@ pub const PathString = packed struct {
pub inline fn slice(this: anytype) string {
@setRuntimeSafety(false); // "cast causes pointer to be null" is fine here. if it is null, the len will be 0.
- return @intToPtr([*]u8, @intCast(usize, this.ptr))[0..this.len];
+ return @ptrFromInt([*]u8, @intCast(usize, this.ptr))[0..this.len];
}
pub inline fn sliceAssumeZ(this: anytype) stringZ {
@setRuntimeSafety(false); // "cast causes pointer to be null" is fine here. if it is null, the len will be 0.
- return @intToPtr([*:0]u8, @intCast(usize, this.ptr))[0..this.len :0];
+ return @ptrFromInt([*:0]u8, @intCast(usize, this.ptr))[0..this.len :0];
}
pub inline fn init(str: string) @This() {
@setRuntimeSafety(false); // "cast causes pointer to be null" is fine here. if it is null, the len will be 0.
return @This(){
- .ptr = @truncate(PointerIntType, @ptrToInt(str.ptr)),
+ .ptr = @truncate(PointerIntType, @intFromPtr(str.ptr)),
.len = @truncate(PathInt, str.len),
};
}
@@ -78,13 +78,13 @@ pub const HashedString = struct {
len: u32,
hash: u32,
- pub const empty = HashedString{ .ptr = @intToPtr([*]const u8, 0xDEADBEEF), .len = 0, .hash = 0 };
+ pub const empty = HashedString{ .ptr = @ptrFromInt([*]const u8, 0xDEADBEEF), .len = 0, .hash = 0 };
pub fn init(buf: string) HashedString {
return HashedString{
.ptr = buf.ptr,
.len = @truncate(u32, buf.len),
- .hash = @truncate(u32, std.hash.Wyhash.hash(0, buf)),
+ .hash = @truncate(u32, bun.hash(buf)),
};
}
@@ -106,7 +106,7 @@ pub const HashedString = struct {
return ((@max(this.hash, other.hash) > 0 and this.hash == other.hash) or (this.ptr == other.ptr)) and this.len == other.len;
},
else => {
- return @as(usize, this.len) == other.len and @truncate(u32, std.hash.Wyhash.hash(0, other[0..other.len])) == this.hash;
+ return @as(usize, this.len) == other.len and @truncate(u32, bun.hash(other[0..other.len])) == this.hash;
},
}
}
diff --git a/src/sync.zig b/src/sync.zig
index 23cde775a..598831099 100644
--- a/src/sync.zig
+++ b/src/sync.zig
@@ -28,7 +28,7 @@ pub const ThreadPool = struct {
errdefer self.deinit();
- const num_workers = std.math.max(1, config.max_threads orelse std.Thread.cpuCount() catch 1);
+ const num_workers = @max(1, config.max_threads orelse std.Thread.cpuCount() catch 1);
self.workers = try self.allocator.alloc(Worker, num_workers);
for (&self.workers) |*worker| {
@@ -91,8 +91,8 @@ pub const ThreadPool = struct {
idle_workers: usize = 0,
fn pack(self: State) usize {
- return ((@as(usize, @boolToInt(self.is_shutdown)) << 0) |
- (@as(usize, @boolToInt(self.is_notified)) << 1) |
+ return ((@as(usize, @intFromBool(self.is_shutdown)) << 0) |
+ (@as(usize, @intFromBool(self.is_notified)) << 1) |
(self.idle_workers << 2));
}
@@ -225,7 +225,7 @@ pub const ThreadPool = struct {
current = self;
defer current = old_current;
- var tick = @ptrToInt(self);
+ var tick = @intFromPtr(self);
var prng = std.rand.DefaultPrng.init(tick);
while (true) {
@@ -978,7 +978,7 @@ else if (@import("builtin").os.tag == .linux)
Futex.wait(
@ptrCast(*const i32, &self.state),
- @enumToInt(new_state),
+ @intFromEnum(new_state),
);
}
}
diff --git a/src/tagged_pointer.zig b/src/tagged_pointer.zig
index 2cf3c41f5..a246ee355 100644
--- a/src/tagged_pointer.zig
+++ b/src/tagged_pointer.zig
@@ -23,7 +23,7 @@ pub const TaggedPointer = packed struct {
@compileError(@typeName(Ptr) ++ " must be a ptr, received: " ++ @tagName(@typeInfo(Ptr)));
}
- const address = @ptrToInt(ptr);
+ const address = @intFromPtr(ptr);
return TaggedPointer{
._ptr = @truncate(AddressableSize, address),
@@ -32,20 +32,20 @@ pub const TaggedPointer = packed struct {
}
pub inline fn get(this: TaggedPointer, comptime Type: type) *Type {
- return @intToPtr(*Type, @intCast(usize, this._ptr));
+ return @ptrFromInt(*Type, @intCast(usize, this._ptr));
}
pub inline fn from(val: anytype) TaggedPointer {
const ValueType = @TypeOf(val);
return switch (ValueType) {
f64, i64, u64 => @bitCast(TaggedPointer, val),
- ?*anyopaque, *anyopaque => @bitCast(TaggedPointer, @ptrToInt(val)),
+ ?*anyopaque, *anyopaque => @bitCast(TaggedPointer, @intFromPtr(val)),
else => @compileError("Unsupported type: " ++ @typeName(ValueType)),
};
}
pub inline fn to(this: TaggedPointer) *anyopaque {
- return @intToPtr(*anyopaque, @bitCast(u64, this));
+ return @ptrFromInt(*anyopaque, @bitCast(u64, this));
}
};
@@ -111,7 +111,7 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
}
pub inline fn tag(this: This) TagType {
- return @intToEnum(TagType, this.repr.data);
+ return @enumFromInt(TagType, this.repr.data);
}
/// unsafely cast a tagged pointer to a specific type, without checking that it's really that type
@@ -122,7 +122,7 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
pub inline fn is(this: This, comptime Type: type) bool {
comptime assert_type(Type);
- return this.repr.data == comptime @enumToInt(@field(Tag, typeBaseName(@typeName(Type))));
+ return this.repr.data == comptime @intFromEnum(@field(Tag, typeBaseName(@typeName(Type))));
}
pub fn set(this: *@This(), _ptr: anytype) void {
@@ -135,9 +135,9 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
pub inline fn isValid(this: This) bool {
return switch (this.repr.data) {
- @enumToInt(
+ @intFromEnum(
@field(Tag, typeBaseName(@typeName(Types[Types.len - 1]))),
- )...@enumToInt(
+ )...@intFromEnum(
@field(Tag, typeBaseName(@typeName(Types[0]))),
) => true,
else => false,
@@ -162,7 +162,7 @@ pub fn TaggedPointerUnion(comptime Types: anytype) type {
const name = comptime typeBaseName(@typeName(Type));
// there will be a compiler error if the passed in type doesn't exist in the enum
- return This{ .repr = TaggedPointer.init(_ptr, @enumToInt(@field(Tag, name))) };
+ return This{ .repr = TaggedPointer.init(_ptr, @intFromEnum(@field(Tag, name))) };
}
};
}
diff --git a/src/thread_pool.zig b/src/thread_pool.zig
index b6e766cf9..3359311d6 100644
--- a/src/thread_pool.zig
+++ b/src/thread_pool.zig
@@ -59,8 +59,8 @@ pub const Config = struct {
/// Statically initialize the thread pool using the configuration.
pub fn init(config: Config) ThreadPool {
return .{
- .stack_size = std.math.max(1, config.stack_size),
- .max_threads = std.math.max(1, config.max_threads),
+ .stack_size = @max(1, config.stack_size),
+ .max_threads = @max(1, config.max_threads),
};
}
@@ -945,11 +945,11 @@ pub const Node = struct {
var stack = self.stack.load(.Monotonic);
while (true) {
// Attach the list to the stack (pt. 1)
- list.tail.next = @intToPtr(?*Node, stack & PTR_MASK);
+ list.tail.next = @ptrFromInt(?*Node, stack & PTR_MASK);
// Update the stack with the list (pt. 2).
// Don't change the HAS_CACHE and IS_CONSUMING bits of the consumer.
- var new_stack = @ptrToInt(list.head);
+ var new_stack = @intFromPtr(list.head);
assert(new_stack & ~PTR_MASK == 0);
new_stack |= (stack & ~PTR_MASK);
@@ -985,7 +985,7 @@ pub const Node = struct {
new_stack,
.Acquire,
.Monotonic,
- ) orelse return self.cache orelse @intToPtr(*Node, stack & PTR_MASK);
+ ) orelse return self.cache orelse @ptrFromInt(*Node, stack & PTR_MASK);
}
}
@@ -1022,7 +1022,7 @@ pub const Node = struct {
assert(stack & IS_CONSUMING != 0);
assert(stack & PTR_MASK != 0);
- const node = @intToPtr(*Node, stack & PTR_MASK);
+ const node = @ptrFromInt(*Node, stack & PTR_MASK);
consumer_ref.* = node.next;
return node;
}
diff --git a/src/toml/toml_lexer.zig b/src/toml/toml_lexer.zig
index 1e739822c..7d576af86 100644
--- a/src/toml/toml_lexer.zig
+++ b/src/toml/toml_lexer.zig
@@ -166,7 +166,7 @@ pub const Lexer = struct {
inline fn step(lexer: *Lexer) void {
lexer.code_point = lexer.nextCodepoint();
- lexer.line_number += @as(u32, @boolToInt(lexer.code_point == '\n'));
+ lexer.line_number += @as(u32, @intFromBool(lexer.code_point == '\n'));
}
pub const Error = error{
@@ -466,7 +466,7 @@ pub const Lexer = struct {
for (text) |c| {
number = number * 10 + @intCast(u32, c - '0');
}
- lexer.number = @intToFloat(f64, number);
+ lexer.number = @floatFromInt(f64, number);
} else {
// Parse a double-precision floating-point number;
if (std.fmt.parseFloat(f64, text)) |num| {
@@ -1115,7 +1115,7 @@ pub const Lexer = struct {
pub fn unexpected(lexer: *Lexer) !void {
const found = finder: {
- lexer.start = std.math.min(lexer.start, lexer.end);
+ lexer.start = @min(lexer.start, lexer.end);
if (lexer.start == lexer.source.contents.len) {
break :finder "end of file";
@@ -1215,5 +1215,5 @@ pub fn isLatin1Identifier(comptime Buffer: type, name: Buffer) bool {
}
inline fn float64(num: anytype) f64 {
- return @intToFloat(f64, num);
+ return @floatFromInt(f64, num);
}
diff --git a/src/url.zig b/src/url.zig
index d0fcdab38..66c4ff015 100644
--- a/src/url.zig
+++ b/src/url.zig
@@ -275,8 +275,8 @@ pub const URL = struct {
if (base.len > path_offset and base[path_offset] == '/' and offset > 0) {
if (url.search.len > 0) {
- url.pathname = base[path_offset..std.math.min(
- std.math.min(offset + url.search.len, base.len),
+ url.pathname = base[path_offset..@min(
+ @min(offset + url.search.len, base.len),
hash_offset,
)];
} else if (hash_offset < std.math.maxInt(u32)) {
@@ -289,8 +289,8 @@ pub const URL = struct {
if (url.path.len > 1) {
const trimmed = std.mem.trim(u8, url.path, "/");
if (trimmed.len > 1) {
- url.path = url.path[std.math.min(
- std.math.max(@ptrToInt(trimmed.ptr) - @ptrToInt(url.path.ptr), 1) - 1,
+ url.path = url.path[@min(
+ @max(@intFromPtr(trimmed.ptr) - @intFromPtr(url.path.ptr), 1) - 1,
hash_offset,
)..];
} else {
@@ -542,12 +542,12 @@ pub const QueryStringMap = struct {
}
pub fn getIndex(this: *const QueryStringMap, input: string) ?usize {
- const hash = std.hash.Wyhash.hash(0, input);
+ const hash = bun.hash(input);
return std.mem.indexOfScalar(u64, this.list.items(.name_hash), hash);
}
pub fn get(this: *const QueryStringMap, input: string) ?string {
- const hash = std.hash.Wyhash.hash(0, input);
+ const hash = bun.hash(input);
const _slice = this.list.slice();
const i = std.mem.indexOfScalar(u64, _slice.items(.name_hash), hash) orelse return null;
return this.str(_slice.items(.value)[i]);
@@ -558,7 +558,7 @@ pub const QueryStringMap = struct {
}
pub fn getAll(this: *const QueryStringMap, input: string, target: []string) usize {
- const hash = std.hash.Wyhash.hash(0, input);
+ const hash = bun.hash(input);
const _slice = this.list.slice();
return @call(.always_inline, getAllWithHashFromOffset, .{ this, target, hash, 0, _slice });
}
@@ -638,7 +638,7 @@ pub const QueryStringMap = struct {
try writer.writeAll(name_slice);
buf_writer_pos += @truncate(u32, name_slice.len);
- var name_hash: u64 = std.hash.Wyhash.hash(0, name_slice);
+ var name_hash: u64 = bun.hash(name_slice);
value.length = PercentEncoding.decode(Writer, writer, result.rawValue(scanner.pathname.pathname)) catch continue;
value.offset = buf_writer_pos;
@@ -659,9 +659,9 @@ pub const QueryStringMap = struct {
name.length = PercentEncoding.decode(Writer, writer, scanner.query.query_string[name.offset..][0..name.length]) catch continue;
name.offset = buf_writer_pos;
buf_writer_pos += name.length;
- name_hash = std.hash.Wyhash.hash(0, buf.items[name.offset..][0..name.length]);
+ name_hash = bun.hash(buf.items[name.offset..][0..name.length]);
} else {
- name_hash = std.hash.Wyhash.hash(0, result.rawName(scanner.query.query_string));
+ name_hash = bun.hash(result.rawName(scanner.query.query_string));
if (std.mem.indexOfScalar(u64, list_slice.items(.name_hash), name_hash)) |index| {
// query string parameters should not override route parameters
@@ -726,7 +726,7 @@ pub const QueryStringMap = struct {
var name = result.name;
var value = result.value;
- const name_hash: u64 = std.hash.Wyhash.hash(0, result.rawName(query_string));
+ const name_hash: u64 = bun.hash(result.rawName(query_string));
list.appendAssumeCapacity(Param{ .name = name, .value = value, .name_hash = name_hash });
}
@@ -752,9 +752,9 @@ pub const QueryStringMap = struct {
name.length = PercentEncoding.decode(Writer, writer, query_string[name.offset..][0..name.length]) catch continue;
name.offset = buf_writer_pos;
buf_writer_pos += name.length;
- name_hash = std.hash.Wyhash.hash(0, buf.items[name.offset..][0..name.length]);
+ name_hash = bun.hash(buf.items[name.offset..][0..name.length]);
} else {
- name_hash = std.hash.Wyhash.hash(0, result.rawName(query_string));
+ name_hash = bun.hash(result.rawName(query_string));
if (std.mem.indexOfScalar(u64, list_slice.items(.name_hash), name_hash)) |index| {
name = list_slice.items(.name)[index];
} else {
@@ -1126,7 +1126,7 @@ pub const FormData = struct {
break;
},
'\\' => {
- i += @boolToInt(field_value.len > i + 1 and field_value[i + 1] == '"');
+ i += @intFromBool(field_value.len > i + 1 and field_value[i + 1] == '"');
},
// the spec requires a end quote, but some browsers don't send it
else => {},
@@ -1434,7 +1434,7 @@ test "Scanner.next - % encoded" {
test "PercentEncoding.decode" {
var buffer: [4096]u8 = undefined;
- std.mem.set(u8, &buffer, 0);
+ @memset(&buffer, 0);
var stream = std.io.fixedBufferStream(&buffer);
var writer = stream.writer();
diff --git a/src/util.zig b/src/util.zig
index fbc98d666..1664cadd9 100644
--- a/src/util.zig
+++ b/src/util.zig
@@ -237,7 +237,7 @@ pub fn fromSlice(
if (comptime std.meta.trait.isIndexable(DefaultType) and (std.meta.trait.isSlice(DefaultType) or std.meta.trait.is(.Array)(DefaultType))) {
var in = std.mem.sliceAsBytes(default);
var out = std.mem.sliceAsBytes(slice);
- @memcpy(out.ptr, in.ptr, in.len);
+ @memcpy(out[0..in.len], in);
} else {
@compileError("Needs a more specific type to copy from");
}
diff --git a/src/walker_skippable.zig b/src/walker_skippable.zig
index 880bed94d..4d5575405 100644
--- a/src/walker_skippable.zig
+++ b/src/walker_skippable.zig
@@ -1,6 +1,7 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const Walker = @This();
+const bun = @import("root").bun;
const path = std.fs.path;
stack: std.ArrayList(StackItem),
@@ -37,30 +38,30 @@ pub fn next(self: *Walker) !?WalkerEntry {
var dirname_len = top.dirname_len;
if (try top.iter.next()) |base| {
switch (base.kind) {
- .Directory => {
+ .directory => {
if (std.mem.indexOfScalar(
u64,
self.skip_dirnames,
// avoid hashing if there will be 0 results
- if (self.skip_dirnames.len > 0) std.hash.Wyhash.hash(self.seed, base.name) else 0,
+ if (self.skip_dirnames.len > 0) bun.hashWithSeed(self.seed, base.name) else 0,
) != null) continue;
},
- .File => {
+ .file => {
if (std.mem.indexOfScalar(
u64,
self.skip_filenames,
// avoid hashing if there will be 0 results
- if (self.skip_filenames.len > 0) std.hash.Wyhash.hash(self.seed, base.name) else 0,
+ if (self.skip_filenames.len > 0) bun.hashWithSeed(self.seed, base.name) else 0,
) != null) continue;
},
// we don't know what it is for a symlink
- .SymLink => {
+ .sym_link => {
if (std.mem.indexOfScalar(
u64,
self.skip_all,
// avoid hashing if there will be 0 results
- if (self.skip_all.len > 0) std.hash.Wyhash.hash(self.seed, base.name) else 0,
+ if (self.skip_all.len > 0) bun.hashWithSeed(self.seed, base.name) else 0,
) != null) continue;
},
@@ -77,7 +78,7 @@ pub fn next(self: *Walker) !?WalkerEntry {
try self.name_buffer.append(0);
self.name_buffer.shrinkRetainingCapacity(cur_len);
- if (base.kind == .Directory) {
+ if (base.kind == .directory) {
var new_dir = top.iter.dir.openIterableDir(base.name, .{}) catch |err| switch (err) {
error.NameTooLong => unreachable, // no path sep in base.name
else => |e| return e,
@@ -143,14 +144,14 @@ pub fn walk(
var skip_name_i: usize = 0;
for (skip_filenames) |name| {
- skip_names[skip_name_i] = std.hash.Wyhash.hash(seed, name);
+ skip_names[skip_name_i] = bun.hashWithSeed(seed, name);
skip_name_i += 1;
}
var skip_filenames_ = skip_names[0..skip_name_i];
var skip_dirnames_ = skip_names[skip_name_i..];
for (skip_dirnames, 0..) |name, i| {
- skip_dirnames_[i] = std.hash.Wyhash.hash(seed, name);
+ skip_dirnames_[i] = bun.hashWithSeed(seed, name);
}
try stack.append(Walker.StackItem{
diff --git a/src/watcher.zig b/src/watcher.zig
index 466463805..155c0b473 100644
--- a/src/watcher.zig
+++ b/src/watcher.zig
@@ -73,7 +73,7 @@ pub const INotify = struct {
// it includes alignment / padding
// but it is a sentineled value
// so we can just trim it to the first null byte
- return bun.sliceTo(@intToPtr([*:0]u8, @ptrToInt(&this.name_len) + @sizeOf(u32)), 0)[0.. :0];
+ return bun.sliceTo(@ptrFromInt([*:0]u8, @intFromPtr(&this.name_len) + @sizeOf(u32)), 0)[0.. :0];
}
};
pub var inotify_fd: EventListIndex = 0;
@@ -367,7 +367,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
var evict_list: [WATCHER_MAX_LIST]WatchItemIndex = undefined;
pub fn getHash(filepath: string) HashType {
- return @truncate(HashType, std.hash.Wyhash.hash(0, filepath));
+ return @truncate(HashType, bun.hash(filepath));
}
pub fn init(ctx: ContextType, fs: *Fs.FileSystem, allocator: std.mem.Allocator) !*Watcher {
@@ -434,7 +434,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
// swapRemove messes up the order
// But, it only messes up the order if any elements in the list appear after the item being removed
// So if we just sort the list by the biggest index first, that should be fine
- std.sort.sort(
+ std.sort.block(
WatchItemIndex,
evict_list[0..evict_list_i],
{},
@@ -570,14 +570,14 @@ pub fn NewWatcher(comptime ContextType: type) type {
else
null;
watchevents[watch_event_id].name_off = temp_name_off;
- watchevents[watch_event_id].name_len = @as(u8, @boolToInt((event.name_len > 0)));
- temp_name_off += @as(u8, @boolToInt((event.name_len > 0)));
+ watchevents[watch_event_id].name_len = @as(u8, @intFromBool((event.name_len > 0)));
+ temp_name_off += @as(u8, @intFromBool((event.name_len > 0)));
watch_event_id += 1;
}
var all_events = watchevents[0..watch_event_id];
- std.sort.sort(WatchEvent, all_events, {}, WatchEvent.sortByIndex);
+ std.sort.block(WatchEvent, all_events, {}, WatchEvent.sortByIndex);
var last_event_index: usize = 0;
var last_event_id: INotify.EventListIndex = std.math.maxInt(INotify.EventListIndex);
@@ -859,7 +859,7 @@ pub fn NewWatcher(comptime ContextType: type) type {
}
}
}
- try this.watchlist.ensureUnusedCapacity(this.allocator, 1 + @intCast(usize, @boolToInt(parent_watch_item == null)));
+ try this.watchlist.ensureUnusedCapacity(this.allocator, 1 + @intCast(usize, @intFromBool(parent_watch_item == null)));
if (autowatch_parent_dir) {
parent_watch_item = parent_watch_item orelse try this.appendDirectoryAssumeCapacity(dir_fd, parent_dir, parent_dir_hash, copy_file_path);
diff --git a/src/wyhash.zig b/src/wyhash.zig
new file mode 100644
index 000000000..bd5cbf62b
--- /dev/null
+++ b/src/wyhash.zig
@@ -0,0 +1,179 @@
+//
+// this file is a copy of Wyhash from the zig standard library, version v0.11.0-dev.2609+5e19250a1
+//
+
+const std = @import("std");
+const mem = std.mem;
+
+const primes = [_]u64{
+ 0xa0761d6478bd642f,
+ 0xe7037ed1a0b428db,
+ 0x8ebc6af09c88c6e3,
+ 0x589965cc75374cc3,
+ 0x1d8e4e27c47d124f,
+};
+
+fn read_bytes(comptime bytes: u8, data: []const u8) u64 {
+ const T = std.meta.Int(.unsigned, 8 * bytes);
+ return mem.readIntLittle(T, data[0..bytes]);
+}
+
+fn read_8bytes_swapped(data: []const u8) u64 {
+ return (read_bytes(4, data) << 32 | read_bytes(4, data[4..]));
+}
+
+fn mum(a: u64, b: u64) u64 {
+ var r = std.math.mulWide(u64, a, b);
+ r = (r >> 64) ^ r;
+ return @truncate(u64, r);
+}
+
+fn mix0(a: u64, b: u64, seed: u64) u64 {
+ return mum(a ^ seed ^ primes[0], b ^ seed ^ primes[1]);
+}
+
+fn mix1(a: u64, b: u64, seed: u64) u64 {
+ return mum(a ^ seed ^ primes[2], b ^ seed ^ primes[3]);
+}
+
+// Wyhash version which does not store internal state for handling partial buffers.
+// This is needed so that we can maximize the speed for the short key case, which will
+// use the non-iterative api which the public Wyhash exposes.
+const WyhashStateless = struct {
+ seed: u64,
+ msg_len: usize,
+
+ pub fn init(seed: u64) WyhashStateless {
+ return WyhashStateless{
+ .seed = seed,
+ .msg_len = 0,
+ };
+ }
+
+ inline fn round(self: *WyhashStateless, b: []const u8) void {
+ std.debug.assert(b.len == 32);
+
+ self.seed = mix0(
+ read_bytes(8, b[0..]),
+ read_bytes(8, b[8..]),
+ self.seed,
+ ) ^ mix1(
+ read_bytes(8, b[16..]),
+ read_bytes(8, b[24..]),
+ self.seed,
+ );
+ }
+
+ pub inline fn update(self: *WyhashStateless, b: []const u8) void {
+ std.debug.assert(b.len % 32 == 0);
+
+ var off: usize = 0;
+ while (off < b.len) : (off += 32) {
+ self.round(b[off .. off + 32]);
+ // @call(.always_inline, self.round, .{b[off .. off + 32]});
+ }
+
+ self.msg_len += b.len;
+ }
+
+ pub inline fn final(self: *WyhashStateless, b: []const u8) u64 {
+ std.debug.assert(b.len < 32);
+
+ const seed = self.seed;
+ const rem_len = @intCast(u5, b.len);
+ const rem_key = b[0..rem_len];
+
+ self.seed = switch (rem_len) {
+ 0 => seed,
+ 1 => mix0(read_bytes(1, rem_key), primes[4], seed),
+ 2 => mix0(read_bytes(2, rem_key), primes[4], seed),
+ 3 => mix0((read_bytes(2, rem_key) << 8) | read_bytes(1, rem_key[2..]), primes[4], seed),
+ 4 => mix0(read_bytes(4, rem_key), primes[4], seed),
+ 5 => mix0((read_bytes(4, rem_key) << 8) | read_bytes(1, rem_key[4..]), primes[4], seed),
+ 6 => mix0((read_bytes(4, rem_key) << 16) | read_bytes(2, rem_key[4..]), primes[4], seed),
+ 7 => mix0((read_bytes(4, rem_key) << 24) | (read_bytes(2, rem_key[4..]) << 8) | read_bytes(1, rem_key[6..]), primes[4], seed),
+ 8 => mix0(read_8bytes_swapped(rem_key), primes[4], seed),
+ 9 => mix0(read_8bytes_swapped(rem_key), read_bytes(1, rem_key[8..]), seed),
+ 10 => mix0(read_8bytes_swapped(rem_key), read_bytes(2, rem_key[8..]), seed),
+ 11 => mix0(read_8bytes_swapped(rem_key), (read_bytes(2, rem_key[8..]) << 8) | read_bytes(1, rem_key[10..]), seed),
+ 12 => mix0(read_8bytes_swapped(rem_key), read_bytes(4, rem_key[8..]), seed),
+ 13 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 8) | read_bytes(1, rem_key[12..]), seed),
+ 14 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 16) | read_bytes(2, rem_key[12..]), seed),
+ 15 => mix0(read_8bytes_swapped(rem_key), (read_bytes(4, rem_key[8..]) << 24) | (read_bytes(2, rem_key[12..]) << 8) | read_bytes(1, rem_key[14..]), seed),
+ 16 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed),
+ 17 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(1, rem_key[16..]), primes[4], seed),
+ 18 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(2, rem_key[16..]), primes[4], seed),
+ 19 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(2, rem_key[16..]) << 8) | read_bytes(1, rem_key[18..]), primes[4], seed),
+ 20 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_bytes(4, rem_key[16..]), primes[4], seed),
+ 21 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 8) | read_bytes(1, rem_key[20..]), primes[4], seed),
+ 22 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 16) | read_bytes(2, rem_key[20..]), primes[4], seed),
+ 23 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1((read_bytes(4, rem_key[16..]) << 24) | (read_bytes(2, rem_key[20..]) << 8) | read_bytes(1, rem_key[22..]), primes[4], seed),
+ 24 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), primes[4], seed),
+ 25 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(1, rem_key[24..]), seed),
+ 26 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(2, rem_key[24..]), seed),
+ 27 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(2, rem_key[24..]) << 8) | read_bytes(1, rem_key[26..]), seed),
+ 28 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), read_bytes(4, rem_key[24..]), seed),
+ 29 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 8) | read_bytes(1, rem_key[28..]), seed),
+ 30 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 16) | read_bytes(2, rem_key[28..]), seed),
+ 31 => mix0(read_8bytes_swapped(rem_key), read_8bytes_swapped(rem_key[8..]), seed) ^ mix1(read_8bytes_swapped(rem_key[16..]), (read_bytes(4, rem_key[24..]) << 24) | (read_bytes(2, rem_key[28..]) << 8) | read_bytes(1, rem_key[30..]), seed),
+ };
+
+ self.msg_len += b.len;
+ return mum(self.seed ^ self.msg_len, primes[4]);
+ }
+
+ pub fn hash(seed: u64, input: []const u8) u64 {
+ const aligned_len = input.len - (input.len % 32);
+
+ var c = WyhashStateless.init(seed);
+ c.update(input[0..aligned_len]);
+ // @call(.always_inline, c.update, .{input[0..aligned_len]});
+ return c.final(input[aligned_len..]);
+ // return @call(.always_inline, c.final, .{input[aligned_len..]});
+ }
+};
+
+/// Fast non-cryptographic 64bit hash function.
+/// See https://github.com/wangyi-fudan/wyhash
+pub const Wyhash = struct {
+ state: WyhashStateless,
+
+ buf: [32]u8,
+ buf_len: usize,
+
+ pub fn init(seed: u64) Wyhash {
+ return Wyhash{
+ .state = WyhashStateless.init(seed),
+ .buf = undefined,
+ .buf_len = 0,
+ };
+ }
+
+ pub fn update(self: *Wyhash, b: []const u8) void {
+ var off: usize = 0;
+
+ if (self.buf_len != 0 and self.buf_len + b.len >= 32) {
+ off += 32 - self.buf_len;
+ mem.copy(u8, self.buf[self.buf_len..], b[0..off]);
+ self.state.update(self.buf[0..]);
+ self.buf_len = 0;
+ }
+
+ const remain_len = b.len - off;
+ const aligned_len = remain_len - (remain_len % 32);
+ self.state.update(b[off .. off + aligned_len]);
+
+ mem.copy(u8, self.buf[self.buf_len..], b[off + aligned_len ..]);
+ self.buf_len += @intCast(u8, b[off + aligned_len ..].len);
+ }
+
+ pub fn final(self: *Wyhash) u64 {
+ const rem_key = self.buf[0..self.buf_len];
+
+ return self.state.final(rem_key);
+ }
+
+ pub fn hash(seed: u64, input: []const u8) u64 {
+ return WyhashStateless.hash(seed, input);
+ }
+};