Implement FromIterator for SpannedString (#512)

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 commit is contained in:
Robin Krahl 2020-10-07 19:55:12 +02:00 committed by GitHub
parent 0e2a111f59
commit 28c64958ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,6 +3,7 @@
//! 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)