Skip to content

Commit 41b6dc1

Browse files
committed
Add helper method to check if attribute value represents boolean value
1 parent 40538b7 commit 41b6dc1

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

Changelog.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,14 @@
1515

1616
### New Features
1717

18+
- [#850]: Add `Attribute::as_bool()` method to get an attribute value as a boolean.
19+
1820
### Bug Fixes
1921

2022
### Misc Changes
2123

24+
[#850]: https://github.com/tafia/quick-xml/pull/850
25+
2226

2327
## 0.37.2 -- 2024-12-29
2428

src/events/attributes.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,42 @@ impl<'a> Attribute<'a> {
9696
Cow::Owned(s) => Ok(s.into()),
9797
}
9898
}
99+
100+
/// If attribute value [represents] valid boolean values, returns `Some`, otherwise returns `None`.
101+
///
102+
/// The valid boolean representations are only `"true"`, `"false"`, `"1"`, and `"0"`.
103+
///
104+
/// # Examples
105+
///
106+
/// ```
107+
/// # use pretty_assertions::assert_eq;
108+
/// use quick_xml::events::attributes::Attribute;
109+
///
110+
/// let attr = Attribute::from(("attr", "false"));
111+
/// assert_eq!(attr.as_bool(), Some(false));
112+
///
113+
/// let attr = Attribute::from(("attr", "0"));
114+
/// assert_eq!(attr.as_bool(), Some(false));
115+
///
116+
/// let attr = Attribute::from(("attr", "true"));
117+
/// assert_eq!(attr.as_bool(), Some(true));
118+
///
119+
/// let attr = Attribute::from(("attr", "1"));
120+
/// assert_eq!(attr.as_bool(), Some(true));
121+
///
122+
/// let attr = Attribute::from(("attr", "bot bool"));
123+
/// assert_eq!(attr.as_bool(), None);
124+
/// ```
125+
///
126+
/// [represents]: https://www.w3.org/TR/xmlschema11-2/#boolean
127+
#[inline]
128+
pub fn as_bool(&self) -> Option<bool> {
129+
match self.value.as_ref() {
130+
b"1" | b"true" => Some(true),
131+
b"0" | b"false" => Some(false),
132+
_ => None,
133+
}
134+
}
99135
}
100136

101137
impl<'a> Debug for Attribute<'a> {

0 commit comments

Comments
 (0)