valve_keyvalue/
serialize.rs1use crate::{ValveKeyValue, ValveKeyValueType};
18use crate::error::{Error, Result};
19
20fn serialize_string(string: String, use_escape_sequences: bool) -> Result<String> {
21 let temp_string = if use_escape_sequences {
22 string
23 .replace('\\', "\\\\")
24 .replace('"', "\\\"")
25 .replace('\n', "\\n")
26 .replace('\t', "\\t")
27 } else {
28 if string.contains('"') {
29 return Err(Error::QuoteInNonEscapeSequencedString);
30 }
31 string
32 };
33
34 if
35 temp_string.contains(char::is_whitespace) ||
36 temp_string.contains('"') ||
37 temp_string.contains('\\') ||
38 temp_string.is_empty()
39 {
40 Ok(format!("\"{}\"", temp_string))
41 } else {
42 Ok(temp_string)
43 }
44}
45
46pub fn serialize_object(
47 input: Vec<ValveKeyValue>,
48 use_escape_sequences: bool,
49 indentation_level: usize,
50 indentation_steps: usize
51) -> Result<String> {
52 let mut full = String::new();
53
54 for keypair in input {
55 full.push_str(&format!(
56 "{}{} {}\n",
57 " ".repeat(indentation_level * indentation_steps),
58 serialize_string(keypair.key, use_escape_sequences)?,
59 match keypair.value {
60 ValveKeyValueType::String(string) => serialize_string(string, use_escape_sequences)?,
61 ValveKeyValueType::Object(object) => {
62 format!(
63 "{{\n{}{}}}",
64 serialize_object(object, use_escape_sequences, indentation_level+1, indentation_steps)?,
65 " ".repeat(indentation_level * indentation_steps)
66 )
67 }
68 }
69 ));
70 }
71
72 Ok(full)
73}
74
75pub fn serialize(input: Vec<ValveKeyValue>, use_escape_sequences: bool, indentation_steps: usize) -> Result<String> {
77 serialize_object(input, use_escape_sequences, 0, indentation_steps)
78}