smallintmap.rs 15.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright 2012 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).
 */

16 17
#[allow(missing_doc)];

S
Sean Chalmers 已提交
18
use std::iter::{Enumerate, FilterMap, Rev};
19
use std::mem::replace;
20
use std::vec;
21

22
#[allow(missing_doc)]
D
Daniel Micay 已提交
23 24
pub struct SmallIntMap<T> {
    priv v: ~[Option<T>],
25 26
}

27
impl<V> Container for SmallIntMap<V> {
28
    /// Return the number of elements in the map
D
Daniel Micay 已提交
29
    fn len(&self) -> uint {
30 31 32 33 34 35
        self.v.iter().count(|elt| elt.is_some())
    }

    /// Return true if there are no elements in the map
    fn is_empty(&self) -> bool {
        self.v.iter().all(|elt| elt.is_none())
36 37 38
    }
}

39
impl<V> Mutable for SmallIntMap<V> {
D
Daniel Micay 已提交
40 41
    /// Clear the map, removing all key-value pairs.
    fn clear(&mut self) { self.v.clear() }
42 43
}

44
impl<V> Map<uint, V> for SmallIntMap<V> {
D
Daniel Micay 已提交
45
    /// Return a reference to the value corresponding to the key
46 47 48 49 50 51 52 53 54 55
    fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
        if *key < self.v.len() {
            match self.v[*key] {
              Some(ref value) => Some(value),
              None => None
            }
        } else {
            None
        }
    }
56
}
57

58
impl<V> MutableMap<uint, V> for SmallIntMap<V> {
D
Daniel Micay 已提交
59
    /// Return a mutable reference to the value corresponding to the key
60 61 62 63 64 65 66 67 68 69 70
    fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
        if *key < self.v.len() {
            match self.v[*key] {
              Some(ref mut value) => Some(value),
              None => None
            }
        } else {
            None
        }
    }

D
Daniel Micay 已提交
71 72 73 74 75 76 77
    /// 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 {
78
            self.v.grow_fn(key - len + 1, |_| None);
D
Daniel Micay 已提交
79 80 81
        }
        self.v[key] = Some(value);
        !exists
82 83
    }

D
Daniel Micay 已提交
84 85 86
    /// 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 {
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
        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> {
D
Daniel Micay 已提交
104
        if *key >= self.v.len() {
105
            return None;
106
        }
107
        self.v[*key].take()
108
    }
D
Daniel Micay 已提交
109 110
}

111
impl<V> SmallIntMap<V> {
D
Daniel Micay 已提交
112
    /// Create an empty SmallIntMap
113
    pub fn new() -> SmallIntMap<V> { SmallIntMap{v: ~[]} }
D
Daniel Micay 已提交
114

115
    pub fn get<'a>(&'a self, key: &uint) -> &'a V {
116 117
        self.find(key).expect("key not present")
    }
118 119 120

    /// An iterator visiting all key-value pairs in ascending order by the keys.
    /// Iterator element type is (uint, &'r V)
P
Palmer Cox 已提交
121 122
    pub fn iter<'r>(&'r self) -> Entries<'r, V> {
        Entries {
123 124 125
            front: 0,
            back: self.v.len(),
            iter: self.v.iter()
126 127 128 129 130 131
        }
    }

    /// 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)
P
Palmer Cox 已提交
132 133
    pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
        MutEntries {
134 135 136
            front: 0,
            back: self.v.len(),
            iter: self.v.mut_iter()
137 138 139 140 141
        }
    }

    /// An iterator visiting all key-value pairs in descending order by the keys.
    /// Iterator element type is (uint, &'r V)
P
Palmer Cox 已提交
142
    pub fn rev_iter<'r>(&'r self) -> RevEntries<'r, V> {
S
Sean Chalmers 已提交
143
        self.iter().rev()
144 145 146 147 148
    }

    /// An iterator visiting all key-value pairs in descending order by the keys,
    /// with mutable references to the values
    /// Iterator element type is (uint, &'r mut V)
P
Palmer Cox 已提交
149
    pub fn mut_rev_iter<'r>(&'r mut self) -> RevMutEntries <'r, V> {
S
Sean Chalmers 已提交
150
        self.mut_iter().rev()
151
    }
152 153

    /// Empties the hash map, moving all values into the specified closure
154
    pub fn move_iter(&mut self)
155
        -> FilterMap<(uint, Option<V>), (uint, V),
P
Palmer Cox 已提交
156
                Enumerate<vec::MoveItems<Option<V>>>>
157 158
    {
        let values = replace(&mut self.v, ~[]);
159
        values.move_iter().enumerate().filter_map(|(i, v)| {
160
            v.map(|v| (i, v))
161 162
        })
    }
163 164
}

