From 07ffe68ad9145a209725ac289f8c4235b4c9b334 Mon Sep 17 00:00:00 2001 From: David Rajchenbach-Teller Date: Thu, 3 Nov 2011 09:37:45 +0100 Subject: [PATCH] uint.rs: added functions div_ceil, div_floor, div_round --- src/lib/uint.rs | 23 +++++++++++++++++++++++ src/test/stdtest/uint.rs | 7 +++++++ 2 files changed, 30 insertions(+) diff --git a/src/lib/uint.rs b/src/lib/uint.rs index a9ea4d03c90..561acc66d66 100644 --- a/src/lib/uint.rs +++ b/src/lib/uint.rs @@ -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; } diff --git a/src/test/stdtest/uint.rs b/src/test/stdtest/uint.rs index 0ba2ac39c1d..28546f4a6f1 100644 --- a/src/test/stdtest/uint.rs +++ b/src/test/stdtest/uint.rs @@ -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); +} \ No newline at end of file