safer tarray
- no longer unwrapping None ptr, instead creating slice from dangling nonnull
This commit is contained in:
parent
fad1effa05
commit
8402f505bc
|
@ -174,14 +174,27 @@ pub mod tarray {
|
||||||
pub fn capacity(&self) -> usize {
|
pub fn capacity(&self) -> usize {
|
||||||
self.max as usize
|
self.max as usize
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn as_slice(&self) -> &[T] {
|
||||||
|
match self.data {
|
||||||
|
Some(ptr) => unsafe { core::slice::from_raw_parts(ptr.as_ptr(), self.len()) },
|
||||||
|
None => unsafe { core::slice::from_raw_parts(NonNull::dangling().as_ptr(), 0) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_slice_mut(&mut self) -> &mut [T] {
|
||||||
|
match self.data {
|
||||||
|
Some(ptr) => unsafe { core::slice::from_raw_parts_mut(ptr.as_ptr(), self.len()) },
|
||||||
|
None => unsafe { core::slice::from_raw_parts_mut(NonNull::dangling().as_ptr(), 0) },
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, I: SliceIndex<[T]>> Index<I> for TArray<T> {
|
impl<T, I: SliceIndex<[T]>> Index<I> for TArray<T> {
|
||||||
type Output = I::Output;
|
type Output = I::Output;
|
||||||
|
|
||||||
fn index(&self, i: I) -> &Self::Output {
|
fn index(&self, i: I) -> &Self::Output {
|
||||||
let data =
|
let data = self.as_slice();
|
||||||
unsafe { std::slice::from_raw_parts(self.data.unwrap().as_ptr(), self.len()) };
|
|
||||||
|
|
||||||
&data[i]
|
&data[i]
|
||||||
}
|
}
|
||||||
|
@ -191,7 +204,7 @@ pub mod tarray {
|
||||||
type Target = [T];
|
type Target = [T];
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
unsafe { std::slice::from_raw_parts(self.data.unwrap().as_ptr(), self.len()) }
|
self.as_slice()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue