1use indexmap::IndexMap;
22#[cfg(feature = "serialization")]
23use serde::{Deserialize, Serialize};
24
25pub mod parse_ctx;
26pub mod parser;
27pub mod system;
28pub mod transform;
29pub(crate) mod utils;
30pub mod vmf;
31
32pub mod errors;
33pub mod prelude;
34
35pub use errors::{VmfError, VmfResult};
36pub use parse_ctx::{FromBlock, ParseCtx};
37
38pub trait VmfSerializable {
40 fn to_vmf_string(&self, indent_level: usize) -> String;
50}
51
52pub use system::{Flattened, Instance, VmfSystem};
53pub use transform::Transform;
54pub use vmf::{EntId, EntityIndex, VmfFile};
55
56#[derive(Debug, Default, Clone, PartialEq, Eq)]
58#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
59pub struct Extras {
60 pub key_values: IndexMap<String, String>,
62 pub blocks: Vec<VmfBlock>,
64}
65
66pub const REPEATED_KEY_SEP: char = '\r';
68
69pub fn write_key_value(output: &mut String, indent: &str, key: &str, value: &str) {
71 for part in value.split(REPEATED_KEY_SEP) {
72 output.push_str(indent);
73 output.push('"');
74 output.push_str(key);
75 output.push_str("\" \"");
76 output.push_str(part);
77 output.push_str("\"\n");
78 }
79}
80
81pub fn join_repeated_key(values: impl IntoIterator<Item = impl std::fmt::Display>) -> String {
83 let mut joined = String::new();
84 for value in values {
85 if !joined.is_empty() {
86 joined.push(REPEATED_KEY_SEP);
87 }
88 joined.push_str(&value.to_string());
89 }
90 joined
91}
92
93impl Extras {
94 pub fn is_empty(&self) -> bool {
95 self.key_values.is_empty() && self.blocks.is_empty()
96 }
97
98 pub fn write_key_values(&self, output: &mut String, indent_level: usize) {
100 let indent = "\t".repeat(indent_level);
101 for (key, value) in &self.key_values {
102 write_key_value(output, &indent, key, value);
103 }
104 }
105
106 pub fn write_blocks(&self, output: &mut String, indent_level: usize) {
108 for block in &self.blocks {
109 output.push_str(&block.serialize(indent_level));
110 }
111 }
112}
113
114#[derive(Debug, Default, Clone, PartialEq, Eq)]
116#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
117pub struct VmfBlock {
118 pub name: String,
120 pub key_values: IndexMap<String, String>, pub blocks: Vec<VmfBlock>,
124}
125
126impl VmfBlock {
127 pub fn serialize(&self, indent_level: usize) -> String {
137 let indent = "\t".repeat(indent_level);
138 let mut output = String::new();
139
140 output.push_str(&format!("{}{}\n", indent, self.name));
142 output.push_str(&format!("{}{{\n", indent));
143
144 for (key, value) in &self.key_values {
146 write_key_value(&mut output, &format!("{indent}\t"), key, value);
147 }
148
149 for block in &self.blocks {
151 output.push_str(&block.serialize(indent_level + 1));
152 }
153
154 output.push_str(&format!("{}}}\n", indent));
156
157 output
158 }
159}