smallintmap.rs 21.7 KB
Newer Older
1
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// 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.

11 12
//! A simple map based on a vector for small integer keys. Space requirements
//! are O(highest integer key).
13

14
#![allow(missing_doc)]
15

16 17
use core::prelude::*;

18
use core::default::Default;
19
use core::fmt;
20
use core::iter;
21 22 23
use core::iter::{Enumerate, FilterMap};
use core::mem::replace;

24
use {Collection, Mutable, Map, MutableMap, MutableSeq};
25 26
use {vec, slice};
use vec::Vec;
27

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
/// A map optimized for small integer keys.
///
/// # Example
///
/// ```
/// use std::collections::SmallIntMap;
///
/// let mut months = SmallIntMap::new();
/// months.insert(1, "Jan");
/// months.insert(2, "Feb");
/// months.insert(3, "Mar");
///
/// if !months.contains_key(&12) {
///     println!("The end is near!");
/// }
///
/// assert_eq!(months.find(&1), Some(&"Jan"));
///
/// match months.find_mut(&3) {
///     Some(value) => *value = "Venus",
///     None => (),
/// }
///
/// assert_eq!(months.find(&3), Some(&"Venus"));
///
/// // Print out all months
/// for (key, value) in months.iter() {
///     println!("month {} is {}", key, value);
/// }
///
/// months.clear();
/// assert!(months.is_empty());
/// ```
D
Daniel Micay 已提交
61
pub struct SmallIntMap<T> {
62
    v: Vec<Option<T>>,
63 64
}

65
impl<V> Collection for SmallIntMap<V> {
66
    /// Return the number of elements in the map.
D
Daniel Micay 已提交
67
    fn len(&self) -> uint {
A
Aaron Turon 已提交
68
        self.v.iter().filter(|elt| elt.is_some()).count()
69 70
    }

71
    /// Return `true` if there are no elements in the map.
72 73
    fn is_empty(&self) -> bool {
        self.v.iter().all(|elt| elt.is_none())
74 75 76
    }
}

77
impl<V> Mutable for SmallIntMap<V> {
D
Daniel Micay 已提交
78 79
    /// Clear the map, removing all key-value pairs.
    fn clear(&mut self) { self.v.clear() }
80 81
}

82
impl<V> Map<uint, V> for SmallIntMap<V> {
83
    /// Return a reference to the value corresponding to the key.
84 85
    fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
        if *key < self.v.len() {
86
            match *self.v.get(*key) {
87 88 89 90 91 92 93
              Some(ref value) => Some(value),
              None => None
            }
        } else {
            None
        }
    }
94
}
95

96
impl<V> MutableMap<uint, V> for SmallIntMap<V> {
97
    /// Return a mutable reference to the value corresponding to the key.
98 99
    fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
        if *key < self.v.len() {
100
            match *self.v.get_mut(*key) {
101 102 103 104 105 106 107 108
              Some(ref mut value) => Some(value),
              None => None
            }
        } else {
            None
        }
    }

D
Daniel Micay 已提交
109
    /// Insert a key-value pair into the map. An existing value for a
110
    /// key is replaced by the new value. Return `true` if the key did
D
Daniel Micay 已提交
111 112 113 114 115
    /// 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 {
116
            self.v.grow_fn(key - len + 1, |_| None);
D
Daniel Micay 已提交
117
        }
118
        *self.v.get_mut(key) = Some(value);
D
Daniel Micay 已提交
119
        !exists
120 121
    }

122 123
    /// Remove a key-value pair from the map. Return `true` if the key
    /// was present in the map, otherwise `false`.
D
Daniel Micay 已提交
124
    fn remove(&mut self, key: &uint) -> bool {
125 126 127 128
        self.pop(key).is_some()
    }

    /// Insert a key-value pair from the map. If the key already had a value
129
    /// present in the map, that value is returned. Otherwise `None` is returned.
