uint.rs: added functions div_ceil, div_floor, div_round
This commit is contained in:
parent
f4399063fc
commit
07ffe68ad9
@ -34,6 +34,29 @@ pure fn mul(x: uint, y: uint) -> uint { ret x * y; }
|
||||
/* Function: div */
|
||||
pure fn div(x: uint, y: uint) -> uint { ret x / y; }
|
||||
|
||||
/**
|
||||
* Divide two numbers, return the result, rounded up.
|
||||
*/
|
||||
pure fn div_ceil(x: uint, y: uint) -> uint {
|
||||
let div = div(x, y);
|
||||
if x % y == 0u { ret div;}
|
||||
else { ret div + 1u; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Divide two numbers, return the result, rounded to the closest integer.
|
||||
*/
|
||||
pure fn div_round(x: uint, y: uint) -> uint {
|
||||
let div = div(x, y);
|
||||
if x % y * 2u < y { ret div;}
|
||||
else { ret div + 1u; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Divide two numbers, return the result, rounded down.
|
||||
*/
|
||||
pure fn div_floor(x: uint, y: uint) -> uint { ret x / y; }
|
||||
|
||||
/* Function: rem */
|
||||
pure fn rem(x: uint, y: uint) -> uint { ret x % y; }
|
||||
|
||||
|
@ -102,3 +102,10 @@ fn test_overflows() {
|
||||
assert (uint::min_value() <= 0u);
|
||||
assert (uint::min_value() + uint::max_value() + 1u == 0u);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_div() {
|
||||
assert(uint::div_floor(3u, 4u) == 0u);
|
||||
assert(uint::div_ceil(3u, 4u) == 1u);
|
||||
assert(uint::div_round(3u, 4u) == 1u);
|
||||
}
|
Loading…
Reference in New Issue
Block a user