Skip to main content

Float

Struct Float 

Source
pub struct Float(/* private fields */);
Expand description

A floating-point value stored in its shortest CBOR encoding form.

Internally the raw bits are stored as f16, f32, or f64: whichever is the shortest form that preserves the value exactly (including NaN payloads and the sign of zero). CBOR::Core’s deterministic encoding rules require this “shortest form” selection, so a Float mirrors the bytes that will be written on the wire.

Two Float values are equal iff they encode to the same CBOR bytes. This differs from IEEE 754 equality in two ways:

  • Float(+0.0) != Float(-0.0) because they encode to different CBOR bytes.
  • Two NaNs compare equal if and only if they have identical payloads and sign, since that determines the encoding.

§Construction

§Examples

use cbor_core::Float;

// Shortest-form storage: 1.0 fits in f16.
assert_eq!(Float::new(1.0_f64).data_type(), cbor_core::DataType::Float16);

// Non-finite round-trip via payload.
let nan = Float::with_payload(1);
assert!(nan.to_f64().is_nan());
assert_eq!(nan.to_payload(), Ok(1));

Implementations§

Source§

impl Float

Source

pub const fn to_f16(self) -> Result<f16>

Available on crate feature half only.

Convert to half::f16.

Returns Err(Precision) for f32 or f64-width values.

Source§

impl Float

Source

pub fn new(value: impl Into<Self>) -> Self

Create a floating-point value in shortest CBOR form.

Equivalent to Float::from(value). The constructor chooses the narrowest CBOR::Core deterministic encoding width that represents value exactly.

Accepted input types: f32, f64, u8, u16, u32, i8, i16, i32, bool (false becomes 0.0, true becomes 1.0).

64-bit integers are intentionally rejected because they are not losslessly representable as f64 in general.

§Examples
use cbor_core::{DataType, Float};

assert_eq!(Float::new(0.0_f64).data_type(), DataType::Float16);
assert_eq!(Float::new(true).to_f64(), 1.0);
Source

pub const fn with_payload(payload: u64) -> Self

Create a non-finite floating-point value from a payload.

The payload is a 53-bit integer, laid out as described in section 2.3.4.2 of draft-rundgren-cbor-core-25. Bit 52 becomes the sign bit of the resulting float, while bits 51-0 form the significand in reversed order.

Bit reversal keeps a given bit position invariant across the f16, f32, and f64 encodings: bit 0 of the payload is always the most-significant significand bit. The result is stored in the shortest CBOR form that preserves the payload.

PayloadCBOR encodingDiagnostic notation
0[0xf9, 0x7c 0x00]Infinity
0x01[0xf9, 0x7e 0x00]NaN
0x10_0000_0000_0000[0xf9, 0xfc 0x00]-Infinity

The maximum allowed payload is 0x1f_ffff_ffff_ffff (53 bits).

§Panics

Panics if payload exceeds the 53-bit maximum.

§Examples
use cbor_core::Float;

assert!(Float::with_payload(0).to_f64().is_infinite());
assert!(Float::with_payload(1).to_f64().is_nan());
assert_eq!(Float::with_payload(2).to_payload(), Ok(2));
Source

pub const fn from_f64(value: f64) -> Self

Create a Float from an f64, usable in const context.

const counterpart of Float::from(value) / Float::new. The value is reduced to the shortest CBOR form (f16, f32, or f64) that preserves it bit-exactly, including NaN payloads and the sign of zero.

use cbor_core::Float;

const F: Float = Float::from_f64(1.0);
assert_eq!(F.to_f64(), 1.0);
Source

pub const fn from_f32(value: f32) -> Self

Create a Float from an f32, usable in const context.

const counterpart of Float::from(value) / Float::new for f32 inputs. NaN payloads are widened without hardware canonicalization; the result is then stored in the shortest CBOR form that preserves the value.

use cbor_core::Float;

const F: Float = Float::from_f32(1.0);
assert_eq!(F.to_f32(), Ok(1.0));
Source

pub const fn data_type(&self) -> DataType

Return the DataType indicating the storage width (f16, f32, or f64).

use cbor_core::{Float, DataType};

