uint.rs: added functions div_ceil, div_floor, div_round

This commit is contained in:
David Rajchenbach-Teller 2011-11-03 09:37:45 +01:00 committed by Brian Anderson
parent f4399063fc
commit 07ffe68ad9
2 changed files with 30 additions and 0 deletions

View File

@ -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; }

View File

@ -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);
}