oldmap.rs 21.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// 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.

11
//! A map type - **deprecated**, use `core::hashmap` instead
12
#[forbid(deprecated_mode)];
13

P
Patrick Walton 已提交
14
use core::cmp::Eq;
15 16 17 18 19 20
use core::hash::Hash;
use core::io::WriterUtil;
use core::io;
use core::ops;
use core::to_str::ToStr;
use core::mutable::Mut;
21
use core::prelude::*;
22 23 24
use core::to_bytes::IterBytes;
use core::uint;
use core::vec;
25

26
/// A convenience type to treat a hashmap as a set
27
pub type Set<K> = HashMap<K, ()>;
28

29
pub type HashMap<K, V> = chained::T<K, V>;
30

31
pub mod util {
32 33 34 35 36
    pub struct Rational {
        // : int::positive(*.den);
        num: int,
        den: int,
    }
B
Ben Blum 已提交
37

38
    pub pure fn rational_leq(x: Rational, y: Rational) -> bool {
B
Ben Blum 已提交
39 40 41 42 43 44 45
        // NB: Uses the fact that rationals have positive denominators WLOG:

        x.num * y.den <= y.num * x.den
    }
}


46 47
// FIXME (#2344): package this up and export it as a datatype usable for
// external code that doesn't want to pay the cost of a box.
48
pub mod chained {
49
    use super::util;
50 51 52 53

