clickhouse-native-rs 2.24.1

Asynchronous ClickHouse client for Rust over the native TCP protocol, a maintained continuation of the clickhouse-rs crate.
Documentation
/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! `Decimal256`: decimals of 39 to 76 digits, `Decimal(P, S)` with `P` from
//! 39 to 76 and `Decimal256(S)` columns.
//!
//! [`Decimal`] keeps up to 38 digits in 16 bytes; a 32-byte value in it would
//! make every `ValueRef` larger, so the wider decimals have a type of their
//! own. Its value is an [`Int256`], the layout ClickHouse stores.

use std::{
    cmp::Ordering,
    error, fmt,
    hash::{Hash, Hasher},
    str::FromStr,
};

use crate::types::{Decimal, Int256, UInt256};

/// The largest precision of a Decimal256.
pub(crate) const MAX_PRECISION: u8 = 76;

/// A decimal of up to 76 digits: `value / 10^scale`.
///
/// A column built from `Vec<Decimal256>` takes the scale of its values, which
/// have to share it: values of different scales panic, as for [`Decimal`].
///
/// ```rust
/// # use clickhouse_native_rs::types::Decimal256;
/// let d: Decimal256 = "-123456789012345678901234567890123456789.0123456789".parse().unwrap();
/// assert_eq!(d.scale(), 10);
/// assert_eq!(d.to_string(), "-123456789012345678901234567890123456789.0123456789");
/// ```
#[derive(Clone, Copy)]
pub struct Decimal256 {
    value: Int256,
    precision: u8,
    scale: u8,
}

/// Why text is not a [`Decimal256`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ParseDecimal256Error;

impl fmt::Display for ParseDecimal256Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("not a decimal of at most 76 digits")
    }
}

impl error::Error for ParseDecimal256Error {}

impl Decimal256 {
    /// The decimal `value / 10^scale` of precision 76.
    ///
    /// # Panics
    ///
    /// When `scale` is greater than 76 or `value` has more than 76 digits.
    pub fn new(value: Int256, scale: u8) -> Decimal256 {
        if scale > MAX_PRECISION {
            panic!("scale can't be greater than {MAX_PRECISION}");
        }
        let decimal = Decimal256::from_raw(value, MAX_PRECISION, scale);
        if !decimal.fits(MAX_PRECISION) {
            panic!("{value} has more than {MAX_PRECISION} digits");
        }
        decimal
    }

    pub(crate) fn from_raw(value: Int256, precision: u8, scale: u8) -> Decimal256 {
        Decimal256 {
            value,
            precision,
            scale,
        }
    }

    /// The internal representation, `value * 10^scale`.
    pub fn internal(&self) -> Int256 {
        self.value
    }

    pub(crate) fn internal_ref(&self) -> &Int256 {
        &self.value
    }

    /// How many decimal digits the fraction has.
    pub fn scale(&self) -> usize {
        usize::from(self.scale)
    }

    /// How many digits the decimal type holds.
    pub fn precision(&self) -> usize {
        usize::from(self.precision)
    }

    /// Whether the value has at most `precision` digits.
    pub(crate) fn fits(&self, precision: u8) -> bool {
        precision <= MAX_PRECISION
            && UInt256::pow10(u32::from(precision))
                .is_some_and(|limit| self.value.unsigned_abs() < limit)
    }

    /// The internal value at `scale`, or `None` when it overflows 256 bits.
    /// Extra fraction digits are cut off, as for [`Decimal`].
    pub(crate) fn rescaled(&self, scale: u8) -> Option<Int256> {
        let negative = self.value.is_negative();
        let mut magnitude = self.value.unsigned_abs();
        match scale.cmp(&self.scale) {
            Ordering::Equal => return Some(self.value),
            Ordering::Greater => {
                for _ in self.scale..scale {
                    magnitude = magnitude.checked_mul_small(10)?;
                }
            }
            Ordering::Less => {
                for _ in scale..self.scale {
                    magnitude = magnitude.div_rem_small(10).0;
                }
            }
        }
        Int256::from_sign_magnitude(negative, magnitude)
    }

    /// The sign, digits and scale without trailing fraction zeros, which
    /// equal decimals share whatever their scale.
    fn normalized(&self) -> (bool, UInt256, u8) {
        let mut magnitude = self.value.unsigned_abs();
        let mut scale = self.scale;
        while scale > 0 {
            let (quotient, rem) = magnitude.div_rem_small(10);
            if rem != 0 {
                break;
            }
            magnitude = quotient;
            scale -= 1;
        }
        (self.value.is_negative(), magnitude, scale)
    }
}

