use std::collections::HashMap;
use std::ops::Deref;
pub fn fold_line<T>(string: T) -> String
where
T: Deref<Target = str>,
{
let mut final_string = String::new();
for (pos, chr) in string.char_indices() {
if pos % 75 == 0 && pos != 0 {
final_string.push_str("\r\n\t");
}
final_string.push(chr);
}
final_string
}
pub fn unfold_line<T>(string: T) -> String
where
T: Deref<Target = str>,
{
string.replace("\r\n\t", "").replace("\r\n ", "")
}
pub fn escape_property<T>(string: T) -> String
where
T: Deref<Target = str>,
{
string
.replace('\\', "\\\\")
.replace(',', "\\,")
.replace(';', "\\;")
.replace('\n', "\\n")
}
pub fn unescape_property<T>(string: T) -> String
where
T: Deref<Target = str>,
{
string
.replace("\\n", "\n")
.replace("\\;", ";")
.replace("\\,", ",")
.replace("\\\\", "\\")
}
#[must_use]
pub fn get_parameters(mut string: String) -> HashMap<String, String> {
string.push(';');
string.push(' ');
let mut map = HashMap::new();
let mut name = String::new();
let mut val = String::new();
let mut on_val = false;
let mut next_param = false;
let mut in_string = false;
for chr in string.chars() {
if next_param {
map.insert(std::mem::take(&mut name), std::mem::take(&mut val));
next_param = false;
on_val = false;
in_string = false;
}
if on_val {
if chr == '"' {
in_string = !in_string;
}
else if chr == ';' && !in_string {
next_param = true;
} else {
val.push(chr);
}
} else {
if chr == '=' {
on_val = true;
} else {
name.push(chr);
}
}
}
map
}
#[must_use]
pub fn get_values(mut string: String) -> Vec<Vec<String>> {
string = string.trim().to_string();
string.push(';');
let mut strings = Vec::new();
let mut escape = false;
strings.push(vec![String::new()]);
for i in string.chars() {
if let Some(active_string) =
strings.last_mut().and_then(|x| x.last_mut())
{
if escape {
match i {
'\\' => active_string.push('\\'),
';' => active_string.push(';'),
',' => active_string.push(','),
'n' => active_string.push('\n'),
_ => (),
}
escape = false;
} else {
match i {
'\\' => escape = true,
';' => strings.push(vec![String::new()]),
',' => {
if let Some(active_val) = strings.last_mut() {
active_val.push(String::new());
}
}
_ => active_string.push(i),
}
}
}
}
strings.pop();
for i in &mut strings {
i.retain(|x| !x.is_empty());
}
strings
}