1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

math: add maxof[T]() and minof[T]() (#17905)

This commit is contained in:
lemon 2023-04-07 21:48:37 +09:00 committed by GitHub
parent 237f9446e2
commit e300fb428a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 96 additions and 0 deletions

68
vlib/math/limit.v Normal file
View File

@ -0,0 +1,68 @@
// Copyright (c) 2019-2023 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module math
// maxof returns the maximum value of the type `T`
[inline]
pub fn maxof[T]() T {
$if T is i8 {
return max_i8
} $else $if T is i16 {
return max_i16
} $else $if T is int {
return max_i32
} $else $if T is i32 {
return max_i32
} $else $if T is i64 {
return max_i64
} $else $if T is u8 {
return max_u8
} $else $if T is byte {
return max_u8
} $else $if T is u16 {
return max_u16
} $else $if T is u32 {
return max_u32
} $else $if T is u64 {
return max_u64
} $else $if T is f32 {
return max_f32
} $else $if T is f64 {
return max_f64
} $else {
panic('A maximum value of the type `${typeof[T]().name}` is not defined.')
}
}
// minof returns the minimum value of the type `T`
[inline]
pub fn minof[T]() T {
$if T is i8 {
return min_i8
} $else $if T is i16 {
return min_i16
} $else $if T is int {
return min_i32
} $else $if T is i32 {
return min_i32
} $else $if T is i64 {
return min_i64
} $else $if T is u8 {
return min_u8
} $else $if T is byte {
return min_u8
} $else $if T is u16 {
return min_u16
} $else $if T is u32 {
return min_u32
} $else $if T is u64 {
return min_u64
} $else $if T is f32 {
return -max_f32
} $else $if T is f64 {
return -max_f64
} $else {
panic('A minimum value of the type `${typeof[T]().name}` is not defined.')
}
}

View File

@ -1059,3 +1059,31 @@ fn test_min_max_int_str() {
assert min_i8.str() == '-128' assert min_i8.str() == '-128'
assert max_i8.str() == '127' assert max_i8.str() == '127'
} }
fn test_maxof_minof() {
assert maxof[i8]() == 127
assert maxof[i16]() == 32767
assert maxof[int]() == 2147483647
assert maxof[i32]() == 2147483647
assert maxof[i64]() == 9223372036854775807
assert maxof[u8]() == 255
assert maxof[byte]() == 255
assert maxof[u16]() == 65535
assert maxof[u32]() == 4294967295
assert maxof[u64]() == 18446744073709551615
assert maxof[f32]() == 3.40282346638528859811704183484516925440e+38
assert maxof[f64]() == 1.797693134862315708145274237317043567981e+308
assert minof[i8]() == -128
assert minof[i16]() == -32768
assert minof[int]() == -2147483648
assert minof[i32]() == -2147483648
assert minof[i64]() == -9223372036854775807 - 1
assert minof[u8]() == 0
assert minof[byte]() == 0
assert minof[u16]() == 0
assert minof[u32]() == 0
assert minof[u64]() == 0
assert minof[f32]() == -3.40282346638528859811704183484516925440e+38
assert minof[f64]() == -1.797693134862315708145274237317043567981e+308
}