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