From 94e30a756edc4c2182168dabd97d481b8aec0ff2 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Sun, 30 Apr 2023 18:02:08 +0100 Subject: std: fix a bunch of typos The majority of these are in comments, some in doc comments which might affect the generated documentation, and a few in parameter names - nothing that should be breaking, however. --- lib/std/math/big/int.zig | 20 ++++++++++---------- lib/std/math/complex/tan.zig | 2 +- lib/std/math/log10.zig | 2 +- lib/std/math/sqrt.zig | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) (limited to 'lib/std/math') diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index 2406d669ec..b01d9b04ff 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -408,7 +408,7 @@ pub const Mutable = struct { } /// Base implementation for addition. Adds `max(a.limbs.len, b.limbs.len)` elements from a and b, - /// and returns whether any overflow occured. + /// and returns whether any overflow occurred. /// r, a and b may be aliases. /// /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`. @@ -467,7 +467,7 @@ pub const Mutable = struct { const req_limbs = calcTwosCompLimbCount(bit_count); // Slice of the upper bits if they exist, these will be ignored and allows us to use addCarry to determine - // if an overflow occured. + // if an overflow occurred. const x = Const{ .positive = a.positive, .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)], @@ -512,7 +512,7 @@ pub const Mutable = struct { const req_limbs = calcTwosCompLimbCount(bit_count); // Slice of the upper bits if they exist, these will be ignored and allows us to use addCarry to determine - // if an overflow occured. + // if an overflow occurred. const x = Const{ .positive = a.positive, .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)], @@ -544,7 +544,7 @@ pub const Mutable = struct { } /// Base implementation for subtraction. Subtracts `max(a.limbs.len, b.limbs.len)` elements from a and b, - /// and returns whether any overflow occured. + /// and returns whether any overflow occurred. /// r, a and b may be aliases. /// /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`. @@ -605,7 +605,7 @@ pub const Mutable = struct { r.add(a, b.negate()); } - /// r = a - b with 2s-complement wrapping semantics. Returns whether any overflow occured. + /// r = a - b with 2s-complement wrapping semantics. Returns whether any overflow occurred. /// /// r, a and b may be aliases /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by @@ -1141,7 +1141,7 @@ pub const Mutable = struct { return; } - // Generate a mask with the bits to check in the most signficant limb. We'll need to check + // Generate a mask with the bits to check in the most significant limb. We'll need to check // all bits with equal or more significance than checkbit. // const msb = @truncate(Log2Limb, checkbit); // const checkmask = (@as(Limb, 1) << msb) -% 1; @@ -2037,7 +2037,7 @@ pub const Const = struct { add_res = ov[0]; carry = ov[1]; sum += @popCount(add_res); - remaining_bits -= limb_bits; // Asserted not to undeflow by fitsInTwosComp + remaining_bits -= limb_bits; // Asserted not to underflow by fitsInTwosComp } // The most significant limb may have fewer than @bitSizeOf(Limb) meaningful bits, @@ -2813,7 +2813,7 @@ pub const Managed = struct { r.setMetadata(m.positive, m.len); } - /// r = a + b with 2s-complement wrapping semantics. Returns whether any overflow occured. + /// r = a + b with 2s-complement wrapping semantics. Returns whether any overflow occurred. /// /// r, a and b may be aliases. /// @@ -2856,7 +2856,7 @@ pub const Managed = struct { r.setMetadata(m.positive, m.len); } - /// r = a - b with 2s-complement wrapping semantics. Returns whether any overflow occured. + /// r = a - b with 2s-complement wrapping semantics. Returns whether any overflow occurred. /// /// r, a and b may be aliases. /// @@ -4010,7 +4010,7 @@ fn llsquareBasecase(r: []Limb, x: []const Limb) void { assert(r.len >= 2 * x_norm.len + 1); // Compute the square of a N-limb bigint with only (N^2 + N)/2 - // multiplications by exploting the symmetry of the coefficients around the + // multiplications by exploiting the symmetry of the coefficients around the // diagonal: // // a b c * diff --git a/lib/std/math/complex/tan.zig b/lib/std/math/complex/tan.zig index 9e1025f74f..a0ce5d18e0 100644 --- a/lib/std/math/complex/tan.zig +++ b/lib/std/math/complex/tan.zig @@ -4,7 +4,7 @@ const math = std.math; const cmath = math.complex; const Complex = cmath.Complex; -/// Returns the tanget of z. +/// Returns the tangent of z. pub fn tan(z: anytype) Complex(@TypeOf(z.re)) { const T = @TypeOf(z.re); const q = Complex(T).init(-z.im, z.re); diff --git a/lib/std/math/log10.zig b/lib/std/math/log10.zig index b1ecb9ad2b..6b5758763c 100644 --- a/lib/std/math/log10.zig +++ b/lib/std/math/log10.zig @@ -58,7 +58,7 @@ pub fn log10_int(x: anytype) Log2Int(@TypeOf(x)) { var log: u32 = 0; inline for (0..11) |i| { - // Unnecesary branches should be removed by the compiler + // Unnecessary branches should be removed by the compiler if (bit_size > (1 << (11 - i)) * 5 * @log2(10.0) and val >= pow10((1 << (11 - i)) * 5)) { const num_digits = (1 << (11 - i)) * 5; val /= pow10(num_digits); diff --git a/lib/std/math/sqrt.zig b/lib/std/math/sqrt.zig index e642f8a309..926582034e 100644 --- a/lib/std/math/sqrt.zig +++ b/lib/std/math/sqrt.zig @@ -11,7 +11,7 @@ const maxInt = std.math.maxInt; /// - sqrt(+-0) = +-0 /// - sqrt(x) = nan if x < 0 /// - sqrt(nan) = nan -/// TODO Decide if all this logic should be implemented directly in the @sqrt bultin function. +/// TODO Decide if all this logic should be implemented directly in the @sqrt builtin function. pub fn sqrt(x: anytype) Sqrt(@TypeOf(x)) { const T = @TypeOf(x); switch (@typeInfo(T)) { -- cgit v1.2.3 From bd3360e03d89fe947e3728ccacd4274653926376 Mon Sep 17 00:00:00 2001 From: dweiller <4678790+dweiller@users.noreplay.github.com> Date: Tue, 2 May 2023 22:08:54 +1000 Subject: convert s[start..start+len] to s[start..][0..len] --- lib/std/Build/Cache/DepTokenizer.zig | 2 +- lib/std/array_list.zig | 4 ++-- lib/std/bounded_array.zig | 2 +- lib/std/compress/deflate/decompressor.zig | 2 +- lib/std/compress/deflate/huffman_bit_writer.zig | 6 +++--- lib/std/hash/crc.zig | 2 +- lib/std/hash/wyhash.zig | 2 +- lib/std/json.zig | 6 +++--- lib/std/math/big/int.zig | 2 +- lib/std/net.zig | 2 +- lib/std/os/windows.zig | 4 ++-- lib/std/testing.zig | 2 +- lib/std/unicode.zig | 2 +- src/link/Plan9/aout.zig | 2 +- 14 files changed, 20 insertions(+), 20 deletions(-) (limited to 'lib/std/math') diff --git a/lib/std/Build/Cache/DepTokenizer.zig b/lib/std/Build/Cache/DepTokenizer.zig index c640fa4adc..1a4e2ddb74 100644 --- a/lib/std/Build/Cache/DepTokenizer.zig +++ b/lib/std/Build/Cache/DepTokenizer.zig @@ -974,7 +974,7 @@ fn hexDump(out: anytype, bytes: []const u8) !void { var line: usize = 0; var offset: usize = 0; while (line < n16) : (line += 1) { - try hexDump16(out, offset, bytes[offset .. offset + 16]); + try hexDump16(out, offset, bytes[offset..][0..16]); offset += 16; } diff --git a/lib/std/array_list.zig b/lib/std/array_list.zig index cbca601b82..bbfa588d6d 100644 --- a/lib/std/array_list.zig +++ b/lib/std/array_list.zig @@ -173,7 +173,7 @@ pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type { @memcpy(self.items[i..][0..items.len], items); } - /// Replace range of elements `list[start..start+len]` with `new_items`. + /// Replace range of elements `list[start..][0..len]` with `new_items`. /// Grows list if `len < new_items.len`. /// Shrinks list if `len > new_items.len`. /// Invalidates pointers if this ArrayList is resized. @@ -654,7 +654,7 @@ pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) typ @memcpy(self.items[i..][0..items.len], items); } - /// Replace range of elements `list[start..start+len]` with `new_items` + /// Replace range of elements `list[start..][0..len]` with `new_items` /// Grows list if `len < new_items.len`. /// Shrinks list if `len > new_items.len` /// Invalidates pointers if this ArrayList is resized. diff --git a/lib/std/bounded_array.zig b/lib/std/bounded_array.zig index be32093fe7..0e0b601af6 100644 --- a/lib/std/bounded_array.zig +++ b/lib/std/bounded_array.zig @@ -168,7 +168,7 @@ pub fn BoundedArrayAligned( @memcpy(self.slice()[i..][0..items.len], items); } - /// Replace range of elements `slice[start..start+len]` with `new_items`. + /// Replace range of elements `slice[start..][0..len]` with `new_items`. /// Grows slice if `len < new_items.len`. /// Shrinks slice if `len > new_items.len`. pub fn replaceRange( diff --git a/lib/std/compress/deflate/decompressor.zig b/lib/std/compress/deflate/decompressor.zig index 6c232c598e..40bde67326 100644 --- a/lib/std/compress/deflate/decompressor.zig +++ b/lib/std/compress/deflate/decompressor.zig @@ -591,7 +591,7 @@ pub fn Decompressor(comptime ReaderType: type) type { } if (!try self.hd1.init(self.allocator, self.bits[0..nlit]) or - !try self.hd2.init(self.allocator, self.bits[nlit .. nlit + ndist])) + !try self.hd2.init(self.allocator, self.bits[nlit..][0..ndist])) { corrupt_input_error_offset = self.roffset; self.err = InflateError.CorruptInput; diff --git a/lib/std/compress/deflate/huffman_bit_writer.zig b/lib/std/compress/deflate/huffman_bit_writer.zig index a42aae467b..0b76d9d89d 100644 --- a/lib/std/compress/deflate/huffman_bit_writer.zig +++ b/lib/std/compress/deflate/huffman_bit_writer.zig @@ -139,7 +139,7 @@ pub fn HuffmanBitWriter(comptime WriterType: type) type { self.bits >>= 48; self.nbits -= 48; var n = self.nbytes; - var bytes = self.bytes[n .. n + 6]; + var bytes = self.bytes[n..][0..6]; bytes[0] = @truncate(u8, bits); bytes[1] = @truncate(u8, bits >> 8); bytes[2] = @truncate(u8, bits >> 16); @@ -344,7 +344,7 @@ pub fn HuffmanBitWriter(comptime WriterType: type) type { self.bits >>= 48; self.nbits -= 48; var n = self.nbytes; - var bytes = self.bytes[n .. n + 6]; + var bytes = self.bytes[n..][0..6]; bytes[0] = @truncate(u8, bits); bytes[1] = @truncate(u8, bits >> 8); bytes[2] = @truncate(u8, bits >> 16); @@ -751,7 +751,7 @@ pub fn HuffmanBitWriter(comptime WriterType: type) type { var bits = self.bits; self.bits >>= 48; self.nbits -= 48; - var bytes = self.bytes[n .. n + 6]; + var bytes = self.bytes[n..][0..6]; bytes[0] = @truncate(u8, bits); bytes[1] = @truncate(u8, bits >> 8); bytes[2] = @truncate(u8, bits >> 16); diff --git a/lib/std/hash/crc.zig b/lib/std/hash/crc.zig index 271b4f93da..0ad154abef 100644 --- a/lib/std/hash/crc.zig +++ b/lib/std/hash/crc.zig @@ -160,7 +160,7 @@ pub fn Crc32WithPoly(comptime poly: Polynomial) type { pub fn update(self: *Self, input: []const u8) void { var i: usize = 0; while (i + 8 <= input.len) : (i += 8) { - const p = input[i .. i + 8]; + const p = input[i..][0..8]; // Unrolling this way gives ~50Mb/s increase self.crc ^= std.mem.readIntLittle(u32, p[0..4]); diff --git a/lib/std/hash/wyhash.zig b/lib/std/hash/wyhash.zig index 772395eab9..934c4f96ad 100644 --- a/lib/std/hash/wyhash.zig +++ b/lib/std/hash/wyhash.zig @@ -65,7 +65,7 @@ const WyhashStateless = struct { var off: usize = 0; while (off < b.len) : (off += 32) { - @call(.always_inline, self.round, .{b[off .. off + 32]}); + @call(.always_inline, self.round, .{b[off..][0..32]}); } self.msg_len += b.len; diff --git a/lib/std/json.zig b/lib/std/json.zig index af928bc564..011463faef 100644 --- a/lib/std/json.zig +++ b/lib/std/json.zig @@ -63,7 +63,7 @@ fn encodesTo(decoded: []const u8, encoded: []const u8) bool { var buf: [4]u8 = undefined; const len = std.unicode.utf8Encode(codepoint, &buf) catch unreachable; if (i + len > decoded.len) return false; - if (!mem.eql(u8, decoded[i .. i + len], buf[0..len])) return false; + if (!mem.eql(u8, decoded[i..][0..len], buf[0..len])) return false; i += len; } } @@ -2285,10 +2285,10 @@ pub fn encodeJsonStringChars(chars: []const u8, options: StringifyOptions, write const ulen = std.unicode.utf8ByteSequenceLength(chars[i]) catch unreachable; // control characters (only things left with 1 byte length) should always be printed as unicode escapes if (ulen == 1 or options.string.String.escape_unicode) { - const codepoint = std.unicode.utf8Decode(chars[i .. i + ulen]) catch unreachable; + const codepoint = std.unicode.utf8Decode(chars[i..][0..ulen]) catch unreachable; try outputUnicodeEscape(codepoint, writer); } else { - try writer.writeAll(chars[i .. i + ulen]); + try writer.writeAll(chars[i..][0..ulen]); } i += ulen - 1; }, diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index b01d9b04ff..5683d8681c 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -4035,7 +4035,7 @@ fn llsquareBasecase(r: []Limb, x: []const Limb) void { for (x_norm, 0..) |v, i| { // Compute and add the squares - const overflow = llmulLimb(.add, r[2 * i ..], x[i .. i + 1], v); + const overflow = llmulLimb(.add, r[2 * i ..], x[i..][0..1], v); assert(!overflow); } } diff --git a/lib/std/net.zig b/lib/std/net.zig index 15a9e01da8..57e50a7349 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -1701,7 +1701,7 @@ fn dnsParse( p += @as(usize, 1) + @boolToInt(p[0] != 0); const len = p[8] * @as(usize, 256) + p[9]; if (@ptrToInt(p) + len > @ptrToInt(r.ptr) + r.len) return error.InvalidDnsPacket; - try callback(ctx, p[1], p[10 .. 10 + len], r); + try callback(ctx, p[1], p[10..][0..len], r); p += 10 + len; } } diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index 22ffc850e6..6755e7adf2 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -835,14 +835,14 @@ pub fn ReadLink(dir: ?HANDLE, sub_path_w: []const u16, out_buffer: []u8) ReadLin const len = buf.SubstituteNameLength >> 1; const path_buf = @as([*]const u16, &buf.PathBuffer); const is_relative = buf.Flags & SYMLINK_FLAG_RELATIVE != 0; - return parseReadlinkPath(path_buf[offset .. offset + len], is_relative, out_buffer); + return parseReadlinkPath(path_buf[offset..][0..len], is_relative, out_buffer); }, IO_REPARSE_TAG_MOUNT_POINT => { const buf = @ptrCast(*const MOUNT_POINT_REPARSE_BUFFER, @alignCast(@alignOf(MOUNT_POINT_REPARSE_BUFFER), &reparse_struct.DataBuffer[0])); const offset = buf.SubstituteNameOffset >> 1; const len = buf.SubstituteNameLength >> 1; const path_buf = @as([*]const u16, &buf.PathBuffer); - return parseReadlinkPath(path_buf[offset .. offset + len], false, out_buffer); + return parseReadlinkPath(path_buf[offset..][0..len], false, out_buffer); }, else => |value| { std.debug.print("unsupported symlink type: {}", .{value}); diff --git a/lib/std/testing.zig b/lib/std/testing.zig index 37e15ff08b..2857ebdbd3 100644 --- a/lib/std/testing.zig +++ b/lib/std/testing.zig @@ -941,7 +941,7 @@ fn printIndicatorLine(source: []const u8, indicator_index: usize) void { fn printWithVisibleNewlines(source: []const u8) void { var i: usize = 0; while (std.mem.indexOfScalar(u8, source[i..], '\n')) |nl| : (i += nl + 1) { - printLine(source[i .. i + nl]); + printLine(source[i..][0..nl]); } print("{s}␃\n", .{source[i..]}); // End of Text symbol (ETX) } diff --git a/lib/std/unicode.zig b/lib/std/unicode.zig index 378b216ef3..9d334218c1 100644 --- a/lib/std/unicode.zig +++ b/lib/std/unicode.zig @@ -185,7 +185,7 @@ pub fn utf8CountCodepoints(s: []const u8) !usize { switch (n) { 1 => {}, // ASCII, no validation needed - else => _ = try utf8Decode(s[i .. i + n]), + else => _ = try utf8Decode(s[i..][0..n]), } i += n; diff --git a/src/link/Plan9/aout.zig b/src/link/Plan9/aout.zig index b39cae5166..d6fbb47d35 100644 --- a/src/link/Plan9/aout.zig +++ b/src/link/Plan9/aout.zig @@ -21,7 +21,7 @@ pub const ExecHdr = extern struct { var buf: [40]u8 = undefined; var i: u8 = 0; inline for (std.meta.fields(@This())) |f| { - std.mem.writeIntSliceBig(u32, buf[i .. i + 4], @field(self, f.name)); + std.mem.writeIntSliceBig(u32, buf[i..][0..4], @field(self, f.name)); i += 4; } return buf; -- cgit v1.2.3 From 5a3eca5d4ca42f92abe60040e21ffd8e307d8466 Mon Sep 17 00:00:00 2001 From: Dominic <4678790+dweiller@users.noreply.github.com> Date: Mon, 8 May 2023 17:59:06 +1000 Subject: Disallow named test decls with duplicate names --- lib/std/fmt.zig | 75 +++++++++++----------- lib/std/hash_map.zig | 34 +++++----- lib/std/io/reader.zig | 23 +++---- lib/std/math/big/int_test.zig | 13 ++-- lib/std/math/big/rational.zig | 52 +++++++-------- lib/std/net/test.zig | 2 +- lib/std/priority_dequeue.zig | 4 +- lib/std/zig/parser_test.zig | 8 +-- src/Module.zig | 26 +++++++- test/behavior.zig | 1 + test/behavior/basic.zig | 2 +- test/behavior/comptime_memory.zig | 2 +- test/behavior/duplicated_test_names.zig | 17 +++++ test/behavior/vector.zig | 14 ---- .../invalid_duplicate_test_decl_name.zig | 10 +++ 15 files changed, 158 insertions(+), 125 deletions(-) create mode 100644 test/behavior/duplicated_test_names.zig create mode 100644 test/cases/compile_errors/invalid_duplicate_test_decl_name.zig (limited to 'lib/std/math') diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index cf791df1a6..c3ccd75d27 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -2244,8 +2244,8 @@ test "struct" { field: u8, }; const value = Struct{ .field = 42 }; - try expectFmt("struct: Struct{ .field = 42 }\n", "struct: {}\n", .{value}); - try expectFmt("struct: Struct{ .field = 42 }\n", "struct: {}\n", .{&value}); + try expectFmt("struct: fmt.test.struct.Struct{ .field = 42 }\n", "struct: {}\n", .{value}); + try expectFmt("struct: fmt.test.struct.Struct{ .field = 42 }\n", "struct: {}\n", .{&value}); } { const Struct = struct { @@ -2253,8 +2253,24 @@ test "struct" { b: u1, }; const value = Struct{ .a = 0, .b = 1 }; - try expectFmt("struct: Struct{ .a = 0, .b = 1 }\n", "struct: {}\n", .{value}); + try expectFmt("struct: fmt.test.struct.Struct{ .a = 0, .b = 1 }\n", "struct: {}\n", .{value}); } + + const S = struct { + a: u32, + b: anyerror, + }; + + const inst = S{ + .a = 456, + .b = error.Unused, + }; + + try expectFmt("fmt.test.struct.S{ .a = 456, .b = error.Unused }", "{}", .{inst}); + // Tuples + try expectFmt("{ }", "{}", .{.{}}); + try expectFmt("{ -1 }", "{}", .{.{-1}}); + try expectFmt("{ -1, 42, 2.5e+04 }", "{}", .{.{ -1, 42, 0.25e5 }}); } test "enum" { @@ -2263,13 +2279,26 @@ test "enum" { Two, }; const value = Enum.Two; - try expectFmt("enum: Enum.Two\n", "enum: {}\n", .{value}); - try expectFmt("enum: Enum.Two\n", "enum: {}\n", .{&value}); - try expectFmt("enum: Enum.One\n", "enum: {}\n", .{Enum.One}); - try expectFmt("enum: Enum.Two\n", "enum: {}\n", .{Enum.Two}); + try expectFmt("enum: fmt.test.enum.Enum.Two\n", "enum: {}\n", .{value}); + try expectFmt("enum: fmt.test.enum.Enum.Two\n", "enum: {}\n", .{&value}); + try expectFmt("enum: fmt.test.enum.Enum.One\n", "enum: {}\n", .{Enum.One}); + try expectFmt("enum: fmt.test.enum.Enum.Two\n", "enum: {}\n", .{Enum.Two}); // test very large enum to verify ct branch quota is large enough - try expectFmt("enum: os.windows.win32error.Win32Error.INVALID_FUNCTION\n", "enum: {}\n", .{std.os.windows.Win32Error.INVALID_FUNCTION}); + // TODO: https://github.com/ziglang/zig/issues/15609 + if (!((builtin.cpu.arch == .wasm32) and builtin.mode == .Debug)) { + try expectFmt("enum: os.windows.win32error.Win32Error.INVALID_FUNCTION\n", "enum: {}\n", .{std.os.windows.Win32Error.INVALID_FUNCTION}); + } + + const E = enum { + One, + Two, + Three, + }; + + const inst = E.Two; + + try expectFmt("fmt.test.enum.E.Two", "{}", .{inst}); } test "non-exhaustive enum" { @@ -2445,24 +2474,6 @@ test "custom" { try expectFmt("dim: 10.200x2.220\n", "dim: {d}\n", .{value}); } -test "struct" { - const S = struct { - a: u32, - b: anyerror, - }; - - const inst = S{ - .a = 456, - .b = error.Unused, - }; - - try expectFmt("fmt.test.struct.S{ .a = 456, .b = error.Unused }", "{}", .{inst}); - // Tuples - try expectFmt("{ }", "{}", .{.{}}); - try expectFmt("{ -1 }", "{}", .{.{-1}}); - try expectFmt("{ -1, 42, 2.5e+04 }", "{}", .{.{ -1, 42, 0.25e5 }}); -} - test "union" { const TU = union(enum) { float: f32, @@ -2493,18 +2504,6 @@ test "union" { try std.testing.expect(mem.eql(u8, eu_result[0..18], "fmt.test.union.EU@")); } -test "enum" { - const E = enum { - One, - Two, - Three, - }; - - const inst = E.Two; - - try expectFmt("fmt.test.enum.E.Two", "{}", .{inst}); -} - test "struct.self-referential" { const S = struct { const SelfType = @This(); diff --git a/lib/std/hash_map.zig b/lib/std/hash_map.zig index df3446a2c0..91f5682831 100644 --- a/lib/std/hash_map.zig +++ b/lib/std/hash_map.zig @@ -1741,6 +1741,22 @@ test "std.hash_map clone" { try expectEqual(b.get(1).?, 1); try expectEqual(b.get(2).?, 2); try expectEqual(b.get(3).?, 3); + + var original = AutoHashMap(i32, i32).init(std.testing.allocator); + defer original.deinit(); + + var i: u8 = 0; + while (i < 10) : (i += 1) { + try original.putNoClobber(i, i * 10); + } + + var copy = try original.clone(); + defer copy.deinit(); + + i = 0; + while (i < 10) : (i += 1) { + try testing.expect(copy.get(i).? == i * 10); + } } test "std.hash_map ensureTotalCapacity with existing elements" { @@ -2072,24 +2088,6 @@ test "std.hash_map basic hash map usage" { try testing.expect(map.remove(3) == true); } -test "std.hash_map clone" { - var original = AutoHashMap(i32, i32).init(std.testing.allocator); - defer original.deinit(); - - var i: u8 = 0; - while (i < 10) : (i += 1) { - try original.putNoClobber(i, i * 10); - } - - var copy = try original.clone(); - defer copy.deinit(); - - i = 0; - while (i < 10) : (i += 1) { - try testing.expect(copy.get(i).? == i * 10); - } -} - test "std.hash_map getOrPutAdapted" { const AdaptedContext = struct { fn eql(self: @This(), adapted_key: []const u8, test_key: u64) bool { diff --git a/lib/std/io/reader.zig b/lib/std/io/reader.zig index 65b7a086c5..0b88e6b31a 100644 --- a/lib/std/io/reader.zig +++ b/lib/std/io/reader.zig @@ -553,10 +553,18 @@ test "Reader.readUntilDelimiter returns StreamTooLong, then bytes read until the } test "Reader.readUntilDelimiter returns EndOfStream" { - var buf: [5]u8 = undefined; - var fis = std.io.fixedBufferStream(""); - const reader = fis.reader(); - try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); + { + var buf: [5]u8 = undefined; + var fis = std.io.fixedBufferStream(""); + const reader = fis.reader(); + try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); + } + { + var buf: [5]u8 = undefined; + var fis = std.io.fixedBufferStream("1234"); + const reader = fis.reader(); + try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); + } } test "Reader.readUntilDelimiter returns bytes read until delimiter, then EndOfStream" { @@ -567,13 +575,6 @@ test "Reader.readUntilDelimiter returns bytes read until delimiter, then EndOfSt try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); } -test "Reader.readUntilDelimiter returns EndOfStream" { - var buf: [5]u8 = undefined; - var fis = std.io.fixedBufferStream("1234"); - const reader = fis.reader(); - try std.testing.expectError(error.EndOfStream, reader.readUntilDelimiter(&buf, '\n')); -} - test "Reader.readUntilDelimiter returns StreamTooLong, then EndOfStream" { var buf: [5]u8 = undefined; var fis = std.io.fixedBufferStream("12345"); diff --git a/lib/std/math/big/int_test.zig b/lib/std/math/big/int_test.zig index 0066ce9940..25f9815f9d 100644 --- a/lib/std/math/big/int_test.zig +++ b/lib/std/math/big/int_test.zig @@ -2012,15 +2012,10 @@ test "big.int shift-right negative" { defer arg2.deinit(); try a.shiftRight(&arg2, 10); try testing.expect((try a.to(i32)) == -1); // -5 >> 10 == -1 -} -test "big.int shift-right negative" { - var a = try Managed.init(testing.allocator); - defer a.deinit(); - - var arg = try Managed.initSet(testing.allocator, -10); - defer arg.deinit(); - try a.shiftRight(&arg, 1232); + var arg3 = try Managed.initSet(testing.allocator, -10); + defer arg3.deinit(); + try a.shiftRight(&arg3, 1232); try testing.expect((try a.to(i32)) == -1); // -10 >> 1232 == -1 } @@ -2483,7 +2478,7 @@ test "big.int gcd non-one small" { try testing.expect((try r.to(u32)) == 1); } -test "big.int gcd non-one small" { +test "big.int gcd non-one medium" { var a = try Managed.initSet(testing.allocator, 4864); defer a.deinit(); var b = try Managed.initSet(testing.allocator, 3458); diff --git a/lib/std/math/big/rational.zig b/lib/std/math/big/rational.zig index c3609a6fa2..cdc33e351d 100644 --- a/lib/std/math/big/rational.zig +++ b/lib/std/math/big/rational.zig @@ -782,36 +782,38 @@ test "big.rational mul" { } test "big.rational div" { - var a = try Rational.init(testing.allocator); - defer a.deinit(); - var b = try Rational.init(testing.allocator); - defer b.deinit(); - var r = try Rational.init(testing.allocator); - defer r.deinit(); + { + var a = try Rational.init(testing.allocator); + defer a.deinit(); + var b = try Rational.init(testing.allocator); + defer b.deinit(); + var r = try Rational.init(testing.allocator); + defer r.deinit(); - try a.setRatio(78923, 23341); - try b.setRatio(123097, 12441414); - try a.div(a, b); + try a.setRatio(78923, 23341); + try b.setRatio(123097, 12441414); + try a.div(a, b); - try r.setRatio(75531824394, 221015929); - try testing.expect((try a.order(r)) == .eq); -} + try r.setRatio(75531824394, 221015929); + try testing.expect((try a.order(r)) == .eq); + } -test "big.rational div" { - var a = try Rational.init(testing.allocator); - defer a.deinit(); - var r = try Rational.init(testing.allocator); - defer r.deinit(); + { + var a = try Rational.init(testing.allocator); + defer a.deinit(); + var r = try Rational.init(testing.allocator); + defer r.deinit(); - try a.setRatio(78923, 23341); - a.invert(); + try a.setRatio(78923, 23341); + a.invert(); - try r.setRatio(23341, 78923); - try testing.expect((try a.order(r)) == .eq); + try r.setRatio(23341, 78923); + try testing.expect((try a.order(r)) == .eq); - try a.setRatio(-78923, 23341); - a.invert(); + try a.setRatio(-78923, 23341); + a.invert(); - try r.setRatio(-23341, 78923); - try testing.expect((try a.order(r)) == .eq); + try r.setRatio(-23341, 78923); + try testing.expect((try a.order(r)) == .eq); + } } diff --git a/lib/std/net/test.zig b/lib/std/net/test.zig index 9923e4932b..817d6c2593 100644 --- a/lib/std/net/test.zig +++ b/lib/std/net/test.zig @@ -182,7 +182,7 @@ test "listen on a port, send bytes, receive bytes" { try testing.expectEqualSlices(u8, "Hello world!", buf[0..n]); } -test "listen on a port, send bytes, receive bytes" { +test "listen on a port, send bytes, receive bytes, async-only" { if (!std.io.is_async) return error.SkipZigTest; if (builtin.os.tag != .linux and !builtin.os.tag.isDarwin()) { diff --git a/lib/std/priority_dequeue.zig b/lib/std/priority_dequeue.zig index db55be3804..05e3d7e58b 100644 --- a/lib/std/priority_dequeue.zig +++ b/lib/std/priority_dequeue.zig @@ -633,7 +633,7 @@ test "std.PriorityDequeue: peekMax" { try expect(queue.peekMax().? == 9); } -test "std.PriorityDequeue: sift up with odd indices" { +test "std.PriorityDequeue: sift up with odd indices, removeMin" { var queue = PDQ.init(testing.allocator, {}); defer queue.deinit(); const items = [_]u32{ 15, 7, 21, 14, 13, 22, 12, 6, 7, 25, 5, 24, 11, 16, 15, 24, 2, 1 }; @@ -647,7 +647,7 @@ test "std.PriorityDequeue: sift up with odd indices" { } } -test "std.PriorityDequeue: sift up with odd indices" { +test "std.PriorityDequeue: sift up with odd indices, removeMax" { var queue = PDQ.init(testing.allocator, {}); defer queue.deinit(); const items = [_]u32{ 15, 7, 21, 14, 13, 22, 12, 6, 7, 25, 5, 24, 11, 16, 15, 24, 2, 1 }; diff --git a/lib/std/zig/parser_test.zig b/lib/std/zig/parser_test.zig index ced57ebf5c..21785278ec 100644 --- a/lib/std/zig/parser_test.zig +++ b/lib/std/zig/parser_test.zig @@ -1240,7 +1240,7 @@ test "zig fmt: infix operator and then multiline string literal" { ); } -test "zig fmt: infix operator and then multiline string literal" { +test "zig fmt: infix operator and then multiline string literal over multiple lines" { try testCanonical( \\const x = "" ++ \\ \\ hi0 @@ -4310,7 +4310,7 @@ test "zig fmt: comptime before comptime field" { }); } -test "zig fmt: invalid else branch statement" { +test "zig fmt: invalid doc comments on comptime and test blocks" { try testError( \\/// This is a doc comment for a comptime block. \\comptime {} @@ -5191,7 +5191,7 @@ test "zig fmt: preserve container doc comment in container without trailing comm ); } -test "zig fmt: make single-line if no trailing comma" { +test "zig fmt: make single-line if no trailing comma, fmt: off" { try testCanonical( \\// Test trailing comma syntax \\// zig fmt: off @@ -5270,7 +5270,7 @@ test "zig fmt: variable initialized with ==" { , &.{.wrong_equal_var_decl}); } -test "zig fmt: missing const/var before local variable" { +test "zig fmt: missing const/var before local variable in comptime block" { try testError( \\comptime { \\ z: u32; diff --git a/src/Module.zig b/src/Module.zig index 538c716bc3..6a33990463 100644 --- a/src/Module.zig +++ b/src/Module.zig @@ -5280,6 +5280,9 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) Allocator.Err } }, }; + var must_free_decl_name = true; + defer if (must_free_decl_name) gpa.free(decl_name); + const is_exported = export_bit and decl_name_index != 0; if (kind == .@"usingnamespace") try namespace.usingnamespace_set.ensureUnusedCapacity(gpa, 1); @@ -5296,6 +5299,7 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) Allocator.Err const new_decl = mod.declPtr(new_decl_index); new_decl.kind = kind; new_decl.name = decl_name; + must_free_decl_name = false; if (kind == .@"usingnamespace") { namespace.usingnamespace_set.putAssumeCapacity(new_decl_index, is_pub); } @@ -5339,9 +5343,29 @@ fn scanDecl(iter: *ScanDeclIter, decl_sub_index: usize, flags: u4) Allocator.Err new_decl.alive = true; // This Decl corresponds to an AST node and therefore always alive. return; } - gpa.free(decl_name); const decl_index = gop.key_ptr.*; const decl = mod.declPtr(decl_index); + if (kind == .@"test") { + const src_loc = SrcLoc{ + .file_scope = decl.getFileScope(), + .parent_decl_node = decl.src_node, + .lazy = .{ .token_offset = 1 }, + }; + const msg = try ErrorMsg.create( + gpa, + src_loc, + "found test declaration with duplicate name: {s}", + .{decl_name}, + ); + errdefer msg.destroy(gpa); + try mod.failed_decls.putNoClobber(gpa, decl_index, msg); + const other_src_loc = SrcLoc{ + .file_scope = namespace.file_scope, + .parent_decl_node = decl_node, + .lazy = .{ .token_offset = 1 }, + }; + try mod.errNoteNonLazy(other_src_loc, msg, "other test here", .{}); + } log.debug("scan existing {*} ({s}) of {*}", .{ decl, decl.name, namespace }); // Update the AST node of the decl; even if its contents are unchanged, it may // have been re-ordered. diff --git a/test/behavior.zig b/test/behavior.zig index 70293bf45d..24652b6612 100644 --- a/test/behavior.zig +++ b/test/behavior.zig @@ -150,6 +150,7 @@ test { _ = @import("behavior/comptime_memory.zig"); _ = @import("behavior/const_slice_child.zig"); _ = @import("behavior/decltest.zig"); + _ = @import("behavior/duplicated_test_names.zig"); _ = @import("behavior/defer.zig"); _ = @import("behavior/empty_tuple_fields.zig"); _ = @import("behavior/empty_union.zig"); diff --git a/test/behavior/basic.zig b/test/behavior/basic.zig index 6fdd309371..8727d0dd41 100644 --- a/test/behavior/basic.zig +++ b/test/behavior/basic.zig @@ -203,7 +203,7 @@ test "multiline string comments at multiple places" { try expect(mem.eql(u8, s1, s2)); } -test "string concatenation" { +test "string concatenation simple" { try expect(mem.eql(u8, "OK" ++ " IT " ++ "WORKED", "OK IT WORKED")); } diff --git a/test/behavior/comptime_memory.zig b/test/behavior/comptime_memory.zig index 5c3012d1dc..ea7a67651c 100644 --- a/test/behavior/comptime_memory.zig +++ b/test/behavior/comptime_memory.zig @@ -45,7 +45,7 @@ test "type pun signed and unsigned as offset many pointer" { } } -test "type pun signed and unsigned as array pointer" { +test "type pun signed and unsigned as array pointer with pointer arithemtic" { if (true) { // TODO https://github.com/ziglang/zig/issues/9646 return error.SkipZigTest; diff --git a/test/behavior/duplicated_test_names.zig b/test/behavior/duplicated_test_names.zig new file mode 100644 index 0000000000..d59945ce30 --- /dev/null +++ b/test/behavior/duplicated_test_names.zig @@ -0,0 +1,17 @@ +const Namespace = struct { + test "thingy" {} +}; + +fn thingy(a: usize, b: usize) usize { + return a + b; +} + +comptime { + _ = Namespace; +} + +test "thingy" {} + +test thingy { + if (thingy(1, 2) != 3) unreachable; +} diff --git a/test/behavior/vector.zig b/test/behavior/vector.zig index 2c55af5f85..b0e717d131 100644 --- a/test/behavior/vector.zig +++ b/test/behavior/vector.zig @@ -1129,20 +1129,6 @@ test "array of vectors is copied" { try std.testing.expectEqual(points2[6], Vec3{ -345, -311, 381 }); } -test "byte vector initialized in inline function" { - const S = struct { - inline fn boolx4(e0: bool, e1: bool, e2: bool, e3: bool) @Vector(4, bool) { - return .{ e0, e1, e2, e3 }; - } - - fn all(vb: @Vector(4, bool)) bool { - return @reduce(.And, vb); - } - }; - - try expect(S.all(S.boolx4(true, true, true, true))); -} - test "byte vector initialized in inline function" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO diff --git a/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig b/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig new file mode 100644 index 0000000000..e27bbe7c1a --- /dev/null +++ b/test/cases/compile_errors/invalid_duplicate_test_decl_name.zig @@ -0,0 +1,10 @@ +test "thingy" {} +test "thingy" {} + +// error +// backend=stage2 +// target=native +// is_test=1 +// +// :1:6: error: found test declaration with duplicate name: test.thingy +// :2:6: note: other test here -- cgit v1.2.3 From 37f56a425949ffb71ec412e298ccd70748c65cc3 Mon Sep 17 00:00:00 2001 From: Brett Hill Date: Fri, 5 May 2023 16:02:22 +1000 Subject: Issue 15535. Normalize remainder in math.big.int.Managed.divTrunc --- lib/std/math/big/int.zig | 2 +- lib/std/math/big/int_test.zig | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) (limited to 'lib/std/math') diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index b01d9b04ff..686a3fdbda 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -1519,7 +1519,7 @@ pub const Mutable = struct { r.positive = r_positive; } - if (xy_trailing != 0) { + if (xy_trailing != 0 and r.limbs[r.len - 1] != 0) { // Manually shift here since we know its limb aligned. mem.copyBackwards(Limb, r.limbs[xy_trailing..], r.limbs[0..r.len]); @memset(r.limbs[0..xy_trailing], 0); diff --git a/lib/std/math/big/int_test.zig b/lib/std/math/big/int_test.zig index 25f9815f9d..0514453cf4 100644 --- a/lib/std/math/big/int_test.zig +++ b/lib/std/math/big/int_test.zig @@ -1373,6 +1373,19 @@ test "big.int div trunc single-single -/-" { try testing.expect((try r.to(i32)) == er); } +test "big.int divTrunc #15535" { + var one = try Managed.initSet(testing.allocator, 1); + defer one.deinit(); + var x = try Managed.initSet(testing.allocator, std.math.pow(u128, 2, 64)); + defer x.deinit(); + var r = try Managed.init(testing.allocator); + defer r.deinit(); + var q = try Managed.init(testing.allocator); + defer q.deinit(); + try q.divTrunc(&r, &x, &x); + try testing.expect(r.order(one) == std.math.Order.lt); +} + test "big.int divFloor #10932" { var a = try Managed.init(testing.allocator); defer a.deinit(); -- cgit v1.2.3 From 3c2841c2020e2a0630b0a0b1b97f07c75c770368 Mon Sep 17 00:00:00 2001 From: InKryption Date: Thu, 11 May 2023 02:31:20 +0200 Subject: std.math.atan: fix mistyped magic constant Co-authored-by: WiserOrb --- lib/std/math/atan.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/std/math') diff --git a/lib/std/math/atan.zig b/lib/std/math/atan.zig index 3a13d943e8..41caae11a6 100644 --- a/lib/std/math/atan.zig +++ b/lib/std/math/atan.zig @@ -161,7 +161,7 @@ fn atan64(x_: f64) f64 { var id: ?usize = undefined; // |x| < 0.4375 - if (ix < 0x3DFC0000) { + if (ix < 0x3FDC0000) { // |x| < 2^(-27) if (ix < 0x3E400000) { if (ix < 0x00100000) { -- cgit v1.2.3 From bfe02ff61a8861c269524c60668a3969cb053720 Mon Sep 17 00:00:00 2001 From: tison Date: Wed, 24 May 2023 08:01:48 +0800 Subject: make `@boolToInt` always return a u1 Signed-off-by: tison --- doc/langref.html.in | 4 ---- lib/std/math.zig | 2 +- lib/std/math/ilogb.zig | 2 +- src/Sema.zig | 6 +++--- src/translate_c.zig | 1 + test/behavior/bool.zig | 17 +++++++++++++---- 6 files changed, 19 insertions(+), 13 deletions(-) (limited to 'lib/std/math') diff --git a/doc/langref.html.in b/doc/langref.html.in index 94aa7d6fc7..14dda686a9 100644 --- a/doc/langref.html.in +++ b/doc/langref.html.in @@ -7850,10 +7850,6 @@ comptime { Converts {#syntax#}true{#endsyntax#} to {#syntax#}@as(u1, 1){#endsyntax#} and {#syntax#}false{#endsyntax#} to {#syntax#}@as(u1, 0){#endsyntax#}.

