cross: DimSlice: add as_ref, as_mut methods to re-borrow the data with a different lifetime

we can't use the actual AsRef, AsMut trait because we aren't returning a
reference but a new type with an inner reference.
This commit is contained in:
2022-08-18 03:25:52 -07:00
parent 300c11f5ca
commit a3b15bd7e7
2 changed files with 39 additions and 0 deletions

View File

@@ -1,3 +1,4 @@
use core::convert::{AsMut, AsRef};
use core::iter::Zip;
use core::ops::{Index, IndexMut};
@@ -5,6 +6,8 @@ use crate::vec::Vec3u;
/// use this to wrap a flat region of memory into something which can be indexed by coordinates in
/// 3d space.
#[cfg_attr(feature = "fmt", derive(Debug))]
#[derive(PartialEq)]
pub struct DimSlice<T> {
dim: Vec3u,
items: T,
@@ -20,6 +23,19 @@ impl<T> DimSlice<T> {
pub fn dim(&self) -> Vec3u {
self.dim
}
/// re-borrow the slice with a different lifetime.
pub fn as_ref<R: ?Sized>(&self) -> DimSlice<&R>
where T: AsRef<R>
{
DimSlice::new(self.dim, self.items.as_ref())
}
/// re-borrow the slice with a different lifetime.
pub fn as_mut<R: ?Sized>(&mut self) -> DimSlice<&mut R>
where T: AsMut<R>
{
DimSlice::new(self.dim, self.items.as_mut())
}
}
#[cfg(feature = "iter")]
@@ -122,6 +138,13 @@ mod test {
assert_eq!(index(Vec3u::new(1, 2, 2), dim), 17);
}
#[test]
fn as_ref() {
let data = [1, 2];
let s = DimSlice::new(Vec3u::new(1, 2, 1), &data[..]);
assert_eq!(s.as_ref(), DimSlice::new(Vec3u::new(1, 2, 1), &data[..]));
}
#[test]
fn dim_slice_index() {
let data = [

View File

@@ -1,3 +1,4 @@
use core::convert::{AsMut, AsRef};
use core::iter::Zip;
use core::ops::{Index, IndexMut};
@@ -5,6 +6,8 @@ use crate::dim::{DimIter, DimSlice};
use crate::vec::Vec3u;
#[cfg_attr(feature = "fmt", derive(Debug))]
#[derive(PartialEq)]
pub struct OffsetDimSlice<T> {
offset: Vec3u,
inner: DimSlice<T>,
@@ -17,6 +20,19 @@ impl<T> OffsetDimSlice<T> {
pub fn indices(&self) -> OffsetDimIter {
OffsetDimIter::new(self.offset, self.inner.indices())
}
/// re-borrow the slice with a different lifetime.
pub fn as_ref<R: ?Sized>(&self) -> OffsetDimSlice<&R>
where T: AsRef<R>
{
OffsetDimSlice { offset: self.offset, inner: self.inner.as_ref()}
}
/// re-borrow the slice with a different lifetime.
pub fn as_mut<R: ?Sized>(&mut self) -> OffsetDimSlice<&mut R>
where T: AsMut<R>
{
OffsetDimSlice { offset: self.offset, inner: self.inner.as_mut()}
}
}
#[cfg(feature = "iter")]