165
impl<V:Clone> SmallIntMap<V> {
166 167 168 169 170
    pub fn update_with_key(&mut self,
                           key: uint,
                           val: V,
                           ff: |uint, V, V| -> V)
                           -> bool {
171 172
        let new_val = match self.find(&key) {
            None => val,
173
            Some(orig) => ff(key, (*orig).clone(), val)
174 175
        };
        self.insert(key, new_val)
176
    }
D
Daniel Micay 已提交
177

178
    pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
D
Daniel Micay 已提交
179 180
        self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
    }
181 182
}

183 184

macro_rules! iterator {
185
    (impl $name:ident -> $elem:ty, $getter:ident) => {
E
Erik Price 已提交
186
        impl<'a, T> Iterator<$elem> for $name<'a, T> {
187
            #[inline]
188 189 190 191 192 193 194 195 196 197 198
            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 ()));
                            }
                        }
                        _ => ()
199
                    }
200
                    self.front += 1;
201 202 203
                }
                None
            }
204 205 206 207 208

            #[inline]
            fn size_hint(&self) -> (uint, Option<uint>) {
                (0, Some(self.back - self.front))
            }
209 210 211 212
        }
    }
}

213 214
macro_rules! double_ended_iterator {
    (impl $name:ident -> $elem:ty, $getter:ident) => {
E
Erik Price 已提交
215
        impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
216
            #[inline]
217 218 219 220 221 222 223 224 225 226
            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 ()));
                            }
                        }
                        _ => ()
227
                    }
228
                    self.back -= 1;
229 230 231 232 233 234 235
                }
                None
            }
        }
    }
}

P
Palmer Cox 已提交
236
pub struct Entries<'a, T> {
237 238
    priv front: uint,
    priv back: uint,
P
Palmer Cox 已提交
239
    priv iter: vec::Items<'a, Option<T>>
240 241
}

P
Palmer Cox 已提交
242 243
iterator!(impl Entries -> (uint, &'a T), get_ref)
double_ended_iterator!(impl Entries -> (uint, &'a T), get_ref)
S
Sean Chalmers 已提交
244
pub type RevEntries<'a, T> = Rev<Entries<'a, T>>;
245

P
Palmer Cox 已提交
246
pub struct MutEntries<'a, T> {
247 248
    priv front: uint,
    priv back: uint,
P
Palmer Cox 已提交
249
    priv iter: vec::MutItems<'a, Option<T>>
250 251
}

P
Palmer Cox 已提交
252 253
iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
double_ended_iterator!(impl MutEntries -> (uint, &'a mut T), get_mut_ref)
S
Sean Chalmers 已提交
254
pub type RevMutEntries<'a, T> = Rev<MutEntries<'a, T>>;
255

256
#[cfg(test)]
257
mod test_map {
258

D
Daniel Micay 已提交
259
    use super::SmallIntMap;
D
Daniel Micay 已提交
260 261 262 263

    #[test]
    fn test_find_mut() {
        let mut m = SmallIntMap::new();
P
Patrick Walton 已提交
264 265 266
        assert!(m.insert(1, 12));
        assert!(m.insert(2, 8));
        assert!(m.insert(5, 14));
D
Daniel Micay 已提交
267 268
        let new = 100;
        match m.find_mut(&5) {
269
            None => fail!(), Some(x) => *x = new
D
Daniel Micay 已提交
270 271 272
        }
        assert_eq!(m.find(&5), Some(&new));
    }
273 274 275

    #[test]
    fn test_len() {
D
Daniel Micay 已提交
276
        let mut map = SmallIntMap::new();
277
        assert_eq!(map.len(), 0);
P
Patrick Walton 已提交
278 279
        assert!(map.is_empty());
        assert!(map.insert(5, 20));
280
        assert_eq!(map.len(), 1);
P
Patrick Walton 已提交
281 282
        assert!(!map.is_empty());
        assert!(map.insert(11, 12));
283
        assert_eq!(map.len(), 2);
P
Patrick Walton 已提交
284 285
        assert!(!map.is_empty());
        assert!(map.insert(14, 22));
286
        assert_eq!(map.len(), 3);
P
Patrick Walton 已提交
287
        assert!(!map.is_empty());
288 289 290 291
    }

    #[test]
    fn test_clear() {
D
Daniel Micay 已提交
292
        let mut map = SmallIntMap::new();
P
Patrick Walton 已提交
293 294 295
        assert!(map.insert(5, 20));
        assert!(map.insert(11, 12));
        assert!(map.insert(14, 22));
296
        map.clear();
P
Patrick Walton 已提交
297 298 299 300
        assert!(map.is_empty());
        assert!(map.find(&5).is_none());
        assert!(map.find(&11).is_none());
        assert!(map.find(&14).is_none());
301 302 303 304
    }

    #[test]
    fn test_insert_with_key() {
D
Daniel Micay 已提交
305
        let mut map = SmallIntMap::new();
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

        // given a new key, initialize it with this new count, given
        // given an existing key, add more to its count
        fn addMoreToCount(_k: uint, v0: uint, v1: uint) -> uint {
            v0 + v1
        }

        fn addMoreToCount_simple(v0: uint, v1: uint) -> uint {
            v0 + v1
        }

        // count integers
        map.update(3, 1, addMoreToCount_simple);
        map.update_with_key(9, 1, addMoreToCount);
        map.update(3, 7, addMoreToCount_simple);
        map.update_with_key(5, 3, addMoreToCount);
        map.update_with_key(3, 2, addMoreToCount);

        // check the total counts
325 326 327
        assert_eq!(map.find(&3).unwrap(), &10);
        assert_eq!(map.find(&5).unwrap(), &3);
        assert_eq!(map.find(&9).unwrap(), &1);
328 329

        // sadly, no sevens were counted
P
Patrick Walton 已提交
330
        assert!(map.find(&7).is_none());
331
    }
332 333 334 335

    #[test]
    fn test_swap() {
        let mut m = SmallIntMap::new();
336 337 338
        assert_eq!(m.swap(1, 2), None);
        assert_eq!(m.swap(1, 3), Some(2));
        assert_eq!(m.swap(1, 4), Some(3));
339 340 341 342 343 344
    }

    #[test]
    fn test_pop() {
        let mut m = SmallIntMap::new();
        m.insert(1, 2);
345 346
        assert_eq!(m.pop(&1), Some(2));
        assert_eq!(m.pop(&1), None);
347
    }
348 349 350

    #[test]
    fn test_iterator() {
351
        let mut m = SmallIntMap::new();
352

353 354 355 356 357
        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));
358

359 360
        let mut it = m.iter();
        assert_eq!(it.size_hint(), (0, Some(11)));
361
        assert_eq!(it.next().unwrap(), (0, &1));
362
        assert_eq!(it.size_hint(), (0, Some(10)));
363
        assert_eq!(it.next().unwrap(), (1, &2));
364 365 366 367 368 369 370
        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)));
371 372 373
        assert!(it.next().is_none());
    }

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    #[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)));
        assert_eq!(m.rev_iter().size_hint(), (0, Some(11)));
        assert_eq!(m.mut_iter().size_hint(), (0, Some(11)));
        assert_eq!(m.mut_rev_iter().size_hint(), (0, Some(11)));
    }