impl From<Decimal> for Decimal256 {
    fn from(decimal: Decimal) -> Self {
        // Precision 76, so that a row of it makes a Decimal256 column.
        Decimal256::from_raw(
            Int256::from(decimal.internal128()),
            MAX_PRECISION,
            decimal.scale,
        )
    }
}

impl PartialEq for Decimal256 {
    fn eq(&self, other: &Self) -> bool {
        self.normalized() == other.normalized()
    }
}

impl Eq for Decimal256 {}

impl Hash for Decimal256 {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.normalized().hash(state);
    }
}

impl fmt::Display for Decimal256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut digits = self.value.unsigned_abs().to_string();
        let scale = self.scale();
        while digits.len() <= scale {
            digits.insert(0, '0');
        }
        if scale > 0 {
            digits.insert(digits.len() - scale, '.');
        }
        if self.value.is_negative() {
            digits.insert(0, '-');
        }
        f.write_str(&digits)
    }
}

impl fmt::Debug for Decimal256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl FromStr for Decimal256 {
    type Err = ParseDecimal256Error;

    /// `-12.345` and the like: an optional sign, digits and an optional
    /// fraction; the scale is the number of fraction digits.
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let (negative, body) = match text.as_bytes().first() {
            Some(b'-') => (true, &text[1..]),
            Some(b'+') => (false, &text[1..]),
            _ => (false, text),
        };
        let (whole, fraction) = body.split_once('.').unwrap_or((body, ""));
        let digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
        if whole.is_empty() && fraction.is_empty() || !digits(whole) || !digits(fraction) {
            return Err(ParseDecimal256Error);
        }
        let scale = u8::try_from(fraction.len()).map_err(|_| ParseDecimal256Error)?;
        let magnitude: UInt256 = format!("{whole}{fraction}")
            .parse()
            .map_err(|_| ParseDecimal256Error)?;
        let value = Int256::from_sign_magnitude(negative, magnitude).ok_or(ParseDecimal256Error)?;
        let decimal = Decimal256::from_raw(value, MAX_PRECISION, scale);
        if scale > MAX_PRECISION || !decimal.fits(MAX_PRECISION) {
            return Err(ParseDecimal256Error);
        }
        Ok(decimal)
    }
}

impl From<Decimal256> for f64 {
    /// The nearest `f64`: parsing the decimal text rounds once.
    fn from(decimal: Decimal256) -> Self {
        decimal.to_string().parse().unwrap_or(f64::NAN)
    }
}

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

    #[test]
    fn test_text() {
        let largest = "9".repeat(76);
        let d: Decimal256 = largest.parse().unwrap();
        assert_eq!(d.to_string(), largest);
        assert!("1".repeat(77).parse::<Decimal256>().is_err());
        for text in ["-0.05", "0.000", "7", "123.4500", "-1", "+5.5"] {
            let d: Decimal256 = text.parse().unwrap();
            assert_eq!(d.to_string(), text.trim_start_matches('+'), "{text}");
        }
        for text in ["", ".", "1.2.3", "--1", "1a", "-"] {
            assert!(text.parse::<Decimal256>().is_err(), "{text}");
        }
        assert_eq!(".5".parse::<Decimal256>().unwrap().to_string(), "0.5");
    }

    #[test]
    fn test_equality_and_rescaling() {
        let a: Decimal256 = "2.0".parse().unwrap();
        let b: Decimal256 = "2.000".parse().unwrap();
        assert_eq!(a, b);
        assert_ne!(a, "2.01".parse::<Decimal256>().unwrap());
        assert_eq!(a.rescaled(3), Some(b.internal()));
        let cut: Decimal256 = "-1.239".parse().unwrap();
        assert_eq!(cut.rescaled(2), Some(Int256::from(-123)));
        // 76 nines with 10 more fraction digits are about 10^86, past 2^255.
        let largest: Decimal256 = "9".repeat(76).parse().unwrap();
        assert_eq!(largest.rescaled(10), None);
        assert!(largest.fits(76) && !largest.fits(75));
        let from_decimal = Decimal256::from(Decimal::new(12345, 2));
        assert_eq!(from_decimal.precision(), 76);
        assert_eq!(from_decimal, "123.45".parse().unwrap());
        assert_eq!(f64::from(from_decimal), 123.45);
        let exact: Decimal256 = "900719925474099.5".parse().unwrap();
        assert_eq!(f64::from(exact), 900_719_925_474_099.5);
        // One rounding: (2^53 + 1) * 2^64 + 1 is just above a midpoint.
        let wide: Decimal256 = "166153499473114502559719956244594689".parse().unwrap();
        assert_eq!(f64::from(wide), 1.6615349947311452e35);
        // Metadata past 76 digits does not fit, instead of panicking.
        assert!(!wide.fits(78));
    }
}