Add basic roc_std Dict and Set implementations

This commit is contained in:
Richard Feldman 2022-08-15 10:59:10 -04:00
parent 97fef48864
commit ec0e80f5d2
No known key found for this signature in database
GPG Key ID: F1F21AA5B1D9E43B
3 changed files with 112 additions and 0 deletions

View File

@ -11,12 +11,16 @@ use core::ops::Drop;
use core::str;
mod roc_box;
mod roc_dict;
mod roc_list;
mod roc_set;
mod roc_str;
mod storage;
pub use roc_box::RocBox;
pub use roc_dict::RocDict;
pub use roc_list::RocList;
pub use roc_set::RocSet;
pub use roc_str::{InteriorNulError, RocStr};
pub use storage::Storage;

View File

@ -0,0 +1,73 @@
use crate::roc_list::{self, RocList};
use core::{
fmt::{self, Debug},
hash::Hash,
};
#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RocDict<K, V>(RocList<(K, V)>);
impl<K, V> RocDict<K, V> {
pub fn with_capacity(capacity: usize) -> Self {
Self(RocList::with_capacity(capacity))
}
pub fn iter(&self) -> impl Iterator<Item = &(K, V)> {
self.into_iter()
}
pub fn iter_keys(&self) -> impl Iterator<Item = &K> {
self.0.iter().map(|(key, _)| key)
}
pub fn iter_values(&self) -> impl Iterator<Item = &V> {
self.0.iter().map(|(_, val)| val)
}
}
impl<K: Hash, V> RocDict<K, V> {
#[allow(unused)]
pub fn from_iter<I: Iterator<Item = (K, V)>>(src: I) -> Self {
let mut ret = Self::with_capacity(src.size_hint().0);
for (key, val) in src {
unsafe {
ret.insert_unchecked(key, val);
}
}
ret
}
unsafe fn insert_unchecked(&mut self, _key: K, _val: V) {
todo!();
}
}
impl<K: Debug, V: Debug> Debug for RocDict<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("RocDict ")?;
f.debug_map()
.entries(self.iter().map(|(k, v)| (k, v)))
.finish()
}
}
impl<K, V> IntoIterator for RocDict<K, V> {
type Item = (K, V);
type IntoIter = roc_list::IntoIter<(K, V)>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a, K, V> IntoIterator for &'a RocDict<K, V> {
type Item = &'a (K, V);
type IntoIter = core::slice::Iter<'a, (K, V)>;
fn into_iter(self) -> Self::IntoIter {
self.0.as_slice().iter()
}
}

View File

@ -0,0 +1,35 @@
use crate::roc_dict::RocDict;
use core::{
fmt::{self, Debug},
hash::Hash,
};
#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RocSet<T>(RocDict<T, ()>);
impl<T> RocSet<T> {
#[allow(unused)]
pub fn with_capacity(capacity: usize) -> Self {
Self(RocDict::with_capacity(capacity))
}
#[allow(unused)]
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.0.iter_keys()
}
}
impl<T: Hash> RocSet<T> {
#[allow(unused)]
pub fn from_iter<I: Iterator<Item = T>>(src: I) -> Self {
Self(RocDict::from_iter(src.map(|elem| (elem, ()))))
}
}
impl<T: Debug> Debug for RocSet<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("RocSet ")?;
f.debug_set().entries(self.iter()).finish()
}
}