summary refs log tree commit diff
path: root/src/libstd/sys/common
diff options
context:
space:
mode:
Diffstat (limited to 'src/libstd/sys/common')
-rw-r--r--src/libstd/sys/common/mod.rs19
1 files changed, 19 insertions, 0 deletions
diff --git a/src/libstd/sys/common/mod.rs b/src/libstd/sys/common/mod.rs
index 44c55d1e2c4..5062be8cd63 100644
--- a/src/libstd/sys/common/mod.rs
+++ b/src/libstd/sys/common/mod.rs
@@ -98,3 +98,22 @@ pub fn cleanup() {
         at_exit_imp::cleanup();
     });
 }
+
+// Computes (value*numer)/denom without overflow, as long as both
+// (numer*denom) and the overall result fit into i64 (which is the case
+// for our time conversions).
+#[allow(dead_code)] // not used on all platforms
+pub fn mul_div_u64(value: u64, numer: u64, denom: u64) -> u64 {
+    let q = value / denom;
+    let r = value % denom;
+    // Decompose value as (value/denom*denom + value%denom),
+    // substitute into (value*numer)/denom and simplify.
+    // r < denom, so (denom*numer) is the upper bound of (r*numer)
+    q * numer + r * numer / denom
+}
+
+#[test]
+fn test_muldiv() {
+    assert_eq!(mul_div_u64( 1_000_000_000_001, 1_000_000_000, 1_000_000),
+               1_000_000_000_001_000);
+}