    use core::io;
    use core::ops;
    use core::option;
54
    use core::prelude::*;
55 56
    use core::uint;
    use core::vec;
N
Niko Matsakis 已提交
57

G
Glenn Willen 已提交
58 59
    const initial_capacity: uint = 32u; // 2^5

B
Brian Anderson 已提交
60
    struct Entry<K, V> {
61 62 63
        hash: uint,
        key: K,
        value: V,
B
Brian Anderson 已提交
64
        mut next: Option<@Entry<K, V>>
N
Niko Matsakis 已提交
65 66
    }

67
    struct HashMap_<K, V> {
68
        mut count: uint,
B
Brian Anderson 已提交
69
        mut chains: ~[mut Option<@Entry<K,V>>]
70 71
    }

72
    pub type T<K, V> = @HashMap_<K, V>;
73

B
Brian Anderson 已提交
74 75 76 77
    enum SearchResult<K, V> {
        NotFound,
        FoundFirst(uint, @Entry<K,V>),
        FoundAfter(@Entry<K,V>, @Entry<K,V>)
N
Niko Matsakis 已提交
78 79
    }

B
Brian Anderson 已提交
80
    priv impl<K:Eq IterBytes Hash, V: Copy> T<K, V> {
81
        pure fn search_rem(k: &K, h: uint, idx: uint,
B
Brian Anderson 已提交
82
                           e_root: @Entry<K,V>) -> SearchResult<K,V> {
N
Niko Matsakis 已提交
83 84 85
            let mut e0 = e_root;
            let mut comp = 1u;   // for logging
            loop {
86
                match copy e0.next {
B
Brian Anderson 已提交
87
                  None => {
P
Paul Stansifer 已提交
88 89
                    debug!("search_tbl: absent, comp %u, hash %u, idx %u",
                           comp, h, idx);
B
Brian Anderson 已提交
90
                    return NotFound;
N
Niko Matsakis 已提交
91
                  }
B
Brian Anderson 已提交
92
                  Some(e1) => {
N
Niko Matsakis 已提交
93
                    comp += 1u;
94
                    unsafe {
95
                        if e1.hash == h && e1.key == *k {
96 97 98
                            debug!("search_tbl: present, comp %u, \
                                    hash %u, idx %u",
                                   comp, h, idx);
B
Brian Anderson 已提交
99
                            return FoundAfter(e0, e1);
100 101 102
                        } else {
                            e0 = e1;
                        }
N
Niko Matsakis 已提交
103 104 105 106 107 108
                    }
                  }
                }
            };
        }

B
Brian Anderson 已提交
109
        pure fn search_tbl(k: &K, h: uint) -> SearchResult<K,V> {
N
Niko Matsakis 已提交
110
            let idx = h % vec::len(self.chains);
111
            match copy self.chains[idx] {
B
Brian Anderson 已提交
112
              None => {
P
Paul Stansifer 已提交
113 114
                debug!("search_tbl: none, comp %u, hash %u, idx %u",
                       0u, h, idx);
B
Brian Anderson 已提交
115
                return NotFound;
N
Niko Matsakis 已提交
116
              }
B
Brian Anderson 已提交
117
              Some(e) => {
118
                unsafe {
119
                    if e.hash == h && e.key == *k {
120 121
                        debug!("search_tbl: present, comp %u, hash %u, \
                                idx %u", 1u, h, idx);
B
Brian Anderson 已提交
122
                        return FoundFirst(idx, e);
123 124 125
                    } else {
                        return self.search_rem(k, h, idx, e);
                    }
N
Niko Matsakis 已提交
126 127 128 129 130
                }
              }
            }
        }

N
Niko Matsakis 已提交
131
        fn rehash() {
132
            let n_old_chains = self.chains.len();
N
Niko Matsakis 已提交
133 134
            let n_new_chains: uint = uint::next_power_of_two(n_old_chains+1u);
            let new_chains = chains(n_new_chains);
B
Brian Anderson 已提交
135
            for self.each_entry |entry| {
N
Niko Matsakis 已提交
136 137
                let idx = entry.hash % n_new_chains;
                entry.next = new_chains[idx];
B
Brian Anderson 已提交
138
                new_chains[idx] = Some(entry);
N
Niko Matsakis 已提交
139
            }
140
            self.chains = move new_chains;
N
Niko Matsakis 已提交
141 142
        }

B
Brian Anderson 已提交
143
        pure fn each_entry(blk: fn(@Entry<K,V>) -> bool) {
144 145 146
            // n.b. we can't use vec::iter() here because self.chains
            // is stored in a mutable location.
            let mut i = 0u, n = self.chains.len();
N
Niko Matsakis 已提交
147 148 149
            while i < n {
                let mut chain = self.chains[i];
                loop {
150
                    chain = match chain {
B
Brian Anderson 已提交
151 152
                      None => break,
                      Some(entry) => {
N
Niko Matsakis 已提交
153
                        let next = entry.next;
B
Brian Anderson 已提交
154
                        if !blk(entry) { return; }
N
Niko Matsakis 已提交
155 156 157
                        next
                      }
                    }
158
                }
N
Niko Matsakis 已提交
159
                i += 1u;
160
            }
N
Niko Matsakis 已提交
161 162 163
        }
    }

D
Daniel Micay 已提交
164
    impl<K:Eq IterBytes Hash Copy, V: Copy> T<K, V> {
165
        pure fn size() -> uint { self.count }
N
Niko Matsakis 已提交
166

167
        pure fn contains_key(k: K) -> bool {
168 169 170
            self.contains_key_ref(&k)
        }

171
        pure fn contains_key_ref(k: &K) -> bool {
172
            let hash = k.hash_keyed(0,0) as uint;
173
            match self.search_tbl(k, hash) {
B
Brian Anderson 已提交
174 175
              NotFound => false,
              FoundFirst(*) | FoundAfter(*) => true
N
Niko Matsakis 已提交
176 177 178
            }
        }

179
        fn insert(k: K, v: V) -> bool {
180
            let hash = k.hash_keyed(0,0) as uint;
181
            match self.search_tbl(&k, hash) {
B
Brian Anderson 已提交
182
              NotFound => {
N
Niko Matsakis 已提交
183 184 185
                self.count += 1u;
                let idx = hash % vec::len(self.chains);
                let old_chain = self.chains[idx];
B
Brian Anderson 已提交
186
                self.chains[idx] = Some(@Entry {
N
Niko Matsakis 已提交
187 188
                    hash: hash,
                    key: k,
189 190
                    value: v,
                    next: old_chain});
N
Niko Matsakis 已提交
191 192

                // consider rehashing if more 3/4 full
193
                let nchains = vec::len(self.chains);
194 195 196 197 198
                let load = util::Rational {
                    num: (self.count + 1u) as int,
                    den: nchains as int,
                };
                if !util::rational_leq(load, util::Rational {num:3, den:4}) {
N
Niko Matsakis 已提交
199 200 201
                    self.rehash();
                }

B
Brian Anderson 已提交
202
                return true;
N
Niko Matsakis 已提交
203
              }
B
Brian Anderson 已提交
204 205
              FoundFirst(idx, entry) => {
                self.chains[idx] = Some(@Entry {
206 207 208 209
                    hash: hash,
                    key: k,
                    value: v,
                    next: entry.next});
B
Brian Anderson 已提交
210
                return false;
N
Niko Matsakis 已提交
211
              }
B
Brian Anderson 已提交
212 213
              FoundAfter(prev, entry) => {
                prev.next = Some(@Entry {
214 215 216 217 218
                    hash: hash,
                    key: k,
                    value: v,
                    next: entry.next});
                return false;
N
Niko Matsakis 已提交
219
              }
220
            }
N
Niko Matsakis 已提交
221 222
        }

T
Tim Chevalier 已提交
223
        pure fn find(k: K) -> Option<V> {
224
            unsafe {
225
                match self.search_tbl(&k, k.hash_keyed(0,0) as uint) {
B
Brian Anderson 已提交
226 227 228
                  NotFound => None,
                  FoundFirst(_, entry) => Some(entry.value),
                  FoundAfter(_, entry) => Some(entry.value)
229
                }
N
Niko Matsakis 已提交
230 231
            }
        }
N
Niko Matsakis 已提交
232

233
        fn update_with_key(key: K, newval: V, ff: fn(K, V, V) -> V) -> bool {
K
Kevin Cantu 已提交
234
/*
235 236 237 238
            match self.find(key) {
                None            => return self.insert(key, val),
                Some(copy orig) => return self.insert(key, ff(key, orig, val))
            }
K
Kevin Cantu 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
*/

            let hash = key.hash_keyed(0,0) as uint;
            match self.search_tbl(&key, hash) {
              NotFound => {
                self.count += 1u;
                let idx = hash % vec::len(self.chains);
                let old_chain = self.chains[idx];
                self.chains[idx] = Some(@Entry {
                    hash: hash,
                    key: key,
                    value: newval,
                    next: old_chain});

                // consider rehashing if more 3/4 full
                let nchains = vec::len(self.chains);
255 256 257 258 259
                let load = util::Rational {
                    num: (self.count + 1u) as int,
                    den: nchains as int,
                };
                if !util::rational_leq(load, util::Rational {num:3, den:4}) {
K
Kevin Cantu 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
                    self.rehash();
                }

                return true;
              }
              FoundFirst(idx, entry) => {
                self.chains[idx] = Some(@Entry {
                    hash: hash,
                    key: key,
                    value: ff(key, entry.value, newval),
                    next: entry.next});
                return false;
              }
              FoundAfter(prev, entry) => {
                prev.next = Some(@Entry {
                    hash: hash,
                    key: key,
                    value: ff(key, entry.value, newval),
                    next: entry.next});
                return false;
              }
            }
        }

284 285
        fn update(key: K, newval: V, ff: fn(V, V) -> V) -> bool {
            return self.update_with_key(key, newval, |_k, v, v1| ff(v,v1));
286 287
        }

288
        pure fn get(k: K) -> V {
289 290
            let opt_v = self.find(k);
            if opt_v.is_none() {
291
                die!(fmt!("Key not found in table: %?", k));
292
            }
T
Tim Chevalier 已提交
293
            option::unwrap(move opt_v)
N
Niko Matsakis 已提交
294
        }
N
Niko Matsakis 已提交
295

T
Tim Chevalier 已提交
296
        fn remove(k: K) -> bool {
297
            match self.search_tbl(&k, k.hash_keyed(0,0) as uint) {
B
Brian Anderson 已提交
298 299
              NotFound => false,
              FoundFirst(idx, entry) => {
N
Niko Matsakis 已提交
300 301
                self.count -= 1u;
                self.chains[idx] = entry.next;
302
                true
N
Niko Matsakis 已提交
303
              }
B
Brian Anderson 已提交
304
              FoundAfter(eprev, entry) => {
N
Niko Matsakis 已提交
305 306
                self.count -= 1u;
                eprev.next = entry.next;
307
                true
N
Niko Matsakis 已提交
308 309 310
              }
            }
        }
N
Niko Matsakis 已提交
311

G
Glenn Willen 已提交
312 313 314 315 316
        fn clear() {
            self.count = 0u;
            self.chains = chains(initial_capacity);
        }

317
        pure fn each(blk: fn(key: K, value: V) -> bool) {
318 319 320
            self.each_ref(|k, v| blk(*k, *v))
        }

T
Tim Chevalier 已提交
321
        pure fn each_key(blk: fn(key: K) -> bool) {
322 323 324
            self.each_key_ref(|p| blk(*p))
        }

T
Tim Chevalier 已提交
325
        pure fn each_value(blk: fn(value: V) -> bool) {
326 327 328
            self.each_value_ref(|p| blk(*p))
        }

329
        pure fn each_ref(blk: fn(key: &K, value: &V) -> bool) {
B
Brian Anderson 已提交
330
            for self.each_entry |entry| {
331
                if !blk(&entry.key, &entry.value) { break; }
N
Niko Matsakis 已提交
332 333
            }
        }
N
Niko Matsakis 已提交
334

335
        pure fn each_key_ref(blk: fn(key: &K) -> bool) {
336 337
            self.each_ref(|k, _v| blk(k))
        }
N
Niko Matsakis 已提交
338

339
        pure fn each_value_ref(blk: fn(value: &V) -> bool) {
340 341
            self.each_ref(|_k, v| blk(v))
        }
N
Niko Matsakis 已提交
342
    }
N
Niko Matsakis 已提交
343

344
    impl<K:Eq IterBytes Hash Copy ToStr, V: ToStr Copy> T<K, V> {
345
        fn to_writer(wr: io::Writer) {
G
Glenn Willen 已提交
346
            if self.count == 0u {
347
                wr.write_str(~"{}");
B
Brian Anderson 已提交
348
                return;
G
Glenn Willen 已提交
349 350
            }

351
            wr.write_str(~"{ ");
G
Glenn Willen 已提交
352 353 354
            let mut first = true;
            for self.each_entry |entry| {
                if !first {
355
                    wr.write_str(~", ");
G
Glenn Willen 已提交
356 357 358
                }
                first = false;
                wr.write_str(entry.key.to_str());
359
                wr.write_str(~": ");
G
Glenn Willen 已提交
360 361
                wr.write_str((copy entry.value).to_str());
            };
362
            wr.write_str(~" }");
G
Glenn Willen 已提交
363
        }
364
    }
G
Glenn Willen 已提交
365

366
    impl<K:Eq IterBytes Hash Copy ToStr, V: ToStr Copy> T<K, V>: ToStr {
367 368 369 370 371
        pure fn to_str() -> ~str {
            unsafe {
                // Meh -- this should be safe
                do io::with_str_writer |wr| { self.to_writer(wr) }
            }
G
Glenn Willen 已提交
372 373 374
        }
    }

375 376 377 378 379 380 381
    impl<K:Eq IterBytes Hash Copy, V: Copy> T<K, V>: ops::Index<K, V> {
        pure fn index(&self, k: K) -> V {
            unsafe {
                self.get(k)
            }
        }
    }
382

B
Brian Anderson 已提交
383
    fn chains<K,V>(nchains: uint) -> ~[mut Option<@Entry<K,V>>] {
384
        vec::cast_to_mut(vec::from_elem(nchains, None))
N
Niko Matsakis 已提交
385 386
    }

387
    pub fn mk<K:Eq IterBytes Hash, V: Copy>() -> T<K,V> {
B
Brian Anderson 已提交
388
        let slf: T<K, V> = @HashMap_ {count: 0u,
389
                                      chains: chains(initial_capacity)};
390
        slf
N
Niko Matsakis 已提交
391 392 393
    }
}

