Skip to content

Commit 35c60ce

Browse files
Merge pull request #314 from rust-lang/try-from-slice
impl TryFrom<&[T]> for Simd
2 parents ecc2875 + 9dc690c commit 35c60ce

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

crates/core_simd/src/vector.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,30 @@ where
650650
}
651651
}
652652

653+
impl<T, const LANES: usize> TryFrom<&[T]> for Simd<T, LANES>
654+
where
655+
LaneCount<LANES>: SupportedLaneCount,
656+
T: SimdElement,
657+
{
658+
type Error = core::array::TryFromSliceError;
659+
660+
fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
661+
Ok(Self::from_array(slice.try_into()?))
662+
}
663+
}
664+
665+
impl<T, const LANES: usize> TryFrom<&mut [T]> for Simd<T, LANES>
666+
where
667+
LaneCount<LANES>: SupportedLaneCount,
668+
T: SimdElement,
669+
{
670+
type Error = core::array::TryFromSliceError;
671+
672+
fn try_from(slice: &mut [T]) -> Result<Self, Self::Error> {
673+
Ok(Self::from_array(slice.try_into()?))
674+
}
675+
}
676+
653677
mod sealed {
654678
pub trait Sealed {}
655679
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#![feature(portable_simd)]
2+
3+
#[cfg(target_arch = "wasm32")]
4+
use wasm_bindgen_test::*;
5+
6+
#[cfg(target_arch = "wasm32")]
7+
wasm_bindgen_test_configure!(run_in_browser);
8+
9+
use core_simd::i32x4;
10+
11+
#[test]
12+
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
13+
fn try_from_slice() {
14+
// Equal length
15+
assert_eq!(
16+
i32x4::try_from([1, 2, 3, 4].as_slice()).unwrap(),
17+
i32x4::from_array([1, 2, 3, 4])
18+
);
19+
20+
// Slice length > vector length
21+
assert!(i32x4::try_from([1, 2, 3, 4, 5].as_slice()).is_err());
22+
23+
// Slice length < vector length
24+
assert!(i32x4::try_from([1, 2, 3].as_slice()).is_err());
25+
}

0 commit comments

Comments
 (0)