Initial commit.

This commit is contained in:
Jesse Brault 2024-11-23 17:58:43 -06:00
commit ae1bf26ada
4 changed files with 81 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
.idea

7
Cargo.lock generated Normal file
View File

@ -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"

6
Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "rust-hash-map"
version = "0.1.0"
edition = "2021"
[dependencies]

66
src/main.rs Normal file
View File

@ -0,0 +1,66 @@
struct HashMap<'a, K: PartialEq, V> {
table: Vec<Option<Vec<(&'a K, &'a V)>>>,
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<String, String> = HashMap::new(8, |s| s.len());
map.put(&jesse, &brault);
assert_eq!(map.get(&jesse), Some(&brault));
}
}
fn main() {
println!("Hello, world!");
}