N
Niko Matsakis 已提交
394
/*
395
Function: hashmap
N
Niko Matsakis 已提交
396 397 398

Construct a hashmap.
*/
399
pub fn HashMap<K:Eq IterBytes Hash Const, V: Copy>()
B
Brian Anderson 已提交
400
        -> HashMap<K, V> {
401
    chained::mk()
N
Niko Matsakis 已提交
402 403
}

404
/// Convenience function for adding keys to a hashmap with nil type keys
T
Tim Chevalier 已提交
405
pub fn set_add<K:Eq IterBytes Hash Const Copy>(set: Set<K>, key: K) -> bool {
406
    set.insert(key, ())
E
Eric Holk 已提交
407
}
408

409
/// Convert a set into a vector.
P
Patrick Walton 已提交
410
pub pure fn vec_from_set<T:Eq IterBytes Hash Copy>(s: Set<T>) -> ~[T] {
411 412 413 414 415
    do vec::build_sized(s.size()) |push| {
        for s.each_key() |k| {
            push(k);
        }
    }
416 417
}

418
/// Construct a hashmap from a vector
419
pub fn hash_from_vec<K: Eq IterBytes Hash Const Copy, V: Copy>(
B
Brian Anderson 已提交
420 421
    items: &[(K, V)]) -> HashMap<K, V> {
    let map = HashMap();
422 423
    for vec::each(items) |item| {
        match *item {
424
            (copy key, copy value) => {
425 426 427
                map.insert(key, value);
            }
        }
428 429 430 431
    }
    map
}

