Skip to content

Commit

Permalink
uint.rs: added functions div_ceil, div_floor, div_round
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoric authored and brson committed Nov 5, 2011
1 parent f439906 commit 07ffe68
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/lib/uint.rs
Expand Up @@ -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; }

Expand Down
7 changes: 7 additions & 0 deletions src/test/stdtest/uint.rs
Expand Up @@ -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);
}

0 comments on commit 07ffe68

Please sign in to comment.