Skip to content

Commit 8dcb4d5

Browse files
Merge pull request #331 from rust-lang/to_slice
Add copy_to_slice
2 parents 9bd30e7 + 36829dd commit 8dcb4d5

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

crates/core_simd/src/vector.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ where
159159
///
160160
/// Panics if the slice's length is less than the vector's `Simd::LANES`.
161161
///
162-
/// # Examples
162+
/// # Example
163163
///
164164
/// ```
165165
/// # #![feature(portable_simd)]
@@ -174,12 +174,43 @@ where
174174
slice.len() >= LANES,
175175
"slice length must be at least the number of lanes"
176176
);
177+
assert!(core::mem::size_of::<Self>() == LANES * core::mem::size_of::<T>());
177178
// Safety:
178179
// - We've checked the length is sufficient.
179180
// - `T` and `Simd<T, N>` are Copy types.
180181
unsafe { slice.as_ptr().cast::<Self>().read_unaligned() }
181182
}
182183

184+
/// Writes a SIMD vector to the first `LANES` elements of a slice.
185+
///
186+
/// # Panics
187+
///
188+
/// Panics if the slice's length is less than the vector's `Simd::LANES`.
189+
///
190+
/// # Example
191+
///
192+
/// ```
193+
/// # #![feature(portable_simd)]
194+
/// # #[cfg(feature = "as_crate")] use core_simd::simd;
195+
/// # #[cfg(not(feature = "as_crate"))] use core::simd;
196+
/// # use simd::u32x4;
197+
/// let mut dest = vec![0; 6];
198+
/// let v = u32x4::from_array([1, 2, 3, 4]);
199+
/// v.copy_to_slice(&mut dest);
200+
/// assert_eq!(&dest, &[1, 2, 3, 4, 0, 0]);
201+
/// ```
202+
pub fn copy_to_slice(self, slice: &mut [T]) {
203+
assert!(
204+
slice.len() >= LANES,
205+
"slice length must be at least the number of lanes"
206+
);
207+
assert!(core::mem::size_of::<Self>() == LANES * core::mem::size_of::<T>());
208+
// Safety:
209+
// - We've checked the length is sufficient
210+
// - `T` and `Simd<T, N>` are Copy types.
211+
unsafe { slice.as_mut_ptr().cast::<Self>().write_unaligned(self) }
212+
}
213+
183214
/// Performs lanewise conversion of a SIMD vector's elements to another SIMD-valid type.
184215
///
185216
/// This follows the semantics of Rust's `as` conversion for casting

0 commit comments

Comments
 (0)