432 433
#[cfg(test)]
mod tests {
434
    use core::option::None;
435 436
    use core::option;
    use core::uint;
437

438 439
    use super::*;

440 441
    #[test]
    fn test_simple() {
P
Paul Stansifer 已提交
442
        debug!("*** starting test_simple");
443 444
        pure fn eq_uint(x: &uint, y: &uint) -> bool { *x == *y }
        pure fn uint_id(x: &uint) -> uint { *x }
P
Paul Stansifer 已提交
445
        debug!("uint -> uint");
446 447
        let hm_uu: HashMap<uint, uint> =
            HashMap::<uint, uint>();
448 449 450 451 452 453 454 455 456 457
        assert (hm_uu.insert(10u, 12u));
        assert (hm_uu.insert(11u, 13u));
        assert (hm_uu.insert(12u, 14u));
        assert (hm_uu.get(11u) == 13u);
        assert (hm_uu.get(12u) == 14u);
        assert (hm_uu.get(10u) == 12u);
        assert (!hm_uu.insert(12u, 14u));
        assert (hm_uu.get(12u) == 14u);
        assert (!hm_uu.insert(12u, 12u));
        assert (hm_uu.get(12u) == 12u);
458 459 460
        let ten: ~str = ~"ten";
        let eleven: ~str = ~"eleven";
        let twelve: ~str = ~"twelve";
P
Paul Stansifer 已提交
461
        debug!("str -> uint");
462 463
        let hm_su: HashMap<~str, uint> =
            HashMap::<~str, uint>();
464
        assert (hm_su.insert(~"ten", 12u));
465
        assert (hm_su.insert(eleven, 13u));
466
        assert (hm_su.insert(~"twelve", 14u));
467
        assert (hm_su.get(eleven) == 13u);
468 469 470 471 472 473 474
        assert (hm_su.get(~"eleven") == 13u);
        assert (hm_su.get(~"twelve") == 14u);
        assert (hm_su.get(~"ten") == 12u);
        assert (!hm_su.insert(~"twelve", 14u));
        assert (hm_su.get(~"twelve") == 14u);
        assert (!hm_su.insert(~"twelve", 12u));
        assert (hm_su.get(~"twelve") == 12u);
P
Paul Stansifer 已提交
475
        debug!("uint -> str");
476 477
        let hm_us: HashMap<uint, ~str> =
            HashMap::<uint, ~str>();
478 479 480
        assert (hm_us.insert(10u, ~"twelve"));
        assert (hm_us.insert(11u, ~"thirteen"));
        assert (hm_us.insert(12u, ~"fourteen"));
481 482 483
        assert hm_us.get(11u) == ~"thirteen";
        assert hm_us.get(12u) == ~"fourteen";
        assert hm_us.get(10u) == ~"twelve";
484
        assert (!hm_us.insert(12u, ~"fourteen"));
485
        assert hm_us.get(12u) == ~"fourteen";
486
        assert (!hm_us.insert(12u, ~"twelve"));
487
        assert hm_us.get(12u) == ~"twelve";
P
Paul Stansifer 已提交
488
        debug!("str -> str");
489 490
        let hm_ss: HashMap<~str, ~str> =
            HashMap::<~str, ~str>();
491 492 493
        assert (hm_ss.insert(ten, ~"twelve"));
        assert (hm_ss.insert(eleven, ~"thirteen"));
        assert (hm_ss.insert(twelve, ~"fourteen"));
494 495 496
        assert hm_ss.get(~"eleven") == ~"thirteen";
        assert hm_ss.get(~"twelve") == ~"fourteen";
        assert hm_ss.get(~"ten") == ~"twelve";
497
        assert (!hm_ss.insert(~"twelve", ~"fourteen"));
498
        assert hm_ss.get(~"twelve") == ~"fourteen";
499
        assert (!hm_ss.insert(~"twelve", ~"twelve"));
500
        assert hm_ss.get(~"twelve") == ~"twelve";
P
Paul Stansifer 已提交
501
        debug!("*** finished test_simple");
502 503 504 505 506 507 508 509
    }


