diff --git a/src/StaticHashMap.zig b/src/StaticHashMap.zig index 62ac6254ea..4506cbfb1c 100644 --- a/src/StaticHashMap.zig +++ b/src/StaticHashMap.zig @@ -243,9 +243,7 @@ fn HashMapMixin( const hash = ctx.hash(key); assert(hash != Self.empty_hash); - var i = hash >> self.shift; - while (true) : (i += 1) { - const entry = self.entries[i]; + for (self.entries[hash >> self.shift ..]) |entry| { if (entry.hash >= hash) { if (!ctx.eql(entry.key, key)) { return null; @@ -264,9 +262,7 @@ fn HashMapMixin( const hash = ctx.hash(key); assert(hash != Self.empty_hash); - var i = hash >> self.shift; - while (true) : (i += 1) { - const entry = self.entries[i]; + for (self.entries[hash >> self.shift ..]) |entry| { if (entry.hash >= hash) { if (!ctx.eql(entry.key, key)) { return false; @@ -275,6 +271,7 @@ fn HashMapMixin( } // self.get_probe_count += 1; } + unreachable; } pub fn delete(self: *Self, key: K) ?V { @@ -502,9 +499,7 @@ pub fn SortedHashMap(comptime V: type, comptime max_load_percentage: comptime_in pub fn get(self: *Self, key: [32]u8) ?V { assert(cmp(key, empty_hash) != .eq); - var i = idx(key, self.shift); - while (true) : (i += 1) { - const entry = self.entries[i]; + for (self.entries[idx(key, self.shift)..]) |entry| { if (cmp(entry.hash, key).compare(.gte)) { if (cmp(entry.hash, key) != .eq) { return null; @@ -551,8 +546,7 @@ pub fn SortedHashMap(comptime V: type, comptime max_load_percentage: comptime_in test "StaticHashMap: put, get, delete, grow" { var map: AutoStaticHashMap(usize, usize, 512) = .{}; - var seed: usize = 0; - while (seed < 128) : (seed += 1) { + for (0..128) |seed| { var rng = std.rand.DefaultPrng.init(seed); const keys = try testing.allocator.alloc(usize, 512); @@ -581,8 +575,7 @@ test "StaticHashMap: put, get, delete, grow" { } test "HashMap: put, get, delete, grow" { - var seed: usize = 0; - while (seed < 128) : (seed += 1) { + for (0..128) |seed| { var rng = std.rand.DefaultPrng.init(seed); const keys = try testing.allocator.alloc(usize, 512); @@ -629,8 +622,7 @@ test "SortedHashMap: cmp" { } test "SortedHashMap: put, get, delete, grow" { - var seed: usize = 0; - while (seed < 128) : (seed += 1) { + for (0..128) |seed| { var rng = std.rand.DefaultPrng.init(seed); const keys = try testing.allocator.alloc([32]u8, 512); diff --git a/src/analytics/analytics_schema.zig b/src/analytics/analytics_schema.zig index 443772412d..6f79d2a925 100644 --- a/src/analytics/analytics_schema.zig +++ b/src/analytics/analytics_schema.zig @@ -64,7 +64,7 @@ pub const Reader = struct { return &([_]T{}); } - switch (comptime T) { + switch (T) { u8 => { return try this.read(length); }, @@ -72,11 +72,8 @@ pub const Reader = struct { return std.mem.readIntSliceNative(T, this.read(length * @sizeOf(T))); }, [:0]const u8, []const u8 => { - var i: u32 = 0; - var array = try this.allocator.alloc(T, length); - while (i < length) : (i += 1) { - array[i] = try this.readArray(u8); - } + const array = try this.allocator.alloc(T, length); + for (array) |*a| a.* = try this.readArray(u8); return array; }, else => { @@ -98,12 +95,8 @@ pub const Reader = struct { else => {}, } - var i: u32 = 0; - var array = try this.allocator.alloc(T, length); - while (i < length) : (i += 1) { - array[i] = try this.readValue(T); - } - + const array = try this.allocator.alloc(T, length); + for (array) |*v| v.* = try this.readValue(T); return array; }, } diff --git a/src/api/schema.zig b/src/api/schema.zig index 897a1d8fda..d618522fe7 100644 --- a/src/api/schema.zig +++ b/src/api/schema.zig @@ -72,11 +72,8 @@ pub const Reader = struct { return std.mem.readIntSliceNative(T, this.read(length * @sizeOf(T))); }, [:0]const u8, []const u8 => { - var i: u32 = 0; - var array = try this.allocator.alloc(T, length); - while (i < length) : (i += 1) { - array[i] = try this.readArray(u8); - } + const array = try this.allocator.alloc(T, length); + for (array) |*a| a.* = try this.readArray(u8); return array; }, else => { @@ -98,12 +95,8 @@ pub const Reader = struct { else => {}, } - var i: u32 = 0; - var array = try this.allocator.alloc(T, length); - while (i < length) : (i += 1) { - array[i] = try this.readValue(T); - } - + const array = try this.allocator.alloc(T, length); + for (array) |*v| v.* = try this.readValue(T); return array; }, } diff --git a/src/bit_set.zig b/src/bit_set.zig index 4b5f9c23f4..6c1875a614 100644 --- a/src/bit_set.zig +++ b/src/bit_set.zig @@ -1602,8 +1602,7 @@ fn testBitSet(a: anytype, b: anytype, len: usize) !void { const needs_ptr = @hasField(std.meta.Child(@TypeOf(a)), "masks") and @typeInfo(@TypeOf(@field(a, "masks"))) != .Pointer; { - var i: usize = 0; - while (i < len) : (i += 1) { + for (0..len) |i| { a.setValue(i, i & 1 == 0); b.setValue(i, i & 2 == 0); } @@ -1649,8 +1648,7 @@ fn testBitSet(a: anytype, b: anytype, len: usize) !void { } { - var i: usize = 0; - while (i < len) : (i += 1) { + for (0..len) |i| { try testing.expectEqual(i & 1 != 0, a.isSet(i)); try testing.expectEqual(i & 2 == 0, b.isSet(i)); } @@ -1696,8 +1694,7 @@ fn testBitSet(a: anytype, b: anytype, len: usize) !void { { try testing.expectEqual(len / 4, a.count()); - var i: usize = 0; - while (i < len) : (i += 1) { + for (0..len) |i| { try testing.expectEqual(i & 1 != 0 and i & 2 != 0, a.isSet(i)); try testing.expectEqual(i & 2 == 0, b.isSet(i)); if (i & 1 == 0) { @@ -1716,8 +1713,7 @@ fn testBitSet(a: anytype, b: anytype, len: usize) !void { { try testing.expectEqual((len + 3) / 4, a.count()); - var i: usize = 0; - while (i < len) : (i += 1) { + for (0..len) |i| { try testing.expectEqual(i & 1 == 0 and i & 2 == 0, a.isSet(i)); try testing.expectEqual(i & 2 == 0, b.isSet(i)); } @@ -1813,15 +1809,13 @@ fn testBitSet(a: anytype, b: anytype, len: usize) !void { } fn fillEven(set: anytype, len: usize) void { - var i: usize = 0; - while (i < len) : (i += 1) { + for (0..len) |i| { set.setValue(i, i & 1 == 0); } } fn fillOdd(set: anytype, len: usize) void { - var i: usize = 0; - while (i < len) : (i += 1) { + for (0..len) |i| { set.setValue(i, i & 1 == 1); } } @@ -1937,8 +1931,7 @@ test "DynamicBitSetUnmanaged" { var empty = try a.clone(allocator); defer empty.deinit(allocator); try testing.expectEqual(old_len, empty.capacity()); - var i: usize = 0; - while (i < old_len) : (i += 1) { + for (0..old_len) |i| { try testing.expectEqual(a.isSet(i), empty.isSet(i)); } @@ -1990,8 +1983,7 @@ test "DynamicBitSet" { var tmp = try a.clone(allocator); defer tmp.deinit(); try testing.expectEqual(old_len, tmp.capacity()); - var i: usize = 0; - while (i < old_len) : (i += 1) { + for (0..old_len) |i| { try testing.expectEqual(a.isSet(i), tmp.isSet(i)); } diff --git a/src/bun.js/api/bun.zig b/src/bun.js/api/bun.zig index 782ab16efe..1bbd920793 100644 --- a/src/bun.js/api/bun.zig +++ b/src/bun.js/api/bun.zig @@ -282,9 +282,8 @@ pub fn flushCSSImports() void { } pub fn getCSSImports() []ZigString { - var i: u16 = 0; const tail = css_imports_list_tail; - while (i < tail) : (i += 1) { + for (0..tail) |i| { ZigString.fromStringPointer(css_imports_list[i], css_imports_buf.items, &css_imports_list_strings[i]); } return css_imports_list_strings[0..tail]; @@ -3269,11 +3268,8 @@ pub const Timer = struct { } else { args = args_buf[0..count]; } - var arg = args.ptr; - var i: u32 = 0; - while (i < count) : (i += 1) { - arg[0] = JSC.JSObject.getIndex(arguments, globalThis, @as(u32, @truncate(i))); - arg += 1; + for (args, 0..) |*arg, i| { + arg.* = JSC.JSObject.getIndex(arguments, globalThis, @as(u32, @truncate(i))); } } } diff --git a/src/bun.js/api/glob.zig b/src/bun.js/api/glob.zig index 2f9fd6a523..55ac123bf1 100644 --- a/src/bun.js/api/glob.zig +++ b/src/bun.js/api/glob.zig @@ -529,8 +529,7 @@ pub fn match(this: *Glob, globalThis: *JSGlobalObject, callframe: *JSC.CallFrame pub fn convertUtf8(codepoints: *std.ArrayList(u32), pattern: []const u8) !void { const iter = CodepointIterator.init(pattern); var cursor = CodepointIterator.Cursor{}; - var i: u32 = 0; - while (iter.next(&cursor)) : (i += 1) { + while (iter.next(&cursor)) { try codepoints.append(@intCast(cursor.c)); } } diff --git a/src/bun.js/api/server.zig b/src/bun.js/api/server.zig index 90fcb4ebb2..7b6166ef57 100644 --- a/src/bun.js/api/server.zig +++ b/src/bun.js/api/server.zig @@ -280,8 +280,7 @@ pub const ServerConfig = struct { } if (this.cert) |cert| { - var i: u32 = 0; - while (i < this.cert_count) : (i += 1) { + for (0..this.cert_count) |i| { const slice = std.mem.span(cert[i]); if (slice.len > 0) { bun.default_allocator.free(slice); @@ -293,8 +292,7 @@ pub const ServerConfig = struct { } if (this.key) |key| { - var i: u32 = 0; - while (i < this.key_count) : (i += 1) { + for (0..this.key_count) |i| { const slice = std.mem.span(key[i]); if (slice.len > 0) { bun.default_allocator.free(slice); @@ -306,8 +304,7 @@ pub const ServerConfig = struct { } if (this.ca) |ca| { - var i: u32 = 0; - while (i < this.ca_count) : (i += 1) { + for (0..this.ca_count) |i| { const slice = std.mem.span(ca[i]); if (slice.len > 0) { bun.default_allocator.free(slice); @@ -355,10 +352,9 @@ pub const ServerConfig = struct { if (count > 0) { const native_array = bun.default_allocator.alloc([*c]const u8, count) catch unreachable; - var i: u32 = 0; var valid_count: u32 = 0; - while (i < count) : (i += 1) { - const item = js_obj.getIndex(global, i); + for (0..count) |i| { + const item = js_obj.getIndex(global, @intCast(i)); if (JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { defer sb.deinit(); const sliced = sb.slice(); @@ -466,11 +462,9 @@ pub const ServerConfig = struct { if (count > 0) { const native_array = bun.default_allocator.alloc([*c]const u8, count) catch unreachable; - var i: u32 = 0; var valid_count: u32 = 0; - - while (i < count) : (i += 1) { - const item = js_obj.getIndex(global, i); + for (0..count) |i| { + const item = js_obj.getIndex(global, @intCast(i)); if (JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { defer sb.deinit(); const sliced = sb.slice(); @@ -574,11 +568,9 @@ pub const ServerConfig = struct { if (count > 0) { const native_array = bun.default_allocator.alloc([*c]const u8, count) catch unreachable; - var i: u32 = 0; var valid_count: u32 = 0; - - while (i < count) : (i += 1) { - const item = js_obj.getIndex(global, i); + for (0..count) |i| { + const item = js_obj.getIndex(global, @intCast(i)); if (JSC.Node.StringOrBuffer.fromJS(global, arena.allocator(), item)) |sb| { defer sb.deinit(); const sliced = sb.slice(); diff --git a/src/bun.js/base.zig b/src/bun.js/base.zig index 75b684385f..2099e23e48 100644 --- a/src/bun.js/base.zig +++ b/src/bun.js/base.zig @@ -1196,11 +1196,8 @@ pub fn wrapInstanceMethod( var args: Args = undefined; const has_exception_ref: bool = comptime brk: { - var i: usize = 0; - while (i < FunctionTypeInfo.params.len) : (i += 1) { - const ArgType = FunctionTypeInfo.params[i].type.?; - - if (ArgType == JSC.C.ExceptionRef) { + for (FunctionTypeInfo.params) |param| { + if (param.type.? == JSC.C.ExceptionRef) { break :brk true; } } @@ -1210,11 +1207,9 @@ pub fn wrapInstanceMethod( var exception_value = [_]JSC.C.JSValueRef{null}; const exception: JSC.C.ExceptionRef = if (comptime has_exception_ref) &exception_value else undefined; - comptime var i: usize = 0; - inline while (i < FunctionTypeInfo.params.len) : (i += 1) { - const ArgType = comptime FunctionTypeInfo.params[i].type.?; - - switch (comptime ArgType) { + inline for (FunctionTypeInfo.params, 0..) |param, i| { + const ArgType = param.type.?; + switch (ArgType) { *Container => { args[i] = this; }, @@ -1373,11 +1368,9 @@ pub fn wrapStaticMethod( var iter = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments.slice()); var args: Args = undefined; - comptime var i: usize = 0; - inline while (i < FunctionTypeInfo.params.len) : (i += 1) { - const ArgType = comptime FunctionTypeInfo.params[i].type.?; - - switch (comptime ArgType) { + inline for (FunctionTypeInfo.params, 0..) |param, i| { + const ArgType = param.type.?; + switch (param.type.?) { *JSC.JSGlobalObject => { args[i] = globalThis.ptr(); }, diff --git a/src/bun.js/bindings/bindings.zig b/src/bun.js/bindings/bindings.zig index b3536e8693..664953d1e7 100644 --- a/src/bun.js/bindings/bindings.zig +++ b/src/bun.js/bindings/bindings.zig @@ -5950,10 +5950,8 @@ pub fn JSPropertyIterator(comptime options: JSPropertyIteratorOptions) type { } pub fn hasLongNames(self: *Self) bool { - var i = self.i; - const len = self.len; var estimated_length: usize = 0; - while (i < len) : (i += 1) { + for (self.i..self.len) |i| { estimated_length += JSC.C.JSStringGetLength(JSC.C.JSPropertyNameArrayGetNameAtIndex(self.array_ref, i)); if (estimated_length > 14) return true; } diff --git a/src/bun.js/javascript.zig b/src/bun.js/javascript.zig index 8a24aa1a1b..9235a5a7b4 100644 --- a/src/bun.js/javascript.zig +++ b/src/bun.js/javascript.zig @@ -2525,12 +2525,10 @@ pub const VirtualMachine = struct { const stack = trace.frames(); if (stack.len > 0) { var vm = VirtualMachine.get(); - var i: i16 = 0; const origin: ?*const URL = if (vm.is_from_devserver) &vm.origin else null; const dir = vm.bundler.fs.top_level_dir; - while (i < stack.len) : (i += 1) { - const frame = stack[@as(usize, @intCast(i))]; + for (stack) |frame| { const file_slice = frame.source_url.toUTF8(bun.default_allocator); defer file_slice.deinit(); const func_slice = frame.function_name.toUTF8(bun.default_allocator); @@ -2648,9 +2646,7 @@ pub const VirtualMachine = struct { if (start_index) |k| { var j = k; - var i: usize = k; - while (i < frames.len) : (i += 1) { - const frame = frames[i]; + for (frames[k..]) |frame| { if (frame.source_url.eqlComptime("bun:wrap") or frame.function_name.eqlComptime("::bunternal::")) { diff --git a/src/bun.zig b/src/bun.zig index b6454ec88a..ef22ae5dfa 100644 --- a/src/bun.zig +++ b/src/bun.zig @@ -304,10 +304,8 @@ pub fn DebugOnlyDefault(comptime val: anytype) if (Environment.allow_assert) @Ty pub inline fn range(comptime min: anytype, comptime max: anytype) [max - min]usize { return comptime brk: { var slice: [max - min]usize = undefined; - var i: usize = min; - while (i < max) { + for (min..max) |i| { slice[i - min] = i; - i += 1; } break :brk slice; }; diff --git a/src/c.zig b/src/c.zig index e6c857e3eb..135e8c5f95 100644 --- a/src/c.zig +++ b/src/c.zig @@ -244,8 +244,7 @@ pub fn getSelfExeSharedLibPaths(allocator: std.mem.Allocator) error{OutOfMemory} allocator.free(slice); } const img_count = std.c._dyld_image_count(); - var i: u32 = 0; - while (i < img_count) : (i += 1) { + for (0..img_count) |i| { const name = std.c._dyld_get_image_name(i); const item = try allocator.dupeZ(u8, mem.sliceTo(name, 0)); errdefer allocator.free(item); diff --git a/src/comptime_string_map.zig b/src/comptime_string_map.zig index ea21eb9003..7b40b4aecd 100644 --- a/src/comptime_string_map.zig +++ b/src/comptime_string_map.zig @@ -98,11 +98,9 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co break :brk i; }; - comptime var i = len_indexes[len]; - // This benchmarked faster for both small and large lists of strings than using a big switch statement // But only so long as the keys are a sorted list. - inline while (i < end) : (i += 1) { + inline for (len_indexes[len]..end) |i| { if (strings.eqlComptimeCheckLenWithType(KeyType, str, kvs[i].key, false)) { return kvs[i].value; } @@ -121,11 +119,9 @@ pub fn ComptimeStringMapWithKeyType(comptime KeyType: type, comptime V: type, co break :brk i; }; - comptime var i = len_indexes[len]; - // This benchmarked faster for both small and large lists of strings than using a big switch statement // But only so long as the keys are a sorted list. - inline while (i < end) : (i += 1) { + inline for (len_indexes[len]..end) |i| { if (eqls(str, kvs[i].key)) { return kvs[i].value; } @@ -475,19 +471,17 @@ pub fn compareString(input: []const u8) !void { 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; var timer = try std.time.Timer.start(); - while (i < 99999999) : (i += 1) { + for (0..99999999) |_| { is_eql = @call(.never_inline, TestEnum2.map.has, .{str}); } const new = timer.lap(); std.debug.print("- new {}\n", .{std.fmt.fmtDuration(new)}); - i = 0; - while (i < 99999999) : (i += 1) { + for (0..99999999) |_| { is_eql = @call(.never_inline, TestEnum2.official.has, .{str}); } diff --git a/src/defines.zig b/src/defines.zig index 9226e269b4..204361be77 100644 --- a/src/defines.zig +++ b/src/defines.zig @@ -169,14 +169,11 @@ fn arePartsEqual(a: []const string, b: []const string) bool { if (a.len != b.len) { return false; } - - var i: usize = 0; - while (i < a.len) : (i += 1) { + for (0..a.len) |i| { if (!strings.eql(a[i], b[i])) { return false; } } - return true; } diff --git a/src/enums.zig b/src/enums.zig index 6acee69b3f..f5aaf71edc 100644 --- a/src/enums.zig +++ b/src/enums.zig @@ -246,8 +246,7 @@ pub fn EnumSet(comptime E: type) type { /// Initializes the set using a struct of bools pub fn init(init_values: EnumFieldStruct(E, bool, false)) Self { var result = Self{}; - comptime var i: usize = 0; - inline while (i < Self.len) : (i += 1) { + inline for (0..Self.len) |i| { const key = comptime Indexer.keyForIndex(i); const tag = comptime @tagName(key); if (@field(init_values, tag)) { @@ -274,8 +273,7 @@ pub fn EnumMap(comptime E: type, comptime V: type) type { /// Initializes the map using a sparse struct of optionals pub fn init(init_values: EnumFieldStruct(E, ?V, @as(?V, null))) Self { var result = Self{}; - comptime var i: usize = 0; - inline while (i < Self.len) : (i += 1) { + inline for (0..Self.len) |i| { const key = comptime Indexer.keyForIndex(i); const tag = comptime @tagName(key); if (@field(init_values, tag)) |*v| { @@ -307,8 +305,7 @@ pub fn EnumMap(comptime E: type, comptime V: type) type { .bits = Self.BitSet.initFull(), .values = undefined, }; - comptime var i: usize = 0; - inline while (i < Self.len) : (i += 1) { + inline for (0..Self.len) |i| { const key = comptime Indexer.keyForIndex(i); const tag = comptime @tagName(key); result.values[i] = @field(init_values, tag); @@ -734,8 +731,7 @@ pub fn EnumArray(comptime E: type, comptime V: type) type { /// Initializes values in the enum array, with the specified default. pub fn initDefault(comptime default: ?V, init_values: EnumFieldStruct(E, V, default)) Self { var result = Self{ .values = undefined }; - comptime var i: usize = 0; - inline while (i < Self.len) : (i += 1) { + inline for (0..Self.len) |i| { const key = comptime Indexer.keyForIndex(i); const tag = @tagName(key); result.values[i] = @field(init_values, tag); diff --git a/src/fmt.zig b/src/fmt.zig index 33f15bff8b..65b2b94937 100644 --- a/src/fmt.zig +++ b/src/fmt.zig @@ -1014,12 +1014,10 @@ pub fn HexIntFormatter(comptime Int: type, comptime lower: bool) type { fn getOutBuf(value: Int) BufType { var buf: BufType = undefined; - comptime var i: usize = 0; - inline while (i < buf.len) : (i += 1) { + inline for (&buf, 0..) |*c, i| { // value relative to the current nibble - buf[i] = table[@as(u8, @as(u4, @truncate(value >> comptime ((buf.len - i - 1) * 4)))) & 0xF]; + c.* = table[@as(u8, @as(u4, @truncate(value >> comptime ((buf.len - i - 1) * 4)))) & 0xF]; } - return buf; } diff --git a/src/hive_array.zig b/src/hive_array.zig index 0f09735992..22593f064e 100644 --- a/src/hive_array.zig +++ b/src/hive_array.zig @@ -135,16 +135,13 @@ test "HiveArray" { a.available = @TypeOf(a.available).initFull(); { - var i: u63 = 0; - while (i < size) { + for (0..size) |i| { const b = a.get().?; try testing.expectEqual(a.indexOf(b), i); try testing.expect(a.put(b)); try testing.expect(a.get().? == b); - i = i + 1; } - i = 0; - while (i < size) : (i += 1) { + for (0..size) |_| { try testing.expect(a.get() == null); } } diff --git a/src/js_ast.zig b/src/js_ast.zig index 2e44d131cd..2454ce0d70 100644 --- a/src/js_ast.zig +++ b/src/js_ast.zig @@ -3331,12 +3331,10 @@ pub const Expr = struct { return Expr.joinWithComma(all[0], all[1], allocator); }, else => { - var i: usize = 1; var expr = all[0]; - while (i < all.len) : (i += 1) { + for (1..all.len) |i| { expr = Expr.joinWithComma(expr, all[i], allocator); } - return expr; }, } diff --git a/src/js_lexer.zig b/src/js_lexer.zig index 769e0063d9..a7ac8f8bdc 100644 --- a/src/js_lexer.zig +++ b/src/js_lexer.zig @@ -309,8 +309,7 @@ fn NewLexer_( defer it.current = original_i; var end_ix = original_i; - var found: usize = 0; - while (found < n) : (found += 1) { + for (0..n) |_| { const next_codepoint = it.nextCodepointSlice(); if (next_codepoint.len == 0) break; end_ix += next_codepoint.len; diff --git a/src/js_parser.zig b/src/js_parser.zig index e2081689c6..01447cb4e0 100644 --- a/src/js_parser.zig +++ b/src/js_parser.zig @@ -1030,9 +1030,7 @@ pub const ImportScanner = struct { if (st.items.len > 0) { found_imports = true; var items_end: usize = 0; - var i: usize = 0; - while (i < st.items.len) : (i += 1) { - const item = st.items[i]; + for (st.items) |item| { const ref = item.name.ref.?; const symbol: Symbol = p.symbols.items[ref.innerIndex()]; @@ -8724,11 +8722,10 @@ fn NewParser_( item_refs.putAssumeCapacity(name, name_loc.*); } } - var i: usize = 0; var end: usize = 0; - while (i < stmt.items.len) : (i += 1) { - var item: js_ast.ClauseItem = stmt.items[i]; + for (stmt.items) |item_| { + var item = item_; const name = p.loadNameFromRef(item.name.ref orelse unreachable); const ref = try p.declareSymbol(.import, item.name.loc, name); item.name.ref = ref; @@ -18820,9 +18817,7 @@ fn NewParser_( const old_is_inside_Swsitch = p.fn_or_arrow_data_visit.is_inside_switch; p.fn_or_arrow_data_visit.is_inside_switch = true; defer p.fn_or_arrow_data_visit.is_inside_switch = old_is_inside_Swsitch; - var i: usize = 0; - while (i < data.cases.len) : (i += 1) { - const case = data.cases[i]; + for (data.cases, 0..) |case, i| { if (case.value) |val| { data.cases[i].value = p.visitExpr(val); // TODO: error messages @@ -20448,11 +20443,8 @@ fn NewParser_( p.enclosing_class_keyword = old_enclosing_class_keyword; } - var i: usize = 0; var constructor_function: ?*E.Function = null; - while (i < class.properties.len) : (i += 1) { - var property = &class.properties[i]; - + for (class.properties) |*property| { if (property.kind == .class_static_block) { const old_fn_or_arrow_data = p.fn_or_arrow_data_visit; const old_fn_only_data = p.fn_only_data_visit; @@ -20488,7 +20480,7 @@ fn NewParser_( if (is_private) { p.recordDeclaredSymbol(property.key.?.data.e_private_identifier.ref) catch unreachable; } else if (property.key) |key| { - class.properties[i].key = p.visitExpr(key); + property.key = p.visitExpr(key); } // Make it an error to use "arguments" in a class body diff --git a/src/js_printer.zig b/src/js_printer.zig index 4e44d3c6a1..b9e99c9afb 100644 --- a/src/js_printer.zig +++ b/src/js_printer.zig @@ -153,12 +153,11 @@ fn ws(comptime str: []const u8) Whitespacer { pub const with = str; pub const without = brk: { - var buf = [_]u8{0} ** str.len; - var i: usize = 0; + var buf = std.mem.zeroes([str.len]u8); var buf_i: usize = 0; - while (i < str.len) : (i += 1) { - if (str[i] != ' ') { - buf[buf_i] = str[i]; + for (str) |c| { + if (c != ' ') { + buf[buf_i] = c; buf_i += 1; } } diff --git a/src/json_parser.zig b/src/json_parser.zig index be2c7b5fa7..4c434e2aa5 100644 --- a/src/json_parser.zig +++ b/src/json_parser.zig @@ -577,11 +577,9 @@ pub fn toAST( return Expr.init(js_ast.E.String, js_ast.E.String.init(value), logger.Loc.Empty); } - var exprs = try allocator.alloc(Expr, value.len); - var i: usize = 0; - while (i < exprs.len) : (i += 1) { - exprs[i] = try toAST(allocator, @TypeOf(value[i]), value[i]); - } + const exprs = try allocator.alloc(Expr, value.len); + for (exprs, 0..) |*ex, i| ex.* = try toAST(allocator, @TypeOf(value[i]), value[i]); + return Expr.init(js_ast.E.Array, js_ast.E.Array{ .items = exprs }, logger.Loc.Empty); }, else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"), @@ -591,11 +589,9 @@ pub fn toAST( return Expr.init(js_ast.E.String, js_ast.E.String.init(value), logger.Loc.Empty); } - var exprs = try allocator.alloc(Expr, value.len); - var i: usize = 0; - while (i < exprs.len) : (i += 1) { - exprs[i] = try toAST(allocator, @TypeOf(value[i]), value[i]); - } + const exprs = try allocator.alloc(Expr, value.len); + for (exprs, 0..) |*ex, i| ex.* = try toAST(allocator, @TypeOf(value[i]), value[i]); + return Expr.init(js_ast.E.Array, js_ast.E.Array{ .items = exprs }, logger.Loc.Empty); }, .Struct => |Struct| { diff --git a/src/linear_fifo.zig b/src/linear_fifo.zig index 8aa6a36433..424deb2048 100644 --- a/src/linear_fifo.zig +++ b/src/linear_fifo.zig @@ -418,8 +418,7 @@ test "LinearFifo(u8, .Dynamic)" { try testing.expectEqualSlices(u8, "HELLO", fifo.readableSlice(0)); { - var i: usize = 0; - while (i < 5) : (i += 1) { + for (0..5) |i| { try fifo.write(&[_]u8{fifo.peekItem(i)}); } try testing.expectEqual(@as(usize, 10), fifo.readableLength()); @@ -452,8 +451,7 @@ test "LinearFifo(u8, .Dynamic)" { { const buf = try fifo.writableWithSize(12); try testing.expectEqual(@as(usize, 12), buf.len); - var i: u8 = 0; - while (i < 10) : (i += 1) { + for (0..10) |i| { buf[i] = i + 'a'; } fifo.update(10); diff --git a/src/linker.zig b/src/linker.zig index f8f2356566..b3e559e0f1 100644 --- a/src/linker.zig +++ b/src/linker.zig @@ -197,20 +197,16 @@ pub const Linker = struct { const is_deferred = result.pending_imports.len > 0; - var import_records = result.ast.import_records.listManaged(linker.allocator); + const import_records = result.ast.import_records.listManaged(linker.allocator); defer { result.ast.import_records = ImportRecord.List.fromList(import_records); } // Step 1. Resolve imports & requires switch (result.loader) { .jsx, .js, .ts, .tsx => { - var record_i: u32 = 0; - const record_count = @as(u32, @truncate(import_records.items.len)); - - while (record_i < record_count) : (record_i += 1) { - var import_record = &import_records.items[record_i]; + for (import_records.items, 0..) |*import_record, record_i| { if (import_record.is_unused or - (is_bun and is_deferred and !result.isPendingImport(record_i))) continue; + (is_bun and is_deferred and !result.isPendingImport(@intCast(record_i)))) continue; const record_index = record_i; if (comptime !ignore_runtime) { @@ -228,7 +224,7 @@ pub const Linker = struct { ); } - result.ast.runtime_import_record_id = record_index; + result.ast.runtime_import_record_id = @intCast(record_index); result.ast.needs_runtime = true; continue; } @@ -240,7 +236,7 @@ pub const Linker = struct { import_record.tag = replacement.tag; import_record.is_external_without_side_effects = true; if (replacement.tag != .none) { - externals.append(record_index) catch unreachable; + externals.append(@intCast(record_index)) catch unreachable; continue; } } diff --git a/src/logger.zig b/src/logger.zig index 5a5ccbe905..604ebfa83f 100644 --- a/src/logger.zig +++ b/src/logger.zig @@ -799,14 +799,7 @@ pub const Log = struct { var string_builder = StringBuilder{}; var notes_count: usize = 0; { - var i: usize = 0; - var j: usize = other.msgs.items.len - self.msgs.items.len; - - while (i < self.msgs.items.len) : ({ - i += 1; - j += 1; - }) { - const msg: Msg = self.msgs.items[i]; + for (self.msgs.items) |msg| { msg.count(&string_builder); if (msg.notes) |notes| { @@ -820,14 +813,7 @@ pub const Log = struct { var note_i: usize = 0; { - var i: usize = 0; - var j: usize = other.msgs.items.len - self.msgs.items.len; - - while (i < self.msgs.items.len) : ({ - i += 1; - j += 1; - }) { - const msg: Msg = self.msgs.items[i]; + for (self.msgs.items, (other.msgs.items.len - self.msgs.items.len)..) |msg, j| { other.msgs.items[j] = msg.cloneWithBuilder(notes_buf[note_i..], &string_builder); note_i += (msg.notes orelse &[_]Data{}).len; } diff --git a/src/multi_array_list.zig b/src/multi_array_list.zig index 3cf9573a92..70be24a180 100644 --- a/src/multi_array_list.zig +++ b/src/multi_array_list.zig @@ -653,8 +653,7 @@ test "basic usage" { try testing.expectEqualStrings("fizzbuzz", list.items(.b)[2]); // Add 6 more things to force a capacity increase. - var i: usize = 0; - while (i < 6) : (i += 1) { + for (0..6) |i| { try list.append(ally, .{ .a = @as(u32, @intCast(4 + i)), .b = "whatever", diff --git a/src/router.zig b/src/router.zig index 8c5d0aa6ca..0dfde3afe8 100644 --- a/src/router.zig +++ b/src/router.zig @@ -204,12 +204,9 @@ pub const Routes = struct { fn matchDynamic(this: *Routes, allocator: std.mem.Allocator, path: string, comptime MatchContext: type, ctx: MatchContext) ?*Route { // its cleaned, so now we search the big list of strings - var i: usize = 0; - while (i < this.dynamic_names.len) : (i += 1) { - const name = this.dynamic_match_names[i]; - const case_sensitive_name_without_leading_slash = this.dynamic_names[i][1..]; - if (Pattern.match(path, case_sensitive_name_without_leading_slash, name, allocator, *@TypeOf(ctx.params), &ctx.params, true)) { - return this.dynamic[i]; + for (this.dynamic_names, this.dynamic_match_names, this.dynamic) |case_sensitive_name, name, route| { + if (Pattern.match(path, case_sensitive_name[1..], name, allocator, *@TypeOf(ctx.params), &ctx.params, true)) { + return route; } } @@ -569,11 +566,8 @@ pub const Route = struct { pub const Sorter = struct { const sort_table: [std.math.maxInt(u8)]u8 = brk: { var table: [std.math.maxInt(u8)]u8 = undefined; - var i: u16 = 0; - while (i < @as(u16, table.len)) { - table[i] = @as(u8, @intCast(i)); - i += 1; - } + for (&table, 0..) |*t, i| t.* = @as(u8, @intCast(i)); + // move dynamic routes to the bottom table['['] = 252; table[']'] = 253; @@ -586,9 +580,8 @@ pub const Route = struct { const math = std.math; const n = @min(lhs.len, rhs.len); - var i: usize = 0; - while (i < n) : (i += 1) { - switch (math.order(sort_table[lhs[i]], sort_table[rhs[i]])) { + for (lhs[0..n], rhs[0..n]) |lhs_i, rhs_i| { + switch (math.order(sort_table[lhs_i], sort_table[rhs_i])) { .eq => continue, .lt => return true, .gt => return false, diff --git a/src/string_immutable.zig b/src/string_immutable.zig index 5d05b6ae33..15ec586f0f 100644 --- a/src/string_immutable.zig +++ b/src/string_immutable.zig @@ -200,9 +200,8 @@ pub fn repeatingBuf(self: []u8, char: u8) void { } pub fn indexOfCharNeg(self: string, char: u8) i32 { - var i: u32 = 0; - while (i < self.len) : (i += 1) { - if (self[i] == char) return @as(i32, @intCast(i)); + for (self, 0..) |c, i| { + if (c == char) return @as(i32, @intCast(i)); } return -1; } @@ -1002,8 +1001,7 @@ pub inline fn append3(allocator: std.mem.Allocator, self: string, other: string, pub inline fn joinBuf(out: []u8, parts: anytype, comptime parts_len: usize) []u8 { var remain = out; var count: usize = 0; - comptime var i: usize = 0; - inline while (i < parts_len) : (i += 1) { + inline for (0..parts_len) |i| { const part = parts[i]; bun.copy(u8, remain, part); remain = remain[part.len..]; @@ -2395,8 +2393,7 @@ pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8 @memcpy(buf.items[0..copy_len], latin1[0..copy_len]); buf.items.len = copy_len; any_needs_escape = true; - comptime var i: usize = 0; - inline while (i < ascii_vector_size) : (i += 1) { + inline for (0..ascii_vector_size) |i| { switch (vec[i]) { '"' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + """.len) catch unreachable; @@ -2449,8 +2446,7 @@ pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8 @as(AsciiVectorU1, @bitCast((vec == vecs[4])))) == 1) { buf.ensureUnusedCapacity(ascii_vector_size + 6) catch unreachable; - comptime var i: usize = 0; - inline while (i < ascii_vector_size) : (i += 1) { + inline for (0..ascii_vector_size) |i| { switch (vec[i]) { '"' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + """.len) catch unreachable; @@ -3109,7 +3105,6 @@ pub fn utf16EqlString(text: []const u16, str: string) bool { var i: usize = 0; // TODO: is it safe to just make this u32 or u21? var r1: i32 = undefined; - var k: u4 = 0; while (i < n) : (i += 1) { r1 = text[i]; if (r1 >= 0xD800 and r1 <= 0xDBFF and i + 1 < n) { @@ -3124,8 +3119,7 @@ pub fn utf16EqlString(text: []const u16, str: string) bool { if (j + width > str.len) { return false; } - k = 0; - while (k < width) : (k += 1) { + for (0..width) |k| { if (temp[k] != str[j]) { return false; } @@ -3409,8 +3403,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) { std.debug.assert(remaining[first_set_byte] > 127); - var j: usize = 0; - while (j < first_set_byte) : (j += 1) { + for (0..first_set_byte) |j| { std.debug.assert(remaining[j] <= 127); } } @@ -3427,8 +3420,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) { std.debug.assert(remaining[first_set_byte] > 127); - var j: usize = 0; - while (j < first_set_byte) : (j += 1) { + for (0..first_set_byte) |j| { std.debug.assert(remaining[j] <= 127); } } @@ -3472,8 +3464,7 @@ pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) { std.debug.assert(remaining[first_set_byte] > 127); - var j: usize = 0; - while (j < first_set_byte) : (j += 1) { + for (0..first_set_byte) |j| { std.debug.assert(remaining[j] <= 127); } } @@ -4217,8 +4208,7 @@ pub fn @"nextUTF16NonASCIIOr$`\\"( test "indexOfNotChar" { { var yes: [312]u8 = undefined; - var i: usize = 0; - while (i < yes.len) { + for (0..yes.len) |i| { @memset(yes, 'a'); yes[i] = 'b'; if (comptime Environment.allow_assert) std.debug.assert(indexOfNotChar(&yes, 'a').? == i); @@ -4770,8 +4760,7 @@ pub fn NewCodePointIterator(comptime CodePointType: type, comptime zeroValue: co defer it.i = original_i; var end_ix = original_i; - var found: usize = 0; - while (found < n) : (found += 1) { + for (0..n) |_| { const next_codepoint = it.nextCodepointSlice() orelse return it.bytes[original_i..]; end_ix += next_codepoint.len; } diff --git a/src/string_mutable.zig b/src/string_mutable.zig index 4a8573b057..b485e5defa 100644 --- a/src/string_mutable.zig +++ b/src/string_mutable.zig @@ -288,11 +288,10 @@ pub const MutableString = struct { pub fn toSocketBuffers(self: *MutableString, comptime count: usize, ranges: anytype) [count]std.os.iovec_const { var buffers: [count]std.os.iovec_const = undefined; - comptime var i: usize = 0; - inline while (i < count) : (i += 1) { - buffers[i] = .{ - .iov_base = self.list.items[ranges[i][0]..ranges[i][1]].ptr, - .iov_len = self.list.items[ranges[i][0]..ranges[i][1]].len, + inline for (&buffers, ranges) |*b, r| { + b.* = .{ + .iov_base = self.list.items[r[0]..r[1]].ptr, + .iov_len = self.list.items[r[0]..r[1]].len, }; } return buffers; diff --git a/src/sync.zig b/src/sync.zig index 47bdfae91c..f37bbed11a 100644 --- a/src/sync.zig +++ b/src/sync.zig @@ -948,8 +948,7 @@ else if (@import("builtin").os.tag == .linux) var new_state = current_state; while (true) { - var spin: u8 = 0; - while (spin < 100) : (spin += 1) { + for (0..100) |spin| { const state = @cmpxchgWeak( State, &self.state, @@ -965,8 +964,7 @@ else if (@import("builtin").os.tag == .linux) .waiting => break, } - var iter = spin + 1; - while (iter > 0) : (iter -= 1) + for (0..spin) |_| spinLoopHint(); } diff --git a/src/thread_pool.zig b/src/thread_pool.zig index 2805e01489..17561e4fb7 100644 --- a/src/thread_pool.zig +++ b/src/thread_pool.zig @@ -1202,8 +1202,7 @@ pub const Node = struct { // Copy the nodes we will steal from the target's array to our own. // Atomically load from the target buffer array as it may be pushing and atomically storing to it. // Atomic store to our array as other steal() threads may be atomically loading from it as above. - var i: Index = 0; - while (i < steal_size) : (i += 1) { + for (0..steal_size) |i| { const node = buffer.array[(buffer_head +% i) % capacity].load(.Unordered); self.array[(tail +% i) % capacity].store(node, .Unordered); } diff --git a/src/url.zig b/src/url.zig index 07dc07ef11..f42a1e30a7 100644 --- a/src/url.zig +++ b/src/url.zig @@ -322,9 +322,8 @@ pub const URL = struct { } pub fn parseProtocol(url: *URL, str: string) ?u31 { - var i: u31 = 0; if (str.len < "://".len) return null; - while (i < str.len) : (i += 1) { + for (0..str.len) |i| { switch (str[i]) { '/', '?', '%' => { return null; @@ -332,7 +331,7 @@ pub const URL = struct { ':' => { if (i + 3 <= str.len and str[i + 1] == '/' and str[i + 2] == '/') { url.protocol = str[0..i]; - return i + 3; + return @intCast(i + 3); } }, else => {}, @@ -343,19 +342,16 @@ pub const URL = struct { } pub fn parseUsername(url: *URL, str: string) ?u31 { - var i: u31 = 0; - // reset it url.username = ""; if (str.len < "@".len) return null; - - while (i < str.len) : (i += 1) { + for (0..str.len) |i| { switch (str[i]) { ':', '@' => { // we found a username, everything before this point in the slice is a username url.username = str[0..i]; - return i + 1; + return @intCast(i + 1); }, // if we reach a slash or "?", there's no username '?', '/' => { @@ -368,20 +364,17 @@ pub const URL = struct { } pub fn parsePassword(url: *URL, str: string) ?u31 { - var i: u31 = 0; - // reset it url.password = ""; if (str.len < "@".len) return null; - - while (i < str.len) : (i += 1) { + for (0..str.len) |i| { switch (str[i]) { '@' => { // we found a password, everything before this point in the slice is a password url.password = str[0..i]; if (Environment.allow_assert) std.debug.assert(str[i..].len < 2 or std.mem.readInt(u16, str[i..][0..2], .little) != std.mem.readInt(u16, "//", .little)); - return i + 1; + return @intCast(i + 1); }, // if we reach a slash or "?", there's no password '?', '/' => { diff --git a/src/util.zig b/src/util.zig index ad99859b9f..d3a7d9580b 100644 --- a/src/util.zig +++ b/src/util.zig @@ -30,10 +30,8 @@ pub fn fromEntries( try map.ensureUnusedCapacity(allocator, entries.len); } - comptime var i: usize = 0; - - inline while (i < std.meta.fields(EntryType).len) : (i += 1) { - map.putAssumeCapacity(entries[i].@"0", entries[i].@"1"); + inline for (entries) |entry| { + map.putAssumeCapacity(entry[0], entry[1]); } return map; @@ -47,7 +45,7 @@ pub fn fromEntries( if (comptime @hasDecl(EntryType, "iterator")) { var iter = entries.iterator(); while (iter.next()) |entry| { - map.putAssumeCapacity(entry.@"0", entry.@"1"); + map.putAssumeCapacity(entry[0], entry[1]); } return map; @@ -60,7 +58,7 @@ pub fn fromEntries( } inline for (comptime std.meta.fieldNames(@TypeOf(EntryType))) |entry| { - map.putAssumeCapacity(entry.@"0", entry.@"1"); + map.putAssumeCapacity(entry[0], entry[1]); } return map; @@ -71,10 +69,8 @@ pub fn fromEntries( try map.ensureUnusedCapacity(allocator, std.meta.fields(std.meta.Child(EntryType)).len); } - comptime var i: usize = 0; - - inline while (i < std.meta.fields(std.meta.Child(EntryType)).len) : (i += 1) { - map.putAssumeCapacity(entries.*[i].@"0", entries.*[i].@"1"); + inline for (entries) |entry| { + map.putAssumeCapacity(entry[0], entry[1]); } return map;