1use super::keep_bom;
15use crate::document::{DocumentError, DocumentResult, Value};
16use std::collections::BTreeMap;
17
18const MAX_INI_VALUE_BYTES: usize = 1024 * 1024;
19
20const ROOT: &str = "";
23
24#[derive(Debug, Clone, Copy)]
25struct IniEntry<'a> {
26 section: &'a str,
27 key: &'a str,
28}
29
30#[derive(Debug)]
34pub struct IniDocument<'a> {
35 source: &'a str,
36 entries: Vec<IniEntry<'a>>,
37 sections: BTreeMap<&'a str, usize>,
38}
39
40impl<'a> IniDocument<'a> {
41 pub fn parse(source: &'a str) -> DocumentResult<Self> {
42 let source = source.strip_prefix('\u{feff}').unwrap_or(source);
43 let mut entries = Vec::new();
44 let mut current: Option<&str> = None;
45 let mut sections = BTreeMap::<&str, usize>::new();
46 for (index, raw) in source.lines().enumerate() {
47 let line_number = index + 1;
48 let line = raw.trim_suffix('\r');
49 let trimmed = line.trim();
50 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
51 continue;
52 }
53 if trimmed.starts_with('[') {
54 let Some(name) = trimmed.strip_circumfix('[', ']') else {
55 return parse_error(line_number, 1, "invalid section header");
56 };
57 let name = name.trim();
58 if name.is_empty() || name.contains(['[', ']']) {
59 return parse_error(line_number, 1, "section name must be non-empty");
60 }
61 if sections.insert(name, line_number).is_some() {
62 return parse_error(line_number, 1, "duplicate section");
63 }
64 if entries
65 .iter()
66 .any(|entry: &IniEntry<'_>| entry.section == ROOT && entry.key == name)
67 {
68 return parse_error(
69 line_number,
70 1,
71 "section name collides with a root entry of the same name",
72 );
73 }
74 current = Some(name);
75 continue;
76 }
77 let section = current.unwrap_or(ROOT);
80 let Some((key, value)) = line.split_once('=') else {
81 return parse_error(line_number, 1, "expected key=value entry");
82 };
83 let key = key.trim();
84 if key.is_empty() || key.contains(['[', ']']) {
85 return parse_error(line_number, 1, "key must be non-empty");
86 }
87 if value.trim().len() > MAX_INI_VALUE_BYTES {
88 return parse_error(
89 line_number,
90 line.find('=').unwrap_or(0) + 2,
91 "value exceeds 1 MiB",
92 );
93 }
94 if entries
95 .iter()
96 .any(|entry: &IniEntry<'_>| entry.section == section && entry.key == key)
97 {
98 return parse_error(
99 line_number,
100 line.find(key).unwrap_or(0) + 1,
101 "duplicate key",
102 );
103 }
104 entries.push(IniEntry { section, key });
105 }
106 Ok(Self {
107 source,
108 entries,
109 sections,
110 })
111 }
112
113 fn has_entry(&self, section: &str, key: &str) -> bool {
114 self.entries
115 .iter()
116 .any(|entry| entry.section == section && entry.key == key)
117 }
118
119 fn has_section(&self, section: &str) -> bool {
120 self.sections.contains_key(section)
121 }
122
123 fn to_value(&self) -> Value {
124 let mut root = BTreeMap::<String, Value>::new();
125 let mut current: Option<String> = None;
126 for raw in self.source.lines() {
127 let line = raw.trim_suffix('\r');
128 let trimmed = line.trim();
129 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
130 continue;
131 }
132 if let Some(name) = trimmed.strip_circumfix('[', ']') {
133 let name = name.trim().to_string();
134 root.insert(name.clone(), Value::Object(BTreeMap::new()));
135 current = Some(name);
136 continue;
137 }
138 let Some((key, value)) = line.split_once('=') else {
139 continue;
140 };
141 let key = key.trim().to_string();
142 let value = Value::String(value.trim().to_string());
143 match current.as_ref() {
144 Some(section) => {
146 if let Some(Value::Object(entries)) = root.get_mut(section) {
147 entries.insert(key, value);
148 }
149 }
150 None => {
152 root.insert(key, value);
153 }
154 }
155 }
156 Value::Object(root)
157 }
158}
159
160pub fn load(content: &str) -> DocumentResult<Value> {
161 Ok(IniDocument::parse(content)?.to_value())
162}
163
164pub fn save(value: &Value) -> DocumentResult<String> {
165 let Value::Object(sections) = value else {
166 return Err(DocumentError::UnsupportedOperation {
167 format: "INI".to_string(),
168 operation: "save".to_string(),
169 detail: "INI requires a section object".to_string(),
170 });
171 };
172 let mut output = String::new();
173 for (key, value) in sections {
177 let Value::String(value) = value else {
178 continue;
179 };
180 output.push_str(key);
181 output.push('=');
182 output.push_str(value);
183 output.push('\n');
184 }
185 for (section, value) in sections {
186 let Value::Object(entries) = value else {
187 if matches!(value, Value::String(_)) {
190 continue;
191 }
192 return Err(DocumentError::UnsupportedOperation {
193 format: "INI".to_string(),
194 operation: "save".to_string(),
195 detail: format!("`{section}` must be a section object or a root string"),
196 });
197 };
198 output.push('[');
199 output.push_str(section);
200 output.push_str("]\n");
201 for (key, value) in entries {
202 let Value::String(value) = value else {
203 return Err(DocumentError::UnsupportedOperation {
204 format: "INI".to_string(),
205 operation: "save".to_string(),
206 detail: format!("entry `{section}.{key}` must remain a string"),
207 });
208 };
209 output.push_str(key);
210 output.push('=');
211 output.push_str(value);
212 output.push('\n');
213 }
214 }
215 validate_round_trip(&output, value, "save")?;
216 Ok(output)
217}
218
219pub(crate) fn set_preserving(content: &str, path: &str, value: &Value) -> DocumentResult<String> {
223 let Value::String(text) = value else {
224 return Err(unsupported("set", "INI values are strings"));
225 };
226 let mut expected = load(content)?;
227 crate::document::set_path(
228 &mut expected,
229 path,
230 value,
231 crate::document::Addressing::INDEX_ONLY,
232 )?;
233 let output = keep_bom(content, |body| edit_entry(body, path, Some(text)))?;
234 validate_round_trip(&output, &expected, "set")?;
235 Ok(output)
236}
237
238fn validate_round_trip(output: &str, expected: &Value, operation: &str) -> DocumentResult<()> {
242 if load(output).is_ok_and(|parsed| &parsed == expected) {
243 return Ok(());
244 }
245 Err(unsupported(
246 operation,
247 "INI names and values must round-trip without changing structure or whitespace",
248 ))
249}
250
251pub(crate) fn unset_preserving(content: &str, path: &str) -> DocumentResult<String> {
254 keep_bom(content, |body| unset_body(body, path))
255}
256
257fn unset_body(content: &str, path: &str) -> DocumentResult<String> {
258 if let [name] = crate::document::parse_path(path)?.as_slice() {
259 let document = IniDocument::parse(content).map_err(|error| with_path(error, path))?;
260 if !document.has_entry(ROOT, name) && document.has_section(name) {
263 return Ok(remove_section(content, name));
264 }
265 }
266 edit_entry(content, path, None)
267}
268
269fn remove_section(content: &str, name: &str) -> String {
271 let lines: Vec<_> = content.split_inclusive('\n').collect();
272 let mut start = None;
273 for (index, line) in lines.iter().enumerate() {
274 if let Some(header) = section_header(line) {
275 if let Some(start) = start {
276 return lines[..start]
277 .iter()
278 .chain(&lines[section_lead(&lines, index)..])
279 .copied()
280 .collect();
281 }
282 if header == name {
283 start = Some(section_lead(&lines, index));
284 }
285 }
286 }
287 lines[..start.unwrap_or(lines.len())].concat()
288}
289
290fn section_lead(lines: &[&str], header: usize) -> usize {
291 let after_content = lines[..header].iter().rposition(|line| {
292 let text = line.trim();
293 !text.is_empty() && !text.starts_with([';', '#'])
294 });
295 match after_content {
296 Some(index) => index + 1,
297 None => lines[..header]
301 .iter()
302 .rposition(|line| line.trim().is_empty())
303 .map_or(0, |index| index + 1),
304 }
305}
306
307fn section_header(line: &str) -> Option<String> {
309 let trimmed = line.trim_end_matches(['\n', '\r']).trim();
310 (trimmed.starts_with('[') && trimmed.ends_with(']'))
311 .then(|| trimmed[1..trimmed.len() - 1].trim().to_string())
312}
313
314fn ensure_terminated(output: &mut String, newline: &str) {
316 if !output.is_empty() && !output.ends_with('\n') {
317 output.push_str(newline);
318 }
319}
320
321fn edit_entry(content: &str, path: &str, replacement: Option<&str>) -> DocumentResult<String> {
322 let segments = crate::document::parse_path(path)?;
323 let (section, key) = match segments.as_slice() {
326 [key] => (ROOT.to_string(), key.clone()),
327 [section, key] => (section.clone(), key.clone()),
328 _ => return Err(unsupported("edit", "INI paths must be key or section.key")),
329 };
330 let document = IniDocument::parse(content).map_err(|error| with_path(error, path))?;
331 let section = §ion;
332 let key = &key;
333 let found = document.has_entry(section, key);
334 let newline = if content.contains("\r\n") {
335 "\r\n"
336 } else {
337 "\n"
338 };
339 let lines: Vec<&str> = content.split_inclusive('\n').collect();
340
341 if found {
342 let mut current = ROOT.to_string();
343 let mut output = String::with_capacity(content.len());
344 for line in &lines {
345 if let Some(name) = section_header(line) {
346 current = name;
347 }
348 let body = line.trim_suffix('\n');
349 let bare = body.trim_suffix('\r');
350 let matches = current == section.as_str()
351 && bare
352 .trim()
353 .split_once('=')
354 .filter(|(name, _)| !name.starts_with(['#', ';']))
355 .is_some_and(|(name, _)| name.trim() == key);
356 if !matches {
357 output.push_str(line);
358 continue;
359 }
360 let Some(value) = replacement else { continue };
363 let eq = bare.find('=').unwrap_or(bare.len());
364 output.push_str(&bare[..eq + 1]);
365 output.push_str(
366 &bare[eq + 1..]
367 .chars()
368 .take_while(|character| character.is_whitespace())
369 .collect::<String>(),
370 );
371 output.push_str(value);
372 if body.ends_with('\r') {
373 output.push('\r');
374 }
375 if line.ends_with('\n') {
376 output.push('\n');
377 }
378 }
379 return Ok(output);
380 }
381
382 let Some(value) = replacement else {
383 return Err(DocumentError::PathNotFound {
384 path: path.to_string(),
385 });
386 };
387 if section == ROOT && document.has_section(key) {
388 return Err(unsupported(
389 "edit",
390 "an INI root key cannot replace a section of the same name",
391 ));
392 }
393 if section != ROOT && document.has_entry(ROOT, section) {
394 return Err(unsupported(
395 "edit",
396 "an INI section cannot replace a root key of the same name",
397 ));
398 }
399
400 let mut section_seen = false;
405 let mut next_header = None;
406 for (index, line) in lines.iter().enumerate() {
407 let Some(name) = section_header(line) else {
408 continue;
409 };
410 if section_seen {
411 next_header = Some(index);
412 break;
413 }
414 if name == *section {
415 section_seen = true;
416 }
417 }
418
419 let entry = format!("{key}={value}{newline}");
420 let mut output = String::with_capacity(content.len() + entry.len());
421
422 if section == ROOT {
426 let first_header = lines
427 .iter()
428 .position(|line| section_header(line).is_some())
429 .unwrap_or(lines.len());
430 let first_header = section_lead(&lines, first_header);
431 for line in &lines[..first_header] {
432 output.push_str(line);
433 }
434 ensure_terminated(&mut output, newline);
435 output.push_str(&entry);
436 for line in &lines[first_header..] {
437 output.push_str(line);
438 }
439 return Ok(output);
440 }
441
442 match (section_seen, next_header) {
443 (true, Some(header)) => {
444 let at = section_lead(&lines, header);
445 for line in &lines[..at] {
446 output.push_str(line);
447 }
448 ensure_terminated(&mut output, newline);
449 output.push_str(&entry);
450 for line in &lines[at..] {
451 output.push_str(line);
452 }
453 }
454 (true, None) => {
455 output.push_str(content);
456 ensure_terminated(&mut output, newline);
457 output.push_str(&entry);
458 }
459 (false, _) => {
460 output.push_str(content);
461 if !output.is_empty() {
462 ensure_terminated(&mut output, newline);
463 output.push_str(newline);
464 }
465 output.push_str(&format!("[{section}]{newline}"));
466 output.push_str(&entry);
467 }
468 }
469 Ok(output)
470}
471
472fn unsupported(operation: &str, detail: &str) -> DocumentError {
473 DocumentError::UnsupportedOperation {
474 format: "INI".to_string(),
475 operation: operation.to_string(),
476 detail: detail.to_string(),
477 }
478}
479
480fn parse_error<T>(line: usize, column: usize, detail: &str) -> DocumentResult<T> {
481 Err(DocumentError::ParseError {
482 format: "INI Core v1".to_string(),
483 detail: format!("line {line}, column {column}: {detail}"),
484 })
485}
486
487fn with_path(error: DocumentError, path: &str) -> DocumentError {
488 match error {
489 DocumentError::ParseError { format, detail } => DocumentError::ParseError {
490 format,
491 detail: format!("path `{path}`: {detail}"),
492 },
493 other => other,
494 }
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500 use crate::document::{Document, Format};
501
502 #[test]
503 fn unrepresentable_edits_leave_the_document_unchanged() {
504 let source = "; keep\r\n[section]\r\nkey = old\r\n";
505 for (path, value) in [
506 ("section.key", "new\nextra=injected"),
507 ("section.key", " padded "),
508 ("section.new=key", "value"),
509 ("section.#hidden", "value"),
510 ("section. leading", "value"),
511 ("new[section.key", "value"),
512 ] {
513 let mut document = Document::parse(source, Format::Ini).unwrap();
514 let original = document.value().clone();
515 assert!(
516 document.set(path, Value::String(value.into())).is_err(),
517 "{path}"
518 );
519 assert_eq!(document.source(), source);
520 assert_eq!(document.value(), &original);
521 }
522 }
523
524 #[test]
525 fn unset_removes_a_whole_section_and_keeps_the_rest() {
526 let source = "top = 1\n[a]\nk = 1\n\n[b]\nk = 2\n";
527 let mut document = Document::parse(source, Format::Ini).unwrap();
528 assert!(document.unset("a").unwrap());
529 assert_eq!(document.source(), "top = 1\n\n[b]\nk = 2\n");
530 assert!(document.value().as_object().unwrap().get("a").is_none());
531 }
532
533 #[test]
534 fn save_refuses_names_and_values_that_change_when_reparsed() {
535 for source in [
536 r##"{"key":"value\nextra=injected"}"##,
537 r##"{"key":" padded "}"##,
538 r##"{"#hidden":"value"}"##,
539 r##"{"section":{"key=other":"value"}}"##,
540 r##"{"bad]section":{"key":"value"}}"##,
541 ] {
542 let value = Format::Json.load(source).unwrap();
543 assert!(save(&value).is_err());
544 }
545 }
546
547 #[test]
548 fn literal_delimiters_inside_values_still_round_trip() {
549 let value = Value::String("new=literal # ; value".into());
550 let source = "; keep\r\n[section]\r\nkey = old\r\n";
551 let edited = set_preserving(source, "section.key", &value).unwrap();
552 assert_eq!(
553 edited,
554 "; keep\r\n[section]\r\nkey = new=literal # ; value\r\n"
555 );
556 let parsed = load(&edited).unwrap();
557 assert_eq!(load(&save(&parsed).unwrap()).unwrap(), parsed);
558 }
559}