130 131 132 133 134 135 136 137 138 139 140 141
    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> {
D
Daniel Micay 已提交
142
        if *key >= self.v.len() {
143
            return None;
144
        }
145
        self.v.get_mut(*key).take()
146
    }
D
Daniel Micay 已提交
147 148
}

149 150 151 152 153
impl<V> Default for SmallIntMap<V> {
    #[inline]
    fn default() -> SmallIntMap<V> { SmallIntMap::new() }
}

154
impl<V> SmallIntMap<V> {
155
    /// Create an empty SmallIntMap.
156 157 158 159 160 161 162
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    /// let mut map: SmallIntMap<&str> = SmallIntMap::new();
    /// ```
163
    pub fn new() -> SmallIntMap<V> { SmallIntMap{v: vec!()} }
D
Daniel Micay 已提交
164

165 166 167 168 169 170 171 172 173
    /// Create an empty SmallIntMap with space for at least `capacity` elements
    /// before resizing.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    /// let mut map: SmallIntMap<&str> = SmallIntMap::with_capacity(10);
    /// ```
174
    pub fn with_capacity(capacity: uint) -> SmallIntMap<V> {
175
        SmallIntMap { v: Vec::with_capacity(capacity) }
176 177
    }

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    /// Retrieves a value for the given key.
    /// See [`find`](../trait.Map.html#tymethod.find) for a non-failing alternative.
    ///
    /// # Failure
    ///
    /// Fails if the key is not present.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    ///
    /// let mut map = SmallIntMap::new();
    /// map.insert(1, "a");
    /// assert_eq!(map.get(&1), &"a");
    /// ```
194
    pub fn get<'a>(&'a self, key: &uint) -> &'a V {
195
        self.find(key).expect("key not present")
196
    }
197

198 199 200 201 202 203 204 205 206 207 208 209
    /// An iterator visiting all keys in ascending order by the keys.
    /// Iterator element type is `uint`.
    pub fn keys<'r>(&'r self) -> Keys<'r, V> {
        self.iter().map(|(k, _v)| k)
    }

    /// An iterator visiting all values in ascending order by the keys.
    /// Iterator element type is `&'r V`.
    pub fn values<'r>(&'r self) -> Values<'r, V> {
        self.iter().map(|(_k, v)| v)
    }

210
    /// An iterator visiting all key-value pairs in ascending order by the keys.
211
    /// Iterator element type is `(uint, &'r V)`.
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    ///
    /// let mut map = SmallIntMap::new();
    /// map.insert(1, "a");
    /// map.insert(3, "c");
    /// map.insert(2, "b");
    ///
    /// // Print `1: a` then `2: b` then `3: c`
    /// for (key, value) in map.iter() {
    ///     println!("{}: {}", key, value);
    /// }
    /// ```
P
Palmer Cox 已提交
228 229
    pub fn iter<'r>(&'r self) -> Entries<'r, V> {
        Entries {
230 231 232
            front: 0,
            back: self.v.len(),
            iter: self.v.iter()
233 234 235 236 237
        }
    }

    /// An iterator visiting all key-value pairs in ascending order by the keys,
    /// with mutable references to the values
238
    /// Iterator element type is `(uint, &'r mut V)`.
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    ///
    /// let mut map = SmallIntMap::new();
    /// map.insert(1, "a");
    /// map.insert(2, "b");
    /// map.insert(3, "c");
    ///
    /// for (key, value) in map.mut_iter() {
    ///     *value = "x";
    /// }
    ///
    /// for (key, value) in map.iter() {
    ///     assert_eq!(value, &"x");
    /// }
    /// ```
P
Palmer Cox 已提交
258 259
    pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
        MutEntries {
260 261 262
            front: 0,
            back: self.v.len(),
            iter: self.v.mut_iter()
263 264 265
        }
    }

