use std::{cmp::Ordering, fmt};
use crate::types::{Marshal, SqlType, StatBuffer, Unmarshal};
#[derive(Copy, Clone, Default)]
#[repr(transparent)]
pub struct BFloat16([u8; 2]);
impl BFloat16 {
pub const fn from_bits(bits: u16) -> Self {
BFloat16(bits.to_le_bytes())
}
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;
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 {
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)
}
}
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}");
}
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);
}
}