Implement FromIterator for Style (#510)

This patch implements FromIterator<&Style> and FromIterator<T:
Into<Style>> for Style to make it easier to programatically create
styles.  Style already has a merge method, but it takes a slice instead
of an iterator.
This commit is contained in:
Robin Krahl 2020-10-06 23:05:52 +02:00 committed by GitHub
parent 02ce9f8a35
commit 3f60d383aa
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,3 +1,5 @@
use std::iter::FromIterator;
use super::{Color, ColorStyle, ColorType, Effect, PaletteColor}; use super::{Color, ColorStyle, ColorType, Effect, PaletteColor};
use enumset::{enum_set, EnumSet}; use enumset::{enum_set, EnumSet};
@ -36,18 +38,7 @@ impl Style {
/// ///
/// Will use the last non-`None` color, and will combine all effects. /// Will use the last non-`None` color, and will combine all effects.
pub fn merge(styles: &[Style]) -> Self { pub fn merge(styles: &[Style]) -> Self {
let mut color = None; styles.iter().collect()
let mut effects = EnumSet::new();
for style in styles {
if style.color.is_some() {
color = style.color;
}
effects.insert_all(style.effects);
}
Style { color, effects }
} }
/// Returns a combination of `self` and `other`. /// Returns a combination of `self` and `other`.
@ -94,3 +85,32 @@ impl From<ColorType> for Style {
ColorStyle::from(color).into() ColorStyle::from(color).into()
} }
} }
/// Creates a new `Style` by merging all given styles.
///
/// Will use the last non-`None` color, and will combine all effects.
impl<'a> FromIterator<&'a Style> for Style {
fn from_iter<I: IntoIterator<Item = &'a Style>>(iter: I) -> Style {
let mut color = None;
let mut effects = EnumSet::new();
for style in iter {
if style.color.is_some() {
color = style.color;
}
effects.insert_all(style.effects);
}
Style { color, effects }
}
}
/// Creates a new `Style` by merging all given styles.
///
/// Will use the last non-`None` color, and will combine all effects.
impl<T: Into<Style>> FromIterator<T> for Style {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Style {
iter.into_iter().map(Into::into).collect()
}
}