N
nham 已提交
266
    /// Empties the map, moving all values into the specified closure.
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    ///
    /// let mut map = SmallIntMap::new();
    /// map.insert(1, "a");
    /// map.insert(3, "c");
    /// map.insert(2, "b");
    ///
    /// // Not possible with .iter()
    /// let vec: Vec<(uint, &str)> = map.move_iter().collect();
    ///
    /// assert_eq!(vec, vec![(1, "a"), (2, "b"), (3, "c")]);
    /// ```
283
    pub fn move_iter(&mut self)
284
        -> FilterMap<(uint, Option<V>), (uint, V),
285
                Enumerate<vec::MoveItems<Option<V>>>>
286
    {
287
        let values = replace(&mut self.v, vec!());
288
        values.move_iter().enumerate().filter_map(|(i, v)| {
289
            v.map(|v| (i, v))
290 291
        })
    }
292 293
}

294
impl<V:Clone> SmallIntMap<V> {
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    /// Update a value in the map. If the key already exists in the map,
    /// modify the value with `ff` taking `oldval, newval`.
    /// Otherwise set the value to `newval`.
    /// Return `true` if the key did not already exist in the map.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    ///
    /// let mut map = SmallIntMap::new();
    ///
    /// // Key does not exist, will do a simple insert
    /// assert!(map.update(1, vec![1i, 2], |old, new| old.append(new.as_slice())));
    /// assert_eq!(map.get(&1), &vec![1i, 2]);
    ///
    /// // Key exists, update the value
    /// assert!(!map.update(1, vec![3i, 4], |old, new| old.append(new.as_slice())));
    /// assert_eq!(map.get(&1), &vec![1i, 2, 3, 4]);
    /// ```
    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))
    }

    /// Update a value in the map. If the key already exists in the map,
    /// modify the value with `ff` taking `key, oldval, newval`.
    /// Otherwise set the value to `newval`.
    /// Return `true` if the key did not already exist in the map.
    ///
    /// # Example
    ///
    /// ```
    /// use std::collections::SmallIntMap;
    ///
    /// let mut map = SmallIntMap::new();
    ///
    /// // Key does not exist, will do a simple insert
    /// assert!(map.update_with_key(7, 10, |key, old, new| (old + new) % key));
    /// assert_eq!(map.get(&7), &10);
    ///
    /// // Key exists, update the value
    /// assert!(!map.update_with_key(7, 20, |key, old, new| (old + new) % key));
    /// assert_eq!(map.get(&7), &2);
    /// ```
339 340 341 342 343
    pub fn update_with_key(&mut self,
                           key: uint,
                           val: V,
                           ff: |uint, V, V| -> V)
                           -> bool {
344 345
        let new_val = match self.find(&key) {
            None => val,
346
            Some(orig) => ff(key, (*orig).clone(), val)
347 348
        };
        self.insert(key, new_val)
349 350 351
    }
}

352
impl<V: fmt::Show> fmt::Show for SmallIntMap<V> {
353 354 355 356 357 358 359 360 361 362
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "{{"));

        for (i, (k, v)) in self.iter().enumerate() {
            if i != 0 { try!(write!(f, ", ")); }
            try!(write!(f, "{}: {}", k, *v));
        }

        write!(f, "}}")
    }
363
}
364 365

macro_rules! iterator {
366
    (impl $name:ident -> $elem:ty, $getter:ident) => {
E
Erik Price 已提交
367
        impl<'a, T> Iterator<$elem> for $name<'a, T> {
368
            #[inline]
369 370 371 372 373 374 375 376 377 378 379
            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 ()));
                            }
                        }
                        _ => ()
380
                    }
381
                    self.front += 1;
382 383 384
                }
                None
            }
385 386 387 388 389

            #[inline]
            fn size_hint(&self) -> (uint, Option<uint>) {
                (0, Some(self.back - self.front))
            }
390 391 392 393
        }
    }
}

