rust/src/libcollections/dlist.rs

1324 lines
36 KiB
Rust
Raw Normal View History

Deprecate the rev_iter pattern in all places where a DoubleEndedIterator is provided (everywhere but treemap) This commit deprecates rev_iter, mut_rev_iter, move_rev_iter everywhere (except treemap) and also deprecates related functions like rsplit, rev_components, and rev_str_components. In every case, these functions can be replaced with the non-reversed form followed by a call to .rev(). To make this more concrete, a translation table for all functional changes necessary follows: * container.rev_iter() -> container.iter().rev() * container.mut_rev_iter() -> container.mut_iter().rev() * container.move_rev_iter() -> container.move_iter().rev() * sliceorstr.rsplit(sep) -> sliceorstr.split(sep).rev() * path.rev_components() -> path.components().rev() * path.rev_str_components() -> path.str_components().rev() In terms of the type system, this change also deprecates any specialized reversed iterator types (except in treemap), opting instead to use Rev directly if any type annotations are needed. However, since methods directly returning reversed iterators are now discouraged, the need for such annotations should be small. However, in those cases, the general pattern for conversion is to take whatever follows Rev in the original reversed name and surround it with Rev<>: * RevComponents<'a> -> Rev<Components<'a>> * RevStrComponents<'a> -> Rev<StrComponents<'a>> * RevItems<'a, T> -> Rev<Items<'a, T>> * etc. The reasoning behind this change is that it makes the standard API much simpler without reducing readability, performance, or power. The presence of functions such as rev_iter adds more boilerplate code to libraries (all of which simply call .iter().rev()), clutters up the documentation, and only helps code by saving two characters. Additionally, the numerous type synonyms that were used to make the type signatures look nice like RevItems add even more boilerplate and clutter up the docs even more. With this change, all that cruft goes away. [breaking-change]
2014-04-20 23:59:12 -05:00
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2013-07-10 09:06:09 -05:00
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A doubly-linked list with owned nodes.
//!
2014-08-04 05:48:39 -05:00
//! The `DList` allows pushing and popping elements at either end.
//!
2014-08-04 05:48:39 -05:00
//! `DList` implements the trait `Deque`. It should be imported with
//! `use collections::Deque`.
// DList is constructed like a singly-linked list over the field `next`.
// including the last link being None; each Node owns its `next` field.
//
// Backlinks over DList::prev are raw pointers that form a full chain in
// the reverse direction.
std: Recreate a `collections` module As with the previous commit with `librand`, this commit shuffles around some `collections` code. The new state of the world is similar to that of librand: * The libcollections crate now only depends on libcore and liballoc. * The standard library has a new module, `std::collections`. All functionality of libcollections is reexported through this module. I would like to stress that this change is purely cosmetic. There are very few alterations to these primitives. There are a number of notable points about the new organization: * std::{str, slice, string, vec} all moved to libcollections. There is no reason that these primitives shouldn't be necessarily usable in a freestanding context that has allocation. These are all reexported in their usual places in the standard library. * The `hashmap`, and transitively the `lru_cache`, modules no longer reside in `libcollections`, but rather in libstd. The reason for this is because the `HashMap::new` contructor requires access to the OSRng for initially seeding the hash map. Beyond this requirement, there is no reason that the hashmap could not move to libcollections. I do, however, have a plan to move the hash map to the collections module. The `HashMap::new` function could be altered to require that the `H` hasher parameter ascribe to the `Default` trait, allowing the entire `hashmap` module to live in libcollections. The key idea would be that the default hasher would be different in libstd. Something along the lines of: // src/libstd/collections/mod.rs pub type HashMap<K, V, H = RandomizedSipHasher> = core_collections::HashMap<K, V, H>; This is not possible today because you cannot invoke static methods through type aliases. If we modified the compiler, however, to allow invocation of static methods through type aliases, then this type definition would essentially be switching the default hasher from `SipHasher` in libcollections to a libstd-defined `RandomizedSipHasher` type. This type's `Default` implementation would randomly seed the `SipHasher` instance, and otherwise perform the same as `SipHasher`. This future state doesn't seem incredibly far off, but until that time comes, the hashmap module will live in libstd to not compromise on functionality. * In preparation for the hashmap moving to libcollections, the `hash` module has moved from libstd to libcollections. A previously snapshotted commit enables a distinct `Writer` trait to live in the `hash` module which `Hash` implementations are now parameterized over. Due to using a custom trait, the `SipHasher` implementation has lost its specialized methods for writing integers. These can be re-added backwards-compatibly in the future via default methods if necessary, but the FNV hashing should satisfy much of the need for speedier hashing. A list of breaking changes: * HashMap::{get, get_mut} no longer fails with the key formatted into the error message with `{:?}`, instead, a generic message is printed. With backtraces, it should still be not-too-hard to track down errors. * The HashMap, HashSet, and LruCache types are now available through std::collections instead of the collections crate. * Manual implementations of hash should be parameterized over `hash::Writer` instead of just `Writer`. [breaking-change]
2014-05-29 20:50:12 -05:00
use core::prelude::*;
use alloc::boxed::Box;
use core::default::Default;
2014-06-07 08:01:44 -05:00
use core::fmt;
std: Recreate a `collections` module As with the previous commit with `librand`, this commit shuffles around some `collections` code. The new state of the world is similar to that of librand: * The libcollections crate now only depends on libcore and liballoc. * The standard library has a new module, `std::collections`. All functionality of libcollections is reexported through this module. I would like to stress that this change is purely cosmetic. There are very few alterations to these primitives. There are a number of notable points about the new organization: * std::{str, slice, string, vec} all moved to libcollections. There is no reason that these primitives shouldn't be necessarily usable in a freestanding context that has allocation. These are all reexported in their usual places in the standard library. * The `hashmap`, and transitively the `lru_cache`, modules no longer reside in `libcollections`, but rather in libstd. The reason for this is because the `HashMap::new` contructor requires access to the OSRng for initially seeding the hash map. Beyond this requirement, there is no reason that the hashmap could not move to libcollections. I do, however, have a plan to move the hash map to the collections module. The `HashMap::new` function could be altered to require that the `H` hasher parameter ascribe to the `Default` trait, allowing the entire `hashmap` module to live in libcollections. The key idea would be that the default hasher would be different in libstd. Something along the lines of: // src/libstd/collections/mod.rs pub type HashMap<K, V, H = RandomizedSipHasher> = core_collections::HashMap<K, V, H>; This is not possible today because you cannot invoke static methods through type aliases. If we modified the compiler, however, to allow invocation of static methods through type aliases, then this type definition would essentially be switching the default hasher from `SipHasher` in libcollections to a libstd-defined `RandomizedSipHasher` type. This type's `Default` implementation would randomly seed the `SipHasher` instance, and otherwise perform the same as `SipHasher`. This future state doesn't seem incredibly far off, but until that time comes, the hashmap module will live in libstd to not compromise on functionality. * In preparation for the hashmap moving to libcollections, the `hash` module has moved from libstd to libcollections. A previously snapshotted commit enables a distinct `Writer` trait to live in the `hash` module which `Hash` implementations are now parameterized over. Due to using a custom trait, the `SipHasher` implementation has lost its specialized methods for writing integers. These can be re-added backwards-compatibly in the future via default methods if necessary, but the FNV hashing should satisfy much of the need for speedier hashing. A list of breaking changes: * HashMap::{get, get_mut} no longer fails with the key formatted into the error message with `{:?}`, instead, a generic message is printed. With backtraces, it should still be not-too-hard to track down errors. * The HashMap, HashSet, and LruCache types are now available through std::collections instead of the collections crate. * Manual implementations of hash should be parameterized over `hash::Writer` instead of just `Writer`. [breaking-change]
2014-05-29 20:50:12 -05:00
use core::iter;
use core::mem;
use core::ptr;
2014-07-29 15:24:06 -05:00
use std::hash::{Writer, Hash};
use {Mutable, Deque, MutableSeq};
2013-07-10 08:27:15 -05:00
/// A doubly-linked list.
pub struct DList<T> {
length: uint,
list_head: Link<T>,
list_tail: Rawlink<Node<T>>,
}
type Link<T> = Option<Box<Node<T>>>;
struct Rawlink<T> { p: *mut T }
struct Node<T> {
next: Link<T>,
prev: Rawlink<Node<T>>,
value: T,
}
/// An iterator over references to the items of a `DList`.
pub struct Items<'a, T:'a> {
head: &'a Link<T>,
tail: Rawlink<Node<T>>,
nelem: uint,
}
// FIXME #11820: the &'a Option<> of the Link stops clone working.
impl<'a, T> Clone for Items<'a, T> {
fn clone(&self) -> Items<'a, T> { *self }
}
/// An iterator over mutable references to the items of a `DList`.
pub struct MutItems<'a, T:'a> {
list: &'a mut DList<T>,
head: Rawlink<Node<T>>,
tail: Rawlink<Node<T>>,
nelem: uint,
}
/// An iterator over mutable references to the items of a `DList`.
#[deriving(Clone)]
pub struct MoveItems<T> {
list: DList<T>
2012-08-27 16:22:25 -05:00
}
/// 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> {
2014-09-14 22:27:36 -05:00
Rawlink{p: ptr::null_mut()}
}
/// Like Option::Some for Rawlink
fn some(n: &mut T) -> Rawlink<T> {
2014-02-14 17:42:01 -06:00
Rawlink{p: n}
}
/// Convert the `Rawlink` into an Option value
fn resolve_immut<'a>(&self) -> Option<&'a T> {
unsafe {
self.p.as_ref()
}
}
/// Convert the `Rawlink` into an Option value
fn resolve<'a>(&mut self) -> Option<&'a mut T> {
if self.p.is_null() {
None
} else {
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 12:34:51 -05:00
Some(unsafe { mem::transmute(self.p) })
}
}
/// Return the `Rawlink` and replace with `Rawlink::none()`
fn take(&mut self) -> Rawlink<T> {
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 12:34:51 -05:00
mem::replace(self, Rawlink::none())
}
}
impl<T> Clone for Rawlink<T> {
#[inline]
fn clone(&self) -> Rawlink<T> {
Rawlink{p: self.p}
}
}
impl<T> Node<T> {
fn new(v: T) -> Node<T> {
Node{value: v, next: None, prev: Rawlink::none()}
}
}
/// Set the .prev field on `next`, then return `Some(next)`
fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
-> Link<T> {
next.prev = prev;
Some(next)
}
impl<T> Collection for DList<T> {
2014-08-04 05:48:39 -05:00
/// Returns `true` if the `DList` is empty.
///
/// This operation should compute in O(1) time.
#[inline]
fn is_empty(&self) -> bool {
self.list_head.is_none()
}
2014-08-04 05:48:39 -05:00
/// Returns the length of the `DList`.
///
/// This operation should compute in O(1) time.
#[inline]
fn len(&self) -> uint {
self.length
}
}
impl<T> Mutable for DList<T> {
2014-08-04 05:48:39 -05:00
/// Removes all elements from the `DList`.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(n) time.
#[inline]
fn clear(&mut self) {
*self = DList::new()
}
}
// private methods
impl<T> DList<T> {
/// Add a Node first in the list
#[inline]
fn push_front_node(&mut self, mut new_head: Box<Node<T>>) {
match self.list_head {
None => {
self.list_tail = Rawlink::some(&mut *new_head);
self.list_head = link_with_prev(new_head, Rawlink::none());
}
Some(ref mut head) => {
new_head.prev = Rawlink::none();
head.prev = Rawlink::some(&mut *new_head);
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 12:34:51 -05:00
mem::swap(head, &mut new_head);
head.next = Some(new_head);
}
}
self.length += 1;
}
/// Remove the first Node and return it, or None if the list is empty
#[inline]
fn pop_front_node(&mut self) -> Option<Box<Node<T>>> {
self.list_head.take().map(|mut front_node| {
self.length -= 1;
match front_node.next.take() {
Some(node) => self.list_head = link_with_prev(node, Rawlink::none()),
None => self.list_tail = Rawlink::none()
}
front_node
})
}
/// Add a Node last in the list
#[inline]
fn push_back_node(&mut self, mut new_tail: Box<Node<T>>) {
match self.list_tail.resolve() {
None => return self.push_front_node(new_tail),
Some(tail) => {
self.list_tail = Rawlink::some(&mut *new_tail);
tail.next = link_with_prev(new_tail, Rawlink::some(tail));
}
}
self.length += 1;
}
/// Remove the last Node and return it, or None if the list is empty
#[inline]
fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
self.list_tail.resolve().map_or(None, |tail| {
self.length -= 1;
self.list_tail = tail.prev;
match tail.prev.resolve() {
None => self.list_head.take(),
Some(tail_prev) => tail_prev.next.take()
}
})
}
}
impl<T> Deque<T> for DList<T> {
2014-08-04 05:48:39 -05:00
/// Provides a reference to the front element, or `None` if the list is
/// empty.
#[inline]
2013-07-10 08:27:15 -05:00
fn front<'a>(&'a self) -> Option<&'a T> {
self.list_head.as_ref().map(|head| &head.value)
}
2014-08-04 05:48:39 -05:00
/// Provides a mutable reference to the front element, or `None` if the list
/// is empty.
#[inline]
2013-07-10 08:27:15 -05:00
fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
self.list_head.as_mut().map(|head| &mut head.value)
}
2014-08-04 05:48:39 -05:00
/// Provides a reference to the back element, or `None` if the list is
/// empty.
#[inline]
2013-07-10 08:27:15 -05:00
fn back<'a>(&'a self) -> Option<&'a T> {
self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
}
2014-08-04 05:48:39 -05:00
/// Provides a mutable reference to the back element, or `None` if the list
/// is empty.
#[inline]
2013-07-10 08:27:15 -05:00
fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
self.list_tail.resolve().map(|tail| &mut tail.value)
}
2014-08-04 05:48:39 -05:00
/// Adds an element first in the list.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(1) time.
fn push_front(&mut self, elt: T) {
2014-04-25 03:08:02 -05:00
self.push_front_node(box Node::new(elt))
}
2014-08-04 05:48:39 -05:00
/// Removes the first element and returns it, or `None` if the list is
/// empty.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(1) time.
fn pop_front(&mut self) -> Option<T> {
self.pop_front_node().map(|box Node{value, ..}| value)
}
}
impl<T> MutableSeq<T> for DList<T> {
fn push(&mut self, elt: T) {
2014-04-25 03:08:02 -05:00
self.push_back_node(box Node::new(elt))
}
fn pop(&mut self) -> Option<T> {
self.pop_back_node().map(|box Node{value, ..}| value)
}
2013-07-10 08:27:15 -05:00
}
impl<T> Default for DList<T> {
#[inline]
fn default() -> DList<T> { DList::new() }
}
impl<T> DList<T> {
2014-08-04 05:48:39 -05:00
/// Creates an empty `DList`.
2013-07-10 08:27:15 -05:00
#[inline]
pub fn new() -> DList<T> {
DList{list_head: None, list_tail: Rawlink::none(), length: 0}
2013-07-10 08:27:15 -05:00
}
2014-08-04 05:48:39 -05:00
/// Moves the last element to the front of the list.
///
2014-08-04 05:48:39 -05:00
/// If the list is empty, does nothing.
///
/// # Example
///
/// ```rust
2014-07-20 19:57:29 -05:00
/// use std::collections::DList;
///
/// let mut dl = DList::new();
2014-07-20 19:57:29 -05:00
/// dl.push(1i);
/// dl.push(2);
/// dl.push(3);
///
/// dl.rotate_forward();
///
/// for e in dl.iter() {
/// println!("{}", e); // prints 3, then 1, then 2
/// }
/// ```
#[inline]
pub fn rotate_forward(&mut self) {
self.pop_back_node().map(|tail| {
self.push_front_node(tail)
});
}
2014-08-04 05:48:39 -05:00
/// Moves the first element to the back of the list.
///
2014-08-04 05:48:39 -05:00
/// If the list is empty, does nothing.
///
/// # Example
///
/// ```rust
2014-07-20 19:57:29 -05:00
/// use std::collections::DList;
///
/// let mut dl = DList::new();
2014-07-20 19:57:29 -05:00
/// dl.push(1i);
/// dl.push(2);
/// dl.push(3);
///
/// dl.rotate_backward();
///
/// for e in dl.iter() {
/// println!("{}", e); // prints 2, then 3, then 1
/// }
/// ```
#[inline]
pub fn rotate_backward(&mut self) {
self.pop_front_node().map(|head| {
self.push_back_node(head)
});
}
2014-08-04 05:48:39 -05:00
/// Adds all elements from `other` to the end of the list.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(1) time.
///
/// # Example
///
/// ```rust
2014-07-20 19:57:29 -05:00
/// use std::collections::DList;
///
/// let mut a = DList::new();
/// let mut b = DList::new();
2014-07-20 19:57:29 -05:00
/// a.push(1i);
/// a.push(2);
/// b.push(3i);
/// b.push(4);
///
/// a.append(b);
///
/// for e in a.iter() {
/// println!("{}", e); // prints 1, then 2, then 3, then 4
/// }
/// ```
pub fn append(&mut self, mut other: DList<T>) {
match self.list_tail.resolve() {
None => *self = other,
Some(tail) => {
// Carefully empty `other`.
let o_tail = other.list_tail.take();
let o_length = other.length;
match other.list_head.take() {
None => return,
Some(node) => {
tail.next = link_with_prev(node, self.list_tail);
self.list_tail = o_tail;
self.length += o_length;
}
}
2012-09-21 21:37:57 -05:00
}
}
}
2014-08-04 05:48:39 -05:00
/// Adds all elements from `other` to the beginning of the list.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(1) time.
///
/// # Example
///
/// ```rust
2014-07-20 19:57:29 -05:00
/// use std::collections::DList;
///
/// let mut a = DList::new();
/// let mut b = DList::new();
2014-07-20 19:57:29 -05:00
/// a.push(1i);
/// a.push(2);
/// b.push(3i);
/// b.push(4);
///
/// a.prepend(b);
///
/// for e in a.iter() {
/// println!("{}", e); // prints 3, then 4, then 1, then 2
/// }
/// ```
#[inline]
pub fn prepend(&mut self, mut other: DList<T>) {
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 12:34:51 -05:00
mem::swap(self, &mut other);
self.append(other);
}
2014-08-04 05:48:39 -05:00
/// Inserts `elt` before the first `x` in the list where `f(x, elt)` is
/// true, or at the end.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(N) time.
///
/// # Example
///
/// ```rust
2014-07-20 19:57:29 -05:00
/// use std::collections::DList;
///
/// let mut a: DList<int> = DList::new();
2014-07-20 19:57:29 -05:00
/// a.push(2i);
/// a.push(4);
/// a.push(7);
/// a.push(8);
///
/// // insert 11 before the first odd number in the list
/// a.insert_when(11, |&e, _| e % 2 == 1);
///
/// for e in a.iter() {
/// println!("{}", e); // prints 2, then 4, then 11, then 7, then 8
/// }
/// ```
pub fn insert_when(&mut self, elt: T, f: |&T, &T| -> bool) {
{
2014-09-14 22:27:36 -05:00
let mut it = self.iter_mut();
loop {
match it.peek_next() {
None => break,
Some(x) => if f(x, &elt) { break }
}
it.next();
}
it.insert_next(elt);
}
}
2014-08-04 05:48:39 -05:00
/// Merges `other` into this `DList`, using the function `f`.
///
/// Iterates both `DList`s with `a` from self and `b` from `other`, and
/// put `a` in the result if `f(a, b)` is true, and otherwise `b`.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(max(N, M)) time.
pub fn merge(&mut self, mut other: DList<T>, f: |&T, &T| -> bool) {
{
2014-09-14 22:27:36 -05:00
let mut it = self.iter_mut();
loop {
let take_a = match (it.peek_next(), other.front()) {
(_ , None) => return,
(None, _ ) => break,
(Some(ref mut x), Some(y)) => f(*x, y),
};
if take_a {
it.next();
} else {
it.insert_next_node(other.pop_front_node().unwrap());
}
2012-09-21 21:37:57 -05:00
}
}
self.append(other);
}
2014-08-04 05:48:39 -05:00
/// Provides a forward iterator.
#[inline]
pub fn iter<'a>(&'a self) -> Items<'a, T> {
Items{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
}
2014-08-04 05:48:39 -05:00
/// Provides a forward iterator with mutable references.
#[inline]
pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
let head_raw = match self.list_head {
Some(ref mut h) => Rawlink::some(&mut **h),
None => Rawlink::none(),
};
MutItems{
nelem: self.len(),
head: head_raw,
tail: self.list_tail,
list: self
}
}
Deprecate the rev_iter pattern in all places where a DoubleEndedIterator is provided (everywhere but treemap) This commit deprecates rev_iter, mut_rev_iter, move_rev_iter everywhere (except treemap) and also deprecates related functions like rsplit, rev_components, and rev_str_components. In every case, these functions can be replaced with the non-reversed form followed by a call to .rev(). To make this more concrete, a translation table for all functional changes necessary follows: * container.rev_iter() -> container.iter().rev() * container.mut_rev_iter() -> container.mut_iter().rev() * container.move_rev_iter() -> container.move_iter().rev() * sliceorstr.rsplit(sep) -> sliceorstr.split(sep).rev() * path.rev_components() -> path.components().rev() * path.rev_str_components() -> path.str_components().rev() In terms of the type system, this change also deprecates any specialized reversed iterator types (except in treemap), opting instead to use Rev directly if any type annotations are needed. However, since methods directly returning reversed iterators are now discouraged, the need for such annotations should be small. However, in those cases, the general pattern for conversion is to take whatever follows Rev in the original reversed name and surround it with Rev<>: * RevComponents<'a> -> Rev<Components<'a>> * RevStrComponents<'a> -> Rev<StrComponents<'a>> * RevItems<'a, T> -> Rev<Items<'a, T>> * etc. The reasoning behind this change is that it makes the standard API much simpler without reducing readability, performance, or power. The presence of functions such as rev_iter adds more boilerplate code to libraries (all of which simply call .iter().rev()), clutters up the documentation, and only helps code by saving two characters. Additionally, the numerous type synonyms that were used to make the type signatures look nice like RevItems add even more boilerplate and clutter up the docs even more. With this change, all that cruft goes away. [breaking-change]
2014-04-20 23:59:12 -05:00
2014-08-04 05:48:39 -05:00
/// Consumes the list into an iterator yielding elements by value.
#[inline]
pub fn into_iter(self) -> MoveItems<T> {
MoveItems{list: self}
}
}
impl<T: Ord> DList<T> {
2014-08-04 05:48:39 -05:00
/// Inserts `elt` sorted in ascending order.
///
2014-08-04 05:48:39 -05:00
/// This operation should compute in O(N) time.
#[inline]
pub fn insert_ordered(&mut self, elt: T) {
self.insert_when(elt, |a, b| a >= b)
}
}
#[unsafe_destructor]
impl<T> Drop for DList<T> {
2013-09-16 20:18:07 -05:00
fn drop(&mut self) {
// Dissolve the dlist in backwards direction
// Just dropping the list_head can lead to stack exhaustion
// when length is >> 1_000_000
2013-09-16 20:18:07 -05:00
let mut tail = self.list_tail;
loop {
match tail.resolve() {
None => break,
Some(prev) => {
prev.next.take(); // release Box<Node<T>>
tail = prev.prev;
}
}
}
2013-09-16 20:18:07 -05:00
self.length = 0;
self.list_head = None;
self.list_tail = Rawlink::none();
}
}
impl<'a, A> Iterator<&'a A> for Items<'a, A> {
#[inline]
fn next(&mut self) -> Option<&'a A> {
if self.nelem == 0 {
return None;
}
self.head.as_ref().map(|head| {
self.nelem -= 1;
self.head = &head.next;
&head.value
})
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(self.nelem, Some(self.nelem))
}
}
impl<'a, A> DoubleEndedIterator<&'a A> for Items<'a, A> {
#[inline]
fn next_back(&mut self) -> Option<&'a A> {
if self.nelem == 0 {
return None;
}
self.tail.resolve_immut().as_ref().map(|prev| {
self.nelem -= 1;
self.tail = prev.prev;
&prev.value
})
}
}
impl<'a, A> ExactSize<&'a A> for Items<'a, A> {}
impl<'a, A> Iterator<&'a mut A> for MutItems<'a, A> {
#[inline]
fn next(&mut self) -> Option<&'a mut A> {
if self.nelem == 0 {
return None;
}
self.head.resolve().map(|next| {
self.nelem -= 1;
self.head = match next.next {
Some(ref mut node) => Rawlink::some(&mut **node),
None => Rawlink::none(),
};
&mut next.value
})
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(self.nelem, Some(self.nelem))
}
}
impl<'a, A> DoubleEndedIterator<&'a mut A> for MutItems<'a, A> {
#[inline]
fn next_back(&mut self) -> Option<&'a mut A> {
if self.nelem == 0 {
return None;
}
self.tail.resolve().map(|prev| {
self.nelem -= 1;
self.tail = prev.prev;
&mut prev.value
})
2013-01-24 17:40:46 -06:00
}
}
impl<'a, A> ExactSize<&'a mut A> for MutItems<'a, A> {}
2014-08-04 05:48:39 -05:00
/// Allows mutating a `DList` while iterating.
pub trait ListInsertion<A> {
2014-08-04 05:48:39 -05:00
/// Inserts `elt` just after to the element most recently returned by
/// `.next()`
///
/// The inserted element does not appear in the iteration.
fn insert_next(&mut self, elt: A);
2014-08-04 05:48:39 -05:00
/// Provides a reference to the next element, without changing the iterator
fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
}
2013-01-24 17:40:46 -06:00
// private methods for MutItems
impl<'a, A> MutItems<'a, A> {
fn insert_next_node(&mut self, mut ins_node: Box<Node<A>>) {
// Insert before `self.head` so that it is between the
// previously yielded element and self.head.
//
// The inserted node will not appear in further iteration.
match self.head.resolve() {
None => { self.list.push_back_node(ins_node); }
Some(node) => {
let prev_node = match node.prev.resolve() {
None => return self.list.push_front_node(ins_node),
Some(prev) => prev,
};
2014-08-18 19:52:38 -05:00
let node_own = prev_node.next.take().unwrap();
ins_node.next = link_with_prev(node_own, Rawlink::some(&mut *ins_node));
prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node));
self.list.length += 1;
}
}
2013-01-24 17:40:46 -06:00
}
}
impl<'a, A> ListInsertion<A> for MutItems<'a, A> {
#[inline]
fn insert_next(&mut self, elt: A) {
2014-04-25 03:08:02 -05:00
self.insert_next_node(box Node::new(elt))
}
#[inline]
fn peek_next<'a>(&'a mut self) -> Option<&'a mut A> {
if self.nelem == 0 {
return None
}
self.head.resolve().map(|head| &mut head.value)
}
}
2013-01-24 17:40:46 -06:00
impl<A> Iterator<A> for MoveItems<A> {
#[inline]
fn next(&mut self) -> Option<A> { self.list.pop_front() }
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(self.list.length, Some(self.list.length))
}
}
2013-01-24 17:40:46 -06:00
impl<A> DoubleEndedIterator<A> for MoveItems<A> {
#[inline]
2014-08-11 18:47:46 -05:00
fn next_back(&mut self) -> Option<A> { self.list.pop() }
}
2013-01-24 17:40:46 -06:00
impl<A> FromIterator<A> for DList<A> {
fn from_iter<T: Iterator<A>>(iterator: T) -> DList<A> {
let mut ret = DList::new();
2013-07-29 19:06:49 -05:00
ret.extend(iterator);
ret
}
}
impl<A> Extendable<A> for DList<A> {
fn extend<T: Iterator<A>>(&mut self, mut iterator: T) {
2014-08-11 18:47:46 -05:00
for elt in iterator { self.push(elt); }
2013-07-29 19:06:49 -05:00
}
}
impl<A: PartialEq> PartialEq for DList<A> {
fn eq(&self, other: &DList<A>) -> bool {
self.len() == other.len() &&
iter::order::eq(self.iter(), other.iter())
}
fn ne(&self, other: &DList<A>) -> bool {
2013-08-29 10:11:11 -05:00
self.len() != other.len() ||
iter::order::ne(self.iter(), other.iter())
}
}
impl<A: Eq> Eq for DList<A> {}
impl<A: PartialOrd> PartialOrd for DList<A> {
fn partial_cmp(&self, other: &DList<A>) -> Option<Ordering> {
iter::order::partial_cmp(self.iter(), other.iter())
}
}
impl<A: Ord> Ord for DList<A> {
#[inline]
fn cmp(&self, other: &DList<A>) -> Ordering {
iter::order::cmp(self.iter(), other.iter())
}
}
impl<A: Clone> Clone for DList<A> {
fn clone(&self) -> DList<A> {
self.iter().map(|x| x.clone()).collect()
}
}
2014-06-07 08:01:44 -05:00
impl<A: fmt::Show> fmt::Show for DList<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "["));
for (i, e) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", *e));
}
write!(f, "]")
}
}
2014-07-29 15:24:06 -05:00
impl<S: Writer, A: Hash<S>> Hash<S> for DList<A> {
fn hash(&self, state: &mut S) {
self.len().hash(state);
for elt in self.iter() {
elt.hash(state);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::*;
std: Recreate a `rand` module This commit shuffles around some of the `rand` code, along with some reorganization. The new state of the world is as follows: * The librand crate now only depends on libcore. This interface is experimental. * The standard library has a new module, `std::rand`. This interface will eventually become stable. Unfortunately, this entailed more of a breaking change than just shuffling some names around. The following breaking changes were made to the rand library: * Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which will return an infinite stream of random values. Previous behavior can be regained with `rng.gen_iter().take(n).collect()` * Rng::gen_ascii_str() was removed. This has been replaced with Rng::gen_ascii_chars() which will return an infinite stream of random ascii characters. Similarly to gen_iter(), previous behavior can be emulated with `rng.gen_ascii_chars().take(n).collect()` * {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all relied on being able to use an OSRng for seeding, but this is no longer available in librand (where these types are defined). To retain the same functionality, these types now implement the `Rand` trait so they can be generated with a random seed from another random number generator. This allows the stdlib to use an OSRng to create seeded instances of these RNGs. * Rand implementations for `Box<T>` and `@T` were removed. These seemed to be pretty rare in the codebase, and it allows for librand to not depend on liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not supported. If this is undesirable, librand can depend on liballoc and regain these implementations. * The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`, but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice structure now has a lifetime associated with it. * The `sample` method on `Rng` has been moved to a top-level function in the `rand` module due to its dependence on `Vec`. cc #13851 [breaking-change]
2014-05-25 03:39:37 -05:00
use std::rand;
2014-07-29 15:24:06 -05:00
use std::hash;
use test::Bencher;
use test;
use {Deque, MutableSeq};
use super::{DList, Node, ListInsertion};
use vec::Vec;
pub fn check_links<T>(list: &DList<T>) {
let mut len = 0u;
let mut last_ptr: Option<&Node<T>> = None;
let mut node_ptr: &Node<T>;
match list.list_head {
None => { assert_eq!(0u, list.length); return }
Some(ref node) => node_ptr = &**node,
}
loop {
match (last_ptr, node_ptr.prev.resolve_immut()) {
(None , None ) => {}
(None , _ ) => fail!("prev link for list_head"),
(Some(p), Some(pptr)) => {
2014-06-25 14:47:34 -05:00
assert_eq!(p as *const Node<T>, pptr as *const Node<T>);
}
_ => fail!("prev link is none, not good"),
}
match node_ptr.next {
Some(ref next) => {
last_ptr = Some(node_ptr);
node_ptr = &**next;
len += 1;
}
None => {
len += 1;
break;
}
}
}
assert_eq!(len, list.length);
}
#[test]
fn test_basic() {
let mut m: DList<Box<int>> = DList::new();
assert_eq!(m.pop_front(), None);
assert_eq!(m.pop(), None);
assert_eq!(m.pop_front(), None);
2014-04-25 03:08:02 -05:00
m.push_front(box 1);
assert_eq!(m.pop_front(), Some(box 1));
m.push(box 2);
m.push(box 3);
assert_eq!(m.len(), 2);
assert_eq!(m.pop_front(), Some(box 2));
assert_eq!(m.pop_front(), Some(box 3));
assert_eq!(m.len(), 0);
assert_eq!(m.pop_front(), None);
m.push(box 1);
m.push(box 3);
m.push(box 5);
m.push(box 7);
assert_eq!(m.pop_front(), Some(box 1));
let mut n = DList::new();
n.push_front(2i);
n.push_front(3);
{
2013-07-10 08:27:15 -05:00
assert_eq!(n.front().unwrap(), &3);
let x = n.front_mut().unwrap();
assert_eq!(*x, 3);
*x = 0;
}
{
2013-07-10 08:27:15 -05:00
assert_eq!(n.back().unwrap(), &2);
let y = n.back_mut().unwrap();
assert_eq!(*y, 2);
*y = 1;
}
assert_eq!(n.pop_front(), Some(0));
assert_eq!(n.pop_front(), Some(1));
}
#[cfg(test)]
fn generate_test() -> DList<int> {
list_from(&[0i,1,2,3,4,5,6])
}
#[cfg(test)]
2013-07-02 14:47:32 -05:00
fn list_from<T: Clone>(v: &[T]) -> DList<T> {
v.iter().map(|x| (*x).clone()).collect()
}
#[test]
2014-09-23 18:23:27 -05:00
#[allow(deprecated)]
fn test_append() {
{
let mut m = DList::new();
let mut n = DList::new();
n.push(2i);
m.append(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop(), Some(2));
check_links(&m);
}
{
let mut m = DList::new();
let n = DList::new();
m.push(2i);
m.append(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop(), Some(2));
check_links(&m);
}
let v = vec![1i,2,3,4,5];
let u = vec![9i,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
m.append(list_from(u.as_slice()));
check_links(&m);
let mut sum = v;
sum.push_all(u.as_slice());
assert_eq!(sum.len(), m.len());
2014-09-14 22:27:36 -05:00
for elt in sum.into_iter() {
assert_eq!(m.pop_front(), Some(elt))
}
}
#[test]
fn test_prepend() {
{
let mut m = DList::new();
let mut n = DList::new();
n.push(2i);
m.prepend(n);
assert_eq!(m.len(), 1);
assert_eq!(m.pop(), Some(2));
check_links(&m);
}
let v = vec![1i,2,3,4,5];
Clean up rustc warnings. compiletest: compact "linux" "macos" etc.as "unix". liballoc: remove a superfluous "use". libcollections: remove invocations of deprecated methods in favor of their suggested replacements and use "_" for a loop counter. libcoretest: remove invocations of deprecated methods; also add "allow(deprecated)" for testing a deprecated method itself. libglob: use "cfg_attr". libgraphviz: add a test for one of data constructors. libgreen: remove a superfluous "use". libnum: "allow(type_overflow)" for type cast into u8 in a test code. librustc: names of static variables should be in upper case. libserialize: v[i] instead of get(). libstd/ascii: to_lowercase() instead of to_lower(). libstd/bitflags: modify AnotherSetOfFlags to use i8 as its backend. It will serve better for testing various aspects of bitflags!. libstd/collections: "allow(deprecated)" for testing a deprecated method itself. libstd/io: remove invocations of deprecated methods and superfluous "use". Also add #[test] where it was missing. libstd/num: introduce a helper function to effectively remove invocations of a deprecated method. libstd/path and rand: remove invocations of deprecated methods and superfluous "use". libstd/task and libsync/comm: "allow(deprecated)" for testing a deprecated method itself. libsync/deque: remove superfluous "unsafe". libsync/mutex and once: names of static variables should be in upper case. libterm: introduce a helper function to effectively remove invocations of a deprecated method. We still see a few warnings about using obsoleted native::task::spawn() in the test modules for libsync. I'm not sure how I should replace them with std::task::TaksBuilder and native::task::NativeTaskBuilder (dependency to libstd?) Signed-off-by: NODA, Kai <nodakai@gmail.com>
2014-10-05 05:11:17 -05:00
let mut u = vec![9i,8,1,2,3,4,5];
let mut m = list_from(v.as_slice());
m.prepend(list_from(u.as_slice()));
check_links(&m);
Clean up rustc warnings. compiletest: compact "linux" "macos" etc.as "unix". liballoc: remove a superfluous "use". libcollections: remove invocations of deprecated methods in favor of their suggested replacements and use "_" for a loop counter. libcoretest: remove invocations of deprecated methods; also add "allow(deprecated)" for testing a deprecated method itself. libglob: use "cfg_attr". libgraphviz: add a test for one of data constructors. libgreen: remove a superfluous "use". libnum: "allow(type_overflow)" for type cast into u8 in a test code. librustc: names of static variables should be in upper case. libserialize: v[i] instead of get(). libstd/ascii: to_lowercase() instead of to_lower(). libstd/bitflags: modify AnotherSetOfFlags to use i8 as its backend. It will serve better for testing various aspects of bitflags!. libstd/collections: "allow(deprecated)" for testing a deprecated method itself. libstd/io: remove invocations of deprecated methods and superfluous "use". Also add #[test] where it was missing. libstd/num: introduce a helper function to effectively remove invocations of a deprecated method. libstd/path and rand: remove invocations of deprecated methods and superfluous "use". libstd/task and libsync/comm: "allow(deprecated)" for testing a deprecated method itself. libsync/deque: remove superfluous "unsafe". libsync/mutex and once: names of static variables should be in upper case. libterm: introduce a helper function to effectively remove invocations of a deprecated method. We still see a few warnings about using obsoleted native::task::spawn() in the test modules for libsync. I'm not sure how I should replace them with std::task::TaksBuilder and native::task::NativeTaskBuilder (dependency to libstd?) Signed-off-by: NODA, Kai <nodakai@gmail.com>
2014-10-05 05:11:17 -05:00
u.extend(v.as_slice().iter().map(|&b| b));
assert_eq!(u.len(), m.len());
for elt in u.into_iter() {
assert_eq!(m.pop_front(), Some(elt))
}
}
#[test]
fn test_rotate() {
let mut n: DList<int> = DList::new();
n.rotate_backward(); check_links(&n);
assert_eq!(n.len(), 0);
n.rotate_forward(); check_links(&n);
assert_eq!(n.len(), 0);
let v = vec![1i,2,3,4,5];
let mut m = list_from(v.as_slice());
m.rotate_backward(); check_links(&m);
m.rotate_forward(); check_links(&m);
assert_eq!(v.iter().collect::<Vec<&int>>(), m.iter().collect());
m.rotate_forward(); check_links(&m);
m.rotate_forward(); check_links(&m);
m.pop_front(); check_links(&m);
m.rotate_forward(); check_links(&m);
m.rotate_backward(); check_links(&m);
m.push_front(9); check_links(&m);
m.rotate_forward(); check_links(&m);
2014-09-14 22:27:36 -05:00
assert_eq!(vec![3i,9,5,1,2], m.into_iter().collect());
}
#[test]
fn test_iterator() {
let m = generate_test();
for (i, elt) in m.iter().enumerate() {
assert_eq!(i as int, *elt);
}
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
n.push_front(4i);
let mut it = n.iter();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
assert_eq!(it.size_hint(), (0, Some(0)));
assert_eq!(it.next(), None);
}
#[test]
fn test_iterator_clone() {
let mut n = DList::new();
n.push(2i);
n.push(3);
n.push(4);
let mut it = n.iter();
it.next();
let mut jt = it.clone();
assert_eq!(it.next(), jt.next());
assert_eq!(it.next_back(), jt.next_back());
assert_eq!(it.next(), jt.next());
}
#[test]
fn test_iterator_double_end() {
let mut n = DList::new();
assert_eq!(n.iter().next(), None);
n.push_front(4i);
n.push_front(5);
n.push_front(6);
let mut it = n.iter();
assert_eq!(it.size_hint(), (3, Some(3)));
assert_eq!(it.next().unwrap(), &6);
assert_eq!(it.size_hint(), (2, Some(2)));
assert_eq!(it.next_back().unwrap(), &4);
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next_back().unwrap(), &5);
assert_eq!(it.next_back(), None);
assert_eq!(it.next(), None);
}
#[test]
fn test_rev_iter() {
let m = generate_test();
Deprecate the rev_iter pattern in all places where a DoubleEndedIterator is provided (everywhere but treemap) This commit deprecates rev_iter, mut_rev_iter, move_rev_iter everywhere (except treemap) and also deprecates related functions like rsplit, rev_components, and rev_str_components. In every case, these functions can be replaced with the non-reversed form followed by a call to .rev(). To make this more concrete, a translation table for all functional changes necessary follows: * container.rev_iter() -> container.iter().rev() * container.mut_rev_iter() -> container.mut_iter().rev() * container.move_rev_iter() -> container.move_iter().rev() * sliceorstr.rsplit(sep) -> sliceorstr.split(sep).rev() * path.rev_components() -> path.components().rev() * path.rev_str_components() -> path.str_components().rev() In terms of the type system, this change also deprecates any specialized reversed iterator types (except in treemap), opting instead to use Rev directly if any type annotations are needed. However, since methods directly returning reversed iterators are now discouraged, the need for such annotations should be small. However, in those cases, the general pattern for conversion is to take whatever follows Rev in the original reversed name and surround it with Rev<>: * RevComponents<'a> -> Rev<Components<'a>> * RevStrComponents<'a> -> Rev<StrComponents<'a>> * RevItems<'a, T> -> Rev<Items<'a, T>> * etc. The reasoning behind this change is that it makes the standard API much simpler without reducing readability, performance, or power. The presence of functions such as rev_iter adds more boilerplate code to libraries (all of which simply call .iter().rev()), clutters up the documentation, and only helps code by saving two characters. Additionally, the numerous type synonyms that were used to make the type signatures look nice like RevItems add even more boilerplate and clutter up the docs even more. With this change, all that cruft goes away. [breaking-change]
2014-04-20 23:59:12 -05:00
for (i, elt) in m.iter().rev().enumerate() {
assert_eq!((6 - i) as int, *elt);
}
let mut n = DList::new();
Deprecate the rev_iter pattern in all places where a DoubleEndedIterator is provided (everywhere but treemap) This commit deprecates rev_iter, mut_rev_iter, move_rev_iter everywhere (except treemap) and also deprecates related functions like rsplit, rev_components, and rev_str_components. In every case, these functions can be replaced with the non-reversed form followed by a call to .rev(). To make this more concrete, a translation table for all functional changes necessary follows: * container.rev_iter() -> container.iter().rev() * container.mut_rev_iter() -> container.mut_iter().rev() * container.move_rev_iter() -> container.move_iter().rev() * sliceorstr.rsplit(sep) -> sliceorstr.split(sep).rev() * path.rev_components() -> path.components().rev() * path.rev_str_components() -> path.str_components().rev() In terms of the type system, this change also deprecates any specialized reversed iterator types (except in treemap), opting instead to use Rev directly if any type annotations are needed. However, since methods directly returning reversed iterators are now discouraged, the need for such annotations should be small. However, in those cases, the general pattern for conversion is to take whatever follows Rev in the original reversed name and surround it with Rev<>: * RevComponents<'a> -> Rev<Components<'a>> * RevStrComponents<'a> -> Rev<StrComponents<'a>> * RevItems<'a, T> -> Rev<Items<'a, T>> * etc. The reasoning behind this change is that it makes the standard API much simpler without reducing readability, performance, or power. The presence of functions such as rev_iter adds more boilerplate code to libraries (all of which simply call .iter().rev()), clutters up the documentation, and only helps code by saving two characters. Additionally, the numerous type synonyms that were used to make the type signatures look nice like RevItems add even more boilerplate and clutter up the docs even more. With this change, all that cruft goes away. [breaking-change]
2014-04-20 23:59:12 -05:00
assert_eq!(n.iter().rev().next(), None);
n.push_front(4i);
Deprecate the rev_iter pattern in all places where a DoubleEndedIterator is provided (everywhere but treemap) This commit deprecates rev_iter, mut_rev_iter, move_rev_iter everywhere (except treemap) and also deprecates related functions like rsplit, rev_components, and rev_str_components. In every case, these functions can be replaced with the non-reversed form followed by a call to .rev(). To make this more concrete, a translation table for all functional changes necessary follows: * container.rev_iter() -> container.iter().rev() * container.mut_rev_iter() -> container.mut_iter().rev() * container.move_rev_iter() -> container.move_iter().rev() * sliceorstr.rsplit(sep) -> sliceorstr.split(sep).rev() * path.rev_components() -> path.components().rev() * path.rev_str_components() -> path.str_components().rev() In terms of the type system, this change also deprecates any specialized reversed iterator types (except in treemap), opting instead to use Rev directly if any type annotations are needed. However, since methods directly returning reversed iterators are now discouraged, the need for such annotations should be small. However, in those cases, the general pattern for conversion is to take whatever follows Rev in the original reversed name and surround it with Rev<>: * RevComponents<'a> -> Rev<Components<'a>> * RevStrComponents<'a> -> Rev<StrComponents<'a>> * RevItems<'a, T> -> Rev<Items<'a, T>> * etc. The reasoning behind this change is that it makes the standard API much simpler without reducing readability, performance, or power. The presence of functions such as rev_iter adds more boilerplate code to libraries (all of which simply call .iter().rev()), clutters up the documentation, and only helps code by saving two characters. Additionally, the numerous type synonyms that were used to make the type signatures look nice like RevItems add even more boilerplate and clutter up the docs even more. With this change, all that cruft goes away. [breaking-change]
2014-04-20 23:59:12 -05:00
let mut it = n.iter().rev();
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(it.next().unwrap(), &4);
assert_eq!(it.size_hint(), (0, Some(0)));
assert_eq!(it.next(), None);
}
#[test]
fn test_mut_iter() {
let mut m = generate_test();
let mut len = m.len();
2014-09-14 22:27:36 -05:00
for (i, elt) in m.iter_mut().enumerate() {
assert_eq!(i as int, *elt);
len -= 1;
}
assert_eq!(len, 0);
let mut n = DList::new();
2014-09-14 22:27:36 -05:00
assert!(n.iter_mut().next().is_none());
n.push_front(4i);
n.push(5);
2014-09-14 22:27:36 -05:00
let mut it = n.iter_mut();
assert_eq!(it.size_hint(), (2, Some(2)));
assert!(it.next().is_some());
assert!(it.next().is_some());
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_iterator_mut_double_end() {
let mut n = DList::new();
2014-09-14 22:27:36 -05:00
assert!(n.iter_mut().next_back().is_none());
n.push_front(4i);
n.push_front(5);
n.push_front(6);
2014-09-14 22:27:36 -05:00
let mut it = n.iter_mut();
assert_eq!(it.size_hint(), (3, Some(3)));
assert_eq!(*it.next().unwrap(), 6);
assert_eq!(it.size_hint(), (2, Some(2)));
assert_eq!(*it.next_back().unwrap(), 4);
assert_eq!(it.size_hint(), (1, Some(1)));
assert_eq!(*it.next_back().unwrap(), 5);
assert!(it.next_back().is_none());
assert!(it.next().is_none());
}
#[test]
fn test_insert_prev() {
let mut m = list_from(&[0i,2,4,6,8]);
let len = m.len();
{
2014-09-14 22:27:36 -05:00
let mut it = m.iter_mut();
it.insert_next(-2);
loop {
match it.next() {
None => break,
Some(elt) => {
it.insert_next(*elt + 1);
match it.peek_next() {
Some(x) => assert_eq!(*x, *elt + 2),
None => assert_eq!(8, *elt),
}
}
}
}
it.insert_next(0);
it.insert_next(1);
}
check_links(&m);
assert_eq!(m.len(), 3 + len * 2);
2014-09-14 22:27:36 -05:00
assert_eq!(m.into_iter().collect::<Vec<int>>(), vec![-2,0,1,2,3,4,5,6,7,8,9,0,1]);
}
#[test]
fn test_merge() {
let mut m = list_from([0i, 1, 3, 5, 6, 7, 2]);
let n = list_from([-1i, 0, 0, 7, 7, 9]);
let len = m.len() + n.len();
m.merge(n, |a, b| a <= b);
assert_eq!(m.len(), len);
check_links(&m);
2014-09-14 22:27:36 -05:00
let res = m.into_iter().collect::<Vec<int>>();
assert_eq!(res, vec![-1, 0, 0, 0, 1, 3, 5, 6, 7, 2, 7, 7, 9]);
}
#[test]
fn test_insert_ordered() {
let mut n = DList::new();
n.insert_ordered(1i);
assert_eq!(n.len(), 1);
assert_eq!(n.pop_front(), Some(1));
let mut m = DList::new();
m.push(2i);
m.push(4);
m.insert_ordered(3);
check_links(&m);
2014-09-14 22:27:36 -05:00
assert_eq!(vec![2,3,4], m.into_iter().collect::<Vec<int>>());
}
#[test]
fn test_mut_rev_iter() {
let mut m = generate_test();
2014-09-14 22:27:36 -05:00
for (i, elt) in m.iter_mut().rev().enumerate() {
assert_eq!((6-i) as int, *elt);
}
let mut n = DList::new();
2014-09-14 22:27:36 -05:00
assert!(n.iter_mut().rev().next().is_none());
n.push_front(4i);
2014-09-14 22:27:36 -05:00
let mut it = n.iter_mut().rev();
assert!(it.next().is_some());
assert!(it.next().is_none());
}
#[test]
fn test_send() {
let n = list_from([1i,2,3]);
2014-01-26 22:13:24 -06:00
spawn(proc() {
check_links(&n);
let a: &[_] = &[&1,&2,&3];
assert_eq!(a, n.iter().collect::<Vec<&int>>().as_slice());
2014-01-26 22:13:24 -06:00
});
}
#[test]
fn test_eq() {
let mut n: DList<u8> = list_from([]);
let mut m = list_from([]);
assert!(n == m);
n.push_front(1);
assert!(n != m);
m.push(1);
assert!(n == m);
2013-08-29 10:11:11 -05:00
let n = list_from([2i,3,4]);
let m = list_from([1i,2,3]);
2013-08-29 10:11:11 -05:00
assert!(n != m);
}
2014-07-29 15:24:06 -05:00
#[test]
fn test_hash() {
let mut x = DList::new();
let mut y = DList::new();
assert!(hash::hash(&x) == hash::hash(&y));
x.push(1i);
x.push(2);
x.push(3);
2014-07-29 15:24:06 -05:00
y.push_front(3i);
y.push_front(2);
y.push_front(1);
assert!(hash::hash(&x) == hash::hash(&y));
}
#[test]
fn test_ord() {
let n: DList<int> = list_from([]);
let m = list_from([1i,2,3]);
assert!(n < m);
assert!(m > n);
assert!(n <= n);
assert!(n >= n);
}
#[test]
fn test_ord_nan() {
let nan = 0.0f64/0.0;
let n = list_from([nan]);
let m = list_from([nan]);
assert!(!(n < m));
assert!(!(n > m));
assert!(!(n <= m));
assert!(!(n >= m));
let n = list_from([nan]);
let one = list_from([1.0f64]);
assert!(!(n < one));
assert!(!(n > one));
assert!(!(n <= one));
assert!(!(n >= one));
let u = list_from([1.0f64,2.0,nan]);
let v = list_from([1.0f64,2.0,3.0]);
assert!(!(u < v));
assert!(!(u > v));
assert!(!(u <= v));
assert!(!(u >= v));
let s = list_from([1.0f64,2.0,4.0,2.0]);
let t = list_from([1.0f64,2.0,3.0,2.0]);
assert!(!(s < t));
assert!(s > one);
assert!(!(s <= one));
assert!(s >= one);
}
#[test]
fn test_fuzz() {
for _ in range(0u, 25) {
fuzz_test(3);
fuzz_test(16);
fuzz_test(189);
}
}
2014-06-07 08:01:44 -05:00
#[test]
fn test_show() {
let list: DList<int> = range(0i, 10).collect();
assert!(list.to_string().as_slice() == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]");
2014-06-07 08:01:44 -05:00
let list: DList<&str> = vec!["just", "one", "test", "more"].iter()
.map(|&s| s)
.collect();
assert!(list.to_string().as_slice() == "[just, one, test, more]");
2014-06-07 08:01:44 -05:00
}
#[cfg(test)]
fn fuzz_test(sz: int) {
let mut m: DList<int> = DList::new();
let mut v = vec![];
for i in range(0, sz) {
check_links(&m);
let r: u8 = rand::random();
match r % 6 {
0 => {
m.pop();
v.pop();
}
1 => {
m.pop_front();
v.remove(0);
}
2 | 4 => {
m.push_front(-i);
v.insert(0, -i);
}
3 | 5 | _ => {
m.push(i);
v.push(i);
}
}
}
check_links(&m);
let mut i = 0u;
2014-09-14 22:27:36 -05:00
for (a, &b) in m.into_iter().zip(v.iter()) {
i += 1;
assert_eq!(a, b);
}
assert_eq!(i, v.len());
}
#[bench]
fn bench_collect_into(b: &mut test::Bencher) {
let v = &[0i, ..64];
b.iter(|| {
let _: DList<int> = v.iter().map(|x| *x).collect();
})
}
#[bench]
fn bench_push_front(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
b.iter(|| {
m.push_front(0);
})
}
#[bench]
fn bench_push_back(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
b.iter(|| {
m.push(0);
})
}
#[bench]
fn bench_push_back_pop_back(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
b.iter(|| {
m.push(0);
m.pop();
})
}
#[bench]
fn bench_push_front_pop_front(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
b.iter(|| {
m.push_front(0);
m.pop_front();
})
}
#[bench]
fn bench_rotate_forward(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
m.push_front(0i);
m.push_front(1);
b.iter(|| {
m.rotate_forward();
})
}
#[bench]
fn bench_rotate_backward(b: &mut test::Bencher) {
let mut m: DList<int> = DList::new();
m.push_front(0i);
m.push_front(1);
b.iter(|| {
m.rotate_backward();
})
}
#[bench]
fn bench_iter(b: &mut test::Bencher) {
let v = &[0i, ..128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().count() == 128);
})
}
#[bench]
fn bench_iter_mut(b: &mut test::Bencher) {
let v = &[0i, ..128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
2014-09-14 22:27:36 -05:00
assert!(m.iter_mut().count() == 128);
})
}
#[bench]
fn bench_iter_rev(b: &mut test::Bencher) {
let v = &[0i, ..128];
let m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
assert!(m.iter().rev().count() == 128);
})
}
#[bench]
fn bench_iter_mut_rev(b: &mut test::Bencher) {
let v = &[0i, ..128];
let mut m: DList<int> = v.iter().map(|&x|x).collect();
b.iter(|| {
2014-09-14 22:27:36 -05:00
assert!(m.iter_mut().rev().count() == 128);
})
}
}