From 1f1a1e6595cb9472927cd91d523982047832aa7a Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Mon, 23 Nov 2015 15:32:40 +1300 Subject: [PATCH 1/3] rustfmt: liballoc, liballoc_*, libarena --- src/liballoc/arc.rs | 37 ++++++++++++++++++------------------ src/liballoc/boxed.rs | 14 ++++++-------- src/liballoc/boxed_test.rs | 3 +-- src/liballoc/heap.rs | 2 +- src/liballoc/rc.rs | 20 +++++++++---------- src/liballoc_jemalloc/lib.rs | 2 +- src/liballoc_system/lib.rs | 6 +++--- src/libarena/lib.rs | 19 ++++++++++-------- 8 files changed, 52 insertions(+), 51 deletions(-) diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 7863f1018116a..77ef8a50619c5 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -131,11 +131,12 @@ pub struct Arc { } #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Send for Arc { } +unsafe impl Send for Arc {} #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Sync for Arc { } +unsafe impl Sync for Arc {} -#[cfg(not(stage0))] // remove cfg after new snapshot +// remove cfg after new snapshot +#[cfg(not(stage0))] #[unstable(feature = "coerce_unsized", issue = "27732")] impl, U: ?Sized> CoerceUnsized> for Arc {} @@ -152,11 +153,12 @@ pub struct Weak { } #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Send for Weak { } +unsafe impl Send for Weak {} #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Sync for Weak { } +unsafe impl Sync for Weak {} -#[cfg(not(stage0))] // remove cfg after new snapshot +// remove cfg after new snapshot +#[cfg(not(stage0))] #[unstable(feature = "coerce_unsized", issue = "27732")] impl, U: ?Sized> CoerceUnsized> for Weak {} @@ -226,7 +228,7 @@ impl Arc { pub fn try_unwrap(this: Self) -> Result { // See `drop` for why all these atomics are like this if this.inner().strong.compare_and_swap(1, 0, Release) != 1 { - return Err(this) + return Err(this); } atomic::fence(Acquire); @@ -265,7 +267,7 @@ impl Arc { // check if the weak counter is currently "locked"; if so, spin. if cur == usize::MAX { - continue + continue; } // NOTE: this code currently ignores the possibility of overflow @@ -276,7 +278,7 @@ impl Arc { // synchronize with the write coming from `is_unique`, so that the // events prior to that write happen before this read. if this.inner().weak.compare_and_swap(cur, cur + 1, Acquire) == cur { - return Weak { _ptr: this._ptr } + return Weak { _ptr: this._ptr }; } } } @@ -568,14 +570,14 @@ impl Drop for Arc { let ptr = *self._ptr; // if ptr.is_null() { return } if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE { - return + return; } // Because `fetch_sub` is already atomic, we do not need to synchronize // with other threads unless we are going to delete the object. This // same logic applies to the below `fetch_sub` to the `weak` count. if self.inner().strong.fetch_sub(1, Release) != 1 { - return + return; } // This fence is needed to prevent reordering of use of the data and @@ -634,13 +636,13 @@ impl Weak { // confirmed via the CAS below. let n = inner.strong.load(Relaxed); if n == 0 { - return None + return None; } // Relaxed is valid for the same reason it is on Arc's Clone impl let old = inner.strong.compare_and_swap(n, n + 1, Relaxed); if old == n { - return Some(Arc { _ptr: self._ptr }) + return Some(Arc { _ptr: self._ptr }); } } } @@ -682,7 +684,7 @@ impl Clone for Weak { } } - return Weak { _ptr: self._ptr } + return Weak { _ptr: self._ptr }; } } @@ -718,7 +720,7 @@ impl Drop for Weak { // see comments above for why this check is here if ptr as *mut u8 as usize == 0 || ptr as *mut u8 as usize == mem::POST_DROP_USIZE { - return + return; } // If we find out that we were the last weak pointer, then its time to @@ -928,8 +930,7 @@ mod tests { struct Canary(*mut atomic::AtomicUsize); - impl Drop for Canary - { + impl Drop for Canary { fn drop(&mut self) { unsafe { match *self { @@ -943,7 +944,7 @@ mod tests { #[test] fn manually_share_arc() { - let v = vec!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let arc_v = Arc::new(v); let (tx, rx) = channel(); diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 65c66ebe768f5..804c593467e5b 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -88,8 +88,7 @@ use core::convert::From; #[unstable(feature = "box_heap", reason = "may be renamed; uncertain about custom allocator design", issue = "27779")] -pub const HEAP: ExchangeHeapSingleton = - ExchangeHeapSingleton { _force_singleton: () }; +pub const HEAP: ExchangeHeapSingleton = ExchangeHeapSingleton { _force_singleton: () }; /// This the singleton type used solely for `boxed::HEAP`. #[unstable(feature = "box_heap", @@ -238,7 +237,7 @@ impl Box { } } -impl Box { +impl Box { /// Constructs a box from the raw pointer. /// /// After this function call, pointer is owned by resulting box. @@ -535,8 +534,7 @@ pub trait FnBox { } #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "0")] -impl FnBox for F - where F: FnOnce +impl FnBox for F where F: FnOnce { type Output = F::Output; @@ -546,7 +544,7 @@ impl FnBox for F } #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "0")] -impl<'a,A,R> FnOnce for Box+'a> { +impl<'a, A, R> FnOnce for Box + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { @@ -555,7 +553,7 @@ impl<'a,A,R> FnOnce for Box+'a> { } #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "0")] -impl<'a,A,R> FnOnce for Box+Send+'a> { +impl<'a, A, R> FnOnce for Box + Send + 'a> { type Output = R; extern "rust-call" fn call_once(self, args: A) -> R { @@ -564,7 +562,7 @@ impl<'a,A,R> FnOnce for Box+Send+'a> { } #[unstable(feature = "coerce_unsized", issue = "27732")] -impl, U: ?Sized> CoerceUnsized> for Box {} +impl, U: ?Sized> CoerceUnsized> for Box {} #[stable(feature = "box_slice_clone", since = "1.3.0")] impl Clone for Box<[T]> { diff --git a/src/liballoc/boxed_test.rs b/src/liballoc/boxed_test.rs index 7f3dadcf24d23..e7da6d04d3f8f 100644 --- a/src/liballoc/boxed_test.rs +++ b/src/liballoc/boxed_test.rs @@ -74,8 +74,7 @@ fn test_show() { #[test] fn deref() { - fn homura>(_: T) { - } + fn homura>(_: T) {} homura(Box::new(765)); } diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index 6961702cbc09d..7e7e3c619cb3a 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -18,7 +18,7 @@ use core::{isize, usize}; #[allow(improper_ctypes)] -extern { +extern "C" { #[allocator] fn __rust_allocate(size: usize, align: usize) -> *mut u8; fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize); diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 7abdc447ee556..a77e4f0633866 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -196,9 +196,10 @@ impl !marker::Send for Rc {} #[stable(feature = "rust1", since = "1.0.0")] impl !marker::Sync for Rc {} -#[cfg(not(stage0))] // remove cfg after new snapshot +// remove cfg after new snapshot +#[cfg(not(stage0))] #[unstable(feature = "coerce_unsized", issue = "27732")] -impl, U: ?Sized> CoerceUnsized> for Rc {} +impl, U: ?Sized> CoerceUnsized> for Rc {} impl Rc { /// Constructs a new `Rc`. @@ -482,7 +483,6 @@ impl Drop for Rc { #[stable(feature = "rust1", since = "1.0.0")] impl Clone for Rc { - /// Makes a clone of the `Rc`. /// /// When you clone an `Rc`, it will create another pointer to the data and @@ -678,21 +678,21 @@ impl Ord for Rc { } #[stable(feature = "rust1", since = "1.0.0")] -impl Hash for Rc { +impl Hash for Rc { fn hash(&self, state: &mut H) { (**self).hash(state); } } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Display for Rc { +impl fmt::Display for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&**self, f) } } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for Rc { +impl fmt::Debug for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } @@ -731,9 +731,10 @@ impl !marker::Send for Weak {} #[stable(feature = "rust1", since = "1.0.0")] impl !marker::Sync for Weak {} -#[cfg(not(stage0))] // remove cfg after new snapshot +// remove cfg after new snapshot +#[cfg(not(stage0))] #[unstable(feature = "coerce_unsized", issue = "27732")] -impl, U: ?Sized> CoerceUnsized> for Weak {} +impl, U: ?Sized> CoerceUnsized> for Weak {} impl Weak { /// Upgrades a weak reference to a strong reference. @@ -810,7 +811,6 @@ impl Drop for Weak { #[stable(feature = "rc_weak", since = "1.4.0")] impl Clone for Weak { - /// Makes a clone of the `Weak`. /// /// This increases the weak reference count. @@ -832,7 +832,7 @@ impl Clone for Weak { } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for Weak { +impl fmt::Debug for Weak { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "(Weak)") } diff --git a/src/liballoc_jemalloc/lib.rs b/src/liballoc_jemalloc/lib.rs index f2ff0593bfa54..f53bc404b8885 100644 --- a/src/liballoc_jemalloc/lib.rs +++ b/src/liballoc_jemalloc/lib.rs @@ -41,7 +41,7 @@ use libc::{c_int, c_void, size_t}; not(target_os = "android"), not(target_env = "musl")), link(name = "pthread"))] -extern { +extern "C" { fn je_mallocx(size: size_t, flags: c_int) -> *mut c_void; fn je_rallocx(ptr: *mut c_void, size: size_t, flags: c_int) -> *mut c_void; fn je_xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t; diff --git a/src/liballoc_system/lib.rs b/src/liballoc_system/lib.rs index 93b64c9caebc9..1befbd61d6d44 100644 --- a/src/liballoc_system/lib.rs +++ b/src/liballoc_system/lib.rs @@ -79,7 +79,7 @@ mod imp { use libc; use MIN_ALIGN; - extern { + extern "C" { // Apparently android doesn't have posix_memalign #[cfg(target_os = "android")] fn memalign(align: libc::size_t, size: libc::size_t) -> *mut libc::c_void; @@ -180,7 +180,7 @@ mod imp { } else { let ptr = HeapAlloc(GetProcessHeap(), 0, (size + align) as SIZE_T) as *mut u8; if ptr.is_null() { - return ptr + return ptr; } align_ptr(ptr, align) } @@ -196,7 +196,7 @@ mod imp { header.0 as LPVOID, (size + align) as SIZE_T) as *mut u8; if new.is_null() { - return new + return new; } align_ptr(new, align) } diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 2234d3608f3f3..abc15df804d49 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -168,8 +168,8 @@ unsafe fn destroy_chunk(chunk: &Chunk) { let start = round_up(after_tydesc, align); - //debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", - // start, size, align, is_done); + // debug!("freeing object: idx = {}, size = {}, align = {}, done = {}", + // start, size, align, is_done); if is_done { ((*tydesc).drop_glue)(buf.offset(start as isize) as *const i8); } @@ -201,8 +201,11 @@ struct TyDesc { align: usize, } -trait AllTypes { fn dummy(&self) { } } -impl AllTypes for T { } +trait AllTypes { + fn dummy(&self) {} +} + +impl AllTypes for T {} unsafe fn get_tydesc() -> *const TyDesc { use std::raw::TraitObject; @@ -624,7 +627,7 @@ mod tests { for _ in 0..100000 { arena.alloc(Noncopy { string: "hello world".to_string(), - array: vec!(1, 2, 3, 4, 5), + array: vec![1, 2, 3, 4, 5], }); } } @@ -635,7 +638,7 @@ mod tests { b.iter(|| { arena.alloc(Noncopy { string: "hello world".to_string(), - array: vec!(1, 2, 3, 4, 5), + array: vec![1, 2, 3, 4, 5], }) }) } @@ -645,7 +648,7 @@ mod tests { b.iter(|| { let _: Box<_> = box Noncopy { string: "hello world".to_string(), - array: vec!(1, 2, 3, 4, 5), + array: vec![1, 2, 3, 4, 5], }; }) } @@ -657,7 +660,7 @@ mod tests { arena.alloc(|| { Noncopy { string: "hello world".to_string(), - array: vec!(1, 2, 3, 4, 5), + array: vec![1, 2, 3, 4, 5], } }) }) From 0dfd875b6efa68ed67988a2f9856fc3bbdc91ce2 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 24 Nov 2015 11:23:48 +1300 Subject: [PATCH 2/3] rustfmt libcollections --- src/libcollections/binary_heap.rs | 94 ++-- src/libcollections/borrow.rs | 48 +- src/libcollections/btree/map.rs | 415 +++++++++++------- src/libcollections/btree/node.rs | 333 +++++++------- src/libcollections/btree/set.rs | 204 ++++++--- src/libcollections/enum_set.rs | 83 ++-- src/libcollections/lib.rs | 7 +- src/libcollections/linked_list.rs | 129 +++--- src/libcollections/range.rs | 24 +- src/libcollections/slice.rs | 112 +++-- src/libcollections/str.rs | 37 +- src/libcollections/string.rs | 93 ++-- src/libcollections/vec.rs | 128 +++--- src/libcollections/vec_deque.rs | 701 +++++++++++++++++------------- 14 files changed, 1426 insertions(+), 982 deletions(-) diff --git a/src/libcollections/binary_heap.rs b/src/libcollections/binary_heap.rs index db555fe61aa37..b643794f8a256 100644 --- a/src/libcollections/binary_heap.rs +++ b/src/libcollections/binary_heap.rs @@ -151,7 +151,7 @@ #![allow(missing_docs)] #![stable(feature = "rust1", since = "1.0.0")] -use core::iter::{FromIterator}; +use core::iter::FromIterator; use core::mem::swap; use core::ptr; use core::fmt; @@ -186,7 +186,9 @@ impl Clone for BinaryHeap { #[stable(feature = "rust1", since = "1.0.0")] impl Default for BinaryHeap { #[inline] - fn default() -> BinaryHeap { BinaryHeap::new() } + fn default() -> BinaryHeap { + BinaryHeap::new() + } } #[stable(feature = "binaryheap_debug", since = "1.4.0")] @@ -207,7 +209,9 @@ impl BinaryHeap { /// heap.push(4); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn new() -> BinaryHeap { BinaryHeap { data: vec![] } } + pub fn new() -> BinaryHeap { + BinaryHeap { data: vec![] } + } /// Creates an empty `BinaryHeap` with a specific capacity. /// This preallocates enough memory for `capacity` elements, @@ -296,7 +300,9 @@ impl BinaryHeap { /// heap.push(4); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn capacity(&self) -> usize { self.data.capacity() } + pub fn capacity(&self) -> usize { + self.data.capacity() + } /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the /// given `BinaryHeap`. Does nothing if the capacity is already sufficient. @@ -419,11 +425,13 @@ impl BinaryHeap { pub fn push_pop(&mut self, mut item: T) -> T { match self.data.get_mut(0) { None => return item, - Some(top) => if *top > item { - swap(&mut item, top); - } else { - return item; - }, + Some(top) => { + if *top > item { + swap(&mut item, top); + } else { + return item; + } + } } self.sift_down(0); @@ -522,7 +530,9 @@ impl BinaryHeap { while hole.pos() > start { let parent = (hole.pos() - 1) / 2; - if hole.element() <= hole.get(parent) { break; } + if hole.element() <= hole.get(parent) { + break; + } hole.move_to(parent); } } @@ -541,7 +551,9 @@ impl BinaryHeap { child = right; } // if we are already in order, stop. - if hole.element() >= hole.get(child) { break; } + if hole.element() >= hole.get(child) { + break; + } hole.move_to(child); child = 2 * hole.pos() + 1; } @@ -555,11 +567,15 @@ impl BinaryHeap { /// Returns the length of the binary heap. #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> usize { self.data.len() } + pub fn len(&self) -> usize { + self.data.len() + } /// Checks if the binary heap is empty. #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// Clears the binary heap, returning an iterator over the removed elements. /// @@ -575,7 +591,9 @@ impl BinaryHeap { /// Drops all items from the binary heap. #[stable(feature = "rust1", since = "1.0.0")] - pub fn clear(&mut self) { self.drain(); } + pub fn clear(&mut self) { + self.drain(); + } } /// Hole represents a hole in a slice i.e. an index without valid value @@ -603,7 +621,9 @@ impl<'a, T> Hole<'a, T> { } #[inline(always)] - fn pos(&self) -> usize { self.pos } + fn pos(&self) -> usize { + self.pos + } /// Return a reference to the element removed #[inline(always)] @@ -647,7 +667,7 @@ impl<'a, T> Drop for Hole<'a, T> { /// `BinaryHeap` iterator. #[stable(feature = "rust1", since = "1.0.0")] -pub struct Iter <'a, T: 'a> { +pub struct Iter<'a, T: 'a> { iter: slice::Iter<'a, T>, } @@ -664,16 +684,22 @@ impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; #[inline] - fn next(&mut self) -> Option<&'a T> { self.iter.next() } + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } #[inline] - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> DoubleEndedIterator for Iter<'a, T> { #[inline] - fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() } + fn next_back(&mut self) -> Option<&'a T> { + self.iter.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -690,16 +716,22 @@ impl Iterator for IntoIter { type Item = T; #[inline] - fn next(&mut self) -> Option { self.iter.next() } + fn next(&mut self) -> Option { + self.iter.next() + } #[inline] - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for IntoIter { #[inline] - fn next_back(&mut self) -> Option { self.iter.next_back() } + fn next_back(&mut self) -> Option { + self.iter.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -716,16 +748,22 @@ impl<'a, T: 'a> Iterator for Drain<'a, T> { type Item = T; #[inline] - fn next(&mut self) -> Option { self.iter.next() } + fn next(&mut self) -> Option { + self.iter.next() + } #[inline] - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { #[inline] - fn next_back(&mut self) -> Option { self.iter.next_back() } + fn next_back(&mut self) -> Option { + self.iter.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -753,7 +791,7 @@ impl From> for Vec { #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator for BinaryHeap { - fn from_iter>(iter: I) -> BinaryHeap { + fn from_iter>(iter: I) -> BinaryHeap { BinaryHeap::from(iter.into_iter().collect::>()) } } @@ -796,7 +834,7 @@ impl<'a, T> IntoIterator for &'a BinaryHeap where T: Ord { #[stable(feature = "rust1", since = "1.0.0")] impl Extend for BinaryHeap { - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { let iter = iterable.into_iter(); let (lower, _) = iter.size_hint(); @@ -810,7 +848,7 @@ impl Extend for BinaryHeap { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } diff --git a/src/libcollections/borrow.rs b/src/libcollections/borrow.rs index c26b42d016a81..bfd4c2e96b587 100644 --- a/src/libcollections/borrow.rs +++ b/src/libcollections/borrow.rs @@ -28,7 +28,10 @@ use self::Cow::*; pub use core::borrow::{Borrow, BorrowMut}; #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, B: ?Sized> Borrow for Cow<'a, B> where B: ToOwned, ::Owned: 'a { +impl<'a, B: ?Sized> Borrow for Cow<'a, B> + where B: ToOwned, + ::Owned: 'a +{ fn borrow(&self) -> &B { &**self } @@ -53,7 +56,9 @@ pub trait ToOwned { #[stable(feature = "rust1", since = "1.0.0")] impl ToOwned for T where T: Clone { type Owned = T; - fn to_owned(&self) -> T { self.clone() } + fn to_owned(&self) -> T { + self.clone() + } } /// A clone-on-write smart pointer. @@ -85,14 +90,16 @@ impl ToOwned for T where T: Clone { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] -pub enum Cow<'a, B: ?Sized + 'a> where B: ToOwned { +pub enum Cow<'a, B: ?Sized + 'a> + where B: ToOwned +{ /// Borrowed data. #[stable(feature = "rust1", since = "1.0.0")] Borrowed(&'a B), /// Owned data. #[stable(feature = "rust1", since = "1.0.0")] - Owned(::Owned) + Owned(::Owned), } #[stable(feature = "rust1", since = "1.0.0")] @@ -103,7 +110,7 @@ impl<'a, B: ?Sized> Clone for Cow<'a, B> where B: ToOwned { Owned(ref o) => { let b: &B = o.borrow(); Owned(b.to_owned()) - }, + } } } } @@ -131,7 +138,7 @@ impl<'a, B: ?Sized> Cow<'a, B> where B: ToOwned { *self = Owned(borrowed.to_owned()); self.to_mut() } - Owned(ref mut owned) => owned + Owned(ref mut owned) => owned, } } @@ -154,7 +161,7 @@ impl<'a, B: ?Sized> Cow<'a, B> where B: ToOwned { pub fn into_owned(self) -> ::Owned { match self { Borrowed(borrowed) => borrowed.to_owned(), - Owned(owned) => owned + Owned(owned) => owned, } } } @@ -166,7 +173,7 @@ impl<'a, B: ?Sized> Deref for Cow<'a, B> where B: ToOwned { fn deref(&self) -> &B { match *self { Borrowed(borrowed) => borrowed, - Owned(ref owned) => owned.borrow() + Owned(ref owned) => owned.borrow(), } } } @@ -183,8 +190,9 @@ impl<'a, B: ?Sized> Ord for Cow<'a, B> where B: Ord + ToOwned { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq> for Cow<'a, B> where - B: PartialEq + ToOwned, C: ToOwned, +impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq> for Cow<'a, B> + where B: PartialEq + ToOwned, + C: ToOwned { #[inline] fn eq(&self, other: &Cow<'b, C>) -> bool { @@ -193,8 +201,7 @@ impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq> for Cow<'a, B> where } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, B: ?Sized> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned, -{ +impl<'a, B: ?Sized> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned { #[inline] fn partial_cmp(&self, other: &Cow<'a, B>) -> Option { PartialOrd::partial_cmp(&**self, &**other) @@ -202,9 +209,9 @@ impl<'a, B: ?Sized> PartialOrd for Cow<'a, B> where B: PartialOrd + ToOwned, } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B> where - B: fmt::Debug + ToOwned, - ::Owned: fmt::Debug, +impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B> + where B: fmt::Debug + ToOwned, + ::Owned: fmt::Debug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -215,9 +222,9 @@ impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B> where } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, B: ?Sized> fmt::Display for Cow<'a, B> where - B: fmt::Display + ToOwned, - ::Owned: fmt::Display, +impl<'a, B: ?Sized> fmt::Display for Cow<'a, B> + where B: fmt::Display + ToOwned, + ::Owned: fmt::Display { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -228,8 +235,7 @@ impl<'a, B: ?Sized> fmt::Display for Cow<'a, B> where } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, B: ?Sized> Hash for Cow<'a, B> where B: Hash + ToOwned -{ +impl<'a, B: ?Sized> Hash for Cow<'a, B> where B: Hash + ToOwned { #[inline] fn hash(&self, state: &mut H) { Hash::hash(&**self, state) @@ -245,7 +251,7 @@ pub trait IntoCow<'a, B: ?Sized> where B: ToOwned { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, B: ?Sized> IntoCow<'a, B> for Cow<'a, B> where B: ToOwned { +impl<'a, B: ?Sized> IntoCow<'a, B> for Cow<'a, B> where B: ToOwned { fn into_cow(self) -> Cow<'a, B> { self } diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 178d7a4a05294..0091beb9ca6d5 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -84,46 +84,46 @@ struct AbsIter { /// An iterator over a BTreeMap's entries. #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, K: 'a, V: 'a> { - inner: AbsIter> + inner: AbsIter>, } /// A mutable iterator over a BTreeMap's entries. #[stable(feature = "rust1", since = "1.0.0")] pub struct IterMut<'a, K: 'a, V: 'a> { - inner: AbsIter> + inner: AbsIter>, } /// An owning iterator over a BTreeMap's entries. #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter { - inner: AbsIter> + inner: AbsIter>, } /// An iterator over a BTreeMap's keys. #[stable(feature = "rust1", since = "1.0.0")] pub struct Keys<'a, K: 'a, V: 'a> { - inner: Map, fn((&'a K, &'a V)) -> &'a K> + inner: Map, fn((&'a K, &'a V)) -> &'a K>, } /// An iterator over a BTreeMap's values. #[stable(feature = "rust1", since = "1.0.0")] pub struct Values<'a, K: 'a, V: 'a> { - inner: Map, fn((&'a K, &'a V)) -> &'a V> + inner: Map, fn((&'a K, &'a V)) -> &'a V>, } /// An iterator over a sub-range of BTreeMap's entries. pub struct Range<'a, K: 'a, V: 'a> { - inner: AbsIter> + inner: AbsIter>, } /// A mutable iterator over a sub-range of BTreeMap's entries. pub struct RangeMut<'a, K: 'a, V: 'a> { - inner: AbsIter> + inner: AbsIter>, } /// A view into a single entry in a map, which may either be vacant or occupied. #[stable(feature = "rust1", since = "1.0.0")] -pub enum Entry<'a, K:'a, V:'a> { +pub enum Entry<'a, K: 'a, V: 'a> { /// A vacant Entry #[stable(feature = "rust1", since = "1.0.0")] Vacant(VacantEntry<'a, K, V>), @@ -135,14 +135,14 @@ pub enum Entry<'a, K:'a, V:'a> { /// A vacant Entry. #[stable(feature = "rust1", since = "1.0.0")] -pub struct VacantEntry<'a, K:'a, V:'a> { +pub struct VacantEntry<'a, K: 'a, V: 'a> { key: K, stack: stack::SearchStack<'a, K, V, node::handle::Edge, node::handle::Leaf>, } /// An occupied Entry. #[stable(feature = "rust1", since = "1.0.0")] -pub struct OccupiedEntry<'a, K:'a, V:'a> { +pub struct OccupiedEntry<'a, K: 'a, V: 'a> { stack: stack::SearchStack<'a, K, V, node::handle::KV, node::handle::LeafOrInternal>, } @@ -151,7 +151,7 @@ impl BTreeMap { #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] pub fn new() -> BTreeMap { - //FIXME(Gankro): Tune this as a function of size_of? + // FIXME(Gankro): Tune this as a function of size_of? BTreeMap::with_b(6) } @@ -189,7 +189,7 @@ impl BTreeMap { pub fn clear(&mut self) { let b = self.b; // avoid recursive destructors by manually traversing the tree - for _ in mem::replace(self, BTreeMap::with_b(b)) {}; + for _ in mem::replace(self, BTreeMap::with_b(b)) {} } // Searching in a B-Tree is pretty straightforward. @@ -216,16 +216,21 @@ impl BTreeMap { /// assert_eq!(map.get(&2), None); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn get(&self, key: &Q) -> Option<&V> where K: Borrow, Q: Ord { + pub fn get(&self, key: &Q) -> Option<&V> + where K: Borrow, + Q: Ord + { let mut cur_node = &self.root; loop { match Node::search(cur_node, key) { Found(handle) => return Some(handle.into_kv().1), - GoDown(handle) => match handle.force() { - Leaf(_) => return None, - Internal(internal_handle) => { - cur_node = internal_handle.into_edge(); - continue; + GoDown(handle) => { + match handle.force() { + Leaf(_) => return None, + Internal(internal_handle) => { + cur_node = internal_handle.into_edge(); + continue; + } } } } @@ -248,7 +253,10 @@ impl BTreeMap { /// assert_eq!(map.contains_key(&2), false); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn contains_key(&self, key: &Q) -> bool where K: Borrow, Q: Ord { + pub fn contains_key(&self, key: &Q) -> bool + where K: Borrow, + Q: Ord + { self.get(key).is_some() } @@ -271,18 +279,23 @@ impl BTreeMap { /// ``` // See `get` for implementation notes, this is basically a copy-paste with mut's added #[stable(feature = "rust1", since = "1.0.0")] - pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> where K: Borrow, Q: Ord { + pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> + where K: Borrow, + Q: Ord + { // temp_node is a Borrowck hack for having a mutable value outlive a loop iteration let mut temp_node = &mut self.root; loop { let cur_node = temp_node; match Node::search(cur_node, key) { Found(handle) => return Some(handle.into_kv_mut().1), - GoDown(handle) => match handle.force() { - Leaf(_) => return None, - Internal(internal_handle) => { - temp_node = internal_handle.into_edge_mut(); - continue; + GoDown(handle) => { + match handle.force() { + Leaf(_) => return None, + Internal(internal_handle) => { + temp_node = internal_handle.into_edge_mut(); + continue; + } } } } @@ -366,7 +379,7 @@ impl BTreeMap { // Perfect match, swap the values and return the old one mem::swap(handle.val_mut(), &mut value); Finished(Some(value)) - }, + } GoDown(handle) => { // We need to keep searching, try to get the search stack // to go down further @@ -448,7 +461,10 @@ impl BTreeMap { /// assert_eq!(map.remove(&1), None); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn remove(&mut self, key: &Q) -> Option where K: Borrow, Q: Ord { + pub fn remove(&mut self, key: &Q) -> Option + where K: Borrow, + Q: Ord + { // See `swap` for a more thorough description of the stuff going on in here let mut stack = stack::PartialSearchStack::new(self); loop { @@ -457,20 +473,20 @@ impl BTreeMap { Found(handle) => { // Perfect match. Terminate the stack here, and remove the entry Finished(Some(pusher.seal(handle).remove())) - }, + } GoDown(handle) => { // We need to keep searching, try to go down the next edge match handle.force() { // We're at a leaf; the key isn't in here Leaf(_) => Finished(None), - Internal(internal_handle) => Continue(pusher.push(internal_handle)) + Internal(internal_handle) => Continue(pusher.push(internal_handle)), } } } }); match result { Finished(ret) => return ret.map(|(_, v)| v), - Continue(new_stack) => stack = new_stack + Continue(new_stack) => stack = new_stack, } } } @@ -505,7 +521,7 @@ impl IntoIterator for BTreeMap { inner: AbsIter { traversals: lca, size: len, - } + }, } } } @@ -534,7 +550,7 @@ impl<'a, K, V> IntoIterator for &'a mut BTreeMap { /// return from a closure enum Continuation { Continue(A), - Finished(B) + Finished(B), } /// The stack module provides a safe interface for constructing and manipulating a stack of ptrs @@ -549,8 +565,7 @@ mod stack { use super::super::node::handle; use vec::Vec; - struct InvariantLifetime<'id>( - marker::PhantomData<::core::cell::Cell<&'id ()>>); + struct InvariantLifetime<'id>(marker::PhantomData<::core::cell::Cell<&'id ()>>); impl<'id> InvariantLifetime<'id> { fn new() -> InvariantLifetime<'id> { @@ -585,7 +600,7 @@ mod stack { type Stack = Vec>; /// A `PartialSearchStack` handles the construction of a search stack. - pub struct PartialSearchStack<'a, K:'a, V:'a> { + pub struct PartialSearchStack<'a, K: 'a, V: 'a> { map: &'a mut BTreeMap, stack: Stack, next: *mut Node, @@ -594,7 +609,7 @@ mod stack { /// A `SearchStack` represents a full path to an element or an edge of interest. It provides /// methods depending on the type of what the path points to for removing an element, inserting /// a new element, and manipulating to element at the top of the stack. - pub struct SearchStack<'a, K:'a, V:'a, Type, NodeType> { + pub struct SearchStack<'a, K: 'a, V: 'a, Type, NodeType> { map: &'a mut BTreeMap, stack: Stack, top: node::Handle<*mut Node, Type, NodeType>, @@ -603,7 +618,7 @@ mod stack { /// A `PartialSearchStack` that doesn't hold a reference to the next node, and is just /// just waiting for a `Handle` to that next node to be pushed. See `PartialSearchStack::with` /// for more details. - pub struct Pusher<'id, 'a, K:'a, V:'a> { + pub struct Pusher<'id, 'a, K: 'a, V: 'a> { map: &'a mut BTreeMap, stack: Stack, _marker: InvariantLifetime<'id>, @@ -656,9 +671,8 @@ mod stack { /// Pushes the requested child of the stack's current top on top of the stack. If the child /// exists, then a new PartialSearchStack is yielded. Otherwise, a VacantSearchStack is /// yielded. - pub fn push(mut self, mut edge: node::Handle>, - handle::Edge, - handle::Internal>) + pub fn push(mut self, + mut edge: node::Handle>, handle::Edge, handle::Internal>) -> PartialSearchStack<'a, K, V> { self.stack.push(edge.as_raw()); PartialSearchStack { @@ -669,9 +683,11 @@ mod stack { } /// Converts the PartialSearchStack into a SearchStack. - pub fn seal - (self, mut handle: node::Handle>, Type, NodeType>) - -> SearchStack<'a, K, V, Type, NodeType> { + pub fn seal(self, + mut handle: node::Handle>, + Type, + NodeType>) + -> SearchStack<'a, K, V, Type, NodeType> { SearchStack { map: self.map, stack: self.stack, @@ -694,9 +710,7 @@ mod stack { /// Converts the stack into a mutable reference to the value it points to, with a lifetime /// tied to the original tree. pub fn into_top(mut self) -> &'a mut V { - unsafe { - &mut *(self.top.from_raw_mut().val_mut() as *mut V) - } + unsafe { &mut *(self.top.from_raw_mut().val_mut() as *mut V) } } } @@ -778,13 +792,13 @@ mod stack { return SearchStack { map: self.map, stack: self.stack, - top: leaf_handle.as_raw() - } + top: leaf_handle.as_raw(), + }; } Internal(mut internal_handle) => { let mut right_handle = internal_handle.right_edge(); - //We're not a proper leaf stack, let's get to work. + // We're not a proper leaf stack, let's get to work. self.stack.push(right_handle.as_raw()); let mut temp_node = right_handle.edge_mut(); @@ -800,9 +814,9 @@ mod stack { return SearchStack { map: self.map, stack: self.stack, - top: handle.as_raw() - } - }, + top: handle.as_raw(), + }; + } Internal(kv_handle) => { // This node is internal, go deeper let mut handle = kv_handle.into_left_edge(); @@ -830,7 +844,8 @@ mod stack { self.map.length += 1; // Insert the key and value into the leaf at the top of the stack - let (mut insertion, inserted_ptr) = self.top.from_raw_mut() + let (mut insertion, inserted_ptr) = self.top + .from_raw_mut() .insert_as_leaf(key, val); loop { @@ -840,24 +855,29 @@ mod stack { // inserting now. return &mut *inserted_ptr; } - Split(key, val, right) => match self.stack.pop() { - // The last insertion triggered a split, so get the next element on the - // stack to recursively insert the split node into. - None => { - // The stack was empty; we've split the root, and need to make a - // a new one. This is done in-place because we can't move the - // root out of a reference to the tree. - Node::make_internal_root(&mut self.map.root, self.map.b, - key, val, right); - - self.map.depth += 1; - return &mut *inserted_ptr; - } - Some(mut handle) => { - // The stack wasn't empty, do the insertion and recurse - insertion = handle.from_raw_mut() - .insert_as_internal(key, val, right); - continue; + Split(key, val, right) => { + match self.stack.pop() { + // The last insertion triggered a split, so get the next element on + // the stack to recursively insert the split node into. + None => { + // The stack was empty; we've split the root, and need to make a + // a new one. This is done in-place because we can't move the + // root out of a reference to the tree. + Node::make_internal_root(&mut self.map.root, + self.map.b, + key, + val, + right); + + self.map.depth += 1; + return &mut *inserted_ptr; + } + Some(mut handle) => { + // The stack wasn't empty, do the insertion and recurse + insertion = handle.from_raw_mut() + .insert_as_internal(key, val, right); + continue; + } } } } @@ -869,7 +889,7 @@ mod stack { #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator<(K, V)> for BTreeMap { - fn from_iter>(iter: T) -> BTreeMap { + fn from_iter>(iter: T) -> BTreeMap { let mut map = BTreeMap::new(); map.extend(iter); map @@ -879,7 +899,7 @@ impl FromIterator<(K, V)> for BTreeMap { #[stable(feature = "rust1", since = "1.0.0")] impl Extend<(K, V)> for BTreeMap { #[inline] - fn extend>(&mut self, iter: T) { + fn extend>(&mut self, iter: T) { for (k, v) in iter { self.insert(k, v); } @@ -888,7 +908,7 @@ impl Extend<(K, V)> for BTreeMap { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().map(|(&key, &value)| (key, value))); } } @@ -912,8 +932,7 @@ impl Default for BTreeMap { #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for BTreeMap { fn eq(&self, other: &BTreeMap) -> bool { - self.len() == other.len() && - self.iter().zip(other).all(|(a, b)| a == b) + self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b) } } @@ -945,7 +964,8 @@ impl Debug for BTreeMap { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap - where K: Borrow, Q: Ord + where K: Borrow, + Q: Ord { type Output = V; @@ -987,8 +1007,8 @@ enum StackOp { Push(T), Pop, } -impl Iterator for AbsIter where - T: DoubleEndedIterator> + Traverse, +impl Iterator for AbsIter + where T: DoubleEndedIterator> + Traverse { type Item = (K, V); @@ -1002,23 +1022,29 @@ impl Iterator for AbsIter where let op = match self.traversals.back_mut() { None => return None, // The queue wasn't empty, so continue along the node in its head - Some(iter) => match iter.next() { - // The head is empty, so Pop it off and continue the process - None => Pop, - // The head yielded an edge, so make that the new head - Some(Edge(next)) => Push(Traverse::traverse(next)), - // The head yielded an entry, so yield that - Some(Elem(kv)) => { - self.size -= 1; - return Some(kv) + Some(iter) => { + match iter.next() { + // The head is empty, so Pop it off and continue the process + None => Pop, + // The head yielded an edge, so make that the new head + Some(Edge(next)) => Push(Traverse::traverse(next)), + // The head yielded an entry, so yield that + Some(Elem(kv)) => { + self.size -= 1; + return Some(kv); + } } } }; // Handle any operation as necessary, without a conflicting borrow of the queue match op { - Push(item) => { self.traversals.push_back(item); }, - Pop => { self.traversals.pop_back(); }, + Push(item) => { + self.traversals.push_back(item); + } + Pop => { + self.traversals.pop_back(); + } } } } @@ -1028,8 +1054,8 @@ impl Iterator for AbsIter where } } -impl DoubleEndedIterator for AbsIter where - T: DoubleEndedIterator> + Traverse, +impl DoubleEndedIterator for AbsIter + where T: DoubleEndedIterator> + Traverse { // next_back is totally symmetric to next #[inline] @@ -1037,37 +1063,51 @@ impl DoubleEndedIterator for AbsIter where loop { let op = match self.traversals.front_mut() { None => return None, - Some(iter) => match iter.next_back() { - None => Pop, - Some(Edge(next)) => Push(Traverse::traverse(next)), - Some(Elem(kv)) => { - self.size -= 1; - return Some(kv) + Some(iter) => { + match iter.next_back() { + None => Pop, + Some(Edge(next)) => Push(Traverse::traverse(next)), + Some(Elem(kv)) => { + self.size -= 1; + return Some(kv); + } } } }; match op { - Push(item) => { self.traversals.push_front(item); }, - Pop => { self.traversals.pop_front(); } + Push(item) => { + self.traversals.push_front(item); + } + Pop => { + self.traversals.pop_front(); + } } } } } impl<'a, K, V> Clone for Iter<'a, K, V> { - fn clone(&self) -> Iter<'a, K, V> { Iter { inner: self.inner.clone() } } + fn clone(&self) -> Iter<'a, K, V> { + Iter { inner: self.inner.clone() } + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> Iterator for Iter<'a, K, V> { type Item = (&'a K, &'a V); - fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option<(&'a K, &'a V)> { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> DoubleEndedIterator for Iter<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(&'a K, &'a V)> { + self.inner.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {} @@ -1076,12 +1116,18 @@ impl<'a, K, V> ExactSizeIterator for Iter<'a, K, V> {} impl<'a, K, V> Iterator for IterMut<'a, K, V> { type Item = (&'a K, &'a mut V); - fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option<(&'a K, &'a mut V)> { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> DoubleEndedIterator for IterMut<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { + self.inner.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {} @@ -1090,70 +1136,102 @@ impl<'a, K, V> ExactSizeIterator for IterMut<'a, K, V> {} impl Iterator for IntoIter { type Item = (K, V); - fn next(&mut self) -> Option<(K, V)> { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option<(K, V)> { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for IntoIter { - fn next_back(&mut self) -> Option<(K, V)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(K, V)> { + self.inner.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for IntoIter {} impl<'a, K, V> Clone for Keys<'a, K, V> { - fn clone(&self) -> Keys<'a, K, V> { Keys { inner: self.inner.clone() } } + fn clone(&self) -> Keys<'a, K, V> { + Keys { inner: self.inner.clone() } + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> Iterator for Keys<'a, K, V> { type Item = &'a K; - fn next(&mut self) -> Option<(&'a K)> { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option<(&'a K)> { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> DoubleEndedIterator for Keys<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(&'a K)> { + self.inner.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> ExactSizeIterator for Keys<'a, K, V> {} impl<'a, K, V> Clone for Values<'a, K, V> { - fn clone(&self) -> Values<'a, K, V> { Values { inner: self.inner.clone() } } + fn clone(&self) -> Values<'a, K, V> { + Values { inner: self.inner.clone() } + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> Iterator for Values<'a, K, V> { type Item = &'a V; - fn next(&mut self) -> Option<(&'a V)> { self.inner.next() } - fn size_hint(&self) -> (usize, Option) { self.inner.size_hint() } + fn next(&mut self) -> Option<(&'a V)> { + self.inner.next() + } + fn size_hint(&self) -> (usize, Option) { + self.inner.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> DoubleEndedIterator for Values<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a V)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(&'a V)> { + self.inner.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, K, V> ExactSizeIterator for Values<'a, K, V> {} impl<'a, K, V> Clone for Range<'a, K, V> { - fn clone(&self) -> Range<'a, K, V> { Range { inner: self.inner.clone() } } + fn clone(&self) -> Range<'a, K, V> { + Range { inner: self.inner.clone() } + } } impl<'a, K, V> Iterator for Range<'a, K, V> { type Item = (&'a K, &'a V); - fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() } + fn next(&mut self) -> Option<(&'a K, &'a V)> { + self.inner.next() + } } impl<'a, K, V> DoubleEndedIterator for Range<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(&'a K, &'a V)> { + self.inner.next_back() + } } impl<'a, K, V> Iterator for RangeMut<'a, K, V> { type Item = (&'a K, &'a mut V); - fn next(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next() } + fn next(&mut self) -> Option<(&'a K, &'a mut V)> { + self.inner.next() + } } impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> { - fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { self.inner.next_back() } + fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> { + self.inner.next_back() + } } impl<'a, K: Ord, V> Entry<'a, K, V> { @@ -1251,7 +1329,7 @@ impl BTreeMap { inner: AbsIter { traversals: lca, size: len, - } + }, } } @@ -1283,7 +1361,7 @@ impl BTreeMap { inner: AbsIter { traversals: lca, size: len, - } + }, } } @@ -1303,7 +1381,9 @@ impl BTreeMap { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn keys<'a>(&'a self) -> Keys<'a, K, V> { - fn first((a, _): (A, B)) -> A { a } + fn first((a, _): (A, B)) -> A { + a + } let first: fn((&'a K, &'a V)) -> &'a K = first; // coerce to fn pointer Keys { inner: self.iter().map(first) } @@ -1325,7 +1405,9 @@ impl BTreeMap { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn values<'a>(&'a self) -> Values<'a, K, V> { - fn second((_, b): (A, B)) -> B { b } + fn second((_, b): (A, B)) -> B { + b + } let second: fn((&'a K, &'a V)) -> &'a V = second; // coerce to fn pointer Values { inner: self.iter().map(second) } @@ -1344,7 +1426,9 @@ impl BTreeMap { /// assert_eq!(a.len(), 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> usize { self.length } + pub fn len(&self) -> usize { + self.length + } /// Returns true if the map contains no elements. /// @@ -1359,7 +1443,9 @@ impl BTreeMap { /// assert!(!a.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } } macro_rules! range_impl { @@ -1518,12 +1604,20 @@ impl BTreeMap { #[unstable(feature = "btree_range", reason = "matches collection reform specification, waiting for dust to settle", issue = "27787")] - pub fn range(&self, min: Bound<&Min>, + pub fn range(&self, + min: Bound<&Min>, max: Bound<&Max>) - -> Range where - K: Borrow + Borrow, + -> Range + where K: Borrow + Borrow { - range_impl!(&self.root, min, max, as_slices_internal, iter, Range, edges, []) + range_impl!(&self.root, + min, + max, + as_slices_internal, + iter, + Range, + edges, + []) } /// Constructs a mutable double-ended iterator over a sub-range of elements in the map, starting @@ -1552,13 +1646,20 @@ impl BTreeMap { #[unstable(feature = "btree_range", reason = "matches collection reform specification, waiting for dust to settle", issue = "27787")] - pub fn range_mut(&mut self, min: Bound<&Min>, + pub fn range_mut(&mut self, + min: Bound<&Min>, max: Bound<&Max>) - -> RangeMut where - K: Borrow + Borrow, + -> RangeMut + where K: Borrow + Borrow { - range_impl!(&mut self.root, min, max, as_slices_internal_mut, iter_mut, RangeMut, - edges_mut, [mut]) + range_impl!(&mut self.root, + min, + max, + as_slices_internal_mut, + iter_mut, + RangeMut, + edges_mut, + [mut]) } /// Gets the given key's corresponding entry in the map for in-place manipulation. @@ -1586,10 +1687,8 @@ impl BTreeMap { match Node::search(node, &key) { Found(handle) => { // Perfect match - Finished(Occupied(OccupiedEntry { - stack: pusher.seal(handle) - })) - }, + Finished(Occupied(OccupiedEntry { stack: pusher.seal(handle) })) + } GoDown(handle) => { match handle.force() { Leaf(leaf_handle) => { @@ -1597,12 +1696,9 @@ impl BTreeMap { stack: pusher.seal(leaf_handle), key: key, })) - }, + } Internal(internal_handle) => { - Continue(( - pusher.push(internal_handle), - key - )) + Continue((pusher.push(internal_handle), key)) } } } @@ -1619,7 +1715,10 @@ impl BTreeMap { } } -impl super::Recover for BTreeMap where K: Borrow + Ord, Q: Ord { +impl super::Recover for BTreeMap + where K: Borrow + Ord, + Q: Ord +{ type Key = K; fn get(&self, key: &Q) -> Option<&K> { @@ -1627,11 +1726,13 @@ impl super::Recover for BTreeMap where K: Borrow + Or loop { match Node::search(cur_node, key) { Found(handle) => return Some(handle.into_kv().0), - GoDown(handle) => match handle.force() { - Leaf(_) => return None, - Internal(internal_handle) => { - cur_node = internal_handle.into_edge(); - continue; + GoDown(handle) => { + match handle.force() { + Leaf(_) => return None, + Internal(internal_handle) => { + cur_node = internal_handle.into_edge(); + continue; + } } } } @@ -1648,20 +1749,20 @@ impl super::Recover for BTreeMap where K: Borrow + Or Found(handle) => { // Perfect match. Terminate the stack here, and remove the entry Finished(Some(pusher.seal(handle).remove())) - }, + } GoDown(handle) => { // We need to keep searching, try to go down the next edge match handle.force() { // We're at a leaf; the key isn't in here Leaf(_) => Finished(None), - Internal(internal_handle) => Continue(pusher.push(internal_handle)) + Internal(internal_handle) => Continue(pusher.push(internal_handle)), } } } }); match result { Finished(ret) => return ret.map(|(k, _)| k), - Continue(new_stack) => stack = new_stack + Continue(new_stack) => stack = new_stack, } } } @@ -1677,7 +1778,7 @@ impl super::Recover for BTreeMap where K: Borrow + Or Found(mut handle) => { mem::swap(handle.key_mut(), &mut key); Finished(Some(key)) - }, + } GoDown(handle) => { match handle.force() { Leaf(leaf_handle) => { diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index dc4b7a1c3f7f3..26479b3f559b9 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -122,7 +122,8 @@ fn test_rounding() { // from the start of a mallocated array. #[inline] fn calculate_offsets(keys_size: usize, - vals_size: usize, vals_align: usize, + vals_size: usize, + vals_align: usize, edges_align: usize) -> (usize, usize) { let vals_offset = round_up_to_next(keys_size, vals_align); @@ -136,13 +137,14 @@ fn calculate_offsets(keys_size: usize, // Returns a tuple of (minimum required alignment, array_size), // from the start of a mallocated array. #[inline] -fn calculate_allocation(keys_size: usize, keys_align: usize, - vals_size: usize, vals_align: usize, - edges_size: usize, edges_align: usize) +fn calculate_allocation(keys_size: usize, + keys_align: usize, + vals_size: usize, + vals_align: usize, + edges_size: usize, + edges_align: usize) -> (usize, usize) { - let (_, edges_offset) = calculate_offsets(keys_size, - vals_size, vals_align, - edges_align); + let (_, edges_offset) = calculate_offsets(keys_size, vals_size, vals_align, edges_align); let end_of_edges = edges_offset + edges_size; let min_align = cmp::max(keys_align, cmp::max(vals_align, edges_align)); @@ -171,14 +173,16 @@ fn calculate_allocation_generic(capacity: usize, is_leaf: bool) -> (usize, (0, 1) } } else { - ((capacity + 1) * mem::size_of::>(), mem::align_of::>()) + ((capacity + 1) * mem::size_of::>(), + mem::align_of::>()) }; - calculate_allocation( - keys_size, keys_align, - vals_size, vals_align, - edges_size, edges_align - ) + calculate_allocation(keys_size, + keys_align, + vals_size, + vals_align, + edges_size, + edges_align) } fn calculate_offsets_generic(capacity: usize, is_leaf: bool) -> (usize, usize) { @@ -191,11 +195,7 @@ fn calculate_offsets_generic(capacity: usize, is_leaf: bool) -> (usize, us mem::align_of::>() }; - calculate_offsets( - keys_size, - vals_size, vals_align, - edges_align - ) + calculate_offsets(keys_size, vals_size, vals_align, edges_align) } /// An iterator over a slice that owns the elements of the slice but not the allocation. @@ -285,8 +285,7 @@ impl Drop for Node { #[unsafe_destructor_blind_to_params] fn drop(&mut self) { if self.keys.is_null() || - (unsafe { self.keys.get() as *const K as usize == mem::POST_DROP_USIZE }) - { + (unsafe { self.keys.get() as *const K as usize == mem::POST_DROP_USIZE }) { // Since we have #[unsafe_no_drop_flag], we have to watch // out for the sentinel value being stored in self.keys. (Using // null is technically a violation of the `Unique` @@ -314,7 +313,9 @@ impl Node { let (alignment, size) = calculate_allocation_generic::(capacity, false); let buffer = heap::allocate(size, alignment); - if buffer.is_null() { ::alloc::oom(); } + if buffer.is_null() { + ::alloc::oom(); + } let (vals_offset, edges_offset) = calculate_offsets_generic::(capacity, false); @@ -332,7 +333,9 @@ impl Node { let (alignment, size) = calculate_allocation_generic::(capacity, true); let buffer = unsafe { heap::allocate(size, alignment) }; - if buffer.is_null() { ::alloc::oom(); } + if buffer.is_null() { + ::alloc::oom(); + } let (vals_offset, _) = calculate_offsets_generic::(capacity, true); @@ -346,25 +349,25 @@ impl Node { } unsafe fn destroy(&mut self) { - let (alignment, size) = - calculate_allocation_generic::(self.capacity(), self.is_leaf()); + let (alignment, size) = calculate_allocation_generic::(self.capacity(), + self.is_leaf()); heap::deallocate(*self.keys as *mut u8, size, alignment); } #[inline] pub fn as_slices<'a>(&'a self) -> (&'a [K], &'a [V]) { - unsafe {( - slice::from_raw_parts(*self.keys, self.len()), - slice::from_raw_parts(*self.vals, self.len()), - )} + unsafe { + (slice::from_raw_parts(*self.keys, self.len()), + slice::from_raw_parts(*self.vals, self.len())) + } } #[inline] pub fn as_slices_mut<'a>(&'a mut self) -> (&'a mut [K], &'a mut [V]) { - unsafe {( - slice::from_raw_parts_mut(*self.keys, self.len()), - slice::from_raw_parts_mut(*self.vals, self.len()), - )} + unsafe { + (slice::from_raw_parts_mut(*self.keys, self.len()), + slice::from_raw_parts_mut(*self.vals, self.len())) + } } #[inline] @@ -376,8 +379,8 @@ impl Node { } else { unsafe { let data = match self.edges { - None => heap::EMPTY as *const Node, - Some(ref p) => **p as *const Node, + None => heap::EMPTY as *const Node, + Some(ref p) => **p as *const Node, }; slice::from_raw_parts(data, self.len() + 1) } @@ -403,8 +406,8 @@ impl Node { } else { unsafe { let data = match self.edges { - None => heap::EMPTY as *mut Node, - Some(ref mut p) => **p as *mut Node, + None => heap::EMPTY as *mut Node, + Some(ref mut p) => **p as *mut Node, }; slice::from_raw_parts_mut(data, len + 1) } @@ -573,29 +576,49 @@ impl Node { /// Searches for the given key in the node. If it finds an exact match, /// `Found` will be yielded with the matching index. If it doesn't find an exact match, /// `GoDown` will be yielded with the index of the subtree the key must lie in. - pub fn search>>(node: NodeRef, key: &Q) - -> SearchResult where K: Borrow, Q: Ord { + pub fn search>>(node: NodeRef, + key: &Q) + -> SearchResult + where K: Borrow, + Q: Ord + { // FIXME(Gankro): Tune when to search linear or binary based on B (and maybe K/V). // For the B configured as of this writing (B = 6), binary search was *significantly* // worse for usizes. match node.as_slices_internal().search_linear(key) { - (index, true) => Found(Handle { node: node, index: index, marker: PhantomData }), - (index, false) => GoDown(Handle { node: node, index: index, marker: PhantomData }), + (index, true) => { + Found(Handle { + node: node, + index: index, + marker: PhantomData, + }) + } + (index, false) => { + GoDown(Handle { + node: node, + index: index, + marker: PhantomData, + }) + } } } } // Public interface -impl Node { +impl Node { /// Make a leaf root from scratch pub fn make_leaf_root(b: usize) -> Node { Node::new_leaf(capacity_from_b(b)) } /// Make an internal root and swap it with an old root - pub fn make_internal_root(left_and_out: &mut Node, b: usize, key: K, value: V, - right: Node) { - let node = mem::replace(left_and_out, unsafe { Node::new_internal(capacity_from_b(b)) }); + pub fn make_internal_root(left_and_out: &mut Node, + b: usize, + key: K, + value: V, + right: Node) { + let node = mem::replace(left_and_out, + unsafe { Node::new_internal(capacity_from_b(b)) }); left_and_out._len = 1; unsafe { ptr::write(left_and_out.keys_mut().get_unchecked_mut(0), key); @@ -611,7 +634,9 @@ impl Node { } /// Does the node not contain any key-value pairs - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// How many key-value pairs the node can fit pub fn capacity(&self) -> usize { @@ -634,7 +659,7 @@ impl Node { } } -impl>, Type, NodeType> Handle { +impl>, Type, NodeType> Handle { /// Returns a reference to the node that contains the pointed-to edge or key/value pair. This /// is very different from `edge` and `edge_mut` because those return children of the node /// returned by `node`. @@ -643,8 +668,8 @@ impl>, Type, NodeType> Handle Handle where - NodeRef: Deref> + DerefMut, +impl Handle + where NodeRef: Deref> + DerefMut { /// Converts a handle into one that stores the same information using a raw pointer. This can /// be useful in conjunction with `from_raw` when the type system is insufficient for @@ -687,9 +712,7 @@ impl<'a, K: 'a, V: 'a> Handle<&'a Node, handle::Edge, handle::Internal> { /// returned pointer has a larger lifetime than what would be returned by `edge` or `edge_mut`, /// making it more suitable for moving down a chain of nodes. pub fn into_edge(self) -> &'a Node { - unsafe { - self.node.edges().get_unchecked(self.index) - } + unsafe { self.node.edges().get_unchecked(self.index) } } } @@ -698,13 +721,11 @@ impl<'a, K: 'a, V: 'a> Handle<&'a mut Node, handle::Edge, handle::Internal /// because the returned pointer has a larger lifetime than what would be returned by /// `edge_mut`, making it more suitable for moving down a chain of nodes. pub fn into_edge_mut(self) -> &'a mut Node { - unsafe { - self.node.edges_mut().get_unchecked_mut(self.index) - } + unsafe { self.node.edges_mut().get_unchecked_mut(self.index) } } } -impl>> Handle { +impl>> Handle { // This doesn't exist because there are no uses for it, // but is fine to add, analogous to edge_mut. // @@ -715,10 +736,12 @@ impl>> Handle { Leaf(Handle), - Internal(Handle) + Internal(Handle), } -impl>, Type> Handle { +impl>, Type> + Handle +{ /// Figure out whether this handle is pointing to something in a leaf node or to something in /// an internal node, clarifying the type according to the result. pub fn force(self) -> ForceResult { @@ -737,16 +760,15 @@ impl>, Type> Handle Handle where - NodeRef: Deref> + DerefMut, +impl Handle + where NodeRef: Deref> + DerefMut { /// Tries to insert this key-value pair at the given index in this leaf node /// If the node is full, we have to split it. /// /// Returns a *mut V to the inserted value, because the caller may want this when /// they're done mutating the tree, but we don't want to borrow anything for now. - pub fn insert_as_leaf(mut self, key: K, value: V) -> - (InsertionResult, *mut V) { + pub fn insert_as_leaf(mut self, key: K, value: V) -> (InsertionResult, *mut V) { if !self.node.is_full() { // The element can fit, just insert it (Fit, unsafe { self.node.insert_kv(self.index, key, value) as *mut _ }) @@ -771,21 +793,22 @@ impl Handle where } } -impl Handle where - NodeRef: Deref> + DerefMut, +impl Handle + where NodeRef: Deref> + DerefMut { /// Returns a mutable reference to the edge pointed-to by this handle. This should not be /// confused with `node`, which references the parent node of what is returned here. pub fn edge_mut(&mut self) -> &mut Node { - unsafe { - self.node.edges_mut().get_unchecked_mut(self.index) - } + unsafe { self.node.edges_mut().get_unchecked_mut(self.index) } } /// Tries to insert this key-value pair at the given index in this internal node /// If the node is full, we have to split it. - pub fn insert_as_internal(mut self, key: K, value: V, right: Node) - -> InsertionResult { + pub fn insert_as_internal(mut self, + key: K, + value: V, + right: Node) + -> InsertionResult { if !self.node.is_full() { // The element can fit, just insert it unsafe { @@ -856,8 +879,8 @@ impl Handle where } } -impl Handle where - NodeRef: Deref> + DerefMut, +impl Handle + where NodeRef: Deref> + DerefMut { /// Gets the handle pointing to the key/value pair just to the left of the pointed-to edge. /// This is unsafe because the handle might point to the first edge in the node, which has no @@ -889,10 +912,8 @@ impl<'a, K: 'a, V: 'a, NodeType> Handle<&'a Node, handle::KV, NodeType> { pub fn into_kv(self) -> (&'a K, &'a V) { let (keys, vals) = self.node.as_slices(); unsafe { - ( - keys.get_unchecked(self.index), - vals.get_unchecked(self.index) - ) + (keys.get_unchecked(self.index), + vals.get_unchecked(self.index)) } } } @@ -904,10 +925,8 @@ impl<'a, K: 'a, V: 'a, NodeType> Handle<&'a mut Node, handle::KV, NodeType pub fn into_kv_mut(self) -> (&'a mut K, &'a mut V) { let (keys, vals) = self.node.as_slices_mut(); unsafe { - ( - keys.get_unchecked_mut(self.index), - vals.get_unchecked_mut(self.index) - ) + (keys.get_unchecked_mut(self.index), + vals.get_unchecked_mut(self.index)) } } @@ -923,8 +942,10 @@ impl<'a, K: 'a, V: 'a, NodeType> Handle<&'a mut Node, handle::KV, NodeType } } -impl<'a, K: 'a, V: 'a, NodeRef: Deref> + 'a, NodeType> Handle { + +impl<'a, K: 'a, V: 'a, NodeRef: Deref> + 'a, NodeType> Handle { // These are fine to include, but are currently unneeded. // // /// Returns a reference to the key pointed-to by this handle. This doesn't return a @@ -942,8 +963,8 @@ impl<'a, K: 'a, V: 'a, NodeRef: Deref> + 'a, NodeType> Handle< // } } -impl<'a, K: 'a, V: 'a, NodeRef, NodeType> Handle where - NodeRef: 'a + Deref> + DerefMut, +impl<'a, K: 'a, V: 'a, NodeRef, NodeType> Handle + where NodeRef: 'a + Deref> + DerefMut { /// Returns a mutable reference to the key pointed-to by this handle. This doesn't return a /// reference with a lifetime as large as `into_kv_mut`, but it also does not consume the @@ -960,8 +981,8 @@ impl<'a, K: 'a, V: 'a, NodeRef, NodeType> Handle } } -impl Handle where - NodeRef: Deref> + DerefMut, +impl Handle + where NodeRef: Deref> + DerefMut { /// Gets the handle pointing to the edge immediately to the left of the key/value pair pointed /// to by this handle. @@ -984,8 +1005,8 @@ impl Handle where } } -impl Handle where - NodeRef: Deref> + DerefMut, +impl Handle + where NodeRef: Deref> + DerefMut { /// Removes the key/value pair at the handle's location. /// @@ -997,8 +1018,8 @@ impl Handle where } } -impl Handle where - NodeRef: Deref> + DerefMut +impl Handle + where NodeRef: Deref> + DerefMut { /// Steal! Stealing is roughly analogous to a binary tree rotation. /// In this case, we're "rotating" right. @@ -1071,7 +1092,8 @@ impl Handle where let right = self.node.remove_edge(self.index + 1); // Give left right's stuff. - self.left_edge().edge_mut() + self.left_edge() + .edge_mut() .absorb(key, val, right); } } @@ -1082,8 +1104,9 @@ impl Node { /// # Panics (in debug build) /// /// Panics if the given index is out of bounds. - pub fn kv_handle(&mut self, index: usize) -> Handle<&mut Node, handle::KV, - handle::LeafOrInternal> { + pub fn kv_handle(&mut self, + index: usize) + -> Handle<&mut Node, handle::KV, handle::LeafOrInternal> { // Necessary for correctness, but in a private module debug_assert!(index < self.len(), "kv_handle index out of bounds"); Handle { @@ -1111,7 +1134,7 @@ impl Node { ptr: Unique::new(*self.keys as *mut u8), capacity: self.capacity(), - is_leaf: self.is_leaf() + is_leaf: self.is_leaf(), }, head_is_edge: true, tail_is_edge: true, @@ -1160,16 +1183,12 @@ impl Node { // This must be followed by insert_edge on an internal node. #[inline] unsafe fn insert_kv(&mut self, index: usize, key: K, val: V) -> &mut V { - ptr::copy( - self.keys().as_ptr().offset(index as isize), - self.keys_mut().as_mut_ptr().offset(index as isize + 1), - self.len() - index - ); - ptr::copy( - self.vals().as_ptr().offset(index as isize), - self.vals_mut().as_mut_ptr().offset(index as isize + 1), - self.len() - index - ); + ptr::copy(self.keys().as_ptr().offset(index as isize), + self.keys_mut().as_mut_ptr().offset(index as isize + 1), + self.len() - index); + ptr::copy(self.vals().as_ptr().offset(index as isize), + self.vals_mut().as_mut_ptr().offset(index as isize + 1), + self.len() - index); ptr::write(self.keys_mut().get_unchecked_mut(index), key); ptr::write(self.vals_mut().get_unchecked_mut(index), val); @@ -1182,11 +1201,9 @@ impl Node { // This can only be called immediately after a call to insert_kv. #[inline] unsafe fn insert_edge(&mut self, index: usize, edge: Node) { - ptr::copy( - self.edges().as_ptr().offset(index as isize), - self.edges_mut().as_mut_ptr().offset(index as isize + 1), - self.len() - index - ); + ptr::copy(self.edges().as_ptr().offset(index as isize), + self.edges_mut().as_mut_ptr().offset(index as isize + 1), + self.len() - index); ptr::write(self.edges_mut().get_unchecked_mut(index), edge); } @@ -1215,16 +1232,12 @@ impl Node { let key = ptr::read(self.keys().get_unchecked(index)); let val = ptr::read(self.vals().get_unchecked(index)); - ptr::copy( - self.keys().as_ptr().offset(index as isize + 1), - self.keys_mut().as_mut_ptr().offset(index as isize), - self.len() - index - 1 - ); - ptr::copy( - self.vals().as_ptr().offset(index as isize + 1), - self.vals_mut().as_mut_ptr().offset(index as isize), - self.len() - index - 1 - ); + ptr::copy(self.keys().as_ptr().offset(index as isize + 1), + self.keys_mut().as_mut_ptr().offset(index as isize), + self.len() - index - 1); + ptr::copy(self.vals().as_ptr().offset(index as isize + 1), + self.vals_mut().as_mut_ptr().offset(index as isize), + self.len() - index - 1); self._len -= 1; @@ -1236,12 +1249,10 @@ impl Node { unsafe fn remove_edge(&mut self, index: usize) -> Node { let edge = ptr::read(self.edges().get_unchecked(index)); - ptr::copy( - self.edges().as_ptr().offset(index as isize + 1), - self.edges_mut().as_mut_ptr().offset(index as isize), - // index can be == len+1, so do the +1 first to avoid underflow. - (self.len() + 1) - index - ); + ptr::copy(self.edges().as_ptr().offset(index as isize + 1), + self.edges_mut().as_mut_ptr().offset(index as isize), + // index can be == len+1, so do the +1 first to avoid underflow. + (self.len() + 1) - index); edge } @@ -1264,22 +1275,16 @@ impl Node { unsafe { right._len = self.len() / 2; let right_offset = self.len() - right.len(); - ptr::copy_nonoverlapping( - self.keys().as_ptr().offset(right_offset as isize), - right.keys_mut().as_mut_ptr(), - right.len() - ); - ptr::copy_nonoverlapping( - self.vals().as_ptr().offset(right_offset as isize), - right.vals_mut().as_mut_ptr(), - right.len() - ); + ptr::copy_nonoverlapping(self.keys().as_ptr().offset(right_offset as isize), + right.keys_mut().as_mut_ptr(), + right.len()); + ptr::copy_nonoverlapping(self.vals().as_ptr().offset(right_offset as isize), + right.vals_mut().as_mut_ptr(), + right.len()); if !self.is_leaf() { - ptr::copy_nonoverlapping( - self.edges().as_ptr().offset(right_offset as isize), - right.edges_mut().as_mut_ptr(), - right.len() + 1 - ); + ptr::copy_nonoverlapping(self.edges().as_ptr().offset(right_offset as isize), + right.edges_mut().as_mut_ptr(), + right.len() + 1); } let key = ptr::read(self.keys().get_unchecked(right_offset - 1)); @@ -1305,22 +1310,18 @@ impl Node { ptr::write(self.keys_mut().get_unchecked_mut(old_len), key); ptr::write(self.vals_mut().get_unchecked_mut(old_len), val); - ptr::copy_nonoverlapping( - right.keys().as_ptr(), - self.keys_mut().as_mut_ptr().offset(old_len as isize + 1), - right.len() - ); - ptr::copy_nonoverlapping( - right.vals().as_ptr(), - self.vals_mut().as_mut_ptr().offset(old_len as isize + 1), - right.len() - ); + ptr::copy_nonoverlapping(right.keys().as_ptr(), + self.keys_mut().as_mut_ptr().offset(old_len as isize + 1), + right.len()); + ptr::copy_nonoverlapping(right.vals().as_ptr(), + self.vals_mut().as_mut_ptr().offset(old_len as isize + 1), + right.len()); if !self.is_leaf() { - ptr::copy_nonoverlapping( - right.edges().as_ptr(), - self.edges_mut().as_mut_ptr().offset(old_len as isize + 1), - right.len() + 1 - ); + ptr::copy_nonoverlapping(right.edges().as_ptr(), + self.edges_mut() + .as_mut_ptr() + .offset(old_len as isize + 1), + right.len() + 1); } right.destroy(); @@ -1382,7 +1383,7 @@ struct MoveTraversalImpl { // For deallocation when we are done iterating. ptr: Unique, capacity: usize, - is_leaf: bool + is_leaf: bool, } unsafe impl Sync for MoveTraversalImpl {} @@ -1395,14 +1396,14 @@ impl TraversalImpl for MoveTraversalImpl { fn next_kv(&mut self) -> Option<(K, V)> { match (self.keys.next(), self.vals.next()) { (Some(k), Some(v)) => Some((k, v)), - _ => None + _ => None, } } fn next_kv_back(&mut self) -> Option<(K, V)> { match (self.keys.next_back(), self.vals.next_back()) { (Some(k), Some(v)) => Some((k, v)), - _ => None + _ => None, } } @@ -1428,8 +1429,7 @@ impl Drop for MoveTraversalImpl { for _ in self.vals.by_ref() {} for _ in self.edges.by_ref() {} - let (alignment, size) = - calculate_allocation_generic::(self.capacity, self.is_leaf); + let (alignment, size) = calculate_allocation_generic::(self.capacity, self.is_leaf); unsafe { heap::deallocate(*self.ptr, size, alignment) }; } } @@ -1467,27 +1467,24 @@ pub type MoveTraversal = AbsTraversal>; impl Iterator for AbsTraversal - where Impl: TraversalImpl { + where Impl: TraversalImpl +{ type Item = TraversalItem; fn next(&mut self) -> Option> { - self.next_edge_item().map(Edge).or_else(|| - self.next_kv_item().map(Elem) - ) + self.next_edge_item().map(Edge).or_else(|| self.next_kv_item().map(Elem)) } } impl DoubleEndedIterator for AbsTraversal - where Impl: TraversalImpl { + where Impl: TraversalImpl +{ fn next_back(&mut self) -> Option> { - self.next_edge_item_back().map(Edge).or_else(|| - self.next_kv_item_back().map(Elem) - ) + self.next_edge_item_back().map(Edge).or_else(|| self.next_kv_item_back().map(Elem)) } } -impl AbsTraversal - where Impl: TraversalImpl { +impl AbsTraversal where Impl: TraversalImpl { /// Advances the iterator and returns the item if it's an edge. Returns None /// and does nothing if the first item is not an edge. pub fn next_edge_item(&mut self) -> Option { diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 0c70a1544ef92..6f3fadb7f0c99 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -34,51 +34,51 @@ use Bound; /// normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code. #[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)] #[stable(feature = "rust1", since = "1.0.0")] -pub struct BTreeSet{ +pub struct BTreeSet { map: BTreeMap, } /// An iterator over a BTreeSet's items. #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, T: 'a> { - iter: Keys<'a, T, ()> + iter: Keys<'a, T, ()>, } /// An owning iterator over a BTreeSet's items. #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter { - iter: Map<::btree_map::IntoIter, fn((T, ())) -> T> + iter: Map<::btree_map::IntoIter, fn((T, ())) -> T>, } /// An iterator over a sub-range of BTreeSet's items. pub struct Range<'a, T: 'a> { - iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T> + iter: Map<::btree_map::Range<'a, T, ()>, fn((&'a T, &'a ())) -> &'a T>, } /// A lazy iterator producing elements in the set difference (in-order). #[stable(feature = "rust1", since = "1.0.0")] -pub struct Difference<'a, T:'a> { +pub struct Difference<'a, T: 'a> { a: Peekable>, b: Peekable>, } /// A lazy iterator producing elements in the set symmetric difference (in-order). #[stable(feature = "rust1", since = "1.0.0")] -pub struct SymmetricDifference<'a, T:'a> { +pub struct SymmetricDifference<'a, T: 'a> { a: Peekable>, b: Peekable>, } /// A lazy iterator producing elements in the set intersection (in-order). #[stable(feature = "rust1", since = "1.0.0")] -pub struct Intersection<'a, T:'a> { +pub struct Intersection<'a, T: 'a> { a: Peekable>, b: Peekable>, } /// A lazy iterator producing elements in the set union (in-order). #[stable(feature = "rust1", since = "1.0.0")] -pub struct Union<'a, T:'a> { +pub struct Union<'a, T: 'a> { a: Peekable>, b: Peekable>, } @@ -161,12 +161,15 @@ impl BTreeSet { #[unstable(feature = "btree_range", reason = "matches collection reform specification, waiting for dust to settle", issue = "27787")] - pub fn range<'a, Min: ?Sized + Ord = T, Max: ?Sized + Ord = T>(&'a self, min: Bound<&Min>, + pub fn range<'a, Min: ?Sized + Ord = T, Max: ?Sized + Ord = T>(&'a self, + min: Bound<&Min>, max: Bound<&Max>) - -> Range<'a, T> where - T: Borrow + Borrow, + -> Range<'a, T> + where T: Borrow + Borrow { - fn first((a, _): (A, B)) -> A { a } + fn first((a, _): (A, B)) -> A { + a + } let first: fn((&'a T, &'a ())) -> &'a T = first; // coerce to fn pointer Range { iter: self.map.range(min, max).map(first) } @@ -194,7 +197,10 @@ impl BTreeSet { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn difference<'a>(&'a self, other: &'a BTreeSet) -> Difference<'a, T> { - Difference{a: self.iter().peekable(), b: other.iter().peekable()} + Difference { + a: self.iter().peekable(), + b: other.iter().peekable(), + } } /// Visits the values representing the symmetric difference, in ascending order. @@ -216,9 +222,13 @@ impl BTreeSet { /// assert_eq!(sym_diff, [1, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet) - -> SymmetricDifference<'a, T> { - SymmetricDifference{a: self.iter().peekable(), b: other.iter().peekable()} + pub fn symmetric_difference<'a>(&'a self, + other: &'a BTreeSet) + -> SymmetricDifference<'a, T> { + SymmetricDifference { + a: self.iter().peekable(), + b: other.iter().peekable(), + } } /// Visits the values representing the intersection, in ascending order. @@ -240,9 +250,11 @@ impl BTreeSet { /// assert_eq!(intersection, [2]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn intersection<'a>(&'a self, other: &'a BTreeSet) - -> Intersection<'a, T> { - Intersection{a: self.iter().peekable(), b: other.iter().peekable()} + pub fn intersection<'a>(&'a self, other: &'a BTreeSet) -> Intersection<'a, T> { + Intersection { + a: self.iter().peekable(), + b: other.iter().peekable(), + } } /// Visits the values representing the union, in ascending order. @@ -263,7 +275,10 @@ impl BTreeSet { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn union<'a>(&'a self, other: &'a BTreeSet) -> Union<'a, T> { - Union{a: self.iter().peekable(), b: other.iter().peekable()} + Union { + a: self.iter().peekable(), + b: other.iter().peekable(), + } } /// Returns the number of elements in the set. @@ -279,7 +294,9 @@ impl BTreeSet { /// assert_eq!(v.len(), 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> usize { self.map.len() } + pub fn len(&self) -> usize { + self.map.len() + } /// Returns true if the set contains no elements. /// @@ -294,7 +311,9 @@ impl BTreeSet { /// assert!(!v.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// Clears the set, removing all values. /// @@ -329,7 +348,10 @@ impl BTreeSet { /// assert_eq!(set.contains(&4), false); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn contains(&self, value: &Q) -> bool where T: Borrow, Q: Ord { + pub fn contains(&self, value: &Q) -> bool + where T: Borrow, + Q: Ord + { self.map.contains_key(value) } @@ -339,7 +361,10 @@ impl BTreeSet { /// but the ordering on the borrowed form *must* match the /// ordering on the value type. #[unstable(feature = "set_recovery", issue = "28050")] - pub fn get(&self, value: &Q) -> Option<&T> where T: Borrow, Q: Ord { + pub fn get(&self, value: &Q) -> Option<&T> + where T: Borrow, + Q: Ord + { Recover::get(&self.map, value) } @@ -482,7 +507,10 @@ impl BTreeSet { /// assert_eq!(set.remove(&2), false); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn remove(&mut self, value: &Q) -> bool where T: Borrow, Q: Ord { + pub fn remove(&mut self, value: &Q) -> bool + where T: Borrow, + Q: Ord + { self.map.remove(value).is_some() } @@ -492,14 +520,17 @@ impl BTreeSet { /// but the ordering on the borrowed form *must* match the /// ordering on the value type. #[unstable(feature = "set_recovery", issue = "28050")] - pub fn take(&mut self, value: &Q) -> Option where T: Borrow, Q: Ord { + pub fn take(&mut self, value: &Q) -> Option + where T: Borrow, + Q: Ord + { Recover::take(&mut self.map, value) } } #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator for BTreeSet { - fn from_iter>(iter: I) -> BTreeSet { + fn from_iter>(iter: I) -> BTreeSet { let mut set = BTreeSet::new(); set.extend(iter); set @@ -524,7 +555,9 @@ impl IntoIterator for BTreeSet { /// assert_eq!(v, [1, 2, 3, 4]); /// ``` fn into_iter(self) -> IntoIter { - fn first((a, _): (A, B)) -> A { a } + fn first((a, _): (A, B)) -> A { + a + } let first: fn((T, ())) -> T = first; // coerce to fn pointer IntoIter { iter: self.map.into_iter().map(first) } @@ -544,7 +577,7 @@ impl<'a, T> IntoIterator for &'a BTreeSet { #[stable(feature = "rust1", since = "1.0.0")] impl Extend for BTreeSet { #[inline] - fn extend>(&mut self, iter: Iter) { + fn extend>(&mut self, iter: Iter) { for elem in iter { self.insert(elem); } @@ -553,7 +586,7 @@ impl Extend for BTreeSet { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } @@ -665,18 +698,26 @@ impl Debug for BTreeSet { } impl<'a, T> Clone for Iter<'a, T> { - fn clone(&self) -> Iter<'a, T> { Iter { iter: self.iter.clone() } } + fn clone(&self) -> Iter<'a, T> { + Iter { iter: self.iter.clone() } + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> Iterator for Iter<'a, T> { type Item = &'a T; - fn next(&mut self) -> Option<&'a T> { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> DoubleEndedIterator for Iter<'a, T> { - fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() } + fn next_back(&mut self) -> Option<&'a T> { + self.iter.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> ExactSizeIterator for Iter<'a, T> {} @@ -686,42 +727,56 @@ impl<'a, T> ExactSizeIterator for Iter<'a, T> {} impl Iterator for IntoIter { type Item = T; - fn next(&mut self) -> Option { self.iter.next() } - fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } + fn next(&mut self) -> Option { + self.iter.next() + } + fn size_hint(&self) -> (usize, Option) { + self.iter.size_hint() + } } #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for IntoIter { - fn next_back(&mut self) -> Option { self.iter.next_back() } + fn next_back(&mut self) -> Option { + self.iter.next_back() + } } #[stable(feature = "rust1", since = "1.0.0")] impl ExactSizeIterator for IntoIter {} impl<'a, T> Clone for Range<'a, T> { - fn clone(&self) -> Range<'a, T> { Range { iter: self.iter.clone() } } + fn clone(&self) -> Range<'a, T> { + Range { iter: self.iter.clone() } + } } impl<'a, T> Iterator for Range<'a, T> { type Item = &'a T; - fn next(&mut self) -> Option<&'a T> { self.iter.next() } + fn next(&mut self) -> Option<&'a T> { + self.iter.next() + } } impl<'a, T> DoubleEndedIterator for Range<'a, T> { - fn next_back(&mut self) -> Option<&'a T> { self.iter.next_back() } + fn next_back(&mut self) -> Option<&'a T> { + self.iter.next_back() + } } /// Compare `x` and `y`, but return `short` if x is None and `long` if y is None -fn cmp_opt(x: Option<&T>, y: Option<&T>, - short: Ordering, long: Ordering) -> Ordering { +fn cmp_opt(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering { match (x, y) { - (None , _ ) => short, - (_ , None ) => long, + (None, _) => short, + (_, None) => long, (Some(x1), Some(y1)) => x1.cmp(y1), } } impl<'a, T> Clone for Difference<'a, T> { fn clone(&self) -> Difference<'a, T> { - Difference { a: self.a.clone(), b: self.b.clone() } + Difference { + a: self.a.clone(), + b: self.b.clone(), + } } } #[stable(feature = "rust1", since = "1.0.0")] @@ -731,9 +786,14 @@ impl<'a, T: Ord> Iterator for Difference<'a, T> { fn next(&mut self) -> Option<&'a T> { loop { match cmp_opt(self.a.peek(), self.b.peek(), Less, Less) { - Less => return self.a.next(), - Equal => { self.a.next(); self.b.next(); } - Greater => { self.b.next(); } + Less => return self.a.next(), + Equal => { + self.a.next(); + self.b.next(); + } + Greater => { + self.b.next(); + } } } } @@ -741,7 +801,10 @@ impl<'a, T: Ord> Iterator for Difference<'a, T> { impl<'a, T> Clone for SymmetricDifference<'a, T> { fn clone(&self) -> SymmetricDifference<'a, T> { - SymmetricDifference { a: self.a.clone(), b: self.b.clone() } + SymmetricDifference { + a: self.a.clone(), + b: self.b.clone(), + } } } #[stable(feature = "rust1", since = "1.0.0")] @@ -751,8 +814,11 @@ impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> { fn next(&mut self) -> Option<&'a T> { loop { match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) { - Less => return self.a.next(), - Equal => { self.a.next(); self.b.next(); } + Less => return self.a.next(), + Equal => { + self.a.next(); + self.b.next(); + } Greater => return self.b.next(), } } @@ -761,7 +827,10 @@ impl<'a, T: Ord> Iterator for SymmetricDifference<'a, T> { impl<'a, T> Clone for Intersection<'a, T> { fn clone(&self) -> Intersection<'a, T> { - Intersection { a: self.a.clone(), b: self.b.clone() } + Intersection { + a: self.a.clone(), + b: self.b.clone(), + } } } #[stable(feature = "rust1", since = "1.0.0")] @@ -771,15 +840,22 @@ impl<'a, T: Ord> Iterator for Intersection<'a, T> { fn next(&mut self) -> Option<&'a T> { loop { let o_cmp = match (self.a.peek(), self.b.peek()) { - (None , _ ) => None, - (_ , None ) => None, + (None, _) => None, + (_, None) => None, (Some(a1), Some(b1)) => Some(a1.cmp(b1)), }; match o_cmp { - None => return None, - Some(Less) => { self.a.next(); } - Some(Equal) => { self.b.next(); return self.a.next() } - Some(Greater) => { self.b.next(); } + None => return None, + Some(Less) => { + self.a.next(); + } + Some(Equal) => { + self.b.next(); + return self.a.next(); + } + Some(Greater) => { + self.b.next(); + } } } } @@ -787,7 +863,10 @@ impl<'a, T: Ord> Iterator for Intersection<'a, T> { impl<'a, T> Clone for Union<'a, T> { fn clone(&self) -> Union<'a, T> { - Union { a: self.a.clone(), b: self.b.clone() } + Union { + a: self.a.clone(), + b: self.b.clone(), + } } } #[stable(feature = "rust1", since = "1.0.0")] @@ -797,8 +876,11 @@ impl<'a, T: Ord> Iterator for Union<'a, T> { fn next(&mut self) -> Option<&'a T> { loop { match cmp_opt(self.a.peek(), self.b.peek(), Greater, Less) { - Less => return self.a.next(), - Equal => { self.b.next(); return self.a.next() } + Less => return self.a.next(), + Equal => { + self.b.next(); + return self.a.next(); + } Greater => return self.b.next(), } } diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 32cd4193d8855..717c1d13af4bd 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -20,7 +20,7 @@ use core::marker; use core::fmt; -use core::iter::{FromIterator}; +use core::iter::FromIterator; use core::ops::{Sub, BitOr, BitAnd, BitXor}; // FIXME(contentions): implement union family of methods? (general design may be @@ -43,11 +43,13 @@ pub struct EnumSet { impl Copy for EnumSet {} impl Clone for EnumSet { - fn clone(&self) -> EnumSet { *self } + fn clone(&self) -> EnumSet { + *self + } } #[stable(feature = "rust1", since = "1.0.0")] -impl fmt::Debug for EnumSet { +impl fmt::Debug for EnumSet { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_set().entries(self).finish() } @@ -79,18 +81,22 @@ pub trait CLike { fn from_usize(usize) -> Self; } -fn bit(e: &E) -> usize { +fn bit(e: &E) -> usize { use core::usize; let value = e.to_usize(); assert!(value < usize::BITS, - "EnumSet only supports up to {} variants.", usize::BITS - 1); + "EnumSet only supports up to {} variants.", + usize::BITS - 1); 1 << value } -impl EnumSet { +impl EnumSet { /// Returns an empty `EnumSet`. pub fn new() -> EnumSet { - EnumSet {bits: 0, marker: marker::PhantomData} + EnumSet { + bits: 0, + marker: marker::PhantomData, + } } /// Returns the number of elements in the given `EnumSet`. @@ -124,14 +130,18 @@ impl EnumSet { /// Returns the union of both `EnumSets`. pub fn union(&self, e: EnumSet) -> EnumSet { - EnumSet {bits: self.bits | e.bits, - marker: marker::PhantomData} + EnumSet { + bits: self.bits | e.bits, + marker: marker::PhantomData, + } } /// Returns the intersection of both `EnumSets`. pub fn intersection(&self, e: EnumSet) -> EnumSet { - EnumSet {bits: self.bits & e.bits, - marker: marker::PhantomData} + EnumSet { + bits: self.bits & e.bits, + marker: marker::PhantomData, + } } /// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before @@ -159,35 +169,47 @@ impl EnumSet { } } -impl Sub for EnumSet { +impl Sub for EnumSet { type Output = EnumSet; fn sub(self, e: EnumSet) -> EnumSet { - EnumSet {bits: self.bits & !e.bits, marker: marker::PhantomData} + EnumSet { + bits: self.bits & !e.bits, + marker: marker::PhantomData, + } } } -impl BitOr for EnumSet { +impl BitOr for EnumSet { type Output = EnumSet; fn bitor(self, e: EnumSet) -> EnumSet { - EnumSet {bits: self.bits | e.bits, marker: marker::PhantomData} + EnumSet { + bits: self.bits | e.bits, + marker: marker::PhantomData, + } } } -impl BitAnd for EnumSet { +impl BitAnd for EnumSet { type Output = EnumSet; fn bitand(self, e: EnumSet) -> EnumSet { - EnumSet {bits: self.bits & e.bits, marker: marker::PhantomData} + EnumSet { + bits: self.bits & e.bits, + marker: marker::PhantomData, + } } } -impl BitXor for EnumSet { +impl BitXor for EnumSet { type Output = EnumSet; fn bitxor(self, e: EnumSet) -> EnumSet { - EnumSet {bits: self.bits ^ e.bits, marker: marker::PhantomData} + EnumSet { + bits: self.bits ^ e.bits, + marker: marker::PhantomData, + } } } @@ -209,13 +231,17 @@ impl Clone for Iter { } } -impl Iter { +impl Iter { fn new(bits: usize) -> Iter { - Iter { index: 0, bits: bits, marker: marker::PhantomData } + Iter { + index: 0, + bits: bits, + marker: marker::PhantomData, + } } } -impl Iterator for Iter { +impl Iterator for Iter { type Item = E; fn next(&mut self) -> Option { @@ -239,8 +265,8 @@ impl Iterator for Iter { } } -impl FromIterator for EnumSet { - fn from_iter>(iter: I) -> EnumSet { +impl FromIterator for EnumSet { + fn from_iter>(iter: I) -> EnumSet { let mut ret = EnumSet::new(); ret.extend(iter); ret @@ -248,7 +274,8 @@ impl FromIterator for EnumSet { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, E> IntoIterator for &'a EnumSet where E: CLike { +impl<'a, E> IntoIterator for &'a EnumSet where E: CLike +{ type Item = E; type IntoIter = Iter; @@ -257,8 +284,8 @@ impl<'a, E> IntoIterator for &'a EnumSet where E: CLike { } } -impl Extend for EnumSet { - fn extend>(&mut self, iter: I) { +impl Extend for EnumSet { + fn extend>(&mut self, iter: I) { for element in iter { self.insert(element); } @@ -267,7 +294,7 @@ impl Extend for EnumSet { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, E: 'a + CLike + Copy> Extend<&'a E> for EnumSet { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index dfdf36e6f605b..39370768ce569 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -74,8 +74,11 @@ extern crate rustc_unicode; extern crate alloc; -#[cfg(test)] #[macro_use] extern crate std; -#[cfg(test)] extern crate test; +#[cfg(test)] +#[macro_use] +extern crate std; +#[cfg(test)] +extern crate test; pub use binary_heap::BinaryHeap; pub use btree_map::BTreeMap; diff --git a/src/libcollections/linked_list.rs b/src/libcollections/linked_list.rs index a689c66eeaff5..631857f8e3c56 100644 --- a/src/libcollections/linked_list.rs +++ b/src/libcollections/linked_list.rs @@ -44,8 +44,8 @@ struct Rawlink { } impl Copy for Rawlink {} -unsafe impl Send for Rawlink {} -unsafe impl Sync for Rawlink {} +unsafe impl Send for Rawlink {} +unsafe impl Sync for Rawlink {} struct Node { next: Link, @@ -55,7 +55,7 @@ struct Node { /// An iterator over references to the items of a `LinkedList`. #[stable(feature = "rust1", since = "1.0.0")] -pub struct Iter<'a, T:'a> { +pub struct Iter<'a, T: 'a> { head: &'a Link, tail: Rawlink>, nelem: usize, @@ -75,7 +75,7 @@ impl<'a, T> Clone for Iter<'a, T> { /// An iterator over mutable references to the items of a `LinkedList`. #[stable(feature = "rust1", since = "1.0.0")] -pub struct IterMut<'a, T:'a> { +pub struct IterMut<'a, T: 'a> { list: &'a mut LinkedList, head: Rawlink>, tail: Rawlink>, @@ -86,19 +86,19 @@ pub struct IterMut<'a, T:'a> { #[derive(Clone)] #[stable(feature = "rust1", since = "1.0.0")] pub struct IntoIter { - list: LinkedList + list: LinkedList, } /// Rawlink is a type like Option but for holding a raw pointer impl Rawlink { /// Like Option::None for Rawlink fn none() -> Rawlink { - Rawlink{p: ptr::null_mut()} + Rawlink { p: ptr::null_mut() } } /// Like Option::Some for Rawlink fn some(n: &mut T) -> Rawlink { - Rawlink{p: n} + Rawlink { p: n } } /// Convert the `Rawlink` into an Option value @@ -139,13 +139,17 @@ impl<'a, T> From<&'a mut Link> for Rawlink> { impl Clone for Rawlink { #[inline] fn clone(&self) -> Rawlink { - Rawlink{p: self.p} + Rawlink { p: self.p } } } impl Node { fn new(v: T) -> Node { - Node{value: v, next: None, prev: Rawlink::none()} + Node { + value: v, + next: None, + prev: Rawlink::none(), + } } /// Update the `prev` link on `next`, then set self's next pointer. @@ -192,7 +196,7 @@ impl LinkedList { self.length -= 1; match front_node.next.take() { Some(node) => self.list_head = link_no_prev(node), - None => self.list_tail = Rawlink::none() + None => self.list_tail = Rawlink::none(), } front_node }) @@ -220,7 +224,7 @@ impl LinkedList { self.list_tail = tail.prev; match tail.prev.resolve_mut() { None => self.list_head.take(), - Some(tail_prev) => tail_prev.next.take() + Some(tail_prev) => tail_prev.next.take(), } }) } @@ -230,7 +234,9 @@ impl LinkedList { #[stable(feature = "rust1", since = "1.0.0")] impl Default for LinkedList { #[inline] - fn default() -> LinkedList { LinkedList::new() } + fn default() -> LinkedList { + LinkedList::new() + } } impl LinkedList { @@ -238,7 +244,11 @@ impl LinkedList { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn new() -> LinkedList { - LinkedList{list_head: None, list_tail: Rawlink::none(), length: 0} + LinkedList { + list_head: None, + list_tail: Rawlink::none(), + length: 0, + } } /// Moves all elements from `other` to the end of the list. @@ -274,7 +284,7 @@ impl LinkedList { self.length = other.length; self.list_head = other.list_head.take(); self.list_tail = other.list_tail.take(); - }, + } Some(tail) => { // Carefully empty `other`. let o_tail = other.list_tail.take(); @@ -296,7 +306,11 @@ impl LinkedList { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn iter(&self) -> Iter { - Iter{nelem: self.len(), head: &self.list_head, tail: self.list_tail} + Iter { + nelem: self.len(), + head: &self.list_head, + tail: self.list_tail, + } } /// Provides a forward iterator with mutable references. @@ -307,7 +321,7 @@ impl LinkedList { nelem: self.len(), head: Rawlink::from(&mut self.list_head), tail: self.list_tail, - list: self + list: self, } } @@ -452,9 +466,7 @@ impl LinkedList { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn back(&self) -> Option<&T> { - unsafe { - self.list_tail.resolve().map(|tail| &tail.value) - } + unsafe { self.list_tail.resolve().map(|tail| &tail.value) } } /// Provides a mutable reference to the back element, or `None` if the list @@ -481,9 +493,7 @@ impl LinkedList { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn back_mut(&mut self) -> Option<&mut T> { - unsafe { - self.list_tail.resolve_mut().map(|tail| &mut tail.value) - } + unsafe { self.list_tail.resolve_mut().map(|tail| &mut tail.value) } } /// Adds an element first in the list. @@ -532,7 +542,7 @@ impl LinkedList { /// #[stable(feature = "rust1", since = "1.0.0")] pub fn pop_front(&mut self) -> Option { - self.pop_front_node().map(|box Node{value, ..}| value) + self.pop_front_node().map(|box Node { value, .. }| value) } /// Appends an element to the back of a list @@ -568,7 +578,7 @@ impl LinkedList { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn pop_back(&mut self) -> Option { - self.pop_back_node().map(|box Node{value, ..}| value) + self.pop_back_node().map(|box Node { value, .. }| value) } /// Splits the list into two at the given index. Returns everything after the given index, @@ -617,7 +627,7 @@ impl LinkedList { iter.next(); } iter.head - } else { + } else { // better off starting from the end let mut iter = self.iter_mut(); for _ in 0..len - 1 - (at - 1) { @@ -641,7 +651,7 @@ impl LinkedList { let second_part = LinkedList { list_head: second_part_head, list_tail: self.list_tail, - length: len - at + length: len - at, }; // Fix the tail ptr of the first part @@ -760,7 +770,9 @@ impl<'a, A> IterMut<'a, A> { // // The inserted node will not appear in further iteration. match unsafe { self.head.resolve_mut() } { - None => { self.list.push_back_node(ins_node); } + None => { + self.list.push_back_node(ins_node); + } Some(node) => { let prev_node = match unsafe { node.prev.resolve_mut() } { None => return self.list.push_front_node(ins_node), @@ -830,11 +842,9 @@ impl<'a, A> IterMut<'a, A> { issue = "27794")] pub fn peek_next(&mut self) -> Option<&mut A> { if self.nelem == 0 { - return None - } - unsafe { - self.head.resolve_mut().map(|head| &mut head.value) + return None; } + unsafe { self.head.resolve_mut().map(|head| &mut head.value) } } } @@ -843,7 +853,9 @@ impl Iterator for IntoIter { type Item = A; #[inline] - fn next(&mut self) -> Option { self.list.pop_front() } + fn next(&mut self) -> Option { + self.list.pop_front() + } #[inline] fn size_hint(&self) -> (usize, Option) { @@ -854,7 +866,9 @@ impl Iterator for IntoIter { #[stable(feature = "rust1", since = "1.0.0")] impl DoubleEndedIterator for IntoIter { #[inline] - fn next_back(&mut self) -> Option { self.list.pop_back() } + fn next_back(&mut self) -> Option { + self.list.pop_back() + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -862,7 +876,7 @@ impl ExactSizeIterator for IntoIter {} #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator for LinkedList { - fn from_iter>(iter: T) -> LinkedList { + fn from_iter>(iter: T) -> LinkedList { let mut ret = LinkedList::new(); ret.extend(iter); ret @@ -877,7 +891,7 @@ impl IntoIterator for LinkedList { /// Consumes the list into an iterator yielding elements by value. #[inline] fn into_iter(self) -> IntoIter { - IntoIter{list: self} + IntoIter { list: self } } } @@ -903,14 +917,16 @@ impl<'a, T> IntoIterator for &'a mut LinkedList { #[stable(feature = "rust1", since = "1.0.0")] impl Extend for LinkedList { - fn extend>(&mut self, iter: T) { - for elt in iter { self.push_back(elt); } + fn extend>(&mut self, iter: T) { + for elt in iter { + self.push_back(elt); + } } } #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } @@ -918,13 +934,11 @@ impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList { #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for LinkedList { fn eq(&self, other: &LinkedList) -> bool { - self.len() == other.len() && - self.iter().eq(other.iter()) + self.len() == other.len() && self.iter().eq(other.iter()) } fn ne(&self, other: &LinkedList) -> bool { - self.len() != other.len() || - self.iter().ne(other.iter()) + self.len() != other.len() || self.iter().ne(other.iter()) } } @@ -974,7 +988,7 @@ impl Hash for LinkedList { mod tests { use std::clone::Clone; use std::iter::{Iterator, IntoIterator, Extend}; - use std::option::Option::{Some, None, self}; + use std::option::Option::{self, Some, None}; use std::__rand::{thread_rng, Rng}; use std::thread; use std::vec::Vec; @@ -991,13 +1005,16 @@ mod tests { let mut last_ptr: Option<&Node> = None; let mut node_ptr: &Node; match list.list_head { - None => { assert_eq!(0, list.length); return } + None => { + assert_eq!(0, list.length); + return; + } Some(ref node) => node_ptr = &**node, } loop { match unsafe { (last_ptr, node_ptr.prev.resolve()) } { - (None , None ) => {} - (None , _ ) => panic!("prev link for list_head"), + (None, None) => {} + (None, _) => panic!("prev link for list_head"), (Some(p), Some(pptr)) => { assert_eq!(p as *const Node, pptr as *const Node); } @@ -1054,8 +1071,8 @@ mod tests { } // Non-empty to non-empty - let v = vec![1,2,3,4,5]; - let u = vec![9,8,1,2,3,4,5]; + let v = vec![1, 2, 3, 4, 5]; + let u = vec![9, 8, 1, 2, 3, 4, 5]; let mut m = list_from(&v); let mut n = list_from(&u); m.append(&mut n); @@ -1077,7 +1094,7 @@ mod tests { #[test] fn test_insert_prev() { - let mut m = list_from(&[0,2,4,6,8]); + let mut m = list_from(&[0, 2, 4, 6, 8]); let len = m.len(); { let mut it = m.iter_mut(); @@ -1099,17 +1116,21 @@ mod tests { } check_links(&m); assert_eq!(m.len(), 3 + len * 2); - assert_eq!(m.into_iter().collect::>(), [-2,0,1,2,3,4,5,6,7,8,9,0,1]); + assert_eq!(m.into_iter().collect::>(), + [-2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]); } #[test] fn test_send() { - let n = list_from(&[1,2,3]); + let n = list_from(&[1, 2, 3]); thread::spawn(move || { check_links(&n); - let a: &[_] = &[&1,&2,&3]; + let a: &[_] = &[&1, &2, &3]; assert_eq!(a, &n.iter().collect::>()[..]); - }).join().ok().unwrap(); + }) + .join() + .ok() + .unwrap(); } #[test] @@ -1179,7 +1200,7 @@ mod tests { v.remove(0); } } - 2 | 4 => { + 2 | 4 => { m.push_front(-i); v.insert(0, -i); } diff --git a/src/libcollections/range.rs b/src/libcollections/range.rs index e7414bcf323f6..c70aa67366b34 100644 --- a/src/libcollections/range.rs +++ b/src/libcollections/range.rs @@ -22,26 +22,38 @@ pub trait RangeArgument { /// Start index (inclusive) /// /// Return start value if present, else `None`. - fn start(&self) -> Option<&T> { None } + fn start(&self) -> Option<&T> { + None + } /// End index (exclusive) /// /// Return end value if present, else `None`. - fn end(&self) -> Option<&T> { None } + fn end(&self) -> Option<&T> { + None + } } impl RangeArgument for RangeFull {} impl RangeArgument for RangeFrom { - fn start(&self) -> Option<&T> { Some(&self.start) } + fn start(&self) -> Option<&T> { + Some(&self.start) + } } impl RangeArgument for RangeTo { - fn end(&self) -> Option<&T> { Some(&self.end) } + fn end(&self) -> Option<&T> { + Some(&self.end) + } } impl RangeArgument for Range { - fn start(&self) -> Option<&T> { Some(&self.start) } - fn end(&self) -> Option<&T> { Some(&self.end) } + fn start(&self) -> Option<&T> { + Some(&self.start) + } + fn end(&self) -> Option<&T> { + Some(&self.end) + } } diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index ec8881279831a..0e615402b46d2 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -156,7 +156,9 @@ mod hack { } #[inline] - pub fn to_vec(s: &[T]) -> Vec where T: Clone { + pub fn to_vec(s: &[T]) -> Vec + where T: Clone + { let mut vector = Vec::with_capacity(s.len()); vector.push_all(s); vector @@ -535,7 +537,9 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn split(&self, pred: F) -> Split where F: FnMut(&T) -> bool { + pub fn split(&self, pred: F) -> Split + where F: FnMut(&T) -> bool + { core_slice::SliceExt::split(self, pred) } @@ -543,7 +547,9 @@ impl [T] { /// match `pred`. The matched element is not contained in the subslices. #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn split_mut(&mut self, pred: F) -> SplitMut where F: FnMut(&T) -> bool { + pub fn split_mut(&mut self, pred: F) -> SplitMut + where F: FnMut(&T) -> bool + { core_slice::SliceExt::split_mut(self, pred) } @@ -567,7 +573,9 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn splitn(&self, n: usize, pred: F) -> SplitN where F: FnMut(&T) -> bool { + pub fn splitn(&self, n: usize, pred: F) -> SplitN + where F: FnMut(&T) -> bool + { core_slice::SliceExt::splitn(self, n, pred) } @@ -580,7 +588,8 @@ impl [T] { #[stable(feature = "rust1", since = "1.0.0")] #[inline] pub fn splitn_mut(&mut self, n: usize, pred: F) -> SplitNMut - where F: FnMut(&T) -> bool { + where F: FnMut(&T) -> bool + { core_slice::SliceExt::splitn_mut(self, n, pred) } @@ -605,7 +614,9 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn rsplitn(&self, n: usize, pred: F) -> RSplitN where F: FnMut(&T) -> bool { + pub fn rsplitn(&self, n: usize, pred: F) -> RSplitN + where F: FnMut(&T) -> bool + { core_slice::SliceExt::rsplitn(self, n, pred) } @@ -618,8 +629,9 @@ impl [T] { /// slice. #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn rsplitn_mut(&mut self, n: usize, pred: F) -> RSplitNMut - where F: FnMut(&T) -> bool { + pub fn rsplitn_mut(&mut self, n: usize, pred: F) -> RSplitNMut + where F: FnMut(&T) -> bool + { core_slice::SliceExt::rsplitn_mut(self, n, pred) } @@ -633,7 +645,9 @@ impl [T] { /// assert!(!v.contains(&50)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn contains(&self, x: &T) -> bool where T: PartialEq { + pub fn contains(&self, x: &T) -> bool + where T: PartialEq + { core_slice::SliceExt::contains(self, x) } @@ -649,7 +663,9 @@ impl [T] { /// assert!(!v.starts_with(&[10, 50])); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn starts_with(&self, needle: &[T]) -> bool where T: PartialEq { + pub fn starts_with(&self, needle: &[T]) -> bool + where T: PartialEq + { core_slice::SliceExt::starts_with(self, needle) } @@ -665,7 +681,9 @@ impl [T] { /// assert!(!v.ends_with(&[50, 30])); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn ends_with(&self, needle: &[T]) -> bool where T: PartialEq { + pub fn ends_with(&self, needle: &[T]) -> bool + where T: PartialEq + { core_slice::SliceExt::ends_with(self, needle) } @@ -692,7 +710,9 @@ impl [T] { /// assert!(match r { Ok(1...4) => true, _ => false, }); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn binary_search(&self, x: &T) -> Result where T: Ord { + pub fn binary_search(&self, x: &T) -> Result + where T: Ord + { core_slice::SliceExt::binary_search(self, x) } @@ -729,7 +749,9 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn binary_search_by(&self, f: F) -> Result where F: FnMut(&T) -> Ordering { + pub fn binary_search_by(&self, f: F) -> Result + where F: FnMut(&T) -> Ordering + { core_slice::SliceExt::binary_search_by(self, f) } @@ -749,7 +771,9 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn sort(&mut self) where T: Ord { + pub fn sort(&mut self) + where T: Ord + { self.sort_by(|a, b| a.cmp(b)) } @@ -772,7 +796,9 @@ impl [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn sort_by(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering { + pub fn sort_by(&mut self, compare: F) + where F: FnMut(&T, &T) -> Ordering + { merge_sort(self, compare) } @@ -796,14 +822,18 @@ impl [T] { /// assert!(dst == [3, 4, 5]); /// ``` #[unstable(feature = "clone_from_slice", issue = "27750")] - pub fn clone_from_slice(&mut self, src: &[T]) -> usize where T: Clone { + pub fn clone_from_slice(&mut self, src: &[T]) -> usize + where T: Clone + { core_slice::SliceExt::clone_from_slice(self, src) } /// Copies `self` into a new `Vec`. #[stable(feature = "rust1", since = "1.0.0")] #[inline] - pub fn to_vec(&self) -> Vec where T: Clone { + pub fn to_vec(&self) -> Vec + where T: Clone + { // NB see hack module in this file hack::to_vec(self) } @@ -886,7 +916,11 @@ impl> SliceConcatExt for [V] { let mut result = Vec::with_capacity(size + self.len()); let mut first = true; for v in self { - if first { first = false } else { result.push(sep.clone()) } + if first { + first = false + } else { + result.push(sep.clone()) + } result.push_all(v.borrow()) } result @@ -903,33 +937,43 @@ impl> SliceConcatExt for [V] { #[stable(feature = "rust1", since = "1.0.0")] impl Borrow<[T]> for Vec { - fn borrow(&self) -> &[T] { &self[..] } + fn borrow(&self) -> &[T] { + &self[..] + } } #[stable(feature = "rust1", since = "1.0.0")] impl BorrowMut<[T]> for Vec { - fn borrow_mut(&mut self) -> &mut [T] { &mut self[..] } + fn borrow_mut(&mut self) -> &mut [T] { + &mut self[..] + } } #[stable(feature = "rust1", since = "1.0.0")] impl ToOwned for [T] { type Owned = Vec; #[cfg(not(test))] - fn to_owned(&self) -> Vec { self.to_vec() } + fn to_owned(&self) -> Vec { + self.to_vec() + } // HACK(japaric): with cfg(test) the inherent `[T]::to_vec`, which is required for this method // definition, is not available. Since we don't require this method for testing purposes, I'll // just stub it // NB see the slice::hack module in slice.rs for more information #[cfg(test)] - fn to_owned(&self) -> Vec { panic!("not available with cfg(test)") } + fn to_owned(&self) -> Vec { + panic!("not available with cfg(test)") + } } //////////////////////////////////////////////////////////////////////////////// // Sorting //////////////////////////////////////////////////////////////////////////////// -fn insertion_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering { +fn insertion_sort(v: &mut [T], mut compare: F) + where F: FnMut(&T, &T) -> Ordering +{ let len = v.len() as isize; let buf_v = v.as_mut_ptr(); @@ -945,8 +989,7 @@ fn insertion_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O // rather than <=, to maintain stability. // 0 <= j - 1 < len, so .offset(j - 1) is in bounds. - while j > 0 && - compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less { + while j > 0 && compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less { j -= 1; } @@ -959,9 +1002,7 @@ fn insertion_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O if i != j { let tmp = ptr::read(read_ptr); - ptr::copy(&*buf_v.offset(j), - buf_v.offset(j + 1), - (i - j) as usize); + ptr::copy(&*buf_v.offset(j), buf_v.offset(j + 1), (i - j) as usize); ptr::copy_nonoverlapping(&tmp, buf_v.offset(j), 1); mem::forget(tmp); } @@ -969,7 +1010,9 @@ fn insertion_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O } } -fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering { +fn merge_sort(v: &mut [T], mut compare: F) + where F: FnMut(&T, &T) -> Ordering +{ // warning: this wildly uses unsafe. const BASE_INSERTION: usize = 32; const LARGE_INSERTION: usize = 16; @@ -998,7 +1041,7 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order let mut working_space = Vec::with_capacity(2 * len); // these both are buffers of length `len`. let mut buf_dat = working_space.as_mut_ptr(); - let mut buf_tmp = unsafe {buf_dat.offset(len as isize)}; + let mut buf_tmp = unsafe { buf_dat.offset(len as isize) }; // length `len`. let buf_v = v.as_ptr(); @@ -1010,7 +1053,7 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order // We could hardcode the sorting comparisons here, and we could // manipulate/step the pointers themselves, rather than repeatedly // .offset-ing. - for start in (0.. len).step_by(insertion) { + for start in (0..len).step_by(insertion) { // start <= i < len; for i in start..cmp::min(start + insertion, len) { // j satisfies: start <= j <= i; @@ -1024,8 +1067,7 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order // start <= j - 1 < len, so .offset(j - 1) is in // bounds. - while j > start as isize && - compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less { + while j > start as isize && compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less { j -= 1; } @@ -1035,9 +1077,7 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order // j + 1 could be `len` (for the last `i`), but in // that case, `i == j` so we don't copy. The // `.offset(j)` is always in bounds. - ptr::copy(&*buf_dat.offset(j), - buf_dat.offset(j + 1), - i - j as usize); + ptr::copy(&*buf_dat.offset(j), buf_dat.offset(j + 1), i - j as usize); ptr::copy_nonoverlapping(read_ptr, buf_dat.offset(j), 1); } } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index c16ce61a1365a..72a148fa2f496 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -57,7 +57,7 @@ pub use core::str::{from_utf8, Chars, CharIndices, Bytes}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::{from_utf8_unchecked, ParseBoolError}; #[stable(feature = "rust1", since = "1.0.0")] -pub use rustc_unicode::str::{SplitWhitespace}; +pub use rustc_unicode::str::SplitWhitespace; #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::pattern; @@ -95,8 +95,8 @@ impl> SliceConcatExt for [S] { // this is wrong without the guarantee that `self` is non-empty // `len` calculation may overflow but push_str but will check boundaries - let len = sep.len() * (self.len() - 1) - + self.iter().map(|s| s.borrow().len()).sum::(); + let len = sep.len() * (self.len() - 1) + + self.iter().map(|s| s.borrow().len()).sum::(); let mut result = String::with_capacity(len); let mut first = true; @@ -122,7 +122,7 @@ impl> SliceConcatExt for [S] { #[derive(Clone)] #[unstable(feature = "str_utf16", issue = "27714")] pub struct Utf16Units<'a> { - encoder: Utf16Encoder> + encoder: Utf16Encoder>, } #[stable(feature = "rust1", since = "1.0.0")] @@ -130,10 +130,14 @@ impl<'a> Iterator for Utf16Units<'a> { type Item = u16; #[inline] - fn next(&mut self) -> Option { self.encoder.next() } + fn next(&mut self) -> Option { + self.encoder.next() + } #[inline] - fn size_hint(&self) -> (usize, Option) { self.encoder.size_hint() } + fn size_hint(&self) -> (usize, Option) { + self.encoder.size_hint() + } } // Return the initial codepoint accumulator for the first byte. @@ -151,16 +155,16 @@ macro_rules! utf8_acc_cont_byte { #[stable(feature = "rust1", since = "1.0.0")] impl Borrow for String { #[inline] - fn borrow(&self) -> &str { &self[..] } + fn borrow(&self) -> &str { + &self[..] + } } #[stable(feature = "rust1", since = "1.0.0")] impl ToOwned for str { type Owned = String; fn to_owned(&self) -> String { - unsafe { - String::from_utf8_unchecked(self.as_bytes().to_owned()) - } + unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) } } } @@ -1450,13 +1454,16 @@ impl str { // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992 // for the definition of `Final_Sigma`. debug_assert!('Σ'.len_utf8() == 2); - let is_word_final = - case_ignoreable_then_cased(from[..i].chars().rev()) && - !case_ignoreable_then_cased(from[i + 2..].chars()); - to.push_str(if is_word_final { "ς" } else { "σ" }); + let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) && + !case_ignoreable_then_cased(from[i + 2..].chars()); + to.push_str(if is_word_final { + "ς" + } else { + "σ" + }); } - fn case_ignoreable_then_cased>(iter: I) -> bool { + fn case_ignoreable_then_cased>(iter: I) -> bool { use rustc_unicode::derived_property::{Cased, Case_Ignorable}; match iter.skip_while(|&c| Case_Ignorable(c)).next() { Some(c) => Cased(c), diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 84667e04e04cb..7934ebd443960 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -61,9 +61,7 @@ impl String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn new() -> String { - String { - vec: Vec::new(), - } + String { vec: Vec::new() } } /// Creates a new string buffer with the given capacity. @@ -92,9 +90,7 @@ impl String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(capacity: usize) -> String { - String { - vec: Vec::with_capacity(capacity), - } + String { vec: Vec::with_capacity(capacity) } } // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is @@ -167,7 +163,12 @@ impl String { pub fn from_utf8(vec: Vec) -> Result { match str::from_utf8(&vec) { Ok(..) => Ok(String { vec: vec }), - Err(e) => Err(FromUtf8Error { bytes: vec, error: e }) + Err(e) => { + Err(FromUtf8Error { + bytes: vec, + error: e, + }) + } } } @@ -240,9 +241,7 @@ impl String { let mut res = String::with_capacity(total); if i > 0 { - unsafe { - res.as_mut_vec().push_all(&v[..i]) - }; + unsafe { res.as_mut_vec().push_all(&v[..i]) }; } // subseqidx is the index of the first byte of the subsequence we're @@ -280,10 +279,10 @@ impl String { } 3 => { match (byte, safe_get(v, i, total)) { - (0xE0 , 0xA0 ... 0xBF) => (), - (0xE1 ... 0xEC, 0x80 ... 0xBF) => (), - (0xED , 0x80 ... 0x9F) => (), - (0xEE ... 0xEF, 0x80 ... 0xBF) => (), + (0xE0, 0xA0...0xBF) => (), + (0xE1...0xEC, 0x80...0xBF) => (), + (0xED, 0x80...0x9F) => (), + (0xEE...0xEF, 0x80...0xBF) => (), _ => { error!(); continue; @@ -298,9 +297,9 @@ impl String { } 4 => { match (byte, safe_get(v, i, total)) { - (0xF0 , 0x90 ... 0xBF) => (), - (0xF1 ... 0xF3, 0x80 ... 0xBF) => (), - (0xF4 , 0x80 ... 0x8F) => (), + (0xF0, 0x90...0xBF) => (), + (0xF1...0xF3, 0x80...0xBF) => (), + (0xF4, 0x80...0x8F) => (), _ => { error!(); continue; @@ -326,9 +325,7 @@ impl String { } } if subseqidx < total { - unsafe { - res.as_mut_vec().push_all(&v[subseqidx..total]) - }; + unsafe { res.as_mut_vec().push_all(&v[subseqidx..total]) }; } Cow::Owned(res) } @@ -388,9 +385,7 @@ impl String { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub unsafe fn from_raw_parts(buf: *mut u8, length: usize, capacity: usize) -> String { - String { - vec: Vec::from_raw_parts(buf, length, capacity), - } + String { vec: Vec::from_raw_parts(buf, length, capacity) } } /// Converts a vector of bytes to a `String` without checking that the @@ -567,10 +562,10 @@ impl String { unsafe { // Attempt to not use an intermediate buffer by just pushing bytes // directly onto this string. - let slice = slice::from_raw_parts_mut ( - self.vec.as_mut_ptr().offset(cur_len as isize), - ch_len - ); + let slice = slice::from_raw_parts_mut(self.vec + .as_mut_ptr() + .offset(cur_len as isize), + ch_len); let used = ch.encode_utf8(slice).unwrap_or(0); self.vec.set_len(cur_len + used); } @@ -630,7 +625,7 @@ impl String { pub fn pop(&mut self) -> Option { let len = self.len(); if len == 0 { - return None + return None; } let ch = self.char_at_reverse(len); @@ -742,7 +737,9 @@ impl String { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> usize { self.vec.len() } + pub fn len(&self) -> usize { + self.vec.len() + } /// Returns true if the string contains no bytes /// @@ -756,7 +753,9 @@ impl String { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// Truncates the string, returning it to 0 length. /// @@ -802,7 +801,9 @@ impl String { #[unstable(feature = "drain", reason = "recently added, matches RFC", issue = "27711")] - pub fn drain(&mut self, range: R) -> Drain where R: RangeArgument { + pub fn drain(&mut self, range: R) -> Drain + where R: RangeArgument + { // Memory safety // // The String version of Drain does not have the memory safety issues @@ -852,11 +853,15 @@ impl FromUtf8Error { /// Consumes this error, returning the bytes that were attempted to make a /// `String` with. #[stable(feature = "rust1", since = "1.0.0")] - pub fn into_bytes(self) -> Vec { self.bytes } + pub fn into_bytes(self) -> Vec { + self.bytes + } /// Access the underlying UTF8-error that was the cause of this error. #[stable(feature = "rust1", since = "1.0.0")] - pub fn utf8_error(&self) -> Utf8Error { self.error } + pub fn utf8_error(&self) -> Utf8Error { + self.error + } } #[stable(feature = "rust1", since = "1.0.0")] @@ -886,7 +891,7 @@ impl Clone for String { #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator for String { - fn from_iter>(iterable: I) -> String { + fn from_iter>(iterable: I) -> String { let mut buf = String::new(); buf.extend(iterable); buf @@ -895,7 +900,7 @@ impl FromIterator for String { #[stable(feature = "rust1", since = "1.0.0")] impl<'a> FromIterator<&'a str> for String { - fn from_iter>(iterable: I) -> String { + fn from_iter>(iterable: I) -> String { let mut buf = String::new(); buf.extend(iterable); buf @@ -904,7 +909,7 @@ impl<'a> FromIterator<&'a str> for String { #[stable(feature = "extend_string", since = "1.4.0")] impl FromIterator for String { - fn from_iter>(iterable: I) -> String { + fn from_iter>(iterable: I) -> String { let mut buf = String::new(); buf.extend(iterable); buf @@ -913,7 +918,7 @@ impl FromIterator for String { #[stable(feature = "rust1", since = "1.0.0")] impl Extend for String { - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { let iterator = iterable.into_iter(); let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); @@ -925,14 +930,14 @@ impl Extend for String { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a> Extend<&'a char> for String { - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { self.extend(iterable.into_iter().cloned()); } } #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Extend<&'a str> for String { - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { for s in iterable { self.push_str(s) } @@ -941,7 +946,7 @@ impl<'a> Extend<&'a str> for String { #[stable(feature = "extend_string", since = "1.4.0")] impl Extend for String { - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { for s in iterable { self.push_str(&s) } @@ -973,9 +978,13 @@ impl<'a, 'b> Pattern<'a> for &'b String { #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for String { #[inline] - fn eq(&self, other: &String) -> bool { PartialEq::eq(&self[..], &other[..]) } + fn eq(&self, other: &String) -> bool { + PartialEq::eq(&self[..], &other[..]) + } #[inline] - fn ne(&self, other: &String) -> bool { PartialEq::ne(&self[..], &other[..]) } + fn ne(&self, other: &String) -> bool { + PartialEq::ne(&self[..], &other[..]) + } } macro_rules! impl_eq { diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index a6d0de18eb6ed..8c1f98bbd07c5 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -248,7 +248,10 @@ impl Vec { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn new() -> Vec { - Vec { buf: RawVec::new(), len: 0 } + Vec { + buf: RawVec::new(), + len: 0, + } } /// Constructs a new, empty `Vec` with the specified capacity. @@ -280,7 +283,10 @@ impl Vec { #[inline] #[stable(feature = "rust1", since = "1.0.0")] pub fn with_capacity(capacity: usize) -> Vec { - Vec { buf: RawVec::with_capacity(capacity), len: 0 } + Vec { + buf: RawVec::with_capacity(capacity), + len: 0, + } } /// Creates a `Vec` directly from the raw components of another vector. @@ -329,8 +335,7 @@ impl Vec { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, - capacity: usize) -> Vec { + pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec { Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length, @@ -547,9 +552,12 @@ impl Vec { assert!(index <= len); // space for the new element - if len == self.buf.cap() { self.buf.double(); } + if len == self.buf.cap() { + self.buf.double(); + } - unsafe { // infallible + unsafe { + // infallible // The spot to put the new value { let p = self.as_mut_ptr().offset(index as isize); @@ -582,7 +590,8 @@ impl Vec { pub fn remove(&mut self, index: usize) -> T { let len = self.len(); assert!(index < len); - unsafe { // infallible + unsafe { + // infallible let ret; { // the place we are taking from. @@ -613,7 +622,9 @@ impl Vec { /// assert_eq!(vec, [2, 4]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn retain(&mut self, mut f: F) where F: FnMut(&T) -> bool { + pub fn retain(&mut self, mut f: F) + where F: FnMut(&T) -> bool + { let len = self.len(); let mut del = 0; { @@ -623,7 +634,7 @@ impl Vec { if !f(&v[i]) { del += 1; } else if del > 0 { - v.swap(i-del, i); + v.swap(i - del, i); } } } @@ -650,7 +661,9 @@ impl Vec { pub fn push(&mut self, value: T) { // This will panic or abort if we would allocate > isize::MAX bytes // or if the length increment would overflow for zero-sized types. - if self.len == self.buf.cap() { self.buf.double(); } + if self.len == self.buf.cap() { + self.buf.double(); + } unsafe { let end = self.as_mut_ptr().offset(self.len as isize); ptr::write(end, value); @@ -702,14 +715,13 @@ impl Vec { self.reserve(other.len()); let len = self.len(); unsafe { - ptr::copy_nonoverlapping( - other.as_ptr(), - self.get_unchecked_mut(len), - other.len()); + ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len()); } self.len += other.len(); - unsafe { other.set_len(0); } + unsafe { + other.set_len(0); + } } /// Create a draining iterator that removes the specified range in the vector @@ -738,7 +750,9 @@ impl Vec { #[unstable(feature = "drain", reason = "recently added, matches RFC", issue = "27711")] - pub fn drain(&mut self, range: R) -> Drain where R: RangeArgument { + pub fn drain(&mut self, range: R) -> Drain + where R: RangeArgument + { // Memory safety // // When the Drain is first created, it shortens the length of @@ -760,9 +774,8 @@ impl Vec { self.set_len(start); // Use the borrow in the IterMut to indicate borrowing behavior of the // whole Drain iterator (like &mut T). - let range_slice = slice::from_raw_parts_mut( - self.as_mut_ptr().offset(start as isize), - end - start); + let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize), + end - start); Drain { tail_start: end, tail_len: len - end, @@ -799,7 +812,9 @@ impl Vec { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> usize { self.len } + pub fn len(&self) -> usize { + self.len + } /// Returns `true` if the vector contains no elements. /// @@ -813,7 +828,9 @@ impl Vec { /// assert!(!v.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// Splits the collection into two at the given index. /// @@ -847,14 +864,12 @@ impl Vec { self.set_len(at); other.set_len(other_len); - ptr::copy_nonoverlapping( - self.as_ptr().offset(at as isize), - other.as_mut_ptr(), - other.len()); + ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize), + other.as_mut_ptr(), + other.len()); } other } - } impl Vec { @@ -937,9 +952,7 @@ impl Vec { // similarly fast) when T is Copy. LLVM is easily confused, so any // extra operations during the loop can prevent this optimisation. unsafe { - ptr::write( - self.get_unchecked_mut(len), - other.get_unchecked(i).clone()); + ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone()); self.set_len(len + 1); } } @@ -1021,7 +1034,9 @@ impl Vec { // Duplicate, advance r. End of vec. Truncate to w. let ln = self.len(); - if ln <= 1 { return; } + if ln <= 1 { + return; + } // Avoid bounds checks by using raw pointers. let p = self.as_mut_ptr(); @@ -1063,9 +1078,11 @@ pub fn from_elem(elem: T, n: usize) -> Vec { //////////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] -impl Clone for Vec { +impl Clone for Vec { #[cfg(not(test))] - fn clone(&self) -> Vec { <[T]>::to_vec(&**self) } + fn clone(&self) -> Vec { + <[T]>::to_vec(&**self) + } // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is // required for this method definition, is not available. Instead use the @@ -1158,7 +1175,6 @@ impl ops::Index for Vec { #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for Vec { - #[inline] fn index_mut(&mut self, index: ops::Range) -> &mut [T] { IndexMut::index_mut(&mut **self, index) @@ -1166,7 +1182,6 @@ impl ops::IndexMut> for Vec { } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for Vec { - #[inline] fn index_mut(&mut self, index: ops::RangeTo) -> &mut [T] { IndexMut::index_mut(&mut **self, index) @@ -1174,7 +1189,6 @@ impl ops::IndexMut> for Vec { } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for Vec { - #[inline] fn index_mut(&mut self, index: ops::RangeFrom) -> &mut [T] { IndexMut::index_mut(&mut **self, index) @@ -1182,7 +1196,6 @@ impl ops::IndexMut> for Vec { } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut for Vec { - #[inline] fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] { self @@ -1216,7 +1229,7 @@ impl ops::DerefMut for Vec { #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator for Vec { #[inline] - fn from_iter>(iterable: I) -> Vec { + fn from_iter>(iterable: I) -> Vec { // Unroll the first iteration, as the vector is going to be // expanded on this iteration in every case when the iterable is not // empty, but the loop in extend_desugared() is not going to see the @@ -1271,7 +1284,11 @@ impl IntoIterator for Vec { }; let buf = ptr::read(&self.buf); mem::forget(self); - IntoIter { _buf: buf, ptr: begin, end: end } + IntoIter { + _buf: buf, + ptr: begin, + end: end, + } } } } @@ -1299,13 +1316,13 @@ impl<'a, T> IntoIterator for &'a mut Vec { #[stable(feature = "rust1", since = "1.0.0")] impl Extend for Vec { #[inline] - fn extend>(&mut self, iterable: I) { + fn extend>(&mut self, iterable: I) { self.extend_desugared(iterable.into_iter()) } } impl Vec { - fn extend_desugared>(&mut self, mut iterator: I) { + fn extend_desugared>(&mut self, mut iterator: I) { // This function should be the moral equivalent of: // // for item in iterator { @@ -1328,7 +1345,7 @@ impl Vec { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, T: 'a + Copy> Extend<&'a T> for Vec { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } @@ -1466,7 +1483,7 @@ impl<'a> From<&'a str> for Vec { #[stable(feature = "rust1", since = "1.0.0")] impl<'a, T> FromIterator for Cow<'a, [T]> where T: Clone { - fn from_iter>(it: I) -> Cow<'a, [T]> { + fn from_iter>(it: I) -> Cow<'a, [T]> { Cow::Owned(FromIterator::from_iter(it)) } } @@ -1494,13 +1511,13 @@ impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone { pub struct IntoIter { _buf: RawVec, ptr: *const T, - end: *const T + end: *const T, } #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Send for IntoIter { } +unsafe impl Send for IntoIter {} #[stable(feature = "rust1", since = "1.0.0")] -unsafe impl Sync for IntoIter { } +unsafe impl Sync for IntoIter {} #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for IntoIter { @@ -1534,7 +1551,12 @@ impl Iterator for IntoIter { fn size_hint(&self) -> (usize, Option) { let diff = (self.end as usize) - (self.ptr as usize); let size = mem::size_of::(); - let exact = diff / (if size == 0 {1} else {size}); + let exact = diff / + (if size == 0 { + 1 + } else { + size + }); (exact, Some(exact)) } @@ -1605,11 +1627,7 @@ impl<'a, T> Iterator for Drain<'a, T> { #[inline] fn next(&mut self) -> Option { - self.iter.next().map(|elt| - unsafe { - ptr::read(elt as *const _) - } - ) + self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) }) } fn size_hint(&self) -> (usize, Option) { @@ -1621,11 +1639,7 @@ impl<'a, T> Iterator for Drain<'a, T> { impl<'a, T> DoubleEndedIterator for Drain<'a, T> { #[inline] fn next_back(&mut self) -> Option { - self.iter.next_back().map(|elt| - unsafe { - ptr::read(elt as *const _) - } - ) + self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) }) } } @@ -1633,7 +1647,7 @@ impl<'a, T> DoubleEndedIterator for Drain<'a, T> { impl<'a, T> Drop for Drain<'a, T> { fn drop(&mut self) { // exhaust self first - while let Some(_) = self.next() { } + while let Some(_) = self.next() {} if self.tail_len > 0 { unsafe { diff --git a/src/libcollections/vec_deque.rs b/src/libcollections/vec_deque.rs index 1064fcdd9178b..10b732534c6ba 100644 --- a/src/libcollections/vec_deque.rs +++ b/src/libcollections/vec_deque.rs @@ -52,7 +52,6 @@ pub struct VecDeque { // to where data should be written. // If tail == head the buffer is empty. The length of the ringbuffer // is defined as the distance between the two. - tail: usize, head: usize, buf: RawVec, @@ -77,7 +76,9 @@ impl Drop for VecDeque { #[stable(feature = "rust1", since = "1.0.0")] impl Default for VecDeque { #[inline] - fn default() -> VecDeque { VecDeque::new() } + fn default() -> VecDeque { + VecDeque::new() + } } impl VecDeque { @@ -124,12 +125,16 @@ impl VecDeque { /// Returns true if and only if the buffer is at capacity #[inline] - fn is_full(&self) -> bool { self.cap() - self.len() == 1 } + fn is_full(&self) -> bool { + self.cap() - self.len() == 1 + } /// Returns the index in the underlying buffer for a given logical element /// index. #[inline] - fn wrap_index(&self, idx: usize) -> usize { wrap_index(idx, self.cap()) } + fn wrap_index(&self, idx: usize) -> usize { + wrap_index(idx, self.cap()) + } /// Returns the index in the underlying buffer for a given logical element /// index + addend. @@ -148,27 +153,41 @@ impl VecDeque { /// Copies a contiguous block of memory len long from src to dst #[inline] unsafe fn copy(&self, dst: usize, src: usize, len: usize) { - debug_assert!(dst + len <= self.cap(), "cpy dst={} src={} len={} cap={}", dst, src, len, + debug_assert!(dst + len <= self.cap(), + "cpy dst={} src={} len={} cap={}", + dst, + src, + len, self.cap()); - debug_assert!(src + len <= self.cap(), "cpy dst={} src={} len={} cap={}", dst, src, len, + debug_assert!(src + len <= self.cap(), + "cpy dst={} src={} len={} cap={}", + dst, + src, + len, self.cap()); - ptr::copy( - self.ptr().offset(src as isize), - self.ptr().offset(dst as isize), - len); + ptr::copy(self.ptr().offset(src as isize), + self.ptr().offset(dst as isize), + len); } /// Copies a contiguous block of memory len long from src to dst #[inline] unsafe fn copy_nonoverlapping(&self, dst: usize, src: usize, len: usize) { - debug_assert!(dst + len <= self.cap(), "cno dst={} src={} len={} cap={}", dst, src, len, + debug_assert!(dst + len <= self.cap(), + "cno dst={} src={} len={} cap={}", + dst, + src, + len, self.cap()); - debug_assert!(src + len <= self.cap(), "cno dst={} src={} len={} cap={}", dst, src, len, + debug_assert!(src + len <= self.cap(), + "cno dst={} src={} len={} cap={}", + dst, + src, + len, self.cap()); - ptr::copy_nonoverlapping( - self.ptr().offset(src as isize), - self.ptr().offset(dst as isize), - len); + ptr::copy_nonoverlapping(self.ptr().offset(src as isize), + self.ptr().offset(dst as isize), + len); } /// Copies a potentially wrapping block of memory len long from src to dest. @@ -176,12 +195,23 @@ impl VecDeque { /// most one continuous overlapping region between src and dest). unsafe fn wrap_copy(&self, dst: usize, src: usize, len: usize) { #[allow(dead_code)] - fn diff(a: usize, b: usize) -> usize {if a <= b {b - a} else {a - b}} - debug_assert!(cmp::min(diff(dst, src), - self.cap() - diff(dst, src)) + len <= self.cap(), - "wrc dst={} src={} len={} cap={}", dst, src, len, self.cap()); + fn diff(a: usize, b: usize) -> usize { + if a <= b { + b - a + } else { + a - b + } + } + debug_assert!(cmp::min(diff(dst, src), self.cap() - diff(dst, src)) + len <= self.cap(), + "wrc dst={} src={} len={} cap={}", + dst, + src, + len, + self.cap()); - if src == dst || len == 0 { return } + if src == dst || len == 0 { + return; + } let dst_after_src = self.wrap_sub(dst, src) < len; @@ -304,13 +334,16 @@ impl VecDeque { // H T // C [o o o o o . . . . . . . . . o o ] - if self.tail <= self.head { // A + if self.tail <= self.head { + // A // Nop - } else if self.head < old_cap - self.tail { // B + } else if self.head < old_cap - self.tail { + // B self.copy_nonoverlapping(old_cap, 0, self.head); self.head += old_cap; debug_assert!(self.head > self.tail); - } else { // C + } else { + // C let new_tail = new_cap - (old_cap - self.tail); self.copy_nonoverlapping(new_tail, self.tail, old_cap - self.tail); self.tail = new_tail; @@ -419,7 +452,8 @@ impl VecDeque { let ri = self.wrap_add(self.tail, i); let rj = self.wrap_add(self.tail, j); unsafe { - ptr::swap(self.ptr().offset(ri as isize), self.ptr().offset(rj as isize)) + ptr::swap(self.ptr().offset(ri as isize), + self.ptr().offset(rj as isize)) } } @@ -436,7 +470,9 @@ impl VecDeque { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - pub fn capacity(&self) -> usize { self.cap() - 1 } + pub fn capacity(&self) -> usize { + self.cap() - 1 + } /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the /// given `VecDeque`. Does nothing if the capacity is already sufficient. @@ -483,14 +519,15 @@ impl VecDeque { pub fn reserve(&mut self, additional: usize) { let old_cap = self.cap(); let used_cap = self.len() + 1; - let new_cap = used_cap - .checked_add(additional) - .and_then(|needed_cap| needed_cap.checked_next_power_of_two()) - .expect("capacity overflow"); + let new_cap = used_cap.checked_add(additional) + .and_then(|needed_cap| needed_cap.checked_next_power_of_two()) + .expect("capacity overflow"); if new_cap > self.capacity() { self.buf.reserve_exact(used_cap, new_cap - used_cap); - unsafe { self.handle_cap_increase(old_cap); } + unsafe { + self.handle_cap_increase(old_cap); + } } } @@ -619,7 +656,7 @@ impl VecDeque { Iter { tail: self.tail, head: self.head, - ring: unsafe { self.buffer_as_slice() } + ring: unsafe { self.buffer_as_slice() }, } } @@ -681,7 +718,7 @@ impl VecDeque { if contiguous { let (empty, buf) = buf.split_at_mut(0); - (&mut buf[tail .. head], empty) + (&mut buf[tail..head], empty) } else { let (mid, right) = buf.split_at_mut(tail); let (left, _) = mid.split_at_mut(head); @@ -704,7 +741,9 @@ impl VecDeque { /// assert_eq!(v.len(), 1); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn len(&self) -> usize { count(self.tail, self.head, self.cap()) } + pub fn len(&self) -> usize { + count(self.tail, self.head, self.cap()) + } /// Returns true if the buffer contains no elements /// @@ -719,7 +758,9 @@ impl VecDeque { /// assert!(!v.is_empty()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - pub fn is_empty(&self) -> bool { self.len() == 0 } + pub fn is_empty(&self) -> bool { + self.len() == 0 + } /// Create a draining iterator that removes the specified range in the /// `VecDeque` and yields the removed items from start to end. The element @@ -751,7 +792,9 @@ impl VecDeque { #[unstable(feature = "drain", reason = "matches collection reform specification, waiting for dust to settle", issue = "27711")] - pub fn drain(&mut self, range: R) -> Drain where R: RangeArgument { + pub fn drain(&mut self, range: R) -> Drain + where R: RangeArgument + { // Memory safety // // When the Drain is first created, the source deque is shortened to @@ -839,7 +882,11 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn front(&self) -> Option<&T> { - if !self.is_empty() { Some(&self[0]) } else { None } + if !self.is_empty() { + Some(&self[0]) + } else { + None + } } /// Provides a mutable reference to the front element, or `None` if the @@ -863,7 +910,11 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn front_mut(&mut self) -> Option<&mut T> { - if !self.is_empty() { Some(&mut self[0]) } else { None } + if !self.is_empty() { + Some(&mut self[0]) + } else { + None + } } /// Provides a reference to the back element, or `None` if the sequence is @@ -883,7 +934,11 @@ impl VecDeque { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn back(&self) -> Option<&T> { - if !self.is_empty() { Some(&self[self.len() - 1]) } else { None } + if !self.is_empty() { + Some(&self[self.len() - 1]) + } else { + None + } } /// Provides a mutable reference to the back element, or `None` if the @@ -908,7 +963,11 @@ impl VecDeque { #[stable(feature = "rust1", since = "1.0.0")] pub fn back_mut(&mut self) -> Option<&mut T> { let len = self.len(); - if !self.is_empty() { Some(&mut self[len - 1]) } else { None } + if !self.is_empty() { + Some(&mut self[len - 1]) + } else { + None + } } /// Removes the first element and returns it, or `None` if the sequence is @@ -955,13 +1014,17 @@ impl VecDeque { if self.is_full() { let old_cap = self.cap(); self.buf.double(); - unsafe { self.handle_cap_increase(old_cap); } + unsafe { + self.handle_cap_increase(old_cap); + } debug_assert!(!self.is_full()); } self.tail = self.wrap_sub(self.tail, 1); let tail = self.tail; - unsafe { self.buffer_write(tail, value); } + unsafe { + self.buffer_write(tail, value); + } } /// Appends an element to the back of a buffer @@ -981,7 +1044,9 @@ impl VecDeque { if self.is_full() { let old_cap = self.cap(); self.buf.double(); - unsafe { self.handle_cap_increase(old_cap); } + unsafe { + self.handle_cap_increase(old_cap); + } debug_assert!(!self.is_full()); } @@ -1130,7 +1195,9 @@ impl VecDeque { if self.is_full() { let old_cap = self.cap(); self.buf.double(); - unsafe { self.handle_cap_increase(old_cap); } + unsafe { + self.handle_cap_increase(old_cap); + } debug_assert!(!self.is_full()); } @@ -1163,7 +1230,9 @@ impl VecDeque { let contiguous = self.is_contiguous(); - match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) { + match (contiguous, + distance_to_tail <= distance_to_head, + idx >= self.tail) { (true, true, _) if index == 0 => { // push_front // @@ -1176,134 +1245,148 @@ impl VecDeque { // self.tail = self.wrap_sub(self.tail, 1); - }, - (true, true, _) => unsafe { - // contiguous, insert closer to tail: - // - // T I H - // [. . . o o A o o o o . . . . . .] - // - // T H - // [. . o o I A o o o o . . . . . .] - // M M - // - // contiguous, insert closer to tail and tail is 0: - // - // - // T I H - // [o o A o o o o . . . . . . . . .] - // - // H T - // [o I A o o o o o . . . . . . . o] - // M M - - let new_tail = self.wrap_sub(self.tail, 1); - - self.copy(new_tail, self.tail, 1); - // Already moved the tail, so we only copy `index - 1` elements. - self.copy(self.tail, self.tail + 1, index - 1); - - self.tail = new_tail; - }, - (true, false, _) => unsafe { - // contiguous, insert closer to head: - // - // T I H - // [. . . o o o o A o o . . . . . .] - // - // T H - // [. . . o o o o I A o o . . . . .] - // M M M - - self.copy(idx + 1, idx, self.head - idx); - self.head = self.wrap_add(self.head, 1); - }, - (false, true, true) => unsafe { - // discontiguous, insert closer to tail, tail section: - // - // H T I - // [o o o o o o . . . . . o o A o o] - // - // H T - // [o o o o o o . . . . o o I A o o] - // M M - - self.copy(self.tail - 1, self.tail, index); - self.tail -= 1; - }, - (false, false, true) => unsafe { - // discontiguous, insert closer to head, tail section: - // - // H T I - // [o o . . . . . . . o o o o o A o] - // - // H T - // [o o o . . . . . . o o o o o I A] - // M M M M - - // copy elements up to new head - self.copy(1, 0, self.head); - - // copy last element into empty spot at bottom of buffer - self.copy(0, self.cap() - 1, 1); - - // move elements from idx to end forward not including ^ element - self.copy(idx + 1, idx, self.cap() - 1 - idx); + } + (true, true, _) => { + unsafe { + // contiguous, insert closer to tail: + // + // T I H + // [. . . o o A o o o o . . . . . .] + // + // T H + // [. . o o I A o o o o . . . . . .] + // M M + // + // contiguous, insert closer to tail and tail is 0: + // + // + // T I H + // [o o A o o o o . . . . . . . . .] + // + // H T + // [o I A o o o o o . . . . . . . o] + // M M + + let new_tail = self.wrap_sub(self.tail, 1); + + self.copy(new_tail, self.tail, 1); + // Already moved the tail, so we only copy `index - 1` elements. + self.copy(self.tail, self.tail + 1, index - 1); + + self.tail = new_tail; + } + } + (true, false, _) => { + unsafe { + // contiguous, insert closer to head: + // + // T I H + // [. . . o o o o A o o . . . . . .] + // + // T H + // [. . . o o o o I A o o . . . . .] + // M M M + + self.copy(idx + 1, idx, self.head - idx); + self.head = self.wrap_add(self.head, 1); + } + } + (false, true, true) => { + unsafe { + // discontiguous, insert closer to tail, tail section: + // + // H T I + // [o o o o o o . . . . . o o A o o] + // + // H T + // [o o o o o o . . . . o o I A o o] + // M M + + self.copy(self.tail - 1, self.tail, index); + self.tail -= 1; + } + } + (false, false, true) => { + unsafe { + // discontiguous, insert closer to head, tail section: + // + // H T I + // [o o . . . . . . . o o o o o A o] + // + // H T + // [o o o . . . . . . o o o o o I A] + // M M M M - self.head += 1; - }, - (false, true, false) if idx == 0 => unsafe { - // discontiguous, insert is closer to tail, head section, - // and is at index zero in the internal buffer: - // - // I H T - // [A o o o o o o o o o . . . o o o] - // - // H T - // [A o o o o o o o o o . . o o o I] - // M M M + // copy elements up to new head + self.copy(1, 0, self.head); - // copy elements up to new tail - self.copy(self.tail - 1, self.tail, self.cap() - self.tail); + // copy last element into empty spot at bottom of buffer + self.copy(0, self.cap() - 1, 1); - // copy last element into empty spot at bottom of buffer - self.copy(self.cap() - 1, 0, 1); + // move elements from idx to end forward not including ^ element + self.copy(idx + 1, idx, self.cap() - 1 - idx); - self.tail -= 1; - }, - (false, true, false) => unsafe { - // discontiguous, insert closer to tail, head section: - // - // I H T - // [o o o A o o o o o o . . . o o o] - // - // H T - // [o o I A o o o o o o . . o o o o] - // M M M M M M - - // copy elements up to new tail - self.copy(self.tail - 1, self.tail, self.cap() - self.tail); - - // copy last element into empty spot at bottom of buffer - self.copy(self.cap() - 1, 0, 1); + self.head += 1; + } + } + (false, true, false) if idx == 0 => { + unsafe { + // discontiguous, insert is closer to tail, head section, + // and is at index zero in the internal buffer: + // + // I H T + // [A o o o o o o o o o . . . o o o] + // + // H T + // [A o o o o o o o o o . . o o o I] + // M M M + + // copy elements up to new tail + self.copy(self.tail - 1, self.tail, self.cap() - self.tail); + + // copy last element into empty spot at bottom of buffer + self.copy(self.cap() - 1, 0, 1); - // move elements from idx-1 to end forward not including ^ element - self.copy(0, 1, idx - 1); + self.tail -= 1; + } + } + (false, true, false) => { + unsafe { + // discontiguous, insert closer to tail, head section: + // + // I H T + // [o o o A o o o o o o . . . o o o] + // + // H T + // [o o I A o o o o o o . . o o o o] + // M M M M M M + + // copy elements up to new tail + self.copy(self.tail - 1, self.tail, self.cap() - self.tail); + + // copy last element into empty spot at bottom of buffer + self.copy(self.cap() - 1, 0, 1); - self.tail -= 1; - }, - (false, false, false) => unsafe { - // discontiguous, insert closer to head, head section: - // - // I H T - // [o o o o A o o . . . . . . o o o] - // - // H T - // [o o o o I A o o . . . . . o o o] - // M M M + // move elements from idx-1 to end forward not including ^ element + self.copy(0, 1, idx - 1); - self.copy(idx + 1, idx, self.head - idx); - self.head += 1; + self.tail -= 1; + } + } + (false, false, false) => { + unsafe { + // discontiguous, insert closer to head, head section: + // + // I H T + // [o o o o A o o . . . . . . o o o] + // + // H T + // [o o o o I A o o . . . . . o o o] + // M M M + + self.copy(idx + 1, idx, self.head - idx); + self.head += 1; + } } } @@ -1357,121 +1440,133 @@ impl VecDeque { let idx = self.wrap_add(self.tail, index); - let elem = unsafe { - Some(self.buffer_read(idx)) - }; + let elem = unsafe { Some(self.buffer_read(idx)) }; let distance_to_tail = index; let distance_to_head = self.len() - index; let contiguous = self.is_contiguous(); - match (contiguous, distance_to_tail <= distance_to_head, idx >= self.tail) { - (true, true, _) => unsafe { - // contiguous, remove closer to tail: - // - // T R H - // [. . . o o x o o o o . . . . . .] - // - // T H - // [. . . . o o o o o o . . . . . .] - // M M - - self.copy(self.tail + 1, self.tail, index); - self.tail += 1; - }, - (true, false, _) => unsafe { - // contiguous, remove closer to head: - // - // T R H - // [. . . o o o o x o o . . . . . .] - // - // T H - // [. . . o o o o o o . . . . . . .] - // M M - - self.copy(idx, idx + 1, self.head - idx - 1); - self.head -= 1; - }, - (false, true, true) => unsafe { - // discontiguous, remove closer to tail, tail section: - // - // H T R - // [o o o o o o . . . . . o o x o o] - // - // H T - // [o o o o o o . . . . . . o o o o] - // M M - - self.copy(self.tail + 1, self.tail, index); - self.tail = self.wrap_add(self.tail, 1); - }, - (false, false, false) => unsafe { - // discontiguous, remove closer to head, head section: - // - // R H T - // [o o o o x o o . . . . . . o o o] - // - // H T - // [o o o o o o . . . . . . . o o o] - // M M - - self.copy(idx, idx + 1, self.head - idx - 1); - self.head -= 1; - }, - (false, false, true) => unsafe { - // discontiguous, remove closer to head, tail section: - // - // H T R - // [o o o . . . . . . o o o o o x o] - // - // H T - // [o o . . . . . . . o o o o o o o] - // M M M M - // - // or quasi-discontiguous, remove next to head, tail section: - // - // H T R - // [. . . . . . . . . o o o o o x o] - // - // T H - // [. . . . . . . . . o o o o o o .] - // M - - // draw in elements in the tail section - self.copy(idx, idx + 1, self.cap() - idx - 1); - - // Prevents underflow. - if self.head != 0 { - // copy first element into empty spot - self.copy(self.cap() - 1, 0, 1); - - // move elements in the head section backwards - self.copy(0, 1, self.head - 1); + match (contiguous, + distance_to_tail <= distance_to_head, + idx >= self.tail) { + (true, true, _) => { + unsafe { + // contiguous, remove closer to tail: + // + // T R H + // [. . . o o x o o o o . . . . . .] + // + // T H + // [. . . . o o o o o o . . . . . .] + // M M + + self.copy(self.tail + 1, self.tail, index); + self.tail += 1; + } + } + (true, false, _) => { + unsafe { + // contiguous, remove closer to head: + // + // T R H + // [. . . o o o o x o o . . . . . .] + // + // T H + // [. . . o o o o o o . . . . . . .] + // M M + + self.copy(idx, idx + 1, self.head - idx - 1); + self.head -= 1; + } + } + (false, true, true) => { + unsafe { + // discontiguous, remove closer to tail, tail section: + // + // H T R + // [o o o o o o . . . . . o o x o o] + // + // H T + // [o o o o o o . . . . . . o o o o] + // M M + + self.copy(self.tail + 1, self.tail, index); + self.tail = self.wrap_add(self.tail, 1); + } + } + (false, false, false) => { + unsafe { + // discontiguous, remove closer to head, head section: + // + // R H T + // [o o o o x o o . . . . . . o o o] + // + // H T + // [o o o o o o . . . . . . . o o o] + // M M + + self.copy(idx, idx + 1, self.head - idx - 1); + self.head -= 1; } + } + (false, false, true) => { + unsafe { + // discontiguous, remove closer to head, tail section: + // + // H T R + // [o o o . . . . . . o o o o o x o] + // + // H T + // [o o . . . . . . . o o o o o o o] + // M M M M + // + // or quasi-discontiguous, remove next to head, tail section: + // + // H T R + // [. . . . . . . . . o o o o o x o] + // + // T H + // [. . . . . . . . . o o o o o o .] + // M + + // draw in elements in the tail section + self.copy(idx, idx + 1, self.cap() - idx - 1); + + // Prevents underflow. + if self.head != 0 { + // copy first element into empty spot + self.copy(self.cap() - 1, 0, 1); + + // move elements in the head section backwards + self.copy(0, 1, self.head - 1); + } - self.head = self.wrap_sub(self.head, 1); - }, - (false, true, false) => unsafe { - // discontiguous, remove closer to tail, head section: - // - // R H T - // [o o x o o o o o o o . . . o o o] - // - // H T - // [o o o o o o o o o o . . . . o o] - // M M M M M + self.head = self.wrap_sub(self.head, 1); + } + } + (false, true, false) => { + unsafe { + // discontiguous, remove closer to tail, head section: + // + // R H T + // [o o x o o o o o o o . . . o o o] + // + // H T + // [o o o o o o o o o o . . . . o o] + // M M M M M - // draw in elements up to idx - self.copy(1, 0, idx); + // draw in elements up to idx + self.copy(1, 0, idx); - // copy last element into empty spot - self.copy(0, self.cap() - 1, 1); + // copy last element into empty spot + self.copy(0, self.cap() - 1, 1); - // move elements from tail to end forward, excluding the last one - self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1); + // move elements from tail to end forward, excluding the last one + self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1); - self.tail = self.wrap_add(self.tail, 1); + self.tail = self.wrap_add(self.tail, 1); + } } } @@ -1587,14 +1682,16 @@ impl VecDeque { /// assert_eq!(&v[..], &[2, 4]); /// ``` #[stable(feature = "vec_deque_retain", since = "1.4.0")] - pub fn retain(&mut self, mut f: F) where F: FnMut(&T) -> bool { + pub fn retain(&mut self, mut f: F) + where F: FnMut(&T) -> bool + { let len = self.len(); let mut del = 0; for i in 0..len { if !f(&self[i]) { del += 1; } else if del > 0 { - self.swap(i-del, i); + self.swap(i - del, i); } } if del > 0 { @@ -1655,10 +1752,10 @@ fn count(tail: usize, head: usize, size: usize) -> usize { /// `VecDeque` iterator. #[stable(feature = "rust1", since = "1.0.0")] -pub struct Iter<'a, T:'a> { +pub struct Iter<'a, T: 'a> { ring: &'a [T], tail: usize, - head: usize + head: usize, } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` @@ -1668,7 +1765,7 @@ impl<'a, T> Clone for Iter<'a, T> { Iter { ring: self.ring, tail: self.tail, - head: self.head + head: self.head, } } } @@ -1711,7 +1808,7 @@ impl<'a, T> ExactSizeIterator for Iter<'a, T> {} /// `VecDeque` mutable iterator. #[stable(feature = "rust1", since = "1.0.0")] -pub struct IterMut<'a, T:'a> { +pub struct IterMut<'a, T: 'a> { ring: &'a mut [T], tail: usize, head: usize, @@ -1845,13 +1942,15 @@ impl<'a, T: 'a> Drop for Drain<'a, T> { (_, 0) => { source_deque.head = drain_tail; } - _ => unsafe { - if tail_len <= head_len { - source_deque.tail = source_deque.wrap_sub(drain_head, tail_len); - source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len); - } else { - source_deque.head = source_deque.wrap_add(drain_tail, head_len); - source_deque.wrap_copy(drain_tail, drain_head, head_len); + _ => { + unsafe { + if tail_len <= head_len { + source_deque.tail = source_deque.wrap_sub(drain_head, tail_len); + source_deque.wrap_copy(source_deque.tail, orig_tail, tail_len); + } else { + source_deque.head = source_deque.wrap_add(drain_tail, head_len); + source_deque.wrap_copy(drain_tail, drain_head, head_len); + } } } } @@ -1864,11 +1963,7 @@ impl<'a, T: 'a> Iterator for Drain<'a, T> { #[inline] fn next(&mut self) -> Option { - self.iter.next().map(|elt| - unsafe { - ptr::read(elt) - } - ) + self.iter.next().map(|elt| unsafe { ptr::read(elt) }) } #[inline] @@ -1881,11 +1976,7 @@ impl<'a, T: 'a> Iterator for Drain<'a, T> { impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { #[inline] fn next_back(&mut self) -> Option { - self.iter.next_back().map(|elt| - unsafe { - ptr::read(elt) - } - ) + self.iter.next_back().map(|elt| unsafe { ptr::read(elt) }) } } @@ -1895,8 +1986,7 @@ impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {} #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for VecDeque { fn eq(&self, other: &VecDeque) -> bool { - self.len() == other.len() && - self.iter().zip(other).all(|(a, b)| a.eq(b)) + self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a.eq(b)) } } @@ -1948,7 +2038,7 @@ impl IndexMut for VecDeque { #[stable(feature = "rust1", since = "1.0.0")] impl FromIterator for VecDeque { - fn from_iter>(iterable: T) -> VecDeque { + fn from_iter>(iterable: T) -> VecDeque { let iterator = iterable.into_iter(); let (lower, _) = iterator.size_hint(); let mut deq = VecDeque::with_capacity(lower); @@ -1965,9 +2055,7 @@ impl IntoIterator for VecDeque { /// Consumes the list into a front-to-back iterator yielding elements by /// value. fn into_iter(self) -> IntoIter { - IntoIter { - inner: self, - } + IntoIter { inner: self } } } @@ -1993,7 +2081,7 @@ impl<'a, T> IntoIterator for &'a mut VecDeque { #[stable(feature = "rust1", since = "1.0.0")] impl Extend for VecDeque { - fn extend>(&mut self, iter: T) { + fn extend>(&mut self, iter: T) { for elt in iter { self.push_back(elt); } @@ -2002,7 +2090,7 @@ impl Extend for VecDeque { #[stable(feature = "extend_ref", since = "1.2.0")] impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque { - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { self.extend(iter.into_iter().cloned()); } } @@ -2049,7 +2137,7 @@ mod tests { #[bench] fn bench_pop_back_100(b: &mut test::Bencher) { - let mut deq= VecDeque::::with_capacity(101); + let mut deq = VecDeque::::with_capacity(101); b.iter(|| { deq.head = 100; @@ -2204,10 +2292,8 @@ mod tests { } // Check that we drain the correct values - let drained: VecDeque<_> = - tester.drain(drain_start..drain_end).collect(); - let drained_expected: VecDeque<_> = - (drain_start..drain_end).collect(); + let drained: VecDeque<_> = tester.drain(drain_start..drain_end).collect(); + let drained_expected: VecDeque<_> = (drain_start..drain_end).collect(); assert_eq!(drained, drained_expected); // We shouldn't have changed the capacity or made the @@ -2217,8 +2303,9 @@ mod tests { assert!(tester.head < tester.cap()); // We should see the correct values in the VecDeque - let expected: VecDeque<_> = - (0..drain_start).chain(drain_end..len).collect(); + let expected: VecDeque<_> = (0..drain_start) + .chain(drain_end..len) + .collect(); assert_eq!(expected, tester); } } From 5fb6531903c4e425f48a859463bee20cfcc7f7c5 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 24 Nov 2015 12:11:20 +1300 Subject: [PATCH 3/3] rustfmt: libflate, libfmt_macros, libgetopts, libgraphviz, liblog, librand --- src/libflate/lib.rs | 2 +- src/libfmt_macros/lib.rs | 14 +- src/libgetopts/lib.rs | 875 +++++++++++++++-------------- src/libgraphviz/lib.rs | 46 +- src/liblog/directive.rs | 6 +- src/liblog/lib.rs | 8 +- src/librand/chacha.rs | 6 +- src/librand/distributions/gamma.rs | 5 +- src/librand/distributions/mod.rs | 7 +- src/librand/isaac.rs | 3 +- src/librand/lib.rs | 7 +- src/librand/rand_impls.rs | 2 +- 12 files changed, 503 insertions(+), 478 deletions(-) diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index 513379b655844..c5f0800e71fbb 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -82,7 +82,7 @@ impl Drop for Bytes { } #[link(name = "miniz", kind = "static")] -extern { +extern "C" { /// Raw miniz compression function. fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void, src_buf_len: size_t, diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index dc69f38e4e7d0..2cd046dc38ab1 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -187,7 +187,7 @@ impl<'a> Parser<'a> { Parser { input: s, cur: s.char_indices().peekable(), - errors: vec!(), + errors: vec![], } } @@ -236,7 +236,7 @@ impl<'a> Parser<'a> { if c.is_whitespace() { self.cur.next(); } else { - break + break; } } } @@ -274,9 +274,7 @@ impl<'a> Parser<'a> { ArgumentIs(i) } else { match self.cur.peek() { - Some(&(_, c)) if c.is_alphabetic() => { - ArgumentNamed(self.word()) - } + Some(&(_, c)) if c.is_alphabetic() => ArgumentNamed(self.word()), _ => ArgumentNext, } } @@ -294,7 +292,7 @@ impl<'a> Parser<'a> { ty: &self.input[..0], }; if !self.consume(':') { - return spec + return spec; } // fill character @@ -419,7 +417,7 @@ impl<'a> Parser<'a> { found = true; self.cur.next(); } else { - break + break; } } if found { @@ -447,7 +445,7 @@ mod tests { precision: CountImplied, width: CountImplied, ty: "", - } + }; } fn musterr(s: &str) { diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index f49451f827d62..c744121f84369 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -98,7 +98,9 @@ #![feature(str_char)] #![cfg_attr(test, feature(rustc_private))] -#[cfg(test)] #[macro_use] extern crate log; +#[cfg(test)] +#[macro_use] +extern crate log; use self::Name::*; use self::HasArg::*; @@ -174,7 +176,7 @@ pub struct OptGroup { /// Whether option has an argument pub hasarg: HasArg, /// How often it can occur - pub occur: Occur + pub occur: Occur, } /// Describes whether an option is given at all or has a value. @@ -239,7 +241,7 @@ impl Name { fn to_string(&self) -> String { match *self { Short(ch) => ch.to_string(), - Long(ref s) => s.to_owned() + Long(ref s) => s.to_owned(), } } } @@ -257,33 +259,37 @@ impl OptGroup { } = (*self).clone(); match (short_name.len(), long_name.len()) { - (0,0) => panic!("this long-format option was given no name"), - (0,_) => Opt { - name: Long((long_name)), - hasarg: hasarg, - occur: occur, - aliases: Vec::new() - }, - (1,0) => Opt { - name: Short(short_name.char_at(0)), - hasarg: hasarg, - occur: occur, - aliases: Vec::new() - }, - (1,_) => Opt { - name: Long((long_name)), - hasarg: hasarg, - occur: occur, - aliases: vec!( - Opt { - name: Short(short_name.char_at(0)), - hasarg: hasarg, - occur: occur, - aliases: Vec::new() - } - ) - }, - (_,_) => panic!("something is wrong with the long-form opt") + (0, 0) => panic!("this long-format option was given no name"), + (0, _) => { + Opt { + name: Long((long_name)), + hasarg: hasarg, + occur: occur, + aliases: Vec::new(), + } + } + (1, 0) => { + Opt { + name: Short(short_name.char_at(0)), + hasarg: hasarg, + occur: occur, + aliases: Vec::new(), + } + } + (1, _) => { + Opt { + name: Long((long_name)), + hasarg: hasarg, + occur: occur, + aliases: vec![Opt { + name: Short(short_name.char_at(0)), + hasarg: hasarg, + occur: occur, + aliases: Vec::new(), + }], + } + } + (_, _) => panic!("something is wrong with the long-form opt"), } } } @@ -292,7 +298,7 @@ impl Matches { fn opt_vals(&self, nm: &str) -> Vec { match find_opt(&self.opts[..], Name::from_str(nm)) { Some(id) => self.vals[id].clone(), - None => panic!("No option '{}' defined", nm) + None => panic!("No option '{}' defined", nm), } } @@ -331,7 +337,7 @@ impl Matches { for nm in names { match self.opt_val(&nm[..]) { Some(Val(ref s)) => return Some(s.clone()), - _ => () + _ => (), } } None @@ -347,7 +353,7 @@ impl Matches { for v in &r { match *v { Val(ref s) => acc.push((*s).clone()), - _ => () + _ => (), } } acc @@ -361,7 +367,7 @@ impl Matches { } match vals[0] { Val(ref s) => Some((*s).clone()), - _ => None + _ => None, } } @@ -378,11 +384,10 @@ impl Matches { } else { match vals[0] { Val(ref s) => Some((*s).clone()), - _ => Some(def.to_owned()) + _ => Some(def.to_owned()), } } } - } fn is_arg(arg: &str) -> bool { @@ -393,7 +398,7 @@ fn find_opt(opts: &[Opt], nm: Name) -> Option { // Search main options. let pos = opts.iter().position(|opt| opt.name == nm); if pos.is_some() { - return pos + return pos; } // Search in aliases. @@ -422,7 +427,7 @@ pub fn reqopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptG hint: hint.to_owned(), desc: desc.to_owned(), hasarg: Yes, - occur: Req + occur: Req, } } @@ -442,7 +447,7 @@ pub fn optopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> OptG hint: hint.to_owned(), desc: desc.to_owned(), hasarg: Yes, - occur: Optional + occur: Optional, } } @@ -460,7 +465,7 @@ pub fn optflag(short_name: &str, long_name: &str, desc: &str) -> OptGroup { hint: "".to_owned(), desc: desc.to_owned(), hasarg: No, - occur: Optional + occur: Optional, } } @@ -479,7 +484,7 @@ pub fn optflagmulti(short_name: &str, long_name: &str, desc: &str) -> OptGroup { hint: "".to_owned(), desc: desc.to_owned(), hasarg: No, - occur: Multi + occur: Multi, } } @@ -499,7 +504,7 @@ pub fn optflagopt(short_name: &str, long_name: &str, desc: &str, hint: &str) -> hint: hint.to_owned(), desc: desc.to_owned(), hasarg: Maybe, - occur: Optional + occur: Optional, } } @@ -520,7 +525,7 @@ pub fn optmulti(short_name: &str, long_name: &str, desc: &str, hint: &str) -> Op hint: hint.to_owned(), desc: desc.to_owned(), hasarg: Yes, - occur: Multi + occur: Multi, } } @@ -530,7 +535,8 @@ pub fn opt(short_name: &str, desc: &str, hint: &str, hasarg: HasArg, - occur: Occur) -> OptGroup { + occur: Occur) + -> OptGroup { let len = short_name.len(); assert!(len == 1 || len == 0); OptGroup { @@ -539,28 +545,18 @@ pub fn opt(short_name: &str, hint: hint.to_owned(), desc: desc.to_owned(), hasarg: hasarg, - occur: occur + occur: occur, } } impl fmt::Display for Fail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ArgumentMissing(ref nm) => { - write!(f, "Argument to option '{}' missing.", *nm) - } - UnrecognizedOption(ref nm) => { - write!(f, "Unrecognized option: '{}'.", *nm) - } - OptionMissing(ref nm) => { - write!(f, "Required option '{}' missing.", *nm) - } - OptionDuplicated(ref nm) => { - write!(f, "Option '{}' given more than once.", *nm) - } - UnexpectedArgument(ref nm) => { - write!(f, "Option '{}' does not take an argument.", *nm) - } + ArgumentMissing(ref nm) => write!(f, "Argument to option '{}' missing.", *nm), + UnrecognizedOption(ref nm) => write!(f, "Unrecognized option: '{}'.", *nm), + OptionMissing(ref nm) => write!(f, "Required option '{}' missing.", *nm), + OptionDuplicated(ref nm) => write!(f, "Option '{}' given more than once.", *nm), + UnexpectedArgument(ref nm) => write!(f, "Option '{}' does not take an argument.", *nm), } } } @@ -577,7 +573,9 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { let opts: Vec = optgrps.iter().map(|x| x.long_to_short()).collect(); let n_opts = opts.len(); - fn f(_x: usize) -> Vec { Vec::new() } + fn f(_x: usize) -> Vec { + Vec::new() + } let mut vals: Vec<_> = (0..n_opts).map(f).collect(); let mut free: Vec = Vec::new(); @@ -590,7 +588,10 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { free.push(cur); } else if cur == "--" { let mut j = i + 1; - while j < l { free.push(args[j].clone()); j += 1; } + while j < l { + free.push(args[j].clone()); + j += 1; + } break; } else { let mut names; @@ -599,10 +600,9 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { let tail = &cur[2..curlen]; let tail_eq: Vec<&str> = tail.split('=').collect(); if tail_eq.len() <= 1 { - names = vec!(Long(tail.to_owned())); + names = vec![Long(tail.to_owned())]; } else { - names = - vec!(Long(tail_eq[0].to_owned())); + names = vec![Long(tail_eq[0].to_owned())]; i_arg = Some(tail_eq[1].to_owned()); } } else { @@ -612,23 +612,22 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { let ch = cur.char_at(j); let opt = Short(ch); - /* In a series of potential options (eg. -aheJ), if we - see one which takes an argument, we assume all - subsequent characters make up the argument. This - allows options such as -L/usr/local/lib/foo to be - interpreted correctly - */ + // In a series of potential options (eg. -aheJ), if we + // see one which takes an argument, we assume all + // subsequent characters make up the argument. This + // allows options such as -L/usr/local/lib/foo to be + // interpreted correctly let opt_id = match find_opt(&opts, opt.clone()) { - Some(id) => id, - None => return Err(UnrecognizedOption(opt.to_string())) + Some(id) => id, + None => return Err(UnrecognizedOption(opt.to_string())), }; names.push(opt); let arg_follows = match opts[opt_id].hasarg { Yes | Maybe => true, - No => false + No => false, }; let next = j + ch.len_utf8(); @@ -644,44 +643,42 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { for nm in &names { name_pos += 1; let optid = match find_opt(&opts, (*nm).clone()) { - Some(id) => id, - None => return Err(UnrecognizedOption(nm.to_string())) + Some(id) => id, + None => return Err(UnrecognizedOption(nm.to_string())), }; match opts[optid].hasarg { - No => { - if name_pos == names.len() && !i_arg.is_none() { - return Err(UnexpectedArgument(nm.to_string())); - } - let v = &mut vals[optid]; - v.push(Given); - } - Maybe => { - if !i_arg.is_none() { - let v = &mut vals[optid]; - v.push(Val((i_arg.clone()) - .unwrap())); - } else if name_pos < names.len() || i + 1 == l || - is_arg(&args[i + 1][..]) { + No => { + if name_pos == names.len() && !i_arg.is_none() { + return Err(UnexpectedArgument(nm.to_string())); + } let v = &mut vals[optid]; v.push(Given); - } else { - i += 1; - let v = &mut vals[optid]; - v.push(Val(args[i].clone())); } - } - Yes => { - if !i_arg.is_none() { - let v = &mut vals[optid]; - v.push(Val(i_arg.clone().unwrap())); - } else if i + 1 == l { - return Err(ArgumentMissing(nm.to_string())); - } else { - i += 1; - let v = &mut vals[optid]; - v.push(Val(args[i].clone())); + Maybe => { + if !i_arg.is_none() { + let v = &mut vals[optid]; + v.push(Val((i_arg.clone()).unwrap())); + } else if name_pos < names.len() || i + 1 == l || is_arg(&args[i + 1][..]) { + let v = &mut vals[optid]; + v.push(Given); + } else { + i += 1; + let v = &mut vals[optid]; + v.push(Val(args[i].clone())); + } + } + Yes => { + if !i_arg.is_none() { + let v = &mut vals[optid]; + v.push(Val(i_arg.clone().unwrap())); + } else if i + 1 == l { + return Err(ArgumentMissing(nm.to_string())); + } else { + i += 1; + let v = &mut vals[optid]; + v.push(Val(args[i].clone())); + } } - } } } } @@ -700,7 +697,7 @@ pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { Ok(Matches { opts: opts, vals: vals, - free: free + free: free, }) } @@ -783,7 +780,8 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> String { row }); - format!("{}\n\nOptions:\n{}\n", brief, + format!("{}\n\nOptions:\n{}\n", + brief, rows.collect::>().join("\n")) } @@ -836,19 +834,19 @@ pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> String { #[derive(Copy, Clone)] enum SplitWithinState { - A, // leading whitespace, initial state - B, // words - C, // internal and trailing whitespace + A, // leading whitespace, initial state + B, // words + C, // internal and trailing whitespace } #[derive(Copy, Clone)] enum Whitespace { Ws, // current char is whitespace - Cr // current char is not whitespace + Cr, // current char is not whitespace } #[derive(Copy, Clone)] enum LengthLimit { UnderLim, // current char makes current substring still fit in limit - OverLim // current char makes current substring no longer fit in limit + OverLim, // current char makes current substring no longer fit in limit } @@ -863,8 +861,8 @@ enum LengthLimit { /// /// Panics during iteration if the string contains a non-whitespace /// sequence longer than the limit. -fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool where - F: FnMut(&str) -> bool +fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool + where F: FnMut(&str) -> bool { // Just for fun, let's write this as a state machine: @@ -883,18 +881,31 @@ fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool where } let mut machine = |cont: &mut bool, (i, c): (usize, char)| -> bool { - let whitespace = if c.is_whitespace() { Ws } else { Cr }; - let limit = if (i - slice_start + 1) <= lim { UnderLim } else { OverLim }; + let whitespace = if c.is_whitespace() { + Ws + } else { + Cr + }; + let limit = if (i - slice_start + 1) <= lim { + UnderLim + } else { + OverLim + }; state = match (state, whitespace, limit) { - (A, Ws, _) => { A } - (A, Cr, _) => { slice_start = i; last_start = i; B } - - (B, Cr, UnderLim) => { B } - (B, Cr, OverLim) if (i - last_start + 1) > lim - => panic!("word starting with {} longer than limit!", - &ss[last_start..i + 1]), - (B, Cr, OverLim) => { + (A, Ws, _) => A, + (A, Cr, _) => { + slice_start = i; + last_start = i; + B + } + + (B, Cr, UnderLim) => B, + (B, Cr, OverLim) if (i - last_start + 1) > lim => { + panic!("word starting with {} longer than limit!", + &ss[last_start..i + 1]) + } + (B, Cr, OverLim) => { *cont = it(&ss[slice_start..last_end]); slice_start = last_start; B @@ -903,7 +914,7 @@ fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool where last_end = i; C } - (B, Ws, OverLim) => { + (B, Ws, OverLim) => { last_end = i; *cont = it(&ss[slice_start..last_end]); A @@ -913,20 +924,18 @@ fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool where last_start = i; B } - (C, Cr, OverLim) => { + (C, Cr, OverLim) => { *cont = it(&ss[slice_start..last_end]); slice_start = i; last_start = i; last_end = i; B } - (C, Ws, OverLim) => { + (C, Ws, OverLim) => { *cont = it(&ss[slice_start..last_end]); A } - (C, Ws, UnderLim) => { - C - } + (C, Ws, UnderLim) => C, }; *cont @@ -935,7 +944,11 @@ fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool where ss.char_indices().all(|x| machine(&mut cont, x)); // Let the automaton 'run out' by supplying trailing whitespace - while cont && match state { B | C => true, A => false } { + while cont && + match state { + B | C => true, + A => false, + } { machine(&mut cont, (fake_i, ' ')); fake_i += 1; } @@ -946,19 +959,21 @@ fn each_split_within(ss: &str, lim: usize, mut it: F) -> bool where fn test_split_within() { fn t(s: &str, i: usize, u: &[String]) { let mut v = Vec::new(); - each_split_within(s, i, |s| { v.push(s.to_string()); true }); - assert!(v.iter().zip(u).all(|(a,b)| a == b)); + each_split_within(s, i, |s| { + v.push(s.to_string()); + true + }); + assert!(v.iter().zip(u).all(|(a, b)| a == b)); } t("", 0, &[]); t("", 15, &[]); t("hello", 15, &["hello".to_string()]); - t("\nMary had a little lamb\nLittle lamb\n", 15, &[ - "Mary had a".to_string(), - "little lamb".to_string(), - "Little lamb".to_string() - ]); - t("\nMary had a little lamb\nLittle lamb\n", ::std::usize::MAX, - &["Mary had a little lamb\nLittle lamb".to_string()]); + t("\nMary had a little lamb\nLittle lamb\n", + 15, + &["Mary had a".to_string(), "little lamb".to_string(), "Little lamb".to_string()]); + t("\nMary had a little lamb\nLittle lamb\n", + ::std::usize::MAX, + &["Mary had a little lamb\nLittle lamb".to_string()]); } #[cfg(test)] @@ -972,442 +987,446 @@ mod tests { // Tests for reqopt #[test] fn test_reqopt() { - let long_args = vec!("--test=20".to_string()); - let opts = vec!(reqopt("t", "test", "testing", "TEST")); + let long_args = vec!["--test=20".to_string()]; + let opts = vec![reqopt("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Ok(ref m) => { - assert!(m.opt_present("test")); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!(m.opt_present("t")); - assert_eq!(m.opt_str("t").unwrap(), "20"); - } - _ => { panic!("test_reqopt failed (long arg)"); } + Ok(ref m) => { + assert!(m.opt_present("test")); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!(m.opt_present("t")); + assert_eq!(m.opt_str("t").unwrap(), "20"); + } + _ => { + panic!("test_reqopt failed (long arg)"); + } } - let short_args = vec!("-t".to_string(), "20".to_string()); + let short_args = vec!["-t".to_string(), "20".to_string()]; match getopts(&short_args, &opts) { - Ok(ref m) => { - assert!((m.opt_present("test"))); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!((m.opt_present("t"))); - assert_eq!(m.opt_str("t").unwrap(), "20"); - } - _ => { panic!("test_reqopt failed (short arg)"); } + Ok(ref m) => { + assert!((m.opt_present("test"))); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), "20"); + } + _ => { + panic!("test_reqopt failed (short arg)"); + } } } #[test] fn test_reqopt_missing() { - let args = vec!("blah".to_string()); - let opts = vec!(reqopt("t", "test", "testing", "TEST")); + let args = vec!["blah".to_string()]; + let opts = vec![reqopt("t", "test", "testing", "TEST")]; let rs = getopts(&args, &opts); match rs { - Err(OptionMissing(_)) => {}, - _ => panic!() + Err(OptionMissing(_)) => {} + _ => panic!(), } } #[test] fn test_reqopt_no_arg() { - let long_args = vec!("--test".to_string()); - let opts = vec!(reqopt("t", "test", "testing", "TEST")); + let long_args = vec!["--test".to_string()]; + let opts = vec![reqopt("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match getopts(&short_args, &opts) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } } #[test] fn test_reqopt_multi() { - let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); - let opts = vec!(reqopt("t", "test", "testing", "TEST")); + let args = vec!["--test=20".to_string(), "-t".to_string(), "30".to_string()]; + let opts = vec![reqopt("t", "test", "testing", "TEST")]; let rs = getopts(&args, &opts); match rs { - Err(OptionDuplicated(_)) => {}, - _ => panic!() + Err(OptionDuplicated(_)) => {} + _ => panic!(), } } // Tests for optopt #[test] fn test_optopt() { - let long_args = vec!("--test=20".to_string()); - let opts = vec!(optopt("t", "test", "testing", "TEST")); + let long_args = vec!["--test=20".to_string()]; + let opts = vec![optopt("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Ok(ref m) => { - assert!(m.opt_present("test")); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!((m.opt_present("t"))); - assert_eq!(m.opt_str("t").unwrap(), "20"); - } - _ => panic!() + Ok(ref m) => { + assert!(m.opt_present("test")); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), "20"); + } + _ => panic!(), } - let short_args = vec!("-t".to_string(), "20".to_string()); + let short_args = vec!["-t".to_string(), "20".to_string()]; match getopts(&short_args, &opts) { - Ok(ref m) => { - assert!((m.opt_present("test"))); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!((m.opt_present("t"))); - assert_eq!(m.opt_str("t").unwrap(), "20"); - } - _ => panic!() + Ok(ref m) => { + assert!((m.opt_present("test"))); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), "20"); + } + _ => panic!(), } } #[test] fn test_optopt_missing() { - let args = vec!("blah".to_string()); - let opts = vec!(optopt("t", "test", "testing", "TEST")); + let args = vec!["blah".to_string()]; + let opts = vec![optopt("t", "test", "testing", "TEST")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert!(!m.opt_present("test")); - assert!(!m.opt_present("t")); - } - _ => panic!() + Ok(ref m) => { + assert!(!m.opt_present("test")); + assert!(!m.opt_present("t")); + } + _ => panic!(), } } #[test] fn test_optopt_no_arg() { - let long_args = vec!("--test".to_string()); - let opts = vec!(optopt("t", "test", "testing", "TEST")); + let long_args = vec!["--test".to_string()]; + let opts = vec![optopt("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match getopts(&short_args, &opts) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } } #[test] fn test_optopt_multi() { - let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); - let opts = vec!(optopt("t", "test", "testing", "TEST")); + let args = vec!["--test=20".to_string(), "-t".to_string(), "30".to_string()]; + let opts = vec![optopt("t", "test", "testing", "TEST")]; let rs = getopts(&args, &opts); match rs { - Err(OptionDuplicated(_)) => {}, - _ => panic!() + Err(OptionDuplicated(_)) => {} + _ => panic!(), } } // Tests for optflag #[test] fn test_optflag() { - let long_args = vec!("--test".to_string()); - let opts = vec!(optflag("t", "test", "testing")); + let long_args = vec!["--test".to_string()]; + let opts = vec![optflag("t", "test", "testing")]; let rs = getopts(&long_args, &opts); match rs { - Ok(ref m) => { - assert!(m.opt_present("test")); - assert!(m.opt_present("t")); - } - _ => panic!() + Ok(ref m) => { + assert!(m.opt_present("test")); + assert!(m.opt_present("t")); + } + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match getopts(&short_args, &opts) { - Ok(ref m) => { - assert!(m.opt_present("test")); - assert!(m.opt_present("t")); - } - _ => panic!() + Ok(ref m) => { + assert!(m.opt_present("test")); + assert!(m.opt_present("t")); + } + _ => panic!(), } } #[test] fn test_optflag_missing() { - let args = vec!("blah".to_string()); - let opts = vec!(optflag("t", "test", "testing")); + let args = vec!["blah".to_string()]; + let opts = vec![optflag("t", "test", "testing")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert!(!m.opt_present("test")); - assert!(!m.opt_present("t")); - } - _ => panic!() + Ok(ref m) => { + assert!(!m.opt_present("test")); + assert!(!m.opt_present("t")); + } + _ => panic!(), } } #[test] fn test_optflag_long_arg() { - let args = vec!("--test=20".to_string()); - let opts = vec!(optflag("t", "test", "testing")); + let args = vec!["--test=20".to_string()]; + let opts = vec![optflag("t", "test", "testing")]; let rs = getopts(&args, &opts); match rs { - Err(UnexpectedArgument(_)) => {}, - _ => panic!() + Err(UnexpectedArgument(_)) => {} + _ => panic!(), } } #[test] fn test_optflag_multi() { - let args = vec!("--test".to_string(), "-t".to_string()); - let opts = vec!(optflag("t", "test", "testing")); + let args = vec!["--test".to_string(), "-t".to_string()]; + let opts = vec![optflag("t", "test", "testing")]; let rs = getopts(&args, &opts); match rs { - Err(OptionDuplicated(_)) => {}, - _ => panic!() + Err(OptionDuplicated(_)) => {} + _ => panic!(), } } #[test] fn test_optflag_short_arg() { - let args = vec!("-t".to_string(), "20".to_string()); - let opts = vec!(optflag("t", "test", "testing")); + let args = vec!["-t".to_string(), "20".to_string()]; + let opts = vec![optflag("t", "test", "testing")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - // The next variable after the flag is just a free argument + Ok(ref m) => { + // The next variable after the flag is just a free argument - assert!(m.free[0] == "20"); - } - _ => panic!() + assert!(m.free[0] == "20"); + } + _ => panic!(), } } // Tests for optflagmulti #[test] fn test_optflagmulti_short1() { - let args = vec!("-v".to_string()); - let opts = vec!(optflagmulti("v", "verbose", "verbosity")); + let args = vec!["-v".to_string()]; + let opts = vec![optflagmulti("v", "verbose", "verbosity")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert_eq!(m.opt_count("v"), 1); - } - _ => panic!() + Ok(ref m) => { + assert_eq!(m.opt_count("v"), 1); + } + _ => panic!(), } } #[test] fn test_optflagmulti_short2a() { - let args = vec!("-v".to_string(), "-v".to_string()); - let opts = vec!(optflagmulti("v", "verbose", "verbosity")); + let args = vec!["-v".to_string(), "-v".to_string()]; + let opts = vec![optflagmulti("v", "verbose", "verbosity")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert_eq!(m.opt_count("v"), 2); - } - _ => panic!() + Ok(ref m) => { + assert_eq!(m.opt_count("v"), 2); + } + _ => panic!(), } } #[test] fn test_optflagmulti_short2b() { - let args = vec!("-vv".to_string()); - let opts = vec!(optflagmulti("v", "verbose", "verbosity")); + let args = vec!["-vv".to_string()]; + let opts = vec![optflagmulti("v", "verbose", "verbosity")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert_eq!(m.opt_count("v"), 2); - } - _ => panic!() + Ok(ref m) => { + assert_eq!(m.opt_count("v"), 2); + } + _ => panic!(), } } #[test] fn test_optflagmulti_long1() { - let args = vec!("--verbose".to_string()); - let opts = vec!(optflagmulti("v", "verbose", "verbosity")); + let args = vec!["--verbose".to_string()]; + let opts = vec![optflagmulti("v", "verbose", "verbosity")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert_eq!(m.opt_count("verbose"), 1); - } - _ => panic!() + Ok(ref m) => { + assert_eq!(m.opt_count("verbose"), 1); + } + _ => panic!(), } } #[test] fn test_optflagmulti_long2() { - let args = vec!("--verbose".to_string(), "--verbose".to_string()); - let opts = vec!(optflagmulti("v", "verbose", "verbosity")); + let args = vec!["--verbose".to_string(), "--verbose".to_string()]; + let opts = vec![optflagmulti("v", "verbose", "verbosity")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert_eq!(m.opt_count("verbose"), 2); - } - _ => panic!() + Ok(ref m) => { + assert_eq!(m.opt_count("verbose"), 2); + } + _ => panic!(), } } #[test] fn test_optflagmulti_mix() { - let args = vec!("--verbose".to_string(), "-v".to_string(), - "-vv".to_string(), "verbose".to_string()); - let opts = vec!(optflagmulti("v", "verbose", "verbosity")); + let args = vec!["--verbose".to_string(), + "-v".to_string(), + "-vv".to_string(), + "verbose".to_string()]; + let opts = vec![optflagmulti("v", "verbose", "verbosity")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert_eq!(m.opt_count("verbose"), 4); - assert_eq!(m.opt_count("v"), 4); - } - _ => panic!() + Ok(ref m) => { + assert_eq!(m.opt_count("verbose"), 4); + assert_eq!(m.opt_count("v"), 4); + } + _ => panic!(), } } // Tests for optmulti #[test] fn test_optmulti() { - let long_args = vec!("--test=20".to_string()); - let opts = vec!(optmulti("t", "test", "testing", "TEST")); + let long_args = vec!["--test=20".to_string()]; + let opts = vec![optmulti("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Ok(ref m) => { - assert!((m.opt_present("test"))); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!((m.opt_present("t"))); - assert_eq!(m.opt_str("t").unwrap(), "20"); - } - _ => panic!() + Ok(ref m) => { + assert!((m.opt_present("test"))); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), "20"); + } + _ => panic!(), } - let short_args = vec!("-t".to_string(), "20".to_string()); + let short_args = vec!["-t".to_string(), "20".to_string()]; match getopts(&short_args, &opts) { - Ok(ref m) => { - assert!((m.opt_present("test"))); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!((m.opt_present("t"))); - assert_eq!(m.opt_str("t").unwrap(), "20"); - } - _ => panic!() + Ok(ref m) => { + assert!((m.opt_present("test"))); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!((m.opt_present("t"))); + assert_eq!(m.opt_str("t").unwrap(), "20"); + } + _ => panic!(), } } #[test] fn test_optmulti_missing() { - let args = vec!("blah".to_string()); - let opts = vec!(optmulti("t", "test", "testing", "TEST")); + let args = vec!["blah".to_string()]; + let opts = vec![optmulti("t", "test", "testing", "TEST")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert!(!m.opt_present("test")); - assert!(!m.opt_present("t")); - } - _ => panic!() + Ok(ref m) => { + assert!(!m.opt_present("test")); + assert!(!m.opt_present("t")); + } + _ => panic!(), } } #[test] fn test_optmulti_no_arg() { - let long_args = vec!("--test".to_string()); - let opts = vec!(optmulti("t", "test", "testing", "TEST")); + let long_args = vec!["--test".to_string()]; + let opts = vec![optmulti("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } - let short_args = vec!("-t".to_string()); + let short_args = vec!["-t".to_string()]; match getopts(&short_args, &opts) { - Err(ArgumentMissing(_)) => {}, - _ => panic!() + Err(ArgumentMissing(_)) => {} + _ => panic!(), } } #[test] fn test_optmulti_multi() { - let args = vec!("--test=20".to_string(), "-t".to_string(), "30".to_string()); - let opts = vec!(optmulti("t", "test", "testing", "TEST")); + let args = vec!["--test=20".to_string(), "-t".to_string(), "30".to_string()]; + let opts = vec![optmulti("t", "test", "testing", "TEST")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert!(m.opt_present("test")); - assert_eq!(m.opt_str("test").unwrap(), "20"); - assert!(m.opt_present("t")); - assert_eq!(m.opt_str("t").unwrap(), "20"); - let pair = m.opt_strs("test"); - assert!(pair[0] == "20"); - assert!(pair[1] == "30"); - } - _ => panic!() + Ok(ref m) => { + assert!(m.opt_present("test")); + assert_eq!(m.opt_str("test").unwrap(), "20"); + assert!(m.opt_present("t")); + assert_eq!(m.opt_str("t").unwrap(), "20"); + let pair = m.opt_strs("test"); + assert!(pair[0] == "20"); + assert!(pair[1] == "30"); + } + _ => panic!(), } } #[test] fn test_unrecognized_option() { - let long_args = vec!("--untest".to_string()); - let opts = vec!(optmulti("t", "test", "testing", "TEST")); + let long_args = vec!["--untest".to_string()]; + let opts = vec![optmulti("t", "test", "testing", "TEST")]; let rs = getopts(&long_args, &opts); match rs { - Err(UnrecognizedOption(_)) => {}, - _ => panic!() + Err(UnrecognizedOption(_)) => {} + _ => panic!(), } - let short_args = vec!("-u".to_string()); + let short_args = vec!["-u".to_string()]; match getopts(&short_args, &opts) { - Err(UnrecognizedOption(_)) => {}, - _ => panic!() + Err(UnrecognizedOption(_)) => {} + _ => panic!(), } } #[test] fn test_combined() { - let args = - vec!("prog".to_string(), - "free1".to_string(), - "-s".to_string(), - "20".to_string(), - "free2".to_string(), - "--flag".to_string(), - "--long=30".to_string(), - "-f".to_string(), - "-m".to_string(), - "40".to_string(), - "-m".to_string(), - "50".to_string(), - "-n".to_string(), - "-A B".to_string(), - "-n".to_string(), - "-60 70".to_string()); - let opts = - vec!(optopt("s", "something", "something", "SOMETHING"), - optflag("", "flag", "a flag"), - reqopt("", "long", "hi", "LONG"), - optflag("f", "", "another flag"), - optmulti("m", "", "mmmmmm", "YUM"), - optmulti("n", "", "nothing", "NOTHING"), - optopt("", "notpresent", "nothing to see here", "NOPE")); + let args = vec!["prog".to_string(), + "free1".to_string(), + "-s".to_string(), + "20".to_string(), + "free2".to_string(), + "--flag".to_string(), + "--long=30".to_string(), + "-f".to_string(), + "-m".to_string(), + "40".to_string(), + "-m".to_string(), + "50".to_string(), + "-n".to_string(), + "-A B".to_string(), + "-n".to_string(), + "-60 70".to_string()]; + let opts = vec![optopt("s", "something", "something", "SOMETHING"), + optflag("", "flag", "a flag"), + reqopt("", "long", "hi", "LONG"), + optflag("f", "", "another flag"), + optmulti("m", "", "mmmmmm", "YUM"), + optmulti("n", "", "nothing", "NOTHING"), + optopt("", "notpresent", "nothing to see here", "NOPE")]; let rs = getopts(&args, &opts); match rs { - Ok(ref m) => { - assert!(m.free[0] == "prog"); - assert!(m.free[1] == "free1"); - assert_eq!(m.opt_str("s").unwrap(), "20"); - assert!(m.free[2] == "free2"); - assert!((m.opt_present("flag"))); - assert_eq!(m.opt_str("long").unwrap(), "30"); - assert!((m.opt_present("f"))); - let pair = m.opt_strs("m"); - assert!(pair[0] == "40"); - assert!(pair[1] == "50"); - let pair = m.opt_strs("n"); - assert!(pair[0] == "-A B"); - assert!(pair[1] == "-60 70"); - assert!((!m.opt_present("notpresent"))); - } - _ => panic!() + Ok(ref m) => { + assert!(m.free[0] == "prog"); + assert!(m.free[1] == "free1"); + assert_eq!(m.opt_str("s").unwrap(), "20"); + assert!(m.free[2] == "free2"); + assert!((m.opt_present("flag"))); + assert_eq!(m.opt_str("long").unwrap(), "30"); + assert!((m.opt_present("f"))); + let pair = m.opt_strs("m"); + assert!(pair[0] == "40"); + assert!(pair[1] == "50"); + let pair = m.opt_strs("n"); + assert!(pair[0] == "-A B"); + assert!(pair[1] == "-60 70"); + assert!((!m.opt_present("notpresent"))); + } + _ => panic!(), } } #[test] fn test_multi() { - let opts = vec!(optopt("e", "", "encrypt", "ENCRYPT"), - optopt("", "encrypt", "encrypt", "ENCRYPT"), - optopt("f", "", "flag", "FLAG")); + let opts = vec![optopt("e", "", "encrypt", "ENCRYPT"), + optopt("", "encrypt", "encrypt", "ENCRYPT"), + optopt("f", "", "flag", "FLAG")]; - let args_single = vec!("-e".to_string(), "foo".to_string()); + let args_single = vec!["-e".to_string(), "foo".to_string()]; let matches_single = &match getopts(&args_single, &opts) { - result::Result::Ok(m) => m, - result::Result::Err(_) => panic!() + result::Result::Ok(m) => m, + result::Result::Err(_) => panic!(), }; assert!(matches_single.opts_present(&["e".to_string()])); assert!(matches_single.opts_present(&["encrypt".to_string(), "e".to_string()])); @@ -1422,11 +1441,13 @@ mod tests { assert_eq!(matches_single.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(), "foo"); - let args_both = vec!("-e".to_string(), "foo".to_string(), "--encrypt".to_string(), - "foo".to_string()); + let args_both = vec!["-e".to_string(), + "foo".to_string(), + "--encrypt".to_string(), + "foo".to_string()]; let matches_both = &match getopts(&args_both, &opts) { - result::Result::Ok(m) => m, - result::Result::Err(_) => panic!() + result::Result::Ok(m) => m, + result::Result::Err(_) => panic!(), }; assert!(matches_both.opts_present(&["e".to_string()])); assert!(matches_both.opts_present(&["encrypt".to_string()])); @@ -1437,7 +1458,8 @@ mod tests { assert!(!matches_both.opts_present(&[])); assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo"); - assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo"); + assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), + "foo"); assert_eq!(matches_both.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["encrypt".to_string(), "e".to_string()]).unwrap(), @@ -1446,12 +1468,12 @@ mod tests { #[test] fn test_nospace() { - let args = vec!("-Lfoo".to_string(), "-M.".to_string()); - let opts = vec!(optmulti("L", "", "library directory", "LIB"), - optmulti("M", "", "something", "MMMM")); + let args = vec!["-Lfoo".to_string(), "-M.".to_string()]; + let opts = vec![optmulti("L", "", "library directory", "LIB"), + optmulti("M", "", "something", "MMMM")]; let matches = &match getopts(&args, &opts) { - result::Result::Ok(m) => m, - result::Result::Err(_) => panic!() + result::Result::Ok(m) => m, + result::Result::Err(_) => panic!(), }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "foo"); @@ -1462,12 +1484,12 @@ mod tests { #[test] fn test_nospace_conflict() { - let args = vec!("-vvLverbose".to_string(), "-v".to_string() ); - let opts = vec!(optmulti("L", "", "library directory", "LIB"), - optflagmulti("v", "verbose", "Verbose")); + let args = vec!["-vvLverbose".to_string(), "-v".to_string()]; + let opts = vec![optmulti("L", "", "library directory", "LIB"), + optflagmulti("v", "verbose", "Verbose")]; let matches = &match getopts(&args, &opts) { - result::Result::Ok(m) => m, - result::Result::Err(e) => panic!( "{}", e ) + result::Result::Ok(m) => m, + result::Result::Err(e) => panic!("{}", e), }; assert!(matches.opts_present(&["L".to_string()])); assert_eq!(matches.opts_str(&["L".to_string()]).unwrap(), "verbose"); @@ -1483,10 +1505,12 @@ mod tests { occur: Occur::Req, aliases: Vec::new(), }; - short.aliases = vec!(Opt { name: Name::Short('b'), - hasarg: HasArg::Yes, - occur: Occur::Req, - aliases: Vec::new() }); + short.aliases = vec![Opt { + name: Name::Short('b'), + hasarg: HasArg::Yes, + occur: Occur::Req, + aliases: Vec::new(), + }]; let verbose = reqopt("b", "banana", "some bananas", "VAL"); assert!(verbose.long_to_short() == short); @@ -1494,10 +1518,9 @@ mod tests { #[test] fn test_aliases_long_and_short() { - let opts = vec!( - optflagmulti("a", "apple", "Desc")); + let opts = vec![optflagmulti("a", "apple", "Desc")]; - let args = vec!("-a".to_string(), "--apple".to_string(), "-a".to_string()); + let args = vec!["-a".to_string(), "--apple".to_string(), "-a".to_string()]; let matches = getopts(&args, &opts).unwrap(); assert_eq!(3, matches.opt_count("a")); @@ -1506,13 +1529,11 @@ mod tests { #[test] fn test_usage() { - let optgroups = vec!( - reqopt("b", "banana", "Desc", "VAL"), - optopt("a", "012345678901234567890123456789", - "Desc", "VAL"), - optflag("k", "kiwi", "Desc"), - optflagopt("p", "", "Desc", "VAL"), - optmulti("l", "", "Desc", "VAL")); + let optgroups = vec![reqopt("b", "banana", "Desc", "VAL"), + optopt("a", "012345678901234567890123456789", "Desc", "VAL"), + optflag("k", "kiwi", "Desc"), + optflagopt("p", "", "Desc", "VAL"), + optmulti("l", "", "Desc", "VAL")]; let expected = "Usage: fruits @@ -1538,11 +1559,13 @@ Options: // indentation should be 24 spaces // lines wrap after 78: or rather descriptions wrap after 54 - let optgroups = vec!( - optflag("k", "kiwi", - "This is a long description which won't be wrapped..+.."), // 54 - optflag("a", "apple", - "This is a long description which _will_ be wrapped..+..")); + let optgroups = vec![optflag("k", + "kiwi", + // 54 + "This is a long description which won't be wrapped..+.."), + optflag("a", + "apple", + "This is a long description which _will_ be wrapped..+..")]; let expected = "Usage: fruits @@ -1562,12 +1585,14 @@ Options: #[test] fn test_usage_description_multibyte_handling() { - let optgroups = vec!( - optflag("k", "k\u{2013}w\u{2013}", - "The word kiwi is normally spelled with two i's"), - optflag("a", "apple", - "This \u{201C}description\u{201D} has some characters that could \ -confuse the line wrapping; an apple costs 0.51€ in some parts of Europe.")); + let optgroups = vec![optflag("k", + "k\u{2013}w\u{2013}", + "The word kiwi is normally spelled with two i's"), + optflag("a", + "apple", + "This \u{201C}description\u{201D} has some characters that \ + could confuse the line wrapping; an apple costs 0.51€ in \ + some parts of Europe.")]; let expected = "Usage: fruits @@ -1588,13 +1613,11 @@ Options: #[test] fn test_short_usage() { - let optgroups = vec!( - reqopt("b", "banana", "Desc", "VAL"), - optopt("a", "012345678901234567890123456789", - "Desc", "VAL"), - optflag("k", "kiwi", "Desc"), - optflagopt("p", "", "Desc", "VAL"), - optmulti("l", "", "Desc", "VAL")); + let optgroups = vec![reqopt("b", "banana", "Desc", "VAL"), + optopt("a", "012345678901234567890123456789", "Desc", "VAL"), + optflag("k", "kiwi", "Desc"), + optflagopt("p", "", "Desc", "VAL"), + optmulti("l", "", "Desc", "VAL")]; let expected = "Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..".to_string(); let generated_usage = short_usage("fruits", &optgroups); diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 1fb54ed9071ab..14a8d78c0b264 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -416,10 +416,10 @@ impl<'a> Id<'a> { _ => return Err(()), } if !chars.all(is_constituent) { - return Err(()) + return Err(()); } } - return Ok(Id{ name: name }); + return Ok(Id { name: name }); fn is_letter_or_underscore(c: char) -> bool { in_range('a', c, 'z') || in_range('A', c, 'Z') || c == '_' @@ -496,11 +496,10 @@ pub trait Labeller<'a,N,E> { /// Escape tags in such a way that it is suitable for inclusion in a /// Graphviz HTML label. pub fn escape_html(s: &str) -> String { - s - .replace("&", "&") - .replace("\"", """) - .replace("<", "<") - .replace(">", ">") + s.replace("&", "&") + .replace("\"", """) + .replace("<", "<") + .replace(">", ">") } impl<'a> LabelText<'a> { @@ -523,9 +522,11 @@ impl<'a> LabelText<'a> { // not escaping \\, since Graphviz escString needs to // interpret backslashes; see EscStr above. '\\' => f(c), - _ => for c in c.escape_default() { - f(c) - }, + _ => { + for c in c.escape_default() { + f(c) + } + } } } fn escape_str(s: &str) -> String { @@ -553,11 +554,13 @@ impl<'a> LabelText<'a> { fn pre_escaped_content(self) -> Cow<'a, str> { match self { EscStr(s) => s, - LabelStr(s) => if s.contains('\\') { - (&*s).escape_default().into_cow() - } else { - s - }, + LabelStr(s) => { + if s.contains('\\') { + (&*s).escape_default().into_cow() + } else { + s + } + } HtmlStr(s) => s, } } @@ -738,7 +741,12 @@ mod tests { } fn edge(from: usize, to: usize, label: &'static str, style: Style) -> Edge { - Edge { from: from, to: to, label: label, style: style } + Edge { + from: from, + to: to, + label: label, + style: style, + } } struct LabelledGraph { @@ -1009,7 +1017,7 @@ r#"digraph single_cyclic_node { #[test] fn hasse_diagram() { - let labels = AllNodesLabelled(vec!("{x,y}", "{x}", "{y}", "{}")); + let labels = AllNodesLabelled(vec!["{x,y}", "{x}", "{y}", "{}"]); let r = test_input(LabelledGraph::new("hasse_diagram", labels, vec![edge(0, 1, "", Style::None), @@ -1033,7 +1041,7 @@ r#"digraph hasse_diagram { #[test] fn left_aligned_text() { - let labels = AllNodesLabelled(vec!( + let labels = AllNodesLabelled(vec![ "if test {\ \\l branch1\ \\l} else {\ @@ -1043,7 +1051,7 @@ r#"digraph hasse_diagram { \\l", "branch1", "branch2", - "afterward")); + "afterward"]); let mut writer = Vec::new(); diff --git a/src/liblog/directive.rs b/src/liblog/directive.rs index 3958969cfca32..18163703e88ba 100644 --- a/src/liblog/directive.rs +++ b/src/liblog/directive.rs @@ -49,7 +49,7 @@ pub fn parse_logging_spec(spec: &str) -> (Vec, Option) { if let Some(m) = mods { for s in m.split(',') { if s.is_empty() { - continue + continue; } let mut parts = s.split('='); let (log_level, name) = match (parts.next(), @@ -69,13 +69,13 @@ pub fn parse_logging_spec(spec: &str) -> (Vec, Option) { Some(num) => (num, Some(part0)), _ => { println!("warning: invalid logging spec '{}', ignoring it", part1); - continue + continue; } } } _ => { println!("warning: invalid logging spec '{}', ignoring it", s); - continue + continue; } }; dirs.push(LogDirective { diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 1de7ebfffdea2..850c5511dd57d 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -296,7 +296,7 @@ pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) { n => { let filter = mem::transmute::<_, &String>(n); if !args.to_string().contains(filter) { - return + return; } } } @@ -375,7 +375,7 @@ pub fn mod_enabled(level: u32, module: &str) -> bool { // check being expanded manually in the logging macro, this function checks // the log level again. if level > unsafe { LOG_LEVEL } { - return false + return false; } // This assertion should never get tripped unless we're in an at_exit @@ -393,9 +393,7 @@ fn enabled(level: u32, module: &str, iter: slice::Iter) for directive in iter.rev() { match directive.name { Some(ref name) if !module.starts_with(&name[..]) => {} - Some(..) | None => { - return level <= directive.level - } + Some(..) | None => return level <= directive.level, } } level <= DEFAULT_LOG_LEVEL diff --git a/src/librand/chacha.rs b/src/librand/chacha.rs index 411ca83608054..e2c157f98a6a4 100644 --- a/src/librand/chacha.rs +++ b/src/librand/chacha.rs @@ -12,8 +12,8 @@ use {Rng, SeedableRng, Rand}; -const KEY_WORDS : usize = 8; // 8 words for the 256-bit key -const STATE_WORDS : usize = 16; +const KEY_WORDS: usize = 8; // 8 words for the 256-bit key +const STATE_WORDS: usize = 16; const CHACHA_ROUNDS: usize = 20; // Cryptographically secure from 8 upwards as of this writing /// A random number generator that uses the ChaCha20 algorithm [1]. @@ -77,7 +77,6 @@ fn core(output: &mut [u32; STATE_WORDS], input: &[u32; STATE_WORDS]) { } impl ChaChaRng { - /// Create an ChaCha random number generator using the default /// fixed key of 8 zero words. pub fn new_unseeded() -> ChaChaRng { @@ -173,7 +172,6 @@ impl Rng for ChaChaRng { } impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { - fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0; KEY_WORDS]); diff --git a/src/librand/distributions/gamma.rs b/src/librand/distributions/gamma.rs index fceda64cbb3f1..8cd7ac06f991b 100644 --- a/src/librand/distributions/gamma.rs +++ b/src/librand/distributions/gamma.rs @@ -89,7 +89,7 @@ impl Gamma { let repr = match shape { 1.0 => One(Exp::new(1.0 / scale)), - 0.0 ... 1.0 => Small(GammaSmallShape::new_raw(shape, scale)), + 0.0...1.0 => Small(GammaSmallShape::new_raw(shape, scale)), _ => Large(GammaLargeShape::new_raw(shape, scale)), }; Gamma { repr: repr } @@ -153,7 +153,8 @@ impl IndependentSample for GammaLargeShape { loop { let StandardNormal(x) = rng.gen::(); let v_cbrt = 1.0 + self.c * x; - if v_cbrt <= 0.0 { // a^3 <= 0 iff a <= 0 + if v_cbrt <= 0.0 { + // a^3 <= 0 iff a <= 0 continue; } diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 4c62e1a350406..a54c8df2352ac 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -118,8 +118,10 @@ impl<'a, T: Clone> WeightedChoice<'a, T> { for item in &mut *items { running_total = match running_total.checked_add(item.weight) { Some(n) => n, - None => panic!("WeightedChoice::new called with a total weight larger than a \ - usize can contain"), + None => { + panic!("WeightedChoice::new called with a total weight larger than a usize \ + can contain") + } }; item.weight = running_total; @@ -199,7 +201,6 @@ mod ziggurat_tables; /// * `pdf`: the probability density function /// * `zero_case`: manual sampling from the tail when we chose the /// bottom box (i.e. i == 0) - // the perf improvement (25-50%) is definitely worth the extra code // size from force-inlining. #[inline(always)] diff --git a/src/librand/isaac.rs b/src/librand/isaac.rs index ac2b9b07ffd13..1f56a82eba86e 100644 --- a/src/librand/isaac.rs +++ b/src/librand/isaac.rs @@ -54,7 +54,6 @@ static EMPTY: IsaacRng = IsaacRng { }; impl IsaacRng { - /// Create an ISAAC random number generator using the default /// fixed seed. pub fn new_unseeded() -> IsaacRng { @@ -403,7 +402,7 @@ impl Isaac64Rng { // abbreviations let mut a = self.a; let mut b = self.b + self.c; - const MIDPOINT: usize = RAND_SIZE_64 / 2; + const MIDPOINT: usize = RAND_SIZE_64 / 2; const MP_VEC: [(usize, usize); 2] = [(0, MIDPOINT), (MIDPOINT, 0)]; macro_rules! ind { ($x:expr) => { diff --git a/src/librand/lib.rs b/src/librand/lib.rs index cf2118b45a471..247dcd03b5d7a 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -306,10 +306,9 @@ impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> { type Item = char; fn next(&mut self) -> Option { - const GEN_ASCII_STR_CHARSET: &'static [u8] = - b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ - abcdefghijklmnopqrstuvwxyz\ - 0123456789"; + const GEN_ASCII_STR_CHARSET: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ + abcdefghijklmnopqrstuvwxyz\ + 0123456789"; Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char) } } diff --git a/src/librand/rand_impls.rs b/src/librand/rand_impls.rs index 726a4554626f5..34b7f37a6788f 100644 --- a/src/librand/rand_impls.rs +++ b/src/librand/rand_impls.rs @@ -202,7 +202,7 @@ tuple_impl!{A, B, C, D, E, F, G, H, I, J} tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} -impl Rand for Option { +impl Rand for Option { #[inline] fn rand(rng: &mut R) -> Option { if rng.gen() {