From ae1bf26ada1882ed8c4c9033319f24b594b4423e Mon Sep 17 00:00:00 2001 From: Jesse Brault Date: Sat, 23 Nov 2024 17:58:43 -0600 Subject: [PATCH] Initial commit. --- .gitignore | 2 ++ Cargo.lock | 7 ++++++ Cargo.toml | 6 +++++ src/main.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2a0038a --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/target +.idea \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..4aef62f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "rust-hash-map" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..21ec434 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "rust-hash-map" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e0b4ff0 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,66 @@ +struct HashMap<'a, K: PartialEq, V> { + table: Vec>>, + hash_fn: fn(&K) -> usize, +} + +impl<'a, K: PartialEq, V> HashMap<'a, K, V> { + fn new(capacity: usize, hash_fn: fn(&K) -> usize) -> Self { + HashMap { + table: Vec::with_capacity(capacity), + hash_fn, + } + } + + fn put(&mut self, k: &'a K, v: &'a V) { + let hash = (self.hash_fn)(&k); + let target_index = hash % self.table.capacity(); + match self.table[target_index].take() { + None => { + let new_container = vec![(k, v)]; + self.table.insert(target_index, Some(new_container)); + }, + Some(mut container) => { + container.push((k, v)); + self.table.insert(target_index, Some(container)); + } + } + } + + fn get(&mut self, k: &K) -> Option<&V> { + let hash = (self.hash_fn)(&k); + let target_index = hash % self.table.capacity(); + let container_opt = self.table[target_index].take(); + if container_opt.is_none() { + None + } else { + let container = container_opt.unwrap(); + for item in container.iter() { + if item.0 == k { + let result = Some(item.1); + self.table[target_index] = Some(container); + return result; + } + } + self.table[target_index] = Some(container); + None + } + } +} + +#[cfg(test)] +mod hash_map_tests { + use super::*; + + #[test] + fn simple_put_and_get() { + let jesse = String::from("Jesse"); + let brault = String::from("Brault"); + let mut map: HashMap = HashMap::new(8, |s| s.len()); + map.put(&jesse, &brault); + assert_eq!(map.get(&jesse), Some(&brault)); + } +} + +fn main() { + println!("Hello, world!"); +}