Add compile-time @min and @max (#2378)

* Add compile-time `@min` and `@max`
This commit is contained in:
Zack Puhl
2025-08-13 11:23:24 -04:00
committed by GitHub
parent f5e6b697b8
commit c8d39251a9
3 changed files with 44 additions and 1 deletions

View File

@@ -126,3 +126,36 @@ macro max(x, ...) @builtin
$endif
}
<*
@require types::is_numerical($typeof($a))
*>
macro @max($a, ...) @builtin @const
{
$if $vacount == 1:
return $a > $vaconst[0] ? $a : $vaconst[0];
$else
var $result = $a;
$for var $x = 0; $x < $vacount; ++$x:
$if $vaconst[$x] > $result: $result = $vaconst[$x]; $endif
$endfor
return $result;
$endif
}
<*
@require types::is_numerical($typeof($a))
*>
macro @min($a, ...) @builtin @const
{
$if $vacount == 1:
return $a < $vaconst[0] ? $a : $vaconst[0];
$else
var $result = $a;
$for var $x = 0; $x < $vacount; ++$x:
$if $vaconst[$x] < $result: $result = $vaconst[$x]; $endif
$endfor
return $result;
$endif
}

View File

@@ -7,6 +7,7 @@
- Add compile-time `@intlog2` macro to math.
- Add compile-time `@clz` builtin. #2367
- Add `bitsizeof` macro builtins. #2376
- Add compile-time `@min` and `@max` builtins. #2378
### Fixes
- List.remove_at would incorrectly trigger ASAN.

View File

@@ -202,4 +202,13 @@ fn void test_bitsizeof()
assert(@bitsizeof(0x1000ul) == 64);
assert(@bitsizeof(0) == 32);
assert(@bitsizeof((char[*])"abcdefghi") == 72);
}
}
fn void test_ct_min_max()
{
assert(@min(4, 5) == 4);
assert(@max(1.234, 1.2345) == 1.2345);
assert(@min(4, 5, 6, 7, 8.90, 3.14) == 3.14);
assert(@max(0, 0, 1.234, 1.2345, 0.2) == 1.2345);
assert(@max(127.9999999, 45 + 46, bitsizeof(uint128)) == 128);
}