    /**
    * Force map growth
    */
    #[test]
    fn test_growth() {
P
Paul Stansifer 已提交
510
        debug!("*** starting test_growth");
511
        let num_to_insert: uint = 64u;
512 513
        pure fn eq_uint(x: &uint, y: &uint) -> bool { *x == *y }
        pure fn uint_id(x: &uint) -> uint { *x }
P
Paul Stansifer 已提交
514
        debug!("uint -> uint");
515 516
        let hm_uu: HashMap<uint, uint> =
            HashMap::<uint, uint>();
517
        let mut i: uint = 0u;
518 519
        while i < num_to_insert {
            assert (hm_uu.insert(i, i * i));
P
Paul Stansifer 已提交
520
            debug!("inserting %u -> %u", i, i*i);
521 522
            i += 1u;
        }
P
Paul Stansifer 已提交
523
        debug!("-----");
524 525
        i = 0u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
526
            debug!("get(%u) = %u", i, hm_uu.get(i));
527 528 529 530 531
            assert (hm_uu.get(i) == i * i);
            i += 1u;
        }
        assert (hm_uu.insert(num_to_insert, 17u));
        assert (hm_uu.get(num_to_insert) == 17u);
P
Paul Stansifer 已提交
532
        debug!("-----");
533 534
        i = 0u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
535
            debug!("get(%u) = %u", i, hm_uu.get(i));
536 537 538
            assert (hm_uu.get(i) == i * i);
            i += 1u;
        }
