Implement clone for hashmap

This commit is contained in:
Gwilym Inzani 2023-05-09 21:05:00 +01:00
parent 1cdf23683a
commit 5decb42cf0
3 changed files with 27 additions and 0 deletions

View file

@ -136,6 +136,7 @@ type HashType = u32;
/// println!("{game}: \"{review}\""); /// println!("{game}: \"{review}\"");
/// } /// }
/// ``` /// ```
#[derive(Clone)]
pub struct HashMap<K, V, ALLOCATOR: Allocator = Global> { pub struct HashMap<K, V, ALLOCATOR: Allocator = Global> {
nodes: NodeStorage<K, V, ALLOCATOR>, nodes: NodeStorage<K, V, ALLOCATOR>,

View file

@ -144,3 +144,28 @@ impl<K, V> Default for Node<K, V> {
Self::new() Self::new()
} }
} }
impl<K, V> Clone for Node<K, V>
where
K: Clone,
V: Clone,
{
fn clone(&self) -> Self {
if self.has_value() {
Self {
hash: self.hash,
distance_to_initial_bucket: self.distance_to_initial_bucket,
key: MaybeUninit::new(unsafe { self.key.assume_init_ref() }.clone()),
value: MaybeUninit::new(unsafe { self.value.assume_init_ref() }.clone()),
}
} else {
Self {
hash: self.hash,
distance_to_initial_bucket: self.distance_to_initial_bucket,
key: MaybeUninit::uninit(),
value: MaybeUninit::uninit(),
}
}
}
}

View file

@ -4,6 +4,7 @@ use alloc::{alloc::Global, vec::Vec};
use crate::{node::Node, number_before_resize, ClonableAllocator, HashType}; use crate::{node::Node, number_before_resize, ClonableAllocator, HashType};
#[derive(Clone)]
pub(crate) struct NodeStorage<K, V, ALLOCATOR: Allocator = Global> { pub(crate) struct NodeStorage<K, V, ALLOCATOR: Allocator = Global> {
nodes: Vec<Node<K, V>, ALLOCATOR>, nodes: Vec<Node<K, V>, ALLOCATOR>,
max_distance_to_initial_bucket: i32, max_distance_to_initial_bucket: i32,