From b62a77b4905150b14c8b0fd6e685f528e4f90ea7 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Mon, 8 Jul 2019 18:08:54 +0200 Subject: [PATCH] Add joining slices of slices with a slice separator, not just a single item --- src/liballoc/slice.rs | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 1b18dbeda9c11..d475c628ff193 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -508,6 +508,7 @@ impl [T] { /// ``` /// assert_eq!(["hello", "world"].join(" "), "hello world"); /// assert_eq!([[1, 2], [3, 4]].join(&0), [1, 2, 0, 3, 4]); + /// assert_eq!([[1, 2], [3, 4]].join(&[0, 0][..]), [1, 2, 0, 0, 3, 4]); /// ``` #[stable(feature = "rename_connect_to_join", since = "1.3.0")] pub fn join(&self, sep: Separator) -> >::Output @@ -654,7 +655,7 @@ impl> Join<&'_ T> for [V] { Some(first) => first, None => return vec![], }; - let size = slice.iter().map(|slice| slice.borrow().len()).sum::() + slice.len() - 1; + let size = slice.iter().map(|v| v.borrow().len()).sum::() + slice.len() - 1; let mut result = Vec::with_capacity(size); result.extend_from_slice(first.borrow()); @@ -666,6 +667,29 @@ impl> Join<&'_ T> for [V] { } } +#[unstable(feature = "slice_concat_ext", issue = "27747")] +impl> Join<&'_ [T]> for [V] { + type Output = Vec; + + fn join(slice: &Self, sep: &[T]) -> Vec { + let mut iter = slice.iter(); + let first = match iter.next() { + Some(first) => first, + None => return vec![], + }; + let size = slice.iter().map(|v| v.borrow().len()).sum::() + + sep.len() * (slice.len() - 1); + let mut result = Vec::with_capacity(size); + result.extend_from_slice(first.borrow()); + + for v in iter { + result.extend_from_slice(sep); + result.extend_from_slice(v.borrow()) + } + result + } +} + //////////////////////////////////////////////////////////////////////////////// // Standard trait implementations for slices ////////////////////////////////////////////////////////////////////////////////