• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! A crate that provides support for half-precision 16-bit floating point types.
2 //!
3 //! This crate provides the [`f16`] type, which is an implementation of the IEEE 754-2008 standard
4 //! [`binary16`] a.k.a `half` floating point type. This 16-bit floating point type is intended for
5 //! efficient storage where the full range and precision of a larger floating point value is not
6 //! required. This is especially useful for image storage formats.
7 //!
8 //! This crate also provides a [`bf16`] type, an alternative 16-bit floating point format. The
9 //! [`bfloat16`] format is a truncated IEEE 754 standard `binary32` float that preserves the
10 //! exponent to allow the same range as [`f32`] but with only 8 bits of precision (instead of 11
11 //! bits for [`f16`]). See the [`bf16`] type for details.
12 //!
13 //! Because [`f16`] and [`bf16`] are primarily for efficient storage, floating point operations such
14 //! as addition, multiplication, etc. are not implemented by hardware. While this crate does provide
15 //! the appropriate trait implementations for basic operations, they each convert the value to
16 //! [`f32`] before performing the operation and then back afterward. When performing complex
17 //! arithmetic, manually convert to and from [`f32`] before and after to reduce repeated conversions
18 //! for each operation.
19 //!
20 //! This crate also provides a [`slice`][mod@slice] module for zero-copy in-place conversions of
21 //! [`u16`] slices to both [`f16`] and [`bf16`], as well as efficient vectorized conversions of
22 //! larger buffers of floating point values to and from these half formats.
23 //!
24 //! The crate uses `#[no_std]` by default, so can be used in embedded environments without using the
25 //! Rust [`std`] library. A `std` feature to enable support for the standard library is available,
26 //! see the [Cargo Features](#cargo-features) section below.
27 //!
28 //! A [`prelude`] module is provided for easy importing of available utility traits.
29 //!
30 //! # Serialization
31 //!
32 //! When the `serde` feature is enabled, [`f16`] and [`bf16`] will be serialized as a newtype of
33 //! [`u16`] by default. In binary formats this is ideal, as it will generally use just two bytes for
34 //! storage. For string formats like JSON, however, this isn't as useful, and due to design
35 //! limitations of serde, it's not possible for the default `Serialize` implementation to support
36 //! different serialization for different formats.
37 //!
38 //! Instead, it's up to the containter type of the floats to control how it is serialized. This can
39 //! easily be controlled when using the derive macros using `#[serde(serialize_with="")]`
40 //! attributes. For both [`f16`] and [`bf16`] a `serialize_as_f32` and `serialize_as_string` are
41 //! provided for use with this attribute.
42 //!
43 //! Deserialization of both float types supports deserializing from the default serialization,
44 //! strings, and `f32`/`f64` values, so no additional work is required.
45 //!
46 //! # Cargo Features
47 //!
48 //! This crate supports a number of optional cargo features. None of these features are enabled by
49 //! default, even `std`.
50 //!
51 //! - **`use-intrinsics`** -- Use [`core::arch`] hardware intrinsics for `f16` and `bf16` conversions
52 //!   if available on the compiler target. This feature currently only works on nightly Rust
53 //!   until the corresponding intrinsics are stabilized.
54 //!
55 //!   When this feature is enabled and the hardware supports it, the functions and traits in the
56 //!   [`slice`][mod@slice] module will use vectorized SIMD intructions for increased efficiency.
57 //!
58 //!   By default, without this feature, conversions are done only in software, which will also be
59 //!   the fallback if the target does not have hardware support. Note that without the `std`
60 //!   feature enabled, no runtime CPU feature detection is used, so the hardware support is only
61 //!   compiled if the compiler target supports the CPU feature.
62 //!
63 //! - **`alloc`** -- Enable use of the [`alloc`] crate when not using the `std` library.
64 //!
65 //!   Among other functions, this enables the [`vec`] module, which contains zero-copy
66 //!   conversions for the [`Vec`] type. This allows fast conversion between raw `Vec<u16>` bits and
67 //!   `Vec<f16>` or `Vec<bf16>` arrays, and vice versa.
68 //!
69 //! - **`std`** -- Enable features that depend on the Rust [`std`] library. This also enables the
70 //!   `alloc` feature automatically.
71 //!
72 //!   Enabling the `std` feature also enables runtime CPU feature detection when the
73 //!   `use-intrsincis` feature is also enabled. Without this feature detection, intrinsics are only
74 //!   used when compiler target supports the target feature.
75 //!
76 //! - **`serde`** -- Adds support for the [`serde`] crate by implementing [`Serialize`] and
77 //!   [`Deserialize`] traits for both [`f16`] and [`bf16`].
78 //!
79 //! - **`num-traits`** -- Adds support for the [`num-traits`] crate by implementing [`ToPrimitive`],
80 //!   [`FromPrimitive`], [`AsPrimitive`], [`Num`], [`Float`], [`FloatCore`], and [`Bounded`] traits
81 //!   for both [`f16`] and [`bf16`].
82 //!
83 //! - **`bytemuck`** -- Adds support for the [`bytemuck`] crate by implementing [`Zeroable`] and
84 //!   [`Pod`] traits for both [`f16`] and [`bf16`].
85 //!
86 //! - **`zerocopy`** -- Adds support for the [`zerocopy`] crate by implementing [`AsBytes`] and
87 //!   [`FromBytes`] traits for both [`f16`] and [`bf16`].
88 //!
89 //! [`alloc`]: https://doc.rust-lang.org/alloc/
90 //! [`std`]: https://doc.rust-lang.org/std/
91 //! [`binary16`]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
92 //! [`bfloat16`]: https://en.wikipedia.org/wiki/Bfloat16_floating-point_format
93 //! [`serde`]: https://crates.io/crates/serde
94 //! [`bytemuck`]: https://crates.io/crates/bytemuck
95 //! [`num-traits`]: https://crates.io/crates/num-traits
96 //! [`zerocopy`]: https://crates.io/crates/zerocopy
97 #![cfg_attr(
98     feature = "alloc",
99     doc = "
100 [`vec`]: mod@vec"
101 )]
102 #![cfg_attr(
103     not(feature = "alloc"),
104     doc = "
105 [`vec`]: #
106 [`Vec`]: https://docs.rust-lang.org/stable/alloc/vec/struct.Vec.html"
107 )]
108 #![cfg_attr(
109     feature = "serde",
110     doc = "
111 [`Serialize`]: serde::Serialize
112 [`Deserialize`]: serde::Deserialize"
113 )]
114 #![cfg_attr(
115     not(feature = "serde"),
116     doc = "
117 [`Serialize`]: https://docs.rs/serde/*/serde/trait.Serialize.html
118 [`Deserialize`]: https://docs.rs/serde/*/serde/trait.Deserialize.html"
119 )]
120 #![cfg_attr(
121     feature = "num-traits",
122     doc = "
123 [`ToPrimitive`]: ::num_traits::ToPrimitive
124 [`FromPrimitive`]: ::num_traits::FromPrimitive
125 [`AsPrimitive`]: ::num_traits::AsPrimitive
126 [`Num`]: ::num_traits::Num
127 [`Float`]: ::num_traits::Float
128 [`FloatCore`]: ::num_traits::float::FloatCore
129 [`Bounded`]: ::num_traits::Bounded"
130 )]
131 #![cfg_attr(
132     not(feature = "num-traits"),
133     doc = "
134 [`ToPrimitive`]: https://docs.rs/num-traits/*/num_traits/cast/trait.ToPrimitive.html
135 [`FromPrimitive`]: https://docs.rs/num-traits/*/num_traits/cast/trait.FromPrimitive.html
136 [`AsPrimitive`]: https://docs.rs/num-traits/*/num_traits/cast/trait.AsPrimitive.html
137 [`Num`]: https://docs.rs/num-traits/*/num_traits/trait.Num.html
138 [`Float`]: https://docs.rs/num-traits/*/num_traits/float/trait.Float.html
139 [`FloatCore`]: https://docs.rs/num-traits/*/num_traits/float/trait.FloatCore.html
140 [`Bounded`]: https://docs.rs/num-traits/*/num_traits/bounds/trait.Bounded.html"
141 )]
142 #![cfg_attr(
143     feature = "bytemuck",
144     doc = "
145 [`Zeroable`]: bytemuck::Zeroable
146 [`Pod`]: bytemuck::Pod"
147 )]
148 #![cfg_attr(
149     not(feature = "bytemuck"),
150     doc = "
151 [`Zeroable`]: https://docs.rs/bytemuck/*/bytemuck/trait.Zeroable.html
152 [`Pod`]: https://docs.rs/bytemuck/*bytemuck/trait.Pod.html"
153 )]
154 #![cfg_attr(
155     feature = "zerocopy",
156     doc = "
157 [`AsBytes`]: zerocopy::AsBytes
158 [`FromBytes`]: zerocopy::FromBytes"
159 )]
160 #![cfg_attr(
161     not(feature = "zerocopy"),
162     doc = "
163 [`AsBytes`]: https://docs.rs/zerocopy/*/zerocopy/trait.AsBytes.html
164 [`FromBytes`]: https://docs.rs/zerocopy/*/zerocopy/trait.FromBytes.html"
165 )]
166 #![warn(
167     missing_docs,
168     missing_copy_implementations,
169     trivial_numeric_casts,
170     future_incompatible
171 )]
172 #![cfg_attr(not(target_arch = "spirv"), warn(missing_debug_implementations))]
173 #![allow(clippy::verbose_bit_mask, clippy::cast_lossless)]
174 #![cfg_attr(not(feature = "std"), no_std)]
175 #![cfg_attr(
176     all(
177         feature = "use-intrinsics",
178         any(target_arch = "x86", target_arch = "x86_64")
179     ),
180     feature(stdsimd, f16c_target_feature)
181 )]
182 #![doc(html_root_url = "https://docs.rs/half/2.2.1")]
183 #![doc(test(attr(deny(warnings), allow(unused))))]
184 #![cfg_attr(docsrs, feature(doc_cfg))]
185 
186 #[cfg(feature = "alloc")]
187 extern crate alloc;
188 
189 mod bfloat;
190 mod binary16;
191 mod leading_zeros;
192 #[cfg(feature = "num-traits")]
193 mod num_traits;
194 
195 #[cfg(not(target_arch = "spirv"))]
196 pub mod slice;
197 #[cfg(feature = "alloc")]
198 #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
199 pub mod vec;
200 
201 pub use bfloat::bf16;
202 pub use binary16::f16;
203 
204 /// A collection of the most used items and traits in this crate for easy importing.
205 ///
206 /// # Examples
207 ///
208 /// ```rust
209 /// use half::prelude::*;
210 /// ```
211 pub mod prelude {
212     #[doc(no_inline)]
213     pub use crate::{bf16, f16};
214 
215     #[cfg(not(target_arch = "spirv"))]
216     #[doc(no_inline)]
217     pub use crate::slice::{HalfBitsSliceExt, HalfFloatSliceExt};
218 
219     #[cfg(feature = "alloc")]
220     #[doc(no_inline)]
221     #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
222     pub use crate::vec::{HalfBitsVecExt, HalfFloatVecExt};
223 }
224 
225 // Keep this module private to crate
226 mod private {
227     use crate::{bf16, f16};
228 
229     pub trait SealedHalf {}
230 
231     impl SealedHalf for f16 {}
232     impl SealedHalf for bf16 {}
233 }
234