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
 */

//! `BFloat16`: the upper 16 bits of a `Float32` (sign, 8 exponent bits and 7
//! mantissa bits), as ClickHouse keeps it.

use std::{cmp::Ordering, fmt};

use crate::types::{Marshal, SqlType, StatBuffer, Unmarshal};

/// A ClickHouse `BFloat16`.
///
/// It converts from `f32` as ClickHouse does, by dropping the lower 16 bits,
/// and to `f32` exactly.
///
/// ```rust
/// # use clickhouse_native_rs::types::BFloat16;
/// let x = BFloat16::from(1.5_f32);
/// assert_eq!(f32::from(x), 1.5);
/// assert_eq!(f32::from(BFloat16::from(1.0039_f32)), 1.0);
/// ```
///
/// It keeps its two little-endian bytes, the layout of the Native format, as
/// columns are read and written as raw bytes.
#[derive(Copy, Clone, Default)]
#[repr(transparent)]
pub struct BFloat16([u8; 2]);

impl BFloat16 {
    /// The value of its 16 bits.
    pub const fn from_bits(bits: u16) -> Self {
        BFloat16(bits.to_le_bytes())
    }

    /// The 16 bits of the value.
    pub const fn to_bits(self) -> u16 {
        u16::from_le_bytes(self.0)
    }
}

impl From<f32> for BFloat16 {
    fn from(value: f32) -> Self {
        let bits = (value.to_bits() >> 16) as u16;
        // A NaN whose payload is all in the dropped bits stays a NaN.
        if value.is_nan() && bits & 0x7f == 0 {
            return BFloat16::from_bits(bits | 0x40);
        }
        BFloat16::from_bits(bits)
    }
}

impl From<BFloat16> for f32 {
    fn from(value: BFloat16) -> Self {
        f32::from_bits(u32::from(value.to_bits()) << 16)
    }
}

impl PartialEq for BFloat16 {
    /// As `f32`s compare: `0.0 == -0.0`, NaN equals nothing.
    fn eq(&self, other: &Self) -> bool {
        f32::from(*self) == f32::from(*other)
    }
}

impl PartialOrd for BFloat16 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        f32::from(*self).partial_cmp(&f32::from(*other))
    }
}

impl fmt::Display for BFloat16 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&f32::from(*self), f)
    }
}

impl fmt::Debug for BFloat16 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&f32::from(*self), f)
    }
}

// The column storage: the two bytes of a value are its Native format.
impl StatBuffer for BFloat16 {
    type Buffer = [u8; 2];

    fn buffer() -> Self::Buffer {
        [0; 2]
    }

    fn sql_type() -> SqlType {
        SqlType::BFloat16
    }
}

impl Marshal for BFloat16 {
    fn marshal(&self, scratch: &mut [u8]) {
        scratch.copy_from_slice(&self.0);
    }
}

impl Unmarshal<BFloat16> for BFloat16 {
    fn unmarshal(scratch: &[u8]) -> Self {
        BFloat16([scratch[0], scratch[1]])
    }
}

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

    #[test]
    fn test_conversions() {
        for x in [
            0.0_f32,
            -0.0,
            1.0,
            -2.5,
            65_280.0,
            f32::INFINITY,
            f32::MIN_POSITIVE,
        ] {
            assert_eq!(f32::from(BFloat16::from(x)).to_bits(), x.to_bits(), "{x}");
        }
        // The lower 16 bits are dropped, not rounded, as ClickHouse does.
        assert_eq!(f32::from(BFloat16::from(1.0039_f32)), 1.0);
        assert_eq!(f32::from(BFloat16::from(-3.99_f32)), -3.984_375);
        assert!(f32::from(BFloat16::from(f32::NAN)).is_nan());
        assert!(f32::from(BFloat16::from(f32::from_bits(0x7f80_0001))).is_nan());
        assert!(f32::from(BFloat16::from(f32::from_bits(0xff80_0001))).is_nan());
        assert_eq!(BFloat16::from(0.0_f32), BFloat16::from(-0.0_f32));
        assert_eq!(BFloat16::from(1.5_f32).to_string(), "1.5");
        assert_eq!(BFloat16::from_bits(0x3fc0).to_bits(), 0x3fc0);
    }
}