Implement FromIterator for SpannedString
This patch implements FromIterator<SpannedString<T>> for
SpannedString<T> to make it easier to create strings programatically.
We could also use fold directly without extracting the first element,
but that would require an additional allocation.
//! This module defines various structs describing a span of text from a
//! larger string.
use std::borrow::Cow;
+use std::iter::FromIterator;
use unicode_width::UnicodeWidthStr;
/// A string with associated spans.
@@ -254,6 +255,22 @@ impl<T> SpannedString<T> {
}
}
+impl<T> FromIterator<SpannedString<T>> for SpannedString<T> {
+ fn from_iter<I: IntoIterator<Item = SpannedString<T>>>(
+ iter: I,
+ ) -> SpannedString<T> {
+ let mut iter = iter.into_iter();
+ if let Some(first) = iter.next() {
+ iter.fold(first, |mut acc, s| {
+ acc.append(s);
+ acc
+ })
+ } else {
+ SpannedString::new()
+ }
+ }
+}
+
impl<'a, T> From<&'a SpannedString<T>> for SpannedStr<'a, T> {
fn from(other: &'a SpannedString<T>) -> Self {
SpannedStr::new(&other.source, &other.spans)
