torvyon-core 0.1.2

Keys, addresses, post-quantum signing and transaction building for the Torvyon blockchain
Documentation
use std::{fmt, str::FromStr};

use crate::{Error, Result};

/// Nibbles in one Byte (the chain's smallest unit is the nibble).
pub const NIBBLES_PER_BYTE: u64 = 100_000_000;
const DECIMALS: usize = 8;

/// An exact amount in nibbles. Never uses floating point.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Amount(u64);

impl Amount {
    /// Zero.
    pub const ZERO: Self = Self(0);

    /// From nibbles.
    pub const fn from_nibbles(nibbles: u64) -> Self {
        Self(nibbles)
    }

    /// In nibbles.
    pub const fn nibbles(self) -> u64 {
        self.0
    }

    /// Parses a Byte amount such as `"1"`, `"0.5"` or `"12.00000001"`.
    pub fn from_byte_str(s: &str) -> Result<Self> {
        let s = s.trim();
        let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
        let digits = |p: &str| p.bytes().all(|b| b.is_ascii_digit());
        if whole.is_empty() && frac.is_empty() || !digits(whole) || !digits(frac) || frac.len() > DECIMALS {
            return Err(Error::InvalidAmount);
        }
        let whole: u64 = if whole.is_empty() {
            0
        } else {
            whole.parse().map_err(|_| Error::InvalidAmount)?
        };
        let frac: u64 = format!("{frac:0<DECIMALS$}")
            .parse()
            .map_err(|_| Error::InvalidAmount)?;
        whole
            .checked_mul(NIBBLES_PER_BYTE)
            .and_then(|n| n.checked_add(frac))
            .map(Self)
            .ok_or(Error::AmountOverflow)
    }

    /// Checked addition.
    pub fn checked_add(self, other: Self) -> Result<Self> {
        self.0.checked_add(other.0).map(Self).ok_or(Error::AmountOverflow)
    }

    /// Checked subtraction.
    pub fn checked_sub(self, other: Self) -> Result<Self> {
        self.0.checked_sub(other.0).map(Self).ok_or(Error::AmountOverflow)
    }
}

/// Formats as Byte with trailing zeros removed: `150000000` → `"1.5"`.
impl fmt::Display for Amount {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let whole = self.0 / NIBBLES_PER_BYTE;
        let frac = self.0 % NIBBLES_PER_BYTE;
        if frac == 0 {
            return write!(f, "{whole}");
        }
        let frac = format!("{frac:0DECIMALS$}");
        write!(f, "{whole}.{}", frac.trim_end_matches('0'))
    }
}

impl FromStr for Amount {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Self::from_byte_str(s)
    }
}

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

    #[test]
    fn format_and_parse() {
        for (nibbles, text) in [
            (0, "0"),
            (1, "0.00000001"),
            (150_000_000, "1.5"),
            (100_000_000, "1"),
            (u64::MAX, "184467440737.09551615"),
        ] {
            assert_eq!(Amount::from_nibbles(nibbles).to_string(), text);
            assert_eq!(Amount::from_byte_str(text), Ok(Amount::from_nibbles(nibbles)));
        }
        assert_eq!(Amount::from_byte_str(".5"), Ok(Amount::from_nibbles(50_000_000)));
    }

    #[test]
    fn rejects_bad_input() {
        for bad in ["", ".", "1.123456789", "-1", "1e3", "1,5", "abc", " . "] {
            assert!(Amount::from_byte_str(bad).is_err(), "{bad}");
        }
        assert_eq!(
            Amount::from_byte_str("184467440737.09551616"),
            Err(Error::AmountOverflow)
        );
    }
}