P
Paul Stansifer 已提交
539
        debug!("str -> str");
540 541
        let hm_ss: HashMap<~str, ~str> =
            HashMap::<~str, ~str>();
542 543 544
        i = 0u;
        while i < num_to_insert {
            assert hm_ss.insert(uint::to_str(i, 2u), uint::to_str(i * i, 2u));
P
Paul Stansifer 已提交
545
            debug!("inserting \"%s\" -> \"%s\"",
546
                   uint::to_str(i, 2u),
P
Paul Stansifer 已提交
547
                   uint::to_str(i*i, 2u));
548 549
            i += 1u;
        }
P
Paul Stansifer 已提交
550
        debug!("-----");
551 552
        i = 0u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
553
            debug!("get(\"%s\") = \"%s\"",
554
                   uint::to_str(i, 2u),
P
Paul Stansifer 已提交
555
                   hm_ss.get(uint::to_str(i, 2u)));
556
            assert hm_ss.get(uint::to_str(i, 2u)) == uint::to_str(i * i, 2u);
557 558 559 560
            i += 1u;
        }
        assert (hm_ss.insert(uint::to_str(num_to_insert, 2u),
                             uint::to_str(17u, 2u)));
561 562
        assert hm_ss.get(uint::to_str(num_to_insert, 2u)) ==
            uint::to_str(17u, 2u);
P
Paul Stansifer 已提交
563
        debug!("-----");
564 565
        i = 0u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
566
            debug!("get(\"%s\") = \"%s\"",
567
                   uint::to_str(i, 2u),
P
Paul Stansifer 已提交
568
                   hm_ss.get(uint::to_str(i, 2u)));
569
            assert hm_ss.get(uint::to_str(i, 2u)) == uint::to_str(i * i, 2u);
570 571
            i += 1u;
        }
P
Paul Stansifer 已提交
572
        debug!("*** finished test_growth");
573 574 575 576
    }

    #[test]
    fn test_removal() {
P
Paul Stansifer 已提交
577
        debug!("*** starting test_removal");
578
        let num_to_insert: uint = 64u;
579 580
        let hm: HashMap<uint, uint> =
            HashMap::<uint, uint>();
581
        let mut i: uint = 0u;
582 583
        while i < num_to_insert {
            assert (hm.insert(i, i * i));
P
Paul Stansifer 已提交
584
            debug!("inserting %u -> %u", i, i*i);
585 586 587
            i += 1u;
        }
        assert (hm.size() == num_to_insert);
P
Paul Stansifer 已提交
588 589
        debug!("-----");
        debug!("removing evens");
590 591 592
        i = 0u;
        while i < num_to_insert {
            let v = hm.remove(i);
593
            assert v;
594 595 596
            i += 2u;
        }
        assert (hm.size() == num_to_insert / 2u);
P
Paul Stansifer 已提交
597
        debug!("-----");
598 599
        i = 1u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
600
            debug!("get(%u) = %u", i, hm.get(i));
601 602 603
            assert (hm.get(i) == i * i);
            i += 2u;
        }
