goosedump 0.12.49

Browse, search, summarize, compact, and learn from coding-agent sessions
// SPDX-License-Identifier: LGPL-2.1-or-later
// Copyright (C) Jarkko Sakkinen 2026

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(transparent)]
pub struct Fp16(pub u16);

unsafe impl bytemuck::Pod for Fp16 {}
unsafe impl bytemuck::Zeroable for Fp16 {}

include!(concat!(env!("OUT_DIR"), "/generated_lut.rs"));

impl Fp16 {
    #[inline]
    pub fn to_f32(self) -> f32 {
        FP16_TO_F32_LUT[self.0 as usize]
    }

    #[inline]
    pub fn decode_le(bytes: &[u8]) -> Self {
        Self(u16::from_le_bytes([bytes[0], bytes[1]]))
    }
}

impl From<Fp16> for f32 {
    #[inline]
    fn from(val: Fp16) -> Self {
        val.to_f32()
    }
}

impl From<f32> for Fp16 {
    fn from(value: f32) -> Self {
        let bits = value.to_bits();
        let sign = u16::from_le_bytes([bits.to_le_bytes()[2], bits.to_le_bytes()[3]]) & 0x8000;
        let exponent = ((bits >> 23) & 0xff).cast_signed();
        let fraction = bits & 0x007f_ffff;
        if exponent == 0xff {
            return if fraction == 0 {
                Self(sign | 0x7c00)
            } else {
                let encoded = (fraction >> 13).to_le_bytes();
                Self(sign | 0x7e00 | (u16::from_le_bytes([encoded[0], encoded[1]]) & 0x01ff))
            };
        }
        let half_exponent = exponent - 112;
        if half_exponent >= 0x1f {
            return Self(sign | 0x7c00);
        }
        if half_exponent <= 0 {
            if half_exponent < -10 {
                return Self(sign);
            }
            let significand = fraction | 0x0080_0000;
            let shift = (14 - half_exponent).unsigned_abs();
            let mut rounded = significand >> shift;
            let remainder = significand & ((1_u32 << shift) - 1);
            let halfway = 1_u32 << (shift - 1);
            if remainder > halfway || (remainder == halfway && rounded & 1 != 0) {
                rounded += 1;
            }
            let encoded = rounded.to_le_bytes();
            return Self(sign | u16::from_le_bytes([encoded[0], encoded[1]]));
        }
        let mut rounded = fraction >> 13;
        let remainder = fraction & 0x1fff;
        if remainder > 0x1000 || (remainder == 0x1000 && rounded & 1 != 0) {
            rounded += 1;
        }
        let exponent_bytes = half_exponent.to_le_bytes();
        let mut encoded_exponent = u16::from_le_bytes([exponent_bytes[0], exponent_bytes[1]]);
        if rounded == 0x400 {
            rounded = 0;
            encoded_exponent += 1;
            if encoded_exponent == 0x1f {
                return Self(sign | 0x7c00);
            }
        }
        let encoded = rounded.to_le_bytes();
        Self(sign | (encoded_exponent << 10) | u16::from_le_bytes([encoded[0], encoded[1]]))
    }
}