-
-
Save RandyMcMillan/81c517b4c87d7e8e88de389d6e776dda to your computer and use it in GitHub Desktop.
hashmap.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::collections::hash_map::DefaultHasher; | |
use std::hash::{Hash, Hasher}; | |
#[derive(Debug, Clone)] | |
struct HashMap<K, V> | |
where | |
K: Eq + Hash + Clone, | |
V: Clone, | |
{ | |
// Buckets for storing key-value pairs | |
buckets: Vec<Option<(K, V)>>, | |
// Capacity of the hashmap | |
capacity: usize, | |
} | |
impl<K, V> HashMap<K, V> | |
where | |
K: Eq + Hash + Clone, | |
V: Clone, | |
{ | |
fn new(capacity: usize) -> Self { | |
HashMap { | |
buckets: vec![None; capacity], | |
capacity, | |
} | |
} | |
fn hash(&self, key: &K) -> usize { | |
let mut hasher = DefaultHasher::new(); | |
key.hash(&mut hasher); | |
hasher.finish() as usize % self.capacity | |
} | |
fn insert(&mut self, key: K, value: V) { | |
let index = self.hash(&key); | |
match &mut self.buckets[index] { | |
Some((k, _)) if k == &key => { | |
// Update existing value | |
self.buckets[index] = Some((key, value)); | |
} | |
_ => { | |
// Insert new key-value pair | |
self.buckets[index] = Some((key, value)); | |
} | |
} | |
} | |
fn get(&self, key: &K) -> Option<&V> { | |
let index = self.hash(key); | |
match &self.buckets[index] { | |
Some((k, v)) if k == key => Some(v), | |
_ => None, | |
} | |
} | |
fn remove(&mut self, key: &K) -> Option<V> { | |
let index = self.hash(key); | |
match self.buckets[index].take() { | |
Some((k, v)) if k == *key => Some(v), | |
_ => None, | |
} | |
} | |
} | |
// Example usage | |
fn main() { | |
let mut map = HashMap::new(10); | |
map.insert(String::from("key1"), 1); | |
map.insert(String::from("key2"), 2); | |
map.insert(String::from("key1"), 3); // Update value for "key1" | |
println!("{:?}", map); | |
println!("Value for key1: {:?}", map.get(&String::from("key1"))); | |
println!("Value for key2: {:?}", map.get(&String::from("key2"))); | |
map.remove(&String::from("key1")); | |
println!("After removing key1: {:?}", map); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment