Skip to content

Commit 6346ecb

Browse files
authored
Add as_ptr(_mut); make as_slice(_mut) into const fn (#147)
Also makes `as_flattened(_mut)` into `const fn`. This uses the same approach as `slice_as_flattened(_mut)` (#144), but constructs a slice of size `U::USIZE`.
1 parent 1099e90 commit 6346ecb

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

src/lib.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -184,14 +184,30 @@ where
184184
{
185185
/// Returns a slice containing the entire array. Equivalent to `&s[..]`.
186186
#[inline]
187-
pub fn as_slice(&self) -> &[T] {
188-
self.0.as_ref()
187+
pub const fn as_slice(&self) -> &[T] {
188+
// SAFETY: `[T]` is layout-identical to `Array<T, U>`, which is a `repr(transparent)`
189+
// newtype for `[T; N]`.
190+
unsafe { slice::from_raw_parts(self.as_ptr(), U::USIZE) }
189191
}
190192

191193
/// Returns a mutable slice containing the entire array. Equivalent to `&mut s[..]`.
192194
#[inline]
193-
pub fn as_mut_slice(&mut self) -> &mut [T] {
194-
self.0.as_mut()
195+
pub const fn as_mut_slice(&mut self) -> &mut [T] {
196+
// SAFETY: `[T]` is layout-identical to `Array<T, U>`, which is a `repr(transparent)`
197+
// newtype for `[T; N]`.
198+
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), U::USIZE) }
199+
}
200+
201+
/// Returns a pointer to the start of the array.
202+
#[allow(trivial_casts)]
203+
pub const fn as_ptr(&self) -> *const T {
204+
self as *const Self as *const T
205+
}
206+
207+
/// Returns a mutable pointer to the start of the array.
208+
#[allow(trivial_casts)]
209+
pub const fn as_mut_ptr(&mut self) -> *mut T {
210+
self as *mut Self as *mut T
195211
}
196212

197213
/// Returns an iterator over the array.
@@ -393,7 +409,7 @@ where
393409
/// let empty_slice_of_arrays: &Array<Array<u32, U10>, U0> = &Array([]);
394410
/// assert!(empty_slice_of_arrays.as_flattened().is_empty());
395411
/// ```
396-
pub fn as_flattened(&self) -> &[T] {
412+
pub const fn as_flattened(&self) -> &[T] {
397413
Array::slice_as_flattened(self.as_slice())
398414
}
399415

@@ -422,7 +438,7 @@ where
422438
/// add_5_to_all(array.as_flattened_mut());
423439
/// assert_eq!(array, Array([Array([6, 7, 8]), Array([9, 10, 11]), Array([12, 13, 14])]));
424440
/// ```
425-
pub fn as_flattened_mut(&mut self) -> &mut [T] {
441+
pub const fn as_flattened_mut(&mut self) -> &mut [T] {
426442
Array::slice_as_flattened_mut(self.as_mut_slice())
427443
}
428444
}

0 commit comments

Comments
 (0)