assert_eq!(Float::new(1.5).data_type(), DataType::Float16);
assert_eq!(Float::new(1.00048828125).data_type(), DataType::Float32);
assert_eq!(Float::new(1.1).data_type(), DataType::Float64);
Source

pub const fn to_f64(self) -> f64

Widen to f64, preserving the exact bit pattern.

Finite values widen losslessly. For NaN values the payload bits are copied verbatim (without hardware canonicalization).

Source

pub const fn to_f32(self) -> Result<f32>

Narrow to f32 when the value fits exactly.

Returns Err(Error::Precision) when the underlying storage is f64, since f64 values cannot in general be narrowed without loss. f16 and f32 values convert losslessly; NaN payloads are preserved.

Source

pub const fn to_payload(self) -> Result<u64>

Retrieve the 53-bit payload of a non-finite value.

Returns Err(Error::InvalidValue) for finite floats. For non-finite values, the payload is reconstructed from the underlying f16/f32/f64 bits by the inverse of Float::with_payload.

use cbor_core::{Float, Error};

for payload in [0, 1, 2, 0x400, 0x1fffffffffffff] {
    assert_eq!(Float::with_payload(payload).to_payload(), Ok(payload));
}

assert_eq!(Float::new(1.0).to_payload(), Err(Error::InvalidValue));
Source

pub const fn is_finite(self) -> bool

Return true if this is a finite floating-point value.

A value is non-finite when its exponent field is all ones (that is, Infinity, -Infinity, or any NaN).

Non-finite values have a payload.

Trait Implementations§

Source§

impl Clone for Float

Source§

fn clone(&self) -> Float

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Float

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<Float> for Value

Source§

fn from(value: Float) -> Self

Converts to this type from the input type.
Source§

impl<'a> From<Float> for ValueKey<'a>

Source§

fn from(value: Float) -> ValueKey<'a>

Converts to this type from the input type.
Source§

impl From<bool> for Float

Source§

fn from(value: bool) -> Self

Converts to this type from the input type.
Source§

impl From<f16> for Float

Available on crate feature half only.
Source§

fn from(value: f16) -> Self

Converts to this type from the input type.
Source§

impl From<f32> for Float

Source§

fn from(value: f32) -> Self

Converts to this type from the input type.
Source§

impl From<f64> for Float

Source§

fn from(value: f64) -> Self

Converts to this type from the input type.
Source§

impl From<i16> for Float

Source§

fn from(value: i16) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for Float

Source§

fn from(value: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i8> for Float

Source§

fn from(value: i8) -> Self

Converts to this type from the input type.
Source§

impl From<u16> for Float

Source§

fn from(value: u16) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Float

Source§

fn from(value: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for Float

Source§

fn from(value: u8) -> Self

Converts to this type from the input type.
Source§

impl Hash for Float

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Float

Source§

fn cmp(&self, other: &Float) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Float

Source§

fn eq(&self, other: &Float) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Float

Source§

fn partial_cmp(&self, other: &Float) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl TryFrom<&Value> for Float

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: &Value) -> Result<Self>

Performs the conversion.
Source§

impl TryFrom<Value> for Float

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(value: Value) -> Result<Self>

Performs the conversion.
Source§

impl Copy for Float

Source§

impl Eq for Float

Source§

impl StructuralPartialEq for Float

Auto Trait Implementations§

§

impl Freeze for Float

§

impl RefUnwindSafe for Float

§

impl Send for Float

§

impl Sync for Float

§

impl Unpin for Float

§

impl UnsafeUnpin for Float

§

impl UnwindSafe for Float

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Az for T

Source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

Source§

fn cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> CheckedAs for T

Source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

Source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> OverflowingAs for T

Source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

Source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
Source§

impl<T> SaturatingAs for T

Source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

Source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> StrictAs for T

Source§

fn strict_as<Dst>(self) -> Dst
where T: StrictCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> StrictCastFrom<Src> for Dst
where Src: StrictCast<Dst>,

Source§

fn strict_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> UnwrappedAs for T

Source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

Source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
Source§

impl<T> WrappingAs for T

Source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
Source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

Source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.