]> git.lizzy.rs Git - rust.git/commitdiff
Make next_power_of_two generic for unsigned integers
authorBrendan Zabarauskas <bjzaba@yahoo.com.au>
Thu, 30 Jan 2014 05:35:17 +0000 (16:35 +1100)
committerBrendan Zabarauskas <bjzaba@yahoo.com.au>
Sat, 1 Feb 2014 02:02:53 +0000 (13:02 +1100)
Also rename `next_power_of_two_opt` to `checked_next_power_of_two`.

src/libarena/lib.rs
src/libstd/at_vec.rs
src/libstd/hashmap.rs
src/libstd/num/mod.rs
src/libstd/num/uint.rs
src/libstd/str.rs
src/libstd/sync/mpmc_bounded_queue.rs
src/libstd/vec.rs

index 27dad55c42946a50b4b55361eb5fa01bc9a6b5d1..56c1871597401dc210d489bdf72725d89866b508 100644 (file)
@@ -178,7 +178,7 @@ fn alloc_pod_grow(&mut self, n_bytes: uint, align: uint) -> *u8 {
         let new_min_chunk_size = num::max(n_bytes, chunk_size);
         self.chunks.set(@Cons(self.pod_head.clone(), self.chunks.get()));
         self.pod_head =
-            chunk(uint::next_power_of_two(new_min_chunk_size + 1u), true);
+            chunk(num::next_power_of_two(new_min_chunk_size + 1u), true);
 
         return self.alloc_pod_inner(n_bytes, align);
     }
@@ -220,7 +220,7 @@ fn alloc_nonpod_grow(&mut self, n_bytes: uint, align: uint)
         let new_min_chunk_size = num::max(n_bytes, chunk_size);
         self.chunks.set(@Cons(self.head.clone(), self.chunks.get()));
         self.head =
-            chunk(uint::next_power_of_two(new_min_chunk_size + 1u), false);
+            chunk(num::next_power_of_two(new_min_chunk_size + 1u), false);
 
         return self.alloc_nonpod_inner(n_bytes, align);
     }
