aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-assets/src/ui_configuration.rs
blob: e678d76075c01c8ca1d61c455fda05a2de989122 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use fparkan_path::{normalize_relative, PathPolicy};
use fparkan_vfs::Vfs;
use std::{collections::BTreeMap, sync::Arc};

pub(super) fn read(vfs: &dyn Vfs, path: &str) -> Result<Arc<[u8]>, String> {
    let path = normalize_relative(
        path.replace("\\\\", "\\").as_bytes(),
        PathPolicy::StrictLegacy,
    )
    .map_err(|error| error.to_string())?;
    vfs.read(&path).map_err(|error| error.to_string())
}

pub(super) fn object<'a>(text: &'a str, name: &str) -> Option<BTreeMap<String, &'a str>> {
    let mut lines = text
        .lines()
        .map(|line| line.split('#').next().unwrap_or_default().trim());
    for line in lines.by_ref() {
        let mut words = line.split_whitespace();
        if words
            .next()
            .is_some_and(|word| word.eq_ignore_ascii_case("object"))
            && words
                .next()
                .is_some_and(|word| word.eq_ignore_ascii_case(name))
        {
            return Some(
                lines
                    .take_while(|line| !line.eq_ignore_ascii_case("end"))
                    .filter_map(|line| line.split_once('='))
                    .map(|(key, value)| (key.trim().to_ascii_uppercase(), value.trim()))
                    .collect(),
            );
        }
    }
    None
}

pub(super) fn field<'a>(fields: &BTreeMap<String, &'a str>, key: &str) -> Result<&'a str, String> {
    let raw = fields.get(key).ok_or_else(|| format!("missing {key}"))?;
    if let Some(quoted) = raw.strip_prefix('"') {
        return quoted
            .split_once('"')
            .map(|(value, _)| value)
            .ok_or_else(|| format!("invalid quoted value for {key}"));
    }
    Ok(raw)
}

pub(super) fn number(fields: &BTreeMap<String, &str>, key: &str) -> Result<u32, String> {
    field(fields, key)?
        .parse()
        .map_err(|_| format!("invalid number for {key}"))
}