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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
use super::{BuildError, EmptyToNone, EnumeratedValue, SvdError, ValidateLevel};
use std::borrow::Cow;
use std::ops::RangeInclusive;

/// Defines arrays and lists.
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(rename_all = "camelCase")
)]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct DimElement {
    /// Defines the number of elements in an array or list
    pub dim: u32,

    /// Specify the address increment between two neighboring array or list members in the address map
    pub dim_increment: u32,

    /// Specify the strings that substitue the placeholder `%s` within `name` and `displayName`.
    /// By default, <dimIndex> is a value starting with 0
    #[cfg_attr(
        feature = "serde",
        serde(
            deserialize_with = "ser_de::deserialize_dim_index",
            serialize_with = "ser_de::serialize_dim_index",
            skip_serializing_if = "Option::is_none"
        )
    )]
    pub dim_index: Option<Vec<String>>,

    /// Specify the name of the structure. If not defined, then the entry of the `name` element is used
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub dim_name: Option<String>,

    /// Grouping element to create enumerations in the header file
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub dim_array_index: Option<DimArrayIndex>,
}

/// Grouping element to create enumerations in the header file
///
/// This information is used for generating an enum in the device header file.
/// The debugger may use this information to display the identifier string
/// as well as the description. Just like symbolic constants making source
/// code more readable, the system view in the debugger becomes more instructive
#[cfg_attr(
    feature = "serde",
    derive(serde::Deserialize, serde::Serialize),
    serde(rename_all = "camelCase")
)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DimArrayIndex {
    /// Specify the base name of enumerations
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Option::is_none")
    )]
    pub header_enum_name: Option<String>,

    /// Specify the values contained in the enumeration
    pub values: Vec<EnumeratedValue>,
}

/// Builder for [`DimElement`]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DimElementBuilder {
    dim: Option<u32>,
    dim_increment: Option<u32>,
    dim_index: Option<Vec<String>>,
    dim_name: Option<String>,
    dim_array_index: Option<DimArrayIndex>,
}

impl From<DimElement> for DimElementBuilder {
    fn from(d: DimElement) -> Self {
        Self {
            dim: Some(d.dim),
            dim_increment: Some(d.dim_increment),
            dim_index: d.dim_index,
            dim_name: d.dim_name,
            dim_array_index: d.dim_array_index,
        }
    }
}

impl DimElementBuilder {
    /// Set the dim of the elements
    pub fn dim(mut self, value: u32) -> Self {
        self.dim = Some(value);
        self
    }
    /// Set the dim increment of the elements
    pub fn dim_increment(mut self, value: u32) -> Self {
        self.dim_increment = Some(value);
        self
    }
    /// Set the dim index of the elements
    pub fn dim_index(mut self, value: Option<Vec<String>>) -> Self {
        self.dim_index = value;
        self
    }
    /// Set the dim name of the elements
    pub fn dim_name(mut self, value: Option<String>) -> Self {
        self.dim_name = value;
        self
    }
    /// Set the dim_array_index of the elements
    pub fn dim_array_index(mut self, value: Option<DimArrayIndex>) -> Self {
        self.dim_array_index = value;
        self
    }
    /// Validate and build a [`DimElement`].
    pub fn build(self, lvl: ValidateLevel) -> Result<DimElement, SvdError> {
        let de = DimElement {
            dim: self
                .dim
                .ok_or_else(|| BuildError::Uninitialized("dim".to_string()))?,
            dim_increment: self
                .dim_increment
                .ok_or_else(|| BuildError::Uninitialized("dim_increment".to_string()))?,
            dim_index: self.dim_index.empty_to_none(),
            dim_name: self.dim_name.empty_to_none(),
            dim_array_index: self.dim_array_index,
        };
        de.validate(lvl)?;
        Ok(de)
    }
}

impl DimElement {
    /// Make a builder for [`DimElement`]
    pub fn builder() -> DimElementBuilder {
        DimElementBuilder::default()
    }

