toml_input/
util.rs

1use serde::Serialize;
2
3use crate::{COMMENT, TAG};
4
5pub fn value_to_string<T: Serialize>(value: &T) -> Result<String, toml::ser::Error> {
6    let mut ser_value = String::new();
7    let serializer = toml::ser::ValueSerializer::new(&mut ser_value);
8    value.serialize(serializer)?;
9    Ok(ser_value)
10}
11
12pub fn prefix_lines(text: &str, prefix: &str) -> String {
13    let lines: Vec<String> = text.lines().map(|line| prefix.to_string() + line).collect();
14    lines.join("\n")
15}
16
17pub fn comment_lines(text: &str) -> String {
18    let lines: Vec<String> = text
19        .lines()
20        .map(|line| COMMENT.to_string() + line)
21        .collect();
22    lines.join("\n")
23}
24
25pub fn append_line(text: &mut String) {
26    if !text.trim().is_empty() {
27        text.push('\n');
28    }
29}
30
31pub fn remove_prefix_tag(key: &str) -> String {
32    key.trim().strip_prefix(".").unwrap_or(key).to_string()
33}
34
35pub fn increase_key(key: &mut String, ident: impl AsRef<str>) {
36    if key.is_empty() {
37        *key = ident.as_ref().to_string();
38    } else {
39        *key = format!("{}{}{}", ident.as_ref(), TAG, key);
40    }
41}
42
43pub fn key_parent(key: &str) -> String {
44    let mut idents: Vec<_> = key.split(TAG).collect();
45    idents.pop();
46    idents.join(TAG)
47}