Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add mutable accessors to strongly typed collections #101

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
210 changes: 173 additions & 37 deletions engine/src/lhs_types/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ use std::{
ops::Deref,
};

use super::{map::InnerMap, TypedMap};

// Ideally, we would want to use Cow<'a, LhsValue<'a>> here
// but it doesnt work for unknown reasons
// See https://github.com/rust-lang/rust/issues/23707#issuecomment-557312736
#[derive(Debug, Clone)]
enum InnerArray<'a> {
pub(crate) enum InnerArray<'a> {
Owned(Vec<LhsValue<'a>>),
Borrowed(&'a [LhsValue<'a>]),
}
Expand Down Expand Up @@ -79,11 +81,17 @@ impl<'a> Deref for InnerArray<'a> {
}
}

impl Default for InnerArray<'_> {
fn default() -> Self {
Self::Owned(Vec::new())
}
}

/// An array of [`Type`].
#[derive(Debug, Clone)]
pub struct Array<'a> {
val_type: CompoundType,
data: InnerArray<'a>,
pub(crate) data: InnerArray<'a>,
}

impl<'a> Array<'a> {
Expand Down Expand Up @@ -479,20 +487,20 @@ impl<'a, 'b> From<&'a mut Array<'b>> for ArrayMut<'a, 'b> {

/// Typed wrapper over an `Array` which provides
/// infaillible operations.
#[derive(Debug)]
#[repr(transparent)]
pub struct TypedArray<'a, V>
where
V: IntoValue<'a>,
{
array: Array<'a>,
array: InnerArray<'a>,
_marker: std::marker::PhantomData<[V]>,
}

impl<'a, V: IntoValue<'a>> TypedArray<'a, V> {
/// Push an element to the back of the array
#[inline]
pub fn push(&mut self, value: V) {
self.array.data.push(value.into_value())
self.array.push(value.into_value())
}

/// Returns the number of elements in the array
Expand All @@ -510,50 +518,74 @@ impl<'a, V: IntoValue<'a>> TypedArray<'a, V> {
/// Shortens the array, keeping the first `len` elements and dropping the rest.
#[inline]
pub fn truncate(&mut self, len: usize) {
self.array.data.truncate(len);
self.array.truncate(len);
}

/// Converts the strongly typed array into a borrowed loosely typed array.
pub fn as_array(&'a self) -> Array<'a> {
Array {
val_type: V::TYPE.into(),
data: InnerArray::Borrowed(self.array.deref()),
}
}
}

impl TypedArray<'static, bool> {
#[inline]
pub(crate) fn iter(&self) -> impl ExactSizeIterator<Item = &bool> + '_ {
self.array.data.iter().map(|value| match value {
self.array.iter().map(|value| match value {
LhsValue::Bool(b) => b,
_ => unsafe { unreachable_unchecked() },
})
}

#[inline]
pub(crate) fn iter_mut(&mut self) -> impl ExactSizeIterator<Item = &mut bool> + '_ {
self.array
.data
.as_vec()
.iter_mut()
.map(|value| match value {
LhsValue::Bool(b) => b,
_ => unsafe { unreachable_unchecked() },
})
self.array.as_vec().iter_mut().map(|value| match value {
LhsValue::Bool(b) => b,
_ => unsafe { unreachable_unchecked() },
})
}
}

impl<T: AsRef<[bool]>> PartialEq<T> for TypedArray<'static, bool> {
fn eq(&self, other: &T) -> bool {
self.iter().eq(other.as_ref())
impl<'a, V: IntoValue<'a>> fmt::Debug for TypedArray<'a, V> {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_list().entries(self.array.iter()).finish()
}
}

impl<'a, V: IntoValue<'a>> PartialEq for TypedArray<'a, V> {
fn eq(&self, other: &Self) -> bool {
self.array.deref() == other.array.deref()
}
}

impl<'a, V: Copy + IntoValue<'a>, S: AsRef<[V]>> PartialEq<S> for TypedArray<'a, V> {
fn eq(&self, other: &S) -> bool {
other
.as_ref()
.iter()
.copied()
.map(IntoValue::into_value)
.eq(self.array.iter())
}
}

impl<'a, V: IntoValue<'a>> From<TypedArray<'a, V>> for Array<'a> {
#[inline]
fn from(value: TypedArray<'a, V>) -> Self {
value.array
Array {
val_type: V::TYPE.into(),
data: value.array,
}
}
}

impl<'a, V: IntoValue<'a>> Default for TypedArray<'a, V> {
#[inline]
fn default() -> Self {
Self {
array: Array::new(V::TYPE),
array: InnerArray::default(),
_marker: std::marker::PhantomData,
}
}
Expand All @@ -563,7 +595,6 @@ impl<'a, V: IntoValue<'a>> Extend<V> for TypedArray<'a, V> {
#[inline]
fn extend<T: IntoIterator<Item = V>>(&mut self, iter: T) {
self.array
.data
.as_vec()
.extend(iter.into_iter().map(IntoValue::into_value))
}
Expand All @@ -575,7 +606,7 @@ impl<'a, V: IntoValue<'a>> FromIterator<V> for TypedArray<'a, V> {
T: IntoIterator<Item = V>,
{
Self {
array: Array::from_iter(iter),
array: InnerArray::Owned(iter.into_iter().map(|elem| elem.into_value()).collect()),
_marker: std::marker::PhantomData,
}
}
Expand All @@ -586,30 +617,135 @@ impl<'a, V: IntoValue<'a>> IntoValue<'a> for TypedArray<'a, V> {

#[inline]
fn into_value(self) -> LhsValue<'a> {
LhsValue::Array(self.array)
LhsValue::Array(self.into())
}
}

