Skip to main content

codec_cbor/general/
float.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use half::f16;
6use zeroize::{Zeroize, ZeroizeOnDrop};
7
8use super::error::{error, CborError, ErrorReason};
9use super::profile::FloatPolicy;
10
11/// Schema-generated IEEE representation width.
12pub use codec_proto::generated::proto::reallyme::codec::v1::CodecGeneralCborFloatWidth as FloatWidth;
13
14/// Owned floating-point bits, zeroized on drop without content-printing traits.
15///
16/// NaN payloads and signs are retained. Shortening a NaN preserves its
17/// significand by right-side zero extension, rather than canonicalizing it.
18pub struct Float {
19    bits: FloatBits,
20}
21
22enum FloatBits {
23    Binary16(u16),
24    Binary32(u32),
25    Binary64(u64),
26}
27
28impl Float {
29    /// Preserve all binary16 bits.
30    #[must_use]
31    pub const fn binary16(bits: u16) -> Self {
32        Self {
33            bits: FloatBits::Binary16(bits),
34        }
35    }
36    /// Preserve all binary32 bits.
37    #[must_use]
38    pub const fn binary32(bits: u32) -> Self {
39        Self {
40            bits: FloatBits::Binary32(bits),
41        }
42    }
43    /// Preserve all binary64 bits.
44    #[must_use]
45    pub const fn binary64(bits: u64) -> Self {
46        Self {
47            bits: FloatBits::Binary64(bits),
48        }
49    }
50    /// Preserve a Rust binary64 value's bits.
51    #[must_use]
52    pub fn from_f64(value: f64) -> Self {
53        Self::binary64(value.to_bits())
54    }
55    /// Inspect representation width.
56    #[must_use]
57    pub const fn width(&self) -> FloatWidth {
58        match self.bits {
59            FloatBits::Binary16(_) => FloatWidth::Binary16,
60            FloatBits::Binary32(_) => FloatWidth::Binary32,
61            FloatBits::Binary64(_) => FloatWidth::Binary64,
62        }
63    }
64    /// Explicitly extract the original bits; callers own any resulting copy.
65    #[must_use]
66    pub fn bits(&self) -> u64 {
67        match self.bits {
68            FloatBits::Binary16(value) => u64::from(value),
69            FloatBits::Binary32(value) => u64::from(value),
70            FloatBits::Binary64(value) => value,
71        }
72    }
73
74    fn layout(&self) -> (u32, u64, u32) {
75        match self.bits {
76            FloatBits::Binary16(_) => (10, 0x1f, 15),
77            FloatBits::Binary32(_) => (23, 0xff, 31),
78            FloatBits::Binary64(_) => (52, 0x7ff, 63),
79        }
80    }
81
82    fn fraction(&self) -> u64 {
83        let (fraction_bits, _, _) = self.layout();
84        self.bits() & ((1_u64 << fraction_bits) - 1)
85    }
86
87    /// Inspect whether the represented value is a NaN.
88    #[must_use]
89    pub fn is_nan(&self) -> bool {
90        !self.is_finite() && self.fraction() != 0
91    }
92    /// Inspect whether the represented value is finite.
93    #[must_use]
94    pub fn is_finite(&self) -> bool {
95        let (fraction_bits, exponent_mask, _) = self.layout();
96        (self.bits() >> fraction_bits) & exponent_mask != exponent_mask
97    }
98
99    /// Convert without losing a NaN's sign or significand.
100    #[must_use]
101    pub fn to_f64(&self) -> f64 {
102        if self.is_nan() {
103            let (fraction_bits, _, sign_bit) = self.layout();
104            let sign = (self.bits() >> sign_bit) << 63;
105            return f64::from_bits(
106                sign | 0x7ff0_0000_0000_0000 | (self.fraction() << (52 - fraction_bits)),
107            );
108        }
109        match self.bits {
110            // The portable conversion avoids host FP16 assembly and gives
111            // native, interpreted, and WASM lanes the same bit-level path.
112            FloatBits::Binary16(value) => f16::from_bits(value).to_f64_const(),
113            FloatBits::Binary32(value) => f64::from(f32::from_bits(value)),
114            FloatBits::Binary64(value) => f64::from_bits(value),
115        }
116    }
117
118    pub(super) fn check(&self, policy: FloatPolicy) -> Result<(), CborError> {
119        match policy {
120            FloatPolicy::Reject => Err(error(ErrorReason::FloatNotAllowed)),
121            FloatPolicy::FiniteOnly if !self.is_finite() => Err(error(ErrorReason::NonFiniteFloat)),
122            _ => Ok(()),
123        }
124    }
125
126    pub(super) fn shortest(&self) -> FloatWidth {
127        if self.is_nan() {
128            let (fraction_bits, _, _) = self.layout();
129            let normalized = self.fraction() << (64 - fraction_bits);
130            if normalized & ((1_u64 << 54) - 1) == 0 {
131                return FloatWidth::Binary16;
132            }
133            if normalized & ((1_u64 << 41) - 1) == 0 {
134                return FloatWidth::Binary32;
135            }
136            return FloatWidth::Binary64;
137        }
138        let value = self.to_f64();
139        if f16::from_f64_const(value).to_f64_const().to_bits() == value.to_bits() {
140            return FloatWidth::Binary16;
141        }
142        // This narrowing is intentional; the round trip proves exactness and
143        // includes the sign of zero. It is never used for lengths or offsets.
144        if f64::from(value as f32).to_bits() == value.to_bits() {
145            return FloatWidth::Binary32;
146        }
147        FloatWidth::Binary64
148    }
149
150    pub(super) fn at_width(&self, width: FloatWidth) -> Result<u64, CborError> {
151        if width == self.width() {
152            return Ok(self.bits());
153        }
154        if self.is_nan() {
155            let (source_bits, _, sign_bit) = self.layout();
156            let (target_bits, exponent, target_sign) = match width {
157                FloatWidth::Binary16 => (10, 0x1f_u64, 15),
158                FloatWidth::Binary32 => (23, 0xff, 31),
159                FloatWidth::Binary64 => (52, 0x7ff, 63),
160                _ => return Err(error(ErrorReason::UnsupportedPolicy)),
161            };
162            let normalized = self.fraction() << (64 - source_bits);
163            let fraction = normalized >> (64 - target_bits);
164            if fraction == 0 || fraction << (64 - target_bits) != normalized {
165                return Err(error(ErrorReason::NonPreferredFloat));
166            }
167            return Ok(((self.bits() >> sign_bit) << target_sign)
168                | (exponent << target_bits)
169                | fraction);
170        }
171        let value = self.to_f64();
172        match width {
173            FloatWidth::Binary16 => Ok(u64::from(f16::from_f64_const(value).to_bits())),
174            FloatWidth::Binary32 => Ok(u64::from((value as f32).to_bits())),
175            FloatWidth::Binary64 => Ok(value.to_bits()),
176            _ => Err(error(ErrorReason::UnsupportedPolicy)),
177        }
178    }
179
180    pub(super) fn equivalent(&self, other: &Self) -> bool {
181        if self.is_nan() || other.is_nan() {
182            if !self.is_nan() || !other.is_nan() {
183                return false;
184            }
185            let (left, _, _) = self.layout();
186            let (right, _, _) = other.layout();
187            return self.fraction() << (64 - left) == other.fraction() << (64 - right);
188        }
189        self.to_f64() == other.to_f64()
190    }
191
192    /// Total-order key whose equality is exactly [`Self::equivalent`].
193    ///
194    /// NaNs key by their right-zero-extended significand, ignoring sign and
195    /// width. Other values key by their exactly widened binary64 bits, with
196    /// both zeros sharing one key because `-0.0 == 0.0`.
197    pub(super) fn equivalence_key(&self) -> (u8, u64) {
198        if self.is_nan() {
199            let (fraction_bits, _, _) = self.layout();
200            return (1, self.fraction() << (64 - fraction_bits));
201        }
202        let value = self.to_f64();
203        if value == 0.0 {
204            (0, 0)
205        } else {
206            (0, value.to_bits())
207        }
208    }
209}
210
211impl Zeroize for Float {
212    fn zeroize(&mut self) {
213        match &mut self.bits {
214            FloatBits::Binary16(value) => value.zeroize(),
215            FloatBits::Binary32(value) => value.zeroize(),
216            FloatBits::Binary64(value) => value.zeroize(),
217        }
218    }
219}
220impl Drop for Float {
221    fn drop(&mut self) {
222        self.zeroize();
223    }
224}
225impl ZeroizeOnDrop for Float {}