390 391
    #[test]
    fn test_mut_iterator() {
392
        let mut m = SmallIntMap::new();
393

394 395 396 397 398
        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));
399

D
Daniel Micay 已提交
400
        for (k, v) in m.mut_iter() {
401
            *v += k as int;
402 403
        }

404 405 406 407 408 409 410
        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());
411 412 413 414
    }

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

417 418 419 420 421
        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));
422

423 424 425 426 427 428 429
        let mut it = m.rev_iter();
        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());
430 431 432 433
    }

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

436 437 438 439 440
        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));
441

D
Daniel Micay 已提交
442
        for (k, v) in m.mut_rev_iter() {
443
            *v += k as int;
444 445
        }

446 447 448 449 450 451 452
        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());
453
    }
454 455

    #[test]
456
    fn test_move_iter() {
457 458 459
        let mut m = SmallIntMap::new();
        m.insert(1, ~2);
        let mut called = false;
460
        for (k, v) in m.move_iter() {
461 462 463 464 465 466 467 468
            assert!(!called);
            called = true;
            assert_eq!(k, 1);
            assert_eq!(v, ~2);
        }
        assert!(called);
        m.insert(2, ~1);
    }
469
}
J
Jihyun Yu 已提交
470

G
Graydon Hoare 已提交
471 472
#[cfg(test)]
mod bench {
L
Liigo Zhuang 已提交
473 474
    extern crate test;
    use self::test::BenchHarness;
475 476
    use super::SmallIntMap;
    use deque::bench::{insert_rand_n, insert_seq_n, find_rand_n, find_seq_n};
G
Graydon Hoare 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529

    // Find seq
    #[bench]
    pub fn insert_rand_100(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        insert_rand_n(100, &mut m, bh);
    }

    #[bench]
    pub fn insert_rand_10_000(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        insert_rand_n(10_000, &mut m, bh);
    }

    // Insert seq
    #[bench]
    pub fn insert_seq_100(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        insert_seq_n(100, &mut m, bh);
    }

    #[bench]
    pub fn insert_seq_10_000(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        insert_seq_n(10_000, &mut m, bh);
    }

    // Find rand
    #[bench]
    pub fn find_rand_100(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        find_rand_n(100, &mut m, bh);
    }

    #[bench]
    pub fn find_rand_10_000(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        find_rand_n(10_000, &mut m, bh);
    }

    // Find seq
    #[bench]
    pub fn find_seq_100(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        find_seq_n(100, &mut m, bh);
    }

    #[bench]
    pub fn find_seq_10_000(bh: &mut BenchHarness) {
        let mut m : SmallIntMap<uint> = SmallIntMap::new();
        find_seq_n(10_000, &mut m, bh);
    }
}