misc: Minor changes on docs and codes

This commit is contained in:
heyrict 2020-04-25 15:10:12 +08:00
parent 71020b0397
commit e7dd987fd7
No known key found for this signature in database
GPG Key ID: 803E2EACED3FF3AA
3 changed files with 14 additions and 4 deletions

View File

@ -1,6 +1,7 @@
use std::borrow::Cow;
use std::collections::BTreeSet;
/// Type that holds a number of variables of type `T`
pub trait VariableHolder<T> {
fn get_variables(&self) -> BTreeSet<T>;
}

View File

@ -36,7 +36,7 @@ escape = _{ "\\" ~ escaped_char }
escaped_char = { "[" | "]" | "(" | ")" | "\\" | "$" }
// TextGroup
//
//
// A textgroup is a pair of `format` and `style` (`[format](style)`)
//
// - `format`: A format string, can contain any number of variables, texts or textgroups.

View File

@ -1,7 +1,7 @@
use ansi_term::Style;
use pest::error::Error;
use rayon::prelude::*;
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator;
use crate::config::parse_style_string;
@ -34,6 +34,7 @@ impl<'a> StringFormatter<'a> {
pub fn new(format: &'a str) -> Result<Self, Error<Rule>> {
parse(format)
.map(|format| {
// Cache all variables
let variables = VariableMapType::from_iter(
format
.get_variables()
@ -113,11 +114,11 @@ impl<'a> StringFormatter<'a> {
FormatElement::Variable(name) => variables
.get(name.as_ref())
.and_then(|segments| {
let value = segments.clone()?;
Some(match value {
Some(match segments.clone()? {
VariableValue::Styled(segments) => segments
.into_iter()
.map(|mut segment| {
// Derive upper style if the style of segments are none.
if !segment.has_style() {
if let Some(style) = style {
segment.set_style(style);
@ -133,6 +134,8 @@ impl<'a> StringFormatter<'a> {
})
.unwrap_or_default(),
FormatElement::Positional(format) => {
// Show the positional format string if all the variables inside are not
// none.
let should_show: bool = format.get_variables().iter().any(|var| {
variables
.get(var.as_ref())
@ -154,6 +157,12 @@ impl<'a> StringFormatter<'a> {
}
}
impl<'a> VariableHolder<String> for StringFormatter<'a> {
fn get_variables(&self) -> BTreeSet<String> {
BTreeSet::from_iter(self.variables.keys().cloned())
}
}
/// Helper function to create a new segment
fn _new_segment(name: String, value: String, style: Option<Style>) -> Segment {
Segment {