rust/src/libcollections/smallintmap.rs

552 lines
16 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
// 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 simple map based on a vector for small integer keys. Space requirements
* are O(highest integer key).
*/
#![allow(missing_doc)]
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::*;
2014-06-07 11:17:58 -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::{Enumerate, FilterMap};
use core::mem::replace;
use {vec, slice};
use vec::Vec;
#[allow(missing_doc)]
pub struct SmallIntMap<T> {
v: Vec<Option<T>>,
}
impl<V> Collection for SmallIntMap<V> {
/// Return the number of elements in the map
2013-06-15 01:20:06 -05:00
fn len(&self) -> uint {
self.v.iter().filter(|elt| elt.is_some()).count()
}
/// Return true if there are no elements in the map
fn is_empty(&self) -> bool {
self.v.iter().all(|elt| elt.is_none())
}
}
impl<V> Mutable for SmallIntMap<V> {
/// Clear the map, removing all key-value pairs.
fn clear(&mut self) { self.v.clear() }
}
impl<V> Map<uint, V> for SmallIntMap<V> {
2013-03-24 19:35:23 -05:00
/// Return a reference to the value corresponding to the key
fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
if *key < self.v.len() {
match *self.v.get(*key) {
Some(ref value) => Some(value),
None => None
}
} else {
None
}
}
}
impl<V> MutableMap<uint, V> for SmallIntMap<V> {
2013-03-24 19:40:17 -05:00
/// Return a mutable reference to the value corresponding to the key
fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
if *key < self.v.len() {
match *self.v.get_mut(*key) {
Some(ref mut value) => Some(value),
None => None
}
} else {
None
}
}
/// Insert a key-value pair into the map. An existing value for a
/// key is replaced by the new value. Return true if the key did
/// not already exist in the map.
fn insert(&mut self, key: uint, value: V) -> bool {
let exists = self.contains_key(&key);
let len = self.v.len();
if len <= key {
self.v.grow_fn(key - len + 1, |_| None);
}
*self.v.get_mut(key) = Some(value);
!exists
}
/// Remove a key-value pair from the map. Return true if the key
/// was present in the map, otherwise false.
fn remove(&mut self, key: &uint) -> bool {
2013-05-04 08:54:58 -05:00
self.pop(key).is_some()
}
/// Insert a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise None is returned.
fn swap(&mut self, key: uint, value: V) -> Option<V> {
match self.find_mut(&key) {
Some(loc) => { return Some(replace(loc, value)); }
None => ()
}
self.insert(key, value);
return None;
}
/// Removes a key from the map, returning the value at the key if the key
/// was previously in the map.
fn pop(&mut self, key: &uint) -> Option<V> {
if *key >= self.v.len() {
2013-05-04 08:54:58 -05:00
return None;
}
self.v.get_mut(*key).take()
}
}
impl<V> SmallIntMap<V> {
/// Create an empty SmallIntMap
pub fn new() -> SmallIntMap<V> { SmallIntMap{v: vec!()} }
/// Create an empty SmallIntMap with capacity `capacity`
pub fn with_capacity(capacity: uint) -> SmallIntMap<V> {
SmallIntMap { v: Vec::with_capacity(capacity) }
}
pub fn get<'a>(&'a self, key: &uint) -> &'a V {
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
::expect(self.find(key), "key not present")
}
/// An iterator visiting all key-value pairs in ascending order by the keys.
/// Iterator element type is (uint, &'r V)
pub fn iter<'r>(&'r self) -> Entries<'r, V> {
Entries {
front: 0,
back: self.v.len(),
iter: self.v.iter()
}
}
/// An iterator visiting all key-value pairs in ascending order by the keys,
/// with mutable references to the values
/// Iterator element type is (uint, &'r mut V)
pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
MutEntries {
front: 0,
back: self.v.len(),
iter: self.v.mut_iter()
}
}
2013-07-08 23:16:23 -05:00
/// Empties the hash map, moving all values into the specified closure
pub fn move_iter(&mut self)
-> FilterMap<(uint, Option<V>), (uint, V),
Enumerate<vec::MoveItems<Option<V>>>>
2013-07-08 23:16:23 -05:00
{
let values = replace(&mut self.v, vec!());
values.move_iter().enumerate().filter_map(|(i, v)| {
v.map(|v| (i, v))
2013-07-08 23:16:23 -05:00
})
}
}
2013-07-02 14:47:32 -05:00
impl<V:Clone> SmallIntMap<V> {
pub fn update_with_key(&mut self,
key: uint,
val: V,
ff: |uint, V, V| -> V)
-> bool {
let new_val = match self.find(&key) {
None => val,
2013-07-02 14:47:32 -05:00
Some(orig) => ff(key, (*orig).clone(), val)
};
self.insert(key, new_val)
}
pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
}
}
2014-06-07 11:17:58 -05:00
impl<V: fmt::Show> fmt::Show for SmallIntMap<V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, r"\{"));
for (i, (k, v)) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}: {}", k, *v));
}
write!(f, r"\}")
}
}
macro_rules! iterator {
(impl $name:ident -> $elem:ty, $getter:ident) => {
impl<'a, T> Iterator<$elem> for $name<'a, T> {
#[inline]
fn next(&mut self) -> Option<$elem> {
while self.front < self.back {
match self.iter.next() {
Some(elem) => {
if elem.is_some() {
let index = self.front;
self.front += 1;
return Some((index, elem. $getter ()));
}
}
_ => ()
}
self.front += 1;
}
None
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
(0, Some(self.back - self.front))
}
}
}
}
macro_rules! double_ended_iterator {
(impl $name:ident -> $elem:ty, $getter:ident) => {
impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<$elem> {
while self.front < self.back {
match self.iter.next_back() {
Some(elem) => {
if elem.is_some() {
self.back -= 1;
return Some((self.back, elem. $getter ()));
}
}
_ => ()
}
self.back -= 1;
}
None
}
}
}
}
pub struct Entries<'a, T> {
front: uint,
back: uint,
iter: slice::Items<'a, Option<T>>
}
iterator!(impl Entries -> (uint, &'a T), get_ref)
double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
pub struct MutEntries<'a, T> {
front: uint,
back: uint,
iter: slice::MutItems<'a, Option<T>>
}
iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
#[cfg(test)]
mod test_map {
use std::prelude::*;
use super::SmallIntMap;
2013-03-24 19:35:23 -05:00
#[test]
fn test_find_mut() {
let mut m = SmallIntMap::new();
2013-03-28 20:39:09 -05:00
assert!(m.insert(1, 12));
assert!(m.insert(2, 8));
assert!(m.insert(5, 14));
2013-03-24 19:35:23 -05:00
let new = 100;
match m.find_mut(&5) {
None => fail!(), Some(x) => *x = new
2013-03-24 19:35:23 -05:00
}
assert_eq!(m.find(&5), Some(&new));
}
#[test]
fn test_len() {
let mut map = SmallIntMap::new();
assert_eq!(map.len(), 0);
2013-03-28 20:39:09 -05:00
assert!(map.is_empty());
assert!(map.insert(5, 20));
assert_eq!(map.len(), 1);
2013-03-28 20:39:09 -05:00
assert!(!map.is_empty());
assert!(map.insert(11, 12));
assert_eq!(map.len(), 2);
2013-03-28 20:39:09 -05:00
assert!(!map.is_empty());
assert!(map.insert(14, 22));
assert_eq!(map.len(), 3);
2013-03-28 20:39:09 -05:00
assert!(!map.is_empty());
}
#[test]
fn test_clear() {
let mut map = SmallIntMap::new();
2013-03-28 20:39:09 -05:00
assert!(map.insert(5, 20));
assert!(map.insert(11, 12));
assert!(map.insert(14, 22));
map.clear();
2013-03-28 20:39:09 -05:00
assert!(map.is_empty());
assert!(map.find(&5).is_none());
assert!(map.find(&11).is_none());
assert!(map.find(&14).is_none());
}
#[test]
fn test_insert_with_key() {
let mut map = SmallIntMap::new();
// given a new key, initialize it with this new count,
// given an existing key, add more to its count
fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
v0 + v1
}
fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
v0 + v1
}
// count integers
map.update(3, 1, add_more_to_count_simple);
map.update_with_key(9, 1, add_more_to_count);
map.update(3, 7, add_more_to_count_simple);
map.update_with_key(5, 3, add_more_to_count);
map.update_with_key(3, 2, add_more_to_count);
// check the total counts
assert_eq!(map.find(&3).unwrap(), &10);
assert_eq!(map.find(&5).unwrap(), &3);
assert_eq!(map.find(&9).unwrap(), &1);
// sadly, no sevens were counted
2013-03-28 20:39:09 -05:00
assert!(map.find(&7).is_none());
}
2013-05-04 08:54:58 -05:00
#[test]
fn test_swap() {
let mut m = SmallIntMap::new();
assert_eq!(m.swap(1, 2), None);
assert_eq!(m.swap(1, 3), Some(2));
assert_eq!(m.swap(1, 4), Some(3));
2013-05-04 08:54:58 -05:00
}
#[test]
fn test_pop() {
let mut m = SmallIntMap::new();
m.insert(1, 2);
assert_eq!(m.pop(&1), Some(2));
assert_eq!(m.pop(&1), None);
2013-05-04 08:54:58 -05:00
}
#[test]
fn test_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
assert!(m.insert(10, 11));
let mut it = m.iter();
assert_eq!(it.size_hint(), (0, Some(11)));
assert_eq!(it.next().unwrap(), (0, &1));
assert_eq!(it.size_hint(), (0, Some(10)));
assert_eq!(it.next().unwrap(), (1, &2));
assert_eq!(it.size_hint(), (0, Some(9)));
assert_eq!(it.next().unwrap(), (3, &5));
assert_eq!(it.size_hint(), (0, Some(7)));
assert_eq!(it.next().unwrap(), (6, &10));
assert_eq!(it.size_hint(), (0, Some(4)));
assert_eq!(it.next().unwrap(), (10, &11));
assert_eq!(it.size_hint(), (0, Some(0)));
assert!(it.next().is_none());
}
#[test]
fn test_iterator_size_hints() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
assert!(m.insert(10, 11));
assert_eq!(m.iter().size_hint(), (0, Some(11)));
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!(m.iter().rev().size_hint(), (0, Some(11)));
assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
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!(m.mut_iter().rev().size_hint(), (0, Some(11)));
}
#[test]
fn test_mut_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
assert!(m.insert(10, 11));
for (k, v) in m.mut_iter() {
*v += k as int;
}
let mut it = m.iter();
assert_eq!(it.next().unwrap(), (0, &1));
assert_eq!(it.next().unwrap(), (1, &3));
assert_eq!(it.next().unwrap(), (3, &8));
assert_eq!(it.next().unwrap(), (6, &16));
assert_eq!(it.next().unwrap(), (10, &21));
assert!(it.next().is_none());
}
#[test]
fn test_rev_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
assert!(m.insert(10, 11));
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 = m.iter().rev();
assert_eq!(it.next().unwrap(), (10, &11));
assert_eq!(it.next().unwrap(), (6, &10));
assert_eq!(it.next().unwrap(), (3, &5));
assert_eq!(it.next().unwrap(), (1, &2));
assert_eq!(it.next().unwrap(), (0, &1));
assert!(it.next().is_none());
}
#[test]
fn test_mut_rev_iterator() {
let mut m = SmallIntMap::new();
assert!(m.insert(0, 1));
assert!(m.insert(1, 2));
assert!(m.insert(3, 5));
assert!(m.insert(6, 10));
assert!(m.insert(10, 11));
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 (k, v) in m.mut_iter().rev() {
*v += k as int;
}
let mut it = m.iter();
assert_eq!(it.next().unwrap(), (0, &1));
assert_eq!(it.next().unwrap(), (1, &3));
assert_eq!(it.next().unwrap(), (3, &8));
assert_eq!(it.next().unwrap(), (6, &16));
assert_eq!(it.next().unwrap(), (10, &21));
assert!(it.next().is_none());
}
2013-07-08 23:16:23 -05:00
#[test]
fn test_move_iter() {
2013-07-08 23:16:23 -05:00
let mut m = SmallIntMap::new();
2014-04-25 03:08:02 -05:00
m.insert(1, box 2);
2013-07-08 23:16:23 -05:00
let mut called = false;
for (k, v) in m.move_iter() {
2013-07-08 23:16:23 -05:00
assert!(!called);
called = true;
assert_eq!(k, 1);
assert_eq!(v, box 2);
2013-07-08 23:16:23 -05:00
}
assert!(called);
2014-04-25 03:08:02 -05:00
m.insert(2, box 1);
2013-07-08 23:16:23 -05:00
}
2014-06-07 11:17:58 -05:00
#[test]
fn test_show() {
let mut map = SmallIntMap::new();
let empty = SmallIntMap::<int>::new();
map.insert(1, 2);
map.insert(3, 4);
let map_str = map.to_str();
let map_str = map_str.as_slice();
assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}");
assert_eq!(format!("{}", empty), "{}".to_string());
}
}
2013-05-22 07:01:21 -05:00
2013-07-19 16:07:00 -05:00
#[cfg(test)]
mod bench {
2014-02-13 19:49:11 -06:00
extern crate test;
use self::test::Bencher;
use super::SmallIntMap;
use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
2013-07-19 16:07:00 -05:00
// Find seq
#[bench]
pub fn insert_rand_100(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
insert_rand_n(100, &mut m, b);
2013-07-19 16:07:00 -05:00
}
#[bench]
pub fn insert_rand_10_000(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
insert_rand_n(10_000, &mut m, b);
2013-07-19 16:07:00 -05:00
}
// Insert seq
#[bench]
pub fn insert_seq_100(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
insert_seq_n(100, &mut m, b);
2013-07-19 16:07:00 -05:00
}
#[bench]
pub fn insert_seq_10_000(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
insert_seq_n(10_000, &mut m, b);
2013-07-19 16:07:00 -05:00
}
// Find rand
#[bench]
pub fn find_rand_100(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
find_rand_n(100, &mut m, b);
2013-07-19 16:07:00 -05:00
}
#[bench]
pub fn find_rand_10_000(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
find_rand_n(10_000, &mut m, b);
2013-07-19 16:07:00 -05:00
}
// Find seq
#[bench]
pub fn find_seq_100(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
find_seq_n(100, &mut m, b);
2013-07-19 16:07:00 -05:00
}
#[bench]
pub fn find_seq_10_000(b: &mut Bencher) {
2013-07-19 16:07:00 -05:00
let mut m : SmallIntMap<uint> = SmallIntMap::new();
find_seq_n(10_000, &mut m, b);
2013-07-19 16:07:00 -05:00
}
}