|
| 1 | +use std::mem; |
1 | 2 | use std::ptr::NonNull;
|
2 | 3 |
|
3 | 4 | use crate::dimension::{self, stride_offset};
|
@@ -111,6 +112,32 @@ where
|
111 | 112 |
|
112 | 113 | (left, right)
|
113 | 114 | }
|
| 115 | + |
| 116 | + /// Cast the raw pointer of the raw array view to a different type |
| 117 | + /// |
| 118 | + /// **Panics** if element size is not compatible. |
| 119 | + /// |
| 120 | + /// Lack of panic does not imply it is a valid cast. The cast works the same |
| 121 | + /// way as regular raw pointer casts. |
| 122 | + /// |
| 123 | + /// While this method is safe, for the same reason as regular raw pointer |
| 124 | + /// casts are safe, access through the produced raw view is only possible |
| 125 | + /// in an unsafe block or function. |
| 126 | + pub fn cast<B>(self) -> RawArrayView<B, D> { |
| 127 | + assert_eq!( |
| 128 | + mem::size_of::<B>(), |
| 129 | + mem::size_of::<A>(), |
| 130 | + "size mismatch in raw view cast" |
| 131 | + ); |
| 132 | + let ptr = self.ptr.cast::<B>(); |
| 133 | + debug_assert!( |
| 134 | + is_aligned(ptr.as_ptr()), |
| 135 | + "alignment mismatch in raw view cast" |
| 136 | + ); |
| 137 | + /* Alignment checked with debug assertion: alignment could be dynamically correct, |
| 138 | + * and we don't have a check that compiles out for that. */ |
| 139 | + unsafe { RawArrayView::new(ptr, self.dim, self.strides) } |
| 140 | + } |
114 | 141 | }
|
115 | 142 |
|
116 | 143 | impl<A, D> RawArrayViewMut<A, D>
|
@@ -222,4 +249,30 @@ where
|
222 | 249 | )
|
223 | 250 | }
|
224 | 251 | }
|
| 252 | + |
| 253 | + /// Cast the raw pointer of the raw array view to a different type |
| 254 | + /// |
| 255 | + /// **Panics** if element size is not compatible. |
| 256 | + /// |
| 257 | + /// Lack of panic does not imply it is a valid cast. The cast works the same |
| 258 | + /// way as regular raw pointer casts. |
| 259 | + /// |
| 260 | + /// While this method is safe, for the same reason as regular raw pointer |
| 261 | + /// casts are safe, access through the produced raw view is only possible |
| 262 | + /// in an unsafe block or function. |
| 263 | + pub fn cast<B>(self) -> RawArrayViewMut<B, D> { |
| 264 | + assert_eq!( |
| 265 | + mem::size_of::<B>(), |
| 266 | + mem::size_of::<A>(), |
| 267 | + "size mismatch in raw view cast" |
| 268 | + ); |
| 269 | + let ptr = self.ptr.cast::<B>(); |
| 270 | + debug_assert!( |
| 271 | + is_aligned(ptr.as_ptr()), |
| 272 | + "alignment mismatch in raw view cast" |
| 273 | + ); |
| 274 | + /* Alignment checked with debug assertion: alignment could be dynamically correct, |
| 275 | + * and we don't have a check that compiles out for that. */ |
| 276 | + unsafe { RawArrayViewMut::new(ptr, self.dim, self.strides) } |
| 277 | + } |
225 | 278 | }
|
0 commit comments