394 395
macro_rules! double_ended_iterator {
    (impl $name:ident -> $elem:ty, $getter:ident) => {
E
Erik Price 已提交
396
        impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
397
            #[inline]
398 399 400 401 402 403 404 405 406 407
            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 ()));
                            }
                        }
                        _ => ()
408
                    }
409
                    self.back -= 1;
410 411 412 413 414 415 416
                }
                None
            }
        }
    }
}

417
/// Forward iterator over a map.
P
Palmer Cox 已提交
418
pub struct Entries<'a, T> {
419 420 421
    front: uint,
    back: uint,
    iter: slice::Items<'a, Option<T>>
422 423
}

P
Palmer Cox 已提交
424 425
iterator!(impl Entries -> (uint, &'a T), get_ref)
double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
426

427 428
/// Forward iterator over the key-value pairs of a map, with the
/// values being mutable.
P
Palmer Cox 已提交
429
pub struct MutEntries<'a, T> {
430 431 432
    front: uint,
    back: uint,
    iter: slice::MutItems<'a, Option<T>>
433 434
}

P
Palmer Cox 已提交
435 436
iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
437

438 439 440 441 442 443 444 445
/// Forward iterator over the keys of a map
pub type Keys<'a, T> =
    iter::Map<'static, (uint, &'a T), uint, Entries<'a, T>>;

/// Forward iterator over the values of a map
pub type Values<'a, T> =
    iter::Map<'static, (uint, &'a T), &'a T, Entries<'a, T>>;

446
#[cfg(test)]
447
mod test_map {
448
    use std::prelude::*;
449

450
    use {Map, MutableMap, Mutable};
D
Daniel Micay 已提交
451
    use super::SmallIntMap;
D
Daniel Micay 已提交
452 453 454 455

    #[test]
    fn test_find_mut() {
        let mut m = SmallIntMap::new();
456
        assert!(m.insert(1, 12i));
P
Patrick Walton 已提交
457 458
        assert!(m.insert(2, 8));
        assert!(m.insert(5, 14));
D
Daniel Micay 已提交
459 460
        let new = 100;
        match m.find_mut(&5) {
461
            None => fail!(), Some(x) => *x = new
D
Daniel Micay 已提交
462 463 464
        }
        assert_eq!(m.find(&5), Some(&new));
    }
465 466 467

    #[test]
    fn test_len() {
D
Daniel Micay 已提交
468
        let mut map = SmallIntMap::new();
469
        assert_eq!(map.len(), 0);
P
Patrick Walton 已提交
470
        assert!(map.is_empty());
471
        assert!(map.insert(5, 20i));
472
        assert_eq!(map.len(), 1);
P
Patrick Walton 已提交
473 474
        assert!(!map.is_empty());
        assert!(map.insert(11, 12));
475
        assert_eq!(map.len(), 2);
P
Patrick Walton 已提交
476 477
        assert!(!map.is_empty());
        assert!(map.insert(14, 22));
478
        assert_eq!(map.len(), 3);
P
Patrick Walton 已提交
479
        assert!(!map.is_empty());
480 481 482 483
    }

    #[test]
    fn test_clear() {
D
Daniel Micay 已提交
484
        let mut map = SmallIntMap::new();
485
        assert!(map.insert(5, 20i));
P
Patrick Walton 已提交
486 487
        assert!(map.insert(11, 12));
        assert!(map.insert(14, 22));
488
        map.clear();
P
Patrick Walton 已提交
489 490 491 492
        assert!(map.is_empty());
        assert!(map.find(&5).is_none());
        assert!(map.find(&11).is_none());
        assert!(map.find(&14).is_none());
493 494 495 496
    }

    #[test]
    fn test_insert_with_key() {
D
Daniel Micay 已提交
497
        let mut map = SmallIntMap::new();
498

499
        // given a new key, initialize it with this new count,
500
        // given an existing key, add more to its count
501
        fn add_more_to_count(_k: uint, v0: uint, v1: uint) -> uint {
502 503 504
            v0 + v1
        }

505
        fn add_more_to_count_simple(v0: uint, v1: uint) -> uint {
506 507 508 509
            v0 + v1
        }

        // count integers
510 511 512 513 514
        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);
515 516