#[test]
fn test_size_of_array() {
assert_eq!(std::mem::size_of::<Array<'_>>(), 32);
impl<'a, V: IntoValue<'a>> TypedArray<'a, TypedArray<'a, V>> {
/// Returns a reference to an element or None if the index is out of bounds.
pub fn get(&self, index: usize) -> Option<&TypedArray<'a, V>> {
self.array.get(index).map(|val| match val {
LhsValue::Array(array) => {
// Safety: this is safe because `TypedArray` is a repr(transparent)
// newtype over `InnerArray`.
unsafe { std::mem::transmute::<&InnerArray<'a>, &TypedArray<'a, V>>(&array.data) }
}
_ => unreachable!(),
})
}

/// Returns a mutable reference to an element or None if the index is out of bounds.
pub fn get_mut(&mut self, index: usize) -> Option<&mut TypedArray<'a, V>> {
self.array.get_mut(index).map(|val| match val {
LhsValue::Array(array) => {
// Safety: this is safe because `TypedArray` is a repr(transparent)
// newtype over `InnerArray`.
unsafe {
std::mem::transmute::<&mut InnerArray<'a>, &mut TypedArray<'a, V>>(
&mut array.data,
)
}
}
_ => unreachable!(),
})
}
}

#[test]
fn test_borrowed_eq_owned() {
let mut owned = Array::new(Type::Bytes);
impl<'a, V: IntoValue<'a>> TypedArray<'a, TypedMap<'a, V>> {
/// Returns a reference to an element or None if the index is out of bounds.
pub fn get(&self, index: usize) -> Option<&TypedMap<'a, V>> {
self.array.get(index).map(|val| match val {
LhsValue::Map(map) => {
// Safety: this is safe because `TypedMap` is a repr(transparent)
// newtype over `InnerMap`.
unsafe { std::mem::transmute::<&InnerMap<'a>, &TypedMap<'a, V>>(&map.data) }
}
_ => unreachable!(),
})
}

/// Returns a mutable reference to an element or None if the index is out of bounds.
pub fn get_mut(&mut self, index: usize) -> Option<&mut TypedMap<'a, V>> {
self.array.get_mut(index).map(|val| match val {
LhsValue::Map(map) => {
// Safety: this is safe because `TypedMap` is a repr(transparent)
// newtype over `InnerMap`.
unsafe {
std::mem::transmute::<&mut InnerMap<'a>, &mut TypedMap<'a, V>>(&mut map.data)
}
}
_ => unreachable!(),
})
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_size_of_array() {
assert_eq!(std::mem::size_of::<Array<'_>>(), 32);
}

#[test]
fn test_borrowed_eq_owned() {
let mut owned = Array::new(Type::Bytes);

owned
.push(LhsValue::Bytes("borrowed".as_bytes().into()))
.unwrap();
owned
.push(LhsValue::Bytes("borrowed".as_bytes().into()))
.unwrap();

let borrowed = owned.as_ref();
let borrowed = owned.as_ref();

assert!(matches!(owned.data, InnerArray::Owned(_)));
assert!(matches!(owned.data, InnerArray::Owned(_)));

assert!(matches!(borrowed.data, InnerArray::Borrowed(_)));
assert!(matches!(borrowed.data, InnerArray::Borrowed(_)));

assert_eq!(owned, borrowed);
assert_eq!(owned, borrowed);

assert_eq!(borrowed, borrowed.to_owned());
assert_eq!(borrowed, borrowed.to_owned());
}

#[test]
fn test_typed_array_get_typed_array() {
let mut array = TypedArray::from_iter([
TypedArray::from_iter(["a", "b", "c"]),
TypedArray::from_iter(["d", "e"]),
]);

assert_eq!(*array.get(0).unwrap(), ["a", "b", "c"],);

assert_eq!(*array.get(1).unwrap(), ["d", "e"]);

array.get_mut(1).unwrap().push("f");

assert_eq!(*array.get(1).unwrap(), ["d", "e", "f"]);
}

fn key(s: &str) -> Box<[u8]> {
s.as_bytes().to_vec().into_boxed_slice()
}

#[test]
fn test_typed_array_get_typed_map() {
let mut array = TypedArray::from_iter([
TypedMap::from_iter([(key("a"), 42), (key("b"), 1337), (key("c"), 0)]),
TypedMap::from_iter([(key("d"), 7), (key("e"), 3)]),
]);

assert_eq!(
array.get(0).unwrap(),
&[(b"a" as &[u8], 42), (b"b", 1337), (b"c", 0)]
);

assert_eq!(array.get(1).unwrap(), &[(b"d" as &[u8], 7), (b"e", 3)]);

array.get_mut(1).unwrap().insert(key("f"), 99);

assert_eq!(
array.get(1).unwrap(),
&[(b"d" as &[u8], 7), (b"e", 3), (b"f", 99)]
);
}
}
Loading
Loading