authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-06-16 13:45:33-07:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-06-16 13:45:33-07:00
log537104fd9d84d94abad3e36d3cd781be4397e299
treea77492de657f8a76c15bdeb443916490db79e1cd
parent5d9e8f27d0dc131e0b4154c5f65376f2fb9f3500
parent2af5bd8aa8711b2a6e60f961290372134090f235
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #16025 from mlugg/feat/remove-std-math-minmax

Consider bounds when refining @min/@max result type; deprecate std.math.{min,max,min3,max3}

62 files changed, 430 insertions(+), 397 deletions(-)

doc/docgen.zig+1-1
...@@ -276,7 +276,7 @@ fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, arg...@@ -276,7 +276,7 @@ fn parseError(tokenizer: *Tokenizer, token: Token, comptime fmt: []const u8, arg
276 }276 }
277 }277 }
278 {278 {
279 const caret_count = std.math.min(token.end, loc.line_end) - token.start;279 const caret_count = @min(token.end, loc.line_end) - token.start;
280 var i: usize = 0;280 var i: usize = 0;
281 while (i < caret_count) : (i += 1) {281 while (i < caret_count) : (i += 1) {
282 print("~", .{});282 print("~", .{});
lib/compiler_rt/divc3.zig+1-2
...@@ -3,7 +3,6 @@ const isNan = std.math.isNan;...@@ -3,7 +3,6 @@ const isNan = std.math.isNan;
3const isInf = std.math.isInf;3const isInf = std.math.isInf;
4const scalbn = std.math.scalbn;4const scalbn = std.math.scalbn;
5const ilogb = std.math.ilogb;5const ilogb = std.math.ilogb;
6const max = std.math.max;
7const fabs = std.math.fabs;6const fabs = std.math.fabs;
8const maxInt = std.math.maxInt;7const maxInt = std.math.maxInt;
9const minInt = std.math.minInt;8const 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) {...@@ -17,7 +16,7 @@ pub inline fn divc3(comptime T: type, a: T, b: T, c_in: T, d_in: T) Complex(T) {
17 var d = d_in;16 var d = d_in;
1817
19 // logbw used to prevent under/over-flow18 // logbw used to prevent under/over-flow
20 const logbw = ilogb(max(fabs(c), fabs(d)));19 const logbw = ilogb(@max(fabs(c), fabs(d)));
21 const logbw_finite = logbw != maxInt(i32) and logbw != minInt(i32);20 const logbw_finite = logbw != maxInt(i32) and logbw != minInt(i32);
22 const ilogbw = if (logbw_finite) b: {21 const ilogbw = if (logbw_finite) b: {
23 c = scalbn(c, -logbw);22 c = scalbn(c, -logbw);
lib/compiler_rt/emutls.zig+2-2
...@@ -49,7 +49,7 @@ const simple_allocator = struct {...@@ -49,7 +49,7 @@ const simple_allocator = struct {
4949
50 /// Allocate a memory chunk.50 /// Allocate a memory chunk.
51 pub fn advancedAlloc(alignment: u29, size: usize) [*]u8 {51 pub fn advancedAlloc(alignment: u29, size: usize) [*]u8 {
52 const minimal_alignment = std.math.max(@alignOf(usize), alignment);52 const minimal_alignment = @max(@alignOf(usize), alignment);
5353
54 var aligned_ptr: ?*anyopaque = undefined;54 var aligned_ptr: ?*anyopaque = undefined;
55 if (std.c.posix_memalign(&aligned_ptr, minimal_alignment, size) != 0) {55 if (std.c.posix_memalign(&aligned_ptr, minimal_alignment, size) != 0) {
...@@ -170,7 +170,7 @@ const current_thread_storage = struct {...@@ -170,7 +170,7 @@ const current_thread_storage = struct {
170170
171 // make it to contains at least 16 objects (to avoid too much171 // make it to contains at least 16 objects (to avoid too much
172 // reallocation at startup).172 // reallocation at startup).
173 const size = std.math.max(16, index);173 const size = @max(16, index);
174174
175 // create a new array and store it.175 // create a new array and store it.
176 var array: *ObjectArray = ObjectArray.init(size);176 var array: *ObjectArray = ObjectArray.init(size);
lib/std/Build/Cache/DepTokenizer.zig+1-1
...@@ -983,7 +983,7 @@ fn hexDump(out: anytype, bytes: []const u8) !void {...@@ -983,7 +983,7 @@ fn hexDump(out: anytype, bytes: []const u8) !void {
983 try printDecValue(out, offset, 8);983 try printDecValue(out, offset, 8);
984 try out.writeAll(":");984 try out.writeAll(":");
985 try out.writeAll(" ");985 try out.writeAll(" ");
986 var end1 = std.math.min(offset + n, offset + 8);986 var end1 = @min(offset + n, offset + 8);
987 for (bytes[offset..end1]) |b| {987 for (bytes[offset..end1]) |b| {
988 try out.writeAll(" ");988 try out.writeAll(" ");
989 try printHexValue(out, b, 2);989 try printHexValue(out, b, 2);
lib/std/Thread.zig+3-3
...@@ -541,7 +541,7 @@ const WindowsThreadImpl = struct {...@@ -541,7 +541,7 @@ const WindowsThreadImpl = struct {
541 // Going lower makes it default to that specified in the executable (~1mb).541 // Going lower makes it default to that specified in the executable (~1mb).
542 // Its also fine if the limit here is incorrect as stack size is only a hint.542 // Its also fine if the limit here is incorrect as stack size is only a hint.
543 var stack_size = std.math.cast(u32, config.stack_size) orelse std.math.maxInt(u32);543 var stack_size = std.math.cast(u32, config.stack_size) orelse std.math.maxInt(u32);
544 stack_size = std.math.max(64 * 1024, stack_size);544 stack_size = @max(64 * 1024, stack_size);
545545
546 instance.thread.thread_handle = windows.kernel32.CreateThread(546 instance.thread.thread_handle = windows.kernel32.CreateThread(
547 null,547 null,
...@@ -690,7 +690,7 @@ const PosixThreadImpl = struct {...@@ -690,7 +690,7 @@ const PosixThreadImpl = struct {
690 defer assert(c.pthread_attr_destroy(&attr) == .SUCCESS);690 defer assert(c.pthread_attr_destroy(&attr) == .SUCCESS);
691691
692 // Use the same set of parameters used by the libc-less impl.692 // Use the same set of parameters used by the libc-less impl.
693 const stack_size = std.math.max(config.stack_size, c.PTHREAD_STACK_MIN);693 const stack_size = @max(config.stack_size, c.PTHREAD_STACK_MIN);
694 assert(c.pthread_attr_setstacksize(&attr, stack_size) == .SUCCESS);694 assert(c.pthread_attr_setstacksize(&attr, stack_size) == .SUCCESS);
695 assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == .SUCCESS);695 assert(c.pthread_attr_setguardsize(&attr, std.mem.page_size) == .SUCCESS);
696696
...@@ -930,7 +930,7 @@ const LinuxThreadImpl = struct {...@@ -930,7 +930,7 @@ const LinuxThreadImpl = struct {
930 var bytes: usize = page_size;930 var bytes: usize = page_size;
931 guard_offset = bytes;931 guard_offset = bytes;
932932
933 bytes += std.math.max(page_size, config.stack_size);933 bytes += @max(page_size, config.stack_size);
934 bytes = std.mem.alignForward(bytes, page_size);934 bytes = std.mem.alignForward(bytes, page_size);
935 stack_offset = bytes;935 stack_offset = bytes;
936936
lib/std/Uri.zig+2-2
...@@ -177,13 +177,13 @@ pub fn parseWithoutScheme(text: []const u8) ParseError!Uri {...@@ -177,13 +177,13 @@ pub fn parseWithoutScheme(text: []const u8) ParseError!Uri {
177177
178 if (std.mem.lastIndexOf(u8, authority, ":")) |index| {178 if (std.mem.lastIndexOf(u8, authority, ":")) |index| {
179 if (index >= end_of_host) { // if not part of the V6 address field179 if (index >= end_of_host) { // if not part of the V6 address field
180 end_of_host = std.math.min(end_of_host, index);180 end_of_host = @min(end_of_host, index);
181 uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort;181 uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort;
182 }182 }
183 }183 }
184 } else if (std.mem.lastIndexOf(u8, authority, ":")) |index| {184 } else if (std.mem.lastIndexOf(u8, authority, ":")) |index| {
185 if (index >= start_of_host) { // if not part of the userinfo field185 if (index >= start_of_host) { // if not part of the userinfo field
186 end_of_host = std.math.min(end_of_host, index);186 end_of_host = @min(end_of_host, index);
187 uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort;187 uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort;
188 }188 }
189 }189 }
lib/std/array_hash_map.zig+3-3
...@@ -815,9 +815,9 @@ pub fn ArrayHashMapUnmanaged(...@@ -815,9 +815,9 @@ pub fn ArrayHashMapUnmanaged(
815 /// no longer guaranteed that no allocations will be performed.815 /// no longer guaranteed that no allocations will be performed.
816 pub fn capacity(self: Self) usize {816 pub fn capacity(self: Self) usize {
817 const entry_cap = self.entries.capacity;817 const entry_cap = self.entries.capacity;
818 const header = self.index_header orelse return math.min(linear_scan_max, entry_cap);818 const header = self.index_header orelse return @min(linear_scan_max, entry_cap);
819 const indexes_cap = header.capacity();819 const indexes_cap = header.capacity();
820 return math.min(entry_cap, indexes_cap);820 return @min(entry_cap, indexes_cap);
821 }821 }
822822
823 /// Clobbers any existing data. To detect if a put would clobber823 /// Clobbers any existing data. To detect if a put would clobber
...@@ -1821,7 +1821,7 @@ fn Index(comptime I: type) type {...@@ -1821,7 +1821,7 @@ fn Index(comptime I: type) type {
1821/// length * the size of an Index(u32). The index is 8 bytes (3 bits repr)1821/// length * the size of an Index(u32). The index is 8 bytes (3 bits repr)
1822/// and max_usize + 1 is not representable, so we need to subtract out 4 bits.1822/// and max_usize + 1 is not representable, so we need to subtract out 4 bits.
1823const max_representable_index_len = @bitSizeOf(usize) - 4;1823const max_representable_index_len = @bitSizeOf(usize) - 4;
1824const max_bit_index = math.min(32, max_representable_index_len);1824const max_bit_index = @min(32, max_representable_index_len);
1825const min_bit_index = 5;1825const min_bit_index = 5;
1826const max_capacity = (1 << max_bit_index) - 1;1826const max_capacity = (1 << max_bit_index) - 1;
1827const index_capacities = blk: {1827const index_capacities = blk: {
lib/std/ascii.zig+1-1
...@@ -422,7 +422,7 @@ test "indexOfIgnoreCase" {...@@ -422,7 +422,7 @@ test "indexOfIgnoreCase" {
422422
423/// Returns the lexicographical order of two slices. O(n).423/// Returns the lexicographical order of two slices. O(n).
424pub fn orderIgnoreCase(lhs: []const u8, rhs: []const u8) std.math.Order {424pub fn orderIgnoreCase(lhs: []const u8, rhs: []const u8) std.math.Order {
425 const n = std.math.min(lhs.len, rhs.len);425 const n = @min(lhs.len, rhs.len);
426 var i: usize = 0;426 var i: usize = 0;
427 while (i < n) : (i += 1) {427 while (i < n) : (i += 1) {
428 switch (std.math.order(toLower(lhs[i]), toLower(rhs[i]))) {428 switch (std.math.order(toLower(lhs[i]), toLower(rhs[i]))) {
lib/std/compress/lzma/decode.zig+1-1
...@@ -59,7 +59,7 @@ pub const Params = struct {...@@ -59,7 +59,7 @@ pub const Params = struct {
59 const pb = @intCast(u3, props);59 const pb = @intCast(u3, props);
6060
61 const dict_size_provided = try reader.readIntLittle(u32);61 const dict_size_provided = try reader.readIntLittle(u32);
62 const dict_size = math.max(0x1000, dict_size_provided);62 const dict_size = @max(0x1000, dict_size_provided);
6363
64 const unpacked_size = switch (options.unpacked_size) {64 const unpacked_size = switch (options.unpacked_size) {
65 .read_from_header => blk: {65 .read_from_header => blk: {
lib/std/crypto/blake3.zig+4-4
...@@ -20,7 +20,7 @@ const ChunkIterator = struct {...@@ -20,7 +20,7 @@ const ChunkIterator = struct {
20 }20 }
2121
22 fn next(self: *ChunkIterator) ?[]u8 {22 fn next(self: *ChunkIterator) ?[]u8 {
23 const next_chunk = self.slice[0..math.min(self.chunk_len, self.slice.len)];23 const next_chunk = self.slice[0..@min(self.chunk_len, self.slice.len)];
24 self.slice = self.slice[next_chunk.len..];24 self.slice = self.slice[next_chunk.len..];
25 return if (next_chunk.len > 0) next_chunk else null;25 return if (next_chunk.len > 0) next_chunk else null;
26 }26 }
...@@ -283,7 +283,7 @@ const ChunkState = struct {...@@ -283,7 +283,7 @@ const ChunkState = struct {
283283
284 fn fillBlockBuf(self: *ChunkState, input: []const u8) []const u8 {284 fn fillBlockBuf(self: *ChunkState, input: []const u8) []const u8 {
285 const want = BLOCK_LEN - self.block_len;285 const want = BLOCK_LEN - self.block_len;
286 const take = math.min(want, input.len);286 const take = @min(want, input.len);
287 @memcpy(self.block[self.block_len..][0..take], input[0..take]);287 @memcpy(self.block[self.block_len..][0..take], input[0..take]);
288 self.block_len += @truncate(u8, take);288 self.block_len += @truncate(u8, take);
289 return input[take..];289 return input[take..];
...@@ -450,7 +450,7 @@ pub const Blake3 = struct {...@@ -450,7 +450,7 @@ pub const Blake3 = struct {
450450
451 // Compress input bytes into the current chunk state.451 // Compress input bytes into the current chunk state.
452 const want = CHUNK_LEN - self.chunk_state.len();452 const want = CHUNK_LEN - self.chunk_state.len();
453 const take = math.min(want, input.len);453 const take = @min(want, input.len);
454 self.chunk_state.update(input[0..take]);454 self.chunk_state.update(input[0..take]);
455 input = input[take..];455 input = input[take..];
456 }456 }
...@@ -663,7 +663,7 @@ fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) !void {...@@ -663,7 +663,7 @@ fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) !void {
663 // Write repeating input pattern to hasher663 // Write repeating input pattern to hasher
664 var input_counter = input_len;664 var input_counter = input_len;
665 while (input_counter > 0) {665 while (input_counter > 0) {
666 const update_len = math.min(input_counter, input_pattern.len);666 const update_len = @min(input_counter, input_pattern.len);
667 hasher.update(input_pattern[0..update_len]);667 hasher.update(input_pattern[0..update_len]);
668 input_counter -= update_len;668 input_counter -= update_len;
669 }669 }
lib/std/crypto/ff.zig+1-1
...@@ -570,7 +570,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type {...@@ -570,7 +570,7 @@ pub fn Modulus(comptime max_bits: comptime_int) type {
570 var out = self.zero;570 var out = self.zero;
571 var i = x.limbs_count() - 1;571 var i = x.limbs_count() - 1;
572 if (self.limbs_count() >= 2) {572 if (self.limbs_count() >= 2) {
573 const start = math.min(i, self.limbs_count() - 2);573 const start = @min(i, self.limbs_count() - 2);
574 var j = start;574 var j = start;
575 while (true) : (j -= 1) {575 while (true) : (j -= 1) {
576 out.v.limbs.set(j, x.limbs.get(i));576 out.v.limbs.set(j, x.limbs.get(i));
lib/std/crypto/ghash_polyval.zig+1-1
...@@ -363,7 +363,7 @@ fn Hash(comptime endian: std.builtin.Endian, comptime shift_key: bool) type {...@@ -363,7 +363,7 @@ fn Hash(comptime endian: std.builtin.Endian, comptime shift_key: bool) type {
363 var mb = m;363 var mb = m;
364364
365 if (st.leftover > 0) {365 if (st.leftover > 0) {
366 const want = math.min(block_length - st.leftover, mb.len);366 const want = @min(block_length - st.leftover, mb.len);
367 const mc = mb[0..want];367 const mc = mb[0..want];
368 for (mc, 0..) |x, i| {368 for (mc, 0..) |x, i| {
369 st.buf[st.leftover + i] = x;369 st.buf[st.leftover + i] = x;
lib/std/crypto/keccak_p.zig+2-2
...@@ -214,7 +214,7 @@ pub fn State(comptime f: u11, comptime capacity: u11, comptime delim: u8, compti...@@ -214,7 +214,7 @@ pub fn State(comptime f: u11, comptime capacity: u11, comptime delim: u8, compti
214 pub fn absorb(self: *Self, bytes_: []const u8) void {214 pub fn absorb(self: *Self, bytes_: []const u8) void {
215 var bytes = bytes_;215 var bytes = bytes_;
216 if (self.offset > 0) {216 if (self.offset > 0) {
217 const left = math.min(rate - self.offset, bytes.len);217 const left = @min(rate - self.offset, bytes.len);
218 @memcpy(self.buf[self.offset..][0..left], bytes[0..left]);218 @memcpy(self.buf[self.offset..][0..left], bytes[0..left]);
219 self.offset += left;219 self.offset += left;
220 if (self.offset == rate) {220 if (self.offset == rate) {
...@@ -249,7 +249,7 @@ pub fn State(comptime f: u11, comptime capacity: u11, comptime delim: u8, compti...@@ -249,7 +249,7 @@ pub fn State(comptime f: u11, comptime capacity: u11, comptime delim: u8, compti
249 pub fn squeeze(self: *Self, out: []u8) void {249 pub fn squeeze(self: *Self, out: []u8) void {
250 var i: usize = 0;250 var i: usize = 0;
251 while (i < out.len) : (i += rate) {251 while (i < out.len) : (i += rate) {
252 const left = math.min(rate, out.len - i);252 const left = @min(rate, out.len - i);
253 self.st.extractBytes(out[i..][0..left]);253 self.st.extractBytes(out[i..][0..left]);
254 self.st.permuteR(rounds);254 self.st.permuteR(rounds);
255 }255 }
lib/std/crypto/poly1305.zig+1-1
...@@ -112,7 +112,7 @@ pub const Poly1305 = struct {...@@ -112,7 +112,7 @@ pub const Poly1305 = struct {
112112
113 // handle leftover113 // handle leftover
114 if (st.leftover > 0) {114 if (st.leftover > 0) {
115 const want = std.math.min(block_length - st.leftover, mb.len);115 const want = @min(block_length - st.leftover, mb.len);
116 const mc = mb[0..want];116 const mc = mb[0..want];
117 for (mc, 0..) |x, i| {117 for (mc, 0..) |x, i| {
118 st.buf[st.leftover + i] = x;118 st.buf[st.leftover + i] = x;
lib/std/crypto/salsa20.zig+1-1
...@@ -404,7 +404,7 @@ pub const XSalsa20Poly1305 = struct {...@@ -404,7 +404,7 @@ pub const XSalsa20Poly1305 = struct {
404 debug.assert(c.len == m.len);404 debug.assert(c.len == m.len);
405 const extended = extend(rounds, k, npub);405 const extended = extend(rounds, k, npub);
406 var block0 = [_]u8{0} ** 64;406 var block0 = [_]u8{0} ** 64;
407 const mlen0 = math.min(32, c.len);407 const mlen0 = @min(32, c.len);
408 @memcpy(block0[32..][0..mlen0], c[0..mlen0]);408 @memcpy(block0[32..][0..mlen0], c[0..mlen0]);
409 Salsa20.xor(block0[0..], block0[0..], 0, extended.key, extended.nonce);409 Salsa20.xor(block0[0..], block0[0..], 0, extended.key, extended.nonce);
410 var mac = Poly1305.init(block0[0..32]);410 var mac = Poly1305.init(block0[0..32]);
lib/std/crypto/scrypt.zig+2-2
...@@ -143,7 +143,7 @@ pub const Params = struct {...@@ -143,7 +143,7 @@ pub const Params = struct {
143143
144 /// Create parameters from ops and mem limits, where mem_limit given in bytes144 /// Create parameters from ops and mem limits, where mem_limit given in bytes
145 pub fn fromLimits(ops_limit: u64, mem_limit: usize) Self {145 pub fn fromLimits(ops_limit: u64, mem_limit: usize) Self {
146 const ops = math.max(32768, ops_limit);146 const ops = @max(32768, ops_limit);
147 const r: u30 = 8;147 const r: u30 = 8;
148 if (ops < mem_limit / 32) {148 if (ops < mem_limit / 32) {
149 const max_n = ops / (r * 4);149 const max_n = ops / (r * 4);
...@@ -151,7 +151,7 @@ pub const Params = struct {...@@ -151,7 +151,7 @@ pub const Params = struct {
151 } else {151 } else {
152 const max_n = mem_limit / (@intCast(usize, r) * 128);152 const max_n = mem_limit / (@intCast(usize, r) * 128);
153 const ln = @intCast(u6, math.log2(max_n));153 const ln = @intCast(u6, math.log2(max_n));
154 const max_rp = math.min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln));154 const max_rp = @min(0x3fffffff, (ops / 4) / (@as(u64, 1) << ln));
155 return Self{ .r = r, .p = @intCast(u30, max_rp / @as(u64, r)), .ln = ln };155 return Self{ .r = r, .p = @intCast(u30, max_rp / @as(u64, r)), .ln = ln };
156 }156 }
157 }157 }
lib/std/crypto/sha3.zig+1-1
...@@ -148,7 +148,7 @@ fn ShakeLike(comptime security_level: u11, comptime delim: u8, comptime rounds:...@@ -148,7 +148,7 @@ fn ShakeLike(comptime security_level: u11, comptime delim: u8, comptime rounds:
148 if (self.offset > 0) {148 if (self.offset > 0) {
149 const left = self.buf.len - self.offset;149 const left = self.buf.len - self.offset;
150 if (left > 0) {150 if (left > 0) {
151 const n = math.min(left, out.len);151 const n = @min(left, out.len);
152 @memcpy(out[0..n], self.buf[self.offset..][0..n]);152 @memcpy(out[0..n], self.buf[self.offset..][0..n]);
153 out = out[n..];153 out = out[n..];
154 self.offset += n;154 self.offset += n;
lib/std/crypto/siphash.zig+1-1
...@@ -433,7 +433,7 @@ test "iterative non-divisible update" {...@@ -433,7 +433,7 @@ test "iterative non-divisible update" {
433 var siphash = Siphash.init(key);433 var siphash = Siphash.init(key);
434 var i: usize = 0;434 var i: usize = 0;
435 while (i < end) : (i += 7) {435 while (i < end) : (i += 7) {
436 siphash.update(buf[i..std.math.min(i + 7, end)]);436 siphash.update(buf[i..@min(i + 7, end)]);
437 }437 }
438 const iterative_hash = siphash.finalInt();438 const iterative_hash = siphash.finalInt();
439439
lib/std/debug.zig+2-2
...@@ -198,7 +198,7 @@ pub fn captureStackTrace(first_address: ?usize, stack_trace: *std.builtin.StackT...@@ -198,7 +198,7 @@ pub fn captureStackTrace(first_address: ?usize, stack_trace: *std.builtin.StackT
198 stack_trace.index = 0;198 stack_trace.index = 0;
199 return;199 return;
200 };200 };
201 const end_index = math.min(first_index + addrs.len, n);201 const end_index = @min(first_index + addrs.len, n);
202 const slice = addr_buf[first_index..end_index];202 const slice = addr_buf[first_index..end_index];
203 // We use a for loop here because slice and addrs may alias.203 // We use a for loop here because slice and addrs may alias.
204 for (slice, 0..) |addr, i| {204 for (slice, 0..) |addr, i| {
...@@ -380,7 +380,7 @@ pub fn writeStackTrace(...@@ -380,7 +380,7 @@ pub fn writeStackTrace(
380 _ = allocator;380 _ = allocator;
381 if (builtin.strip_debug_info) return error.MissingDebugInfo;381 if (builtin.strip_debug_info) return error.MissingDebugInfo;
382 var frame_index: usize = 0;382 var frame_index: usize = 0;
383 var frames_left: usize = std.math.min(stack_trace.index, stack_trace.instruction_addresses.len);383 var frames_left: usize = @min(stack_trace.index, stack_trace.instruction_addresses.len);
384384
385 while (frames_left != 0) : ({385 while (frames_left != 0) : ({
386 frames_left -= 1;386 frames_left -= 1;
lib/std/dynamic_library.zig+1-2
...@@ -8,7 +8,6 @@ const elf = std.elf;...@@ -8,7 +8,6 @@ const elf = std.elf;
8const windows = std.os.windows;8const windows = std.os.windows;
9const system = std.os.system;9const system = std.os.system;
10const maxInt = std.math.maxInt;10const maxInt = std.math.maxInt;
11const max = std.math.max;
1211
13pub const DynLib = switch (builtin.os.tag) {12pub const DynLib = switch (builtin.os.tag) {
14 .linux => if (builtin.link_libc) DlDynlib else ElfDynLib,13 .linux => if (builtin.link_libc) DlDynlib else ElfDynLib,
...@@ -152,7 +151,7 @@ pub const ElfDynLib = struct {...@@ -152,7 +151,7 @@ pub const ElfDynLib = struct {
152 }) {151 }) {
153 const ph = @intToPtr(*elf.Phdr, ph_addr);152 const ph = @intToPtr(*elf.Phdr, ph_addr);
154 switch (ph.p_type) {153 switch (ph.p_type) {
155 elf.PT_LOAD => virt_addr_end = max(virt_addr_end, ph.p_vaddr + ph.p_memsz),154 elf.PT_LOAD => virt_addr_end = @max(virt_addr_end, ph.p_vaddr + ph.p_memsz),
156 elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, elf_addr + ph.p_offset),155 elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, elf_addr + ph.p_offset),
157 else => {},156 else => {},
158 }157 }
lib/std/event/loop.zig+1-1
...@@ -179,7 +179,7 @@ pub const Loop = struct {...@@ -179,7 +179,7 @@ pub const Loop = struct {
179179
180 // We need at least one of these in case the fs thread wants to use onNextTick180 // We need at least one of these in case the fs thread wants to use onNextTick
181 const extra_thread_count = thread_count - 1;181 const extra_thread_count = thread_count - 1;
182 const resume_node_count = std.math.max(extra_thread_count, 1);182 const resume_node_count = @max(extra_thread_count, 1);
183 self.eventfd_resume_nodes = try self.arena.allocator().alloc(183 self.eventfd_resume_nodes = try self.arena.allocator().alloc(
184 std.atomic.Stack(ResumeNode.EventFd).Node,184 std.atomic.Stack(ResumeNode.EventFd).Node,
185 resume_node_count,185 resume_node_count,
lib/std/fifo.zig+1-1
...@@ -150,7 +150,7 @@ pub fn LinearFifo(...@@ -150,7 +150,7 @@ pub fn LinearFifo(
150 start -= self.buf.len;150 start -= self.buf.len;
151 return self.buf[start .. start + (self.count - offset)];151 return self.buf[start .. start + (self.count - offset)];
152 } else {152 } else {
153 const end = math.min(self.head + self.count, self.buf.len);153 const end = @min(self.head + self.count, self.buf.len);
154 return self.buf[start..end];154 return self.buf[start..end];
155 }155 }
156 }156 }
lib/std/fmt.zig+9-9
...@@ -921,8 +921,8 @@ fn formatSizeImpl(comptime base: comptime_int) type {...@@ -921,8 +921,8 @@ fn formatSizeImpl(comptime base: comptime_int) type {
921921
922 const log2 = math.log2(value);922 const log2 = math.log2(value);
923 const magnitude = switch (base) {923 const magnitude = switch (base) {
924 1000 => math.min(log2 / comptime math.log2(1000), mags_si.len - 1),924 1000 => @min(log2 / comptime math.log2(1000), mags_si.len - 1),
925 1024 => math.min(log2 / 10, mags_iec.len - 1),925 1024 => @min(log2 / 10, mags_iec.len - 1),
926 else => unreachable,926 else => unreachable,
927 };927 };
928 const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, base), lossyCast(f64, magnitude));928 const new_value = lossyCast(f64, value) / math.pow(f64, lossyCast(f64, base), lossyCast(f64, magnitude));
...@@ -1103,7 +1103,7 @@ pub fn formatFloatScientific(...@@ -1103,7 +1103,7 @@ pub fn formatFloatScientific(
11031103
1104 var printed: usize = 0;1104 var printed: usize = 0;
1105 if (float_decimal.digits.len > 1) {1105 if (float_decimal.digits.len > 1) {
1106 const num_digits = math.min(float_decimal.digits.len, precision + 1);1106 const num_digits = @min(float_decimal.digits.len, precision + 1);
1107 try writer.writeAll(float_decimal.digits[1..num_digits]);1107 try writer.writeAll(float_decimal.digits[1..num_digits]);
1108 printed += num_digits - 1;1108 printed += num_digits - 1;
1109 }1109 }
...@@ -1116,7 +1116,7 @@ pub fn formatFloatScientific(...@@ -1116,7 +1116,7 @@ pub fn formatFloatScientific(
1116 try writer.writeAll(float_decimal.digits[0..1]);1116 try writer.writeAll(float_decimal.digits[0..1]);
1117 try writer.writeAll(".");1117 try writer.writeAll(".");
1118 if (float_decimal.digits.len > 1) {1118 if (float_decimal.digits.len > 1) {
1119 const num_digits = if (@TypeOf(value) == f32) math.min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len;1119 const num_digits = if (@TypeOf(value) == f32) @min(@as(usize, 9), float_decimal.digits.len) else float_decimal.digits.len;
11201120
1121 try writer.writeAll(float_decimal.digits[1..num_digits]);1121 try writer.writeAll(float_decimal.digits[1..num_digits]);
1122 } else {1122 } else {
...@@ -1299,7 +1299,7 @@ pub fn formatFloatDecimal(...@@ -1299,7 +1299,7 @@ pub fn formatFloatDecimal(
1299 var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0;1299 var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0;
13001300
1301 // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this.1301 // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this.
1302 var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len);1302 var num_digits_whole_no_pad = @min(num_digits_whole, float_decimal.digits.len);
13031303
1304 if (num_digits_whole > 0) {1304 if (num_digits_whole > 0) {
1305 // We may have to zero pad, for instance 1e4 requires zero padding.1305 // We may have to zero pad, for instance 1e4 requires zero padding.
...@@ -1326,7 +1326,7 @@ pub fn formatFloatDecimal(...@@ -1326,7 +1326,7 @@ pub fn formatFloatDecimal(
1326 // Zero-fill until we reach significant digits or run out of precision.1326 // Zero-fill until we reach significant digits or run out of precision.
1327 if (float_decimal.exp <= 0) {1327 if (float_decimal.exp <= 0) {
1328 const zero_digit_count = @intCast(usize, -float_decimal.exp);1328 const zero_digit_count = @intCast(usize, -float_decimal.exp);
1329 const zeros_to_print = math.min(zero_digit_count, precision);1329 const zeros_to_print = @min(zero_digit_count, precision);
13301330
1331 var i: usize = 0;1331 var i: usize = 0;
1332 while (i < zeros_to_print) : (i += 1) {1332 while (i < zeros_to_print) : (i += 1) {
...@@ -1357,7 +1357,7 @@ pub fn formatFloatDecimal(...@@ -1357,7 +1357,7 @@ pub fn formatFloatDecimal(
1357 var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0;1357 var num_digits_whole = if (float_decimal.exp > 0) @intCast(usize, float_decimal.exp) else 0;
13581358
1359 // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this.1359 // the actual slice into the buffer, we may need to zero-pad between num_digits_whole and this.
1360 var num_digits_whole_no_pad = math.min(num_digits_whole, float_decimal.digits.len);1360 var num_digits_whole_no_pad = @min(num_digits_whole, float_decimal.digits.len);
13611361
1362 if (num_digits_whole > 0) {1362 if (num_digits_whole > 0) {
1363 // We may have to zero pad, for instance 1e4 requires zero padding.1363 // We may have to zero pad, for instance 1e4 requires zero padding.
...@@ -1410,12 +1410,12 @@ pub fn formatInt(...@@ -1410,12 +1410,12 @@ pub fn formatInt(
14101410
1411 // The type must have the same size as `base` or be wider in order for the1411 // The type must have the same size as `base` or be wider in order for the
1412 // division to work1412 // division to work
1413 const min_int_bits = comptime math.max(value_info.bits, 8);1413 const min_int_bits = comptime @max(value_info.bits, 8);
1414 const MinInt = std.meta.Int(.unsigned, min_int_bits);1414 const MinInt = std.meta.Int(.unsigned, min_int_bits);
14151415
1416 const abs_value = math.absCast(int_value);1416 const abs_value = math.absCast(int_value);
1417 // The worst case in terms of space needed is base 2, plus 1 for the sign1417 // The worst case in terms of space needed is base 2, plus 1 for the sign
1418 var buf: [1 + math.max(value_info.bits, 1)]u8 = undefined;1418 var buf: [1 + @max(@as(comptime_int, value_info.bits), 1)]u8 = undefined;
14191419
1420 var a: MinInt = abs_value;1420 var a: MinInt = abs_value;
1421 var index: usize = buf.len;1421 var index: usize = buf.len;
lib/std/hash/wyhash.zig+1-1
...@@ -252,7 +252,7 @@ test "iterative non-divisible update" {...@@ -252,7 +252,7 @@ test "iterative non-divisible update" {
252 var wy = Wyhash.init(seed);252 var wy = Wyhash.init(seed);
253 var i: usize = 0;253 var i: usize = 0;
254 while (i < end) : (i += 33) {254 while (i < end) : (i += 33) {
255 wy.update(buf[i..std.math.min(i + 33, end)]);255 wy.update(buf[i..@min(i + 33, end)]);
256 }256 }
257 const iterative_hash = wy.final();257 const iterative_hash = wy.final();
258258
lib/std/hash_map.zig+3-3
...@@ -1507,7 +1507,7 @@ pub fn HashMapUnmanaged(...@@ -1507,7 +1507,7 @@ pub fn HashMapUnmanaged(
15071507
1508 fn grow(self: *Self, allocator: Allocator, new_capacity: Size, ctx: Context) Allocator.Error!void {1508 fn grow(self: *Self, allocator: Allocator, new_capacity: Size, ctx: Context) Allocator.Error!void {
1509 @setCold(true);1509 @setCold(true);
1510 const new_cap = std.math.max(new_capacity, minimal_capacity);1510 const new_cap = @max(new_capacity, minimal_capacity);
1511 assert(new_cap > self.capacity());1511 assert(new_cap > self.capacity());
1512 assert(std.math.isPowerOfTwo(new_cap));1512 assert(std.math.isPowerOfTwo(new_cap));
15131513
...@@ -1540,7 +1540,7 @@ pub fn HashMapUnmanaged(...@@ -1540,7 +1540,7 @@ pub fn HashMapUnmanaged(
1540 const header_align = @alignOf(Header);1540 const header_align = @alignOf(Header);
1541 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);1541 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);
1542 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);1542 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);
1543 const max_align = comptime math.max3(header_align, key_align, val_align);1543 const max_align = comptime @max(header_align, key_align, val_align);
15441544
1545 const meta_size = @sizeOf(Header) + new_capacity * @sizeOf(Metadata);1545 const meta_size = @sizeOf(Header) + new_capacity * @sizeOf(Metadata);
1546 comptime assert(@alignOf(Metadata) == 1);1546 comptime assert(@alignOf(Metadata) == 1);
...@@ -1575,7 +1575,7 @@ pub fn HashMapUnmanaged(...@@ -1575,7 +1575,7 @@ pub fn HashMapUnmanaged(
1575 const header_align = @alignOf(Header);1575 const header_align = @alignOf(Header);
1576 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);1576 const key_align = if (@sizeOf(K) == 0) 1 else @alignOf(K);
1577 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);1577 const val_align = if (@sizeOf(V) == 0) 1 else @alignOf(V);
1578 const max_align = comptime math.max3(header_align, key_align, val_align);1578 const max_align = comptime @max(header_align, key_align, val_align);
15791579
1580 const cap = self.capacity();1580 const cap = self.capacity();
1581 const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata);1581 const meta_size = @sizeOf(Header) + cap * @sizeOf(Metadata);
lib/std/heap/arena_allocator.zig+1-1
...@@ -110,7 +110,7 @@ pub const ArenaAllocator = struct {...@@ -110,7 +110,7 @@ pub const ArenaAllocator = struct {
110 // value.110 // value.
111 const requested_capacity = switch (mode) {111 const requested_capacity = switch (mode) {
112 .retain_capacity => self.queryCapacity(),112 .retain_capacity => self.queryCapacity(),
113 .retain_with_limit => |limit| std.math.min(limit, self.queryCapacity()),113 .retain_with_limit => |limit| @min(limit, self.queryCapacity()),
114 .free_all => 0,114 .free_all => 0,
115 };115 };
116 if (requested_capacity == 0) {116 if (requested_capacity == 0) {
lib/std/heap/memory_pool.zig+2-2
...@@ -40,11 +40,11 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type...@@ -40,11 +40,11 @@ pub fn MemoryPoolExtra(comptime Item: type, comptime pool_options: Options) type
4040
41 /// Size of the memory pool items. This is not necessarily the same41 /// Size of the memory pool items. This is not necessarily the same
42 /// as `@sizeOf(Item)` as the pool also uses the items for internal means.42 /// as `@sizeOf(Item)` as the pool also uses the items for internal means.
43 pub const item_size = std.math.max(@sizeOf(Node), @sizeOf(Item));43 pub const item_size = @max(@sizeOf(Node), @sizeOf(Item));
4444
45 /// Alignment of the memory pool items. This is not necessarily the same45 /// Alignment of the memory pool items. This is not necessarily the same
46 /// as `@alignOf(Item)` as the pool also uses the items for internal means.46 /// as `@alignOf(Item)` as the pool also uses the items for internal means.
47 pub const item_alignment = std.math.max(@alignOf(Node), pool_options.alignment orelse 0);47 pub const item_alignment = @max(@alignOf(Node), pool_options.alignment orelse 0);
4848
49 const Node = struct {49 const Node = struct {
50 next: ?*@This(),50 next: ?*@This(),
lib/std/http/protocol.zig+1-1
...@@ -82,7 +82,7 @@ pub const HeadersParser = struct {...@@ -82,7 +82,7 @@ pub const HeadersParser = struct {
82 /// If the amount returned is less than `bytes.len`, you may assume that the parser is in a content state and the82 /// If the amount returned is less than `bytes.len`, you may assume that the parser is in a content state and the
83 /// first byte of content is located at `bytes[result]`.83 /// first byte of content is located at `bytes[result]`.
84 pub fn findHeadersEnd(r: *HeadersParser, bytes: []const u8) u32 {84 pub fn findHeadersEnd(r: *HeadersParser, bytes: []const u8) u32 {
85 const vector_len: comptime_int = comptime std.math.max(std.simd.suggestVectorSize(u8) orelse 1, 8);85 const vector_len: comptime_int = comptime @max(std.simd.suggestVectorSize(u8) orelse 1, 8);
86 const len = @intCast(u32, bytes.len);86 const len = @intCast(u32, bytes.len);
87 var index: u32 = 0;87 var index: u32 = 0;
8888
lib/std/io/fixed_buffer_stream.zig+2-2
...@@ -76,7 +76,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type {...@@ -76,7 +76,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
76 }76 }
7777
78 pub fn seekTo(self: *Self, pos: u64) SeekError!void {78 pub fn seekTo(self: *Self, pos: u64) SeekError!void {
79 self.pos = if (std.math.cast(usize, pos)) |x| std.math.min(self.buffer.len, x) else self.buffer.len;79 self.pos = if (std.math.cast(usize, pos)) |x| @min(self.buffer.len, x) else self.buffer.len;
80 }80 }
8181
82 pub fn seekBy(self: *Self, amt: i64) SeekError!void {82 pub fn seekBy(self: *Self, amt: i64) SeekError!void {
...@@ -91,7 +91,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type {...@@ -91,7 +91,7 @@ pub fn FixedBufferStream(comptime Buffer: type) type {
91 } else {91 } else {
92 const amt_usize = std.math.cast(usize, amt) orelse std.math.maxInt(usize);92 const amt_usize = std.math.cast(usize, amt) orelse std.math.maxInt(usize);
93 const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize);93 const new_pos = std.math.add(usize, self.pos, amt_usize) catch std.math.maxInt(usize);
94 self.pos = std.math.min(self.buffer.len, new_pos);94 self.pos = @min(self.buffer.len, new_pos);
95 }95 }
96 }96 }
9797
lib/std/io/limited_reader.zig+1-1
...@@ -14,7 +14,7 @@ pub fn LimitedReader(comptime ReaderType: type) type {...@@ -14,7 +14,7 @@ pub fn LimitedReader(comptime ReaderType: type) type {
14 const Self = @This();14 const Self = @This();
1515
16 pub fn read(self: *Self, dest: []u8) Error!usize {16 pub fn read(self: *Self, dest: []u8) Error!usize {
17 const max_read = std.math.min(self.bytes_left, dest.len);17 const max_read = @min(self.bytes_left, dest.len);
18 const n = try self.inner_reader.read(dest[0..max_read]);18 const n = try self.inner_reader.read(dest[0..max_read]);
19 self.bytes_left -= n;19 self.bytes_left -= n;
20 return n;20 return n;
lib/std/io/reader.zig+1-1
...@@ -325,7 +325,7 @@ pub fn Reader(...@@ -325,7 +325,7 @@ pub fn Reader(
325 var remaining = num_bytes;325 var remaining = num_bytes;
326326
327 while (remaining > 0) {327 while (remaining > 0) {
328 const amt = std.math.min(remaining, options.buf_size);328 const amt = @min(remaining, options.buf_size);
329 try self.readNoEof(buf[0..amt]);329 try self.readNoEof(buf[0..amt]);
330 remaining -= amt;330 remaining -= amt;
331 }331 }
lib/std/io/writer.zig+1-1
...@@ -39,7 +39,7 @@ pub fn Writer(...@@ -39,7 +39,7 @@ pub fn Writer(
3939
40 var remaining: usize = n;40 var remaining: usize = n;
41 while (remaining > 0) {41 while (remaining > 0) {
42 const to_write = std.math.min(remaining, bytes.len);42 const to_write = @min(remaining, bytes.len);
43 try self.writeAll(bytes[0..to_write]);43 try self.writeAll(bytes[0..to_write]);
44 remaining -= to_write;44 remaining -= to_write;
45 }45 }
lib/std/math.zig+7-96
...@@ -165,7 +165,7 @@ pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool {...@@ -165,7 +165,7 @@ pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool {
165 if (isNan(x) or isNan(y))165 if (isNan(x) or isNan(y))
166 return false;166 return false;
167167
168 return @fabs(x - y) <= max(@fabs(x), @fabs(y)) * tolerance;168 return @fabs(x - y) <= @max(@fabs(x), @fabs(y)) * tolerance;
169}169}
170170
171test "approxEqAbs and approxEqRel" {171test "approxEqAbs and approxEqRel" {
...@@ -434,104 +434,15 @@ pub fn Min(comptime A: type, comptime B: type) type {...@@ -434,104 +434,15 @@ pub fn Min(comptime A: type, comptime B: type) type {
434 return @TypeOf(@as(A, 0) + @as(B, 0));434 return @TypeOf(@as(A, 0) + @as(B, 0));
435}435}
436436
437/// Returns the smaller number. When one parameter's type's full range437pub const min = @compileError("deprecated; use @min instead");
438/// fits in the other, the return type is the smaller type.438pub const max = @compileError("deprecated; use @max instead");
439pub fn min(x: anytype, y: anytype) Min(@TypeOf(x), @TypeOf(y)) {439pub const min3 = @compileError("deprecated; use @min instead");
440 const Result = Min(@TypeOf(x), @TypeOf(y));440pub const max3 = @compileError("deprecated; use @max instead");
441 if (x < y) {
442 // TODO Zig should allow this as an implicit cast because x is
443 // immutable and in this scope it is known to fit in the
444 // return type.
445 switch (@typeInfo(Result)) {
446 .Int => return @intCast(Result, x),
447 else => return x,
448 }
449 } else {
450 // TODO Zig should allow this as an implicit cast because y is
451 // immutable and in this scope it is known to fit in the
452 // return type.
453 switch (@typeInfo(Result)) {
454 .Int => return @intCast(Result, y),
455 else => return y,
456 }
457 }
458}
459
460test "min" {
461 try testing.expect(min(@as(i32, -1), @as(i32, 2)) == -1);
462 {
463 var a: u16 = 999;
464 var b: u32 = 10;
465 var result = min(a, b);
466 try testing.expect(@TypeOf(result) == u16);
467 try testing.expect(result == 10);
468 }
469 {
470 var a: f64 = 10.34;
471 var b: f32 = 999.12;
472 var result = min(a, b);
473 try testing.expect(@TypeOf(result) == f64);
474 try testing.expect(result == 10.34);
475 }
476 {
477 var a: i8 = -127;
478 var b: i16 = -200;
479 var result = min(a, b);
480 try testing.expect(@TypeOf(result) == i16);
481 try testing.expect(result == -200);
482 }
483 {
484 const a = 10.34;
485 var b: f32 = 999.12;
486 var result = min(a, b);
487 try testing.expect(@TypeOf(result) == f32);
488 try testing.expect(result == 10.34);
489 }
490}
491
492/// Finds the minimum of three numbers.
493pub fn min3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) {
494 return min(x, min(y, z));
495}
496
497test "min3" {
498 try testing.expect(min3(@as(i32, 0), @as(i32, 1), @as(i32, 2)) == 0);
499 try testing.expect(min3(@as(i32, 0), @as(i32, 2), @as(i32, 1)) == 0);
500 try testing.expect(min3(@as(i32, 1), @as(i32, 0), @as(i32, 2)) == 0);
501 try testing.expect(min3(@as(i32, 1), @as(i32, 2), @as(i32, 0)) == 0);
502 try testing.expect(min3(@as(i32, 2), @as(i32, 0), @as(i32, 1)) == 0);
503 try testing.expect(min3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 0);
504}
505
506/// Returns the maximum of two numbers. Return type is the one with the
507/// larger range.
508pub fn max(x: anytype, y: anytype) @TypeOf(x, y) {
509 return if (x > y) x else y;
510}
511
512test "max" {
513 try testing.expect(max(@as(i32, -1), @as(i32, 2)) == 2);
514 try testing.expect(max(@as(i32, 2), @as(i32, -1)) == 2);
515}
516
517/// Finds the maximum of three numbers.
518pub fn max3(x: anytype, y: anytype, z: anytype) @TypeOf(x, y, z) {
519 return max(x, max(y, z));
520}
521
522test "max3" {
523 try testing.expect(max3(@as(i32, 0), @as(i32, 1), @as(i32, 2)) == 2);
524 try testing.expect(max3(@as(i32, 0), @as(i32, 2), @as(i32, 1)) == 2);
525 try testing.expect(max3(@as(i32, 1), @as(i32, 0), @as(i32, 2)) == 2);
526 try testing.expect(max3(@as(i32, 1), @as(i32, 2), @as(i32, 0)) == 2);
527 try testing.expect(max3(@as(i32, 2), @as(i32, 0), @as(i32, 1)) == 2);
528 try testing.expect(max3(@as(i32, 2), @as(i32, 1), @as(i32, 0)) == 2);
529}
530441
531/// Limit val to the inclusive range [lower, upper].442/// Limit val to the inclusive range [lower, upper].
532pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {443pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, upper) {
533 assert(lower <= upper);444 assert(lower <= upper);
534 return max(lower, min(val, upper));445 return @max(lower, @min(val, upper));
535}446}
536test "clamp" {447test "clamp" {
537 // Within range448 // Within range
...@@ -795,7 +706,7 @@ pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) t...@@ -795,7 +706,7 @@ pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) t
795 return u0;706 return u0;
796 }707 }
797 const signedness: std.builtin.Signedness = if (from < 0) .signed else .unsigned;708 const signedness: std.builtin.Signedness = if (from < 0) .signed else .unsigned;
798 const largest_positive_integer = max(if (from < 0) (-from) - 1 else from, to); // two's complement709 const largest_positive_integer = @max(if (from < 0) (-from) - 1 else from, to); // two's complement
799 const base = log2(largest_positive_integer);710 const base = log2(largest_positive_integer);
800 const upper = (1 << base) - 1;711 const upper = (1 << base) - 1;
801 var magnitude_bits = if (upper >= largest_positive_integer) base else base + 1;712 var magnitude_bits = if (upper >= largest_positive_integer) base else base + 1;
lib/std/math/big/int.zig+48-48
...@@ -44,12 +44,12 @@ pub fn calcDivLimbsBufferLen(a_len: usize, b_len: usize) usize {...@@ -44,12 +44,12 @@ pub fn calcDivLimbsBufferLen(a_len: usize, b_len: usize) usize {
44}44}
4545
46pub fn calcMulLimbsBufferLen(a_len: usize, b_len: usize, aliases: usize) usize {46pub fn calcMulLimbsBufferLen(a_len: usize, b_len: usize, aliases: usize) usize {
47 return aliases * math.max(a_len, b_len);47 return aliases * @max(a_len, b_len);
48}48}
4949
50pub fn calcMulWrapLimbsBufferLen(bit_count: usize, a_len: usize, b_len: usize, aliases: usize) usize {50pub fn calcMulWrapLimbsBufferLen(bit_count: usize, a_len: usize, b_len: usize, aliases: usize) usize {
51 const req_limbs = calcTwosCompLimbCount(bit_count);51 const req_limbs = calcTwosCompLimbCount(bit_count);
52 return aliases * math.min(req_limbs, math.max(a_len, b_len));52 return aliases * @min(req_limbs, @max(a_len, b_len));
53}53}
5454
55pub fn calcSetStringLimbsBufferLen(base: u8, string_len: usize) usize {55pub fn calcSetStringLimbsBufferLen(base: u8, string_len: usize) usize {
...@@ -396,7 +396,7 @@ pub const Mutable = struct {...@@ -396,7 +396,7 @@ pub const Mutable = struct {
396 /// scalar is a primitive integer type.396 /// scalar is a primitive integer type.
397 ///397 ///
398 /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by398 /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by
399 /// r is `math.max(a.limbs.len, calcLimbLen(scalar)) + 1`.399 /// r is `@max(a.limbs.len, calcLimbLen(scalar)) + 1`.
400 pub fn addScalar(r: *Mutable, a: Const, scalar: anytype) void {400 pub fn addScalar(r: *Mutable, a: Const, scalar: anytype) void {
401 // Normally we could just determine the number of limbs needed with calcLimbLen,401 // Normally we could just determine the number of limbs needed with calcLimbLen,
402 // but that is not comptime-known when scalar is not a comptime_int. Instead, we402 // but that is not comptime-known when scalar is not a comptime_int. Instead, we
...@@ -414,11 +414,11 @@ pub const Mutable = struct {...@@ -414,11 +414,11 @@ pub const Mutable = struct {
414 return add(r, a, operand);414 return add(r, a, operand);
415 }415 }
416416
417 /// Base implementation for addition. Adds `max(a.limbs.len, b.limbs.len)` elements from a and b,417 /// Base implementation for addition. Adds `@max(a.limbs.len, b.limbs.len)` elements from a and b,
418 /// and returns whether any overflow occurred.418 /// and returns whether any overflow occurred.
419 /// r, a and b may be aliases.419 /// r, a and b may be aliases.
420 ///420 ///
421 /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`.421 /// Asserts r has enough elements to hold the result. The upper bound is `@max(a.limbs.len, b.limbs.len)`.
422 fn addCarry(r: *Mutable, a: Const, b: Const) bool {422 fn addCarry(r: *Mutable, a: Const, b: Const) bool {
423 if (a.eqZero()) {423 if (a.eqZero()) {
424 r.copy(b);424 r.copy(b);
...@@ -452,12 +452,12 @@ pub const Mutable = struct {...@@ -452,12 +452,12 @@ pub const Mutable = struct {
452 /// r, a and b may be aliases.452 /// r, a and b may be aliases.
453 ///453 ///
454 /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by454 /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by
455 /// r is `math.max(a.limbs.len, b.limbs.len) + 1`.455 /// r is `@max(a.limbs.len, b.limbs.len) + 1`.
456 pub fn add(r: *Mutable, a: Const, b: Const) void {456 pub fn add(r: *Mutable, a: Const, b: Const) void {
457 if (r.addCarry(a, b)) {457 if (r.addCarry(a, b)) {
458 // Fix up the result. Note that addCarry normalizes by a.limbs.len or b.limbs.len,458 // Fix up the result. Note that addCarry normalizes by a.limbs.len or b.limbs.len,
459 // so we need to set the length here.459 // so we need to set the length here.
460 const msl = math.max(a.limbs.len, b.limbs.len);460 const msl = @max(a.limbs.len, b.limbs.len);
461 // `[add|sub]Carry` normalizes by `msl`, so we need to fix up the result manually here.461 // `[add|sub]Carry` normalizes by `msl`, so we need to fix up the result manually here.
462 // Note, the fact that it normalized means that the intermediary limbs are zero here.462 // Note, the fact that it normalized means that the intermediary limbs are zero here.
463 r.len = msl + 1;463 r.len = msl + 1;
...@@ -477,12 +477,12 @@ pub const Mutable = struct {...@@ -477,12 +477,12 @@ pub const Mutable = struct {
477 // if an overflow occurred.477 // if an overflow occurred.
478 const x = Const{478 const x = Const{
479 .positive = a.positive,479 .positive = a.positive,
480 .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)],480 .limbs = a.limbs[0..@min(req_limbs, a.limbs.len)],
481 };481 };
482482
483 const y = Const{483 const y = Const{
484 .positive = b.positive,484 .positive = b.positive,
485 .limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)],485 .limbs = b.limbs[0..@min(req_limbs, b.limbs.len)],
486 };486 };
487487
488 var carry_truncated = false;488 var carry_truncated = false;
...@@ -492,7 +492,7 @@ pub const Mutable = struct {...@@ -492,7 +492,7 @@ pub const Mutable = struct {
492 // truncate anyway.492 // truncate anyway.
493 // - a and b had less elements than req_limbs, and those were overflowed. This case needs to be handled.493 // - a and b had less elements than req_limbs, and those were overflowed. This case needs to be handled.
494 // Note: after this we still might need to wrap.494 // Note: after this we still might need to wrap.
495 const msl = math.max(a.limbs.len, b.limbs.len);495 const msl = @max(a.limbs.len, b.limbs.len);
496 if (msl < req_limbs) {496 if (msl < req_limbs) {
497 r.limbs[msl] = 1;497 r.limbs[msl] = 1;
498 r.len = req_limbs;498 r.len = req_limbs;
...@@ -522,12 +522,12 @@ pub const Mutable = struct {...@@ -522,12 +522,12 @@ pub const Mutable = struct {
522 // if an overflow occurred.522 // if an overflow occurred.
523 const x = Const{523 const x = Const{
524 .positive = a.positive,524 .positive = a.positive,
525 .limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)],525 .limbs = a.limbs[0..@min(req_limbs, a.limbs.len)],
526 };526 };
527527
528 const y = Const{528 const y = Const{
529 .positive = b.positive,529 .positive = b.positive,
530 .limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)],530 .limbs = b.limbs[0..@min(req_limbs, b.limbs.len)],
531 };531 };
532532
533 if (r.addCarry(x, y)) {533 if (r.addCarry(x, y)) {
...@@ -535,7 +535,7 @@ pub const Mutable = struct {...@@ -535,7 +535,7 @@ pub const Mutable = struct {
535 // - We overflowed req_limbs, in which case we need to saturate.535 // - We overflowed req_limbs, in which case we need to saturate.
536 // - a and b had less elements than req_limbs, and those were overflowed.536 // - a and b had less elements than req_limbs, and those were overflowed.
537 // Note: In this case, might _also_ need to saturate.537 // Note: In this case, might _also_ need to saturate.
538 const msl = math.max(a.limbs.len, b.limbs.len);538 const msl = @max(a.limbs.len, b.limbs.len);
539 if (msl < req_limbs) {539 if (msl < req_limbs) {
540 r.limbs[msl] = 1;540 r.limbs[msl] = 1;
541 r.len = req_limbs;541 r.len = req_limbs;
...@@ -550,11 +550,11 @@ pub const Mutable = struct {...@@ -550,11 +550,11 @@ pub const Mutable = struct {
550 r.saturate(r.toConst(), signedness, bit_count);550 r.saturate(r.toConst(), signedness, bit_count);
551 }551 }
552552
553 /// Base implementation for subtraction. Subtracts `max(a.limbs.len, b.limbs.len)` elements from a and b,553 /// Base implementation for subtraction. Subtracts `@max(a.limbs.len, b.limbs.len)` elements from a and b,
554 /// and returns whether any overflow occurred.554 /// and returns whether any overflow occurred.
555 /// r, a and b may be aliases.555 /// r, a and b may be aliases.
556 ///556 ///
557 /// Asserts r has enough elements to hold the result. The upper bound is `max(a.limbs.len, b.limbs.len)`.557 /// Asserts r has enough elements to hold the result. The upper bound is `@max(a.limbs.len, b.limbs.len)`.
558 fn subCarry(r: *Mutable, a: Const, b: Const) bool {558 fn subCarry(r: *Mutable, a: Const, b: Const) bool {
559 if (a.eqZero()) {559 if (a.eqZero()) {
560 r.copy(b);560 r.copy(b);
...@@ -607,7 +607,7 @@ pub const Mutable = struct {...@@ -607,7 +607,7 @@ pub const Mutable = struct {
607 /// r, a and b may be aliases.607 /// r, a and b may be aliases.
608 ///608 ///
609 /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by609 /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by
610 /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. The +1 is not needed if both operands are positive.610 /// r is `@max(a.limbs.len, b.limbs.len) + 1`. The +1 is not needed if both operands are positive.
611 pub fn sub(r: *Mutable, a: Const, b: Const) void {611 pub fn sub(r: *Mutable, a: Const, b: Const) void {
612 r.add(a, b.negate());612 r.add(a, b.negate());
613 }613 }
...@@ -714,7 +714,7 @@ pub const Mutable = struct {...@@ -714,7 +714,7 @@ pub const Mutable = struct {
714714
715 const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: {715 const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: {
716 const start = buf_index;716 const start = buf_index;
717 const a_len = math.min(req_limbs, a.limbs.len);717 const a_len = @min(req_limbs, a.limbs.len);
718 @memcpy(limbs_buffer[buf_index..][0..a_len], a.limbs[0..a_len]);718 @memcpy(limbs_buffer[buf_index..][0..a_len], a.limbs[0..a_len]);
719 buf_index += a_len;719 buf_index += a_len;
720 break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst();720 break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst();
...@@ -722,7 +722,7 @@ pub const Mutable = struct {...@@ -722,7 +722,7 @@ pub const Mutable = struct {
722722
723 const b_copy = if (rma.limbs.ptr == b.limbs.ptr) blk: {723 const b_copy = if (rma.limbs.ptr == b.limbs.ptr) blk: {
724 const start = buf_index;724 const start = buf_index;
725 const b_len = math.min(req_limbs, b.limbs.len);725 const b_len = @min(req_limbs, b.limbs.len);
726 @memcpy(limbs_buffer[buf_index..][0..b_len], b.limbs[0..b_len]);726 @memcpy(limbs_buffer[buf_index..][0..b_len], b.limbs[0..b_len]);
727 buf_index += b_len;727 buf_index += b_len;
728 break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst();728 break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst();
...@@ -755,13 +755,13 @@ pub const Mutable = struct {...@@ -755,13 +755,13 @@ pub const Mutable = struct {
755 const req_limbs = calcTwosCompLimbCount(bit_count);755 const req_limbs = calcTwosCompLimbCount(bit_count);
756756
757 // We can ignore the upper bits here, those results will be discarded anyway.757 // We can ignore the upper bits here, those results will be discarded anyway.
758 const a_limbs = a.limbs[0..math.min(req_limbs, a.limbs.len)];758 const a_limbs = a.limbs[0..@min(req_limbs, a.limbs.len)];
759 const b_limbs = b.limbs[0..math.min(req_limbs, b.limbs.len)];759 const b_limbs = b.limbs[0..@min(req_limbs, b.limbs.len)];
760760
761 @memset(rma.limbs[0..req_limbs], 0);761 @memset(rma.limbs[0..req_limbs], 0);
762762
763 llmulacc(.add, allocator, rma.limbs, a_limbs, b_limbs);763 llmulacc(.add, allocator, rma.limbs, a_limbs, b_limbs);
764 rma.normalize(math.min(req_limbs, a.limbs.len + b.limbs.len));764 rma.normalize(@min(req_limbs, a.limbs.len + b.limbs.len));
765 rma.positive = (a.positive == b.positive);765 rma.positive = (a.positive == b.positive);
766 rma.truncate(rma.toConst(), signedness, bit_count);766 rma.truncate(rma.toConst(), signedness, bit_count);
767 }767 }
...@@ -1211,7 +1211,7 @@ pub const Mutable = struct {...@@ -1211,7 +1211,7 @@ pub const Mutable = struct {
1211 ///1211 ///
1212 /// a and b are zero-extended to the longer of a or b.1212 /// a and b are zero-extended to the longer of a or b.
1213 ///1213 ///
1214 /// Asserts that r has enough limbs to store the result. Upper bound is `math.max(a.limbs.len, b.limbs.len)`.1214 /// Asserts that r has enough limbs to store the result. Upper bound is `@max(a.limbs.len, b.limbs.len)`.
1215 pub fn bitOr(r: *Mutable, a: Const, b: Const) void {1215 pub fn bitOr(r: *Mutable, a: Const, b: Const) void {
1216 // Trivial cases, llsignedor does not support zero.1216 // Trivial cases, llsignedor does not support zero.
1217 if (a.eqZero()) {1217 if (a.eqZero()) {
...@@ -1235,8 +1235,8 @@ pub const Mutable = struct {...@@ -1235,8 +1235,8 @@ pub const Mutable = struct {
1235 /// r may alias with a or b.1235 /// r may alias with a or b.
1236 ///1236 ///
1237 /// Asserts that r has enough limbs to store the result.1237 /// Asserts that r has enough limbs to store the result.
1238 /// If a or b is positive, the upper bound is `math.min(a.limbs.len, b.limbs.len)`.1238 /// If a or b is positive, the upper bound is `@min(a.limbs.len, b.limbs.len)`.
1239 /// If a and b are negative, the upper bound is `math.max(a.limbs.len, b.limbs.len) + 1`.1239 /// If a and b are negative, the upper bound is `@max(a.limbs.len, b.limbs.len) + 1`.
1240 pub fn bitAnd(r: *Mutable, a: Const, b: Const) void {1240 pub fn bitAnd(r: *Mutable, a: Const, b: Const) void {
1241 // Trivial cases, llsignedand does not support zero.1241 // Trivial cases, llsignedand does not support zero.
1242 if (a.eqZero()) {1242 if (a.eqZero()) {
...@@ -1260,8 +1260,8 @@ pub const Mutable = struct {...@@ -1260,8 +1260,8 @@ pub const Mutable = struct {
1260 /// r may alias with a or b.1260 /// r may alias with a or b.
1261 ///1261 ///
1262 /// Asserts that r has enough limbs to store the result. If a and b share the same signedness, the1262 /// Asserts that r has enough limbs to store the result. If a and b share the same signedness, the
1263 /// upper bound is `math.max(a.limbs.len, b.limbs.len)`. Otherwise, if either a or b is negative1263 /// upper bound is `@max(a.limbs.len, b.limbs.len)`. Otherwise, if either a or b is negative
1264 /// but not both, the upper bound is `math.max(a.limbs.len, b.limbs.len) + 1`.1264 /// but not both, the upper bound is `@max(a.limbs.len, b.limbs.len) + 1`.
1265 pub fn bitXor(r: *Mutable, a: Const, b: Const) void {1265 pub fn bitXor(r: *Mutable, a: Const, b: Const) void {
1266 // Trivial cases, because llsignedxor does not support negative zero.1266 // Trivial cases, because llsignedxor does not support negative zero.
1267 if (a.eqZero()) {1267 if (a.eqZero()) {
...@@ -1284,7 +1284,7 @@ pub const Mutable = struct {...@@ -1284,7 +1284,7 @@ pub const Mutable = struct {
1284 /// rma may alias x or y.1284 /// rma may alias x or y.
1285 /// x and y may alias each other.1285 /// x and y may alias each other.
1286 /// Asserts that `rma` has enough limbs to store the result. Upper bound is1286 /// Asserts that `rma` has enough limbs to store the result. Upper bound is
1287 /// `math.min(x.limbs.len, y.limbs.len)`.1287 /// `@min(x.limbs.len, y.limbs.len)`.
1288 ///1288 ///
1289 /// `limbs_buffer` is used for temporary storage during the operation. When this function returns,1289 /// `limbs_buffer` is used for temporary storage during the operation. When this function returns,
1290 /// it will have the same length as it had when the function was called.1290 /// it will have the same length as it had when the function was called.
...@@ -1546,7 +1546,7 @@ pub const Mutable = struct {...@@ -1546,7 +1546,7 @@ pub const Mutable = struct {
1546 if (yi != 0) break i;1546 if (yi != 0) break i;
1547 } else unreachable;1547 } else unreachable;
15481548
1549 const xy_trailing = math.min(x_trailing, y_trailing);1549 const xy_trailing = @min(x_trailing, y_trailing);
15501550
1551 if (y.len - xy_trailing == 1) {1551 if (y.len - xy_trailing == 1) {
1552 const divisor = y.limbs[y.len - 1];1552 const divisor = y.limbs[y.len - 1];
...@@ -2589,7 +2589,7 @@ pub const Managed = struct {...@@ -2589,7 +2589,7 @@ pub const Managed = struct {
2589 .allocator = allocator,2589 .allocator = allocator,
2590 .metadata = 1,2590 .metadata = 1,
2591 .limbs = block: {2591 .limbs = block: {
2592 const limbs = try allocator.alloc(Limb, math.max(default_capacity, capacity));2592 const limbs = try allocator.alloc(Limb, @max(default_capacity, capacity));
2593 limbs[0] = 0;2593 limbs[0] = 0;
2594 break :block limbs;2594 break :block limbs;
2595 },2595 },
...@@ -2918,7 +2918,7 @@ pub const Managed = struct {...@@ -2918,7 +2918,7 @@ pub const Managed = struct {
2918 ///2918 ///
2919 /// Returns an error if memory could not be allocated.2919 /// Returns an error if memory could not be allocated.
2920 pub fn sub(r: *Managed, a: *const Managed, b: *const Managed) !void {2920 pub fn sub(r: *Managed, a: *const Managed, b: *const Managed) !void {
2921 try r.ensureCapacity(math.max(a.len(), b.len()) + 1);2921 try r.ensureCapacity(@max(a.len(), b.len()) + 1);
2922 var m = r.toMutable();2922 var m = r.toMutable();
2923 m.sub(a.toConst(), b.toConst());2923 m.sub(a.toConst(), b.toConst());
2924 r.setMetadata(m.positive, m.len);2924 r.setMetadata(m.positive, m.len);
...@@ -3025,11 +3025,11 @@ pub const Managed = struct {...@@ -3025,11 +3025,11 @@ pub const Managed = struct {
3025 }3025 }
30263026
3027 pub fn ensureAddScalarCapacity(r: *Managed, a: Const, scalar: anytype) !void {3027 pub fn ensureAddScalarCapacity(r: *Managed, a: Const, scalar: anytype) !void {
3028 try r.ensureCapacity(math.max(a.limbs.len, calcLimbLen(scalar)) + 1);3028 try r.ensureCapacity(@max(a.limbs.len, calcLimbLen(scalar)) + 1);
3029 }3029 }
30303030
3031 pub fn ensureAddCapacity(r: *Managed, a: Const, b: Const) !void {3031 pub fn ensureAddCapacity(r: *Managed, a: Const, b: Const) !void {
3032 try r.ensureCapacity(math.max(a.limbs.len, b.limbs.len) + 1);3032 try r.ensureCapacity(@max(a.limbs.len, b.limbs.len) + 1);
3033 }3033 }
30343034
3035 pub fn ensureMulCapacity(rma: *Managed, a: Const, b: Const) !void {3035 pub fn ensureMulCapacity(rma: *Managed, a: Const, b: Const) !void {
...@@ -3123,7 +3123,7 @@ pub const Managed = struct {...@@ -3123,7 +3123,7 @@ pub const Managed = struct {
3123 ///3123 ///
3124 /// a and b are zero-extended to the longer of a or b.3124 /// a and b are zero-extended to the longer of a or b.
3125 pub fn bitOr(r: *Managed, a: *const Managed, b: *const Managed) !void {3125 pub fn bitOr(r: *Managed, a: *const Managed, b: *const Managed) !void {
3126 try r.ensureCapacity(math.max(a.len(), b.len()));3126 try r.ensureCapacity(@max(a.len(), b.len()));
3127 var m = r.toMutable();3127 var m = r.toMutable();
3128 m.bitOr(a.toConst(), b.toConst());3128 m.bitOr(a.toConst(), b.toConst());
3129 r.setMetadata(m.positive, m.len);3129 r.setMetadata(m.positive, m.len);
...@@ -3132,9 +3132,9 @@ pub const Managed = struct {...@@ -3132,9 +3132,9 @@ pub const Managed = struct {
3132 /// r = a & b3132 /// r = a & b
3133 pub fn bitAnd(r: *Managed, a: *const Managed, b: *const Managed) !void {3133 pub fn bitAnd(r: *Managed, a: *const Managed, b: *const Managed) !void {
3134 const cap = if (a.isPositive() or b.isPositive())3134 const cap = if (a.isPositive() or b.isPositive())
3135 math.min(a.len(), b.len())3135 @min(a.len(), b.len())
3136 else3136 else
3137 math.max(a.len(), b.len()) + 1;3137 @max(a.len(), b.len()) + 1;
3138 try r.ensureCapacity(cap);3138 try r.ensureCapacity(cap);
3139 var m = r.toMutable();3139 var m = r.toMutable();
3140 m.bitAnd(a.toConst(), b.toConst());3140 m.bitAnd(a.toConst(), b.toConst());
...@@ -3143,7 +3143,7 @@ pub const Managed = struct {...@@ -3143,7 +3143,7 @@ pub const Managed = struct {
31433143
3144 /// r = a ^ b3144 /// r = a ^ b
3145 pub fn bitXor(r: *Managed, a: *const Managed, b: *const Managed) !void {3145 pub fn bitXor(r: *Managed, a: *const Managed, b: *const Managed) !void {
3146 var cap = math.max(a.len(), b.len()) + @boolToInt(a.isPositive() != b.isPositive());3146 var cap = @max(a.len(), b.len()) + @boolToInt(a.isPositive() != b.isPositive());
3147 try r.ensureCapacity(cap);3147 try r.ensureCapacity(cap);
31483148
3149 var m = r.toMutable();3149 var m = r.toMutable();
...@@ -3156,7 +3156,7 @@ pub const Managed = struct {...@@ -3156,7 +3156,7 @@ pub const Managed = struct {
3156 ///3156 ///
3157 /// rma's allocator is used for temporary storage to boost multiplication performance.3157 /// rma's allocator is used for temporary storage to boost multiplication performance.
3158 pub fn gcd(rma: *Managed, x: *const Managed, y: *const Managed) !void {3158 pub fn gcd(rma: *Managed, x: *const Managed, y: *const Managed) !void {
3159 try rma.ensureCapacity(math.min(x.len(), y.len()));3159 try rma.ensureCapacity(@min(x.len(), y.len()));
3160 var m = rma.toMutable();3160 var m = rma.toMutable();
3161 var limbs_buffer = std.ArrayList(Limb).init(rma.allocator);3161 var limbs_buffer = std.ArrayList(Limb).init(rma.allocator);
3162 defer limbs_buffer.deinit();3162 defer limbs_buffer.deinit();
...@@ -3356,13 +3356,13 @@ fn llmulaccKaratsuba(...@@ -3356,13 +3356,13 @@ fn llmulaccKaratsuba(
3356 // For a1 and b1 we only need `limbs_after_split` limbs.3356 // For a1 and b1 we only need `limbs_after_split` limbs.
3357 const a1 = blk: {3357 const a1 = blk: {
3358 var a1 = a[split..];3358 var a1 = a[split..];
3359 a1.len = math.min(llnormalize(a1), limbs_after_split);3359 a1.len = @min(llnormalize(a1), limbs_after_split);
3360 break :blk a1;3360 break :blk a1;
3361 };3361 };
33623362
3363 const b1 = blk: {3363 const b1 = blk: {
3364 var b1 = b[split..];3364 var b1 = b[split..];
3365 b1.len = math.min(llnormalize(b1), limbs_after_split);3365 b1.len = @min(llnormalize(b1), limbs_after_split);
3366 break :blk b1;3366 break :blk b1;
3367 };3367 };
33683368
...@@ -3381,10 +3381,10 @@ fn llmulaccKaratsuba(...@@ -3381,10 +3381,10 @@ fn llmulaccKaratsuba(
33813381
3382 // Compute p2.3382 // Compute p2.
3383 // Note, we don't need to compute all of p2, just enough limbs to satisfy r.3383 // Note, we don't need to compute all of p2, just enough limbs to satisfy r.
3384 const p2_limbs = math.min(limbs_after_split, a1.len + b1.len);3384 const p2_limbs = @min(limbs_after_split, a1.len + b1.len);
33853385
3386 @memset(tmp[0..p2_limbs], 0);3386 @memset(tmp[0..p2_limbs], 0);
3387 llmulacc(.add, allocator, tmp[0..p2_limbs], a1[0..math.min(a1.len, p2_limbs)], b1[0..math.min(b1.len, p2_limbs)]);3387 llmulacc(.add, allocator, tmp[0..p2_limbs], a1[0..@min(a1.len, p2_limbs)], b1[0..@min(b1.len, p2_limbs)]);
3388 const p2 = tmp[0..llnormalize(tmp[0..p2_limbs])];3388 const p2 = tmp[0..llnormalize(tmp[0..p2_limbs])];
33893389
3390 // Add p2 * B to the result.3390 // Add p2 * B to the result.
...@@ -3392,7 +3392,7 @@ fn llmulaccKaratsuba(...@@ -3392,7 +3392,7 @@ fn llmulaccKaratsuba(
33923392
3393 // Add p2 * B^2 to the result if required.3393 // Add p2 * B^2 to the result if required.
3394 if (limbs_after_split2 > 0) {3394 if (limbs_after_split2 > 0) {
3395 llaccum(op, r[split * 2 ..], p2[0..math.min(p2.len, limbs_after_split2)]);3395 llaccum(op, r[split * 2 ..], p2[0..@min(p2.len, limbs_after_split2)]);
3396 }3396 }
33973397
3398 // Compute p0.3398 // Compute p0.
...@@ -3406,13 +3406,13 @@ fn llmulaccKaratsuba(...@@ -3406,13 +3406,13 @@ fn llmulaccKaratsuba(
3406 llaccum(op, r, p0);3406 llaccum(op, r, p0);
34073407
3408 // Add p0 * B to the result. In this case, we may not need all of it.3408 // Add p0 * B to the result. In this case, we may not need all of it.
3409 llaccum(op, r[split..], p0[0..math.min(limbs_after_split, p0.len)]);3409 llaccum(op, r[split..], p0[0..@min(limbs_after_split, p0.len)]);
34103410
3411 // Finally, compute and add p1.3411 // Finally, compute and add p1.
3412 // From now on we only need `limbs_after_split` limbs for a0 and b0, since the result of the3412 // From now on we only need `limbs_after_split` limbs for a0 and b0, since the result of the
3413 // following computation will be added * B.3413 // following computation will be added * B.
3414 const a0x = a0[0..std.math.min(a0.len, limbs_after_split)];3414 const a0x = a0[0..@min(a0.len, limbs_after_split)];
3415 const b0x = b0[0..std.math.min(b0.len, limbs_after_split)];3415 const b0x = b0[0..@min(b0.len, limbs_after_split)];
34163416
3417 const j0_sign = llcmp(a0x, a1);3417 const j0_sign = llcmp(a0x, a1);
3418 const j1_sign = llcmp(b1, b0x);3418 const j1_sign = llcmp(b1, b0x);
...@@ -3544,7 +3544,7 @@ fn llmulLimb(comptime op: AccOp, acc: []Limb, y: []const Limb, xi: Limb) bool {...@@ -3544,7 +3544,7 @@ fn llmulLimb(comptime op: AccOp, acc: []Limb, y: []const Limb, xi: Limb) bool {
3544 return false;3544 return false;
3545 }3545 }
35463546
3547 const split = std.math.min(y.len, acc.len);3547 const split = @min(y.len, acc.len);
3548 var a_lo = acc[0..split];3548 var a_lo = acc[0..split];
3549 var a_hi = acc[split..];3549 var a_hi = acc[split..];
35503550
...@@ -4023,8 +4023,8 @@ fn llsignedand(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_...@@ -4023,8 +4023,8 @@ fn llsignedand(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_
4023// r may alias.4023// r may alias.
4024// a and b must not be -0.4024// a and b must not be -0.
4025// Returns `true` when the result is positive.4025// Returns `true` when the result is positive.
4026// If the sign of a and b is equal, then r requires at least `max(a.len, b.len)` limbs are required.4026// If the sign of a and b is equal, then r requires at least `@max(a.len, b.len)` limbs are required.
4027// Otherwise, r requires at least `max(a.len, b.len) + 1` limbs.4027// Otherwise, r requires at least `@max(a.len, b.len) + 1` limbs.
4028fn llsignedxor(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_positive: bool) bool {4028fn llsignedxor(r: []Limb, a: []const Limb, a_positive: bool, b: []const Limb, b_positive: bool) bool {
4029 @setRuntimeSafety(debug_safety);4029 @setRuntimeSafety(debug_safety);
4030 assert(a.len != 0 and b.len != 0);4030 assert(a.len != 0 and b.len != 0);
lib/std/math/ldexp.zig+1-1
...@@ -48,7 +48,7 @@ pub fn ldexp(x: anytype, n: i32) @TypeOf(x) {...@@ -48,7 +48,7 @@ pub fn ldexp(x: anytype, n: i32) @TypeOf(x) {
48 return @bitCast(T, sign_bit); // Severe underflow. Return +/- 048 return @bitCast(T, sign_bit); // Severe underflow. Return +/- 0
4949
50 // Result underflowed, we need to shift and round50 // Result underflowed, we need to shift and round
51 const shift = @intCast(Log2Int(TBits), math.min(-n, -(exponent + n) + 1));51 const shift = @intCast(Log2Int(TBits), @min(-n, -(exponent + n) + 1));
52 const exact_tie: bool = @ctz(repr) == shift - 1;52 const exact_tie: bool = @ctz(repr) == shift - 1;
53 var result = repr & mantissa_mask;53 var result = repr & mantissa_mask;
5454
lib/std/mem.zig+6-6
...@@ -596,7 +596,7 @@ pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void {...@@ -596,7 +596,7 @@ pub fn sortUnstableContext(a: usize, b: usize, context: anytype) void {
596596
597/// Compares two slices of numbers lexicographically. O(n).597/// Compares two slices of numbers lexicographically. O(n).
598pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order {598pub fn order(comptime T: type, lhs: []const T, rhs: []const T) math.Order {
599 const n = math.min(lhs.len, rhs.len);599 const n = @min(lhs.len, rhs.len);
600 var i: usize = 0;600 var i: usize = 0;
601 while (i < n) : (i += 1) {601 while (i < n) : (i += 1) {
602 switch (math.order(lhs[i], rhs[i])) {602 switch (math.order(lhs[i], rhs[i])) {
...@@ -642,7 +642,7 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {...@@ -642,7 +642,7 @@ pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
642/// Compares two slices and returns the index of the first inequality.642/// Compares two slices and returns the index of the first inequality.
643/// Returns null if the slices are equal.643/// Returns null if the slices are equal.
644pub fn indexOfDiff(comptime T: type, a: []const T, b: []const T) ?usize {644pub fn indexOfDiff(comptime T: type, a: []const T, b: []const T) ?usize {
645 const shortest = math.min(a.len, b.len);645 const shortest = @min(a.len, b.len);
646 if (a.ptr == b.ptr)646 if (a.ptr == b.ptr)
647 return if (a.len == b.len) null else shortest;647 return if (a.len == b.len) null else shortest;
648 var index: usize = 0;648 var index: usize = 0;
...@@ -3296,7 +3296,7 @@ pub fn min(comptime T: type, slice: []const T) T {...@@ -3296,7 +3296,7 @@ pub fn min(comptime T: type, slice: []const T) T {
3296 assert(slice.len > 0);3296 assert(slice.len > 0);
3297 var best = slice[0];3297 var best = slice[0];
3298 for (slice[1..]) |item| {3298 for (slice[1..]) |item| {
3299 best = math.min(best, item);3299 best = @min(best, item);
3300 }3300 }
3301 return best;3301 return best;
3302}3302}
...@@ -3313,7 +3313,7 @@ pub fn max(comptime T: type, slice: []const T) T {...@@ -3313,7 +3313,7 @@ pub fn max(comptime T: type, slice: []const T) T {
3313 assert(slice.len > 0);3313 assert(slice.len > 0);
3314 var best = slice[0];3314 var best = slice[0];
3315 for (slice[1..]) |item| {3315 for (slice[1..]) |item| {
3316 best = math.max(best, item);3316 best = @max(best, item);
3317 }3317 }
3318 return best;3318 return best;
3319}3319}
...@@ -3332,8 +3332,8 @@ pub fn minMax(comptime T: type, slice: []const T) struct { min: T, max: T } {...@@ -3332,8 +3332,8 @@ pub fn minMax(comptime T: type, slice: []const T) struct { min: T, max: T } {
3332 var minVal = slice[0];3332 var minVal = slice[0];
3333 var maxVal = slice[0];3333 var maxVal = slice[0];
3334 for (slice[1..]) |item| {3334 for (slice[1..]) |item| {
3335 minVal = math.min(minVal, item);3335 minVal = @min(minVal, item);
3336 maxVal = math.max(maxVal, item);3336 maxVal = @max(maxVal, item);
3337 }3337 }
3338 return .{ .min = minVal, .max = maxVal };3338 return .{ .min = minVal, .max = maxVal };
3339}3339}
lib/std/net.zig+4-4
...@@ -1482,11 +1482,11 @@ fn getResolvConf(allocator: mem.Allocator, rc: *ResolvConf) !void {...@@ -1482,11 +1482,11 @@ fn getResolvConf(allocator: mem.Allocator, rc: *ResolvConf) !void {
1482 error.InvalidCharacter => continue,1482 error.InvalidCharacter => continue,
1483 };1483 };
1484 if (mem.eql(u8, name, "ndots")) {1484 if (mem.eql(u8, name, "ndots")) {
1485 rc.ndots = std.math.min(value, 15);1485 rc.ndots = @min(value, 15);
1486 } else if (mem.eql(u8, name, "attempts")) {1486 } else if (mem.eql(u8, name, "attempts")) {
1487 rc.attempts = std.math.min(value, 10);1487 rc.attempts = @min(value, 10);
1488 } else if (mem.eql(u8, name, "timeout")) {1488 } else if (mem.eql(u8, name, "timeout")) {
1489 rc.timeout = std.math.min(value, 60);1489 rc.timeout = @min(value, 60);
1490 }1490 }
1491 }1491 }
1492 } else if (mem.eql(u8, token, "nameserver")) {1492 } else if (mem.eql(u8, token, "nameserver")) {
...@@ -1615,7 +1615,7 @@ fn resMSendRc(...@@ -1615,7 +1615,7 @@ fn resMSendRc(
1615 }1615 }
16161616
1617 // Wait for a response, or until time to retry1617 // Wait for a response, or until time to retry
1618 const clamped_timeout = std.math.min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2);1618 const clamped_timeout = @min(@as(u31, std.math.maxInt(u31)), t1 + retry_interval - t2);
1619 const nevents = os.poll(&pfd, clamped_timeout) catch 0;1619 const nevents = os.poll(&pfd, clamped_timeout) catch 0;
1620 if (nevents == 0) continue;1620 if (nevents == 0) continue;
16211621
lib/std/os/linux.zig+2-2
...@@ -317,7 +317,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {...@@ -317,7 +317,7 @@ pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
317 .getdents,317 .getdents,
318 @bitCast(usize, @as(isize, fd)),318 @bitCast(usize, @as(isize, fd)),
319 @ptrToInt(dirp),319 @ptrToInt(dirp),
320 std.math.min(len, maxInt(c_int)),320 @min(len, maxInt(c_int)),
321 );321 );
322}322}
323323
...@@ -326,7 +326,7 @@ pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {...@@ -326,7 +326,7 @@ pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {
326 .getdents64,326 .getdents64,
327 @bitCast(usize, @as(isize, fd)),327 @bitCast(usize, @as(isize, fd)),
328 @ptrToInt(dirp),328 @ptrToInt(dirp),
329 std.math.min(len, maxInt(c_int)),329 @min(len, maxInt(c_int)),
330 );330 );
331}331}
332332
lib/std/os/linux/io_uring.zig+2-2
...@@ -277,7 +277,7 @@ pub const IO_Uring = struct {...@@ -277,7 +277,7 @@ pub const IO_Uring = struct {
277 fn copy_cqes_ready(self: *IO_Uring, cqes: []linux.io_uring_cqe, wait_nr: u32) u32 {277 fn copy_cqes_ready(self: *IO_Uring, cqes: []linux.io_uring_cqe, wait_nr: u32) u32 {
278 _ = wait_nr;278 _ = wait_nr;
279 const ready = self.cq_ready();279 const ready = self.cq_ready();
280 const count = std.math.min(cqes.len, ready);280 const count = @min(cqes.len, ready);
281 var head = self.cq.head.*;281 var head = self.cq.head.*;
282 var tail = head +% count;282 var tail = head +% count;
283 // TODO Optimize this by using 1 or 2 memcpy's (if the tail wraps) rather than a loop.283 // 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 {...@@ -1093,7 +1093,7 @@ pub const SubmissionQueue = struct {
1093 pub fn init(fd: os.fd_t, p: linux.io_uring_params) !SubmissionQueue {1093 pub fn init(fd: os.fd_t, p: linux.io_uring_params) !SubmissionQueue {
1094 assert(fd >= 0);1094 assert(fd >= 0);
1095 assert((p.features & linux.IORING_FEAT_SINGLE_MMAP) != 0);1095 assert((p.features & linux.IORING_FEAT_SINGLE_MMAP) != 0);
1096 const size = std.math.max(1096 const size = @max(
1097 p.sq_off.array + p.sq_entries * @sizeOf(u32),1097 p.sq_off.array + p.sq_entries * @sizeOf(u32),
1098 p.cq_off.cqes + p.cq_entries * @sizeOf(linux.io_uring_cqe),1098 p.cq_off.cqes + p.cq_entries * @sizeOf(linux.io_uring_cqe),
1099 );1099 );
lib/std/os/windows.zig+2-2
...@@ -272,7 +272,7 @@ pub fn RtlGenRandom(output: []u8) RtlGenRandomError!void {...@@ -272,7 +272,7 @@ pub fn RtlGenRandom(output: []u8) RtlGenRandomError!void {
272 const max_read_size: ULONG = maxInt(ULONG);272 const max_read_size: ULONG = maxInt(ULONG);
273273
274 while (total_read < output.len) {274 while (total_read < output.len) {
275 const to_read: ULONG = math.min(buff.len, max_read_size);275 const to_read: ULONG = @min(buff.len, max_read_size);
276276
277 if (advapi32.RtlGenRandom(buff.ptr, to_read) == 0) {277 if (advapi32.RtlGenRandom(buff.ptr, to_read) == 0) {
278 return unexpectedError(kernel32.GetLastError());278 return unexpectedError(kernel32.GetLastError());
...@@ -501,7 +501,7 @@ pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64, io_mode: std.io.Mo...@@ -501,7 +501,7 @@ pub fn ReadFile(in_hFile: HANDLE, buffer: []u8, offset: ?u64, io_mode: std.io.Mo
501 return @as(usize, bytes_transferred);501 return @as(usize, bytes_transferred);
502 } else {502 } else {
503 while (true) {503 while (true) {
504 const want_read_count = @intCast(DWORD, math.min(@as(DWORD, maxInt(DWORD)), buffer.len));504 const want_read_count: DWORD = @min(@as(DWORD, maxInt(DWORD)), buffer.len);
505 var amt_read: DWORD = undefined;505 var amt_read: DWORD = undefined;
506 var overlapped_data: OVERLAPPED = undefined;506 var overlapped_data: OVERLAPPED = undefined;
507 const overlapped: ?*OVERLAPPED = if (offset) |off| blk: {507 const overlapped: ?*OVERLAPPED = if (offset) |off| blk: {
lib/std/pdb.zig+1-1
...@@ -1049,7 +1049,7 @@ const MsfStream = struct {...@@ -1049,7 +1049,7 @@ const MsfStream = struct {
1049 var size: usize = 0;1049 var size: usize = 0;
1050 var rem_buffer = buffer;1050 var rem_buffer = buffer;
1051 while (size < buffer.len) {1051 while (size < buffer.len) {
1052 const size_to_read = math.min(self.block_size - offset, rem_buffer.len);1052 const size_to_read = @min(self.block_size - offset, rem_buffer.len);
1053 size += try in.read(rem_buffer[0..size_to_read]);1053 size += try in.read(rem_buffer[0..size_to_read]);
1054 rem_buffer = buffer[size..];1054 rem_buffer = buffer[size..];
1055 offset += size_to_read;1055 offset += size_to_read;
lib/std/rand.zig+1-1
...@@ -410,7 +410,7 @@ pub const Random = struct {...@@ -410,7 +410,7 @@ pub const Random = struct {
410 r.uintLessThan(T, sum)410 r.uintLessThan(T, sum)
411 else if (comptime std.meta.trait.isFloat(T))411 else if (comptime std.meta.trait.isFloat(T))
412 // take care that imprecision doesn't lead to a value slightly greater than sum412 // take care that imprecision doesn't lead to a value slightly greater than sum
413 std.math.min(r.float(T) * sum, sum - std.math.floatEps(T))413 @min(r.float(T) * sum, sum - std.math.floatEps(T))
414 else414 else
415 @compileError("weightedIndex does not support proportions of type " ++ @typeName(T));415 @compileError("weightedIndex does not support proportions of type " ++ @typeName(T));
416416
lib/std/sort/block.zig+5-5
...@@ -590,7 +590,7 @@ pub fn block(...@@ -590,7 +590,7 @@ pub fn block(
590 // 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 well590 // 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
591 var lastA = firstA;591 var lastA = firstA;
592 var lastB = Range.init(0, 0);592 var lastB = Range.init(0, 0);
593 var blockB = Range.init(B.start, B.start + math.min(block_size, B.length()));593 var blockB = Range.init(B.start, B.start + @min(block_size, B.length()));
594 blockA.start += firstA.length();594 blockA.start += firstA.length();
595 indexA = buffer1.start;595 indexA = buffer1.start;
596596
...@@ -849,7 +849,7 @@ fn findFirstForward(...@@ -849,7 +849,7 @@ fn findFirstForward(
849 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,849 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,
850) usize {850) usize {
851 if (range.length() == 0) return range.start;851 if (range.length() == 0) return range.start;
852 const skip = math.max(range.length() / unique, @as(usize, 1));852 const skip = @max(range.length() / unique, @as(usize, 1));
853853
854 var index = range.start + skip;854 var index = range.start + skip;
855 while (lessThan(context, items[index - 1], value)) : (index += skip) {855 while (lessThan(context, items[index - 1], value)) : (index += skip) {
...@@ -871,7 +871,7 @@ fn findFirstBackward(...@@ -871,7 +871,7 @@ fn findFirstBackward(
871 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,871 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,
872) usize {872) usize {
873 if (range.length() == 0) return range.start;873 if (range.length() == 0) return range.start;
874 const skip = math.max(range.length() / unique, @as(usize, 1));874 const skip = @max(range.length() / unique, @as(usize, 1));
875875
876 var index = range.end - skip;876 var index = range.end - skip;
877 while (index > range.start and !lessThan(context, items[index - 1], value)) : (index -= skip) {877 while (index > range.start and !lessThan(context, items[index - 1], value)) : (index -= skip) {
...@@ -893,7 +893,7 @@ fn findLastForward(...@@ -893,7 +893,7 @@ fn findLastForward(
893 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,893 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,
894) usize {894) usize {
895 if (range.length() == 0) return range.start;895 if (range.length() == 0) return range.start;
896 const skip = math.max(range.length() / unique, @as(usize, 1));896 const skip = @max(range.length() / unique, @as(usize, 1));
897897
898 var index = range.start + skip;898 var index = range.start + skip;
899 while (!lessThan(context, value, items[index - 1])) : (index += skip) {899 while (!lessThan(context, value, items[index - 1])) : (index += skip) {
...@@ -915,7 +915,7 @@ fn findLastBackward(...@@ -915,7 +915,7 @@ fn findLastBackward(
915 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,915 comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool,
916) usize {916) usize {
917 if (range.length() == 0) return range.start;917 if (range.length() == 0) return range.start;
918 const skip = math.max(range.length() / unique, @as(usize, 1));918 const skip = @max(range.length() / unique, @as(usize, 1));
919919
920 var index = range.end - skip;920 var index = range.end - skip;
921 while (index > range.start and lessThan(context, value, items[index - 1])) : (index -= skip) {921 while (index > range.start and lessThan(context, value, items[index - 1])) : (index -= skip) {
lib/std/zig/render.zig+2-2
...@@ -1960,7 +1960,7 @@ fn renderArrayInit(...@@ -1960,7 +1960,7 @@ fn renderArrayInit(
19601960
1961 if (!this_contains_newline) {1961 if (!this_contains_newline) {
1962 const column = column_counter % row_size;1962 const column = column_counter % row_size;
1963 column_widths[column] = std.math.max(column_widths[column], width);1963 column_widths[column] = @max(column_widths[column], width);
19641964
1965 const expr_last_token = tree.lastToken(expr) + 1;1965 const expr_last_token = tree.lastToken(expr) + 1;
1966 const next_expr = section_exprs[i + 1];1966 const next_expr = section_exprs[i + 1];
...@@ -1980,7 +1980,7 @@ fn renderArrayInit(...@@ -1980,7 +1980,7 @@ fn renderArrayInit(
19801980
1981 if (!contains_newline) {1981 if (!contains_newline) {
1982 const column = column_counter % row_size;1982 const column = column_counter % row_size;
1983 column_widths[column] = std.math.max(column_widths[column], width);1983 column_widths[column] = @max(column_widths[column], width);
1984 }1984 }
1985 }1985 }
1986 }1986 }
lib/std/zig/system/NativeTargetInfo.zig+3-3
...@@ -503,7 +503,7 @@ fn glibcVerFromSoFile(file: fs.File) !std.builtin.Version {...@@ -503,7 +503,7 @@ fn glibcVerFromSoFile(file: fs.File) !std.builtin.Version {
503 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);503 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);
504 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);504 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);
505 var strtab_buf: [4096:0]u8 = undefined;505 var strtab_buf: [4096:0]u8 = undefined;
506 const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len);506 const shstrtab_len = @min(shstrtab_size, strtab_buf.len);
507 const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len);507 const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len);
508 const shstrtab = strtab_buf[0..shstrtab_read_len];508 const shstrtab = strtab_buf[0..shstrtab_read_len];
509 const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum);509 const shnum = elfInt(is_64, need_bswap, hdr32.e_shnum, hdr64.e_shnum);
...@@ -757,7 +757,7 @@ pub fn abiAndDynamicLinkerFromFile(...@@ -757,7 +757,7 @@ pub fn abiAndDynamicLinkerFromFile(
757 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);757 const shstrtab_off = elfInt(is_64, need_bswap, shstr32.sh_offset, shstr64.sh_offset);
758 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);758 const shstrtab_size = elfInt(is_64, need_bswap, shstr32.sh_size, shstr64.sh_size);
759 var strtab_buf: [4096:0]u8 = undefined;759 var strtab_buf: [4096:0]u8 = undefined;
760 const shstrtab_len = std.math.min(shstrtab_size, strtab_buf.len);760 const shstrtab_len = @min(shstrtab_size, strtab_buf.len);
761 const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len);761 const shstrtab_read_len = try preadMin(file, &strtab_buf, shstrtab_off, shstrtab_len);
762 const shstrtab = strtab_buf[0..shstrtab_read_len];762 const shstrtab = strtab_buf[0..shstrtab_read_len];
763763
...@@ -806,7 +806,7 @@ pub fn abiAndDynamicLinkerFromFile(...@@ -806,7 +806,7 @@ pub fn abiAndDynamicLinkerFromFile(
806 const rpoff_file = ds.offset + rpoff_usize;806 const rpoff_file = ds.offset + rpoff_usize;
807 const rp_max_size = ds.size - rpoff_usize;807 const rp_max_size = ds.size - rpoff_usize;
808808
809 const strtab_len = std.math.min(rp_max_size, strtab_buf.len);809 const strtab_len = @min(rp_max_size, strtab_buf.len);
810 const strtab_read_len = try preadMin(file, &strtab_buf, rpoff_file, strtab_len);810 const strtab_read_len = try preadMin(file, &strtab_buf, rpoff_file, strtab_len);
811 const strtab = strtab_buf[0..strtab_read_len];811 const strtab = strtab_buf[0..strtab_read_len];
812812
src/Autodoc.zig+2-2
...@@ -1494,8 +1494,6 @@ fn walkInstruction(...@@ -1494,8 +1494,6 @@ fn walkInstruction(
1494 .frame_type,1494 .frame_type,
1495 .frame_size,1495 .frame_size,
1496 .ptr_to_int,1496 .ptr_to_int,
1497 .min,
1498 .max,
1499 .bit_not,1497 .bit_not,
1500 // @check1498 // @check
1501 .clz,1499 .clz,
...@@ -1546,6 +1544,8 @@ fn walkInstruction(...@@ -1546,6 +1544,8 @@ fn walkInstruction(
1546 .offset_of,1544 .offset_of,
1547 .splat,1545 .splat,
1548 .reduce,1546 .reduce,
1547 .min,
1548 .max,
1549 => {1549 => {
1550 const pl_node = data[inst_index].pl_node;1550 const pl_node = data[inst_index].pl_node;
1551 const extra = file.zir.extraData(Zir.Inst.Bin, pl_node.payload_index);1551 const extra = file.zir.extraData(Zir.Inst.Bin, pl_node.payload_index);
src/Sema.zig+144-116
...@@ -22367,9 +22367,9 @@ fn analyzeShuffle(...@@ -22367,9 +22367,9 @@ fn analyzeShuffle(
22367 // to it up to the length of the longer vector. This recursion terminates22367 // to it up to the length of the longer vector. This recursion terminates
22368 // in 1 call because these calls to analyzeShuffle guarantee a_len == b_len.22368 // in 1 call because these calls to analyzeShuffle guarantee a_len == b_len.
22369 if (a_len != b_len) {22369 if (a_len != b_len) {
22370 const min_len = std.math.min(a_len, b_len);22370 const min_len = @min(a_len, b_len);
22371 const max_src = if (a_len > b_len) a_src else b_src;22371 const max_src = if (a_len > b_len) a_src else b_src;
22372 const max_len = try sema.usizeCast(block, max_src, std.math.max(a_len, b_len));22372 const max_len = try sema.usizeCast(block, max_src, @max(a_len, b_len));
2237322373
22374 const expand_mask_values = try sema.arena.alloc(InternPool.Index, max_len);22374 const expand_mask_values = try sema.arena.alloc(InternPool.Index, max_len);
22375 for (@intCast(usize, 0)..@intCast(usize, min_len)) |i| {22375 for (@intCast(usize, 0)..@intCast(usize, min_len)) |i| {
...@@ -22984,104 +22984,127 @@ fn analyzeMinMax(...@@ -22984,104 +22984,127 @@ fn analyzeMinMax(
22984 else => @compileError("unreachable"),22984 else => @compileError("unreachable"),
22985 };22985 };
2298622986
22987 // First, find all comptime-known arguments, and get their min/max22987 // The set of runtime-known operands. Set up in the loop below.
22988 var runtime_known = try std.DynamicBitSet.initFull(sema.arena, operands.len);22988 var runtime_known = try std.DynamicBitSet.initFull(sema.arena, operands.len);
22989 // The current minmax value - initially this will always be comptime-known, then we'll add
22990 // runtime values into the mix later.
22989 var cur_minmax: ?Air.Inst.Ref = null;22991 var cur_minmax: ?Air.Inst.Ref = null;
22990 var cur_minmax_src: LazySrcLoc = undefined; // defined if cur_minmax not null22992 var cur_minmax_src: LazySrcLoc = undefined; // defined if cur_minmax not null
22993 // The current known scalar bounds of the value.
22994 var bounds_status: enum {
22995 unknown, // We've only seen undef comptime_ints so far, so do not know the bounds.
22996 defined, // We've seen only integers, so the bounds are defined.
22997 non_integral, // There are floats in the mix, so the bounds aren't defined.
22998 } = .unknown;
22999 var cur_min_scalar: Value = undefined;
23000 var cur_max_scalar: Value = undefined;
23001
23002 // First, find all comptime-known arguments, and get their min/max
23003
22991 for (operands, operand_srcs, 0..) |operand, operand_src, operand_idx| {23004 for (operands, operand_srcs, 0..) |operand, operand_src, operand_idx| {
22992 // Resolve the value now to avoid redundant calls to `checkSimdBinOp` - we'll have to call23005 // Resolve the value now to avoid redundant calls to `checkSimdBinOp` - we'll have to call
22993 // it in the runtime path anyway since the result type may have been refined23006 // it in the runtime path anyway since the result type may have been refined
22994 const uncasted_operand_val = (try sema.resolveMaybeUndefVal(operand)) orelse continue;23007 const unresolved_uncoerced_val = try sema.resolveMaybeUndefVal(operand) orelse continue;
22995 if (cur_minmax) |cur| {23008 const uncoerced_val = try sema.resolveLazyValue(unresolved_uncoerced_val);
22996 const simd_op = try sema.checkSimdBinOp(block, src, cur, operand, cur_minmax_src, operand_src);23009
22997 const cur_val = simd_op.lhs_val.?; // cur_minmax is comptime-known23010 runtime_known.unset(operand_idx);
22998 const operand_val = simd_op.rhs_val.?; // we checked the operand was resolvable above23011
2299923012 switch (bounds_status) {
23000 runtime_known.unset(operand_idx);23013 .unknown, .defined => refine_bounds: {
23014 const ty = sema.typeOf(operand);
23015 if (!ty.scalarType(mod).isInt(mod) and !ty.scalarType(mod).eql(Type.comptime_int, mod)) {
23016 bounds_status = .non_integral;
23017 break :refine_bounds;
23018 }
23019 const scalar_bounds: ?[2]Value = bounds: {
23020 if (!ty.isVector(mod)) break :bounds try uncoerced_val.intValueBounds(mod);
23021 var cur_bounds: [2]Value = try Value.intValueBounds(try uncoerced_val.elemValue(mod, 0), mod) orelse break :bounds null;
23022 const len = try sema.usizeCast(block, src, ty.vectorLen(mod));
23023 for (1..len) |i| {
23024 const elem = try uncoerced_val.elemValue(mod, i);
23025 const elem_bounds = try elem.intValueBounds(mod) orelse break :bounds null;
23026 cur_bounds = .{
23027 Value.numberMin(elem_bounds[0], cur_bounds[0], mod),
23028 Value.numberMax(elem_bounds[1], cur_bounds[1], mod),
23029 };
23030 }
23031 break :bounds cur_bounds;
23032 };
23033 if (scalar_bounds) |bounds| {
23034 if (bounds_status == .unknown) {
23035 cur_min_scalar = bounds[0];
23036 cur_max_scalar = bounds[1];
23037 bounds_status = .defined;
23038 } else {
23039 cur_min_scalar = opFunc(cur_min_scalar, bounds[0], mod);
23040 cur_max_scalar = opFunc(cur_max_scalar, bounds[1], mod);
23041 }
23042 }
23043 },
23044 .non_integral => {},
23045 }
2300123046
23002 if (cur_val.isUndef(mod)) continue; // result is also undef23047 const cur = cur_minmax orelse {
23003 if (operand_val.isUndef(mod)) {23048 cur_minmax = operand;
23004 cur_minmax = try sema.addConstUndef(simd_op.result_ty);23049 cur_minmax_src = operand_src;
23005 continue;23050 continue;
23006 }23051 };
2300723052
23008 const resolved_cur_val = try sema.resolveLazyValue(cur_val);23053 const simd_op = try sema.checkSimdBinOp(block, src, cur, operand, cur_minmax_src, operand_src);
23009 const resolved_operand_val = try sema.resolveLazyValue(operand_val);23054 const cur_val = try sema.resolveLazyValue(simd_op.lhs_val.?); // cur_minmax is comptime-known
23055 const operand_val = try sema.resolveLazyValue(simd_op.rhs_val.?); // we checked the operand was resolvable above
2301023056
23011 const vec_len = simd_op.len orelse {23057 const vec_len = simd_op.len orelse {
23012 const result_val = opFunc(resolved_cur_val, resolved_operand_val, mod);23058 const result_val = opFunc(cur_val, operand_val, mod);
23013 cur_minmax = try sema.addConstant(simd_op.result_ty, result_val);23059 cur_minmax = try sema.addConstant(simd_op.result_ty, result_val);
23014 continue;23060 continue;
23015 };23061 };
23016 const elems = try sema.arena.alloc(InternPool.Index, vec_len);23062 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
23017 for (elems, 0..) |*elem, i| {23063 for (elems, 0..) |*elem, i| {
23018 const lhs_elem_val = try resolved_cur_val.elemValue(mod, i);23064 const lhs_elem_val = try cur_val.elemValue(mod, i);
23019 const rhs_elem_val = try resolved_operand_val.elemValue(mod, i);23065 const rhs_elem_val = try operand_val.elemValue(mod, i);
23020 elem.* = try opFunc(lhs_elem_val, rhs_elem_val, mod).intern(simd_op.scalar_ty, mod);23066 const uncoerced_elem = opFunc(lhs_elem_val, rhs_elem_val, mod);
23021 }23067 elem.* = (try mod.getCoerced(uncoerced_elem, simd_op.scalar_ty)).toIntern();
23022 cur_minmax = try sema.addConstant(simd_op.result_ty, (try mod.intern(.{ .aggregate = .{
23023 .ty = simd_op.result_ty.toIntern(),
23024 .storage = .{ .elems = elems },
23025 } })).toValue());
23026 } else {
23027 runtime_known.unset(operand_idx);
23028 cur_minmax = try sema.addConstant(sema.typeOf(operand), uncasted_operand_val);
23029 cur_minmax_src = operand_src;
23030 }23068 }
23069 cur_minmax = try sema.addConstant(simd_op.result_ty, (try mod.intern(.{ .aggregate = .{
23070 .ty = simd_op.result_ty.toIntern(),
23071 .storage = .{ .elems = elems },
23072 } })).toValue());
23031 }23073 }
2303223074
23033 const opt_runtime_idx = runtime_known.findFirstSet();23075 const opt_runtime_idx = runtime_known.findFirstSet();
2303423076
23035 const comptime_refined_ty: ?Type = if (cur_minmax) |ct_minmax_ref| refined: {23077 if (cur_minmax) |ct_minmax_ref| refine: {
23036 // Refine the comptime-known result type based on the operation23078 // Refine the comptime-known result type based on the bounds. This isn't strictly necessary
23079 // in the runtime case, since we'll refine the type again later, but keeping things as small
23080 // as possible will allow us to emit more optimal AIR (if all the runtime operands have
23081 // smaller types than the non-refined comptime type).
23082
23037 const val = (try sema.resolveMaybeUndefVal(ct_minmax_ref)).?;23083 const val = (try sema.resolveMaybeUndefVal(ct_minmax_ref)).?;
23038 const orig_ty = sema.typeOf(ct_minmax_ref);23084 const orig_ty = sema.typeOf(ct_minmax_ref);
2303923085
23040 if (opt_runtime_idx == null and orig_ty.eql(Type.comptime_int, mod)) {23086 if (opt_runtime_idx == null and orig_ty.scalarType(mod).eql(Type.comptime_int, mod)) {
23041 // If all arguments were `comptime_int`, and there are no runtime args, we'll preserve that type23087 // If all arguments were `comptime_int`, and there are no runtime args, we'll preserve that type
23042 break :refined orig_ty;23088 break :refine;
23043 }23089 }
2304423090
23045 const refined_ty = if (orig_ty.zigTypeTag(mod) == .Vector) blk: {23091 // We can't refine float types
23046 const elem_ty = orig_ty.childType(mod);23092 if (orig_ty.scalarType(mod).isAnyFloat()) break :refine;
23047 const len = orig_ty.vectorLen(mod);
23048
23049 if (len == 0) break :blk orig_ty;
23050 if (elem_ty.isAnyFloat()) break :blk orig_ty; // can't refine floats
2305123093
23052 var cur_min: Value = try val.elemValue(mod, 0);23094 assert(bounds_status == .defined); // there was a non-comptime-int integral comptime-known arg
23053 var cur_max: Value = cur_min;
23054 for (1..len) |idx| {
23055 const elem_val = try val.elemValue(mod, idx);
23056 if (elem_val.isUndef(mod)) break :blk orig_ty; // can't refine undef
23057 if (Value.order(elem_val, cur_min, mod).compare(.lt)) cur_min = elem_val;
23058 if (Value.order(elem_val, cur_max, mod).compare(.gt)) cur_max = elem_val;
23059 }
2306023095
23061 const refined_elem_ty = try mod.intFittingRange(cur_min, cur_max);23096 const refined_scalar_ty = try mod.intFittingRange(cur_min_scalar, cur_max_scalar);
23062 break :blk try mod.vectorType(.{23097 const refined_ty = if (orig_ty.isVector(mod)) try mod.vectorType(.{
23063 .len = len,23098 .len = orig_ty.vectorLen(mod),
23064 .child = refined_elem_ty.toIntern(),23099 .child = refined_scalar_ty.toIntern(),
23065 });23100 }) else refined_scalar_ty;
23066 } else blk: {
23067 if (orig_ty.isAnyFloat()) break :blk orig_ty; // can't refine floats
23068 if (val.isUndef(mod)) break :blk orig_ty; // can't refine undef
23069 break :blk try mod.intFittingRange(val, val);
23070 };
2307123101
23072 // Apply the refined type to the current value - this isn't strictly necessary in the23102 // Apply the refined type to the current value
23073 // runtime case since we'll refine again afterwards, but keeping things as small as possible23103 if (std.debug.runtime_safety) {
23074 // will allow us to emit more optimal AIR (if all the runtime operands have smaller types23104 assert(try sema.intFitsInType(val, refined_ty, null));
23075 // than the non-refined comptime type).
23076 if (!refined_ty.eql(orig_ty, mod)) {
23077 if (std.debug.runtime_safety) {
23078 assert(try sema.intFitsInType(val, refined_ty, null));
23079 }
23080 cur_minmax = try sema.coerceInMemory(val, refined_ty);
23081 }23105 }
2308223106 cur_minmax = try sema.coerceInMemory(val, refined_ty);
23083 break :refined refined_ty;23107 }
23084 } else null;
2308523108
23086 const runtime_idx = opt_runtime_idx orelse return cur_minmax.?;23109 const runtime_idx = opt_runtime_idx orelse return cur_minmax.?;
23087 const runtime_src = operand_srcs[runtime_idx];23110 const runtime_src = operand_srcs[runtime_idx];
...@@ -23102,6 +23125,11 @@ fn analyzeMinMax(...@@ -23102,6 +23125,11 @@ fn analyzeMinMax(
23102 cur_minmax = operands[0];23125 cur_minmax = operands[0];
23103 cur_minmax_src = runtime_src;23126 cur_minmax_src = runtime_src;
23104 runtime_known.unset(0); // don't look at this operand in the loop below23127 runtime_known.unset(0); // don't look at this operand in the loop below
23128 const scalar_ty = sema.typeOf(cur_minmax.?).scalarType(mod);
23129 if (scalar_ty.isInt(mod)) {
23130 cur_min_scalar = try scalar_ty.minInt(mod, scalar_ty);
23131 cur_max_scalar = try scalar_ty.maxInt(mod, scalar_ty);
23132 }
23105 }23133 }
2310623134
23107 var it = runtime_known.iterator(.{});23135 var it = runtime_known.iterator(.{});
...@@ -23112,49 +23140,49 @@ fn analyzeMinMax(...@@ -23112,49 +23140,49 @@ fn analyzeMinMax(
23112 const rhs_src = operand_srcs[idx];23140 const rhs_src = operand_srcs[idx];
23113 const simd_op = try sema.checkSimdBinOp(block, src, lhs, rhs, lhs_src, rhs_src);23141 const simd_op = try sema.checkSimdBinOp(block, src, lhs, rhs, lhs_src, rhs_src);
23114 if (known_undef) {23142 if (known_undef) {
23115 cur_minmax = try sema.addConstant(simd_op.result_ty, Value.undef);23143 cur_minmax = try sema.addConstUndef(simd_op.result_ty);
23116 } else {23144 } else {
23117 cur_minmax = try block.addBinOp(air_tag, simd_op.lhs, simd_op.rhs);23145 cur_minmax = try block.addBinOp(air_tag, simd_op.lhs, simd_op.rhs);
23118 }23146 }
23147 // Compute the bounds of this type
23148 switch (bounds_status) {
23149 .unknown, .defined => refine_bounds: {
23150 const scalar_ty = sema.typeOf(rhs).scalarType(mod);
23151 if (scalar_ty.isAnyFloat()) {
23152 bounds_status = .non_integral;
23153 break :refine_bounds;
23154 }
23155 const scalar_min = try scalar_ty.minInt(mod, scalar_ty);
23156 const scalar_max = try scalar_ty.maxInt(mod, scalar_ty);
23157 if (bounds_status == .unknown) {
23158 cur_min_scalar = scalar_min;
23159 cur_max_scalar = scalar_max;
23160 bounds_status = .defined;
23161 } else {
23162 cur_min_scalar = opFunc(cur_min_scalar, scalar_min, mod);
23163 cur_max_scalar = opFunc(cur_max_scalar, scalar_max, mod);
23164 }
23165 },
23166 .non_integral => {},
23167 }
23119 }23168 }
2312023169
23121 if (comptime_refined_ty) |comptime_ty| refine: {23170 // Finally, refine the type based on the known bounds.
23122 // Finally, refine the type based on the comptime-known bound.23171 const unrefined_ty = sema.typeOf(cur_minmax.?);
23123 if (known_undef) break :refine; // can't refine undef23172 if (unrefined_ty.scalarType(mod).isAnyFloat()) {
23124 const unrefined_ty = sema.typeOf(cur_minmax.?);23173 // We can't refine floats, so we're done.
23125 const is_vector = unrefined_ty.zigTypeTag(mod) == .Vector;23174 return cur_minmax.?;
23126 const comptime_elem_ty = if (is_vector) comptime_ty.childType(mod) else comptime_ty;23175 }
23127 const unrefined_elem_ty = if (is_vector) unrefined_ty.childType(mod) else unrefined_ty;23176 assert(bounds_status == .defined); // there were integral runtime operands
2312823177 const refined_scalar_ty = try mod.intFittingRange(cur_min_scalar, cur_max_scalar);
23129 if (unrefined_elem_ty.isAnyFloat()) break :refine; // we can't refine floats23178 const refined_ty = if (unrefined_ty.isVector(mod)) try mod.vectorType(.{
2313023179 .len = unrefined_ty.vectorLen(mod),
23131 // Compute the final bounds based on the runtime type and the comptime-known bound type23180 .child = refined_scalar_ty.toIntern(),
23132 const min_val = switch (air_tag) {23181 }) else refined_scalar_ty;
23133 .min => try unrefined_elem_ty.minInt(mod, unrefined_elem_ty),
23134 .max => try comptime_elem_ty.minInt(mod, comptime_elem_ty), // @max(ct, rt) >= ct
23135 else => unreachable,
23136 };
23137 const max_val = switch (air_tag) {
23138 .min => try comptime_elem_ty.maxInt(mod, comptime_elem_ty), // @min(ct, rt) <= ct
23139 .max => try unrefined_elem_ty.maxInt(mod, unrefined_elem_ty),
23140 else => unreachable,
23141 };
23142
23143 // Find the smallest type which can contain these bounds
23144 const final_elem_ty = try mod.intFittingRange(min_val, max_val);
23145
23146 const final_ty = if (is_vector)
23147 try mod.vectorType(.{
23148 .len = unrefined_ty.vectorLen(mod),
23149 .child = final_elem_ty.toIntern(),
23150 })
23151 else
23152 final_elem_ty;
2315323182
23154 if (!final_ty.eql(unrefined_ty, mod)) {23183 if (!refined_ty.eql(unrefined_ty, mod)) {
23155 // We've reduced the type - cast the result down23184 // We've reduced the type - cast the result down
23156 return block.addTyOp(.intcast, final_ty, cur_minmax.?);23185 return block.addTyOp(.intcast, refined_ty, cur_minmax.?);
23157 }
23158 }23186 }
2315923187
23160 return cur_minmax.?;23188 return cur_minmax.?;
...@@ -31273,7 +31301,7 @@ fn cmpNumeric(...@@ -31273,7 +31301,7 @@ fn cmpNumeric(
31273 }31301 }
3127431302
31275 const dest_ty = if (dest_float_type) |ft| ft else blk: {31303 const dest_ty = if (dest_float_type) |ft| ft else blk: {
31276 const max_bits = std.math.max(lhs_bits, rhs_bits);31304 const max_bits = @max(lhs_bits, rhs_bits);
31277 const casted_bits = std.math.cast(u16, max_bits) orelse return sema.fail(block, src, "{d} exceeds maximum integer bit count", .{max_bits});31305 const casted_bits = std.math.cast(u16, max_bits) orelse return sema.fail(block, src, "{d} exceeds maximum integer bit count", .{max_bits});
31278 const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned;31306 const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned;
31279 break :blk try mod.intType(signedness, casted_bits);31307 break :blk try mod.intType(signedness, casted_bits);
...@@ -35800,7 +35828,7 @@ fn intAddScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {...@@ -35800,7 +35828,7 @@ fn intAddScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {
35800 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, sema);35828 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, sema);
35801 const limbs = try sema.arena.alloc(35829 const limbs = try sema.arena.alloc(
35802 std.math.big.Limb,35830 std.math.big.Limb,
35803 std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,35831 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
35804 );35832 );
35805 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };35833 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
35806 result_bigint.add(lhs_bigint, rhs_bigint);35834 result_bigint.add(lhs_bigint, rhs_bigint);
...@@ -35890,7 +35918,7 @@ fn intSubScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {...@@ -35890,7 +35918,7 @@ fn intSubScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {
35890 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, sema);35918 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, sema);
35891 const limbs = try sema.arena.alloc(35919 const limbs = try sema.arena.alloc(
35892 std.math.big.Limb,35920 std.math.big.Limb,
35893 std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,35921 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
35894 );35922 );
35895 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };35923 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
35896 result_bigint.sub(lhs_bigint, rhs_bigint);35924 result_bigint.sub(lhs_bigint, rhs_bigint);
src/TypedValue.zig+5-5
...@@ -111,7 +111,7 @@ pub fn print(...@@ -111,7 +111,7 @@ pub fn print(
111 .val = val.castTag(.repeated).?.data,111 .val = val.castTag(.repeated).?.data,
112 };112 };
113 const len = ty.arrayLen(mod);113 const len = ty.arrayLen(mod);
114 const max_len = std.math.min(len, max_aggregate_items);114 const max_len = @min(len, max_aggregate_items);
115 while (i < max_len) : (i += 1) {115 while (i < max_len) : (i += 1) {
116 if (i != 0) try writer.writeAll(", ");116 if (i != 0) try writer.writeAll(", ");
117 try print(elem_tv, writer, level - 1, mod);117 try print(elem_tv, writer, level - 1, mod);
...@@ -130,7 +130,7 @@ pub fn print(...@@ -130,7 +130,7 @@ pub fn print(
130 const len = payload.len.toUnsignedInt(mod);130 const len = payload.len.toUnsignedInt(mod);
131131
132 if (elem_ty.eql(Type.u8, mod)) str: {132 if (elem_ty.eql(Type.u8, mod)) str: {
133 const max_len = @intCast(usize, std.math.min(len, max_string_len));133 const max_len: usize = @min(len, max_string_len);
134 var buf: [max_string_len]u8 = undefined;134 var buf: [max_string_len]u8 = undefined;
135135
136 var i: u32 = 0;136 var i: u32 = 0;
...@@ -149,7 +149,7 @@ pub fn print(...@@ -149,7 +149,7 @@ pub fn print(
149149
150 try writer.writeAll(".{ ");150 try writer.writeAll(".{ ");
151151
152 const max_len = std.math.min(len, max_aggregate_items);152 const max_len = @min(len, max_aggregate_items);
153 var i: u32 = 0;153 var i: u32 = 0;
154 while (i < max_len) : (i += 1) {154 while (i < max_len) : (i += 1) {
155 if (i != 0) try writer.writeAll(", ");155 if (i != 0) try writer.writeAll(", ");
...@@ -455,7 +455,7 @@ fn printAggregate(...@@ -455,7 +455,7 @@ fn printAggregate(
455 const len = ty.arrayLen(mod);455 const len = ty.arrayLen(mod);
456456
457 if (elem_ty.eql(Type.u8, mod)) str: {457 if (elem_ty.eql(Type.u8, mod)) str: {
458 const max_len = @intCast(usize, std.math.min(len, max_string_len));458 const max_len: usize = @min(len, max_string_len);
459 var buf: [max_string_len]u8 = undefined;459 var buf: [max_string_len]u8 = undefined;
460460
461 var i: u32 = 0;461 var i: u32 = 0;
...@@ -471,7 +471,7 @@ fn printAggregate(...@@ -471,7 +471,7 @@ fn printAggregate(
471471
472 try writer.writeAll(".{ ");472 try writer.writeAll(".{ ");
473473
474 const max_len = std.math.min(len, max_aggregate_items);474 const max_len = @min(len, max_aggregate_items);
475 var i: u32 = 0;475 var i: u32 = 0;
476 while (i < max_len) : (i += 1) {476 while (i < max_len) : (i += 1) {
477 if (i != 0) try writer.writeAll(", ");477 if (i != 0) try writer.writeAll(", ");
src/arch/x86_64/CodeGen.zig+2-2
...@@ -2907,7 +2907,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {...@@ -2907,7 +2907,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
2907 const dst_info = dst_ty.intInfo(mod);2907 const dst_info = dst_ty.intInfo(mod);
2908 const src_ty = try mod.intType(dst_info.signedness, switch (tag) {2908 const src_ty = try mod.intType(dst_info.signedness, switch (tag) {
2909 else => unreachable,2909 else => unreachable,
2910 .mul, .mulwrap => math.max3(2910 .mul, .mulwrap => @max(
2911 self.activeIntBits(bin_op.lhs),2911 self.activeIntBits(bin_op.lhs),
2912 self.activeIntBits(bin_op.rhs),2912 self.activeIntBits(bin_op.rhs),
2913 dst_info.bits / 2,2913 dst_info.bits / 2,
...@@ -3349,7 +3349,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {...@@ -3349,7 +3349,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
33493349
3350 const lhs_active_bits = self.activeIntBits(bin_op.lhs);3350 const lhs_active_bits = self.activeIntBits(bin_op.lhs);
3351 const rhs_active_bits = self.activeIntBits(bin_op.rhs);3351 const rhs_active_bits = self.activeIntBits(bin_op.rhs);
3352 const src_bits = math.max3(lhs_active_bits, rhs_active_bits, dst_info.bits / 2);3352 const src_bits = @max(lhs_active_bits, rhs_active_bits, dst_info.bits / 2);
3353 const src_ty = try mod.intType(dst_info.signedness, src_bits);3353 const src_ty = try mod.intType(dst_info.signedness, src_bits);
33543354
3355 const lhs = try self.resolveInst(bin_op.lhs);3355 const lhs = try self.resolveInst(bin_op.lhs);
src/link/Elf.zig+1-1
...@@ -2326,7 +2326,7 @@ fn allocateAtom(self: *Elf, atom_index: Atom.Index, new_block_size: u64, alignme...@@ -2326,7 +2326,7 @@ fn allocateAtom(self: *Elf, atom_index: Atom.Index, new_block_size: u64, alignme
2326 self.debug_aranges_section_dirty = true;2326 self.debug_aranges_section_dirty = true;
2327 }2327 }
2328 }2328 }
2329 shdr.sh_addralign = math.max(shdr.sh_addralign, alignment);2329 shdr.sh_addralign = @max(shdr.sh_addralign, alignment);
23302330
2331 // This function can also reallocate an atom.2331 // This function can also reallocate an atom.
2332 // In this case we need to "unplug" it from its previous location before2332 // In this case we need to "unplug" it from its previous location before
src/link/MachO/CodeSignature.zig+3-3
...@@ -99,7 +99,7 @@ const CodeDirectory = struct {...@@ -99,7 +99,7 @@ const CodeDirectory = struct {
9999
100 fn addSpecialHash(self: *CodeDirectory, index: u32, hash: [hash_size]u8) void {100 fn addSpecialHash(self: *CodeDirectory, index: u32, hash: [hash_size]u8) void {
101 assert(index > 0);101 assert(index > 0);
102 self.inner.nSpecialSlots = std.math.max(self.inner.nSpecialSlots, index);102 self.inner.nSpecialSlots = @max(self.inner.nSpecialSlots, index);
103 self.special_slots[index - 1] = hash;103 self.special_slots[index - 1] = hash;
104 }104 }
105105
...@@ -426,11 +426,11 @@ pub fn estimateSize(self: CodeSignature, file_size: u64) u32 {...@@ -426,11 +426,11 @@ pub fn estimateSize(self: CodeSignature, file_size: u64) u32 {
426 var n_special_slots: u32 = 0;426 var n_special_slots: u32 = 0;
427 if (self.requirements) |req| {427 if (self.requirements) |req| {
428 ssize += @sizeOf(macho.BlobIndex) + req.size();428 ssize += @sizeOf(macho.BlobIndex) + req.size();
429 n_special_slots = std.math.max(n_special_slots, req.slotType());429 n_special_slots = @max(n_special_slots, req.slotType());
430 }430 }
431 if (self.entitlements) |ent| {431 if (self.entitlements) |ent| {
432 ssize += @sizeOf(macho.BlobIndex) + ent.size() + hash_size;432 ssize += @sizeOf(macho.BlobIndex) + ent.size() + hash_size;
433 n_special_slots = std.math.max(n_special_slots, ent.slotType());433 n_special_slots = @max(n_special_slots, ent.slotType());
434 }434 }
435 if (self.signature) |sig| {435 if (self.signature) |sig| {
436 ssize += @sizeOf(macho.BlobIndex) + sig.size();436 ssize += @sizeOf(macho.BlobIndex) + sig.size();
src/link/MachO/Object.zig+1-1
...@@ -530,7 +530,7 @@ pub fn splitRegularSections(self: *Object, zld: *Zld, object_id: u32) !void {...@@ -530,7 +530,7 @@ pub fn splitRegularSections(self: *Object, zld: *Zld, object_id: u32) !void {
530 sect.addr + sect.size - addr;530 sect.addr + sect.size - addr;
531531
532 const atom_align = if (addr > 0)532 const atom_align = if (addr > 0)
533 math.min(@ctz(addr), sect.@"align")533 @min(@ctz(addr), sect.@"align")
534 else534 else
535 sect.@"align";535 sect.@"align";
536536
src/link/Wasm.zig+1-1
...@@ -2027,7 +2027,7 @@ fn parseAtom(wasm: *Wasm, atom_index: Atom.Index, kind: Kind) !void {...@@ -2027,7 +2027,7 @@ fn parseAtom(wasm: *Wasm, atom_index: Atom.Index, kind: Kind) !void {
2027 };2027 };
20282028
2029 const segment: *Segment = &wasm.segments.items[final_index];2029 const segment: *Segment = &wasm.segments.items[final_index];
2030 segment.alignment = std.math.max(segment.alignment, atom.alignment);2030 segment.alignment = @max(segment.alignment, atom.alignment);
20312031
2032 try wasm.appendAtomAtIndex(final_index, atom_index);2032 try wasm.appendAtomAtIndex(final_index, atom_index);
2033}2033}
src/link/Wasm/Object.zig+1-1
...@@ -979,7 +979,7 @@ pub fn parseIntoAtoms(object: *Object, gpa: Allocator, object_index: u16, wasm_b...@@ -979,7 +979,7 @@ pub fn parseIntoAtoms(object: *Object, gpa: Allocator, object_index: u16, wasm_b
979979
980 const segment: *Wasm.Segment = &wasm_bin.segments.items[final_index];980 const segment: *Wasm.Segment = &wasm_bin.segments.items[final_index];
981 if (relocatable_data.type == .data) { //code section and debug sections are 1-byte aligned981 if (relocatable_data.type == .data) { //code section and debug sections are 1-byte aligned
982 segment.alignment = std.math.max(segment.alignment, atom.alignment);982 segment.alignment = @max(segment.alignment, atom.alignment);
983 }983 }
984984
985 try wasm_bin.appendAtomAtIndex(final_index, atom_index);985 try wasm_bin.appendAtomAtIndex(final_index, atom_index);
src/main.zig+1-1
...@@ -5391,7 +5391,7 @@ fn gimmeMoreOfThoseSweetSweetFileDescriptors() void {...@@ -5391,7 +5391,7 @@ fn gimmeMoreOfThoseSweetSweetFileDescriptors() void {
5391 // setrlimit() now returns with errno set to EINVAL in places that historically succeeded.5391 // setrlimit() now returns with errno set to EINVAL in places that historically succeeded.
5392 // It no longer accepts "rlim_cur = RLIM.INFINITY" for RLIM.NOFILE.5392 // It no longer accepts "rlim_cur = RLIM.INFINITY" for RLIM.NOFILE.
5393 // Use "rlim_cur = min(OPEN_MAX, rlim_max)".5393 // Use "rlim_cur = min(OPEN_MAX, rlim_max)".
5394 lim.max = std.math.min(std.os.darwin.OPEN_MAX, lim.max);5394 lim.max = @min(std.os.darwin.OPEN_MAX, lim.max);
5395 }5395 }
5396 if (lim.cur == lim.max) return;5396 if (lim.cur == lim.max) return;
53975397
src/translate_c.zig+1-1
...@@ -2400,7 +2400,7 @@ fn transStringLiteralInitializer(...@@ -2400,7 +2400,7 @@ fn transStringLiteralInitializer(
24002400
2401 if (array_size == 0) return Tag.empty_array.create(c.arena, elem_type);2401 if (array_size == 0) return Tag.empty_array.create(c.arena, elem_type);
24022402
2403 const num_inits = math.min(str_length, array_size);2403 const num_inits = @min(str_length, array_size);
2404 const init_node = if (num_inits > 0) blk: {2404 const init_node = if (num_inits > 0) blk: {
2405 if (is_narrow) {2405 if (is_narrow) {
2406 // "string literal".* or string literal"[0..num_inits].*2406 // "string literal".* or string literal"[0..num_inits].*
src/translate_c/ast.zig+7-7
...@@ -1824,7 +1824,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -1824,7 +1824,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
1824 },1824 },
1825 .switch_prong => {1825 .switch_prong => {
1826 const payload = node.castTag(.switch_prong).?.data;1826 const payload = node.castTag(.switch_prong).?.data;
1827 var items = try c.gpa.alloc(NodeIndex, std.math.max(payload.cases.len, 1));1827 var items = try c.gpa.alloc(NodeIndex, @max(payload.cases.len, 1));
1828 defer c.gpa.free(items);1828 defer c.gpa.free(items);
1829 items[0] = 0;1829 items[0] = 0;
1830 for (payload.cases, 0..) |item, i| {1830 for (payload.cases, 0..) |item, i| {
...@@ -1973,7 +1973,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -1973,7 +1973,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
1973 const payload = node.castTag(.tuple).?.data;1973 const payload = node.castTag(.tuple).?.data;
1974 _ = try c.addToken(.period, ".");1974 _ = try c.addToken(.period, ".");
1975 const l_brace = try c.addToken(.l_brace, "{");1975 const l_brace = try c.addToken(.l_brace, "{");
1976 var inits = try c.gpa.alloc(NodeIndex, std.math.max(payload.len, 2));1976 var inits = try c.gpa.alloc(NodeIndex, @max(payload.len, 2));
1977 defer c.gpa.free(inits);1977 defer c.gpa.free(inits);
1978 inits[0] = 0;1978 inits[0] = 0;
1979 inits[1] = 0;1979 inits[1] = 0;
...@@ -2007,7 +2007,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -2007,7 +2007,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
2007 const payload = node.castTag(.container_init_dot).?.data;2007 const payload = node.castTag(.container_init_dot).?.data;
2008 _ = try c.addToken(.period, ".");2008 _ = try c.addToken(.period, ".");
2009 const l_brace = try c.addToken(.l_brace, "{");2009 const l_brace = try c.addToken(.l_brace, "{");
2010 var inits = try c.gpa.alloc(NodeIndex, std.math.max(payload.len, 2));2010 var inits = try c.gpa.alloc(NodeIndex, @max(payload.len, 2));
2011 defer c.gpa.free(inits);2011 defer c.gpa.free(inits);
2012 inits[0] = 0;2012 inits[0] = 0;
2013 inits[1] = 0;2013 inits[1] = 0;
...@@ -2046,7 +2046,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {...@@ -2046,7 +2046,7 @@ fn renderNode(c: *Context, node: Node) Allocator.Error!NodeIndex {
2046 const lhs = try renderNode(c, payload.lhs);2046 const lhs = try renderNode(c, payload.lhs);
20472047
2048 const l_brace = try c.addToken(.l_brace, "{");2048 const l_brace = try c.addToken(.l_brace, "{");
2049 var inits = try c.gpa.alloc(NodeIndex, std.math.max(payload.inits.len, 1));2049 var inits = try c.gpa.alloc(NodeIndex, @max(payload.inits.len, 1));
2050 defer c.gpa.free(inits);2050 defer c.gpa.free(inits);
2051 inits[0] = 0;2051 inits[0] = 0;
2052 for (payload.inits, 0..) |init, i| {2052 for (payload.inits, 0..) |init, i| {
...@@ -2102,7 +2102,7 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {...@@ -2102,7 +2102,7 @@ fn renderRecord(c: *Context, node: Node) !NodeIndex {
2102 const num_vars = payload.variables.len;2102 const num_vars = payload.variables.len;
2103 const num_funcs = payload.functions.len;2103 const num_funcs = payload.functions.len;
2104 const total_members = payload.fields.len + num_vars + num_funcs;2104 const total_members = payload.fields.len + num_vars + num_funcs;
2105 const members = try c.gpa.alloc(NodeIndex, std.math.max(total_members, 2));2105 const members = try c.gpa.alloc(NodeIndex, @max(total_members, 2));
2106 defer c.gpa.free(members);2106 defer c.gpa.free(members);
2107 members[0] = 0;2107 members[0] = 0;
2108 members[1] = 0;2108 members[1] = 0;
...@@ -2195,7 +2195,7 @@ fn renderFieldAccess(c: *Context, lhs: NodeIndex, field_name: []const u8) !NodeI...@@ -2195,7 +2195,7 @@ fn renderFieldAccess(c: *Context, lhs: NodeIndex, field_name: []const u8) !NodeI
21952195
2196fn renderArrayInit(c: *Context, lhs: NodeIndex, inits: []const Node) !NodeIndex {2196fn renderArrayInit(c: *Context, lhs: NodeIndex, inits: []const Node) !NodeIndex {
2197 const l_brace = try c.addToken(.l_brace, "{");2197 const l_brace = try c.addToken(.l_brace, "{");
2198 var rendered = try c.gpa.alloc(NodeIndex, std.math.max(inits.len, 1));2198 var rendered = try c.gpa.alloc(NodeIndex, @max(inits.len, 1));
2199 defer c.gpa.free(rendered);2199 defer c.gpa.free(rendered);
2200 rendered[0] = 0;2200 rendered[0] = 0;
2201 for (inits, 0..) |init, i| {2201 for (inits, 0..) |init, i| {
...@@ -2904,7 +2904,7 @@ fn renderMacroFunc(c: *Context, node: Node) !NodeIndex {...@@ -2904,7 +2904,7 @@ fn renderMacroFunc(c: *Context, node: Node) !NodeIndex {
29042904
2905fn renderParams(c: *Context, params: []Payload.Param, is_var_args: bool) !std.ArrayList(NodeIndex) {2905fn renderParams(c: *Context, params: []Payload.Param, is_var_args: bool) !std.ArrayList(NodeIndex) {
2906 _ = try c.addToken(.l_paren, "(");2906 _ = try c.addToken(.l_paren, "(");
2907 var rendered = try std.ArrayList(NodeIndex).initCapacity(c.gpa, std.math.max(params.len, 1));2907 var rendered = try std.ArrayList(NodeIndex).initCapacity(c.gpa, @max(params.len, 1));
2908 errdefer rendered.deinit();2908 errdefer rendered.deinit();
29092909
2910 for (params, 0..) |param, i| {2910 for (params, 0..) |param, i| {
src/type.zig+1-1
...@@ -1633,7 +1633,7 @@ pub const Type = struct {...@@ -1633,7 +1633,7 @@ pub const Type = struct {
1633 const len = array_type.len + @boolToInt(array_type.sentinel != .none);1633 const len = array_type.len + @boolToInt(array_type.sentinel != .none);
1634 if (len == 0) return 0;1634 if (len == 0) return 0;
1635 const elem_ty = array_type.child.toType();1635 const elem_ty = array_type.child.toType();
1636 const elem_size = std.math.max(elem_ty.abiAlignment(mod), elem_ty.abiSize(mod));1636 const elem_size = @max(elem_ty.abiAlignment(mod), elem_ty.abiSize(mod));
1637 if (elem_size == 0) return 0;1637 if (elem_size == 0) return 0;
1638 const elem_bit_size = try bitSizeAdvanced(elem_ty, mod, opt_sema);1638 const elem_bit_size = try bitSizeAdvanced(elem_ty, mod, opt_sema);
1639 return (len - 1) * 8 * elem_size + elem_bit_size;1639 return (len - 1) * 8 * elem_size + elem_bit_size;
src/value.zig+18-4
...@@ -2458,7 +2458,7 @@ pub const Value = struct {...@@ -2458,7 +2458,7 @@ pub const Value = struct {
2458 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);2458 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2459 const limbs = try arena.alloc(2459 const limbs = try arena.alloc(
2460 std.math.big.Limb,2460 std.math.big.Limb,
2461 std.math.max(2461 @max(
2462 // For the saturate2462 // For the saturate
2463 std.math.big.int.calcTwosCompLimbCount(info.bits),2463 std.math.big.int.calcTwosCompLimbCount(info.bits),
2464 lhs_bigint.limbs.len + rhs_bigint.limbs.len,2464 lhs_bigint.limbs.len + rhs_bigint.limbs.len,
...@@ -2572,7 +2572,7 @@ pub const Value = struct {...@@ -2572,7 +2572,7 @@ pub const Value = struct {
2572 const limbs = try arena.alloc(2572 const limbs = try arena.alloc(
2573 std.math.big.Limb,2573 std.math.big.Limb,
2574 // + 1 for negatives2574 // + 1 for negatives
2575 std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,2575 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
2576 );2576 );
2577 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };2577 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
2578 result_bigint.bitAnd(lhs_bigint, rhs_bigint);2578 result_bigint.bitAnd(lhs_bigint, rhs_bigint);
...@@ -2638,7 +2638,7 @@ pub const Value = struct {...@@ -2638,7 +2638,7 @@ pub const Value = struct {
2638 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);2638 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2639 const limbs = try arena.alloc(2639 const limbs = try arena.alloc(
2640 std.math.big.Limb,2640 std.math.big.Limb,
2641 std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len),2641 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
2642 );2642 );
2643 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };2643 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
2644 result_bigint.bitOr(lhs_bigint, rhs_bigint);2644 result_bigint.bitOr(lhs_bigint, rhs_bigint);
...@@ -2677,7 +2677,7 @@ pub const Value = struct {...@@ -2677,7 +2677,7 @@ pub const Value = struct {
2677 const limbs = try arena.alloc(2677 const limbs = try arena.alloc(
2678 std.math.big.Limb,2678 std.math.big.Limb,
2679 // + 1 for negatives2679 // + 1 for negatives
2680 std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,2680 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
2681 );2681 );
2682 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };2682 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
2683 result_bigint.bitXor(lhs_bigint, rhs_bigint);2683 result_bigint.bitXor(lhs_bigint, rhs_bigint);
...@@ -4146,6 +4146,20 @@ pub const Value = struct {...@@ -4146,6 +4146,20 @@ pub const Value = struct {
4146 return val.toIntern() == .generic_poison;4146 return val.toIntern() == .generic_poison;
4147 }4147 }
41484148
4149 /// For an integer (comptime or fixed-width) `val`, returns the comptime-known bounds of the value.
4150 /// If `val` is not undef, the bounds are both `val`.
4151 /// If `val` is undef and has a fixed-width type, the bounds are the bounds of the type.
4152 /// If `val` is undef and is a `comptime_int`, returns null.
4153 pub fn intValueBounds(val: Value, mod: *Module) !?[2]Value {
4154 if (!val.isUndef(mod)) return .{ val, val };
4155 const ty = mod.intern_pool.typeOf(val.toIntern());
4156 if (ty == .comptime_int_type) return null;
4157 return .{
4158 try ty.toType().minInt(mod, ty.toType()),
4159 try ty.toType().maxInt(mod, ty.toType()),
4160 };
4161 }
4162
4149 /// This type is not copyable since it may contain pointers to its inner data.4163 /// This type is not copyable since it may contain pointers to its inner data.
4150 pub const Payload = struct {4164 pub const Payload = struct {
4151 tag: Tag,4165 tag: Tag,
stage1/zig.h+17-20
...@@ -487,14 +487,14 @@ typedef ptrdiff_t intptr_t;...@@ -487,14 +487,14 @@ typedef ptrdiff_t intptr_t;
487 zig_basic_operator(uint##w##_t, div_floor_u##w, /) \487 zig_basic_operator(uint##w##_t, div_floor_u##w, /) \
488\488\
489 static inline int##w##_t zig_div_floor_i##w(int##w##_t lhs, int##w##_t rhs) { \489 static inline int##w##_t zig_div_floor_i##w(int##w##_t lhs, int##w##_t rhs) { \
490 return lhs / rhs - (((lhs ^ rhs) & (lhs % rhs)) < INT##w##_C(0)); \490 return lhs / rhs + (lhs % rhs != INT##w##_C(0) ? zig_shr_i##w(lhs ^ rhs, UINT8_C(w) - UINT8_C(1)) : INT##w##_C(0)); \
491 } \491 } \
492\492\
493 zig_basic_operator(uint##w##_t, mod_u##w, %) \493 zig_basic_operator(uint##w##_t, mod_u##w, %) \
494\494\
495 static inline int##w##_t zig_mod_i##w(int##w##_t lhs, int##w##_t rhs) { \495 static inline int##w##_t zig_mod_i##w(int##w##_t lhs, int##w##_t rhs) { \
496 int##w##_t rem = lhs % rhs; \496 int##w##_t rem = lhs % rhs; \
497 return rem + (((lhs ^ rhs) & rem) < INT##w##_C(0) ? rhs : INT##w##_C(0)); \497 return rem + (rem != INT##w##_C(0) ? rhs & zig_shr_i##w(lhs ^ rhs, UINT8_C(w) - UINT8_C(1)) : INT##w##_C(0)); \
498 } \498 } \
499\499\
500 static inline uint##w##_t zig_shlw_u##w(uint##w##_t lhs, uint8_t rhs, uint8_t bits) { \500 static inline uint##w##_t zig_shlw_u##w(uint##w##_t lhs, uint8_t rhs, uint8_t bits) { \
...@@ -1078,7 +1078,7 @@ static inline int64_t zig_bit_reverse_i64(int64_t val, uint8_t bits) {...@@ -1078,7 +1078,7 @@ static inline int64_t zig_bit_reverse_i64(int64_t val, uint8_t bits) {
1078 uint##w##_t temp = val - ((val >> 1) & (UINT##w##_MAX / 3)); \1078 uint##w##_t temp = val - ((val >> 1) & (UINT##w##_MAX / 3)); \
1079 temp = (temp & (UINT##w##_MAX / 5)) + ((temp >> 2) & (UINT##w##_MAX / 5)); \1079 temp = (temp & (UINT##w##_MAX / 5)) + ((temp >> 2) & (UINT##w##_MAX / 5)); \
1080 temp = (temp + (temp >> 4)) & (UINT##w##_MAX / 17); \1080 temp = (temp + (temp >> 4)) & (UINT##w##_MAX / 17); \
1081 return temp * (UINT##w##_MAX / 255) >> (w - 8); \1081 return temp * (UINT##w##_MAX / 255) >> (UINT8_C(w) - UINT8_C(8)); \
1082 } \1082 } \
1083\1083\
1084 zig_builtin_popcount_common(w)1084 zig_builtin_popcount_common(w)
...@@ -1298,15 +1298,6 @@ static inline zig_i128 zig_rem_i128(zig_i128 lhs, zig_i128 rhs) {...@@ -1298,15 +1298,6 @@ static inline zig_i128 zig_rem_i128(zig_i128 lhs, zig_i128 rhs) {
1298 return lhs % rhs;1298 return lhs % rhs;
1299}1299}
13001300
1301static inline zig_i128 zig_div_floor_i128(zig_i128 lhs, zig_i128 rhs) {
1302 return zig_div_trunc_i128(lhs, rhs) - (((lhs ^ rhs) & zig_rem_i128(lhs, rhs)) < zig_make_i128(0, 0));
1303}
1304
1305static inline zig_i128 zig_mod_i128(zig_i128 lhs, zig_i128 rhs) {
1306 zig_i128 rem = zig_rem_i128(lhs, rhs);
1307 return rem + (((lhs ^ rhs) & rem) < zig_make_i128(0, 0) ? rhs : zig_make_i128(0, 0));
1308}
1309
1310#else /* zig_has_int128 */1301#else /* zig_has_int128 */
13111302
1312static inline zig_u128 zig_not_u128(zig_u128 val, uint8_t bits) {1303static inline zig_u128 zig_not_u128(zig_u128 val, uint8_t bits) {
...@@ -1394,20 +1385,26 @@ static zig_i128 zig_rem_i128(zig_i128 lhs, zig_i128 rhs) {...@@ -1394,20 +1385,26 @@ static zig_i128 zig_rem_i128(zig_i128 lhs, zig_i128 rhs) {
1394 return __modti3(lhs, rhs);1385 return __modti3(lhs, rhs);
1395}1386}
13961387
1397static inline zig_i128 zig_mod_i128(zig_i128 lhs, zig_i128 rhs) {1388#endif /* zig_has_int128 */
1398 zig_i128 rem = zig_rem_i128(lhs, rhs);1389
1399 return zig_add_i128(rem, ((lhs.hi ^ rhs.hi) & rem.hi) < INT64_C(0) ? rhs : zig_make_i128(0, 0));1390#define zig_div_floor_u128 zig_div_trunc_u128
1400}
14011391
1402static inline zig_i128 zig_div_floor_i128(zig_i128 lhs, zig_i128 rhs) {1392static inline zig_i128 zig_div_floor_i128(zig_i128 lhs, zig_i128 rhs) {
1403 return zig_sub_i128(zig_div_trunc_i128(lhs, rhs), zig_make_i128(0, zig_cmp_i128(zig_and_i128(zig_xor_i128(lhs, rhs), zig_rem_i128(lhs, rhs)), zig_make_i128(0, 0)) < INT32_C(0)));1393 zig_i128 rem = zig_rem_i128(lhs, rhs);
1394 int64_t mask = zig_or_u64((uint64_t)zig_hi_i128(rem), zig_lo_i128(rem)) != UINT64_C(0)
1395 ? zig_shr_i64(zig_xor_i64(zig_hi_i128(lhs), zig_hi_i128(rhs)), UINT8_C(63)) : INT64_C(0);
1396 return zig_add_i128(zig_div_trunc_i128(lhs, rhs), zig_make_i128(mask, (uint64_t)mask));
1404}1397}
14051398
1406#endif /* zig_has_int128 */
1407
1408#define zig_div_floor_u128 zig_div_trunc_u128
1409#define zig_mod_u128 zig_rem_u1281399#define zig_mod_u128 zig_rem_u128
14101400
1401static inline zig_i128 zig_mod_i128(zig_i128 lhs, zig_i128 rhs) {
1402 zig_i128 rem = zig_rem_i128(lhs, rhs);
1403 int64_t mask = zig_or_u64((uint64_t)zig_hi_i128(rem), zig_lo_i128(rem)) != UINT64_C(0)
1404 ? zig_shr_i64(zig_xor_i64(zig_hi_i128(lhs), zig_hi_i128(rhs)), UINT8_C(63)) : INT64_C(0);
1405 return zig_add_i128(rem, zig_and_i128(rhs, zig_make_i128(mask, (uint64_t)mask)));
1406}
1407
1411static inline zig_u128 zig_min_u128(zig_u128 lhs, zig_u128 rhs) {1408static inline zig_u128 zig_min_u128(zig_u128 lhs, zig_u128 rhs) {
1412 return zig_cmp_u128(lhs, rhs) < INT32_C(0) ? lhs : rhs;1409 return zig_cmp_u128(lhs, rhs) < INT32_C(0) ? lhs : rhs;
1413}1410}
stage1/zig1.wasm
Binary files a/stage1/zig1.wasm and b/stage1/zig1.wasm differ
test/behavior/maximum_minimum.zig+85
...@@ -1,6 +1,7 @@...@@ -1,6 +1,7 @@
1const std = @import("std");1const std = @import("std");
2const builtin = @import("builtin");2const builtin = @import("builtin");
3const mem = std.mem;3const mem = std.mem;
4const assert = std.debug.assert;
4const expect = std.testing.expect;5const expect = std.testing.expect;
5const expectEqual = std.testing.expectEqual;6const expectEqual = std.testing.expectEqual;
67
...@@ -210,3 +211,87 @@ test "@min/@max on comptime_int" {...@@ -210,3 +211,87 @@ test "@min/@max on comptime_int" {
210 try expectEqual(-2, min);211 try expectEqual(-2, min);
211 try expectEqual(2, max);212 try expectEqual(2, max);
212}213}
214
215test "@min/@max notices bounds from types" {
216 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
217 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
218 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
219 if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;
220
221 var x: u16 = 123;
222 var y: u32 = 456;
223 var z: u8 = 10;
224
225 const min = @min(x, y, z);
226 const max = @max(x, y, z);
227
228 comptime assert(@TypeOf(min) == u8);
229 comptime assert(@TypeOf(max) == u32);
230
231 try expectEqual(z, min);
232 try expectEqual(y, max);
233}
234
235test "@min/@max notices bounds from vector types" {
236 if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
237 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
238 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
239 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
240 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
241 if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;
242
243 var x: @Vector(2, u16) = .{ 30, 67 };
244 var y: @Vector(2, u32) = .{ 20, 500 };
245 var z: @Vector(2, u8) = .{ 60, 15 };
246
247 const min = @min(x, y, z);
248 const max = @max(x, y, z);
249
250 comptime assert(@TypeOf(min) == @Vector(2, u8));
251 comptime assert(@TypeOf(max) == @Vector(2, u32));
252
253 try expectEqual(@Vector(2, u8){ 20, 15 }, min);
254 try expectEqual(@Vector(2, u32){ 60, 500 }, max);
255}
256
257test "@min/@max notices bounds from types when comptime-known value is undef" {
258 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
259 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
260 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
261 if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;
262
263 var x: u32 = 1_000_000;
264 const y: u16 = undefined;
265 // y is comptime-known, but is undef, so bounds cannot be refined using its value
266
267 const min = @min(x, y);
268 const max = @max(x, y);
269
270 comptime assert(@TypeOf(min) == u16);
271 comptime assert(@TypeOf(max) == u32);
272
273 // Cannot assert values as one was undefined
274}
275
276test "@min/@max notices bounds from vector types when element of comptime-known vector is undef" {
277 if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
278 if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
279 if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
280 if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
281 if (builtin.zig_backend == .stage2_sparc64) return error.SkipZigTest; // TODO
282 if (builtin.zig_backend == .stage2_spirv64) return error.SkipZigTest;
283
284 var x: @Vector(2, u32) = .{ 1_000_000, 12345 };
285 const y: @Vector(2, u16) = .{ 10, undefined };
286 // y is comptime-known, but an element is undef, so bounds cannot be refined using its value
287
288 const min = @min(x, y);
289 const max = @max(x, y);
290
291 comptime assert(@TypeOf(min) == @Vector(2, u16));
292 comptime assert(@TypeOf(max) == @Vector(2, u32));
293
294 try expectEqual(@as(u16, 10), min[0]);
295 try expectEqual(@as(u32, 1_000_000), max[0]);
296 // Cannot assert values at index 1 as one was undefined
297}