Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
170 changes: 27 additions & 143 deletions aaa-stdlib/src/map.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,19 @@
use std::{
cell::RefCell,
collections::hash_map::DefaultHasher,
collections::HashMap,
fmt::{Display, Formatter, Result},
hash::{Hash, Hasher},
rc::Rc,
};

use crate::var::UserType;

type MapBuckets<K, V> = Vec<Vec<(K, V)>>;

pub struct Map<K, V>
where
K: UserType,
V: UserType,
{
buckets: Rc<RefCell<MapBuckets<K, V>>>,
bucket_count: usize,
size: usize,
inner: HashMap<K, V>,
iterator_count: Rc<RefCell<usize>>,
}

Expand All @@ -27,40 +23,14 @@ where
V: UserType,
{
pub fn new() -> Self {
let bucket_count = 16;
Self {
buckets: Rc::new(RefCell::new(vec![vec![]; bucket_count])),
size: 0,
bucket_count,
inner: HashMap::new(),
iterator_count: Rc::new(RefCell::new(0)),
}
}

fn get_bucket_id(&self, key: &K, bucket_count: usize) -> usize {
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
let hash = hasher.finish();
hash as usize % bucket_count
}

fn find_in_bucket(&self, bucket_id: usize, key: &K) -> Option<V> {
let bucket = &self.buckets.borrow()[bucket_id];

for (k, v) in bucket.iter() {
if key == k {
return Some(v.clone());
}
}
None
}

fn load_factor(&self) -> f64 {
self.len() as f64 / self.bucket_count as f64
}

pub fn get(&self, key: &K) -> Option<V> {
let bucket_id = self.get_bucket_id(key, self.bucket_count);
self.find_in_bucket(bucket_id, key)
self.inner.get(key).cloned()
}

pub fn contains_key(&self, key: &K) -> bool {
Expand All @@ -69,77 +39,29 @@ where

pub fn insert(&mut self, key: K, value: V) {
self.detect_invalid_change();
let bucket_id = self.get_bucket_id(&key, self.bucket_count);

{
let bucket = &mut self.buckets.borrow_mut()[bucket_id];

for (k, v) in bucket.iter_mut() {
if key == *k {
*v = value;
return;
}
}

bucket.push((key, value));
self.size += 1;
}

if self.load_factor() > 0.75 {
self.rehash(2 * self.bucket_count)
}
}

pub fn rehash(&mut self, new_bucket_count: usize) {
let mut new_buckets = vec![vec![]; new_bucket_count];

for bucket in self.buckets.borrow().iter() {
for (key, value) in bucket.iter() {
let index = self.get_bucket_id(key, new_bucket_count);
new_buckets[index].push((key.clone(), value.clone()));
}
}

*self.buckets.borrow_mut() = new_buckets;
self.bucket_count = new_bucket_count;
self.inner.insert(key, value);
}

pub fn len(&self) -> usize {
self.size
self.inner.len()
}

pub fn is_empty(&self) -> bool {
self.size == 0
self.inner.is_empty()
}

pub fn clear(&mut self) {
self.detect_invalid_change();

for bucket in self.buckets.borrow_mut().iter_mut() {
bucket.clear();
}
self.size = 0;
self.inner.clear();
}

pub fn remove_entry(&mut self, key: &K) -> Option<(K, V)> {
self.detect_invalid_change();

let bucket_id = self.get_bucket_id(key, self.bucket_count);
let bucket = &mut self.buckets.borrow_mut()[bucket_id];

let position = bucket.iter().position(|(k, _v)| k == key);

match position {
Some(index) => {
self.size -= 1;
Some(bucket.remove(index))
}
None => None,
}
self.inner.remove_entry(key)
}

pub fn iter(&self) -> HashTableIterator<K, V> {
HashTableIterator::new(self.buckets.clone(), self.iterator_count.clone())
pub fn iter(&self) -> MapIterator<K, V> {
MapIterator::new(self.inner.clone().into_iter(), self.iterator_count.clone())
}

fn detect_invalid_change(&self) {
Expand All @@ -152,10 +74,8 @@ where

pub fn fmt_as_set(&self) -> String {
let mut parts = vec![];
for bucket in self.buckets.borrow().iter() {
for (k, _) in bucket.iter() {
parts.push(format!("{k:?}"));
}
for (item, _) in self.iter() {
parts.push(format!("{item:?}"));
}
format!("{{{}}}", parts.join(","))
}
Expand All @@ -167,22 +87,7 @@ where
V: UserType,
{
fn eq(&self, other: &Self) -> bool {
if self.len() != other.len() {
return false;
}

for (key, value) in self.iter() {
match other.get(&key) {
None => return false,
Some(v) => {
if v != value {
return false;
}
}
}
}

true
return self.inner == other.inner;
}
}

Expand All @@ -200,10 +105,8 @@ where
{
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut parts = vec![];
for bucket in self.buckets.borrow().iter() {
for (k, v) in bucket.iter() {
parts.push(format!("{k:?}: {v:?}"));
}
for (k, v) in self.iter() {
parts.push(format!("{k:?}: {v:?}"));
}
write!(f, "{{{}}}", parts.join(", "))
}
Expand Down Expand Up @@ -244,65 +147,46 @@ where
}
}

pub struct HashTableIterator<K, V>
pub struct MapIterator<K, V>
where
K: UserType,
V: UserType,
{
buckets: Rc<RefCell<MapBuckets<K, V>>>,
iterator: std::collections::hash_map::IntoIter<K, V>,
iterator_count: Rc<RefCell<usize>>,
bucket_id: usize,
offset_in_bucket: usize,
}

pub type MapIterator<K, V> = HashTableIterator<K, V>;

impl<K, V> HashTableIterator<K, V>
impl<K, V> MapIterator<K, V>
where
K: UserType,
V: UserType,
{
pub fn new(buckets: Rc<RefCell<MapBuckets<K, V>>>, iterator_count: Rc<RefCell<usize>>) -> Self {
pub fn new(
iterator: std::collections::hash_map::IntoIter<K, V>,
iterator_count: Rc<RefCell<usize>>,
) -> Self {
*iterator_count.borrow_mut() += 1;

Self {
buckets,
iterator,
iterator_count,
bucket_id: 0,
offset_in_bucket: 0,
}
}
}

impl<K, V> Iterator for HashTableIterator<K, V>
impl<K, V> Iterator for MapIterator<K, V>
where
K: UserType,
V: UserType,
{
type Item = (K, V);

fn next(&mut self) -> Option<Self::Item> {
let buckets = self.buckets.borrow();

loop {
match buckets.get(self.bucket_id) {
Some(bucket) => match bucket.get(self.offset_in_bucket) {
Some((k, v)) => {
self.offset_in_bucket += 1;
return Some((k.clone(), v.clone()));
}
None => {
self.bucket_id += 1;
self.offset_in_bucket = 0;
}
},
None => return None,
}
}
self.iterator.next()
}
}

impl<K, V> Drop for HashTableIterator<K, V>
impl<K, V> Drop for MapIterator<K, V>
where
K: UserType,
V: UserType,
Expand Down
6 changes: 3 additions & 3 deletions aaa-stdlib/src/set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ use std::{
};

use crate::{
map::{HashTableIterator, Map},
map::{Map, MapIterator},
var::UserType,
};

// Can't use unit type `()` as it does not implement Display, Hash or UserType
#[derive(Clone, Debug, Hash, PartialEq)]
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct SetValue;

impl Display for SetValue {
Expand All @@ -30,4 +30,4 @@ impl UserType for SetValue {

pub type Set<T> = Map<T, SetValue>;

pub type SetIterator<T> = HashTableIterator<T, SetValue>;
pub type SetIterator<T> = MapIterator<T, SetValue>;
2 changes: 1 addition & 1 deletion aaa-stdlib/src/var.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use crate::{
vector::{Vector, VectorIterator},
};

pub trait UserType: Clone + Debug + Display + Hash + PartialEq {
pub trait UserType: Clone + Debug + Display + Hash + PartialEq + Eq {
fn kind(&self) -> String;
fn clone_recursive(&self) -> Self;
}
Expand Down
Loading