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; use [`IcalFloat::get`] to
8//! parse it into an [`f64`]. Pure data, no escaping; the owning property's wire
9//! name lives on [`crate::prop::IcalProp::name`].
10
11use alloc::{borrow::Cow, string::String};
12
13/// A decoded float value, kept as its raw text.
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct IcalFloat<'a>(pub Cow<'a, str>);
16
17impl IcalFloat<'_> {
18    /// Parse the raw text into an [`f64`]; `None` if it is not a valid float.
19    pub fn get(&self) -> Option<f64> {
20        self.0.parse().ok()
21    }
22}
23
24impl<'a> From<&'a str> for IcalFloat<'a> {
25    fn from(value: &'a str) -> Self {
26        Self(Cow::Borrowed(value))
27    }
28}
29
30impl From<String> for IcalFloat<'_> {
31    fn from(value: String) -> Self {
32        Self(Cow::Owned(value))
33    }
34}
35
36impl<'a> From<Cow<'a, str>> for IcalFloat<'a> {
37    fn from(value: Cow<'a, str>) -> Self {
38        Self(value)
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use crate::value::float::IcalFloat;
45
46    #[test]
47    fn get_parses_signed_float() {
48        assert_eq!(IcalFloat::from("-12.5").get(), Some(-12.5));
49        assert_eq!(IcalFloat::from("abc").get(), None);
50    }
51}