Skip to content

Commit

Permalink
Make from_iter() optimized (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
cecton authored Nov 17, 2023
1 parent 1c30020 commit 00aed91
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,12 @@ impl<T: ImplicitClone + 'static> Default for IArray<T> {

impl<T: ImplicitClone + 'static> FromIterator<T> for IArray<T> {
fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Self {
let vec = it.into_iter().collect::<Vec<T>>();
Self::Rc(Rc::from(vec))
let mut it = it.into_iter();
if it.size_hint() == (1, Some(1)) {
Self::Single([it.next().unwrap()])
} else {
Self::Rc(Rc::from(it.collect::<Vec<T>>()))
}
}
}

Expand Down Expand Up @@ -394,6 +398,14 @@ mod test_array {
let _array = [Rc::new(Item)].into_iter().collect::<IArray<Rc<Item>>>();
}

#[test]
fn from_iter_is_optimized() {
let array_1 = [1].into_iter().collect::<IArray<u32>>();
assert!(matches!(array_1, IArray::Single(_)));
let array_2 = [1, 2].into_iter().collect::<IArray<u32>>();
assert!(matches!(array_2, IArray::Rc(_)));
}

#[test]
fn static_array() {
const _ARRAY: IArray<u32> = IArray::Static(&[1, 2, 3]);
Expand Down

0 comments on commit 00aed91

Please sign in to comment.