From 28c64958ca02ac028c8e4bdd1fe24ae6400dace7 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Wed, 7 Oct 2020 19:55:12 +0200 Subject: [PATCH] Implement FromIterator for SpannedString (#512) This patch implements FromIterator> for SpannedString 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. --- cursive-core/src/utils/span.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/cursive-core/src/utils/span.rs b/cursive-core/src/utils/span.rs index ac05014..f0f35ae 100644 --- a/cursive-core/src/utils/span.rs +++ b/cursive-core/src/utils/span.rs @@ -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 SpannedString { } } +impl FromIterator> for SpannedString { + fn from_iter>>( + iter: I, + ) -> SpannedString { + 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> for SpannedStr<'a, T> { fn from(other: &'a SpannedString) -> Self { SpannedStr::new(&other.source, &other.spans)