Skip to main content

base/
ini.rs

1// ini -- settings files: UTF-8 "[section]" / "key=value" text              [src/core/ini.s]
2//
3//   Ini::new() / Ini::load(path) / Ini::parse(bytes)    a missing or unreadable file is empty
4//   ini.save(path) -> bool       plat::write_file, creates missing directories
5//   ini.to_bytes()               the text save writes
6//   ini.get(sec, key) -> Option<&str>   (get_bytes for values that are not UTF-8)
7//   ini.get_int(sec, key, def)   decimal (+/-), 0x hex, true/false/yes/no/on/off; else def
8//   ini.get_f64(sec, key, def)   '.' decimal point only; else def
9//   ini.set(sec, key, value) / set_int / set_f64 -> bool   add or replace (false: bad name)
10//   ini.remove(sec, key) -> bool
11//   ini.section(sec) -> Vec<(&str, &str)>   the keys of a section and their values, in order
12//   ini.sections() -> Vec<&str>   the section names in file order (each once; not "")
13//   ini.items() -> Vec<Item>      headers, keys and malformed lines with their line numbers
14//                                 (files that are checked: a theme names a mistake's line)
15//
16// Format: one entry per line; sec "" = the keys before the first [section].  Section and
17// key names compare ASCII case-insensitively; values are stored as written (blanks around
18// names and values trimmed; no quoting, no inline comments, so values may contain ';' and
19// '#').  Lines starting with ';' or '#', blank lines and malformed lines (no '=', "[" without
20// "]", NUL bytes, longer than LINE_MAX) are kept verbatim and written back unchanged, as are
21// all lines not touched by set (the original spacing survives).  New keys go after the
22// last key of their section, new sections to the end.  A UTF-8 BOM is skipped.  Files are
23// read up to FILE_MAX bytes; after LINES_MAX lines the rest is kept as one verbatim block.
24// Line ends: LF, CRLF (any number of CRs before the LF are dropped) when reading; written as
25// CRLF on Windows, LF on Linux.  Key names must not contain '=', NUL, CR or LF nor start with
26// ';' '#' '['; section names must not contain ']', NUL, CR or LF; neither may start or end with
27// a blank (set -> false).  CR / LF inside a value are written as blanks.
28
29use alloc::format;
30use alloc::vec::Vec;
31
32use crate::num::{f64_format, f64_parse, parse_i64};
33
34const FILE_MAX: u64 = 0x100_0000; // 16 MB read at most
35const LINE_MAX: usize = 0x10000; // longer lines are kept verbatim, not interpreted
36const LINES_MAX: usize = 0x40000;
37#[cfg(windows)]
38const EOL: &[u8] = b"\r\n";
39#[cfg(not(windows))]
40const EOL: &[u8] = b"\n";
41
42#[derive(Clone, Copy, PartialEq, Eq)]
43enum Kind {
44    Raw, // blank, comment, malformed
45    Sec,
46    Kv,
47}
48
49struct Line {
50    kind: Kind,
51    dirty: bool, // written as key=value / [name] instead of the raw text
52    sec: i32,    // line index of the section header, -1 = before any header
53    raw: Vec<u8>, // the line without its end
54    name: Vec<u8>, // section name / key
55    value: Vec<u8>,
56}
57
58impl Line {
59    fn new(kind: Kind, sec: i32) -> Line {
60        Line { kind, dirty: false, sec, raw: Vec::new(), name: Vec::new(), value: Vec::new() }
61    }
62}
63
64/// a settings object (one thread at a time)
65#[derive(Default)]
66pub struct Ini {
67    lines: Vec<Line>,
68}
69
70/// a line of the file as Ini::items lists it (line numbers from 1)
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Item<'a> {
73    /// a "[name]" header
74    Section { line: usize, name: &'a str },
75    /// "key = value" of section sec ("" before the first header)
76    Key { line: usize, sec: &'a str, key: &'a str, value: &'a str },
77    /// neither blank, a comment, a header nor a key (or not UTF-8)
78    Bad { line: usize, text: &'a [u8] },
79}
80
81/// n bytes equal ignoring ASCII case (only letters may differ in case)  [ieq]
82fn ieq(a: &[u8], b: &[u8]) -> bool {
83    a.len() == b.len()
84        && a.iter().zip(b).all(|(&x, &y)| x == y || (x | 32 == y | 32 && (x | 32).wrapping_sub(b'a') <= 25))
85}
86
87fn blank(c: u8) -> bool {
88    c == b' ' || c == b'\t'
89}
90
91/// usable as a key (is_key) or section name  [name_ok]
92fn name_ok(s: &[u8], is_key: bool) -> bool {
93    let (Some(&first), Some(&last)) = (s.first(), s.last()) else { return false };
94    if blank(first) || blank(last) || (is_key && matches!(first, b';' | b'#' | b'[')) {
95        return false;
96    }
97    let forbid = if is_key { b'=' } else { b']' };
98    !s.iter().any(|&c| c == b'\r' || c == b'\n' || c == 0 || c == forbid)
99}
100
101fn trim(mut s: &[u8]) -> &[u8] {
102    while let [c, rest @ ..] = s {
103        if !blank(*c) {
104            break;
105        }
106        s = rest;
107    }
108    while let [rest @ .., c] = s {
109        if !blank(*c) {
110            break;
111        }
112        s = rest;
113    }
114    s
115}
116
117impl Ini {
118    pub fn new() -> Ini {
119        Ini { lines: Vec::new() }
120    }
121
122    /// the parsed file; empty when it is missing or unreadable  [ini_load]
123    pub fn load(path: &str) -> Ini {
124        let Some(f) = plat::File::open(path, plat::FO_READ) else { return Ini::new() };
125        let size = f.size().unwrap_or(0).min(FILE_MAX) as usize;
126        if size == 0 {
127            return Ini::new();
128        }
129        let mut data = alloc::vec![0u8; size];
130        let got = f.read_at(0, &mut data).unwrap_or(0);
131        drop(f);
132        Ini::parse(&data[..got])
133    }
134
135    /// like load, but None when the file could not be read completely (unreadable, its size
136    /// unknown, longer than FILE_MAX, or whether it exists is unknown: refused, an I/O error, a
137    /// folder there); a missing or empty file gives an empty Ini
138    pub fn load_checked(path: &str) -> Option<Ini> {
139        let Some(f) = plat::File::open(path, plat::FO_READ) else {
140            // only a name that is surely free counts as missing
141            return (plat::file_exists_checked(path) == Some(0)).then(Ini::new);
142        };
143        let full = f.size()?;
144        if full > FILE_MAX {
145            return None;
146        }
147        let size = full as usize;
148        if size == 0 {
149            return Some(Ini::new());
150        }
151        let mut data = alloc::vec![0u8; size];
152        let got = f.read_at(0, &mut data)?;
153        drop(f);
154        if got != size {
155            return None;
156        }
157        Some(Ini::parse(&data))
158    }
159
160    /// parse settings text  [ini_parse]
161    pub fn parse(data: &[u8]) -> Ini {
162        let mut ini = Ini::new();
163        let mut pos = if data.starts_with(&[0xEF, 0xBB, 0xBF]) { 3 } else { 0 };
164        let end = data.len();
165        let mut cur: i32 = -1;
166        while pos < end {
167            if ini.lines.len() >= LINES_MAX - 1 {
168                // too many lines: the rest as one verbatim block (without its last line end)
169                let mut e = end;
170                if data[e - 1] == b'\n' {
171                    e -= 1;
172                }
173                while e > pos && data[e - 1] == b'\r' {
174                    e -= 1;
175                }
176                ini.classify(&data[pos..e], true, &mut cur);
177                break;
178            }
179            let lf = data[pos..].iter().position(|&c| c == b'\n').map_or(end, |k| pos + k);
180            let nul = data[pos..lf].contains(&0);
181            let mut e = lf;
182            while e > pos && data[e - 1] == b'\r' {
183                e -= 1; // every CR before the LF: a kept one would read back differently
184            }
185            ini.classify(&data[pos..e], nul, &mut cur);
186            pos = lf + 1;
187        }
188        ini
189    }
190
191    /// append one line  [classify]
192    fn classify(&mut self, raw: &[u8], verbatim: bool, cur: &mut i32) {
193        let mut ln = Line::new(Kind::Raw, *cur);
194        ln.raw = raw.to_vec();
195        let t = trim(raw);
196        if !verbatim && raw.len() <= LINE_MAX && !t.is_empty() && t[0] != b';' && t[0] != b'#' {
197            if t[0] == b'[' {
198                if let Some(close) = t.iter().position(|&c| c == b']') {
199                    let after = trim(&t[close + 1..]);
200                    let name = trim(&t[1..close]);
201                    if (after.is_empty() || after[0] == b';' || after[0] == b'#') && !name.is_empty() {
202                        ln.kind = Kind::Sec;
203                        ln.name = name.to_vec();
204                        ln.sec = self.lines.len() as i32;
205                        *cur = ln.sec; // following keys belong here
206                    }
207                }
208            } else if let Some(eq) = t.iter().position(|&c| c == b'=') {
209                let key = trim(&t[..eq]);
210                if !key.is_empty() {
211                    ln.kind = Kind::Kv;
212                    ln.name = key.to_vec();
213                    ln.value = trim(&t[eq + 1..]).to_vec();
214                }
215            }
216        }
217        self.lines.push(ln);
218    }
219
220    /// the text save writes
221    pub fn to_bytes(&self) -> Vec<u8> {
222        let mut out = Vec::new();
223        for l in &self.lines {
224            if !l.dirty {
225                out.extend_from_slice(&l.raw);
226            } else if l.kind == Kind::Sec {
227                out.push(b'[');
228                out.extend_from_slice(&l.name);
229                out.push(b']');
230            } else {
231                out.extend_from_slice(&l.name);
232                out.push(b'=');
233                out.extend_from_slice(&l.value);
234            }
235            out.extend_from_slice(EOL);
236        }
237        out
238    }
239
240    /// Write through plat::write_file; missing directories are created. [ini_save]
241    pub fn save(&self, path: &str) -> bool {
242        let text = self.to_bytes();
243        mkparent(path);
244        plat::write_file(path, &text)
245    }
246
247    /// the line of the key or None  [find_kv]
248    fn find_kv(&self, sec: &str, key: &str) -> Option<usize> {
249        let (sec, key) = (sec.as_bytes(), key.as_bytes());
250        self.lines.iter().position(|l| {
251            l.kind == Kind::Kv
252                && ieq(&l.name, key)
253                && if l.sec < 0 { sec.is_empty() } else { !sec.is_empty() && ieq(&self.lines[l.sec as usize].name, sec) }
254        })
255    }
256
257    /// the first header named sec  [find_sec]
258    fn find_sec(&self, sec: &str) -> Option<usize> {
259        self.lines.iter().position(|l| l.kind == Kind::Sec && ieq(&l.name, sec.as_bytes()))
260    }
261
262    /// where a new key of section line s (-1 = global) goes: after its last key, else right
263    /// after the header (global: before the first header)  [sec_end]
264    fn sec_end(&self, s: i32) -> usize {
265        let mut after = None;
266        let mut first_hdr = None;
267        for (i, l) in self.lines.iter().enumerate() {
268            if l.kind == Kind::Sec {
269                first_hdr.get_or_insert(i);
270            } else if l.kind == Kind::Kv && l.sec == s {
271                after = Some(i + 1);
272            }
273        }
274        match after {
275            Some(a) => a,
276            None if s >= 0 => s as usize + 1,
277            None => first_hdr.unwrap_or(self.lines.len()),
278        }
279    }
280
281    /// insert a line; section references at or behind pos move with their header
282    fn line_insert(&mut self, pos: usize, ln: Line) {
283        for l in self.lines.iter_mut() {
284            if l.sec >= pos as i32 {
285                l.sec += 1;
286            }
287        }
288        self.lines.insert(pos, ln);
289    }
290
291    /// remove a line (references to it become -1, those behind it move down)
292    fn line_delete(&mut self, pos: usize) {
293        self.lines.remove(pos);
294        for l in self.lines.iter_mut() {
295            if l.sec == pos as i32 {
296                l.sec = -1;
297            } else if l.sec > pos as i32 {
298                l.sec -= 1;
299            }
300        }
301    }
302
303    /// every key of a section with its value, in file order (entries that are not UTF-8 are
304    /// left out; sec "" = the keys before the first header)
305    pub fn section(&self, sec: &str) -> Vec<(&str, &str)> {
306        let s = sec.as_bytes();
307        self.lines
308            .iter()
309            .filter(|l| l.kind == Kind::Kv && if l.sec < 0 { s.is_empty() } else { !s.is_empty() && ieq(&self.lines[l.sec as usize].name, s) })
310            .filter_map(|l| Some((core::str::from_utf8(&l.name).ok()?, core::str::from_utf8(&l.value).ok()?)))
311            .collect()
312    }
313
314    /// the names of the sections in file order, each once (names that are not UTF-8 are left
315    /// out; the keys before the first header are not a section here)
316    pub fn sections(&self) -> Vec<&str> {
317        let mut out: Vec<&str> = Vec::new();
318        for l in self.lines.iter().filter(|l| l.kind == Kind::Sec) {
319            if let Ok(n) = core::str::from_utf8(&l.name) {
320                if !out.iter().any(|o| ieq(o.as_bytes(), n.as_bytes())) {
321                    out.push(n);
322                }
323            }
324        }
325        out
326    }
327
328    /// every header, key and malformed line in file order with its line number; blank lines
329    /// and comments are left out
330    pub fn items(&self) -> Vec<Item<'_>> {
331        let mut out = Vec::new();
332        for (i, l) in self.lines.iter().enumerate() {
333            let line = i + 1;
334            match l.kind {
335                Kind::Sec => match core::str::from_utf8(&l.name) {
336                    Ok(name) => out.push(Item::Section { line, name }),
337                    Err(_) => out.push(Item::Bad { line, text: &l.raw }),
338                },
339                Kind::Kv => {
340                    let sec = if l.sec < 0 { Ok("") } else { core::str::from_utf8(&self.lines[l.sec as usize].name) };
341                    match (sec, core::str::from_utf8(&l.name), core::str::from_utf8(&l.value)) {
342                        (Ok(sec), Ok(key), Ok(value)) => out.push(Item::Key { line, sec, key, value }),
343                        _ => out.push(Item::Bad { line, text: &l.raw }),
344                    }
345                }
346                Kind::Raw => {
347                    let t = trim(&l.raw);
348                    if !t.is_empty() && t[0] != b';' && t[0] != b'#' {
349                        out.push(Item::Bad { line, text: &l.raw });
350                    }
351                }
352            }
353        }
354        out
355    }
356
357    /// the value, or None when missing or not UTF-8  [ini_get]
358    pub fn get(&self, sec: &str, key: &str) -> Option<&str> {
359        core::str::from_utf8(self.get_bytes(sec, key)?).ok()
360    }
361
362    pub fn get_bytes(&self, sec: &str, key: &str) -> Option<&[u8]> {
363        self.find_kv(sec, key).map(|i| self.lines[i].value.as_slice())
364    }
365
366    /// [ini_get_int]
367    pub fn get_int(&self, sec: &str, key: &str, def: i64) -> i64 {
368        self.get_bytes(sec, key).and_then(parse_i64).unwrap_or(def)
369    }
370
371    /// the whole value must be the number  [ini_get_f64]
372    pub fn get_f64(&self, sec: &str, key: &str, def: f64) -> f64 {
373        match self.get_bytes(sec, key) {
374            Some(v) => match f64_parse(v) {
375                (x, used) if used > 0 && used == v.len() => x,
376                _ => def,
377            },
378            None => def,
379        }
380    }
381
382    /// add or replace (false: a bad name)  [ini_set]
383    pub fn set(&mut self, sec: &str, key: &str, value: &str) -> bool {
384        if !name_ok(key.as_bytes(), true) || (!sec.is_empty() && !name_ok(sec.as_bytes(), false)) {
385            return false;
386        }
387        let v: Vec<u8> = value.bytes().map(|c| if c == b'\r' || c == b'\n' || c == 0 { b' ' } else { c }).collect();
388        if let Some(i) = self.find_kv(sec, key) {
389            let l = &mut self.lines[i];
390            l.value = v;
391            l.dirty = true;
392            return true;
393        }
394        let mut s: i32 = -1; // section line of the new key
395        if !sec.is_empty() {
396            s = match self.find_sec(sec) {
397                Some(i) => i as i32,
398                None => {
399                    // a new section at the end, after a blank line
400                    let n = self.lines.len();
401                    if n > 0 && !(self.lines[n - 1].kind == Kind::Raw && self.lines[n - 1].raw.is_empty()) {
402                        self.line_insert(n, Line::new(Kind::Raw, -1));
403                    }
404                    let n = self.lines.len();
405                    let mut h = Line::new(Kind::Sec, n as i32);
406                    h.dirty = true;
407                    h.name = sec.as_bytes().to_vec();
408                    self.line_insert(n, h);
409                    n as i32
410                }
411            };
412        }
413        let pos = self.sec_end(s);
414        let mut k = Line::new(Kind::Kv, s);
415        k.dirty = true;
416        k.name = key.as_bytes().to_vec();
417        k.value = v;
418        self.line_insert(pos, k);
419        true
420    }
421
422    /// [ini_set_int]
423    pub fn set_int(&mut self, sec: &str, key: &str, value: i64) -> bool {
424        self.set(sec, key, &format!("{value}"))
425    }
426
427    /// the shortest text that reads back to the same double  [ini_set_f64]
428    pub fn set_f64(&mut self, sec: &str, key: &str, value: f64) -> bool {
429        self.set(sec, key, &f64_format(value))
430    }
431
432    /// false: not there  [ini_remove]
433    pub fn remove(&mut self, sec: &str, key: &str) -> bool {
434        match self.find_kv(sec, key) {
435            Some(i) => {
436                self.line_delete(i);
437                true
438            }
439            None => false,
440        }
441    }
442}
443
444/// create the directory part of path (if any)  [mkparent]
445fn mkparent(path: &str) {
446    let b = path.as_bytes();
447    let Some(sep) = b.iter().rposition(|&c| c == b'/' || c == b'\\') else { return };
448    if sep == 0 || (sep == 2 && b[1] == b':') {
449        return; // "/name", "C:/name"
450    }
451    plat::mkdir(&path[..sep]);
452}