P
Paul Stansifer 已提交
604
        debug!("-----");
605 606
        i = 1u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
607
            debug!("get(%u) = %u", i, hm.get(i));
608 609 610
            assert (hm.get(i) == i * i);
            i += 2u;
        }
P
Paul Stansifer 已提交
611
        debug!("-----");
612 613 614
        i = 0u;
        while i < num_to_insert {
            assert (hm.insert(i, i * i));
P
Paul Stansifer 已提交
615
            debug!("inserting %u -> %u", i, i*i);
616 617 618
            i += 2u;
        }
        assert (hm.size() == num_to_insert);
P
Paul Stansifer 已提交
619
        debug!("-----");
620 621
        i = 0u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
622
            debug!("get(%u) = %u", i, hm.get(i));
623 624 625
            assert (hm.get(i) == i * i);
            i += 1u;
        }
P
Paul Stansifer 已提交
626
        debug!("-----");
627 628 629
        assert (hm.size() == num_to_insert);
        i = 0u;
        while i < num_to_insert {
P
Paul Stansifer 已提交
630
            debug!("get(%u) = %u", i, hm.get(i));
631 632 633
            assert (hm.get(i) == i * i);
            i += 1u;
        }
P
Paul Stansifer 已提交
634
        debug!("*** finished test_removal");
635 636 637 638
    }

    #[test]
    fn test_contains_key() {
639
        let key = ~"k";
640
        let map = HashMap::<~str, ~str>();
641
        assert (!map.contains_key(key));
642
        map.insert(key, ~"val");
643 644 645 646 647
        assert (map.contains_key(key));
    }

    #[test]
    fn test_find() {
648
        let key = ~"k";
649
        let map = HashMap::<~str, ~str>();
B
Brian Anderson 已提交
650
        assert (option::is_none(&map.find(key)));
651
        map.insert(key, ~"val");
652
        assert (option::get(map.find(key)) == ~"val");
653
    }
654

G
Glenn Willen 已提交
655 656
    #[test]
    fn test_clear() {
657
        let key = ~"k";
658
        let map = HashMap::<~str, ~str>();
659
        map.insert(key, ~"val");
G
Glenn Willen 已提交
660 661 662 663 664 665 666
        assert (map.size() == 1);
        assert (map.contains_key(key));
        map.clear();
        assert (map.size() == 0);
        assert (!map.contains_key(key));
    }

667 668
    #[test]
    fn test_hash_from_vec() {
669
        let map = hash_from_vec(~[
670 671 672
            (~"a", 1),
            (~"b", 2),
            (~"c", 3)
673
        ]);
674
        assert map.size() == 3u;
675 676 677
        assert map.get(~"a") == 1;
        assert map.get(~"b") == 2;
        assert map.get(~"c") == 3;
678
    }
K
Kevin Cantu 已提交
679 680

    #[test]
681
    fn test_update_with_key() {
682
        let map = HashMap::<~str, uint>();
K
Kevin Cantu 已提交
683

K
Kevin Cantu 已提交
684 685 686 687 688 689 690
        // given a new key, initialize it with this new count, given
        // given an existing key, add more to its count
        fn addMoreToCount(_k: ~str, v0: uint, v1: uint) -> uint {
            v0 + v1
        }

        fn addMoreToCount_simple(v0: uint, v1: uint) -> uint {
K
Kevin Cantu 已提交
691 692 693
            v0 + v1
        }

K
Kevin Cantu 已提交
694 695
        // count the number of several types of animal,
        // adding in groups as we go
696 697 698 699 700
        map.update(~"cat",      1, addMoreToCount_simple);
        map.update_with_key(~"mongoose", 1, addMoreToCount);
        map.update(~"cat",      7, addMoreToCount_simple);
        map.update_with_key(~"ferret",   3, addMoreToCount);
        map.update_with_key(~"cat",      2, addMoreToCount);
K
Kevin Cantu 已提交
701

K
Kevin Cantu 已提交
702
        // check the total counts
K
Kevin Cantu 已提交
703 704 705 706
        assert 10 == option::get(map.find(~"cat"));
        assert  3 == option::get(map.find(~"ferret"));
        assert  1 == option::get(map.find(~"mongoose"));

K
Kevin Cantu 已提交
707
        // sadly, no mythical animals were counted!
K
Kevin Cantu 已提交
708 709
        assert None == map.find(~"unicorn");
    }
E
Erick Tryzelaar 已提交
710
}