Fix implementation; tests passing.
This commit is contained in:
parent
ae1bf26ada
commit
6229ba7acc
23
src/main.rs
23
src/main.rs
@ -4,13 +4,21 @@ struct HashMap<'a, K: PartialEq, V> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, K: PartialEq, V> HashMap<'a, K, V> {
|
impl<'a, K: PartialEq, V> HashMap<'a, K, V> {
|
||||||
fn new(capacity: usize, hash_fn: fn(&K) -> usize) -> Self {
|
fn new(hash_fn: fn(&K) -> usize) -> Self {
|
||||||
HashMap {
|
HashMap {
|
||||||
table: Vec::with_capacity(capacity),
|
table: vec![None; 16],
|
||||||
hash_fn,
|
hash_fn,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fn with_capacity(capacity: usize, hash_fn: fn(&K) -> usize) -> Self {
|
||||||
|
HashMap {
|
||||||
|
table: vec![None; capacity],
|
||||||
|
hash_fn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn put(&mut self, k: &'a K, v: &'a V) {
|
fn put(&mut self, k: &'a K, v: &'a V) {
|
||||||
let hash = (self.hash_fn)(&k);
|
let hash = (self.hash_fn)(&k);
|
||||||
let target_index = hash % self.table.capacity();
|
let target_index = hash % self.table.capacity();
|
||||||
@ -55,7 +63,16 @@ mod hash_map_tests {
|
|||||||
fn simple_put_and_get() {
|
fn simple_put_and_get() {
|
||||||
let jesse = String::from("Jesse");
|
let jesse = String::from("Jesse");
|
||||||
let brault = String::from("Brault");
|
let brault = String::from("Brault");
|
||||||
let mut map: HashMap<String, String> = HashMap::new(8, |s| s.len());
|
let mut map: HashMap<String, String> = HashMap::new(|s| s.len());
|
||||||
|
map.put(&jesse, &brault);
|
||||||
|
assert_eq!(map.get(&jesse), Some(&brault));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn put_and_get_with_str() {
|
||||||
|
let jesse = "Jesse";
|
||||||
|
let brault = "Brault";
|
||||||
|
let mut map: HashMap<&str, &str> = HashMap::new(|s| s.len());
|
||||||
map.put(&jesse, &brault);
|
map.put(&jesse, &brault);
|
||||||
assert_eq!(map.get(&jesse), Some(&brault));
|
assert_eq!(map.get(&jesse), Some(&brault));
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user