thaler 0.1.0

The Thaler API: financial data from SEC filings, with the source filing for every value.
Documentation
//! A figure as the API sends it: a decimal string, exact to the digit as
//! filed.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize};

/// A figure as a decimal string: `416161000000`, `39.75`, `-58000000`,
/// `0.3018`. The API never sends a number, because a double loses digits
/// past the fifteenth; this keeps the digits and lets you parse them into
/// the arithmetic type you use. With the `rust_decimal` feature,
/// `Decimal::to_decimal` gives the `rust_decimal` crate's type.
#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct Decimal(String);

/// Why a string is not a decimal.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("not a decimal string: {0:?}")]
pub struct NotADecimal(pub String);

fn is_decimal(text: &str) -> bool {
    let digits = text.strip_prefix('-').unwrap_or(text);
    let (whole, fraction) = match digits.split_once('.') {
        Some((whole, fraction)) => (whole, Some(fraction)),
        None => (digits, None),
    };
    let all_digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
    all_digits(whole) && fraction.is_none_or(all_digits)
}

impl Decimal {
    /// The digits as the API sent them.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The figure as an `f64`, rounded past the fifteenth digit.
    pub fn to_f64(&self) -> f64 {
        self.0.parse().unwrap_or(f64::NAN)
    }

    /// The figure as an `i64`, when it is written without a fraction and
    /// fits; `"1.0"` is `None`.
    pub fn to_i64(&self) -> Option<i64> {
        self.0.parse().ok()
    }

    /// Whether the figure is below zero.
    pub fn is_negative(&self) -> bool {
        self.0.starts_with('-') && self.0.bytes().any(|b| (b'1'..=b'9').contains(&b))
    }

    /// The figure in the `rust_decimal` crate's type.
    #[cfg(feature = "rust_decimal")]
    pub fn to_decimal(&self) -> Result<rust_decimal::Decimal, rust_decimal::Error> {
        self.0.parse()
    }
}

impl fmt::Debug for Decimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Decimal({})", self.0)
    }
}

impl fmt::Display for Decimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for Decimal {
    type Err = NotADecimal;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        if is_decimal(text) {
            Ok(Decimal(text.to_string()))
        } else {
            Err(NotADecimal(text.to_string()))
        }
    }
}

impl TryFrom<String> for Decimal {
    type Error = NotADecimal;

    fn try_from(text: String) -> Result<Self, Self::Error> {
        if is_decimal(&text) {
            Ok(Decimal(text))
        } else {
            Err(NotADecimal(text))
        }
    }
}

impl From<i64> for Decimal {
    fn from(value: i64) -> Self {
        Decimal(value.to_string())
    }
}

impl AsRef<str> for Decimal {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl<'de> Deserialize<'de> for Decimal {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let text = String::deserialize(deserializer)?;
        Decimal::try_from(text).map_err(serde::de::Error::custom)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_the_wire_and_refuses_a_float() {
        for text in ["416161000000", "-58000000", "39.75", "0.3018", "1.000", "0"] {
            let value: Decimal = serde_json::from_str(&format!("\"{text}\"")).unwrap();
            assert_eq!(value.as_str(), text);
            assert_eq!(value.to_string(), text);
        }
        for text in ["\"1e5\"", "\"\"", "\"1.\"", "\".5\"", "42", "null"] {
            assert!(serde_json::from_str::<Decimal>(text).is_err(), "{text}");
        }
        assert_eq!("39.75".parse::<Decimal>().unwrap().to_f64(), 39.75);
        assert_eq!(
            "-58000000".parse::<Decimal>().unwrap().to_i64(),
            Some(-58_000_000)
        );
        assert!("-0.5".parse::<Decimal>().unwrap().is_negative());
        assert!(!"-0".parse::<Decimal>().unwrap().is_negative());
        assert_eq!(format!("{:?}", Decimal::from(7)), "Decimal(7)");
    }

    #[cfg(feature = "rust_decimal")]
    #[test]
    fn converts_to_rust_decimal() {
        let value: Decimal = "0.3018".parse().unwrap();
        assert_eq!(value.to_decimal().unwrap().to_string(), "0.3018");
    }
}