    /// Get array of indexes from string
    pub fn parse_indexes(text: &str) -> Option<Vec<String>> {
        (if text.contains('-') {
            let (start, end) = text.split_once('-')?;
            if let (Ok(start), Ok(end)) = (start.parse::<u32>(), end.parse::<u32>()) {
                Some((start..=end).map(|i| i.to_string()).collect::<Vec<_>>())
            } else {
                let mut start = start.bytes();
                let mut end = end.bytes();
                match (start.next(), start.next(), end.next(), end.next()) {
                    (Some(start), None, Some(end), None)
                        if (start.is_ascii_lowercase() && end.is_ascii_lowercase())
                            || (start.is_ascii_uppercase() && end.is_ascii_uppercase()) =>
                    {
                        Some((start..=end).map(|c| char::from(c).to_string()).collect())
                    }
                    _ => None,
                }
            }
        } else {
            Some(text.split(',').map(|s| s.to_string()).collect())
        })
        .filter(|v| !v.is_empty())
    }
    /// Try to represent [`DimElement`] as range of integer indexes
    pub fn indexes_as_range(&self) -> Option<RangeInclusive<u32>> {
        let mut integers = Vec::with_capacity(self.dim as usize);
        for idx in self.indexes() {
            // XXX: indexes that begin with leading zero are not compatible with range (`0-x`) syntax in serialization
            // see https://github.com/rust-embedded/svdtools/pull/178#issuecomment-1801433808
            let val = idx.parse::<u32>().ok()?;
            if val.to_string() != idx {
                return None;
            }
            integers.push(val);
        }
        let min = *integers.iter().min()?;
        let max = *integers.iter().max()?;
        if max - min + 1 != self.dim {
            return None;
        }
        for (&i, r) in integers.iter().zip(min..=max) {
            if i != r {
                return None;
            }
        }
        Some(min..=max)
    }
    /// Modify an existing [`DimElement`] based on a [builder](DimElementBuilder).
    pub fn modify_from(
        &mut self,
        builder: DimElementBuilder,
        lvl: ValidateLevel,
    ) -> Result<(), SvdError> {
        if let Some(dim) = builder.dim {
            self.dim = dim;
        }
        if let Some(dim_increment) = builder.dim_increment {
            self.dim_increment = dim_increment;
        }
        if builder.dim_index.is_some() {
            self.dim_index = builder.dim_index.empty_to_none();
        }
        if builder.dim_name.is_some() {
            self.dim_name = builder.dim_name.empty_to_none();
        }
        if builder.dim_array_index.is_some() {
            self.dim_array_index = builder.dim_array_index;
        }
        self.validate(lvl)
    }
    /// Validate the [`DimElement`].
    ///
    /// # Notes
    ///
    /// This doesn't do anything.
    pub fn validate(&self, _lvl: ValidateLevel) -> Result<(), SvdError> {
        // TODO
        Ok(())
    }
    /// Get the indexes of the array or list.
    pub fn indexes(&self) -> Indexes {
        Indexes {
            i: 0,
            dim: self.dim,
            dim_index: &self.dim_index,
        }
    }
}

/// Indexes into a [DimElement]
pub struct Indexes<'a> {
    i: u32,
    dim: u32,
    dim_index: &'a Option<Vec<String>>,
}

impl<'a> Iterator for Indexes<'a> {
    type Item = Cow<'a, str>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.i == self.dim {
            return None;
        }
        let i = self.i;
        self.i += 1;
        if let Some(index) = self.dim_index.as_ref() {
            Some(index[i as usize].as_str().into())
        } else {
            Some(i.to_string().into())
        }
    }
}

#[cfg(feature = "serde")]
mod ser_de {
    use super::*;
    use serde::{de, Deserialize, Deserializer, Serializer};
    #[derive(serde::Serialize, serde::Deserialize)]
    #[serde(untagged)]
    enum DimIndex {
        Array(Vec<String>),
        String(String),
    }

    pub fn deserialize_dim_index<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(match Option::<DimIndex>::deserialize(deserializer)? {
            None => None,
            Some(DimIndex::Array(a)) => Some(a),
            Some(DimIndex::String(s)) => Some(
                DimElement::parse_indexes(&s)
                    .ok_or_else(|| de::Error::custom("Failed to deserialize dimIndex"))?,
            ),
        })
    }

    pub fn serialize_dim_index<S>(val: &Option<Vec<String>>, s: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        s.serialize_str(&val.as_ref().unwrap().join(","))
    }
}