index 18cb470db4da24fb08c7de265546c92cca860a89..55e90248e1c3b608149c72e16c6b72ae3ee9fa5e 100644 (file)
@@ -177,9 +177,9 @@ pub mod raw {
     use cast::{transmute, transmute_copy};
     use container::Container;
     use option::None;
-    use ptr;
     use mem;
-    use uint;
+    use num::next_power_of_two;
+    use ptr;
     use unstable::intrinsics::{move_val_init, TyDesc};
     use unstable::intrinsics;
     use unstable::raw::{Box, Vec};
@@ -293,7 +293,7 @@ fn local_realloc(ptr: *(), size: uint) -> *() {
      */
     #[inline]
     pub unsafe fn reserve_at_least<T>(v: &mut @[T], n: uint) {
-        reserve(v, uint::next_power_of_two(n));
+        reserve(v, next_power_of_two(n));
     }
 }
 
index 13a03d3252514d378c6d3cdb76b0909fc48d8565..31bf4679144bcb6485b3838229dd34eb69245754 100644 (file)
@@ -388,7 +388,7 @@ pub fn with_capacity_and_keys(k0: u64, k1: u64, capacity: uint) -> HashMap<K, V>
     pub fn reserve_at_least(&mut self, n: uint) {
         if n > self.buckets.len() {
             let buckets = n * 4 / 3 + 1;
-            self.resize(uint::next_power_of_two(buckets));
+            self.resize(num::next_power_of_two(buckets));
         }
     }
 
index 956c04db09c63416acabae661c8d83b763b6abf5..976761b512053309e698a261e96fd717bd907f67 100644 (file)
@@ -440,7 +440,39 @@ pub trait Primitive: Clone
 /// A collection of traits relevant to primitive signed and unsigned integers
 pub trait Int: Integer
              + Primitive
-             + Bitwise {}
+             + Bitwise
+             + CheckedAdd
+             + CheckedSub
+             // + CheckedMul // FIXME #8849: currently not impled on 32-bit
+             + CheckedDiv {}
+
+/// Returns the smallest power of 2 greater than or equal to `n`.
+#[inline]
+pub fn next_power_of_two<T: Unsigned + Int>(n: T) -> T {
+    let halfbits: T = cast(size_of::<T>() * 4).unwrap();
+    let mut tmp: T = n - one();
+    let mut shift: T = one();
+    while shift <= halfbits {
+        tmp = tmp | (tmp >> shift);
+        shift = shift << one();
+    }
+    tmp + one()
+}
+
+/// Returns the smallest power of 2 greater than or equal to `n`. If the next
+/// power of two is greater than the type's maximum value, `None` is returned,
+/// otherwise the power of 2 is wrapped in `Some`.
+#[inline]
+pub fn checked_next_power_of_two<T: Unsigned + Int>(n: T) -> Option<T> {
+    let halfbits: T = cast(size_of::<T>() * 4).unwrap();
+    let mut tmp: T = n - one();
+    let mut shift: T = one();
+    while shift <= halfbits {
+        tmp = tmp | (tmp >> shift);
+        shift = shift << one();
+    }
+    tmp.checked_add(&one())
+}
 
 /// Used for representing the classification of floating point numbers
 #[deriving(Eq)]
@@ -1589,6 +1621,48 @@ fn test_checked_mul() {
         assert_eq!(third.checked_mul(&4), None);
     }
 
+    macro_rules! test_next_power_of_two(
+        ($test_name:ident, $T:ident) => (
+            fn $test_name() {
+                #[test];
+                assert_eq!(next_power_of_two::<$T>(0), 0);
+                let mut next_power = 1;
+                for i in range::<$T>(1, 40) {
+                     assert_eq!(next_power_of_two(i), next_power);
+                     if i == next_power { next_power *= 2 }
+                }
+            }
+        )
+    )
+
+    test_next_power_of_two!(test_next_power_of_two_u8, u8)
+    test_next_power_of_two!(test_next_power_of_two_u16, u16)
+    test_next_power_of_two!(test_next_power_of_two_u32, u32)
+    test_next_power_of_two!(test_next_power_of_two_u64, u64)
+    test_next_power_of_two!(test_next_power_of_two_uint, uint)
+
+    macro_rules! test_checked_next_power_of_two(
+        ($test_name:ident, $T:ident) => (
+            fn $test_name() {
+                #[test];
+                assert_eq!(checked_next_power_of_two::<$T>(0), None);
+                let mut next_power = 1;
+                for i in range::<$T>(1, 40) {
+                     assert_eq!(checked_next_power_of_two(i), Some(next_power));
+                     if i == next_power { next_power *= 2 }
+                }
+                assert!(checked_next_power_of_two::<$T>($T::MAX / 2).is_some());
+                assert_eq!(checked_next_power_of_two::<$T>($T::MAX - 1), None);
+                assert_eq!(checked_next_power_of_two::<$T>($T::MAX), None);
+            }
+        )
+    )
+
+    test_checked_next_power_of_two!(test_checked_next_power_of_two_u8, u8)
+    test_checked_next_power_of_two!(test_checked_next_power_of_two_u16, u16)
+    test_checked_next_power_of_two!(test_checked_next_power_of_two_u32, u32)
+    test_checked_next_power_of_two!(test_checked_next_power_of_two_u64, u64)
+    test_checked_next_power_of_two!(test_checked_next_power_of_two_uint, uint)
 
     #[deriving(Eq)]
     struct Value { x: int }
index 89914571adaf81ca5bc9999443513e8a2fcf79e3..7954cdc92f07ea4ed463055e8739297d9bd6bcfa 100644 (file)
@@ -15,7 +15,6 @@
 use prelude::*;
 
 use default::Default;
-use mem;
 use num::{Bitwise, Bounded};
 use num::{CheckedAdd, CheckedSub, CheckedMul};
 use num::{CheckedDiv, Zero, One, strconv};
@@ -79,26 +78,6 @@ pub fn div_round(x: uint, y: uint) -> uint {
 ///
 pub fn div_floor(x: uint, y: uint) -> uint { return x / y; }
 
-/// Returns the smallest power of 2 greater than or equal to `n`
-#[inline]
-pub fn next_power_of_two(n: uint) -> uint {
-    let halfbits: uint = mem::size_of::<uint>() * 4u;
-    let mut tmp: uint = n - 1u;
-    let mut shift: uint = 1u;
-    while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; }
-    tmp + 1u
-}
-
-/// Returns the smallest power of 2 greater than or equal to `n`
-#[inline]
-pub fn next_power_of_two_opt(n: uint) -> Option<uint> {
-    let halfbits: uint = mem::size_of::<uint>() * 4u;
-    let mut tmp: uint = n - 1u;
-    let mut shift: uint = 1u;
-    while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; }
-    tmp.checked_add(&1)
-}
-
 #[cfg(target_word_size = "32")]
 impl CheckedAdd for uint {
     #[inline]
@@ -165,50 +144,6 @@ fn checked_mul(&self, v: &uint) -> Option<uint> {
     }
 }
 
