Skip to main content

ical/value/
integer.rs

1//! # Integer value
2//!
3//! The decoded integer value kind.
4//!
5//! Backs the integer-valued properties and parameters (RFC 5545 3.3.8): a
6//! signed decimal integer such as `1234` or `-9`. The value is kept as its
7//! raw text so the original lexical form round-trips; [`IcalInteger::get`]
8//! parses it into an [`i64`].
9
10use alloc::{borrow::Cow, string::String};
11
12/// A decoded integer value (signed), kept as its raw text.
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
14pub struct IcalInteger<'a>(pub Cow<'a, str>);
15
16impl IcalInteger<'_> {
17    /// Parse the raw text into an [`i64`]; `None` if it is not a valid integer.
18    pub fn get(&self) -> Option<i64> {
19        self.0.parse().ok()
20    }
21}
22
23impl<'a> From<&'a str> for IcalInteger<'a> {
24    fn from(value: &'a str) -> Self {
25        Self(Cow::Borrowed(value))
26    }
27}
28
29impl From<String> for IcalInteger<'_> {
30    fn from(value: String) -> Self {
31        Self(Cow::Owned(value))
32    }
33}
34
35impl<'a> From<Cow<'a, str>> for IcalInteger<'a> {
36    fn from(value: Cow<'a, str>) -> Self {
37        Self(value)
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use crate::value::integer::IcalInteger;
44
45    #[test]
46    fn get_parses_signed_integer() {
47        assert_eq!(IcalInteger::from("-9").get(), Some(-9));
48        assert_eq!(IcalInteger::from("abc").get(), None);
49    }
50}