        // check the total counts
517 518 519
        assert_eq!(map.find(&3).unwrap(), &10);
        assert_eq!(map.find(&5).unwrap(), &3);
        assert_eq!(map.find(&9).unwrap(), &1);
520 521

        // sadly, no sevens were counted
P
Patrick Walton 已提交
522
        assert!(map.find(&7).is_none());
523
    }
524 525 526 527

    #[test]
    fn test_swap() {
        let mut m = SmallIntMap::new();
528 529 530
        assert_eq!(m.swap(1, 2i), None);
        assert_eq!(m.swap(1, 3i), Some(2));
        assert_eq!(m.swap(1, 4i), Some(3));
531 532 533 534 535
    }

    #[test]
    fn test_pop() {
        let mut m = SmallIntMap::new();
536
        m.insert(1, 2i);
537 538
        assert_eq!(m.pop(&1), Some(2));
        assert_eq!(m.pop(&1), None);
539
    }
540

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    #[test]
    fn test_keys() {
        let mut map = SmallIntMap::new();
        map.insert(1, 'a');
        map.insert(2, 'b');
        map.insert(3, 'c');
        let keys = map.keys().collect::<Vec<uint>>();
        assert_eq!(keys.len(), 3);
        assert!(keys.contains(&1));
        assert!(keys.contains(&2));
        assert!(keys.contains(&3));
    }

    #[test]
    fn test_values() {
        let mut map = SmallIntMap::new();
        map.insert(1, 'a');
        map.insert(2, 'b');
        map.insert(3, 'c');
        let values = map.values().map(|&v| v).collect::<Vec<char>>();
        assert_eq!(values.len(), 3);
        assert!(values.contains(&'a'));
        assert!(values.contains(&'b'));
        assert!(values.contains(&'c'));
    }

567 568
    #[test]
    fn test_iterator() {
569
        let mut m = SmallIntMap::new();
570

571
        assert!(m.insert(0, 1i));
572 573 574 575
        assert!(m.insert(1, 2));
        assert!(m.insert(3, 5));
        assert!(m.insert(6, 10));
        assert!(m.insert(10, 11));
576

577 578
        let mut it = m.iter();
        assert_eq!(it.size_hint(), (0, Some(11)));
579
        assert_eq!(it.next().unwrap(), (0, &1));
580
        assert_eq!(it.size_hint(), (0, Some(10)));
581
        assert_eq!(it.next().unwrap(), (1, &2));
582 583 584 585 586 587 588
        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)));
589 590 591
        assert!(it.next().is_none());
    }

592 593 594 595
    #[test]
    fn test_iterator_size_hints() {
        let mut m = SmallIntMap::new();

596
        assert!(m.insert(0, 1i));
597 598 599 600 601 602
        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)));
603
        assert_eq!(m.iter().rev().size_hint(), (0, Some(11)));
604
        assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
605
        assert_eq!(m.mut_iter().rev().size_hint(), (0, Some(11)));
606 607
    }

608 609
    #[test]
    fn test_mut_iterator() {
610
        let mut m = SmallIntMap::new();
611

612
        assert!(m.insert(0, 1i));
613 614 615 616
        assert!(m.insert(1, 2));
        assert!(m.insert(3, 5));
        assert!(m.insert(6, 10));
        assert!(m.insert(10, 11));
617

D
Daniel Micay 已提交
618
        for (k, v) in m.mut_iter() {
619
            *v += k as int;
620 621
        }

622 623 624 625 626 627 628
        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());
629 630 631 632
    }

    #[test]
    fn test_rev_iterator() {
633
        let mut m = SmallIntMap::new();
634

635
        assert!(m.insert(0, 1i));
636 637 638 639
        assert!(m.insert(1, 2));
        assert!(m.insert(3, 5));
        assert!(m.insert(6, 10));
        assert!(m.insert(10, 11));
640

641
        let mut it = m.iter().rev();
642 643 644 645 646 647
        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());
