Skip to content

Commit 9bc8f31

Browse files
authored
Merge pull request #233 from kossnikita/feature/write-constraint-check
add write constraint range check
2 parents e0f5253 + 822a680 commit 9bc8f31

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

svd-rs/src/field.rs

+5
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,11 @@ impl FieldInfo {
312312
_ => return Err(Error::IncompatibleEnumeratedValues.into()),
313313
}
314314
}
315+
316+
if let Some(WriteConstraint::Range(constraint)) = self.write_constraint {
317+
constraint.check_range(0..2_u64.pow(self.bit_range.width))?;
318+
}
319+
315320
Ok(())
316321
}
317322

svd-rs/src/lib.rs

+3
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,9 @@ pub enum SvdError {
166166
/// RegisterProperties error
167167
#[error("`RegisterProperties error: {0}")]
168168
RegisterProperties(#[from] registerproperties::Error),
169+
/// WriteConstraint error
170+
#[error("`WriteConstraint error: {0}")]
171+
WriteConstraint(#[from] writeconstraint::Error),
169172
}
170173

171174
/// Errors from a builder

svd-rs/src/writeconstraint.rs

+27
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use super::SvdError;
2+
13
/// Define constraints for writing values to a field
24
#[cfg_attr(
35
feature = "serde",
@@ -25,3 +27,28 @@ pub struct WriteConstraintRange {
2527
#[cfg_attr(feature = "serde", serde(rename = "maximum"))]
2628
pub max: u64,
2729
}
30+
31+
/// Errors for [`WriteConstraintRange::check_range`]
32+
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
33+
pub enum Error {
34+
/// The value is not in range.
35+
#[error("Value {0} out of range {1:?}")]
36+
OutOfRange(u64, core::ops::Range<u64>),
37+
/// Minimum is greater than maximum.
38+
#[error("Range minimum {0} is greater than maximum {1}")]
39+
ReversedRange(u64, u64),
40+
}
41+
42+
impl WriteConstraintRange {
43+
pub(crate) fn check_range(&self, range: core::ops::Range<u64>) -> Result<(), SvdError> {
44+
if self.min > self.max {
45+
return Err(Error::ReversedRange(self.min, self.max).into());
46+
}
47+
for v in [&self.min, &self.max] {
48+
if !range.contains(v) {
49+
return Err(Error::OutOfRange(*v, range.clone()).into());
50+
}
51+
}
52+
Ok(())
53+
}
54+
}

0 commit comments

Comments
 (0)