Skip to content

Commit 6a8ba95

Browse files
David Rajchenbach-Tellerbrson
authored andcommitted
---
yaml --- r: 6143 b: refs/heads/master c: 07ffe68 h: refs/heads/master i: 6141: b0b6f9a 6139: 3753328 6135: 617fa82 6127: f9c2d3b 6111: 64f5f9a 6079: f30c23b 6015: ab62096 5887: 5e4beb8 5631: 9c6cf88 5119: 6aa0c94 4095: 21df5ad v: v3
1 parent f908b57 commit 6a8ba95

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
11
---
2-
refs/heads/master: f4399063fc2a3bd6e34bee185abfb6b56c4236a7
2+
refs/heads/master: 07ffe68ad9145a209725ac289f8c4235b4c9b334

trunk/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

trunk/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)