-#[test]
-fn test_next_power_of_two() {
-    assert!((next_power_of_two(0u) == 0u));
-    assert!((next_power_of_two(1u) == 1u));
-    assert!((next_power_of_two(2u) == 2u));
-    assert!((next_power_of_two(3u) == 4u));
-    assert!((next_power_of_two(4u) == 4u));
-    assert!((next_power_of_two(5u) == 8u));
-    assert!((next_power_of_two(6u) == 8u));
-    assert!((next_power_of_two(7u) == 8u));
-    assert!((next_power_of_two(8u) == 8u));
-    assert!((next_power_of_two(9u) == 16u));
-    assert!((next_power_of_two(10u) == 16u));
-    assert!((next_power_of_two(11u) == 16u));
-    assert!((next_power_of_two(12u) == 16u));
-    assert!((next_power_of_two(13u) == 16u));
-    assert!((next_power_of_two(14u) == 16u));
-    assert!((next_power_of_two(15u) == 16u));
-    assert!((next_power_of_two(16u) == 16u));
-    assert!((next_power_of_two(17u) == 32u));
-    assert!((next_power_of_two(18u) == 32u));
-    assert!((next_power_of_two(19u) == 32u));
-    assert!((next_power_of_two(20u) == 32u));
-    assert!((next_power_of_two(21u) == 32u));
-    assert!((next_power_of_two(22u) == 32u));
-    assert!((next_power_of_two(23u) == 32u));
-    assert!((next_power_of_two(24u) == 32u));
-    assert!((next_power_of_two(25u) == 32u));
-    assert!((next_power_of_two(26u) == 32u));
-    assert!((next_power_of_two(27u) == 32u));
-    assert!((next_power_of_two(28u) == 32u));
-    assert!((next_power_of_two(29u) == 32u));
-    assert!((next_power_of_two(30u) == 32u));
-    assert!((next_power_of_two(31u) == 32u));
-    assert!((next_power_of_two(32u) == 32u));
-    assert!((next_power_of_two(33u) == 64u));
-    assert!((next_power_of_two(34u) == 64u));
-    assert!((next_power_of_two(35u) == 64u));
-    assert!((next_power_of_two(36u) == 64u));
-    assert!((next_power_of_two(37u) == 64u));
-    assert!((next_power_of_two(38u) == 64u));
-    assert!((next_power_of_two(39u) == 64u));
-}
-
 #[test]
 fn test_overflows() {
     use uint;
index 9cc9799d0c017b2b9cba4f2c6248167ef0d2db93..cefa39fb3cd244cbe96b968d0e9ec200b13fed3b 100644 (file)
@@ -104,7 +104,7 @@ fn main() {
 use iter::{Filter, AdditiveIterator, Map};
 use iter::{Rev, DoubleEndedIterator, ExactSize};
 use libc;
-use num::{Saturating};
+use num::{Saturating, checked_next_power_of_two};
 use option::{None, Option, Some};
 use ptr;
 use ptr::RawPtr;
@@ -2640,7 +2640,7 @@ fn reserve(&mut self, n: uint) {
 
     #[inline]
     fn reserve_at_least(&mut self, n: uint) {
-        self.reserve(uint::next_power_of_two_opt(n).unwrap_or(n))
+        self.reserve(checked_next_power_of_two(n).unwrap_or(n))
     }
 
     #[inline]
index bb0e96f96de2b8417583d4f9e7119b3d2237a42b..74f3a6f6918da8b44a7978d3e878790b623a43db 100644 (file)
 
 use clone::Clone;
 use kinds::Send;
+use num::next_power_of_two;
 use option::{Option, Some, None};
 use sync::arc::UnsafeArc;
 use sync::atomics::{AtomicUint,Relaxed,Release,Acquire};
-use uint;
 use vec;
 
 struct Node<T> {
@@ -64,7 +64,7 @@ fn with_capacity(capacity: uint) -> State<T> {
                 2u
             } else {
                 // use next power of 2 as capacity
-                uint::next_power_of_two(capacity)
+                next_power_of_two(capacity)
             }
         } else {
             capacity
index 467bcf075f60cae573ad80b13aef6924dd54624c..11b5790aeb79245e270cbb2cde677e9142cfbb9b 100644 (file)
 use cmp;
 use default::Default;
 use iter::*;
-use num::{Integer, CheckedAdd, Saturating};
+use num::{Integer, CheckedAdd, Saturating, checked_next_power_of_two};
 use option::{None, Option, Some};
 use ptr::to_unsafe_ptr;
 use ptr;
@@ -1486,7 +1486,7 @@ fn reserve(&mut self, n: uint) {
 
     #[inline]
     fn reserve_at_least(&mut self, n: uint) {
-        self.reserve(uint::next_power_of_two_opt(n).unwrap_or(n));
+        self.reserve(checked_next_power_of_two(n).unwrap_or(n));
     }
 
     #[inline]