//! A lib of vector operators //! Allow for replacement and formatting of strings use crate::{errors::SnippetError, tokenizer}; /// A dynamic formatter, formatting a string with any number of /// {} with element of a Vec, by default the search doen't need to /// be exhaustive and wont fail if either the array or format string don't /// match up in length, use dynamic_format_strict for this behaviour /// A pseudo dynamic formatter, tries to fill all {} in a string with the values /// in a vector pub fn dynamic_format(format_string: &str, vector: Vec) -> Result where T: std::fmt::Display, { let token_list = tokenizer::create_tokens_from_string(format_string)?; let cap = format_string.len() + 5 * vector.len(); let mut final_string = String::with_capacity(cap); let mut moving_index = 0; for tok in token_list { match tok { tokenizer::SnippetToken::Substitution(s) => { let index; match s.id() { Some(i) => index = i, None => { index = moving_index; moving_index += 1 } }; if let Some(text) = vector.get(index) { final_string.push_str(&text.to_string()) } else { return Err(SnippetError::IndexError(index)); } } tokenizer::SnippetToken::Text(t) => final_string.push_str(t), } } Ok(final_string) } /// Fill the argument vector with a list of defaults values if needed pub fn complete_vec(to_fill: &Vec, defaults: &Vec) -> Result, SnippetError> where T: Clone, { let size_o = to_fill.len(); let size_d = defaults.len(); match size_o.cmp(&size_d) { std::cmp::Ordering::Greater => Err(SnippetError::Unknown), //TODO: Fix this error std::cmp::Ordering::Equal => Ok(to_fill.clone()), std::cmp::Ordering::Less => { let mut output = to_fill.clone(); (size_o..size_d).for_each(|i| { output.push(defaults[i].clone()); }); Ok(output) } } } #[cfg(test)] mod test { use super::*; #[test] fn test_dynamic_format() { let res = dynamic_format( "big str {} with many {} formatters", vec!["aaa", "bbb", "ccc", "dddd"], ) .unwrap(); assert_eq!(res, ("big str aaa with many bbb formatters".to_string())); let res = dynamic_format("{} {0} {0} {2} {d} {1}", vec!["aaa", "bbb", "ccc", "dddd"]).unwrap(); assert_eq!(res, ("aaa aaa aaa ccc {d} bbb".to_string())); let res = dynamic_format("{100}", vec!["a"]); assert!(res.is_err()); let res = dynamic_format("", vec!["a"]).unwrap(); assert_eq!(res, "".to_string()); } #[test] fn test_complete_vec() { let smol = vec!["A"]; let big = vec!["a", "b", "c", "d", "e", "f"]; let eq = vec!["T", "U", "I", "O"]; let deff = vec!["AA", "BB", "CC", "DD"]; assert_eq!( complete_vec(&smol, &deff).unwrap(), vec!["A", "BB", "CC", "DD"] ); assert_eq!(complete_vec(&eq, &deff).unwrap(), eq); assert!(complete_vec(&big, &deff).is_err()); } }