Skip to content

Commit 199b09c

Browse files
bitdriftrFintanH
authored andcommitted
Implement From conversion for non-empty hardcoded arrays
1 parent 95d5cb1 commit 199b09c

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/lib.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1056,6 +1056,25 @@ impl<A> Extend<A> for NonEmpty<A> {
10561056
}
10571057
}
10581058

1059+
impl<T, const S: usize> From<[T; S]> for NonEmpty<T> {
1060+
fn from(array: [T; S]) -> Self {
1061+
use std::collections::VecDeque;
1062+
const {
1063+
if S == 0 {
1064+
panic!("tried to construct NonEmpty from an empty array")
1065+
}
1066+
}
1067+
1068+
let mut vec = VecDeque::from(array);
1069+
1070+
// SAFETY: we know that S is not 0, so we can safely unwrap
1071+
NonEmpty {
1072+
head: vec.pop_front().unwrap(),
1073+
tail: vec.into(),
1074+
}
1075+
}
1076+
}
1077+
10591078
#[cfg(feature = "serialize")]
10601079
pub mod serialize {
10611080
use core::{convert::TryFrom, fmt};
@@ -1094,6 +1113,22 @@ mod tests {
10941113

10951114
use crate::NonEmpty;
10961115

1116+
#[test]
1117+
fn test_const_array_construction() {
1118+
let xs: [usize; 2] = [1, 2];
1119+
let expected = nonempty![1, 2];
1120+
assert_eq!(NonEmpty::from(xs), expected);
1121+
1122+
// N.b. uncommenting this below, rightfully, panics the evaluation of
1123+
// the program. This being left here for anyone to prove to themselves
1124+
// that this does indeed panic. Unfortunately, `#[should_panic]` does
1125+
// not work in this case, since the panic happens at evaluation time –
1126+
// due to the `const` – rather than run time.
1127+
1128+
// let xs: [usize; 0] = [];
1129+
// let _ = NonEmpty::from(xs);
1130+
}
1131+
10971132
#[test]
10981133
fn test_from_conversion() {
10991134
let result = NonEmpty::from((1, vec![2, 3, 4, 5]));

0 commit comments

Comments
 (0)