Skip to main content

ical/value/
float.rs

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