-

- If the value is known at compile-time, the return type is {#syntax#}comptime_int{#endsyntax#} - instead of {#syntax#}u1{#endsyntax#}. -

{#header_close#} {#header_open|@bitSizeOf#} diff --git a/lib/std/math.zig b/lib/std/math.zig index 02b737610c..4221118ba5 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -1684,7 +1684,7 @@ pub fn break_f80(x: f80) F80 { pub inline fn sign(i: anytype) @TypeOf(i) { const T = @TypeOf(i); return switch (@typeInfo(T)) { - .Int, .ComptimeInt => @as(T, @boolToInt(i > 0)) - @boolToInt(i < 0), + .Int, .ComptimeInt => @as(T, @boolToInt(i > 0)) - @as(T, @boolToInt(i < 0)), .Float, .ComptimeFloat => @intToFloat(T, @boolToInt(i > 0)) - @intToFloat(T, @boolToInt(i < 0)), .Vector => |vinfo| blk: { switch (@typeInfo(vinfo.child)) { diff --git a/lib/std/math/ilogb.zig b/lib/std/math/ilogb.zig index 88ae168406..c091619f3a 100644 --- a/lib/std/math/ilogb.zig +++ b/lib/std/math/ilogb.zig @@ -48,7 +48,7 @@ fn ilogbX(comptime T: type, x: T) i32 { } // offset sign bit, exponent bits, and integer bit (if present) + bias - const offset = 1 + exponentBits + @boolToInt(T == f80) - exponentBias; + const offset = 1 + exponentBits + @as(comptime_int, @boolToInt(T == f80)) - exponentBias; return offset - @intCast(i32, @clz(u)); } diff --git a/src/Sema.zig b/src/Sema.zig index 138c19acf4..9178392d27 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -18445,9 +18445,9 @@ fn zirBoolToInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A const inst_data = sema.code.instructions.items(.data)[inst].un_node; const operand = try sema.resolveInst(inst_data.operand); if (try sema.resolveMaybeUndefVal(operand)) |val| { - if (val.isUndef()) return sema.addConstUndef(Type.initTag(.u1)); - const bool_ints = [2]Air.Inst.Ref{ .zero, .one }; - return bool_ints[@boolToInt(val.toBool())]; + if (val.isUndef()) return sema.addConstUndef(Type.u1); + if (val.toBool()) return sema.addConstant(Type.u1, Value.one); + return sema.addConstant(Type.u1, Value.zero); } return block.addUnOp(.bool_to_int, operand); } diff --git a/src/translate_c.zig b/src/translate_c.zig index bc7a1138da..becb2779b2 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -2494,6 +2494,7 @@ fn transCCast( if (isBoolRes(src_int_expr)) { src_int_expr = try Tag.bool_to_int.create(c.arena, src_int_expr); + return Tag.as.create(c.arena, .{ .lhs = dst_node, .rhs = src_int_expr }); } switch (cIntTypeCmp(dst_type, src_type)) { diff --git a/test/behavior/bool.zig b/test/behavior/bool.zig index d216d72a05..8cfd87bf21 100644 --- a/test/behavior/bool.zig +++ b/test/behavior/bool.zig @@ -1,6 +1,7 @@ const std = @import("std"); const builtin = @import("builtin"); const expect = std.testing.expect; +const expectEqual = std.testing.expectEqual; test "bool literals" { try expect(true); @@ -12,14 +13,22 @@ test "cast bool to int" { const t = true; const f = false; - try expect(@boolToInt(t) == @as(u32, 1)); - try expect(@boolToInt(f) == @as(u32, 0)); + try expectEqual(@as(u32, 1), @boolToInt(t)); + try expectEqual(@as(u32, 0), @boolToInt(f)); + try expectEqual(-1, @bitCast(i1, @boolToInt(t))); + try expectEqual(0, @bitCast(i1, @boolToInt(f))); + try expectEqual(u1, @TypeOf(@boolToInt(t))); + try expectEqual(u1, @TypeOf(@boolToInt(f))); try nonConstCastBoolToInt(t, f); } fn nonConstCastBoolToInt(t: bool, f: bool) !void { - try expect(@boolToInt(t) == @as(u32, 1)); - try expect(@boolToInt(f) == @as(u32, 0)); + try expectEqual(@as(u32, 1), @boolToInt(t)); + try expectEqual(@as(u32, 0), @boolToInt(f)); + try expectEqual(@as(i1, -1), @bitCast(i1, @boolToInt(t))); + try expectEqual(@as(i1, 0), @bitCast(i1, @boolToInt(f))); + try expectEqual(u1, @TypeOf(@boolToInt(t))); + try expectEqual(u1, @TypeOf(@boolToInt(f))); } test "bool cmp" { -- cgit v1.2.3 From 4422af8be96d243db7840b840737069c38be8afb Mon Sep 17 00:00:00 2001 From: Mizuochi Keita Date: Wed, 24 May 2023 23:54:51 +0900 Subject: std.math.big.int: Add Sqrt Implemented with reference to Modern Computer Arithmetic, Algorithm 1.13. https://members.loria.fr/PZimmermann/mca/pub226.html The below optimization ideas are derived from Go's big package. * Minimize initial loop value * Reuse loop values math/big/int.go: https://cs.opensource.google/go/go/+/refs/tags/go1.20.4:src/math/big/int.go;l=1286 --- lib/std/math/big/int.zig | 78 +++++++++++++++++++++++++++++++++++++++++++ lib/std/math/big/int_test.zig | 30 +++++++++++++++++ 2 files changed, 108 insertions(+) (limited to 'lib/std/math') diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index 2fa0eef922..1f5bf123d6 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -66,6 +66,13 @@ pub fn calcPowLimbsBufferLen(a_bit_count: usize, y: usize) usize { return 2 + (a_bit_count * y + (limb_bits - 1)) / limb_bits; } +pub fn calcSqrtLimbsBufferLen(a_bit_count: usize) usize { + const a_limb_count = (a_bit_count - 1) / limb_bits + 1; + const shift = (a_bit_count + 1) / 2; + const u_s_rem_limb_count = 1 + ((shift - 1) / limb_bits + 1); + return a_limb_count + 3 * u_s_rem_limb_count + calcDivLimbsBufferLen(a_limb_count, u_s_rem_limb_count); +} + // Compute the number of limbs required to store a 2s-complement number of `bit_count` bits. pub fn calcTwosCompLimbCount(bit_count: usize) usize { return std.math.divCeil(usize, bit_count, @bitSizeOf(Limb)) catch unreachable; @@ -1344,6 +1351,64 @@ pub const Mutable = struct { r.positive = a.positive or (b & 1) == 0; } + /// r = ⌊√a⌋ + /// + /// r may alias a. + /// + /// Asserts that `r` has enough limbs to store the result. Upper bound is + /// `(a.limbs.len - 1) / 2 + 1`. + /// + /// `limbs_buffer` is used for temporary storage. + /// The amount required is given by `calcSqrtLimbsBufferLen`. + pub fn sqrt( + r: *Mutable, + a: Const, + limbs_buffer: []Limb, + ) void { + // Brent and Zimmermann, Modern Computer Arithmetic, Algorithm 1.13 SqrtInt + // https://members.loria.fr/PZimmermann/mca/pub226.html + var buf_index: usize = 0; + var t = b: { + const start = buf_index; + buf_index += a.limbs.len; + break :b Mutable.init(limbs_buffer[start..buf_index], 0); + }; + var u = b: { + const start = buf_index; + const shift = (a.bitCountAbs() + 1) / 2; + buf_index += 1 + ((shift - 1) / limb_bits + 1); + var m = Mutable.init(limbs_buffer[start..buf_index], 1); + m.shiftLeft(m.toConst(), shift); // u must be >= ⌊√a⌋, and should be as small as possible for efficiency + break :b m; + }; + var s = b: { + const start = buf_index; + buf_index += u.limbs.len; + break :b u.toConst().toMutable(limbs_buffer[start..buf_index]); + }; + var rem = b: { + const start = buf_index; + buf_index += s.limbs.len; + break :b Mutable.init(limbs_buffer[start..buf_index], 0); + }; + + while (true) { + t.divFloor(&rem, a, s.toConst(), limbs_buffer[buf_index..]); + t.add(t.toConst(), s.toConst()); + u.shiftRight(t.toConst(), 1); + + if (u.toConst().order(s.toConst()).compare(.gte)) { + r.copy(s.toConst()); + return; + } + + // Avoid copying u to s by swapping u and s + var tmp_s = s; + s = u; + u = tmp_s; + } + } + /// rma may not alias x or y. /// x and y may alias each other. /// Asserts that `rma` has enough limbs to store the result. Upper bound is given by `calcGcdNoAliasLimbLen`. @@ -3140,6 +3205,19 @@ pub const Managed = struct { } } + /// r = ⌊√a⌋ + pub fn sqrt(rma: *Managed, a: *const Managed) !void { + const needed_limbs = calcSqrtLimbsBufferLen(a.bitCountAbs()); + + const limbs_buffer = try rma.allocator.alloc(Limb, needed_limbs); + defer rma.allocator.free(limbs_buffer); + + try rma.ensureCapacity((a.len() - 1) / 2 + 1); + var m = rma.toMutable(); + m.sqrt(a.toConst(), limbs_buffer); + rma.setMetadata(m.positive, m.len); + } + /// r = truncate(Int(signedness, bit_count), a) pub fn truncate(r: *Managed, a: *const Managed, signedness: Signedness, bit_count: usize) !void { try r.ensureCapacity(calcTwosCompLimbCount(bit_count)); diff --git a/lib/std/math/big/int_test.zig b/lib/std/math/big/int_test.zig index 0514453cf4..9c3c1b6881 100644 --- a/lib/std/math/big/int_test.zig +++ b/lib/std/math/big/int_test.zig @@ -2622,6 +2622,36 @@ test "big.int pow" { } } +test "big.int sqrt" { + var r = try Managed.init(testing.allocator); + defer r.deinit(); + var a = try Managed.init(testing.allocator); + defer a.deinit(); + + // not aliased + try r.set(0); + try a.set(25); + try r.sqrt(&a); + try testing.expectEqual(@as(i32, 5), try r.to(i32)); + + // aliased + try a.set(25); + try a.sqrt(&a); + try testing.expectEqual(@as(i32, 5), try a.to(i32)); + + // bottom + try r.set(0); + try a.set(24); + try r.sqrt(&a); + try testing.expectEqual(@as(i32, 4), try r.to(i32)); + + // large number + try r.set(0); + try a.set(0x1_0000_0000_0000); + try r.sqrt(&a); + try testing.expectEqual(@as(i32, 0x100_0000), try r.to(i32)); +} + test "big.int regression test for 1 limb overflow with alias" { // Note these happen to be two consecutive Fibonacci sequence numbers, the // first two whose sum exceeds 2**64. -- cgit v1.2.3 From ec58b475b7ee913ff7ad0bf59bb2c71f0705e76e Mon Sep 17 00:00:00 2001 From: Mizuochi Keita Date: Fri, 26 May 2023 15:55:21 +0900 Subject: std.math.big.int: Fix typo - `bytes` -> `buffer` - Correct naming consistency between 1. fn argument and doc comment of `(read|write)PackedTwosComplement` 2. fn arguments of `(read|write)PackedTwosComplement` and `(read|write)TwosComplement` --- lib/std/math/big/int.zig | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) (limited to 'lib/std/math') diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index 1f5bf123d6..fdee6b6190 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -1890,7 +1890,7 @@ pub const Mutable = struct { /// if it were a field in packed memory at the provided bit offset. pub fn readPackedTwosComplement( x: *Mutable, - bytes: []const u8, + buffer: []const u8, bit_offset: usize, bit_count: usize, endian: Endian, @@ -1909,11 +1909,11 @@ pub const Mutable = struct { const total_bits = bit_offset + bit_count; var last_byte = switch (endian) { .Little => ((total_bits + 7) / 8) - 1, - .Big => bytes.len - ((total_bits + 7) / 8), + .Big => buffer.len - ((total_bits + 7) / 8), }; const sign_bit = @as(u8, 1) << @intCast(u3, (total_bits - 1) % 8); - positive = ((bytes[last_byte] & sign_bit) == 0); + positive = ((buffer[last_byte] & sign_bit) == 0); } // Copy all complete limbs @@ -1922,7 +1922,7 @@ pub const Mutable = struct { var bit_index: usize = 0; while (limb_index < bit_count / @bitSizeOf(Limb)) : (limb_index += 1) { // Read one Limb of bits - var limb = mem.readPackedInt(Limb, bytes, bit_index + bit_offset, endian); + var limb = mem.readPackedInt(Limb, buffer, bit_index + bit_offset, endian); bit_index += @bitSizeOf(Limb); // 2's complement (bitwise not, then add carry bit) @@ -1938,10 +1938,10 @@ pub const Mutable = struct { if (bit_count != bit_index) { // Read all remaining bits var limb = switch (signedness) { - .unsigned => mem.readVarPackedInt(Limb, bytes, bit_index + bit_offset, bit_count - bit_index, endian, .unsigned), + .unsigned => mem.readVarPackedInt(Limb, buffer, bit_index + bit_offset, bit_count - bit_index, endian, .unsigned), .signed => b: { const SLimb = std.meta.Int(.signed, @bitSizeOf(Limb)); - const limb = mem.readVarPackedInt(SLimb, bytes, bit_index + bit_offset, bit_count - bit_index, endian, .signed); + const limb = mem.readVarPackedInt(SLimb, buffer, bit_index + bit_offset, bit_count - bit_index, endian, .signed); break :b @bitCast(Limb, limb); }, }; @@ -2383,7 +2383,7 @@ pub const Const = struct { /// /// This is equivalent to storing the value of an integer with `bit_count` bits as /// if it were a field in packed memory at the provided bit offset. - pub fn writePackedTwosComplement(x: Const, bytes: []u8, bit_offset: usize, bit_count: usize, endian: Endian) void { + pub fn writePackedTwosComplement(x: Const, buffer: []u8, bit_offset: usize, bit_count: usize, endian: Endian) void { assert(x.fitsInTwosComp(if (x.positive) .unsigned else .signed, bit_count)); // Copy all complete limbs @@ -2401,7 +2401,7 @@ pub const Const = struct { } // Write one Limb of bits - mem.writePackedInt(Limb, bytes, bit_index + bit_offset, limb, endian); + mem.writePackedInt(Limb, buffer, bit_index + bit_offset, limb, endian); bit_index += @bitSizeOf(Limb); } @@ -2413,7 +2413,7 @@ pub const Const = struct { if (!x.positive) limb = ~limb +% carry; // Write all remaining bits - mem.writeVarPackedInt(bytes, bit_index + bit_offset, bit_count - bit_index, limb, endian); + mem.writeVarPackedInt(buffer, bit_index + bit_offset, bit_count - bit_index, limb, endian); } } -- cgit v1.2.3 From 6c2f3745564aefa669b336e249888bb7390b3a3f Mon Sep 17 00:00:00 2001 From: Evin Yulo Date: Sat, 20 May 2023 20:58:28 -0400 Subject: Use the word 'base' consistently instead of 'radix' --- lib/std/fmt.zig | 98 ++++++++++++++++++------------------- lib/std/fmt/parse_float/decimal.zig | 4 +- lib/std/math/big/int.zig | 16 +++--- lib/std/math/scalbn.zig | 4 +- lib/std/zig/c_translation.zig | 13 +++-- src/main.zig | 8 +-- src/translate_c.zig | 10 ++-- src/translate_c/ast.zig | 6 +-- 8 files changed, 81 insertions(+), 78 deletions(-) (limited to 'lib/std/math') diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index be6ebf20ac..92e15f06ba 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -748,7 +748,7 @@ pub fn formatIntValue( options: FormatOptions, writer: anytype, ) !void { - comptime var radix = 10; + comptime var base = 10; comptime var case: Case = .lower; const int_value = if (@TypeOf(value) == comptime_int) blk: { @@ -757,7 +757,7 @@ pub fn formatIntValue( } else value; if (fmt.len == 0 or comptime std.mem.eql(u8, fmt, "d")) { - radix = 10; + base = 10; case = .lower; } else if (comptime std.mem.eql(u8, fmt, "c")) { if (@typeInfo(@TypeOf(int_value)).Int.bits <= 8) { @@ -772,22 +772,22 @@ pub fn formatIntValue( @compileError("cannot print integer that is larger than 21 bits as an UTF-8 sequence"); } } else if (comptime std.mem.eql(u8, fmt, "b")) { - radix = 2; + base = 2; case = .lower; } else if (comptime std.mem.eql(u8, fmt, "x")) { - radix = 16; + base = 16; case = .lower; } else if (comptime std.mem.eql(u8, fmt, "X")) { - radix = 16; + base = 16; case = .upper; } else if (comptime std.mem.eql(u8, fmt, "o")) { - radix = 8; + base = 8; case = .lower; } else { invalidFmtError(fmt, value); } - return formatInt(int_value, radix, case, options, writer); + return formatInt(int_value, base, case, options, writer); } fn formatFloatValue( @@ -906,7 +906,7 @@ pub fn fmtSliceEscapeUpper(bytes: []const u8) std.fmt.Formatter(formatSliceEscap return .{ .data = bytes }; } -fn formatSizeImpl(comptime radix: comptime_int) type { +fn formatSizeImpl(comptime base: comptime_int) type { return struct { fn formatSizeImpl( value: u64, @@ -926,13 +926,13 @@ fn formatSizeImpl(comptime radix: comptime_int) type { const mags_iec = " KMGTPEZY"; const log2 = math.log2(value); - const magnitude = switch (radix) { + const magnitude = switch (base) { 1000 => math.min(log2 / comptime math.log2(1000), mags_si.len - 1), 1024 => math.min(log2 / 10, mags_iec.len - 1), else => unreachable, }; - const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, radix), lossyCast(f64, magnitude)); - const suffix = switch (radix) { + const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, base), lossyCast(f64, magnitude)); + const suffix = switch (base) { 1000 => mags_si[magnitude], 1024 => mags_iec[magnitude], else => unreachable, @@ -944,7 +944,7 @@ fn formatSizeImpl(comptime radix: comptime_int) type { bufstream.writer().writeAll(if (suffix == ' ') "B" - else switch (radix) { + else switch (base) { 1000 => &[_]u8{ suffix, 'B' }, 1024 => &[_]u8{ suffix, 'i', 'B' }, else => unreachable, @@ -1730,21 +1730,21 @@ pub fn Formatter(comptime format_fn: anytype) type { } /// Parses the string `buf` as signed or unsigned representation in the -/// specified radix of an integral value of type `T`. +/// specified base of an integral value of type `T`. /// -/// When `radix` is zero the string prefix is examined to detect the true radix: -/// * A prefix of "0b" implies radix=2, -/// * A prefix of "0o" implies radix=8, -/// * A prefix of "0x" implies radix=16, -/// * Otherwise radix=10 is assumed. +/// When `base` is zero the string prefix is examined to detect the true base: +/// * A prefix of "0b" implies base=2, +/// * A prefix of "0o" implies base=8, +/// * A prefix of "0x" implies base=16, +/// * Otherwise base=10 is assumed. /// /// Ignores '_' character in `buf`. /// See also `parseUnsigned`. -pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) ParseIntError!T { +pub fn parseInt(comptime T: type, buf: []const u8, base: u8) ParseIntError!T { if (buf.len == 0) return error.InvalidCharacter; - if (buf[0] == '+') return parseWithSign(T, buf[1..], radix, .pos); - if (buf[0] == '-') return parseWithSign(T, buf[1..], radix, .neg); - return parseWithSign(T, buf, radix, .pos); + if (buf[0] == '+') return parseWithSign(T, buf[1..], base, .pos); + if (buf[0] == '-') return parseWithSign(T, buf[1..], base, .neg); + return parseWithSign(T, buf, base, .pos); } test "parseInt" { @@ -1777,7 +1777,7 @@ test "parseInt" { try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "-", 10)); try std.testing.expectError(error.InvalidCharacter, parseInt(i32, "-", 10)); - // autodectect the radix + // autodectect the base try std.testing.expect((try parseInt(i32, "111", 0)) == 111); try std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111); try std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111); @@ -1804,29 +1804,29 @@ test "parseInt" { fn parseWithSign( comptime T: type, buf: []const u8, - radix: u8, + base: u8, comptime sign: enum { pos, neg }, ) ParseIntError!T { if (buf.len == 0) return error.InvalidCharacter; - var buf_radix = radix; + var buf_base = base; var buf_start = buf; - if (radix == 0) { + if (base == 0) { // Treat is as a decimal number by default. - buf_radix = 10; - // Detect the radix by looking at buf prefix. + buf_base = 10; + // Detect the base by looking at buf prefix. if (buf.len > 2 and buf[0] == '0') { switch (std.ascii.toLower(buf[1])) { 'b' => { - buf_radix = 2; + buf_base = 2; buf_start = buf[2..]; }, 'o' => { - buf_radix = 8; + buf_base = 8; buf_start = buf[2..]; }, 'x' => { - buf_radix = 16; + buf_base = 16; buf_start = buf[2..]; }, else => {}, @@ -1845,28 +1845,28 @@ fn parseWithSign( for (buf_start) |c| { if (c == '_') continue; - const digit = try charToDigit(c, buf_radix); + const digit = try charToDigit(c, buf_base); - if (x != 0) x = try math.mul(T, x, math.cast(T, buf_radix) orelse return error.Overflow); + if (x != 0) x = try math.mul(T, x, math.cast(T, buf_base) orelse return error.Overflow); x = try add(T, x, math.cast(T, digit) orelse return error.Overflow); } return x; } -/// Parses the string `buf` as unsigned representation in the specified radix +/// Parses the string `buf` as unsigned representation in the specified base /// of an integral value of type `T`. /// -/// When `radix` is zero the string prefix is examined to detect the true radix: -/// * A prefix of "0b" implies radix=2, -/// * A prefix of "0o" implies radix=8, -/// * A prefix of "0x" implies radix=16, -/// * Otherwise radix=10 is assumed. +/// When `base` is zero the string prefix is examined to detect the true base: +/// * A prefix of "0b" implies base=2, +/// * A prefix of "0o" implies base=8, +/// * A prefix of "0x" implies base=16, +/// * Otherwise base=10 is assumed. /// /// Ignores '_' character in `buf`. /// See also `parseInt`. -pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseIntError!T { - return parseWithSign(T, buf, radix, .pos); +pub fn parseUnsigned(comptime T: type, buf: []const u8, base: u8) ParseIntError!T { + return parseWithSign(T, buf, base, .pos); } test "parseUnsigned" { @@ -1889,7 +1889,7 @@ test "parseUnsigned" { try std.testing.expect((try parseUnsigned(u32, "NUMBER", 36)) == 1442151747); - // these numbers should fit even though the radix itself doesn't fit in the destination type + // these numbers should fit even though the base itself doesn't fit in the destination type try std.testing.expect((try parseUnsigned(u1, "0", 10)) == 0); try std.testing.expect((try parseUnsigned(u1, "1", 10)) == 1); try std.testing.expectError(error.Overflow, parseUnsigned(u1, "2", 10)); @@ -1906,14 +1906,14 @@ test "parseUnsigned" { } /// Parses a number like '2G', '2Gi', or '2GiB'. -pub fn parseIntSizeSuffix(buf: []const u8, radix: u8) ParseIntError!usize { +pub fn parseIntSizeSuffix(buf: []const u8, digit_base: u8) ParseIntError!usize { var without_B = buf; if (mem.endsWith(u8, buf, "B")) without_B.len -= 1; var without_i = without_B; - var base: usize = 1000; + var magnitude_base: usize = 1000; if (mem.endsWith(u8, without_B, "i")) { without_i.len -= 1; - base = 1024; + magnitude_base = 1024; } if (without_i.len == 0) return error.InvalidCharacter; const orders_of_magnitude: usize = switch (without_i[without_i.len - 1]) { @@ -1935,11 +1935,11 @@ pub fn parseIntSizeSuffix(buf: []const u8, radix: u8) ParseIntError!usize { } else if (without_i.len != without_B.len) { return error.InvalidCharacter; } - const multiplier = math.powi(usize, base, orders_of_magnitude) catch |err| switch (err) { + const multiplier = math.powi(usize, magnitude_base, orders_of_magnitude) catch |err| switch (err) { error.Underflow => unreachable, error.Overflow => return error.Overflow, }; - const number = try std.fmt.parseInt(usize, without_suffix, radix); + const number = try std.fmt.parseInt(usize, without_suffix, digit_base); return math.mul(usize, number, multiplier); } @@ -1962,7 +1962,7 @@ test { _ = &parseFloat; } -pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { +pub fn charToDigit(c: u8, base: u8) (error{InvalidCharacter}!u8) { const value = switch (c) { '0'...'9' => c - '0', 'A'...'Z' => c - 'A' + 10, @@ -1970,7 +1970,7 @@ pub fn charToDigit(c: u8, radix: u8) (error{InvalidCharacter}!u8) { else => return error.InvalidCharacter, }; - if (value >= radix) return error.InvalidCharacter; + if (value >= base) return error.InvalidCharacter; return value; } diff --git a/lib/std/fmt/parse_float/decimal.zig b/lib/std/fmt/parse_float/decimal.zig index 9dbe7095ac..5bb5fa8d5e 100644 --- a/lib/std/fmt/parse_float/decimal.zig +++ b/lib/std/fmt/parse_float/decimal.zig @@ -34,13 +34,13 @@ pub fn Decimal(comptime T: type) type { /// For a double-precision IEEE-754 float, this required 767 digits, /// so we store the max digits + 1. /// - /// We can exactly represent a float in radix `b` from radix 2 if + /// We can exactly represent a float in base `b` from base 2 if /// `b` is divisible by 2. This function calculates the exact number of /// digits required to exactly represent that float. /// /// According to the "Handbook of Floating Point Arithmetic", /// for IEEE754, with emin being the min exponent, p2 being the - /// precision, and b being the radix, the number of digits follows as: + /// precision, and b being the base, the number of digits follows as: /// /// `−emin + p2 + ⌊(emin + 1) log(2, b) − log(1 − 2^(−p2), b)⌋` /// diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index fdee6b6190..c4d3ccf077 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -1627,7 +1627,7 @@ pub const Mutable = struct { // while x >= y * b^(n - t): // x -= y * b^(n - t) // q[n - t] += 1 - // Note, this algorithm is performed only once if y[t] > radix/2 and y is even, which we + // Note, this algorithm is performed only once if y[t] > base/2 and y is even, which we // enforced in step 0. This means we can replace the while with an if. // Note, multiplication by b^(n - t) comes down to shifting to the right by n - t limbs. // We can also replace x >= y * b^(n - t) by x/b^(n - t) >= y, and use shifts for that. @@ -2206,20 +2206,20 @@ pub const Const = struct { out_stream: anytype, ) !void { _ = options; - comptime var radix = 10; + comptime var base = 10; comptime var case: std.fmt.Case = .lower; if (fmt.len == 0 or comptime mem.eql(u8, fmt, "d")) { - radix = 10; + base = 10; case = .lower; } else if (comptime mem.eql(u8, fmt, "b")) { - radix = 2; + base = 2; case = .lower; } else if (comptime mem.eql(u8, fmt, "x")) { - radix = 16; + base = 16; case = .lower; } else if (comptime mem.eql(u8, fmt, "X")) { - radix = 16; + base = 16; case = .upper; } else { std.fmt.invalidFmtError(fmt, self); @@ -2237,8 +2237,8 @@ pub const Const = struct { .limbs = &([1]Limb{comptime math.maxInt(Limb)} ** available_len), .positive = false, }; - var buf: [biggest.sizeInBaseUpperBound(radix)]u8 = undefined; - const len = self.toString(&buf, radix, case, &limbs); + var buf: [biggest.sizeInBaseUpperBound(base)]u8 = undefined; + const len = self.toString(&buf, base, case, &limbs); return out_stream.writeAll(buf[0..len]); } diff --git a/lib/std/math/scalbn.zig b/lib/std/math/scalbn.zig index 294ee4abf0..2c8c3733fa 100644 --- a/lib/std/math/scalbn.zig +++ b/lib/std/math/scalbn.zig @@ -3,11 +3,11 @@ const expect = std.testing.expect; /// Returns a * FLT_RADIX ^ exp. /// -/// Zig only supports binary radix IEEE-754 floats. Hence FLT_RADIX=2, and this is an alias for ldexp. +/// Zig only supports binary base IEEE-754 floats. Hence FLT_RADIX=2, and this is an alias for ldexp. pub const scalbn = @import("ldexp.zig").ldexp; test "math.scalbn" { - // Verify we are using radix 2. + // Verify we are using base 2. try expect(scalbn(@as(f16, 1.5), 4) == 24.0); try expect(scalbn(@as(f32, 1.5), 4) == 24.0); try expect(scalbn(@as(f64, 1.5), 4) == 24.0); diff --git a/lib/std/zig/c_translation.zig b/lib/std/zig/c_translation.zig index 6e95ab53ab..1273527358 100644 --- a/lib/std/zig/c_translation.zig +++ b/lib/std/zig/c_translation.zig @@ -262,16 +262,19 @@ test "sizeof" { try testing.expect(sizeof(anyopaque) == 1); } -pub const CIntLiteralRadix = enum { decimal, octal, hexadecimal }; +pub const CIntLiteralBase = enum { decimal, octal, hexadecimal }; -fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime radix: CIntLiteralRadix) type { +/// Deprecated: use `CIntLiteralBase` +pub const CIntLiteralRadix = CIntLiteralBase; + +fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: comptime_int, comptime base: CIntLiteralBase) type { const signed_decimal = [_]type{ c_int, c_long, c_longlong, c_ulonglong }; const signed_oct_hex = [_]type{ c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong }; const unsigned = [_]type{ c_uint, c_ulong, c_ulonglong }; const list: []const type = if (@typeInfo(SuffixType).Int.signedness == .unsigned) &unsigned - else if (radix == .decimal) + else if (base == .decimal) &signed_decimal else &signed_oct_hex; @@ -290,8 +293,8 @@ fn PromoteIntLiteralReturnType(comptime SuffixType: type, comptime number: compt pub fn promoteIntLiteral( comptime SuffixType: type, comptime number: comptime_int, - comptime radix: CIntLiteralRadix, -) PromoteIntLiteralReturnType(SuffixType, number, radix) { + comptime base: CIntLiteralBase, +) PromoteIntLiteralReturnType(SuffixType, number, base) { return number; } diff --git a/src/main.zig b/src/main.zig index b4778c1b00..bc40dbc431 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5786,12 +5786,12 @@ pub fn cmdChangelist( try bw.flush(); } -fn eatIntPrefix(arg: []const u8, radix: u8) []const u8 { +fn eatIntPrefix(arg: []const u8, base: u8) []const u8 { if (arg.len > 2 and arg[0] == '0') { switch (std.ascii.toLower(arg[1])) { - 'b' => if (radix == 2) return arg[2..], - 'o' => if (radix == 8) return arg[2..], - 'x' => if (radix == 16) return arg[2..], + 'b' => if (base == 2) return arg[2..], + 'o' => if (base == 8) return arg[2..], + 'x' => if (base == 16) return arg[2..], else => {}, } } diff --git a/src/translate_c.zig b/src/translate_c.zig index becb2779b2..8cc2d1856c 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -5735,21 +5735,21 @@ fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!Node { switch (m.list[m.i].id) { .IntegerLiteral => |suffix| { - var radix: []const u8 = "decimal"; + var base: []const u8 = "decimal"; if (lit_bytes.len >= 2 and lit_bytes[0] == '0') { switch (lit_bytes[1]) { '0'...'7' => { // Octal lit_bytes = try std.fmt.allocPrint(c.arena, "0o{s}", .{lit_bytes[1..]}); - radix = "octal"; + base = "octal"; }, 'X' => { // Hexadecimal with capital X, valid in C but not in Zig lit_bytes = try std.fmt.allocPrint(c.arena, "0x{s}", .{lit_bytes[2..]}); - radix = "hexadecimal"; + base = "hexadecimal"; }, 'x' => { - radix = "hexadecimal"; + base = "hexadecimal"; }, else => {}, } @@ -5794,7 +5794,7 @@ fn parseCNumLit(c: *Context, m: *MacroCtx) ParseError!Node { return Tag.helpers_promoteIntLiteral.create(c.arena, .{ .type = type_node, .value = literal_node, - .radix = try Tag.enum_literal.create(c.arena, radix), + .base = try Tag.enum_literal.create(c.arena, base), }); } }, diff --git a/src/translate_c/ast.zig b/src/translate_c/ast.zig index 328feb989a..6c6bbf28bd 100644 --- a/src/translate_c/ast.zig +++ b/src/translate_c/ast.zig @@ -120,7 +120,7 @@ pub const Node = extern union { std_math_Log2Int, /// @intCast(lhs, rhs) int_cast, - /// @import("std").zig.c_translation.promoteIntLiteral(value, type, radix) + /// @import("std").zig.c_translation.promoteIntLiteral(value, type, base) helpers_promoteIntLiteral, /// @import("std").meta.alignment(value) std_meta_alignment, @@ -699,7 +699,7 @@ pub const Payload = struct { data: struct { value: Node, type: Node, - radix: Node, + base: Node, }, }; @@ -898,7 +898,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex { .helpers_promoteIntLiteral => { const payload = node.castTag(.helpers_promoteIntLiteral).?.data; const import_node = try renderStdImport(c, &.{ "zig", "c_translation", "promoteIntLiteral" }); - return renderCall(c, import_node, &.{ payload.type, payload.value, payload.radix }); + return renderCall(c, import_node, &.{ payload.type, payload.value, payload.base }); }, .std_meta_alignment => { const payload = node.castTag(.std_meta_alignment).?.data; -- cgit v1.2.3 From a803e9cf48e9566638e6ec1e23fe0b885e2651ee Mon Sep 17 00:00:00 2001 From: Jacob Young Date: Mon, 29 May 2023 21:47:34 -0400 Subject: Sema: fix vector comparison and interning of -0 --- lib/std/math/big/int.zig | 3 +++ src/Sema.zig | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) (limited to 'lib/std/math') diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index c4d3ccf077..13ead1c421 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -2158,6 +2158,9 @@ pub const Const = struct { pub fn to(self: Const, comptime T: type) ConvertError!T { switch (@typeInfo(T)) { .Int => |info| { + // Make sure -0 is handled correctly. + if (self.eqZero()) return 0; + const UT = std.meta.Int(.unsigned, info.bits); if (!self.fitsInTwosComp(info.signedness, info.bits)) { diff --git a/src/Sema.zig b/src/Sema.zig index 452efc8583..d25b022254 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -34538,10 +34538,13 @@ fn compareScalar( rhs: Value, ty: Type, ) CompileError!bool { + const mod = sema.mod; + const coerced_lhs = try mod.getCoerced(lhs, ty); + const coerced_rhs = try mod.getCoerced(rhs, ty); switch (op) { - .eq => return sema.valuesEqual(lhs, rhs, ty), - .neq => return !(try sema.valuesEqual(lhs, rhs, ty)), - else => return Value.compareHeteroAdvanced(lhs, op, rhs, sema.mod, sema), + .eq => return sema.valuesEqual(coerced_lhs, coerced_rhs, ty), + .neq => return !(try sema.valuesEqual(coerced_lhs, coerced_rhs, ty)), + else => return Value.compareHeteroAdvanced(coerced_lhs, op, coerced_rhs, mod, sema), } } -- cgit v1.2.3 From 26fac15f485e89dc7106256e1aa79184c1761efd Mon Sep 17 00:00:00 2001 From: Jacob Young Date: Wed, 31 May 2023 00:42:24 -0400 Subject: math.big.int: fix ctz of zero --- lib/std/math/big/int.zig | 4 ++-- src/value.zig | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/std/math') diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index 13ead1c421..ec79d843da 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -2512,7 +2512,7 @@ pub const Const = struct { return total_limb_lz + bits - total_limb_bits; } - pub fn ctz(a: Const) Limb { + pub fn ctz(a: Const, bits: Limb) Limb { // Limbs are stored in little-endian order. var result: Limb = 0; for (a.limbs) |limb| { @@ -2520,7 +2520,7 @@ pub const Const = struct { result += limb_tz; if (limb_tz != @sizeOf(Limb) * 8) break; } - return result; + return @min(result, bits); } }; diff --git a/src/value.zig b/src/value.zig index 89ba1fba67..62a83c7901 100644 --- a/src/value.zig +++ b/src/value.zig @@ -1216,10 +1216,10 @@ pub const Value = struct { return bigint.clz(ty.intInfo(mod).bits); } - pub fn ctz(val: Value, _: Type, mod: *Module) u64 { + pub fn ctz(val: Value, ty: Type, mod: *Module) u64 { var bigint_buf: BigIntSpace = undefined; const bigint = val.toBigInt(&bigint_buf, mod); - return bigint.ctz(); + return bigint.ctz(ty.intInfo(mod).bits); } pub fn popCount(val: Value, ty: Type, mod: *Module) u64 { -- cgit v1.2.3 From 259315606827620daaabf82b479e59ee710097cd Mon Sep 17 00:00:00 2001 From: r00ster91 Date: Fri, 2 Jun 2023 22:02:45 -0400 Subject: migration: std.math.{min, min3, max, max3} -> `@min` & `@max` --- doc/docgen.zig | 2 +- lib/compiler_rt/divc3.zig | 3 +- lib/compiler_rt/emutls.zig | 4 +- lib/std/Build/Cache/DepTokenizer.zig | 2 +- lib/std/Thread.zig | 6 +- lib/std/Uri.zig | 4 +- lib/std/array_hash_map.zig | 6 +- lib/std/ascii.zig | 2 +- lib/std/compress/lzma/decode.zig | 2 +- lib/std/crypto/blake3.zig | 8 +-- lib/std/crypto/ff.zig | 2 +- lib/std/crypto/ghash_polyval.zig | 2 +- lib/std/crypto/keccak_p.zig | 4 +- lib/std/crypto/poly1305.zig | 2 +- lib/std/crypto/salsa20.zig | 2 +- lib/std/crypto/scrypt.zig | 4 +- lib/std/crypto/sha3.zig | 2 +- lib/std/crypto/siphash.zig | 2 +- lib/std/debug.zig | 4 +- lib/std/dynamic_library.zig | 3 +- lib/std/event/loop.zig | 2 +- lib/std/fifo.zig | 2 +- lib/std/fmt.zig | 18 +++--- lib/std/hash/wyhash.zig | 2 +- lib/std/hash_map.zig | 6 +- lib/std/heap/arena_allocator.zig | 2 +- lib/std/heap/memory_pool.zig | 4 +- lib/std/http/protocol.zig | 2 +- lib/std/io/fixed_buffer_stream.zig | 4 +- lib/std/io/limited_reader.zig | 2 +- lib/std/io/reader.zig | 2 +- lib/std/io/writer.zig | 2 +- lib/std/math.zig | 103 +++----------------------------- lib/std/math/big/int.zig | 96 ++++++++++++++--------------- lib/std/math/ldexp.zig | 2 +- lib/std/mem.zig | 12 ++-- lib/std/net.zig | 8 +-- lib/std/os/linux.zig | 4 +- lib/std/os/linux/io_uring.zig | 4 +- lib/std/os/windows.zig | 4 +- lib/std/pdb.zig | 2 +- lib/std/rand.zig | 2 +- lib/std/sort/block.zig | 10 ++-- lib/std/zig/render.zig | 4 +- lib/std/zig/system/NativeTargetInfo.zig | 6 +- src/Sema.zig | 10 ++-- src/TypedValue.zig | 10 ++-- src/arch/x86_64/CodeGen.zig | 4 +- src/link/Elf.zig | 2 +- src/link/MachO/CodeSignature.zig | 6 +- src/link/MachO/Object.zig | 2 +- src/link/Wasm.zig | 2 +- src/link/Wasm/Object.zig | 2 +- src/main.zig | 2 +- src/translate_c.zig | 2 +- src/translate_c/ast.zig | 14 ++--- src/type.zig | 2 +- src/value.zig | 8 +-- 58 files changed, 173 insertions(+), 264 deletions(-) (limited to 'lib/std/math') diff --git a/doc/docgen.zig b/doc/docgen.zig index bdbde6f5d2..4a9e33fbdd 100644 --- a/doc/docgen.zig +++ b/doc/docgen.zig @@ -276,7 +276,7 @@ fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, arg } } { - const caret_count = std.math.min(token.end, loc.line_end) - token.start; + const caret_count = @min(token.end, loc.line_end) - token.start; var i: usize = 0; while (i < caret_count) : (i += 1) { print("~", .{}); diff --git a/lib/compiler_rt/divc3.zig b/lib/compiler_rt/divc3.zig index 4e4dba2856..c4241c1483 100644 --- a/lib/compiler_rt/divc3.zig +++ b/lib/compiler_rt/divc3.zig @@ -3,7 +3,6 @@ const isNan = std.math.isNan; const isInf = std.math.isInf; const scalbn = std.math.scalbn; const ilogb = std.math.ilogb; -const max = std.math.max; const fabs = std.math.fabs; const maxInt = std.math.maxInt; const minInt = std.math.minInt; @@ -17,7 +16,7 @@ pub inline fn divc3(comptime T: type, a: T, b: T, c_in: T, d_in: T) Complex(T) { var d = d_in; // logbw used to prevent under/over-flow - const logbw = ilogb(max(fabs(c), fabs(d))); + const logbw = ilogb(@max(fabs(c), fabs(d))); const logbw_finite = logbw != maxInt(i32) and logbw != minInt(i32); const ilogbw = if (logbw_finite) b: { c = scalbn(c, -logbw); diff --git a/lib/compiler_rt/emutls.zig b/lib/compiler_rt/emutls.zig index 05a2de97a8..47c71efadd 100644 --- a/lib/compiler_rt/emutls.zig +++ b/lib/compiler_rt/emutls.zig @@ -49,7 +49,7 @@ const simple_allocator = struct { /// Allocate a memory chunk. pub fn advancedAlloc(alignment: u29, size: usize) [*]u8 { - const minimal_alignment = std.math.max(@alignOf(usize), alignment); + const minimal_alignment = @max(@alignOf(usize), alignment); var aligned_ptr: ?*anyopaque = undefined; if (std.c.posix_memalign(&aligned_ptr, minimal_alignment, size) != 0) { @@ -170,7 +170,7 @@ const current_thread_storage = struct { // make it to contains at least 16 objects (to avoid too much // reallocation at startup). - const size = std.math.max(16, index); + const size = @max(16, index); // create a new array and store it. var array: *ObjectArray = ObjectArray.init(size); diff --git a/lib/std/Build/Cache/DepTokenizer.zig b/lib/std/Build/Cache/DepTokenizer.zig index 1a4e2ddb74..0e5224edc0 100644 --- a/lib/std/Build/Cache/DepTokenizer.zig +++ b/lib/std/Build/Cache/DepTokenizer.zig @@ -983,7 +983,7 @@ fn hexDump(out: anytype, bytes: []const u8) !void { try printDecValue(out, offset, 8); try out.writeAll(":"); try out.writeAll(" "); - var end1 = std.math.min(offset + n, offset + 8); + var end1 = @min(offset + n, offset + 8); for (bytes[offset..end1]) |b| { try out.writeAll(" "); try printHexValue(out, b, 2); diff --git a/lib/std/Thread.zig b/lib/std/Thread.zig index ed6a9383e3..76650a9072 100644 --- a/lib/std/Thread.zig +++ b/lib/std/Thread.zig @@ -541,7 +541,7 @@ const WindowsThreadImpl = struct { // Going lower makes it default to that specified in the executable (~1mb). // Its also fine if the limit here is incorrect as stack size is only a hint. var stack_size = std.math.cast(u32, config.stack_size) orelse std.math.maxInt(u32); - stack_size = std.math.max(64 * 1024, stack_size); + stack_size = @max(64 * 1024, stack_size); instance.thread.thread_handle = windows.kernel32.CreateThread( null, @@ -690,7 +690,7 @@ const PosixThreadImpl = struct { defer assert(c.pthread_attr_destroy(&attr) == .SUCCESS); // Use the same set of parameters used by the libc-less impl. - const stack_size = std.math.max(config.stack_size, c.PTHREAD_STACK_MIN); + const stack_size = @max(config.stack_size, c.PTHREAD_STACK_MIN); assert(c.pthread_attr_setstacksize(&attr, stack_size) == .SUCCESS); assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == .SUCCESS); @@ -930,7 +930,7 @@ const LinuxThreadImpl = struct { var bytes: usize = page_size; guard_offset = bytes; - bytes += std.math.max(page_size, config.stack_size); + bytes += @max(page_size, config.stack_size); bytes = std.mem.alignForward(bytes, page_size); stack_offset = bytes; diff --git a/lib/std/Uri.zig b/lib/std/Uri.zig index 7a9755bd28..198ab461ae 100644 --- a/lib/std/Uri.zig +++ b/lib/std/Uri.zig @@ -177,13 +177,13 @@ pub fn parseWithoutScheme(text: []const u8) ParseError!Uri { if (std.mem.lastIndexOf(u8, authority, ":")) |index| { if (index >= end_of_host) { // if not part of the V6 address field - end_of_host = std.math.min(end_of_host, index); + end_of_host = @min(end_of_host, index); uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort; } } } else if (std.mem.lastIndexOf(u8, authority, ":")) |index| { if (index >= start_of_host) { // if not part of the userinfo field - end_of_host = std.math.min(end_of_host, index); + end_of_host = @min(end_of_host, index); uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort; } } diff --git a/lib/std/array_hash_map.zig b/lib/std/array_hash_map.zig index 55b9aac6e4..b46b5c12f0 100644 --- a/lib/std/array_hash_map.zig +++ b/lib/std/array_hash_map.zig @@ -815,9 +815,9 @@ pub fn ArrayHashMapUnmanaged( /// no longer guaranteed that no allocations will be performed. pub fn capacity(self: Self) usize { const entry_cap = self.entries.capacity; - const header = self.index_header orelse return math.min(linear_scan_max, entry_cap); + const header = self.index_header orelse return @min(linear_scan_max, entry_cap); const indexes_cap = header.capacity(); - return math.min(entry_cap, indexes_cap); + return @min(entry_cap, indexes_cap); } /// Clobbers any existing data. To detect if a put would clobber @@ -1821,7 +1821,7 @@ fn Index(comptime I: type) type { /// length * the size of an Index(u32). The index is 8 bytes (3 bits repr) /// and max_usize + 1 is not representable, so we need to subtract out 4 bits. const max_representable_index_len = @bitSizeOf(usize) - 4; -const max_bit_index = math.min(32, max_representable_index_len); +const max_bit_index = @min(32, max_representable_index_len); const min_bit_index = 5; const max_capacity = (1 << max_bit_index) - 1; const index_capacities = blk: { diff --git a/lib/std/ascii.zig b/lib/std/ascii.zig index 941f398f20..e47ef4db65 100644 --- a/lib/std/ascii.zig +++ b/lib/std/ascii.zig @@ -422,7 +422,7 @@ test "indexOfIgnoreCase" { /// Returns the lexicographical order of two slices. O(n). pub fn orderIgnoreCase(lhs: []const u8, rhs: []const u8) std.math.Order { - const n = std.math.min(lhs.len, rhs.len); + const n = @min(lhs.len, rhs.len); var i: usize = 0; while (i < n) : (i += 1) { switch (std.math.order(toLower(lhs[i]), toLower(rhs[i]))) { diff --git a/lib/std/compress/lzma/decode.zig b/lib/std/compress/lzma/decode.zig index dc220d8e87..f539abf8b1 100644 --- a/lib/std/compress/lzma/decode.zig +++ b/lib/std/compress/lzma/decode.zig @@ -59,7 +59,7 @@ pub const Params = struct { const pb = @intCast(u3, props); const dict_size_provided = try reader.readIntLittle(u32); - const dict_size = math.max(0x1000, dict_size_provided); + const dict_size = @max(0x1000, dict_size_provided); const unpacked_size = switch (options.unpacked_size) { .read_from_header => blk: { diff --git a/lib/std/crypto/blake3.zig b/lib/std/crypto/blake3.zig index fb580fda13..7ad1511e79 100644 --- a/lib/std/crypto/blake3.zig +++ b/lib/std/crypto/blake3.zig @@ -20,7 +20,7 @@ const ChunkIterator = struct { } fn next(self: *ChunkIterator) ?[]u8 { - const next_chunk = self.slice[0..math.min(self.chunk_len, self.slice.len)]; + const next_chunk = self.slice[0..@min(self.chunk_len, self.slice.len)]; self.slice = self.slice[next_chunk.len..]; return if (next_chunk.len > 0) next_chunk else null; } @@ -283,7 +283,7 @@ const ChunkState = struct { fn fillBlockBuf(self: *ChunkState, input: []const u8) []const u8 { const want = BLOCK_LEN - self.block_len; - const take = math.min(want, input.len); + const take = @min(want, input.len); @memcpy(self.block[self.block_len..][0..take], input[0..take]); self.block_len += @truncate(u8, take); return input[take..]; @@ -450,7 +450,7 @@ pub const Blake3 = struct { // Compress input bytes into the current chunk state. const want = CHUNK_LEN - self.chunk_state.len(); - const take = math.min(want, input.len); + const take = @min(want, input.len); self.chunk_state.update(input[0..take]); input = input[take..]; } @@ -663,7 +663,7 @@ fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) !void { // Write repeating input pattern to hasher var input_counter = input_len; while (input_counter > 0) { - const update_len = math.min(input_counter, input_pattern.len); + const update_len = @min(input_counter, input_pattern.len); hasher.update(input_pattern[0..update_len]); input_counter -= update_len; } diff --git a/lib/std/crypto/ff.zig b/lib/std/crypto/ff.zig index 84753ddefb..37e3d1c1b3 100644 --- a/lib/std/crypto/ff.zig +++ b/lib/std/crypto/ff.zig @@ -570,7 +570,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type { var out = self.zero; var i = x.limbs_count() - 1; if (self.limbs_count() >= 2) { - const start = math.min(i, self.limbs_count() - 2); + const start = @min(i, self.limbs_count() - 2); var j = start; while (true) : (j -= 1) { out.v.limbs.set(j, x.limbs.get(i)); diff --git a/lib/std/crypto/ghash_polyval.zig b/lib/std/crypto/ghash_polyval.zig index 46645d710f..2fbff25f72 100644 --- a/lib/std/crypto/ghash_polyval.zig +++ b/lib/std/crypto/ghash_polyval.zig @@ -363,7 +363,7 @@ fn Hash(comptime endian: std.builtin.Endian, comptime shift_key: bool) type { var mb = m; if (st.leftover > 0) { - const want = math.min(block_length - st.leftover, mb.len); + const want = @min(block_length - st.leftover, mb.len); const mc = mb[0..want]; for (mc, 0..) |x, i| { st.buf[st.leftover + i] = x; diff --git a/lib/std/crypto/keccak_p.zig b/lib/std/crypto/keccak_p.zig index 9226f2f6d4..ddc9b1b847 100644 --- a/lib/std/crypto/keccak_p.zig +++ b/lib/std/crypto/keccak_p.zig @@ -214,7 +214,7 @@ pub fn State(comptime f: u11, comptime capacity: u11, comptime delim: u8, compti pub fn absorb(self: *Self, bytes_: []const u8) void { var bytes = bytes_; if (self.offset > 0) { - const left = math.min(rate - self.offset, bytes.len); + const left = @min(rate - self.offset, bytes.len); @memcpy(self.buf[self.offset..][0..left], bytes[0..left]); self.offset += left; if (self.offset == rate) { @@ -249,7 +249,7 @@ pub fn State(comptime f: u11, comptime capacity: u11, comptime delim: u8, compti pub fn squeeze(self: *Self, out: []u8) void { var i: usize = 0; while (i < out.len) : (i += rate) { - const left = math.min(rate, out.len - i); + const left = @min(rate, out.len - i); self.st.extractBytes(out[i..][0..left]); self.st.permuteR(rounds); } diff --git a/lib/std/crypto/poly1305.zig b/lib/std/crypto/poly1305.zig index a2873f1145..51e1c2ab24 100644 --- a/lib/std/crypto/poly1305.zig +++ b/lib/std/crypto/poly1305.zig @@ -112,7 +112,7 @@ pub const Poly1305 = struct { // handle leftover if (st.leftover > 0) { - const want = std.math.min(block_length - st.leftover, mb.len); + const want = @min(block_length - st.leftover, mb.len); const mc = mb[0..want]; for (mc, 0..) |x, i| { st.buf[st.leftover + i] = x; diff --git a/lib/std/crypto/salsa20.zig b/lib/std/crypto/salsa20.zig index 7f57e6cecb..c8a639ad0b 100644 --- a/lib/std/crypto/salsa20.zig +++ b/lib/std/crypto/salsa20.zig @@ -404,7 +404,7 @@ pub const XSalsa20Poly1305 = struct { debug.assert(c.len == m.len); const extended = extend(rounds, k, npub); var block0 = [_]u8{0} ** 64; - const mlen0 = math.min(32, c.len); + const mlen0 = @min(32, c.len); @memcpy(block0[32..][0..mlen0], c[0..mlen0]); Salsa20.xor(block0[0..], block0[0..], 0, extended.key, extended.nonce); var mac = Poly1305.init(block0[0..32]); diff --git a/lib/std/crypto/scrypt.zig b/lib/std/crypto/scrypt.zig index b8e8ef55e2..97dd9b95d0 100644 --- a/lib/std/crypto/scrypt.zig +++ b/lib/std/crypto/scrypt.zig @@ -143,7 +143,7 @@ pub const Params = struct { /// Create parameters from ops and mem limits, where mem_limit given in bytes pub fn fromLimits(ops_limit: u64, mem_limit: usize) Self { - const ops = math.max(32768, ops_limit); + const ops = @max(32768, ops_limit); const r: u30 = 8; if (ops < mem_limit / 32) { const max_n = ops / (r * 4); @@ -151,7 +151,7 @@ pub const Params = struct { } else { const max_n = mem_limit / (@intCast(usize, r) * 128); const ln = @intCast(u6, math.log2(max_n)); - const max_rp = math.min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln)); + const max_rp = @min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln)); return Self{ .r = r, .p = @intCast(u30, max_rp / @as(u64, r)), .ln = ln }; } } diff --git a/lib/std/crypto/sha3.zig b/lib/std/crypto/sha3.zig index 23f9e65534..0226490881 100644 --- a/lib/std/crypto/sha3.zig +++ b/lib/std/crypto/sha3.zig @@ -148,7 +148,7 @@ fn ShakeLike(comptime security_level: u11, comptime delim: u8, comptime rounds: if (self.offset > 0) { const left = self.buf.len - self.offset; if (left > 0) { - const n = math.min(left, out.len); + const n = @min(left, out.len); @memcpy(out[0..n], self.buf[self.offset..][0..n]); out = out[n..]; self.offset += n; diff --git a/lib/std/crypto/siphash.zig b/lib/std/crypto/siphash.zig index 37d219f868..70f4f2fd53 100644 --- a/lib/std/crypto/siphash.zig +++ b/lib/std/crypto/siphash.zig @@ -433,7 +433,7 @@ test "iterative non-divisible update" { var siphash = Siphash.init(key); var i: usize = 0; while (i < end) : (i += 7) { - siphash.update(buf[i..std.math.min(i + 7, end)]); + siphash.update(buf[i..@min(i + 7, end)]); } const iterative_hash = siphash.finalInt(); diff --git a/lib/std/debug.zig b/lib/std/debug.zig index ea0d467085..3015c30bfb 100644 --- a/lib/std/debug.zig +++ b/lib/std/debug.zig @@ -198,7 +198,7 @@ pub fn captureStackTrace(first_address: ?usize, stack_trace: *std.builtin.StackT stack_trace.index = 0; return; }; - const end_index = math.min(first_index + addrs.len, n); + const end_index = @min(first_index + addrs.len, n); const slice = addr_buf[first_index..end_index]; // We use a for loop here because slice and addrs may alias. for (slice, 0..) |addr, i| { @@ -380,7 +380,7 @@ pub fn writeStackTrace( _ = allocator; if (builtin.strip_debug_info) return error.MissingDebugInfo; var frame_index: usize = 0; - var frames_left: usize = std.math.min(stack_trace.index, stack_trace.instruction_addresses.len); + var frames_left: usize = @min(stack_trace.index, stack_trace.instruction_addresses.len); while (frames_left != 0) : ({ frames_left -= 1; diff --git a/lib/std/dynamic_library.zig b/lib/std/dynamic_library.zig index 59ad7429cf..94da2f4d6d 100644 --- a/lib/std/dynamic_library.zig +++ b/lib/std/dynamic_library.zig @@ -8,7 +8,6 @@ const elf = std.elf; const windows = std.os.windows; const system = std.os.system; const maxInt = std.math.maxInt; -const max = std.math.max; pub const DynLib = switch (builtin.os.tag) { .linux => if (builtin.link_libc) DlDynlib else ElfDynLib, @@ -152,7 +151,7 @@ pub const ElfDynLib = struct { }) { const ph = @intToPtr(*elf.Phdr, ph_addr); switch (ph.p_type) { - elf.PT_LOAD => virt_addr_end = max(virt_addr_end, ph.p_vaddr + ph.p_memsz), + elf.PT_LOAD => virt_addr_end = @max(virt_addr_end, ph.p_vaddr + ph.p_memsz), elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, elf_addr + ph.p_offset), else => {}, } diff --git a/lib/std/event/loop.zig b/lib/std/event/loop.zig index c8d41d3eb0..bc0162423b 100644 --- a/lib/std/event/loop.zig +++ b/lib/std/event/loop.zig @@ -179,7 +179,7 @@ pub const Loop = struct { // We need at least one of these in case the fs thread wants to use onNextTick const extra_thread_count = thread_count - 1; - const resume_node_count = std.math.max(extra_thread_count, 1); + const resume_node_count = @max(extra_thread_count, 1); self.eventfd_resume_nodes = try self.arena.allocator().alloc( std.atomic.Stack(ResumeNode.EventFd).Node, resume_node_count, diff --git a/lib/std/fifo.zig b/lib/std/fifo.zig index bc88e61d76..535376d38f 100644 --- a/lib/std/fifo.zig +++ b/lib/std/fifo.zig @@ -150,7 +150,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]; } } diff --git a/lib/std/fmt.zig b/lib/std/fmt.zig index 6896d0a7a0..c9d8e611ca 100644 --- a/lib/std/fmt.zig +++ b/lib/std/fmt.zig @@ -921,8 +921,8 @@ fn formatSizeImpl(comptime base: comptime_int) type { const log2 = math.log2(value); const magnitude = switch (base) { - 1000 => math.min(log2 / comptime math.log2(1000), mags_si.len - 1), - 1024 => math.min(log2 / 10, mags_iec.len - 1), + 1000 => @min(log2 / comptime math.log2(1000), mags_si.len - 1), + 1024 => @min(log2 / 10, mags_iec.len - 1), else => unreachable, }; const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, base), lossyCast(f64, magnitude)); @@ -1103,7 +1103,7 @@ pub fn formatFloatScientific( var printed: usize = 0; if (float_decimal.digits.len > 1) { - const num_digits = math.min(float_decimal.digits.len, precision + 1); + const num_digits = @min(float_decimal.digits.len, precision + 1); try writer.writeAll(float_decimal.digits[1..num_digits]); printed += num_digits - 1; } @@ -1116,7 +1116,7 @@ pub fn formatFloatScientific( try writer.writeAll(float_decimal.digits[0..1]); try writer.writeAll("."); if (float_decimal.digits.len > 1) { - const num_digits = if (@TypeOf(value) == f32) math.min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len; + const num_digits = if (@TypeOf(value) == f32) @min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len; try writer.writeAll(float_decimal.digits[1..num_digits]); } else { @@ -1299,7 +1299,7 @@ pub fn formatFloatDecimal( var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0; // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this. - var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len); + var num_digits_whole_no_pad = @min(num_digits_whole, float_decimal.digits.len); if (num_digits_whole > 0) { // We may have to zero pad, for instance 1e4 requires zero padding. @@ -1326,7 +1326,7 @@ pub fn formatFloatDecimal( // Zero-fill until we reach significant digits or run out of precision. if (float_decimal.exp <= 0) { const zero_digit_count = @intCast(usize, -float_decimal.exp); - const zeros_to_print = math.min(zero_digit_count, precision); + const zeros_to_print = @min(zero_digit_count, precision); var i: usize = 0; while (i < zeros_to_print) : (i += 1) { @@ -1357,7 +1357,7 @@ pub fn formatFloatDecimal( var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0; // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this. - var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len); + var num_digits_whole_no_pad = @min(num_digits_whole, float_decimal.digits.len); if (num_digits_whole > 0) { // We may have to zero pad, for instance 1e4 requires zero padding. @@ -1410,12 +1410,12 @@ pub fn formatInt( // The type must have the same size as `base` or be wider in order for the // division to work - const min_int_bits = comptime math.max(value_info.bits, 8); + const min_int_bits = comptime @max(value_info.bits, 8); const MinInt = std.meta.Int(.unsigned, min_int_bits); const abs_value = math.absCast(int_value); // The worst case in terms of space needed is base 2, plus 1 for the sign - var buf: [1 + math.max(value_info.bits, 1)]u8 = undefined; + var buf: [1 + @max(@as(comptime_int, value_info.bits), 1)]u8 = undefined; var a: MinInt = abs_value; var index: usize = buf.len; diff --git a/lib/std/hash/wyhash.zig b/lib/std/hash/wyhash.zig index 3426bca9f4..c36c3fe87c 100644 --- a/lib/std/hash/wyhash.zig +++ b/lib/std/hash/wyhash.zig @@ -252,7 +252,7 @@ test "iterative non-divisible update" { var wy = Wyhash.init(seed); var i: usize = 0; while (i < end) : (i += 33) { - wy.update(buf[i..std.math.min(i + 33, end)]); + wy.update(buf[i..@min(i + 33, end)]); } const iterative_hash = wy.final(); diff --git a/lib/std/hash_map.zig b/lib/std/hash_map.zig index 041d99606e..5b539ddaad 100644 --- a/lib/std/hash_map.zig +++ b/lib/std/hash_map.zig @@ -1507,7 +1507,7 @@ pub fn HashMapUnmanaged( fn grow(self: *Self, allocator: Allocator, new_capacity: Size, ctx: Context) Allocator.Error!void { @setCold(true); - const new_cap = std.math.max(new_capacity, minimal_capacity); + const new_cap = @max(new_capacity, minimal_capacity); assert(new_cap > self.capacity()); assert(std.math.isPowerOfTwo(new_cap)); @@ -1540,7 +1540,7 @@ pub fn HashMapUnmanaged( const header_align = @alignOf(Header); const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K); const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V); - const max_align = comptime math.max3(header_align, key_align, val_align); + const max_align = comptime @max(header_align, key_align, val_align); const meta_size = @sizeOf(Header) + new_capacity * @sizeOf(Metadata); comptime assert(@alignOf(Metadata) == 1); @@ -1575,7 +1575,7 @@ pub fn HashMapUnmanaged( const header_align = @alignOf(Header); const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K); const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V); - const max_align = comptime math.max3(header_align, key_align, val_align); + const max_align = comptime @max(header_align, key_align, val_align); const cap = self.capacity(); const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata); diff --git a/lib/std/heap/arena_allocator.zig b/lib/std/heap/arena_allocator.zig index c0eeae6e61..c7e0569067 100644 --- a/lib/std/heap/arena_allocator.zig +++ b/lib/std/heap/arena_allocator.zig @@ -110,7 +110,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) { diff --git a/lib/std/heap/memory_pool.zig b/lib/std/heap/memory_pool.zig index ca6eb7f518..3fc7dfbfca 100644 --- a/lib/std/heap/memory_pool.zig +++ b/lib/std/heap/memory_pool.zig @@ -40,11 +40,11 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type /// Size of the memory pool items. This is not necessarily the same /// as `@sizeOf(Item)` as the pool also uses the items for internal means. - pub const item_size = std.math.max(@sizeOf(Node), @sizeOf(Item)); + pub const item_size = @max(@sizeOf(Node), @sizeOf(Item)); /// Alignment of the memory pool items. This is not necessarily the same /// as `@alignOf(Item)` as the pool also uses the items for internal means. - pub const item_alignment = std.math.max(@alignOf(Node), pool_options.alignment orelse 0); + pub const item_alignment = @max(@alignOf(Node), pool_options.alignment orelse 0); const Node = struct { next: ?*@This(), diff --git a/lib/std/http/protocol.zig b/lib/std/http/protocol.zig index b001b3cddf..b5c2cdfa0c 100644 --- a/lib/std/http/protocol.zig +++ b/lib/std/http/protocol.zig @@ -82,7 +82,7 @@ pub const HeadersParser = struct { /// If the amount returned is less than `bytes.len`, you may assume that the parser is in a content state and the /// first byte of content is located at `bytes[result]`. pub fn findHeadersEnd(r: *HeadersParser, bytes: []const u8) u32 { - const vector_len: comptime_int = comptime std.math.max(std.simd.suggestVectorSize(u8) orelse 1, 8); + const vector_len: comptime_int = comptime @max(std.simd.suggestVectorSize(u8) orelse 1, 8); const len = @intCast(u32, bytes.len); var index: u32 = 0; diff --git a/lib/std/io/fixed_buffer_stream.zig b/lib/std/io/fixed_buffer_stream.zig index c170dd1f74..27b978744c 100644 --- a/lib/std/io/fixed_buffer_stream.zig +++ b/lib/std/io/fixed_buffer_stream.zig @@ -76,7 +76,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type { } pub fn seekTo(self: *Self, pos: u64) SeekError!void { - self.pos = if (std.math.cast(usize, pos)) |x| std.math.min(self.buffer.len, x) else self.buffer.len; + self.pos = if (std.math.cast(usize, pos)) |x| @min(self.buffer.len, x) else self.buffer.len; } pub fn seekBy(self: *Self, amt: i64) SeekError!void { @@ -91,7 +91,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type { } else { const amt_usize = std.math.cast(usize, amt) orelse std.math.maxInt(usize); const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize); - self.pos = std.math.min(self.buffer.len, new_pos); + self.pos = @min(self.buffer.len, new_pos); } } diff --git a/lib/std/io/limited_reader.zig b/lib/std/io/limited_reader.zig index aa00af0d09..09d76007da 100644 --- a/lib/std/io/limited_reader.zig +++ b/lib/std/io/limited_reader.zig @@ -14,7 +14,7 @@ pub fn LimitedReader(comptime ReaderType: type) type { const Self = @This(); pub fn read(self: *Self, dest: []u8) Error!usize { - const max_read = std.math.min(self.bytes_left, dest.len); + const max_read = @min(self.bytes_left, dest.len); const n = try self.inner_reader.read(dest[0..max_read]); self.bytes_left -= n; return n; diff --git a/lib/std/io/reader.zig b/lib/std/io/reader.zig index 344515d07b..abdca56d3c 100644 --- a/lib/std/io/reader.zig +++ b/lib/std/io/reader.zig @@ -325,7 +325,7 @@ pub fn Reader( var remaining = num_bytes; while (remaining > 0) { - const amt = std.math.min(remaining, options.buf_size); + const amt = @min(remaining, options.buf_size); try self.readNoEof(buf[0..amt]); remaining -= amt; } diff --git a/lib/std/io/writer.zig b/lib/std/io/writer.zig index cfc76de452..d0b7fa11ee 100644 --- a/lib/std/io/writer.zig +++ b/lib/std/io/writer.zig @@ -39,7 +39,7 @@ pub fn Writer( var remaining: usize = n; while (remaining > 0) { - const to_write = std.math.min(remaining, bytes.len); + const to_write = @min(remaining, bytes.len); try self.writeAll(bytes[0..to_write]); remaining -= to_write; } diff --git a/lib/std/math.zig b/lib/std/math.zig index 46a7e40a37..e60e964747 100644 --- a/lib/std/math.zig +++ b/lib/std/math.zig @@ -165,7 +165,7 @@ pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool { if (isNan(x) or isNan(y)) return false; - return @fabs(x - y) <= max(@fabs(x), @fabs(y)) * tolerance; + return @fabs(x - y) <= @max(@fabs(x), @fabs(y)) * tolerance; } test "approxEqAbs and approxEqRel" { @@ -434,104 +434,15 @@ pub fn Min(comptime A: type, comptime B: type) type { return @TypeOf(@as(A, 0) + @as(B, 0)); } -/// Returns the smaller number. When one parameter's type's full range -/// fits in the other, the return type is the smaller type. -pub fn min(x: anytype, y: anytype) Min(@TypeOf(x), @TypeOf(y)) { - const Result = Min(@TypeOf(x), @TypeOf(y)); - if (x < y) { - // TODO Zig should allow this as an implicit cast because x is - // immutable and in this scope it is known to fit in the - // return type. - switch (@typeInfo(Result)) { - .Int => return @intCast(Result, x), - else => return x, - } - } else { - // TODO Zig should allow this as an implicit cast because y is - // immutable and in this scope it is known to fit in the - // return type. - switch (@typeInfo(Result)) { - .Int => return @intCast(Result, y), - else => return y, - } - } -} - -test "min" { - try testing.expect(min(@as(i32, -1), @as(i32, 2)) == -1); - { - var a: u16 = 999; - var b: u32 = 10; - var result = min(a, b); - try testing.expect(@TypeOf(result) == u16); - try testing.expect(result == 10); - } - { - var a: f64 = 10.34; - var b: f32 = 999.12; - var result = min(a, b); - try testing.expect(@TypeOf(result) == f64); - try testing.expect(result == 10.34); - } - { - var a: i8 = -127; - var b: i16 = -200; - var result = min(a, b); - try testing.expect(@TypeOf(result) == i16); - try testing.expect(result == -200); - } - { - const a = 10.34; - var b: f32 = 999.12; - var result = min(a, b); - try testing.expect(@TypeOf(result) == f32); - try testing.expect(result == 10.34); - } -} - -/// Finds the minimum of three numbers. -pub fn min3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) { - return min(x, min(y, z)); -} - -test "min3" { - try testing.expect(min3(@as(i32, 0), @as(i32, 1), @as(i32, 2)) == 0); - try testing.expect(min3(@as(i32, 0), @as(i32, 2), @as(i32, 1)) == 0); - try testing.expect(min3(@as(i32, 1), @as(i32, 0), @as(i32, 2)) == 0); - try testing.expect(min3(@as(i32, 1), @as(i32, 2), @as(i32, 0)) == 0); - try testing.expect(min3(@as(i32, 2), @as(i32, 0), @as(i32, 1)) == 0); - try testing.expect(min3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 0); -} - -/// Returns the maximum of two numbers. Return type is the one with the -/// larger range. -pub fn max(x: anytype, y: anytype) @TypeOf(x, y) { - return if (x > y) x else y; -} - -test "max" { - try testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2); - try testing.expect(max(@as(i32, 2), @as(i32, -1)) == 2); -} - -/// Finds the maximum of three numbers. -pub fn max3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) { - return max(x, max(y, z)); -} - -test "max3" { - try testing.expect(max3(@as(i32, 0), @as(i32, 1), @as(i32, 2)) == 2); - try testing.expect(max3(@as(i32, 0), @as(i32, 2), @as(i32, 1)) == 2); - try testing.expect(max3(@as(i32, 1), @as(i32, 0), @as(i32, 2)) == 2); - try testing.expect(max3(@as(i32, 1), @as(i32, 2), @as(i32, 0)) == 2); - try testing.expect(max3(@as(i32, 2), @as(i32, 0), @as(i32, 1)) == 2); - try testing.expect(max3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 2); -} +pub const min = @compileError("deprecated; use @min instead"); +pub const max = @compileError("deprecated; use @max instead"); +pub const min3 = @compileError("deprecated; use @min instead"); +pub const max3 = @compileError("deprecated; use @max instead"); /// Limit val to the inclusive range [lower, upper]. pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) { assert(lower <= upper); - return max(lower, min(val, upper)); + return @max(lower, @min(val, upper)); } test "clamp" { // Within range @@ -795,7 +706,7 @@ pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) t return u0; } const signedness: std.builtin.Signedness = if (from < 0) .signed else .unsigned; - const largest_positive_integer = max(if (from < 0) (-from) - 1 else from, to); // two's complement + const largest_positive_integer = @max(if (from < 0) (-from) - 1 else from, to); // two's complement const base = log2(largest_positive_integer); const upper = (1 << base) - 1; var magnitude_bits = if (upper >= largest_positive_integer) base else base + 1; diff --git a/lib/std/math/big/int.zig b/lib/std/math/big/int.zig index ec79d843da..487812e1de 100644 --- a/lib/std/math/big/int.zig +++ b/lib/std/math/big/int.zig @@ -44,12 +44,12 @@ pub fn calcDivLimbsBufferLen(a_len: usize, b_len: usize) usize { } pub fn calcMulLimbsBufferLen(a_len: usize, b_len: usize, aliases: usize) usize { - return aliases * math.max(a_len, b_len); + return aliases * @max(a_len, b_len); } pub fn calcMulWrapLimbsBufferLen(bit_count: usize, a_len: usize, b_len: usize, aliases: usize) usize { const req_limbs = calcTwosCompLimbCount(bit_count); - return aliases * math.min(req_limbs, math.max(a_len, b_len)); + return aliases * @min(req_limbs, @max(a_len, b_len)); } pub fn calcSetStringLimbsBufferLen(base: u8, string_len: usize) usize { @@ -396,7 +396,7 @@ pub const Mutable = struct { /// scalar is a primitive integer type. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by - /// r is `math.max(a.limbs.len, calcLimbLen(scalar)) + 1`. + /// r is `@max(a.limbs.len, calcLimbLen(scalar)) + 1`. pub fn addScalar(r: *Mutable, a: Const, scalar: anytype) void { // Normally we could just determine the number of limbs needed with calcLimbLen, // but that is not comptime-known when scalar is not a comptime_int. Instead, we @@ -414,11 +414,11 @@ pub const Mutable = struct { return add(r, a, operand); } - /// Base implementation for addition. Adds `max(a.limbs.len, b.limbs.len)` elements from a and b, + /// Base implementation for addition. Adds `@max(a.limbs.len, b.limbs.len)` elements from a and b, /// and returns whether any overflow occurred. /// r, a and b may be aliases. /// - /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`. + /// Asserts r has enough elements to hold the result. The upper bound is `@max(a.limbs.len, b.limbs.len)`. fn addCarry(r: *Mutable, a: Const, b: Const) bool { if (a.eqZero()) { r.copy(b); @@ -452,12 +452,12 @@ pub const Mutable = struct { /// r, a and b may be aliases. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by - /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. + /// r is `@max(a.limbs.len, b.limbs.len) + 1`. pub fn add(r: *Mutable, a: Const, b: Const) void { if (r.addCarry(a, b)) { // Fix up the result. Note that addCarry normalizes by a.limbs.len or b.limbs.len, // so we need to set the length here. - const msl = math.max(a.limbs.len, b.limbs.len); + const msl = @max(a.limbs.len, b.limbs.len); // `[add|sub]Carry` normalizes by `msl`, so we need to fix up the result manually here. // Note, the fact that it normalized means that the intermediary limbs are zero here. r.len = msl + 1; @@ -477,12 +477,12 @@ pub const Mutable = struct { // if an overflow occurred. const x = Const{ .positive = a.positive, - .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)], + .limbs = a.limbs[0..@min(req_limbs, a.limbs.len)], }; const y = Const{ .positive = b.positive, - .limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)], + .limbs = b.limbs[0..@min(req_limbs, b.limbs.len)], }; var carry_truncated = false; @@ -492,7 +492,7 @@ pub const Mutable = struct { // truncate anyway. // - a and b had less elements than req_limbs, and those were overflowed. This case needs to be handled. // Note: after this we still might need to wrap. - const msl = math.max(a.limbs.len, b.limbs.len); + const msl = @max(a.limbs.len, b.limbs.len); if (msl < req_limbs) { r.limbs[msl] = 1; r.len = req_limbs; @@ -522,12 +522,12 @@ pub const Mutable = struct { // if an overflow occurred. const x = Const{ .positive = a.positive, - .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)], + .limbs = a.limbs[0..@min(req_limbs, a.limbs.len)], }; const y = Const{ .positive = b.positive, - .limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)], + .limbs = b.limbs[0..@min(req_limbs, b.limbs.len)], }; if (r.addCarry(x, y)) { @@ -535,7 +535,7 @@ pub const Mutable = struct { // - We overflowed req_limbs, in which case we need to saturate. // - a and b had less elements than req_limbs, and those were overflowed. // Note: In this case, might _also_ need to saturate. - const msl = math.max(a.limbs.len, b.limbs.len); + const msl = @max(a.limbs.len, b.limbs.len); if (msl < req_limbs) { r.limbs[msl] = 1; r.len = req_limbs; @@ -550,11 +550,11 @@ pub const Mutable = struct { r.saturate(r.toConst(), signedness, bit_count); } - /// Base implementation for subtraction. Subtracts `max(a.limbs.len, b.limbs.len)` elements from a and b, + /// Base implementation for subtraction. Subtracts `@max(a.limbs.len, b.limbs.len)` elements from a and b, /// and returns whether any overflow occurred. /// r, a and b may be aliases. /// - /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`. + /// Asserts r has enough elements to hold the result. The upper bound is `@max(a.limbs.len, b.limbs.len)`. fn subCarry(r: *Mutable, a: Const, b: Const) bool { if (a.eqZero()) { r.copy(b); @@ -607,7 +607,7 @@ pub const Mutable = struct { /// r, a and b may be aliases. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by - /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. The +1 is not needed if both operands are positive. + /// r is `@max(a.limbs.len, b.limbs.len) + 1`. The +1 is not needed if both operands are positive. pub fn sub(r: *Mutable, a: Const, b: Const) void { r.add(a, b.negate()); } @@ -714,7 +714,7 @@ pub const Mutable = struct { const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: { const start = buf_index; - const a_len = math.min(req_limbs, a.limbs.len); + const a_len = @min(req_limbs, a.limbs.len); @memcpy(limbs_buffer[buf_index..][0..a_len], a.limbs[0..a_len]); buf_index += a_len; break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst(); @@ -722,7 +722,7 @@ pub const Mutable = struct { const b_copy = if (rma.limbs.ptr == b.limbs.ptr) blk: { const start = buf_index; - const b_len = math.min(req_limbs, b.limbs.len); + const b_len = @min(req_limbs, b.limbs.len); @memcpy(limbs_buffer[buf_index..][0..b_len], b.limbs[0..b_len]); buf_index += b_len; break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst(); @@ -755,13 +755,13 @@ pub const Mutable = struct { const req_limbs = calcTwosCompLimbCount(bit_count); // We can ignore the upper bits here, those results will be discarded anyway. - const a_limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)]; - const b_limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)]; + const a_limbs = a.limbs[0..@min(req_limbs, a.limbs.len)]; + const b_limbs = b.limbs[0..@min(req_limbs, b.limbs.len)]; @memset(rma.limbs[0..req_limbs], 0); llmulacc(.add, allocator, rma.limbs, a_limbs, b_limbs); - rma.normalize(math.min(req_limbs, a.limbs.len + b.limbs.len)); + rma.normalize(@min(req_limbs, a.limbs.len + b.limbs.len)); rma.positive = (a.positive == b.positive); rma.truncate(rma.toConst(), signedness, bit_count); } @@ -1211,7 +1211,7 @@ pub const Mutable = struct { /// /// a and b are zero-extended to the longer of a or b. /// - /// Asserts that r has enough limbs to store the result. Upper bound is `math.max(a.limbs.len, b.limbs.len)`. + /// Asserts that r has enough limbs to store the result. Upper bound is `@max(a.limbs.len, b.limbs.len)`. pub fn bitOr(r: *Mutable, a: Const, b: Const) void { // Trivial cases, llsignedor does not support zero. if (a.eqZero()) { @@ -1235,8 +1235,8 @@ pub const Mutable = struct { /// r may alias with a or b. /// /// Asserts that r has enough limbs to store the result. - /// If a or b is positive, the upper bound is `math.min(a.limbs.len, b.limbs.len)`. - /// If a and b are negative, the upper bound is `math.max(a.limbs.len, b.limbs.len) + 1`. + /// If a or b is positive, the upper bound is `@min(a.limbs.len, b.limbs.len)`. + /// If a and b are negative, the upper bound is `@max(a.limbs.len, b.limbs.len) + 1`. pub fn bitAnd(r: *Mutable, a: Const, b: Const) void { // Trivial cases, llsignedand does not support zero. if (a.eqZero()) { @@ -1260,8 +1260,8 @@ pub const Mutable = struct { /// r may alias with a or b. /// /// Asserts that r has enough limbs to store the result. If a and b share the same signedness, the - /// upper bound is `math.max(a.limbs.len, b.limbs.len)`. Otherwise, if either a or b is negative - /// but not both, the upper bound is `math.max(a.limbs.len, b.limbs.len) + 1`. + /// upper bound is `@max(a.limbs.len, b.limbs.len)`. Otherwise, if either a or b is negative + /// but not both, the upper bound is `@max(a.limbs.len, b.limbs.len) + 1`. pub fn bitXor(r: *Mutable, a: Const, b: Const) void { // Trivial cases, because llsignedxor does not support negative zero. if (a.eqZero()) { @@ -1284,7 +1284,7 @@ pub const Mutable = struct { /// rma may alias x or y. /// x and y may alias each other. /// Asserts that `rma` has enough limbs to store the result. Upper bound is - /// `math.min(x.limbs.len, y.limbs.len)`. + /// `@min(x.limbs.len, y.limbs.len)`. /// /// `limbs_buffer` is used for temporary storage during the operation. When this function returns, /// it will have the same length as it had when the function was called. @@ -1546,7 +1546,7 @@ pub const Mutable = struct { if (yi != 0) break i; } else unreachable; - const xy_trailing = math.min(x_trailing, y_trailing); + const xy_trailing = @min(x_trailing, y_trailing); if (y.len - xy_trailing == 1) { const divisor = y.limbs[y.len - 1]; @@ -2589,7 +2589,7 @@ pub const Managed = struct { .allocator = allocator, .metadata = 1, .limbs = block: { - const limbs = try allocator.alloc(Limb, math.max(default_capacity, capacity)); + const limbs = try allocator.alloc(Limb, @max(default_capacity, capacity)); limbs[0] = 0; break :block limbs; }, @@ -2918,7 +2918,7 @@ pub const Managed = struct { /// /// Returns an error if memory could not be allocated. pub fn sub(r: *Managed, a: *const Managed, b: *const Managed) !void { - try r.ensureCapacity(math.max(a.len(), b.len()) + 1); + try r.ensureCapacity(@max(a.len(), b.len()) + 1); var m = r.toMutable(); m.sub(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); @@ -3025,11 +3025,11 @@ pub const Managed = struct { } pub fn ensureAddScalarCapacity(r: *Managed, a: Const, scalar: anytype) !void { - try r.ensureCapacity(math.max(a.limbs.len, calcLimbLen(scalar)) + 1); + try r.ensureCapacity(@max(a.limbs.len, calcLimbLen(scalar)) + 1); } pub fn ensureAddCapacity(r: *Managed, a: Const, b: Const) !void { - try r.ensureCapacity(math.max(a.limbs.len, b.limbs.len) + 1); + try r.ensureCapacity(@max(a.limbs.len, b.limbs.len) + 1); } pub fn ensureMulCapacity(rma: *Managed, a: Const, b: Const) !void { @@ -3123,7 +3123,7 @@ pub const Managed = struct { /// /// a and b are zero-extended to the longer of a or b. pub fn bitOr(r: *Managed, a: *const Managed, b: *const Managed) !void { - try r.ensureCapacity(math.max(a.len(), b.len())); + try r.ensureCapacity(@max(a.len(), b.len())); var m = r.toMutable(); m.bitOr(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); @@ -3132,9 +3132,9 @@ pub const Managed = struct { /// r = a & b pub fn bitAnd(r: *Managed, a: *const Managed, b: *const Managed) !void { const cap = if (a.isPositive() or b.isPositive()) - math.min(a.len(), b.len()) + @min(a.len(), b.len()) else - math.max(a.len(), b.len()) + 1; + @max(a.len(), b.len()) + 1; try r.ensureCapacity(cap); var m = r.toMutable(); m.bitAnd(a.toConst(), b.toConst()); @@ -3143,7 +3143,7 @@ pub const Managed = struct { /// r = a ^ b pub fn bitXor(r: *Managed, a: *const Managed, b: *const Managed) !void { - var cap = math.max(a.len(), b.len()) + @boolToInt(a.isPositive() != b.isPositive()); + var cap = @max(a.len(), b.len()) + @boolToInt(a.isPositive() != b.isPositive()); try r.ensureCapacity(cap); var m = r.toMutable(); @@ -3156,7 +3156,7 @@ pub const Managed = struct { /// /// rma's allocator is used for temporary storage to boost multiplication performance. pub fn gcd(rma: *Managed, x: *const Managed, y: *const Managed) !void { - try rma.ensureCapacity(math.min(x.len(), y.len())); + try rma.ensureCapacity(@min(x.len(), y.len())); var m = rma.toMutable(); var limbs_buffer = std.ArrayList(Limb).init(rma.allocator); defer limbs_buffer.deinit(); @@ -3356,13 +3356,13 @@ fn llmulaccKaratsuba( // For a1 and b1 we only need `limbs_after_split` limbs. const a1 = blk: { var a1 = a[split..]; - a1.len = math.min(llnormalize(a1), limbs_after_split); + a1.len = @min(llnormalize(a1), limbs_after_split); break :blk a1; }; const b1 = blk: { var b1 = b[split..]; - b1.len = math.min(llnormalize(b1), limbs_after_split); + b1.len = @min(llnormalize(b1), limbs_after_split); break :blk b1; }; @@ -3381,10 +3381,10 @@ fn llmulaccKaratsuba( // Compute p2. // Note, we don't need to compute all of p2, just enough limbs to satisfy r. - const p2_limbs = math.min(limbs_after_split, a1.len + b1.len); + const p2_limbs = @min(limbs_after_split, a1.len + b1.len); @memset(tmp[0..p2_limbs], 0); - llmulacc(.add, allocator, tmp[0..p2_limbs], a1[0..math.min(a1.len, p2_limbs)], b1[0..math.min(b1.len, p2_limbs)]); + llmulacc(.add, allocator, tmp[0..p2_limbs], a1[0..@min(a1.len, p2_limbs)], b1[0..@min(b1.len, p2_limbs)]); const p2 = tmp[0..llnormalize(tmp[0..p2_limbs])]; // Add p2 * B to the result. @@ -3392,7 +3392,7 @@ fn llmulaccKaratsuba( // Add p2 * B^2 to the result if required. if (limbs_after_split2 > 0) { - llaccum(op, r[split * 2 ..], p2[0..math.min(p2.len, limbs_after_split2)]); + llaccum(op, r[split * 2 ..], p2[0..@min(p2.len, limbs_after_split2)]); } // Compute p0. @@ -3406,13 +3406,13 @@ fn llmulaccKaratsuba( llaccum(op, r, p0); // Add p0 * B to the result. In this case, we may not need all of it. - llaccum(op, r[split..], p0[0..math.min(limbs_after_split, p0.len)]); + llaccum(op, r[split..], p0[0..@min(limbs_after_split, p0.len)]); // Finally, compute and add p1. // From now on we only need `limbs_after_split` limbs for a0 and b0, since the result of the // following computation will be added * B. - const a0x = a0[0..std.math.min(a0.len, limbs_after_split)]; - const b0x = b0[0..std.math.min(b0.len, limbs_after_split)]; + const a0x = a0[0..@min(a0.len, limbs_after_split)]; + const b0x = b0[0..@min(b0.len, limbs_after_split)]; const j0_sign = llcmp(a0x, a1); const j1_sign = llcmp(b1, b0x); @@ -3544,7 +3544,7 @@ fn llmulLimb(comptime op: AccOp, acc: []Limb, y: []const Limb, xi: Limb) bool { return false; } - const split = std.math.min(y.len, acc.len); + const split = @min(y.len, acc.len); var a_lo = acc[0..split]; var a_hi = acc[split..]; @@ -4023,8 +4023,8 @@ fn llsignedand(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_ // r may alias. // a and b must not be -0. // Returns `true` when the result is positive. -// If the sign of a and b is equal, then r requires at least `max(a.len, b.len)` limbs are required. -// Otherwise, r requires at least `max(a.len, b.len) + 1` limbs. +// If the sign of a and b is equal, then r requires at least `@max(a.len, b.len)` limbs are required. +// Otherwise, r requires at least `@max(a.len, b.len) + 1` limbs. fn llsignedxor(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_positive: bool) bool { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); diff --git a/lib/std/math/ldexp.zig b/lib/std/math/ldexp.zig index d2fd8db9b7..8947475159 100644 --- a/lib/std/math/ldexp.zig +++ b/lib/std/math/ldexp.zig @@ -48,7 +48,7 @@ pub fn ldexp(x: anytype, n: i32) @TypeOf(x) { return @bitCast(T, sign_bit); // Severe underflow. Return +/- 0 // Result underflowed, we need to shift and round - const shift = @intCast(Log2Int(TBits), math.min(-n, -(exponent + n) + 1)); + const shift = @intCast(Log2Int(TBits), @min(-n, -(exponent + n) + 1)); const exact_tie: bool = @ctz(repr) == shift - 1; var result = repr & mantissa_mask; diff --git a/lib/std/mem.zig b/lib/std/mem.zig index c4ad708887..2f34745a64 100644 --- a/lib/std/mem.zig +++ b/lib/std/mem.zig @@ -596,7 +596,7 @@ pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void { /// Compares two slices of numbers lexicographically. O(n). pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order { - const n = math.min(lhs.len, rhs.len); + const n = @min(lhs.len, rhs.len); var i: usize = 0; while (i < n) : (i += 1) { switch (math.order(lhs[i], rhs[i])) { @@ -642,7 +642,7 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool { /// Compares two slices and returns the index of the first inequality. /// Returns null if the slices are equal. pub fn indexOfDiff(comptime T: type, a: []const T, b: []const T) ?usize { - const shortest = math.min(a.len, b.len); + const shortest = @min(a.len, b.len); if (a.ptr == b.ptr) return if (a.len == b.len) null else shortest; var index: usize = 0; @@ -3296,7 +3296,7 @@ pub fn min(comptime T: type, slice: []const T) T { assert(slice.len > 0); var best = slice[0]; for (slice[1..]) |item| { - best = math.min(best, item); + best = @min(best, item); } return best; } @@ -3313,7 +3313,7 @@ pub fn max(comptime T: type, slice: []const T) T { assert(slice.len > 0); var best = slice[0]; for (slice[1..]) |item| { - best = math.max(best, item); + best = @max(best, item); } return best; } @@ -3332,8 +3332,8 @@ pub fn minMax(comptime T: type, slice: []const T) struct { min: T, max: T } { var minVal = slice[0]; var maxVal = slice[0]; for (slice[1..]) |item| { - minVal = math.min(minVal, item); - maxVal = math.max(maxVal, item); + minVal = @min(minVal, item); + maxVal = @max(maxVal, item); } return .{ .min = minVal, .max = maxVal }; } diff --git a/lib/std/net.zig b/lib/std/net.zig index 64b13ec544..dfd6fe4a9e 100644 --- a/lib/std/net.zig +++ b/lib/std/net.zig @@ -1482,11 +1482,11 @@ fn getResolvConf(allocator: mem.Allocator, rc: *ResolvConf) !void { error.InvalidCharacter => continue, }; if (mem.eql(u8, name, "ndots")) { - rc.ndots = std.math.min(value, 15); + rc.ndots = @min(value, 15); } else if (mem.eql(u8, name, "attempts")) { - rc.attempts = std.math.min(value, 10); + rc.attempts = @min(value, 10); } else if (mem.eql(u8, name, "timeout")) { - rc.timeout = std.math.min(value, 60); + rc.timeout = @min(value, 60); } } } else if (mem.eql(u8, token, "nameserver")) { @@ -1615,7 +1615,7 @@ fn resMSendRc( } // Wait for a response, or until time to retry - const clamped_timeout = std.math.min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2); + const clamped_timeout = @min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2); const nevents = os.poll(&pfd, clamped_timeout) catch 0; if (nevents == 0) continue; diff --git a/lib/std/os/linux.zig b/lib/std/os/linux.zig index ef0ec94d3b..e4d6790505 100644 --- a/lib/std/os/linux.zig +++ b/lib/std/os/linux.zig @@ -317,7 +317,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize { .getdents, @bitCast(usize, @as(isize, fd)), @ptrToInt(dirp), - std.math.min(len, maxInt(c_int)), + @min(len, maxInt(c_int)), ); } @@ -326,7 +326,7 @@ pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize { .getdents64, @bitCast(usize, @as(isize, fd)), @ptrToInt(dirp), - std.math.min(len, maxInt(c_int)), + @min(len, maxInt(c_int)), ); } diff --git a/lib/std/os/linux/io_uring.zig b/lib/std/os/linux/io_uring.zig index b7467d765f..0610b214d5 100644 --- a/lib/std/os/linux/io_uring.zig +++ b/lib/std/os/linux/io_uring.zig @@ -277,7 +277,7 @@ pub const IO_Uring = struct { fn copy_cqes_ready(self: *IO_Uring, cqes: []linux.io_uring_cqe, wait_nr: u32) u32 { _ = wait_nr; const ready = self.cq_ready(); - const count = std.math.min(cqes.len, ready); + const count = @min(cqes.len, ready); var head = self.cq.head.*; var tail = head +% count; // TODO Optimize this by using 1 or 2 memcpy's (if the tail wraps) rather than a loop. @@ -1093,7 +1093,7 @@ pub const SubmissionQueue = struct { pub fn init(fd: os.fd_t, p: linux.io_uring_params) !SubmissionQueue { assert(fd >= 0); assert((p.features & linux.IORING_FEAT_SINGLE_MMAP) != 0); - const size = std.math.max( + const size = @max( p.sq_off.array + p.sq_entries * @sizeOf(u32), p.cq_off.cqes + p.cq_entries * @sizeOf(linux.io_uring_cqe), ); diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index e559e48915..389c4bea12 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -272,7 +272,7 @@ pub fn RtlGenRandom(output: []u8) RtlGenRandomError!void { const max_read_size: ULONG = maxInt(ULONG); while (total_read < output.len) { - const to_read: ULONG = math.min(buff.len, max_read_size); + const to_read: ULONG = @min(buff.len, max_read_size); if (advapi32.RtlGenRandom(buff.ptr, to_read) == 0) { return unexpectedError(kernel32.GetLastError()); @@ -501,7 +501,7 @@ pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64, io_mode: std.io.Mo return @as(usize, bytes_transferred); } else { while (true) { - const want_read_count = @intCast(DWORD, math.min(@as(DWORD, maxInt(DWORD)), buffer.len)); + const want_read_count: DWORD = @min(@as(DWORD, maxInt(DWORD)), buffer.len); var amt_read: DWORD = undefined; var overlapped_data: OVERLAPPED = undefined; const overlapped: ?*OVERLAPPED = if (offset) |off| blk: { diff --git a/lib/std/pdb.zig b/lib/std/pdb.zig index 5bc836b08e..180507ba71 100644 --- a/lib/std/pdb.zig +++ b/lib/std/pdb.zig @@ -1049,7 +1049,7 @@ const MsfStream = struct { var size: usize = 0; var rem_buffer = buffer; while (size < buffer.len) { - const size_to_read = math.min(self.block_size - offset, rem_buffer.len); + const size_to_read = @min(self.block_size - offset, rem_buffer.len); size += try in.read(rem_buffer[0..size_to_read]); rem_buffer = buffer[size..]; offset += size_to_read; diff --git a/lib/std/rand.zig b/lib/std/rand.zig index 1e9f4051e9..f07562c911 100644 --- a/lib/std/rand.zig +++ b/lib/std/rand.zig @@ -410,7 +410,7 @@ pub const Random = struct { r.uintLessThan(T, sum) else if (comptime std.meta.trait.isFloat(T)) // take care that imprecision doesn't lead to a value slightly greater than sum - std.math.min(r.float(T) * sum, sum - std.math.floatEps(T)) + @min(r.float(T) * sum, sum - std.math.floatEps(T)) else @compileError("weightedIndex does not support proportions of type " ++ @typeName(T)); diff --git a/lib/std/sort/block.zig b/lib/std/sort/block.zig index 6c1be9c6c2..518d148a73 100644 --- a/lib/std/sort/block.zig +++ b/lib/std/sort/block.zig @@ -590,7 +590,7 @@ pub fn block( // whenever we leave an A block behind, we'll need to merge the previous A block with any B blocks that follow it, so track that information as well var lastA = firstA; var lastB = Range.init(0, 0); - var blockB = Range.init(B.start, B.start + math.min(block_size, B.length())); + var blockB = Range.init(B.start, B.start + @min(block_size, B.length())); blockA.start += firstA.length(); indexA = buffer1.start; @@ -849,7 +849,7 @@ fn findFirstForward( comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length() / unique, @as(usize, 1)); + const skip = @max(range.length() / unique, @as(usize, 1)); var index = range.start + skip; while (lessThan(context, items[index - 1], value)) : (index += skip) { @@ -871,7 +871,7 @@ fn findFirstBackward( comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length() / unique, @as(usize, 1)); + const skip = @max(range.length() / unique, @as(usize, 1)); var index = range.end - skip; while (index > range.start and !lessThan(context, items[index - 1], value)) : (index -= skip) { @@ -893,7 +893,7 @@ fn findLastForward( comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length() / unique, @as(usize, 1)); + const skip = @max(range.length() / unique, @as(usize, 1)); var index = range.start + skip; while (!lessThan(context, value, items[index - 1])) : (index += skip) { @@ -915,7 +915,7 @@ fn findLastBackward( comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) usize { if (range.length() == 0) return range.start; - const skip = math.max(range.length() / unique, @as(usize, 1)); + const skip = @max(range.length() / unique, @as(usize, 1)); var index = range.end - skip; while (index > range.start and lessThan(context, value, items[index - 1])) : (index -= skip) { diff --git a/lib/std/zig/render.zig b/lib/std/zig/render.zig index 83fa68567f..3930c9714a 100644 --- a/lib/std/zig/render.zig +++ b/lib/std/zig/render.zig @@ -1960,7 +1960,7 @@ fn renderArrayInit( if (!this_contains_newline) { const column = column_counter % row_size; - column_widths[column] = std.math.max(column_widths[column], width); + column_widths[column] = @max(column_widths[column], width); const expr_last_token = tree.lastToken(expr) + 1; const next_expr = section_exprs[i + 1]; @@ -1980,7 +1980,7 @@ fn renderArrayInit( if (!contains_newline) { const column = column_counter % row_size; - column_widths[column] = std.math.max(column_widths[column], width); + column_widths[column] = @max(column_widths[column], width); } } } diff --git a/lib/std/zig/system/NativeTargetInfo.zig b/lib/std/zig/system/NativeTargetInfo.zig index f17356fdcd..cddaea2295 100644 --- a/lib/std/zig/system/NativeTargetInfo.zig +++ b/lib/std/zig/system/NativeTargetInfo.zig @@ -503,7 +503,7 @@ fn glibcVerFromSoFile(file: fs.File) !std.builtin.Version { const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset); const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size); var strtab_buf: [4096:0]u8 = undefined; - const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len); + const shstrtab_len = @min(shstrtab_size, strtab_buf.len); const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len); const shstrtab = strtab_buf[0..shstrtab_read_len]; const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum); @@ -757,7 +757,7 @@ pub fn abiAndDynamicLinkerFromFile( const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset); const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size); var strtab_buf: [4096:0]u8 = undefined; - const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len); + const shstrtab_len = @min(shstrtab_size, strtab_buf.len); const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len); const shstrtab = strtab_buf[0..shstrtab_read_len]; @@ -806,7 +806,7 @@ pub fn abiAndDynamicLinkerFromFile( const rpoff_file = ds.offset + rpoff_usize; const rp_max_size = ds.size - rpoff_usize; - const strtab_len = std.math.min(rp_max_size, strtab_buf.len); + const strtab_len = @min(rp_max_size, strtab_buf.len); const strtab_read_len = try preadMin(file, &strtab_buf, rpoff_file, strtab_len); const strtab = strtab_buf[0..strtab_read_len]; diff --git a/src/Sema.zig b/src/Sema.zig index 99ebd044f9..36fe5a6ee8 100644 --- a/src/Sema.zig +++ b/src/Sema.zig @@ -22367,9 +22367,9 @@ fn analyzeShuffle( // to it up to the length of the longer vector. This recursion terminates // in 1 call because these calls to analyzeShuffle guarantee a_len == b_len. if (a_len != b_len) { - const min_len = std.math.min(a_len, b_len); + const min_len = @min(a_len, b_len); const max_src = if (a_len > b_len) a_src else b_src; - const max_len = try sema.usizeCast(block, max_src, std.math.max(a_len, b_len)); + const max_len = try sema.usizeCast(block, max_src, @max(a_len, b_len)); const expand_mask_values = try sema.arena.alloc(InternPool.Index, max_len); for (@intCast(usize, 0)..@intCast(usize, min_len)) |i| { @@ -31301,7 +31301,7 @@ fn cmpNumeric( } const dest_ty = if (dest_float_type) |ft| ft else blk: { - const max_bits = std.math.max(lhs_bits, rhs_bits); + const max_bits = @max(lhs_bits, rhs_bits); const casted_bits = std.math.cast(u16, max_bits) orelse return sema.fail(block, src, "{d} exceeds maximum integer bit count", .{max_bits}); const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned; break :blk try mod.intType(signedness, casted_bits); @@ -35828,7 +35828,7 @@ fn intAddScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value { const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, sema); const limbs = try sema.arena.alloc( std.math.big.Limb, - std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, + @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, ); var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.add(lhs_bigint, rhs_bigint); @@ -35918,7 +35918,7 @@ fn intSubScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value { const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, sema); const limbs = try sema.arena.alloc( std.math.big.Limb, - std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, + @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, ); var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.sub(lhs_bigint, rhs_bigint); diff --git a/src/TypedValue.zig b/src/TypedValue.zig index 9d3fb67d1f..93454710dc 100644 --- a/src/TypedValue.zig +++ b/src/TypedValue.zig @@ -111,7 +111,7 @@ pub fn print( .val = val.castTag(.repeated).?.data, }; const len = ty.arrayLen(mod); - const max_len = std.math.min(len, max_aggregate_items); + const max_len = @min(len, max_aggregate_items); while (i < max_len) : (i += 1) { if (i != 0) try writer.writeAll(", "); try print(elem_tv, writer, level - 1, mod); @@ -130,7 +130,7 @@ pub fn print( const len = payload.len.toUnsignedInt(mod); if (elem_ty.eql(Type.u8, mod)) str: { - const max_len = @intCast(usize, std.math.min(len, max_string_len)); + const max_len: usize = @min(len, max_string_len); var buf: [max_string_len]u8 = undefined; var i: u32 = 0; @@ -149,7 +149,7 @@ pub fn print( try writer.writeAll(".{ "); - const max_len = std.math.min(len, max_aggregate_items); + const max_len = @min(len, max_aggregate_items); var i: u32 = 0; while (i < max_len) : (i += 1) { if (i != 0) try writer.writeAll(", "); @@ -455,7 +455,7 @@ fn printAggregate( const len = ty.arrayLen(mod); if (elem_ty.eql(Type.u8, mod)) str: { - const max_len = @intCast(usize, std.math.min(len, max_string_len)); + const max_len: usize = @min(len, max_string_len); var buf: [max_string_len]u8 = undefined; var i: u32 = 0; @@ -471,7 +471,7 @@ fn printAggregate( try writer.writeAll(".{ "); - const max_len = std.math.min(len, max_aggregate_items); + const max_len = @min(len, max_aggregate_items); var i: u32 = 0; while (i < max_len) : (i += 1) { if (i != 0) try writer.writeAll(", "); diff --git a/src/arch/x86_64/CodeGen.zig b/src/arch/x86_64/CodeGen.zig index a1b57516ee..6d98ecce4f 100644 --- a/src/arch/x86_64/CodeGen.zig +++ b/src/arch/x86_64/CodeGen.zig @@ -2907,7 +2907,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void { const dst_info = dst_ty.intInfo(mod); const src_ty = try mod.intType(dst_info.signedness, switch (tag) { else => unreachable, - .mul, .mulwrap => math.max3( + .mul, .mulwrap => @max( self.activeIntBits(bin_op.lhs), self.activeIntBits(bin_op.rhs), dst_info.bits / 2, @@ -3349,7 +3349,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void { const lhs_active_bits = self.activeIntBits(bin_op.lhs); const rhs_active_bits = self.activeIntBits(bin_op.rhs); - const src_bits = math.max3(lhs_active_bits, rhs_active_bits, dst_info.bits / 2); + const src_bits = @max(lhs_active_bits, rhs_active_bits, dst_info.bits / 2); const src_ty = try mod.intType(dst_info.signedness, src_bits); const lhs = try self.resolveInst(bin_op.lhs); diff --git a/src/link/Elf.zig b/src/link/Elf.zig index 409eca6e7a..0863a22fac 100644 --- a/src/link/Elf.zig +++ b/src/link/Elf.zig @@ -2326,7 +2326,7 @@ fn allocateAtom(self: *Elf, atom_index: Atom.Index, new_block_size: u64, alignme self.debug_aranges_section_dirty = true; } } - shdr.sh_addralign = math.max(shdr.sh_addralign, alignment); + shdr.sh_addralign = @max(shdr.sh_addralign, alignment); // This function can also reallocate an atom. // In this case we need to "unplug" it from its previous location before diff --git a/src/link/MachO/CodeSignature.zig b/src/link/MachO/CodeSignature.zig index 59b3e50b07..4709560ba7 100644 --- a/src/link/MachO/CodeSignature.zig +++ b/src/link/MachO/CodeSignature.zig @@ -99,7 +99,7 @@ const CodeDirectory = struct { fn addSpecialHash(self: *CodeDirectory, index: u32, hash: [hash_size]u8) void { assert(index > 0); - self.inner.nSpecialSlots = std.math.max(self.inner.nSpecialSlots, index); + self.inner.nSpecialSlots = @max(self.inner.nSpecialSlots, index); self.special_slots[index - 1] = hash; } @@ -426,11 +426,11 @@ pub fn estimateSize(self: CodeSignature, file_size: u64) u32 { var n_special_slots: u32 = 0; if (self.requirements) |req| { ssize += @sizeOf(macho.BlobIndex) + req.size(); - n_special_slots = std.math.max(n_special_slots, req.slotType()); + n_special_slots = @max(n_special_slots, req.slotType()); } if (self.entitlements) |ent| { ssize += @sizeOf(macho.BlobIndex) + ent.size() + hash_size; - n_special_slots = std.math.max(n_special_slots, ent.slotType()); + n_special_slots = @max(n_special_slots, ent.slotType()); } if (self.signature) |sig| { ssize += @sizeOf(macho.BlobIndex) + sig.size(); diff --git a/src/link/MachO/Object.zig b/src/link/MachO/Object.zig index b218fdbd2d..105a806075 100644 --- a/src/link/MachO/Object.zig +++ b/src/link/MachO/Object.zig @@ -530,7 +530,7 @@ pub fn splitRegularSections(self: *Object, zld: *Zld, object_id: u32) !void { sect.addr + sect.size - addr; const atom_align = if (addr > 0) - math.min(@ctz(addr), sect.@"align") + @min(@ctz(addr), sect.@"align") else sect.@"align"; diff --git a/src/link/Wasm.zig b/src/link/Wasm.zig index fdac7dfa63..5126033995 100644 --- a/src/link/Wasm.zig +++ b/src/link/Wasm.zig @@ -2027,7 +2027,7 @@ fn parseAtom(wasm: *Wasm, atom_index: Atom.Index, kind: Kind) !void { }; const segment: *Segment = &wasm.segments.items[final_index]; - segment.alignment = std.math.max(segment.alignment, atom.alignment); + segment.alignment = @max(segment.alignment, atom.alignment); try wasm.appendAtomAtIndex(final_index, atom_index); } diff --git a/src/link/Wasm/Object.zig b/src/link/Wasm/Object.zig index 363648971a..33f54dece5 100644 --- a/src/link/Wasm/Object.zig +++ b/src/link/Wasm/Object.zig @@ -979,7 +979,7 @@ pub fn parseIntoAtoms(object: *Object, gpa: Allocator, object_index: u16, wasm_b const segment: *Wasm.Segment = &wasm_bin.segments.items[final_index]; if (relocatable_data.type == .data) { //code section and debug sections are 1-byte aligned - segment.alignment = std.math.max(segment.alignment, atom.alignment); + segment.alignment = @max(segment.alignment, atom.alignment); } try wasm_bin.appendAtomAtIndex(final_index, atom_index); diff --git a/src/main.zig b/src/main.zig index 5d666840c0..aedca80d26 100644 --- a/src/main.zig +++ b/src/main.zig @@ -5391,7 +5391,7 @@ fn gimmeMoreOfThoseSweetSweetFileDescriptors() void { // setrlimit() now returns with errno set to EINVAL in places that historically succeeded. // It no longer accepts "rlim_cur = RLIM.INFINITY" for RLIM.NOFILE. // Use "rlim_cur = min(OPEN_MAX, rlim_max)". - lim.max = std.math.min(std.os.darwin.OPEN_MAX, lim.max); + lim.max = @min(std.os.darwin.OPEN_MAX, lim.max); } if (lim.cur == lim.max) return; diff --git a/src/translate_c.zig b/src/translate_c.zig index 8cc2d1856c..67176ff74b 100644 --- a/src/translate_c.zig +++ b/src/translate_c.zig @@ -2400,7 +2400,7 @@ fn transStringLiteralInitializer( if (array_size == 0) return Tag.empty_array.create(c.arena, elem_type); - const num_inits = math.min(str_length, array_size); + const num_inits = @min(str_length, array_size); const init_node = if (num_inits > 0) blk: { if (is_narrow) { // "string literal".* or string literal"[0..num_inits].* diff --git a/src/translate_c/ast.zig b/src/translate_c/ast.zig index 6c6bbf28bd..443c56a84a 100644 --- a/src/translate_c/ast.zig +++ b/src/translate_c/ast.zig @@ -1824,7 +1824,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex { }, .switch_prong => { const payload = node.castTag(.switch_prong).?.data; - var items = try c.gpa.alloc(NodeIndex, std.math.max(payload.cases.len, 1)); + var items = try c.gpa.alloc(NodeIndex, @max(payload.cases.len, 1)); defer c.gpa.free(items); items[0] = 0; for (payload.cases, 0..) |item, i| { @@ -1973,7 +1973,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex { const payload = node.castTag(.tuple).?.data; _ = try c.addToken(.period, "."); const l_brace = try c.addToken(.l_brace, "{"); - var inits = try c.gpa.alloc(NodeIndex, std.math.max(payload.len, 2)); + var inits = try c.gpa.alloc(NodeIndex, @max(payload.len, 2)); defer c.gpa.free(inits); inits[0] = 0; inits[1] = 0; @@ -2007,7 +2007,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex { const payload = node.castTag(.container_init_dot).?.data; _ = try c.addToken(.period, "."); const l_brace = try c.addToken(.l_brace, "{"); - var inits = try c.gpa.alloc(NodeIndex, std.math.max(payload.len, 2)); + var inits = try c.gpa.alloc(NodeIndex, @max(payload.len, 2)); defer c.gpa.free(inits); inits[0] = 0; inits[1] = 0; @@ -2046,7 +2046,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex { const lhs = try renderNode(c, payload.lhs); const l_brace = try c.addToken(.l_brace, "{"); - var inits = try c.gpa.alloc(NodeIndex, std.math.max(payload.inits.len, 1)); + var inits = try c.gpa.alloc(NodeIndex, @max(payload.inits.len, 1)); defer c.gpa.free(inits); inits[0] = 0; for (payload.inits, 0..) |init, i| { @@ -2102,7 +2102,7 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex { const num_vars = payload.variables.len; const num_funcs = payload.functions.len; const total_members = payload.fields.len + num_vars + num_funcs; - const members = try c.gpa.alloc(NodeIndex, std.math.max(total_members, 2)); + const members = try c.gpa.alloc(NodeIndex, @max(total_members, 2)); defer c.gpa.free(members); members[0] = 0; members[1] = 0; @@ -2195,7 +2195,7 @@ fn renderFieldAccess(c: *Context, lhs: NodeIndex, field_name: []const u8) !NodeI fn renderArrayInit(c: *Context, lhs: NodeIndex, inits: []const Node) !NodeIndex { const l_brace = try c.addToken(.l_brace, "{"); - var rendered = try c.gpa.alloc(NodeIndex, std.math.max(inits.len, 1)); + var rendered = try c.gpa.alloc(NodeIndex, @max(inits.len, 1)); defer c.gpa.free(rendered); rendered[0] = 0; for (inits, 0..) |init, i| { @@ -2904,7 +2904,7 @@ fn renderMacroFunc(c: *Context, node: Node) !NodeIndex { fn renderParams(c: *Context, params: []Payload.Param, is_var_args: bool) !std.ArrayList(NodeIndex) { _ = try c.addToken(.l_paren, "("); - var rendered = try std.ArrayList(NodeIndex).initCapacity(c.gpa, std.math.max(params.len, 1)); + var rendered = try std.ArrayList(NodeIndex).initCapacity(c.gpa, @max(params.len, 1)); errdefer rendered.deinit(); for (params, 0..) |param, i| { diff --git a/src/type.zig b/src/type.zig index 22523a7141..bb82a50682 100644 --- a/src/type.zig +++ b/src/type.zig @@ -1633,7 +1633,7 @@ pub const Type = struct { const len = array_type.len + @boolToInt(array_type.sentinel != .none); if (len == 0) return 0; const elem_ty = array_type.child.toType(); - const elem_size = std.math.max(elem_ty.abiAlignment(mod), elem_ty.abiSize(mod)); + const elem_size = @max(elem_ty.abiAlignment(mod), elem_ty.abiSize(mod)); if (elem_size == 0) return 0; const elem_bit_size = try bitSizeAdvanced(elem_ty, mod, opt_sema); return (len - 1) * 8 * elem_size + elem_bit_size; diff --git a/src/value.zig b/src/value.zig index 85204e2b10..8590aa8872 100644 --- a/src/value.zig +++ b/src/value.zig @@ -2458,7 +2458,7 @@ pub const Value = struct { const rhs_bigint = rhs.toBigInt(&rhs_space, mod); const limbs = try arena.alloc( std.math.big.Limb, - std.math.max( + @max( // For the saturate std.math.big.int.calcTwosCompLimbCount(info.bits), lhs_bigint.limbs.len + rhs_bigint.limbs.len, @@ -2572,7 +2572,7 @@ pub const Value = struct { const limbs = try arena.alloc( std.math.big.Limb, // + 1 for negatives - std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, + @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.bitAnd(lhs_bigint, rhs_bigint); @@ -2638,7 +2638,7 @@ pub const Value = struct { const rhs_bigint = rhs.toBigInt(&rhs_space, mod); const limbs = try arena.alloc( std.math.big.Limb, - std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len), + @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len), ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.bitOr(lhs_bigint, rhs_bigint); @@ -2677,7 +2677,7 @@ pub const Value = struct { const limbs = try arena.alloc( std.math.big.Limb, // + 1 for negatives - std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, + @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.bitXor(lhs_bigint, rhs_bigint); -- cgit v1.2.3