use crate::{ValveKeyValue, ValveKeyValueType};
use crate::error::{Error, Result};
fn serialize_string(string: String, use_escape_sequences: bool) -> Result<String> {
let temp_string = if use_escape_sequences {
string
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('\n', "\\n")
.replace('\t', "\\t")
} else {
if string.contains('"') {
return Err(Error::QuoteInNonEscapeSequencedString);
}
string
};
if
temp_string.contains(char::is_whitespace) ||
temp_string.contains('"') ||
temp_string.contains('\\') ||
temp_string.is_empty()
{
Ok(format!("\"{}\"", temp_string))
} else {
Ok(temp_string)
}
}
pub fn serialize_object(
input: Vec<ValveKeyValue>,
use_escape_sequences: bool,
indentation_level: usize,
indentation_steps: usize
) -> Result<String> {
let mut full = String::new();
for keypair in input {
full.push_str(&format!(
"{}{} {}\n",
" ".repeat(indentation_level * indentation_steps),
serialize_string(keypair.key, use_escape_sequences)?,
match keypair.value {
ValveKeyValueType::String(string) => serialize_string(string, use_escape_sequences)?,
ValveKeyValueType::Object(object) => {
format!(
"{{\n{}{}}}",
serialize_object(object, use_escape_sequences, indentation_level+1, indentation_steps)?,
" ".repeat(indentation_level * indentation_steps)
)
}
}
));
}
Ok(full)
}
pub fn serialize(input: Vec<ValveKeyValue>, use_escape_sequences: bool, indentation_steps: usize) -> Result<String> {
serialize_object(input, use_escape_sequences, 0, indentation_steps)
}