648 649 650 651
    }

    #[test]
    fn test_mut_rev_iterator() {
652
        let mut m = SmallIntMap::new();
653

654
        assert!(m.insert(0, 1i));
655 656 657 658
        assert!(m.insert(1, 2));
        assert!(m.insert(3, 5));
        assert!(m.insert(6, 10));
        assert!(m.insert(10, 11));
659

660
        for (k, v) in m.mut_iter().rev() {
661
            *v += k as int;
662 663
        }

664 665 666 667 668 669 670
        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());
671
    }
672 673

    #[test]
674
    fn test_move_iter() {
675
        let mut m = SmallIntMap::new();
676
        m.insert(1, box 2i);
677
        let mut called = false;
678
        for (k, v) in m.move_iter() {
679 680 681
            assert!(!called);
            called = true;
            assert_eq!(k, 1);
682
            assert_eq!(v, box 2i);
683 684
        }
        assert!(called);
685
        m.insert(2, box 1i);
686
    }
687 688 689 690 691 692

    #[test]
    fn test_show() {
        let mut map = SmallIntMap::new();
        let empty = SmallIntMap::<int>::new();

693 694
        map.insert(1, 2i);
        map.insert(3, 4i);
695

696
        let map_str = map.to_string();
697 698 699 700
        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());
    }
701
}
J
Jihyun Yu 已提交
702

G
Graydon Hoare 已提交
703 704
#[cfg(test)]
mod bench {
L
Liigo Zhuang 已提交
705
    extern crate test;
706
    use self::test::Bencher;
707 708
    use super::SmallIntMap;
    use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
G
Graydon Hoare 已提交
709 710 711

    // Find seq
    #[bench]
712
    pub fn insert_rand_100(b: &mut Bencher) {
G
Graydon Hoare 已提交
713
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
714
        insert_rand_n(100, &mut m, b);
G
Graydon Hoare 已提交
715 716 717
    }

    #[bench]
718
    pub fn insert_rand_10_000(b: &mut Bencher) {
G
Graydon Hoare 已提交
719
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
720
        insert_rand_n(10_000, &mut m, b);
G
Graydon Hoare 已提交
721 722 723 724
    }

    // Insert seq
    #[bench]
725
    pub fn insert_seq_100(b: &mut Bencher) {
G
Graydon Hoare 已提交
726
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
727
        insert_seq_n(100, &mut m, b);
G
Graydon Hoare 已提交
728 729 730
    }

    #[bench]
731
    pub fn insert_seq_10_000(b: &mut Bencher) {
G
Graydon Hoare 已提交
732
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
733
        insert_seq_n(10_000, &mut m, b);
G
Graydon Hoare 已提交
734 735 736 737
    }

    // Find rand
    #[bench]
738
    pub fn find_rand_100(b: &mut Bencher) {
G
Graydon Hoare 已提交
739
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
740
        find_rand_n(100, &mut m, b);
G
Graydon Hoare 已提交
741 742 743
    }

    #[bench]
744
    pub fn find_rand_10_000(b: &mut Bencher) {
G
Graydon Hoare 已提交
745
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
746
        find_rand_n(10_000, &mut m, b);
G
Graydon Hoare 已提交
747 748 749 750
    }

    // Find seq
    #[bench]
751
    pub fn find_seq_100(b: &mut Bencher) {
G
Graydon Hoare 已提交
752
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
753
        find_seq_n(100, &mut m, b);
G
Graydon Hoare 已提交
754 755 756
    }

    #[bench]
757
    pub fn find_seq_10_000(b: &mut Bencher) {
G
Graydon Hoare 已提交
758
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
759
        find_seq_n(10_000, &mut m, b);
G
Graydon Hoare 已提交
760 761
    }
}