Skip to main content

viva_genapi/
text.rs

1//! Feature values as text: for a program that does not know a feature's type
2//! in advance — a command line, a configuration file.
3
4use crate::nodes::Node;
5use crate::{GenApiError, NodeMap, RegisterIo, SkOutput};
6
7impl NodeMap {
8    /// Read a feature as text, formatted by its type: an integer in decimal,
9    /// a float in the shortest form that reads back to the same value, an
10    /// enumeration as its entry's name, a boolean as `true` or `false`.
11    ///
12    /// A category has no value and a command none to read: both are errors.
13    /// So is a `<Register>`, a byte array with no declared interpretation;
14    /// read it with [`NodeMap::get_register`].
15    pub fn get_text(&self, name: &str, io: &dyn RegisterIo) -> Result<String, GenApiError> {
16        match self.node(name) {
17            Some(Node::Integer(_) | Node::IntConverter(_)) => {
18                Ok(self.get_integer(name, io)?.to_string())
19            }
20            Some(Node::Float(_)) => Ok(self.get_float(name, io)?.to_string()),
21            Some(Node::Enum(_)) => self.get_enum(name, io),
22            Some(Node::Boolean(_)) => Ok(self.get_bool(name, io)?.to_string()),
23            Some(Node::SwissKnife(sk)) => match sk.output {
24                SkOutput::Float => Ok(self.get_float(name, io)?.to_string()),
25                SkOutput::Integer => Ok(self.get_integer(name, io)?.to_string()),
26            },
27            Some(Node::Converter(conv)) => match conv.output {
28                SkOutput::Float => Ok(self.get_converter(name, io)?.to_string()),
29                SkOutput::Integer => Ok((self.get_converter(name, io)? as i64).to_string()),
30            },
31            Some(Node::String(_)) => self.get_string(name, io),
32            Some(Node::Command(_)) => Err(GenApiError::wrong_kind(
33                name,
34                "Command",
35                "a feature with a value (a command is executed)",
36            )),
37            Some(Node::Category(_)) => Err(GenApiError::wrong_kind(
38                name,
39                "Category",
40                "a feature with a value",
41            )),
42            // A `<Register>` is a byte array with no declared interpretation:
43            // rendering it here would mean inventing an encoding nothing asked
44            // for. Raw access goes through `get_register`.
45            Some(Node::Register(_)) => Err(GenApiError::wrong_kind(
46                name,
47                "Register",
48                "a feature with a text form (a register is read as bytes)",
49            )),
50            None => Err(GenApiError::NodeNotFound(name.to_string())),
51        }
52    }
53
54    /// Write a feature from text, parsed by its type: the counterpart of
55    /// [`NodeMap::get_text`]. An integer is decimal or `0x`-prefixed
56    /// hexadecimal; a boolean is `true`/`false` or `1`/`0`.
57    ///
58    /// Text that does not parse as the feature's type is
59    /// [`GenApiError::InvalidText`], and nothing is written. A command is
60    /// executed, never set, and a category has nothing to set: both are
61    /// errors.
62    pub fn set_text(
63        &mut self,
64        name: &str,
65        text: &str,
66        io: &dyn RegisterIo,
67    ) -> Result<(), GenApiError> {
68        let invalid = |expected: &'static str| GenApiError::InvalidText {
69            name: name.to_string(),
70            expected,
71            text: text.to_string(),
72        };
73        match self.node(name) {
74            // A converter writes through its `<FormulaTo>`: `set_integer` and
75            // `set_float` dispatch to it.
76            Some(Node::Integer(_) | Node::IntConverter(_)) => {
77                let value = parse_integer(text).ok_or_else(|| invalid("an integer"))?;
78                self.set_integer(name, value, io)
79            }
80            Some(Node::Float(_) | Node::Converter(_)) => {
81                let value: f64 = text.trim().parse().map_err(|_| invalid("a number"))?;
82                self.set_float(name, value, io)
83            }
84            Some(Node::Enum(_)) => self.set_enum(name, text.trim(), io),
85            Some(Node::Boolean(_)) => {
86                let value = parse_bool(text).ok_or_else(|| invalid("a boolean"))?;
87                self.set_bool(name, value, io)
88            }
89            Some(Node::String(_)) => self.set_string(name, text, io),
90            Some(Node::Command(_)) => Err(GenApiError::wrong_kind(
91                name,
92                "Command",
93                "a feature that is set (a command is executed)",
94            )),
95            Some(other @ (Node::SwissKnife(_) | Node::Register(_) | Node::Category(_))) => Err(
96                GenApiError::wrong_kind(name, other.kind_name(), "a feature set from text"),
97            ),
98            None => Err(GenApiError::NodeNotFound(name.to_string())),
99        }
100    }
101}
102
103/// `true`/`false` or `1`/`0`, in any case.
104pub(crate) fn parse_bool(text: &str) -> Option<bool> {
105    match text.trim().to_ascii_lowercase().as_str() {
106        "1" | "true" => Some(true),
107        "0" | "false" => Some(false),
108        _ => None,
109    }
110}
111
112/// Decimal, or hexadecimal after `0x`; either may be negative.
113pub(crate) fn parse_integer(text: &str) -> Option<i64> {
114    let text = text.trim();
115    let (negative, digits) = match text.strip_prefix('-') {
116        Some(rest) => (true, rest),
117        None => (false, text),
118    };
119    let magnitude = match digits
120        .strip_prefix("0x")
121        .or_else(|| digits.strip_prefix("0X"))
122    {
123        Some(hex) => i64::from_str_radix(hex, 16).ok()?,
124        None => return text.parse().ok(),
125    };
126    Some(if negative { -magnitude } else { magnitude })
127}
128
129/// A register's bytes as `0x` and two lowercase hexadecimal digits per byte,
130/// in register order.
131pub(crate) fn bytes_to_hex(bytes: &[u8]) -> String {
132    let mut out = String::with_capacity(2 + bytes.len() * 2);
133    out.push_str("0x");
134    for byte in bytes {
135        out.push_str(&format!("{byte:02x}"));
136    }
137    out
138}
139
140/// The inverse of [`bytes_to_hex`]; the `0x` is optional.
141pub(crate) fn hex_to_bytes(text: &str) -> Option<Vec<u8>> {
142    let text = text.trim();
143    let digits = text
144        .strip_prefix("0x")
145        .or_else(|| text.strip_prefix("0X"))
146        .unwrap_or(text);
147    if !digits.len().is_multiple_of(2) {
148        return None;
149    }
150    (0..digits.len())
151        .step_by(2)
152        .map(|i| u8::from_str_radix(digits.get(i..i + 2)?, 16).ok())
153        .collect()
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn integers_are_decimal_or_hexadecimal() {
162        assert_eq!(parse_integer("42"), Some(42));
163        assert_eq!(parse_integer(" -7 "), Some(-7));
164        assert_eq!(parse_integer("0x1F"), Some(31));
165        assert_eq!(parse_integer("-0x10"), Some(-16));
166        assert_eq!(parse_integer("4.5"), None);
167        assert_eq!(parse_integer("0x"), None);
168    }
169
170    #[test]
171    fn register_bytes_round_trip_through_hex() {
172        let bytes = [0x00, 0x1f, 0xa0, 0xff];
173        assert_eq!(bytes_to_hex(&bytes), "0x001fa0ff");
174        assert_eq!(hex_to_bytes("0x001fa0ff").as_deref(), Some(&bytes[..]));
175        assert_eq!(hex_to_bytes("001FA0FF").as_deref(), Some(&bytes[..]));
176        assert_eq!(hex_to_bytes("0x123"), None);
177        assert_eq!(hex_to_bytes("0xzz"), None);
178    }
179}