Skip to content

Commit 07ffe68

Browse files
David Rajchenbach-Tellerbrson
authored andcommitted
uint.rs: added functions div_ceil, div_floor, div_round
1 parent f439906 commit 07ffe68

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/lib/uint.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,29 @@ pure fn mul(x: uint, y: uint) -> uint { ret x * y; }
3434
/* Function: div */
3535
pure fn div(x: uint, y: uint) -> uint { ret x / y; }
3636

37+
/**
38+
* Divide two numbers, return the result, rounded up.
39+
*/
40+
pure fn div_ceil(x: uint, y: uint) -> uint {
41+
let div = div(x, y);
42+
if x % y == 0u { ret div;}
43+
else { ret div + 1u; }
44+
}
45+
46+
/**
47+
* Divide two numbers, return the result, rounded to the closest integer.
48+
*/
49+
pure fn div_round(x: uint, y: uint) -> uint {
50+
let div = div(x, y);
51+
if x % y * 2u < y { ret div;}
52+
else { ret div + 1u; }
53+
}
54+
55+
/**
56+
* Divide two numbers, return the result, rounded down.
57+
*/
58+
pure fn div_floor(x: uint, y: uint) -> uint { ret x / y; }
59+
3760
/* Function: rem */
3861
pure fn rem(x: uint, y: uint) -> uint { ret x % y; }
3962

src/test/stdtest/uint.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,3 +102,10 @@ fn test_overflows() {
102102
assert (uint::min_value() <= 0u);
103103
assert (uint::min_value() + uint::max_value() + 1u == 0u);
104104
}
105+
106+
#[test]
107+
fn test_div() {
108+
assert(uint::div_floor(3u, 4u) == 0u);
109+
assert(uint::div_ceil(3u, 4u) == 1u);
110+
assert(uint::div_round(3u, 4u) == 1u);
111+
}

0 commit comments

Comments
 (0)