svd_parser/
types.rs

1//! Shared primitive types for use in SVD objects.
2#![allow(clippy::manual_strip)]
3
4use roxmltree::Node;
5
6use super::{ElementExt, Parse, SVDError, SVDErrorAt};
7
8impl Parse for u32 {
9    type Object = u32;
10    type Error = SVDErrorAt;
11    type Config = ();
12
13    fn parse(tree: &Node, _config: &Self::Config) -> Result<u32, Self::Error> {
14        let text = tree.get_text()?;
15
16        (if text.starts_with("0x") || text.starts_with("0X") {
17            u32::from_str_radix(&text["0x".len()..], 16)
18        } else if text.starts_with('#') {
19            // Handle strings in the binary form of:
20            // #01101x1
21            // along with don't care character x (replaced with 0)
22            u32::from_str_radix(
23                &str::replace(&text.to_lowercase()["#".len()..], "x", "0"),
24                2,
25            )
26        } else if text.starts_with("0b") {
27            // Handle strings in the binary form of:
28            // 0b01101x1
29            // along with don't care character x (replaced with 0)
30            u32::from_str_radix(&str::replace(&text["0b".len()..], "x", "0"), 2)
31        } else {
32            text.parse::<u32>()
33        })
34        .map_err(|e| SVDError::from(e).at(tree.id()))
35    }
36}
37
38impl Parse for u64 {
39    type Object = u64;
40    type Error = SVDErrorAt;
41    type Config = ();
42
43    fn parse(tree: &Node, _config: &Self::Config) -> Result<u64, Self::Error> {
44        let text = tree.get_text()?;
45
46        (if text.starts_with("0x") || text.starts_with("0X") {
47            u64::from_str_radix(&text["0x".len()..], 16)
48        } else if text.starts_with('#') {
49            // Handle strings in the binary form of:
50            // #01101x1
51            // along with don't care character x (replaced with 0)
52            u64::from_str_radix(
53                &str::replace(&text.to_lowercase()["#".len()..], "x", "0"),
54                2,
55            )
56        } else if text.starts_with("0b") {
57            // Handle strings in the binary form of:
58            // 0b01101x1
59            // along with don't care character x (replaced with 0)
60            u64::from_str_radix(&str::replace(&text["0b".len()..], "x", "0"), 2)
61        } else {
62            text.parse::<u64>()
63        })
64        .map_err(|e| SVDError::from(e).at(tree.id()))
65    }
66}
67
68pub struct BoolParse;
69
70impl Parse for BoolParse {
71    type Object = bool;
72    type Error = SVDErrorAt;
73    type Config = ();
74
75    fn parse(tree: &Node, _config: &Self::Config) -> Result<bool, Self::Error> {
76        let text = tree.get_text()?;
77        match text {
78            "0" => Ok(false),
79            "1" => Ok(true),
80            _ => match text.parse() {
81                Ok(b) => Ok(b),
82                Err(e) => Err(SVDError::InvalidBooleanValue(text.into(), e).at(tree.id())),
83            },
84        }
85    }
86}