Skip to main content

valve_keyvalue/
serialize.rs

1/*
2   Copyright 2026 Gerg0Vagyok
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17use 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
75// small wrapper to make it nicer to use
76pub 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}