rustfmt libcollections

This commit is contained in:
Nick Cameron 2015-11-24 11:23:48 +13:00
parent 1f1a1e6595
commit 0dfd875b6e
14 changed files with 1414 additions and 970 deletions

View File

@ -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<T: Clone> Clone for BinaryHeap<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Default for BinaryHeap<T> {
#[inline]
fn default() -> BinaryHeap<T> { BinaryHeap::new() }
fn default() -> BinaryHeap<T> {
BinaryHeap::new()
}
}
#[stable(feature = "binaryheap_debug", since = "1.4.0")]
@ -207,7 +209,9 @@ impl<T: Ord> BinaryHeap<T> {
/// heap.push(4);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> BinaryHeap<T> { BinaryHeap { data: vec![] } }
pub fn new() -> BinaryHeap<T> {
BinaryHeap { data: vec![] }
}
/// Creates an empty `BinaryHeap` with a specific capacity.
/// This preallocates enough memory for `capacity` elements,
@ -296,7 +300,9 @@ impl<T: Ord> BinaryHeap<T> {
/// 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<T: Ord> BinaryHeap<T> {
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<T: Ord> BinaryHeap<T> {
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<T: Ord> BinaryHeap<T> {
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<T: Ord> BinaryHeap<T> {
/// 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<T: Ord> BinaryHeap<T> {
/// 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<usize>) { self.iter.size_hint() }
fn size_hint(&self) -> (usize, Option<usize>) {
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<T> Iterator for IntoIter<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> { self.iter.next() }
fn next(&mut self) -> Option<T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> DoubleEndedIterator for IntoIter<T> {
#[inline]
fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
fn next_back(&mut self) -> Option<T> {
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<T> { self.iter.next() }
fn next(&mut self) -> Option<T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
fn size_hint(&self) -> (usize, Option<usize>) {
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<T> { self.iter.next_back() }
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
@ -753,7 +791,7 @@ impl<T> From<BinaryHeap<T>> for Vec<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> FromIterator<T> for BinaryHeap<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BinaryHeap<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BinaryHeap<T> {
BinaryHeap::from(iter.into_iter().collect::<Vec<_>>())
}
}
@ -796,7 +834,7 @@ impl<'a, T> IntoIterator for &'a BinaryHeap<T> where T: Ord {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BinaryHeap<T> {
fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
let iter = iterable.into_iter();
let (lower, _) = iter.size_hint();
@ -810,7 +848,7 @@ impl<T: Ord> Extend<T> for BinaryHeap<T> {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BinaryHeap<T> {
fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}

View File

@ -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<B> for Cow<'a, B> where B: ToOwned, <B as ToOwned>::Owned: 'a {
impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B>
where B: ToOwned,
<B as ToOwned>::Owned: 'a
{
fn borrow(&self) -> &B {
&**self
}
@ -53,7 +56,9 @@ pub trait ToOwned {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> 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<T> 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(<B as ToOwned>::Owned)
Owned(<B as ToOwned>::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) -> <B as ToOwned>::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<Cow<'b, C>> for Cow<'a, B> where
B: PartialEq<C> + ToOwned, C: ToOwned,
impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> for Cow<'a, B>
where B: PartialEq<C> + ToOwned,
C: ToOwned
{
#[inline]
fn eq(&self, other: &Cow<'b, C>) -> bool {
@ -193,8 +201,7 @@ impl<'a, 'b, B: ?Sized, C: ?Sized> PartialEq<Cow<'b, C>> 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<Ordering> {
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,
<B as ToOwned>::Owned: fmt::Debug,
impl<'a, B: ?Sized> fmt::Debug for Cow<'a, B>
where B: fmt::Debug + ToOwned,
<B as 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,
<B as ToOwned>::Owned: fmt::Display,
impl<'a, B: ?Sized> fmt::Display for Cow<'a, B>
where B: fmt::Display + ToOwned,
<B as 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<H: Hasher>(&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
}

View File

@ -84,46 +84,46 @@ struct AbsIter<T> {
/// An iterator over a BTreeMap's entries.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Iter<'a, K: 'a, V: 'a> {
inner: AbsIter<Traversal<'a, K, V>>
inner: AbsIter<Traversal<'a, K, V>>,
}
/// 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<MutTraversal<'a, K, V>>
inner: AbsIter<MutTraversal<'a, K, V>>,
}
/// An owning iterator over a BTreeMap's entries.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoIter<K, V> {
inner: AbsIter<MoveTraversal<K, V>>
inner: AbsIter<MoveTraversal<K, V>>,
}
/// An iterator over a BTreeMap's keys.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Keys<'a, K: 'a, V: 'a> {
inner: Map<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K>
inner: Map<Iter<'a, K, V>, 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<Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V>
inner: Map<Iter<'a, K, V>, 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<Traversal<'a, K, V>>
inner: AbsIter<Traversal<'a, K, V>>,
}
/// A mutable iterator over a sub-range of BTreeMap's entries.
pub struct RangeMut<'a, K: 'a, V: 'a> {
inner: AbsIter<MutTraversal<'a, K, V>>
inner: AbsIter<MutTraversal<'a, K, V>>,
}
/// 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<K: Ord, V> BTreeMap<K, V> {
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
pub fn new() -> BTreeMap<K, V> {
//FIXME(Gankro): Tune this as a function of size_of<K/V>?
// FIXME(Gankro): Tune this as a function of size_of<K/V>?
BTreeMap::with_b(6)
}
@ -189,7 +189,7 @@ impl<K: Ord, V> BTreeMap<K, V> {
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<K: Ord, V> BTreeMap<K, V> {
/// assert_eq!(map.get(&2), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V> where K: Borrow<Q>, Q: Ord {
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where K: Borrow<Q>,
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<K: Ord, V> BTreeMap<K, V> {
/// assert_eq!(map.contains_key(&2), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where K: Borrow<Q>, Q: Ord {
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where K: Borrow<Q>,
Q: Ord
{
self.get(key).is_some()
}
@ -271,18 +279,23 @@ impl<K: Ord, V> BTreeMap<K, V> {
/// ```
// 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<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V> where K: Borrow<Q>, Q: Ord {
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
where K: Borrow<Q>,
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<K: Ord, V> BTreeMap<K, V> {
// 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<K: Ord, V> BTreeMap<K, V> {
/// assert_eq!(map.remove(&1), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V> where K: Borrow<Q>, Q: Ord {
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where K: Borrow<Q>,
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<K: Ord, V> BTreeMap<K, V> {
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<K, V> IntoIterator for BTreeMap<K, V> {
inner: AbsIter {
traversals: lca,
size: len,
}
},
}
}
}
@ -534,7 +550,7 @@ impl<'a, K, V> IntoIterator for &'a mut BTreeMap<K, V> {
/// return from a closure
enum Continuation<A, B> {
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<K, V> = Vec<StackItem<K, V>>;
/// 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<K, V>,
stack: Stack<K, V>,
next: *mut Node<K, V>,
@ -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<K, V>,
stack: Stack<K, V>,
top: node::Handle<*mut Node<K, V>, 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<K, V>,
stack: Stack<K, V>,
_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<IdRef<'id, Node<K, V>>,
handle::Edge,
handle::Internal>)
pub fn push(mut self,
mut edge: node::Handle<IdRef<'id, Node<K, V>>, 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<Type, NodeType>
(self, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>)
-> SearchStack<'a, K, V, Type, NodeType> {
pub fn seal<Type, NodeType>(self,
mut handle: node::Handle<IdRef<'id, Node<K, V>>,
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);
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;
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<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
fn from_iter<T: IntoIterator<Item=(K, V)>>(iter: T) -> BTreeMap<K, V> {
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> BTreeMap<K, V> {
let mut map = BTreeMap::new();
map.extend(iter);
map
@ -879,7 +899,7 @@ impl<K: Ord, V> FromIterator<(K, V)> for BTreeMap<K, V> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
#[inline]
fn extend<T: IntoIterator<Item=(K, V)>>(&mut self, iter: T) {
fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
for (k, v) in iter {
self.insert(k, v);
}
@ -888,7 +908,7 @@ impl<K: Ord, V> Extend<(K, V)> for BTreeMap<K, V> {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, K: Ord + Copy, V: Copy> Extend<(&'a K, &'a V)> for BTreeMap<K, V> {
fn extend<I: IntoIterator<Item=(&'a K, &'a V)>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
}
}
@ -912,8 +932,7 @@ impl<K: Ord, V> Default for BTreeMap<K, V> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<K: PartialEq, V: PartialEq> PartialEq for BTreeMap<K, V> {
fn eq(&self, other: &BTreeMap<K, V>) -> 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<K: Debug, V: Debug> Debug for BTreeMap<K, V> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap<K, V>
where K: Borrow<Q>, Q: Ord
where K: Borrow<Q>,
Q: Ord
{
type Output = V;
@ -987,8 +1007,8 @@ enum StackOp<T> {
Push(T),
Pop,
}
impl<K, V, E, T> Iterator for AbsIter<T> where
T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>,
impl<K, V, E, T> Iterator for AbsIter<T>
where T: DoubleEndedIterator<Item = TraversalItem<K, V, E>> + Traverse<E>
{
type Item = (K, V);
@ -1002,23 +1022,29 @@ impl<K, V, E, T> Iterator for AbsIter<T> 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<K, V, E, T> Iterator for AbsIter<T> where
}
}
impl<K, V, E, T> DoubleEndedIterator for AbsIter<T> where
T: DoubleEndedIterator<Item=TraversalItem<K, V, E>> + Traverse<E>,
impl<K, V, E, T> DoubleEndedIterator for AbsIter<T>
where T: DoubleEndedIterator<Item = TraversalItem<K, V, E>> + Traverse<E>
{
// next_back is totally symmetric to next
#[inline]
@ -1037,37 +1063,51 @@ impl<K, V, E, T> DoubleEndedIterator for AbsIter<T> 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<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<(&'a K, &'a V)> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
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<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
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<K, V> Iterator for IntoIter<K, V> {
type Item = (K, V);
fn next(&mut self) -> Option<(K, V)> { self.inner.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<(K, V)> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
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<K, V> ExactSizeIterator for IntoIter<K, V> {}
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<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<(&'a K)> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
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<usize>) { self.inner.size_hint() }
fn next(&mut self) -> Option<(&'a V)> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
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<K, V> BTreeMap<K, V> {
inner: AbsIter {
traversals: lca,
size: len,
}
},
}
}
@ -1283,7 +1361,7 @@ impl<K, V> BTreeMap<K, V> {
inner: AbsIter {
traversals: lca,
size: len,
}
},
}
}
@ -1303,7 +1381,9 @@ impl<K, V> BTreeMap<K, V> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
fn first<A, B>((a, _): (A, B)) -> A { a }
fn first<A, B>((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<K, V> BTreeMap<K, V> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn values<'a>(&'a self) -> Values<'a, K, V> {
fn second<A, B>((_, b): (A, B)) -> B { b }
fn second<A, B>((_, 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<K, V> BTreeMap<K, V> {
/// 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<K, V> BTreeMap<K, V> {
/// 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<K: Ord, V> BTreeMap<K, V> {
#[unstable(feature = "btree_range",
reason = "matches collection reform specification, waiting for dust to settle",
issue = "27787")]
pub fn range<Min: ?Sized + Ord = K, Max: ?Sized + Ord = K>(&self, min: Bound<&Min>,
pub fn range<Min: ?Sized + Ord = K, Max: ?Sized + Ord = K>(&self,
min: Bound<&Min>,
max: Bound<&Max>)
-> Range<K, V> where
K: Borrow<Min> + Borrow<Max>,
-> Range<K, V>
where K: Borrow<Min> + Borrow<Max>
{
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<K: Ord, V> BTreeMap<K, V> {
#[unstable(feature = "btree_range",
reason = "matches collection reform specification, waiting for dust to settle",
issue = "27787")]
pub fn range_mut<Min: ?Sized + Ord = K, Max: ?Sized + Ord = K>(&mut self, min: Bound<&Min>,
pub fn range_mut<Min: ?Sized + Ord = K, Max: ?Sized + Ord = K>(&mut self,
min: Bound<&Min>,
max: Bound<&Max>)
-> RangeMut<K, V> where
K: Borrow<Min> + Borrow<Max>,
-> RangeMut<K, V>
where K: Borrow<Min> + Borrow<Max>
{
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<K: Ord, V> BTreeMap<K, V> {
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<K: Ord, V> BTreeMap<K, V> {
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<K: Ord, V> BTreeMap<K, V> {
}
}
impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()> where K: Borrow<Q> + Ord, Q: Ord {
impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
where K: Borrow<Q> + Ord,
Q: Ord
{
type Key = K;
fn get(&self, key: &Q) -> Option<&K> {
@ -1627,11 +1726,13 @@ impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()> where K: Borrow<Q> + 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<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()> where K: Borrow<Q> + 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<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()> where K: Borrow<Q> + Or
Found(mut handle) => {
mem::swap(handle.key_mut(), &mut key);
Finished(Some(key))
},
}
GoDown(handle) => {
match handle.force() {
Leaf(leaf_handle) => {

View File

@ -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<K, V>(capacity: usize, is_leaf: bool) -> (usize,
(0, 1)
}
} else {
((capacity + 1) * mem::size_of::<Node<K, V>>(), mem::align_of::<Node<K, V>>())
((capacity + 1) * mem::size_of::<Node<K, V>>(),
mem::align_of::<Node<K, V>>())
};
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<K, V>(capacity: usize, is_leaf: bool) -> (usize, usize) {
@ -191,11 +195,7 @@ fn calculate_offsets_generic<K, V>(capacity: usize, is_leaf: bool) -> (usize, us
mem::align_of::<Node<K, V>>()
};
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<K, V> Drop for Node<K, V> {
#[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<K, V> Node<K, V> {
let (alignment, size) = calculate_allocation_generic::<K, V>(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::<K, V>(capacity, false);
@ -332,7 +333,9 @@ impl<K, V> Node<K, V> {
let (alignment, size) = calculate_allocation_generic::<K, V>(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::<K, V>(capacity, true);
@ -346,25 +349,25 @@ impl<K, V> Node<K, V> {
}
unsafe fn destroy(&mut self) {
let (alignment, size) =
calculate_allocation_generic::<K, V>(self.capacity(), self.is_leaf());
let (alignment, size) = calculate_allocation_generic::<K, V>(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<K, V> Node<K, V> {
} else {
unsafe {
let data = match self.edges {
None => heap::EMPTY as *const Node<K,V>,
Some(ref p) => **p as *const Node<K,V>,
None => heap::EMPTY as *const Node<K, V>,
Some(ref p) => **p as *const Node<K, V>,
};
slice::from_raw_parts(data, self.len() + 1)
}
@ -403,8 +406,8 @@ impl<K, V> Node<K, V> {
} else {
unsafe {
let data = match self.edges {
None => heap::EMPTY as *mut Node<K,V>,
Some(ref mut p) => **p as *mut Node<K,V>,
None => heap::EMPTY as *mut Node<K, V>,
Some(ref mut p) => **p as *mut Node<K, V>,
};
slice::from_raw_parts_mut(data, len + 1)
}
@ -573,29 +576,49 @@ impl<K: Ord, V> Node<K, V> {
/// 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<Q: ?Sized, NodeRef: Deref<Target=Node<K, V>>>(node: NodeRef, key: &Q)
-> SearchResult<NodeRef> where K: Borrow<Q>, Q: Ord {
pub fn search<Q: ?Sized, NodeRef: Deref<Target = Node<K, V>>>(node: NodeRef,
key: &Q)
-> SearchResult<NodeRef>
where K: Borrow<Q>,
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 <K, V> Node<K, V> {
impl<K, V> Node<K, V> {
/// Make a leaf root from scratch
pub fn make_leaf_root(b: usize) -> Node<K, V> {
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<K,V>, b: usize, key: K, value: V,
right: Node<K,V>) {
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<K, V>,
b: usize,
key: K,
value: V,
right: Node<K, V>) {
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 <K, V> Node<K, V> {
}
/// 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 <K, V> Node<K, V> {
}
}
impl<K, V, NodeRef: Deref<Target=Node<K, V>>, Type, NodeType> Handle<NodeRef, Type, NodeType> {
impl<K, V, NodeRef: Deref<Target = Node<K, V>>, Type, NodeType> Handle<NodeRef, Type, NodeType> {
/// 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<K, V, NodeRef: Deref<Target=Node<K, V>>, Type, NodeType> Handle<NodeRef, Ty
}
}
impl<K, V, NodeRef, Type, NodeType> Handle<NodeRef, Type, NodeType> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut,
impl<K, V, NodeRef, Type, NodeType> Handle<NodeRef, Type, NodeType>
where NodeRef: Deref<Target = Node<K, V>> + 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<K, V>, 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<K, V> {
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<K, V>, 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<K, V> {
unsafe {
self.node.edges_mut().get_unchecked_mut(self.index)
}
unsafe { self.node.edges_mut().get_unchecked_mut(self.index) }
}
}
impl<K, V, NodeRef: Deref<Target=Node<K, V>>> Handle<NodeRef, handle::Edge, handle::Internal> {
impl<K, V, NodeRef: Deref<Target = Node<K, V>>> Handle<NodeRef, handle::Edge, handle::Internal> {
// 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<K, V, NodeRef: Deref<Target=Node<K, V>>> Handle<NodeRef, handle::Edge, hand
pub enum ForceResult<NodeRef, Type> {
Leaf(Handle<NodeRef, Type, handle::Leaf>),
Internal(Handle<NodeRef, Type, handle::Internal>)
Internal(Handle<NodeRef, Type, handle::Internal>),
}
impl<K, V, NodeRef: Deref<Target=Node<K, V>>, Type> Handle<NodeRef, Type, handle::LeafOrInternal> {
impl<K, V, NodeRef: Deref<Target = Node<K, V>>, Type>
Handle<NodeRef, Type, handle::LeafOrInternal>
{
/// 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<NodeRef, Type> {
@ -737,16 +760,15 @@ impl<K, V, NodeRef: Deref<Target=Node<K, V>>, Type> Handle<NodeRef, Type, handle
}
}
}
impl<K, V, NodeRef> Handle<NodeRef, handle::Edge, handle::Leaf> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut,
impl<K, V, NodeRef> Handle<NodeRef, handle::Edge, handle::Leaf>
where NodeRef: Deref<Target = Node<K, V>> + 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<K, V>, *mut V) {
pub fn insert_as_leaf(mut self, key: K, value: V) -> (InsertionResult<K, V>, *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<K, V, NodeRef> Handle<NodeRef, handle::Edge, handle::Leaf> where
}
}
impl<K, V, NodeRef> Handle<NodeRef, handle::Edge, handle::Internal> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut,
impl<K, V, NodeRef> Handle<NodeRef, handle::Edge, handle::Internal>
where NodeRef: Deref<Target = Node<K, V>> + 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<K, V> {
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<K, V>)
-> InsertionResult<K, V> {
pub fn insert_as_internal(mut self,
key: K,
value: V,
right: Node<K, V>)
-> InsertionResult<K, V> {
if !self.node.is_full() {
// The element can fit, just insert it
unsafe {
@ -856,8 +879,8 @@ impl<K, V, NodeRef> Handle<NodeRef, handle::Edge, handle::Internal> where
}
}
impl<K, V, NodeRef, NodeType> Handle<NodeRef, handle::Edge, NodeType> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut,
impl<K, V, NodeRef, NodeType> Handle<NodeRef, handle::Edge, NodeType>
where NodeRef: Deref<Target = Node<K, V>> + 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<K, V>, 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<K, V>, 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<K, V>, handle::KV, NodeType
}
}
impl<'a, K: 'a, V: 'a, NodeRef: Deref<Target=Node<K, V>> + 'a, NodeType> Handle<NodeRef, handle::KV,
NodeType> {
impl<'a, K: 'a, V: 'a, NodeRef: Deref<Target = Node<K, V>> + 'a, NodeType> Handle<NodeRef,
handle::KV,
NodeType> {
// 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<Target=Node<K, V>> + 'a, NodeType> Handle<
// }
}
impl<'a, K: 'a, V: 'a, NodeRef, NodeType> Handle<NodeRef, handle::KV, NodeType> where
NodeRef: 'a + Deref<Target=Node<K, V>> + DerefMut,
impl<'a, K: 'a, V: 'a, NodeRef, NodeType> Handle<NodeRef, handle::KV, NodeType>
where NodeRef: 'a + Deref<Target = Node<K, V>> + 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<NodeRef, handle::KV, NodeType>
}
}
impl<K, V, NodeRef, NodeType> Handle<NodeRef, handle::KV, NodeType> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut,
impl<K, V, NodeRef, NodeType> Handle<NodeRef, handle::KV, NodeType>
where NodeRef: Deref<Target = Node<K, V>> + 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<K, V, NodeRef, NodeType> Handle<NodeRef, handle::KV, NodeType> where
}
}
impl<K, V, NodeRef> Handle<NodeRef, handle::KV, handle::Leaf> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut,
impl<K, V, NodeRef> Handle<NodeRef, handle::KV, handle::Leaf>
where NodeRef: Deref<Target = Node<K, V>> + DerefMut
{
/// Removes the key/value pair at the handle's location.
///
@ -997,8 +1018,8 @@ impl<K, V, NodeRef> Handle<NodeRef, handle::KV, handle::Leaf> where
}
}
impl<K, V, NodeRef> Handle<NodeRef, handle::KV, handle::Internal> where
NodeRef: Deref<Target=Node<K, V>> + DerefMut
impl<K, V, NodeRef> Handle<NodeRef, handle::KV, handle::Internal>
where NodeRef: Deref<Target = Node<K, V>> + DerefMut
{
/// Steal! Stealing is roughly analogous to a binary tree rotation.
/// In this case, we're "rotating" right.
@ -1071,7 +1092,8 @@ impl<K, V, NodeRef> Handle<NodeRef, handle::KV, handle::Internal> 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<K, V> Node<K, V> {
/// # Panics (in debug build)
///
/// Panics if the given index is out of bounds.
pub fn kv_handle(&mut self, index: usize) -> Handle<&mut Node<K, V>, handle::KV,
handle::LeafOrInternal> {
pub fn kv_handle(&mut self,
index: usize)
-> Handle<&mut Node<K, V>, 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<K, V> Node<K, V> {
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<K, V> Node<K, V> {
// 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<K, V> Node<K, V> {
// This can only be called immediately after a call to insert_kv.
#[inline]
unsafe fn insert_edge(&mut self, index: usize, edge: Node<K, V>) {
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<K, V> Node<K, V> {
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<K, V> Node<K, V> {
unsafe fn remove_edge(&mut self, index: usize) -> Node<K, V> {
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<K, V> Node<K, V> {
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<K, V> Node<K, V> {
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<K, V> {
// For deallocation when we are done iterating.
ptr: Unique<u8>,
capacity: usize,
is_leaf: bool
is_leaf: bool,
}
unsafe impl<K: Sync, V: Sync> Sync for MoveTraversalImpl<K, V> {}
@ -1395,14 +1396,14 @@ impl<K, V> TraversalImpl for MoveTraversalImpl<K, V> {
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<K, V> Drop for MoveTraversalImpl<K, V> {
for _ in self.vals.by_ref() {}
for _ in self.edges.by_ref() {}
let (alignment, size) =
calculate_allocation_generic::<K, V>(self.capacity, self.is_leaf);
let (alignment, size) = calculate_allocation_generic::<K, V>(self.capacity, self.is_leaf);
unsafe { heap::deallocate(*self.ptr, size, alignment) };
}
}
@ -1467,27 +1467,24 @@ pub type MoveTraversal<K, V> = AbsTraversal<MoveTraversalImpl<K, V>>;
impl<K, V, E, Impl> Iterator for AbsTraversal<Impl>
where Impl: TraversalImpl<Item=(K, V), Edge=E> {
where Impl: TraversalImpl<Item = (K, V), Edge = E>
{
type Item = TraversalItem<K, V, E>;
fn next(&mut self) -> Option<TraversalItem<K, V, E>> {
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<K, V, E, Impl> DoubleEndedIterator for AbsTraversal<Impl>
where Impl: TraversalImpl<Item=(K, V), Edge=E> {
where Impl: TraversalImpl<Item = (K, V), Edge = E>
{
fn next_back(&mut self) -> Option<TraversalItem<K, V, E>> {
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<K, V, E, Impl> AbsTraversal<Impl>
where Impl: TraversalImpl<Item=(K, V), Edge=E> {
impl<K, V, E, Impl> AbsTraversal<Impl> where Impl: TraversalImpl<Item = (K, V), Edge = E> {
/// 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<E> {

View File

@ -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<T>{
pub struct BTreeSet<T> {
map: BTreeMap<T, ()>,
}
/// 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<T> {
iter: Map<::btree_map::IntoIter<T, ()>, fn((T, ())) -> T>
iter: Map<::btree_map::IntoIter<T, ()>, 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<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// 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<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// 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<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
/// 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<Iter<'a, T>>,
b: Peekable<Iter<'a, T>>,
}
@ -161,12 +161,15 @@ impl<T: Ord> BTreeSet<T> {
#[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<Min> + Borrow<Max>,
-> Range<'a, T>
where T: Borrow<Min> + Borrow<Max>
{
fn first<A, B>((a, _): (A, B)) -> A { a }
fn first<A, B>((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<T: Ord> BTreeSet<T> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn difference<'a>(&'a self, other: &'a BTreeSet<T>) -> 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<T: Ord> BTreeSet<T> {
/// assert_eq!(sym_diff, [1, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn symmetric_difference<'a>(&'a self, other: &'a BTreeSet<T>)
-> SymmetricDifference<'a, T> {
SymmetricDifference{a: self.iter().peekable(), b: other.iter().peekable()}
pub fn symmetric_difference<'a>(&'a self,
other: &'a BTreeSet<T>)
-> 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<T: Ord> BTreeSet<T> {
/// assert_eq!(intersection, [2]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>)
-> Intersection<'a, T> {
Intersection{a: self.iter().peekable(), b: other.iter().peekable()}
pub fn intersection<'a>(&'a self, other: &'a BTreeSet<T>) -> 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<T: Ord> BTreeSet<T> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn union<'a>(&'a self, other: &'a BTreeSet<T>) -> 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<T: Ord> BTreeSet<T> {
/// 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<T: Ord> BTreeSet<T> {
/// 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<T: Ord> BTreeSet<T> {
/// assert_eq!(set.contains(&4), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
pub fn contains<Q: ?Sized>(&self, value: &Q) -> bool
where T: Borrow<Q>,
Q: Ord
{
self.map.contains_key(value)
}
@ -339,7 +361,10 @@ impl<T: Ord> BTreeSet<T> {
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
#[unstable(feature = "set_recovery", issue = "28050")]
pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T> where T: Borrow<Q>, Q: Ord {
pub fn get<Q: ?Sized>(&self, value: &Q) -> Option<&T>
where T: Borrow<Q>,
Q: Ord
{
Recover::get(&self.map, value)
}
@ -482,7 +507,10 @@ impl<T: Ord> BTreeSet<T> {
/// assert_eq!(set.remove(&2), false);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool where T: Borrow<Q>, Q: Ord {
pub fn remove<Q: ?Sized>(&mut self, value: &Q) -> bool
where T: Borrow<Q>,
Q: Ord
{
self.map.remove(value).is_some()
}
@ -492,14 +520,17 @@ impl<T: Ord> BTreeSet<T> {
/// but the ordering on the borrowed form *must* match the
/// ordering on the value type.
#[unstable(feature = "set_recovery", issue = "28050")]
pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T> where T: Borrow<Q>, Q: Ord {
pub fn take<Q: ?Sized>(&mut self, value: &Q) -> Option<T>
where T: Borrow<Q>,
Q: Ord
{
Recover::take(&mut self.map, value)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> FromIterator<T> for BTreeSet<T> {
fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> BTreeSet<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> BTreeSet<T> {
let mut set = BTreeSet::new();
set.extend(iter);
set
@ -524,7 +555,9 @@ impl<T> IntoIterator for BTreeSet<T> {
/// assert_eq!(v, [1, 2, 3, 4]);
/// ```
fn into_iter(self) -> IntoIter<T> {
fn first<A, B>((a, _): (A, B)) -> A { a }
fn first<A, B>((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<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Ord> Extend<T> for BTreeSet<T> {
#[inline]
fn extend<Iter: IntoIterator<Item=T>>(&mut self, iter: Iter) {
fn extend<Iter: IntoIterator<Item = T>>(&mut self, iter: Iter) {
for elem in iter {
self.insert(elem);
}
@ -553,7 +586,7 @@ impl<T: Ord> Extend<T> for BTreeSet<T> {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, T: 'a + Ord + Copy> Extend<&'a T> for BTreeSet<T> {
fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}
@ -665,18 +698,26 @@ impl<T: Debug> Debug for BTreeSet<T> {
}
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<usize>) { self.iter.size_hint() }
fn next(&mut self) -> Option<&'a T> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
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<T> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<T> { self.iter.next() }
fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() }
fn next(&mut self) -> Option<T> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> DoubleEndedIterator for IntoIter<T> {
fn next_back(&mut self) -> Option<T> { self.iter.next_back() }
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ExactSizeIterator for IntoIter<T> {}
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<T: Ord>(x: Option<&T>, y: Option<&T>,
short: Ordering, long: Ordering) -> Ordering {
fn cmp_opt<T: Ord>(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(),
}
}

View File

@ -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<E> {
impl<E> Copy for EnumSet<E> {}
impl<E> Clone for EnumSet<E> {
fn clone(&self) -> EnumSet<E> { *self }
fn clone(&self) -> EnumSet<E> {
*self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<E:CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
impl<E: CLike + fmt::Debug> fmt::Debug for EnumSet<E> {
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:CLike>(e: &E) -> usize {
fn bit<E: CLike>(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<E:CLike> EnumSet<E> {
impl<E: CLike> EnumSet<E> {
/// Returns an empty `EnumSet`.
pub fn new() -> EnumSet<E> {
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<E:CLike> EnumSet<E> {
/// Returns the union of both `EnumSets`.
pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
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<E>) -> EnumSet<E> {
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<E:CLike> EnumSet<E> {
}
}
impl<E:CLike> Sub for EnumSet<E> {
impl<E: CLike> Sub for EnumSet<E> {
type Output = EnumSet<E>;
fn sub(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & !e.bits, marker: marker::PhantomData}
EnumSet {
bits: self.bits & !e.bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> BitOr for EnumSet<E> {
impl<E: CLike> BitOr for EnumSet<E> {
type Output = EnumSet<E>;
fn bitor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits, marker: marker::PhantomData}
EnumSet {
bits: self.bits | e.bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> BitAnd for EnumSet<E> {
impl<E: CLike> BitAnd for EnumSet<E> {
type Output = EnumSet<E>;
fn bitand(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits, marker: marker::PhantomData}
EnumSet {
bits: self.bits & e.bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> BitXor for EnumSet<E> {
impl<E: CLike> BitXor for EnumSet<E> {
type Output = EnumSet<E>;
fn bitxor(self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits ^ e.bits, marker: marker::PhantomData}
EnumSet {
bits: self.bits ^ e.bits,
marker: marker::PhantomData,
}
}
}
@ -209,13 +231,17 @@ impl<E> Clone for Iter<E> {
}
}
impl<E:CLike> Iter<E> {
impl<E: CLike> Iter<E> {
fn new(bits: usize) -> Iter<E> {
Iter { index: 0, bits: bits, marker: marker::PhantomData }
Iter {
index: 0,
bits: bits,
marker: marker::PhantomData,
}
}
}
impl<E:CLike> Iterator for Iter<E> {
impl<E: CLike> Iterator for Iter<E> {
type Item = E;
fn next(&mut self) -> Option<E> {
@ -239,8 +265,8 @@ impl<E:CLike> Iterator for Iter<E> {
}
}
impl<E:CLike> FromIterator<E> for EnumSet<E> {
fn from_iter<I: IntoIterator<Item=E>>(iter: I) -> EnumSet<E> {
impl<E: CLike> FromIterator<E> for EnumSet<E> {
fn from_iter<I: IntoIterator<Item = E>>(iter: I) -> EnumSet<E> {
let mut ret = EnumSet::new();
ret.extend(iter);
ret
@ -248,7 +274,8 @@ impl<E:CLike> FromIterator<E> for EnumSet<E> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike
{
type Item = E;
type IntoIter = Iter<E>;
@ -257,8 +284,8 @@ impl<'a, E> IntoIterator for &'a EnumSet<E> where E: CLike {
}
}
impl<E:CLike> Extend<E> for EnumSet<E> {
fn extend<I: IntoIterator<Item=E>>(&mut self, iter: I) {
impl<E: CLike> Extend<E> for EnumSet<E> {
fn extend<I: IntoIterator<Item = E>>(&mut self, iter: I) {
for element in iter {
self.insert(element);
}
@ -267,7 +294,7 @@ impl<E:CLike> Extend<E> for EnumSet<E> {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, E: 'a + CLike + Copy> Extend<&'a E> for EnumSet<E> {
fn extend<I: IntoIterator<Item=&'a E>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = &'a E>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}

View File

@ -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;

View File

@ -44,8 +44,8 @@ struct Rawlink<T> {
}
impl<T> Copy for Rawlink<T> {}
unsafe impl<T:Send> Send for Rawlink<T> {}
unsafe impl<T:Sync> Sync for Rawlink<T> {}
unsafe impl<T: Send> Send for Rawlink<T> {}
unsafe impl<T: Sync> Sync for Rawlink<T> {}
struct Node<T> {
next: Link<T>,
@ -55,7 +55,7 @@ struct Node<T> {
/// 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<T>,
tail: Rawlink<Node<T>>,
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<T>,
head: Rawlink<Node<T>>,
tail: Rawlink<Node<T>>,
@ -86,19 +86,19 @@ pub struct IterMut<'a, T:'a> {
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct IntoIter<T> {
list: LinkedList<T>
list: LinkedList<T>,
}
/// Rawlink is a type like Option<T> but for holding a raw pointer
impl<T> Rawlink<T> {
/// Like Option::None for Rawlink
fn none() -> Rawlink<T> {
Rawlink{p: ptr::null_mut()}
Rawlink { p: ptr::null_mut() }
}
/// Like Option::Some for Rawlink
fn some(n: &mut T) -> Rawlink<T> {
Rawlink{p: n}
Rawlink { p: n }
}
/// Convert the `Rawlink` into an Option value
@ -139,13 +139,17 @@ impl<'a, T> From<&'a mut Link<T>> for Rawlink<Node<T>> {
impl<T> Clone for Rawlink<T> {
#[inline]
fn clone(&self) -> Rawlink<T> {
Rawlink{p: self.p}
Rawlink { p: self.p }
}
}
impl<T> Node<T> {
fn new(v: T) -> Node<T> {
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<T> LinkedList<T> {
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<T> LinkedList<T> {
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<T> LinkedList<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for LinkedList<T> {
#[inline]
fn default() -> LinkedList<T> { LinkedList::new() }
fn default() -> LinkedList<T> {
LinkedList::new()
}
}
impl<T> LinkedList<T> {
@ -238,7 +244,11 @@ impl<T> LinkedList<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> LinkedList<T> {
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<T> LinkedList<T> {
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<T> LinkedList<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn iter(&self) -> Iter<T> {
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<T> LinkedList<T> {
nelem: self.len(),
head: Rawlink::from(&mut self.list_head),
tail: self.list_tail,
list: self
list: self,
}
}
@ -452,9 +466,7 @@ impl<T> LinkedList<T> {
#[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<T> LinkedList<T> {
#[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<T> LinkedList<T> {
///
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop_front(&mut self) -> Option<T> {
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<T> LinkedList<T> {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop_back(&mut self) -> Option<T> {
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<T> LinkedList<T> {
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<T> LinkedList<T> {
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<A> Iterator for IntoIter<A> {
type Item = A;
#[inline]
fn next(&mut self) -> Option<A> { self.list.pop_front() }
fn next(&mut self) -> Option<A> {
self.list.pop_front()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
@ -854,7 +866,9 @@ impl<A> Iterator for IntoIter<A> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> DoubleEndedIterator for IntoIter<A> {
#[inline]
fn next_back(&mut self) -> Option<A> { self.list.pop_back() }
fn next_back(&mut self) -> Option<A> {
self.list.pop_back()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
@ -862,7 +876,7 @@ impl<A> ExactSizeIterator for IntoIter<A> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> FromIterator<A> for LinkedList<A> {
fn from_iter<T: IntoIterator<Item=A>>(iter: T) -> LinkedList<A> {
fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> LinkedList<A> {
let mut ret = LinkedList::new();
ret.extend(iter);
ret
@ -877,7 +891,7 @@ impl<T> IntoIterator for LinkedList<T> {
/// Consumes the list into an iterator yielding elements by value.
#[inline]
fn into_iter(self) -> IntoIter<T> {
IntoIter{list: self}
IntoIter { list: self }
}
}
@ -903,14 +917,16 @@ impl<'a, T> IntoIterator for &'a mut LinkedList<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> Extend<A> for LinkedList<A> {
fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
for elt in iter { self.push_back(elt); }
fn extend<T: IntoIterator<Item = A>>(&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<T> {
fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}
@ -918,13 +934,11 @@ impl<'a, T: 'a + Copy> Extend<&'a T> for LinkedList<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<A: PartialEq> PartialEq for LinkedList<A> {
fn eq(&self, other: &LinkedList<A>) -> bool {
self.len() == other.len() &&
self.iter().eq(other.iter())
self.len() == other.len() && self.iter().eq(other.iter())
}
fn ne(&self, other: &LinkedList<A>) -> bool {
self.len() != other.len() ||
self.iter().ne(other.iter())
self.len() != other.len() || self.iter().ne(other.iter())
}
}
@ -974,7 +988,7 @@ impl<A: Hash> Hash for LinkedList<A> {
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<T>> = None;
let mut node_ptr: &Node<T>;
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<T>, pptr as *const Node<T>);
}
@ -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::<Vec<_>>(), [-2,0,1,2,3,4,5,6,7,8,9,0,1]);
assert_eq!(m.into_iter().collect::<Vec<_>>(),
[-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::<Vec<_>>()[..]);
}).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);
}

View File

@ -22,26 +22,38 @@ pub trait RangeArgument<T> {
/// 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<T> RangeArgument<T> for RangeFull {}
impl<T> RangeArgument<T> for RangeFrom<T> {
fn start(&self) -> Option<&T> { Some(&self.start) }
fn start(&self) -> Option<&T> {
Some(&self.start)
}
}
impl<T> RangeArgument<T> for RangeTo<T> {
fn end(&self) -> Option<&T> { Some(&self.end) }
fn end(&self) -> Option<&T> {
Some(&self.end)
}
}
impl<T> RangeArgument<T> for Range<T> {
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)
}
}

View File

@ -156,7 +156,9 @@ mod hack {
}
#[inline]
pub fn to_vec<T>(s: &[T]) -> Vec<T> where T: Clone {
pub fn to_vec<T>(s: &[T]) -> Vec<T>
where T: Clone
{
let mut vector = Vec::with_capacity(s.len());
vector.push_all(s);
vector
@ -535,7 +537,9 @@ impl<T> [T] {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn split<F>(&self, pred: F) -> Split<T, F> where F: FnMut(&T) -> bool {
pub fn split<F>(&self, pred: F) -> Split<T, F>
where F: FnMut(&T) -> bool
{
core_slice::SliceExt::split(self, pred)
}
@ -543,7 +547,9 @@ impl<T> [T] {
/// match `pred`. The matched element is not contained in the subslices.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F> where F: FnMut(&T) -> bool {
pub fn split_mut<F>(&mut self, pred: F) -> SplitMut<T, F>
where F: FnMut(&T) -> bool
{
core_slice::SliceExt::split_mut(self, pred)
}
@ -567,7 +573,9 @@ impl<T> [T] {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F> where F: FnMut(&T) -> bool {
pub fn splitn<F>(&self, n: usize, pred: F) -> SplitN<T, F>
where F: FnMut(&T) -> bool
{
core_slice::SliceExt::splitn(self, n, pred)
}
@ -580,7 +588,8 @@ impl<T> [T] {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn splitn_mut<F>(&mut self, n: usize, pred: F) -> SplitNMut<T, F>
where F: FnMut(&T) -> bool {
where F: FnMut(&T) -> bool
{
core_slice::SliceExt::splitn_mut(self, n, pred)
}
@ -605,7 +614,9 @@ impl<T> [T] {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F> where F: FnMut(&T) -> bool {
pub fn rsplitn<F>(&self, n: usize, pred: F) -> RSplitN<T, F>
where F: FnMut(&T) -> bool
{
core_slice::SliceExt::rsplitn(self, n, pred)
}
@ -618,8 +629,9 @@ impl<T> [T] {
/// slice.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
where F: FnMut(&T) -> bool {
pub fn rsplitn_mut<F>(&mut self, n: usize, pred: F) -> RSplitNMut<T, F>
where F: FnMut(&T) -> bool
{
core_slice::SliceExt::rsplitn_mut(self, n, pred)
}
@ -633,7 +645,9 @@ impl<T> [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> [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> [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> [T] {
/// assert!(match r { Ok(1...4) => true, _ => false, });
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn binary_search(&self, x: &T) -> Result<usize, usize> where T: Ord {
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where T: Ord
{
core_slice::SliceExt::binary_search(self, x)
}
@ -729,7 +749,9 @@ impl<T> [T] {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize> where F: FnMut(&T) -> Ordering {
pub fn binary_search_by<F>(&self, f: F) -> Result<usize, usize>
where F: FnMut(&T) -> Ordering
{
core_slice::SliceExt::binary_search_by(self, f)
}
@ -749,7 +771,9 @@ impl<T> [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> [T] {
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn sort_by<F>(&mut self, compare: F) where F: FnMut(&T, &T) -> Ordering {
pub fn sort_by<F>(&mut self, compare: F)
where F: FnMut(&T, &T) -> Ordering
{
merge_sort(self, compare)
}
@ -796,14 +822,18 @@ impl<T> [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<T> where T: Clone {
pub fn to_vec(&self) -> Vec<T>
where T: Clone
{
// NB see hack module in this file
hack::to_vec(self)
}
@ -886,7 +916,11 @@ impl<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> 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<T: Clone, V: Borrow<[T]>> SliceConcatExt<T> for [V] {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Borrow<[T]> for Vec<T> {
fn borrow(&self) -> &[T] { &self[..] }
fn borrow(&self) -> &[T] {
&self[..]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> BorrowMut<[T]> for Vec<T> {
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<T: Clone> ToOwned for [T] {
type Owned = Vec<T>;
#[cfg(not(test))]
fn to_owned(&self) -> Vec<T> { self.to_vec() }
fn to_owned(&self) -> Vec<T> {
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<T> { panic!("not available with cfg(test)") }
fn to_owned(&self) -> Vec<T> {
panic!("not available with cfg(test)")
}
}
////////////////////////////////////////////////////////////////////////////////
// Sorting
////////////////////////////////////////////////////////////////////////////////
fn insertion_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
fn insertion_sort<T, F>(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<T, F>(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<T, F>(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<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> O
}
}
fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Ordering {
fn merge_sort<T, F>(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<T, F>(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<T, F>(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<T, F>(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<T, F>(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);
}
}

View File

@ -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<S: Borrow<str>> SliceConcatExt<str> 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::<usize>();
let len = sep.len() * (self.len() - 1) +
self.iter().map(|s| s.borrow().len()).sum::<usize>();
let mut result = String::with_capacity(len);
let mut first = true;
@ -122,7 +122,7 @@ impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
#[derive(Clone)]
#[unstable(feature = "str_utf16", issue = "27714")]
pub struct Utf16Units<'a> {
encoder: Utf16Encoder<Chars<'a>>
encoder: Utf16Encoder<Chars<'a>>,
}
#[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<u16> { self.encoder.next() }
fn next(&mut self) -> Option<u16> {
self.encoder.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
fn size_hint(&self) -> (usize, Option<usize>) {
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<str> 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<I: Iterator<Item=char>>(iter: I) -> bool {
fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
use rustc_unicode::derived_property::{Cased, Case_Ignorable};
match iter.skip_while(|&c| Case_Ignorable(c)).next() {
Some(c) => Cased(c),

View File

@ -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<u8>) -> Result<String, FromUtf8Error> {
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<char> {
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<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
pub fn drain<R>(&mut self, range: R) -> Drain
where R: RangeArgument<usize>
{
// 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<u8> { self.bytes }
pub fn into_bytes(self) -> Vec<u8> {
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<char> for String {
fn from_iter<I: IntoIterator<Item=char>>(iterable: I) -> String {
fn from_iter<I: IntoIterator<Item = char>>(iterable: I) -> String {
let mut buf = String::new();
buf.extend(iterable);
buf
@ -895,7 +900,7 @@ impl FromIterator<char> for String {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a> FromIterator<&'a str> for String {
fn from_iter<I: IntoIterator<Item=&'a str>>(iterable: I) -> String {
fn from_iter<I: IntoIterator<Item = &'a str>>(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<String> for String {
fn from_iter<I: IntoIterator<Item=String>>(iterable: I) -> String {
fn from_iter<I: IntoIterator<Item = String>>(iterable: I) -> String {
let mut buf = String::new();
buf.extend(iterable);
buf
@ -913,7 +918,7 @@ impl FromIterator<String> for String {
#[stable(feature = "rust1", since = "1.0.0")]
impl Extend<char> for String {
fn extend<I: IntoIterator<Item=char>>(&mut self, iterable: I) {
fn extend<I: IntoIterator<Item = char>>(&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<char> for String {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a> Extend<&'a char> for String {
fn extend<I: IntoIterator<Item=&'a char>>(&mut self, iterable: I) {
fn extend<I: IntoIterator<Item = &'a char>>(&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<I: IntoIterator<Item=&'a str>>(&mut self, iterable: I) {
fn extend<I: IntoIterator<Item = &'a str>>(&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<String> for String {
fn extend<I: IntoIterator<Item=String>>(&mut self, iterable: I) {
fn extend<I: IntoIterator<Item = String>>(&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 {

View File

@ -248,7 +248,10 @@ impl<T> Vec<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> Vec<T> {
Vec { buf: RawVec::new(), len: 0 }
Vec {
buf: RawVec::new(),
len: 0,
}
}
/// Constructs a new, empty `Vec<T>` with the specified capacity.
@ -280,7 +283,10 @@ impl<T> Vec<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn with_capacity(capacity: usize) -> Vec<T> {
Vec { buf: RawVec::with_capacity(capacity), len: 0 }
Vec {
buf: RawVec::with_capacity(capacity),
len: 0,
}
}
/// Creates a `Vec<T>` directly from the raw components of another vector.
@ -329,8 +335,7 @@ impl<T> Vec<T> {
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn from_raw_parts(ptr: *mut T, length: usize,
capacity: usize) -> Vec<T> {
pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
Vec {
buf: RawVec::from_raw_parts(ptr, capacity),
len: length,
@ -547,9 +552,12 @@ impl<T> Vec<T> {
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<T> Vec<T> {
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<T> Vec<T> {
/// assert_eq!(vec, [2, 4]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
pub fn retain<F>(&mut self, mut f: F)
where F: FnMut(&T) -> bool
{
let len = self.len();
let mut del = 0;
{
@ -623,7 +634,7 @@ impl<T> Vec<T> {
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<T> Vec<T> {
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<T> Vec<T> {
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<T> Vec<T> {
#[unstable(feature = "drain",
reason = "recently added, matches RFC",
issue = "27711")]
pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
pub fn drain<R>(&mut self, range: R) -> Drain<T>
where R: RangeArgument<usize>
{
// Memory safety
//
// When the Drain is first created, it shortens the length of
@ -760,9 +774,8 @@ impl<T> Vec<T> {
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<T> Vec<T> {
/// ```
#[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<T> Vec<T> {
/// 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<T> Vec<T> {
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<T: Clone> Vec<T> {
@ -937,9 +952,7 @@ impl<T: Clone> Vec<T> {
// 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<T: PartialEq> Vec<T> {
// 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<T: Clone>(elem: T, n: usize) -> Vec<T> {
////////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Clone> Clone for Vec<T> {
impl<T: Clone> Clone for Vec<T> {
#[cfg(not(test))]
fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) }
fn clone(&self) -> Vec<T> {
<[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<T> ops::Index<ops::RangeFull> for Vec<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
#[inline]
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
IndexMut::index_mut(&mut **self, index)
@ -1166,7 +1182,6 @@ impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
#[inline]
fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
IndexMut::index_mut(&mut **self, index)
@ -1174,7 +1189,6 @@ impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
#[inline]
fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
IndexMut::index_mut(&mut **self, index)
@ -1182,7 +1196,6 @@ impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
#[inline]
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
self
@ -1216,7 +1229,7 @@ impl<T> ops::DerefMut for Vec<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> FromIterator<T> for Vec<T> {
#[inline]
fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Vec<T> {
fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Vec<T> {
// 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<T> IntoIterator for Vec<T> {
};
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<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Extend<T> for Vec<T> {
#[inline]
fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
self.extend_desugared(iterable.into_iter())
}
}
impl<T> Vec<T> {
fn extend_desugared<I: Iterator<Item=T>>(&mut self, mut iterator: I) {
fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
// This function should be the moral equivalent of:
//
// for item in iterator {
@ -1328,7 +1345,7 @@ impl<T> Vec<T> {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}
@ -1466,7 +1483,7 @@ impl<'a> From<&'a str> for Vec<u8> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
fn from_iter<I: IntoIterator<Item=T>>(it: I) -> Cow<'a, [T]> {
fn from_iter<I: IntoIterator<Item = T>>(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<T> {
_buf: RawVec<T>,
ptr: *const T,
end: *const T
end: *const T,
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: Send> Send for IntoIter<T> { }
unsafe impl<T: Send> Send for IntoIter<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: Sync> Sync for IntoIter<T> { }
unsafe impl<T: Sync> Sync for IntoIter<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Iterator for IntoIter<T> {
@ -1534,7 +1551,12 @@ impl<T> Iterator for IntoIter<T> {
fn size_hint(&self) -> (usize, Option<usize>) {
let diff = (self.end as usize) - (self.ptr as usize);
let size = mem::size_of::<T>();
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<T> {
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<usize>) {
@ -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<T> {
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 {

View File

@ -52,7 +52,6 @@ pub struct VecDeque<T> {
// 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<T>,
@ -77,7 +76,9 @@ impl<T> Drop for VecDeque<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for VecDeque<T> {
#[inline]
fn default() -> VecDeque<T> { VecDeque::new() }
fn default() -> VecDeque<T> {
VecDeque::new()
}
}
impl<T> VecDeque<T> {
@ -124,12 +125,16 @@ impl<T> VecDeque<T> {
/// 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<T> VecDeque<T> {
/// 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<T> VecDeque<T> {
/// 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<T> VecDeque<T> {
// 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<T> VecDeque<T> {
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<T> VecDeque<T> {
/// ```
#[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<T> VecDeque<T> {
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<T> VecDeque<T> {
Iter {
tail: self.tail,
head: self.head,
ring: unsafe { self.buffer_as_slice() }
ring: unsafe { self.buffer_as_slice() },
}
}
@ -681,7 +718,7 @@ impl<T> VecDeque<T> {
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<T> VecDeque<T> {
/// 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<T> VecDeque<T> {
/// 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<T> VecDeque<T> {
#[unstable(feature = "drain",
reason = "matches collection reform specification, waiting for dust to settle",
issue = "27711")]
pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
pub fn drain<R>(&mut self, range: R) -> Drain<T>
where R: RangeArgument<usize>
{
// Memory safety
//
// When the Drain is first created, the source deque is shortened to
@ -839,7 +882,11 @@ impl<T> VecDeque<T> {
/// ```
#[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<T> VecDeque<T> {
/// ```
#[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<T> VecDeque<T> {
/// ```
#[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<T> VecDeque<T> {
#[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<T> VecDeque<T> {
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<T> VecDeque<T> {
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<T> VecDeque<T> {
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<T> VecDeque<T> {
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<T> VecDeque<T> {
//
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
}
(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);
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.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.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(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.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 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);
// 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);
// move elements from idx to end forward not including ^ element
self.copy(idx + 1, idx, self.cap() - 1 - idx);
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
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 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);
// copy last element into empty spot at bottom of buffer
self.copy(self.cap() - 1, 0, 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
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 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);
// 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);
// move elements from idx-1 to end forward not including ^ element
self.copy(0, 1, idx - 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.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;
self.copy(idx + 1, idx, self.head - idx);
self.head += 1;
}
}
}
@ -1357,121 +1440,133 @@ impl<T> VecDeque<T> {
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
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.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.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.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
// draw in elements up to idx
self.copy(1, 0, idx);
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
// copy last element into empty spot
self.copy(0, self.cap() - 1, 1);
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
// move elements from tail to end forward, excluding the last one
self.copy(self.tail + 1, self.tail, self.cap() - self.tail - 1);
// draw in elements in the tail section
self.copy(idx, idx + 1, self.cap() - idx - 1);
self.tail = self.wrap_add(self.tail, 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
// draw in elements up to idx
self.copy(1, 0, idx);
// 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);
self.tail = self.wrap_add(self.tail, 1);
}
}
}
@ -1587,14 +1682,16 @@ impl<T> VecDeque<T> {
/// assert_eq!(&v[..], &[2, 4]);
/// ```
#[stable(feature = "vec_deque_retain", since = "1.4.0")]
pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
pub fn retain<F>(&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<T> {
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<T> {
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<A: PartialEq> PartialEq for VecDeque<A> {
fn eq(&self, other: &VecDeque<A>) -> 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<A> IndexMut<usize> for VecDeque<A> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> FromIterator<A> for VecDeque<A> {
fn from_iter<T: IntoIterator<Item=A>>(iterable: T) -> VecDeque<A> {
fn from_iter<T: IntoIterator<Item = A>>(iterable: T) -> VecDeque<A> {
let iterator = iterable.into_iter();
let (lower, _) = iterator.size_hint();
let mut deq = VecDeque::with_capacity(lower);
@ -1965,9 +2055,7 @@ impl<T> IntoIterator for VecDeque<T> {
/// Consumes the list into a front-to-back iterator yielding elements by
/// value.
fn into_iter(self) -> IntoIter<T> {
IntoIter {
inner: self,
}
IntoIter { inner: self }
}
}
@ -1993,7 +2081,7 @@ impl<'a, T> IntoIterator for &'a mut VecDeque<T> {
#[stable(feature = "rust1", since = "1.0.0")]
impl<A> Extend<A> for VecDeque<A> {
fn extend<T: IntoIterator<Item=A>>(&mut self, iter: T) {
fn extend<T: IntoIterator<Item = A>>(&mut self, iter: T) {
for elt in iter {
self.push_back(elt);
}
@ -2002,7 +2090,7 @@ impl<A> Extend<A> for VecDeque<A> {
#[stable(feature = "extend_ref", since = "1.2.0")]
impl<'a, T: 'a + Copy> Extend<&'a T> for VecDeque<T> {
fn extend<I: IntoIterator<Item=&'a T>>(&mut self, iter: I) {
fn extend<I: IntoIterator<Item = &'a T>>(&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::<i32>::with_capacity(101);
let mut deq = VecDeque::<i32>::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);
}
}