Skip to main content

fixed/
lib.rs

1// Copyright © 2018–2026 Trevor Spiteri
2
3// This library is free software: you can redistribute it and/or
4// modify it under the terms of either
5//
6//   * the Apache License, Version 2.0 or
7//   * the MIT License
8//
9// at your option.
10//
11// You should have recieved copies of the Apache License and the MIT
12// License along with the library. If not, see
13// <https://www.apache.org/licenses/LICENSE-2.0> and
14// <https://opensource.org/licenses/MIT>.
15
16/*!
17# Fixed-point numbers
18
19The [*fixed* crate] provides fixed-point numbers.
20
21  * [`FixedI8`] and [`FixedU8`] are eight-bit fixed-point numbers.
22  * [`FixedI16`] and [`FixedU16`] are 16-bit fixed-point numbers.
23  * [`FixedI32`] and [`FixedU32`] are 32-bit fixed-point numbers.
24  * [`FixedI64`] and [`FixedU64`] are 64-bit fixed-point numbers.
25  * [`FixedI128`] and [`FixedU128`] are 128-bit fixed-point numbers.
26
27An <i>n</i>-bit fixed-point number has
28<span style="white-space: nowrap;"><i>f</i> = `Frac`</span>
29fractional bits where
30<span style="white-space: nowrap;">0 ≤ <i>f</i> ≤ <i>n</i></span>,
31and
32<span style="white-space: nowrap;"><i>n</i> &minus; <i>f</i></span>
33integer bits. For example, <code>[FixedI32]\<[U24]></code> is a 32-bit signed
34fixed-point number with
35<span style="white-space: nowrap;"><i>n</i> = 32</span>
36total bits,
37<span style="white-space: nowrap;"><i>f</i> = 24</span>
38fractional bits, and
39<span style="white-space: nowrap;"><i>n</i> &minus; <i>f</i> = 8</span>
40integer bits. <code>[FixedI32]\<[U0]></code> behaves like [`i32`], and
41<code>[FixedU32]\<[U0]></code> behaves like [`u32`].
42
43The difference between any two successive representable numbers is constant
44throughout the possible range for a fixed-point number:
45<span style="white-space: nowrap;"><i>Δ</i> = 1/2<sup><i>f</i></sup></span>.
46When
47<span style="white-space: nowrap;"><i>f</i> = 0</span>,
48like in <code>[FixedI32]\<[U0]></code>,
49<span style="white-space: nowrap;"><i>Δ</i> = 1</span>
50because representable numbers are integers, and the difference between two
51successive integers is 1. When
52<span style="white-space: nowrap;"><i>f</i> = <i>n</i></span>,
53<span style="white-space: nowrap;"><i>Δ</i> = 1/2<sup><i>n</i></sup></span>
54and the value lies in the range
55<span style="white-space:
56nowrap;">&minus;0.5 ≤ <i>x</i> < 0.5</span>
57for signed numbers like <code>[FixedI32]\<[U32]></code>, and in the range
58<span style="white-space: nowrap;">0 ≤ <i>x</i> < 1</span>
59for unsigned numbers like <code>[FixedU32]\<[U32]></code>.
60
61The main features are
62
63  * Representation of binary fixed-point numbers up to 128 bits wide.
64  * Conversions between fixed-point numbers and numeric primitives.
65  * Comparisons between fixed-point numbers and numeric primitives.
66  * Parsing from strings in decimal, binary, octal and hexadecimal.
67  * Display as decimal, binary, octal and hexadecimal.
68  * Arithmetic and logic operations.
69
70This crate does *not* provide decimal fixed-point numbers. For example 0.001
71cannot be represented exactly, as it is 1/10<sup>3</sup>. It is binary fractions
72like 1/2<sup>4</sup> (0.0625) that can be represented exactly, provided there
73are enough fractional bits.
74
75This crate does *not* provide general analytic functions.
76
77  * No algebraic functions are provided, for example no `pow`.
78  * No trigonometric functions are provided, for example no `sin` or `cos`.
79  * No other transcendental functions are provided, for example no `log` or
80    `exp`.
81
82These functions are not provided because different implementations can have
83different trade-offs, for example trading some correctness for speed.
84Implementations can be provided in other crates.
85
86  * The [*cordic* crate] provides various functions implemented using the
87    [CORDIC] algorithm.
88
89The conversions supported cover the following cases.
90
91  * Infallible lossless conversions between fixed-point numbers and numeric
92    primitives are provided using [`From`] and [`Into`]. These never fail
93    (infallible) and do not lose any bits (lossless).
94  * Infallible lossy conversions between fixed-point numbers and numeric
95    primitives are provided using the [`LossyFrom`] and [`LossyInto`] traits.
96    The source can have more fractional bits than the destination.
97  * Checked lossless conversions between fixed-point numbers and numeric
98    primitives are provided using the [`LosslessTryFrom`] and
99    [`LosslessTryInto`] traits. The source cannot have more fractional bits than
100    the destination.
101  * Checked conversions between fixed-point numbers and numeric primitives are
102    provided using the [`FromFixed`] and [`ToFixed`] traits, or using the
103    [`from_num`] and [`to_num`] methods and [their checked
104    versions][`checked_from_num`].
105  * Additionally, [`az`] casts are implemented for conversion between
106    fixed-point numbers and numeric primitives.
107  * Fixed-point numbers can be parsed from decimal strings using [`FromStr`],
108    and from binary, octal and hexadecimal strings using the
109    [`from_str_binary`], [`from_str_octal`] and [`from_str_hex`] methods. The
110    result is rounded to the nearest, with ties rounded to even.
111  * Fixed-point numbers can be converted to strings using [`Display`],
112    [`Binary`], [`Octal`], [`LowerHex`], [`UpperHex`], [`LowerExp`] and
113    [`UpperExp`]. The output is rounded to the nearest, with ties rounded to
114    even.
115  * All fixed-point numbers are plain old data, so [`bytemuck`] bit casting
116    conversions can be used.
117
118## Quick examples
119
120```rust
121use fixed::types::I20F12;
122
123// 19/3 = 6 1/3
124let six_and_third = I20F12::from_num(19) / 3;
125// four decimal digits for 12 binary digits
126assert_eq!(six_and_third.to_string(), "6.3333");
127// find the ceil and convert to i32
128assert_eq!(six_and_third.ceil().to_num::<i32>(), 7);
129// we can also compare directly to integers
130assert_eq!(six_and_third.ceil(), 7);
131```
132
133The type [`I20F12`] is a 32-bit fixed-point signed number with 20 integer bits
134and 12 fractional bits. It is an alias to <code>[FixedI32]\<[U12]></code>. The
135unsigned counterpart would be [`U20F12`]. Aliases are provided for all
136combinations of integer and fractional bits adding up to a total of eight, 16,
13732, 64 or 128 bits.
138
139```rust
140use fixed::types::{I4F4, I4F12};
141
142// -8 ≤ I4F4 < 8 with steps of 1/16 (~0.06)
143let a = I4F4::from_num(1);
144// multiplication and division by integers are possible
145let ans1 = a / 5 * 17;
146// 1 / 5 × 17 = 3 2/5 (3.4), but we get 3 3/16 (~3.2)
147assert_eq!(ans1, I4F4::from_bits((3 << 4) + 3));
148assert_eq!(ans1.to_string(), "3.2");
149
150// -8 ≤ I4F12 < 8 with steps of 1/4096 (~0.0002)
151let wider_a = I4F12::from(a);
152let wider_ans = wider_a / 5 * 17;
153let ans2 = I4F4::from_num(wider_ans);
154// now the answer is the much closer 3 6/16 (~3.4)
155assert_eq!(ans2, I4F4::from_bits((3 << 4) + 6));
156assert_eq!(ans2.to_string(), "3.4");
157```
158
159The second example shows some precision and conversion issues. The low precision
160of `a` means that `a / 5` is 3⁄16 instead of 1⁄5, leading to an inaccurate
161result `ans1` = 3 3⁄16 (~3.2). With a higher precision, we get `wider_a / 5`
162equal to 819⁄4096, leading to a more accurate intermediate result `wider_ans` =
1633 1635⁄4096. When we convert back to four fractional bits, we get `ans2` = 3
1646⁄16 (~3.4).
165
166Note that we can convert from [`I4F4`] to [`I4F12`] using [`From`], as the
167target type has the same number of integer bits and a larger number of
168fractional bits. Converting from [`I4F12`] to [`I4F4`] cannot use [`From`] as we
169have less fractional bits, so we use [`from_num`] instead.
170
171## Comparing fixed-point numbers
172
173With floating-point numbers like [`f32`], checking two numbers for equality can
174require calculating both the absolute difference
175(<span style="white-space: nowrap;">|<i>a</i> &minus; <i>b</i>|</span>)
176and the relative difference
177(<span style="white-space: nowrap;">|<i>a</i> &minus; <i>b</i>| / <i>a</i></span>)
178to account for rounding errors and different precisions.
179
180With fixed-point numbers, this is simpler. Since the point is fixed, and very
181tiny numbers simply underflow to zero, it is usually enough to just check that
182the absolute difference between two numbers is smaller than a specific
183threshold.
184
185You can do this using [`saturating_dist`] and [`DELTA`]. For example to ensure
186that the difference between two numbers is less than
187<span style="white-space: nowrap;">4 × <i>Δ</i></span>:
188
189```rust
190use fixed::types::I20F12;
191
192let a = I20F12::from_num(1.5);
193// b is not exactly 1.5 because of rounding errors
194let b = a.sqrt() * a.sqrt();
195// check for equality by comparing to 4 × Δ
196assert!(a.saturating_dist(b) < 4 * I20F12::DELTA);
197```
198
199Note that [`saturating_dist`] was used instead of [`dist`] to avoid overflow if
200<i>a</i> and <i>b</i> are very different, for example [`MIN`] and [`MAX`].
201
202## Writing fixed-point constants and values literally
203
204The [`lit`] method, which is available as a `const` function, can be used to
205parse literals. It supports
206  * underscores as separators;
207  * prefixes “`0b`”, “`0o`” and “`0x`” for binary, octal and hexadecimal
208    numbers;
209  * an optional decimal exponent with separator “`e`” or “`E`” for decimal,
210    binary and octal numbers, or with separator “`@`” for all supported radices
211    including hexadecimal.
212
213```rust
214use fixed::types::I16F16;
215
216// 0.1275e2 is 12.75
217const TWELVE_POINT_75: I16F16 = I16F16::lit("0.127_5e2");
218// 1.8 hexadecimal is 1.5 decimal, and 18@-1 is 1.8
219const ONE_POINT_5: I16F16 = I16F16::lit("0x_18@-1");
220// 12.75 + 1.5 = 14.25
221let sum = TWELVE_POINT_75 + ONE_POINT_5;
222assert_eq!(sum, 14.25);
223```
224
225## Using the *fixed* crate
226
227The *fixed* crate is available on [crates.io][*fixed* crate]. To use it in your
228crate, add it as a dependency inside [*Cargo.toml*]:
229
230```toml
231[dependencies]
232fixed = "1.31"
233```
234
235The *fixed* crate requires rustc version 1.93.0 or later.
236
237## Optional features
238
239The *fixed* crate has these optional feature:
240
241 1. `arbitrary`, disabled by default. This provides the generation of arbitrary
242    fixed-point numbers from raw, unstructured data. This feature requires the
243    [*arbitrary* crate].
244 2. `borsh`, disabled by default. This implements serialization and
245    deserialization using the [*borsh* crate].
246 3. `compat-readonly-static`, disabled by default. This enables compatibility
247    with platforms where statics are read-only by disabling caching of
248    formatting flags in atomic statics. Note that this may incur a small
249    performance overhead when formatting many numbers using the hexadecimal
250    debug specifiers `{:x?}` or `{:X?}`.
251 4. `defmt`, disabled by default. This implements formatting using the [*defmt*
252    crate]. Note that the implementation delegates to the [`Display`] trait.
253    This means formatting is performed on the device and the resulting string is
254    sent over the wire. To minimize log bandwidth, you can transmit the integer
255    representation, for example `value.to_bits()`, and then decode on the host.
256 5. `serde`, disabled by default. This provides serialization support for the
257    fixed-point types. This feature requires the [*serde* crate].
258 6. `std`, disabled by default. This is for features that are not possible under
259    `no_std`: currently this is only required for the `serde-str` feature.
260 7. `serde-str`, disabled by default. Fixed-point numbers are serialized as
261    strings showing the value when using human-readable formats. This feature
262    requires the `serde` and the `std` optional features. **Warning:** numbers
263    serialized when this feature is enabled cannot be deserialized when this
264    feature is disabled, and vice versa.
265
266To enable features, you can add the dependency like this to [*Cargo.toml*]:
267
268```toml
269[dependencies.fixed]
270features = ["serde"]
271version = "1.31"
272```
273
274## Experimental optional features
275
276It is not considered a breaking change if the following experimental features
277are removed. The removal of experimental features would however require a minor
278version bump. Similarly, on a minor version bump, optional dependencies can be
279updated to an incompatible newer version.
280
281 1. `num-traits`, disabled by default. This implements some traits from the
282    [*num-traits* crate]. (The plan is to promote this to an optional feature
283    once the [*num-traits* crate] reaches version 1.0.0.)
284 2. `nightly-float`, disabled by default. This requires the nightly compiler,
285    and implements conversions and comparisons with the experimental [`f16`] and
286    [`f128`] primitives. (The plan is to always implement the conversions and
287    comparisons and remove this experimental feature once the primitives are
288    stabilized.)
289
290[`f128`]: https://doc.rust-lang.org/nightly/std/primitive.f128.html
291[`f16`]: https://doc.rust-lang.org/nightly/std/primitive.f16.html
292
293## Deprecated optional features
294
295The following optional features are deprecated and will be removed in the next
296major version of the crate.
297
298 1. `az`, has no effect. Previously required for the [`az`] cast traits. Now
299    these cast traits are always provided.
300 2. `f16`, has no effect. Previously required for conversion to/from
301    <code>[half]::[f16][half::f16]</code> and
302    <code>[half]::[bf16][half::bf16]</code>. Now these conversions are always
303    provided.
304
305## License
306
307This crate is free software: you can redistribute it and/or modify it under the
308terms of either
309
310  * the [Apache License, Version 2.0][LICENSE-APACHE] or
311  * the [MIT License][LICENSE-MIT]
312
313at your option.
314
315### Contribution
316
317Unless you explicitly state otherwise, any contribution intentionally submitted
318for inclusion in the work by you, as defined in the Apache License, Version 2.0,
319shall be dual licensed as above, without any additional terms or conditions.
320
321[*Cargo.toml*]: https://doc.rust-lang.org/cargo/guide/dependencies.html
322[*arbitrary* crate]: https://crates.io/crates/arbitrary
323[*borsh* crate]: https://crates.io/crates/borsh
324[*cordic* crate]: https://crates.io/crates/cordic
325[*fixed* crate]: https://crates.io/crates/fixed
326[*half* crate]: https://crates.io/crates/half
327[*num-traits* crate]: https://crates.io/crates/num-traits
328[*serde* crate]: https://crates.io/crates/serde
329[*typenum* crate]: https://crates.io/crates/typenum
330[CORDIC]: https://en.wikipedia.org/wiki/CORDIC
331[LICENSE-APACHE]: https://www.apache.org/licenses/LICENSE-2.0
332[LICENSE-MIT]: https://opensource.org/licenses/MIT
333[U0]: crate::types::extra::U0
334[U24]: crate::types::extra::U24
335[`Binary`]: core::fmt::Binary
336[`DELTA`]: FixedI32::DELTA
337[`Display`]: core::fmt::Display
338[`FromStr`]: core::str::FromStr
339[`I20F12`]: crate::types::I20F12
340[`I4F12`]: crate::types::I4F12
341[`I4F4`]: crate::types::I4F4
342[`LosslessTryFrom`]: traits::LosslessTryFrom
343[`LosslessTryInto`]: traits::LosslessTryInto
344[`LossyFrom`]: traits::LossyFrom
345[`LossyInto`]: traits::LossyInto
346[`LowerExp`]: core::fmt::LowerExp
347[`LowerHex`]: core::fmt::LowerHex
348[`MAX`]: FixedI32::MAX
349[`MIN`]: FixedI32::MIN
350[`Octal`]: core::fmt::Octal
351[`U20F12`]: types::U20F12
352[`UpperExp`]: core::fmt::UpperExp
353[`UpperHex`]: core::fmt::UpperHex
354[`checked_from_num`]: FixedI32::checked_from_num
355[`dist`]: FixedI32::dist
356[`from_num`]: FixedI32::from_num
357[`from_str_binary`]: FixedI32::from_str_binary
358[`from_str_hex`]: FixedI32::from_str_hex
359[`from_str_octal`]: FixedI32::from_str_octal
360[`lit`]: FixedI32::lit
361[`saturating_dist`]: FixedI32::saturating_dist
362[`to_num`]: FixedI32::to_num
363*/
364#![cfg_attr(not(feature = "std"), no_std)]
365#![warn(missing_docs)]
366#![warn(unsafe_op_in_unsafe_fn)]
367#![doc(html_root_url = "https://docs.rs/fixed/~1.31")]
368#![doc(html_logo_url = "data:image/svg+xml;base64,
369PHN2ZyB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgdmVyc2lvbj0iMS4xIiB2aWV3Qm94PSIwIDAgMzMuODY3IDMzLjg2NyIgeG1s
370bnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcz48Y2xpcFBhdGggaWQ9ImIiPjxjaXJjbGUgY3g9IjE2LjkzMyIg
371Y3k9IjI4MC4wNyIgcj0iMTYuOTMzIiBmaWxsPSIjMDA3MmIyIi8+PC9jbGlwUGF0aD48Y2xpcFBhdGggaWQ9ImEiPjxjaXJjbGUg
372Y3g9IjE2LjkzMyIgY3k9IjI4MC4wNyIgcj0iMTYuOTMzIiBmaWxsPSIjMDA3MmIyIi8+PC9jbGlwUGF0aD48L2RlZnM+PGcgdHJh
373bnNmb3JtPSJ0cmFuc2xhdGUoMCAtMjYzLjEzKSI+PHBhdGggZD0ibTMzLjg2NyAyODAuMDdhMTYuOTMzIDE2LjkzMyAwIDAgMS0x
374Ni45MzMgMTYuOTMzIDE2LjkzMyAxNi45MzMgMCAwIDEtMTYuOTMzLTE2LjkzMyAxNi45MzMgMTYuOTMzIDAgMCAxIDE2LjkzMy0x
375Ni45MzMgMTYuOTMzIDE2LjkzMyAwIDAgMSAxNi45MzMgMTYuOTMzeiIgZmlsbD0iI2Y3ZjFhMSIgc3Ryb2tlLXdpZHRoPSIuNTA0
376NjciLz48cGF0aCBkPSJtMjEuMzQ0IDI4NS4zNGg3LjU2OTJ2LTIuMDk5N2gtMi40MDQ1Yy0wLjQ5MTA3IDAtMS4yMzYxIDAuMDY3
377Ny0xLjc5NDkgMC4xMzU0NyAxLjkxMzUtMS44Nzk2IDMuNjc0NS0zLjY0MDcgMy42NzQ1LTUuNTg4IDAtMi4wNDg5LTEuNDM5My0z
378LjQwMzYtMy41NTYtMy40MDM2LTEuNTA3MSAwLTIuNTIzMSAwLjU5MjY3LTMuNTU2IDEuNzYxMWwxLjMwMzkgMS4yODY5YzAuNTQx
379ODctMC41NzU3MyAxLjEzNDUtMS4xMDA3IDEuOTEzNS0xLjEwMDcgMC45MzEzMyAwIDEuNTI0IDAuNTc1NzQgMS41MjQgMS42MjU2
380IDAgMS41MDcxLTEuOTY0MyAzLjQzNzUtNC42NzM2IDUuODQyem0xMi43NjggMC4yMDMyYzIuMjg2IDAgMy44MS0xLjI4NjkgMy44
381MS0yLjk4MDMgMC0xLjQyMjQtMC44Mjk3My0yLjI1MjEtMS44NjI3LTIuODEwOXYtMC4wNjc3YzAuNzQ1MDctMC40OTEwNyAxLjQw
382NTUtMS4zMjA4IDEuNDA1NS0yLjM1MzcgMC0xLjc3OC0xLjMwMzktMi45NDY0LTMuMjY4MS0yLjk0NjQtMS45OTgxIDAtMy40Mzc1
383IDEuMTM0NS0zLjQzNzUgMi45NjMzIDAgMS4xMzQ1IDAuNjA5NiAxLjkxMzUgMS40MzkzIDIuNTR2MC4wNjc3Yy0xLjAxNiAwLjU0
384MTg3LTEuODI4OCAxLjMzNzctMS44Mjg4IDIuNjQxNiAwIDEuNzQ0MSAxLjU5MTcgMi45NDY0IDMuNzQyMyAyLjk0NjR6bTAuNjc3
385MzMtNi40Njg1Yy0xLjEwMDctMC40MjMzMy0xLjg0NTctMC44NDY2Ny0xLjg0NTctMS43MjcyIDAtMC44Mjk3MyAwLjU0MTg3LTEu
386MjM2MSAxLjIwMjMtMS4yMzYxIDAuODEyOCAwIDEuMzAzOSAwLjU1ODggMS4zMDM5IDEuMzg4NSAwIDAuNTU4OC0wLjIzNzA3IDEu
387MDgzNy0wLjY2MDQgMS41NzQ4em0tMC42MjY1MyA0Ljc0MTNjLTAuODk3NDYgMC0xLjY1OTUtMC41NTg4LTEuNjU5NS0xLjUwNzEg
388MC0wLjY2MDQgMC4zNTU2LTEuMjcgMC44Mjk3My0xLjcxMDMgMS4zNTQ3IDAuNTc1NzMgMi4yNjkxIDAuOTMxMzMgMi4yNjkxIDEu
389ODc5NiAwIDAuODk3NDctMC42MDk2IDEuMzM3Ny0xLjQzOTMgMS4zMzc3eiIgY2xpcC1wYXRoPSJ1cmwoI2EpIiBmaWxsPSIjMDA3
390MmIyIiBzdHJva2Utd2lkdGg9Ii4yNjQ1OHB4IiBhcmlhLWxhYmVsPSIyOCIvPjxwYXRoIGQ9Im0xNS4zNDYgMjg1LjM2aDMuMTc1
391bDEuNTg3NS0yLjc0OTYtMS41ODc1LTIuNzQ5Ny0zLjE3NSAxZS00IC0xLjU4NzUgMi43NDk2eiIgZmlsbD0iIzAwNWI4ZSIgc3Ry
392b2tlLXdpZHRoPSIuMjY0NTgiLz48cGF0aCBkPSJtLTAuMjExNjcgMjg1LjU0YzIuMzAyOSAwIDMuODQzOS0xLjk2NDMgMy44NDM5
393LTUuNjIxOXMtMS41NDA5LTUuNTM3Mi0zLjg0MzktNS41MzcyYy0yLjMwMjkgMC0zLjg0MzkgMS44Nzk2LTMuODQzOSA1LjUzNzJz
394MS41NDA5IDUuNjIxOSAzLjg0MzkgNS42MjE5em0wLTEuOTMwNGMtMC44Mjk3MyAwLTEuNDkwMS0wLjc2Mi0xLjQ5MDEtMy42OTE1
395IDAtMi45NDY0IDAuNjYwNC0zLjYwNjggMS40OTAxLTMuNjA2OCAwLjg0NjY3IDAgMS40OTAxIDAuNjYwNCAxLjQ5MDEgMy42MDY4
396IDAgMi45Mjk1LTAuNjQzNDcgMy42OTE1LTEuNDkwMSAzLjY5MTV6bTkuMTI3MS0zLjIzNDNjMC44MTI4IDAgMS40MDU1IDAuNDIz
397MzQgMS40MDU1IDEuNTU3OSAwIDEuMjE5Mi0wLjYwOTYgMS43NDQxLTEuMzU0NyAxLjc0NDFzLTEuNDU2My0wLjU0MTg2LTEuNjc2
398NC0yLjIzNTJjMC40NDAyNy0wLjc2MiAxLjA2NjgtMS4wNjY4IDEuNjI1Ni0xLjA2Njh6bTAuMTAxNiA1LjE2NDdjMS45NDczIDAg
399My41NzI5LTEuMzcxNiAzLjU3MjktMy42MDY4IDAtMi4yNjkxLTEuMzU0Ny0zLjMxODktMy4yMDA0LTMuMzE4OS0wLjY2MDQgMC0x
400LjU5MTcgMC40MjMzMy0yLjE1MDUgMS4xMzQ1IDAuMDg0NjY3LTIuNTA2MSAxLjAzMjktMy4zNTI4IDIuMjE4My0zLjM1MjggMC42
401MjY1MyAwIDEuMzAzOSAwLjM1NTYgMS42NzY0IDAuNzYybDEuMzAzOS0xLjQ5MDFjLTAuNjc3MzMtMC42OTQyNy0xLjcxMDMtMS4y
402ODY5LTMuMTMyNy0xLjI4NjktMi4yNjkxIDAtNC4zNTE5IDEuODExOS00LjM1MTkgNS44MjUxIDAgMy43NzYxIDEuOTgxMiA1LjMz
403NCA0LjA2NCA1LjMzNHoiIGNsaXAtcGF0aD0idXJsKCNiKSIgZmlsbD0iIzAwNzJiMiIgc3Ryb2tlLXdpZHRoPSIuMjY0NThweCIg
404YXJpYS1sYWJlbD0iMDYiLz48cGF0aCBkPSJtMTYuOTMzIDI4NC45NmMxLjI5NTQgMCAyLjI2MDYtMS4wMTYgMi4yNjA2LTIuMzM2
405OCAwLTEuMzQ2Mi0wLjk2NTItMi4zNjIyLTIuMjYwNi0yLjM2MjJzLTIuMjYwNiAxLjAxNi0yLjI2MDYgMi4zNjIyYzAgMS4zMjA4
406IDAuOTY1MiAyLjMzNjggMi4yNjA2IDIuMzM2OHoiIGZpbGw9IiMwMDcyYjIiIHN0cm9rZS13aWR0aD0iLjI2NDU4cHgiIGFyaWEt
407bGFiZWw9Ii4iLz48L2c+PC9zdmc+Cg==
408")]
409#![doc(test(attr(deny(warnings))))]
410#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
411#![cfg_attr(feature = "nightly-float", feature(f16, f128))]
412
413#[cfg(all(not(feature = "std"), test))]
414extern crate std;
415
416#[macro_use]
417mod macros;
418
419mod arith;
420#[cfg(feature = "borsh")]
421mod borshize;
422mod bytes;
423mod cast;
424mod cmp;
425mod cmp_fixed;
426pub mod consts;
427mod convert;
428mod debug_hex;
429#[cfg(feature = "defmt")]
430mod defmt;
431mod display;
432pub mod f128;
433mod float_helper;
434mod from_str;
435mod helpers;
436mod hypot;
437#[cfg(feature = "arbitrary")]
438mod impl_arbitrary;
439mod impl_bytemuck;
440#[cfg(feature = "num-traits")]
441mod impl_num_traits;
442mod int256;
443mod int_helper;
444mod inv_lerp;
445mod lerp;
446mod log;
447mod log10;
448mod prim_traits;
449mod saturating;
450#[cfg(feature = "serde")]
451mod serdeize;
452mod sqrt;
453mod strict;
454pub mod traits;
455mod traits_bits;
456pub mod types;
457mod wrapping;
458
459pub use crate::f128::private::F128;
460pub use crate::from_str::ParseFixedError;
461#[cfg(feature = "num-traits")]
462pub use crate::impl_num_traits::RadixParseFixedError;
463use crate::log::Base;
464pub use crate::saturating::Saturating;
465#[allow(deprecated)]
466pub use crate::strict::{Strict, Unwrapped};
467use crate::traits::{FromFixed, ToFixed};
468use crate::types::extra::{
469    Diff, IsLessOrEqual, LeEqU8, LeEqU16, LeEqU32, LeEqU64, LeEqU128, Sum, True, U0, U4, U5, U6,
470    U7, U8, U12, U13, U14, U15, U16, U28, U29, U30, U31, U32, U60, U61, U62, U63, U64, U124, U125,
471    U126, U127, U128, Unsigned,
472};
473pub use crate::wrapping::Wrapping;
474use core::hash::{Hash, Hasher};
475use core::marker::PhantomData;
476use core::num::NonZero;
477use core::ops::{Add, Sub};
478
479/// A prelude to import useful traits.
480///
481/// This prelude is similar to the [standard library’s prelude][std::prelude] in
482/// that you’ll almost always want to import its entire contents, but unlike the
483/// standard library’s prelude you’ll have to do so manually:
484///
485/// ```rust
486/// # #[allow(unused_imports)]
487/// use fixed::prelude::*;
488/// ```
489///
490/// The prelude may grow over time as additional items see ubiquitous use.
491///
492/// # Contents
493///
494/// The prelude re-exports the following:
495///
496///  * <code>[traits]::{[FromFixed], [ToFixed]}</code>, checked conversions
497///    from/to fixed-point numbers.
498///  * <code>[traits]::{[LossyFrom], [LossyInto]}</code>, infallible lossy
499///    conversions.
500///  * <code>[traits]::{[LosslessTryFrom], [LosslessTryInto]}</code>, checked
501///    lossless conversions.
502///
503/// [LosslessTryFrom]: crate::traits::LosslessTryFrom
504/// [LosslessTryInto]: crate::traits::LosslessTryInto
505/// [LossyFrom]: crate::traits::LossyFrom
506/// [LossyInto]: crate::traits::LossyInto
507pub mod prelude {
508    pub use crate::traits::{
509        FromFixed, LosslessTryFrom, LosslessTryInto, LossyFrom, LossyInto, ToFixed,
510    };
511}
512
513#[macro_use]
514mod macros_from_to;
515#[macro_use]
516mod macros_round;
517#[macro_use]
518mod macros_no_frac;
519#[macro_use]
520mod macros_frac;
521#[macro_use]
522mod macros_const;
523
524macro_rules! fixed {
525    (
526        description = $description:literal,
527        {Self, Inner} = {$Self:ident, $Inner:ident},
528        Signedness = $Signedness:ident,
529        LeEqU = $LeEqU:ident,
530        {Unm1, Un} = {$Unm1:ident, $Un:ident},
531        [nm4 ..= np1]
532            = [$nm4:literal, $nm3:literal, $nm2:literal, $nm1:literal, $n:literal, $np1:literal],
533        {ISelf, IInner} = {$ISelf:ident, $IInner:ident},
534        {USelf, UInner} = {$USelf:ident, $UInner:ident},
535        [LeEqUC0 ..= LeEqUC3] = [$LeEqUC0:ident, $LeEqUC1:ident, $LeEqUC2:ident, $LeEqUC3:ident],
536        nbytes = $nbytes:literal,
537        {bytes_val, rev_bytes_val} = {$bytes_val:literal, $rev_bytes_val:literal $(,)?},
538        {be_bytes, le_bytes} = {$be_bytes:literal, $le_bytes:literal $(,)?},
539        $(
540            n2 = $n2:literal,
541            {Double, DoubleInner} = {$Double:ident, $DoubleInner:ident},
542            {IDouble, IDoubleInner} = {$IDouble:ident, $IDoubleInner:ident},
543        )?
544    ) => {
545        comment! {
546            $description, "-bit ",
547            if_signed_unsigned!($Signedness, "signed", "unsigned"),
548            " number with `Frac` fractional bits.
549
550The number has ", $n, " bits, of which <i>f</i>&nbsp;=&nbsp;`Frac` are
551fractional bits and ", $n, "&nbsp;&minus;&nbsp;<i>f</i> are integer bits.
552The value <i>x</i> can lie in the range ",
553            if_signed_unsigned!(
554                $Signedness,
555                concat!("&minus;2<sup>", $nm1, "</sup>/2<sup><i>f</i></sup>"),
556                "0",
557            ),
558            "&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;2<sup>",
559            if_signed_unsigned!($Signedness, $nm1, $n),
560            "</sup>/2<sup><i>f</i></sup>. The difference between successive
561numbers is constant throughout the range: <i>Δ</i>&nbsp;=&nbsp;1/2<sup><i>f</i></sup>.
562
563For <code>", stringify!($Self), "\\<[U0]></code>, <i>f</i>&nbsp;=&nbsp;0 and
564<i>Δ</i>&nbsp;=&nbsp;1, and the fixed-point number behaves like ",
565            if_signed_unsigned!($Signedness, "an", "a"),
566            " [`", stringify!($Inner), "`] with the value lying in the range ",
567            if_signed_unsigned!(
568                $Signedness,
569                concat!("&minus;2<sup>", $nm1, "</sup>"),
570                "0",
571            ),
572            "&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;2<sup>",
573            if_signed_unsigned!($Signedness, $nm1, $n),
574            "</sup>. For <code>", stringify!($Self), "\\<[U", $n, "]></code>,
575<i>f</i>&nbsp;=&nbsp;", $n, " and
576<i>Δ</i>&nbsp;=&nbsp;1/2<sup>", $n, "</sup>, and the value lies in the
577range ",
578            if_signed_unsigned!(
579                $Signedness,
580                "&minus;1/2&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;1/2",
581                "0&nbsp;≤&nbsp;<i>x</i>&nbsp;<&nbsp;1",
582            ),
583            ".
584
585`Frac` is an [`Unsigned`] as provided by the [*typenum* crate].
586
587`", stringify!($Self), "<Frac>` has the same size, alignment and ABI as
588[`", stringify!($Inner), "`]; it is `#[repr(transparent)]` with
589[`", stringify!($Inner), "`] as the only non-zero-sized field.
590
591# Examples
592
593```rust
594use fixed::types::extra::U3;
595use fixed::", stringify!($Self), ";
596let eleven = ", stringify!($Self), "::<U3>::from_num(11);
597assert_eq!(eleven, ", stringify!($Self), "::<U3>::from_bits(11 << 3));
598assert_eq!(eleven, 11);
599assert_eq!(eleven.to_string(), \"11\");
600let two_point_75 = eleven / 4;
601assert_eq!(two_point_75, ", stringify!($Self), "::<U3>::from_bits(11 << 1));
602assert_eq!(two_point_75, 2.75);
603assert_eq!(two_point_75.to_string(), \"2.8\");
604```
605
606[*typenum* crate]: https://crates.io/crates/typenum
607[U", $n, "]: crate::types::extra::U", $n, "
608[U0]: crate::types::extra::U0
609";
610            #[repr(transparent)]
611            pub struct $Self<Frac> {
612                pub(crate) bits: $Inner,
613                phantom: PhantomData<Frac>,
614            }
615        }
616
617        impl<Frac> Clone for $Self<Frac> {
618            #[inline]
619            fn clone(&self) -> $Self<Frac> {
620                *self
621            }
622        }
623
624        impl<Frac> Copy for $Self<Frac> {}
625
626        impl<Frac> Default for $Self<Frac> {
627            #[inline]
628            fn default() -> Self {
629                $Self {
630                    bits: Default::default(),
631                    phantom: PhantomData,
632                }
633            }
634        }
635
636        impl<Frac> Hash for $Self<Frac> {
637            #[inline]
638            fn hash<H: Hasher>(&self, state: &mut H) {
639                self.bits.hash(state);
640            }
641        }
642
643        // inherent methods that do not require Frac bounds, some of which can thus be const
644        fixed_no_frac! {
645            {Self, Inner} = {$Self, $Inner},
646            Signedness = $Signedness,
647            LeEqU = $LeEqU,
648            {Unm1, Un} = {$Unm1, $Un},
649            [nm4 ..= np1] = [$nm4, $nm3, $nm2, $nm1, $n, $np1],
650            {ISelf, IInner} = {$ISelf, $IInner},
651            {USelf, UInner} = {$USelf, $UInner},
652            nbytes = $nbytes,
653            {bytes_val, rev_bytes_val} = {$bytes_val, $rev_bytes_val},
654            {be_bytes, le_bytes} = {$be_bytes, $le_bytes},
655            $(
656                n2 = $n2,
657                {Double, DoubleInner} = {$Double, $DoubleInner},
658                {IDouble, IDoubleInner} = {$IDouble, $IDoubleInner},
659            )?
660        }
661        // inherent methods that require Frac bounds, and cannot be const
662        fixed_frac! {
663            {Self, Inner} = {$Self, $Inner},
664            Signedness = $Signedness,
665            LeEqU = $LeEqU,
666            {nm4, nm1, n} = {$nm4, $nm1, $n},
667            {USelf, UInner} = {$USelf, $UInner},
668        }
669        fixed_const! {
670            Self = $Self,
671            Signedness = $Signedness,
672            LeEqU = $LeEqU,
673            [nm4 ..= n] = [$nm4, $nm3, $nm2, $nm1, $n],
674            [LeEqUC0 ..= LeEqUC3] = [$LeEqUC0, $LeEqUC1, $LeEqUC2, $LeEqUC3],
675        }
676    };
677}
678
679fixed! {
680    description = "An eight",
681    {Self, Inner} = {FixedU8, u8},
682    Signedness = Unsigned,
683    LeEqU = LeEqU8,
684    {Unm1, Un} = {U7, U8},
685    [nm4 ..= np1] = [4, 5, 6, 7, 8, 9],
686    {ISelf, IInner} = {FixedI8, i8},
687    {USelf, UInner} = {FixedU8, u8},
688    [LeEqUC0 ..= LeEqUC3] = [U8, U7, U6, U5],
689    nbytes = 1,
690    {bytes_val, rev_bytes_val} = {"0x12", "0x12"},
691    {be_bytes, le_bytes} = {"[0x12]", "[0x12]"},
692    n2 = 16,
693    {Double, DoubleInner} = {FixedU16, u16},
694    {IDouble, IDoubleInner} = {FixedI16, i16},
695}
696fixed! {
697    description = "A 16",
698    {Self, Inner} = {FixedU16, u16},
699    Signedness = Unsigned,
700    LeEqU = LeEqU16,
701    {Unm1, Un} = {U15, U16},
702    [nm4 ..= np1] = [12, 13, 14, 15, 16, 17],
703    {ISelf, IInner} = {FixedI16, i16},
704    {USelf, UInner} = {FixedU16, u16},
705    [LeEqUC0 ..= LeEqUC3] = [U16, U15, U14, U13],
706    nbytes = 2,
707    {bytes_val, rev_bytes_val} = {"0x1234", "0x3412"},
708    {be_bytes, le_bytes} = {"[0x12, 0x34]", "[0x34, 0x12]"},
709    n2 = 32,
710    {Double, DoubleInner} = {FixedU32, u32},
711    {IDouble, IDoubleInner} = {FixedI32, i32},
712}
713fixed! {
714    description = "A 32",
715    {Self, Inner} = {FixedU32, u32},
716    Signedness = Unsigned,
717    LeEqU = LeEqU32,
718    {Unm1, Un} = {U31, U32},
719    [nm4 ..= np1] = [28, 29, 30, 31, 32, 33],
720    {ISelf, IInner} = {FixedI32, i32},
721    {USelf, UInner} = {FixedU32, u32},
722    [LeEqUC0 ..= LeEqUC3] = [U32, U31, U30, U29],
723    nbytes = 4,
724    {bytes_val, rev_bytes_val} = {"0x1234_5678", "0x7856_3412"},
725    {be_bytes, le_bytes} = {"[0x12, 0x34, 0x56, 0x78]", "[0x78, 0x56, 0x34, 0x12]"},
726    n2 = 64,
727    {Double, DoubleInner} = {FixedU64, u64},
728    {IDouble, IDoubleInner} = {FixedI64, i64},
729}
730fixed! {
731    description = "A 64",
732    {Self, Inner} = {FixedU64, u64},
733    Signedness = Unsigned,
734    LeEqU = LeEqU64,
735    {Unm1, Un} = {U63, U64},
736    [nm4 ..= np1] = [60, 61, 62, 63, 64, 65],
737    {ISelf, IInner} = {FixedI64, i64},
738    {USelf, UInner} = {FixedU64, u64},
739    [LeEqUC0 ..= LeEqUC3] = [U64, U63, U62, U61],
740    nbytes = 8,
741    {bytes_val, rev_bytes_val} = {"0x1234_5678_9ABC_DE0F", "0x0FDE_BC9A_7856_3412"},
742    {be_bytes, le_bytes} = {
743        "[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0x0F]",
744        "[0x0F, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]",
745    },
746    n2 = 128,
747    {Double, DoubleInner} = {FixedU128, u128},
748    {IDouble, IDoubleInner} = {FixedI128, i128},
749}
750fixed! {
751    description = "A 128",
752    {Self, Inner} = {FixedU128, u128},
753    Signedness = Unsigned,
754    LeEqU = LeEqU128,
755    {Unm1, Un} = {U127, U128},
756    [nm4 ..= np1] = [124, 125, 126, 127, 128, 129],
757    {ISelf, IInner} = {FixedI128, i128},
758    {USelf, UInner} = {FixedU128, u128},
759    [LeEqUC0 ..= LeEqUC3] = [U128, U127, U126, U125],
760    nbytes = 16,
761    {bytes_val, rev_bytes_val} = {
762        "0x1234_5678_9ABC_DEF0_0102_0304_0506_0708",
763        "0x0807_0605_0403_0201_F0DE_BC9A_7856_3412",
764    },
765    {be_bytes, le_bytes} = {
766        "[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, \
767         0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]",
768        "[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, \
769         0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]",
770    },
771}
772fixed! {
773    description = "An eight",
774    {Self, Inner} = {FixedI8, i8},
775    Signedness = Signed,
776    LeEqU = LeEqU8,
777    {Unm1, Un} = {U7, U8},
778    [nm4 ..= np1] = [4, 5, 6, 7, 8, 9],
779    {ISelf, IInner} = {FixedI8, i8},
780    {USelf, UInner} = {FixedU8, u8},
781    [LeEqUC0 ..= LeEqUC3] = [U7, U6, U5, U4],
782    nbytes = 1,
783    {bytes_val, rev_bytes_val} = {"0x12", "0x12"},
784    {be_bytes, le_bytes} = {"[0x12]", "[0x12]"},
785    n2 = 16,
786    {Double, DoubleInner} = {FixedI16, i16},
787    {IDouble, IDoubleInner} = {FixedI16, i16},
788}
789fixed! {
790    description = "A 16",
791    {Self, Inner} = {FixedI16, i16},
792    Signedness = Signed,
793    LeEqU = LeEqU16,
794    {Unm1, Un} = {U15, U16},
795    [nm4 ..= np1] = [12, 13, 14, 15, 16, 17],
796    {ISelf, IInner} = {FixedI16, i16},
797    {USelf, UInner} = {FixedU16, u16},
798    [LeEqUC0 ..= LeEqUC3] = [U15, U14, U13, U12],
799    nbytes = 2,
800    {bytes_val, rev_bytes_val} = {"0x1234", "0x3412"},
801    {be_bytes, le_bytes} = {"[0x12, 0x34]", "[0x34, 0x12]"},
802    n2 = 32,
803    {Double, DoubleInner} = {FixedI32, i32},
804    {IDouble, IDoubleInner} = {FixedI32, i32},
805}
806fixed! {
807    description = "A 32",
808    {Self, Inner} = {FixedI32, i32},
809    Signedness = Signed,
810    LeEqU = LeEqU32,
811    {Unm1, Un} = {U31, U32},
812    [nm4 ..= np1] = [28, 29, 30, 31, 32, 33],
813    {ISelf, IInner} = {FixedI32, i32},
814    {USelf, UInner} = {FixedU32, u32},
815    [LeEqUC0 ..= LeEqUC3] = [U31, U30, U29, U28],
816    nbytes = 4,
817    {bytes_val, rev_bytes_val} = {"0x1234_5678", "0x7856_3412"},
818    {be_bytes, le_bytes} = {"[0x12, 0x34, 0x56, 0x78]", "[0x78, 0x56, 0x34, 0x12]"},
819    n2 = 64,
820    {Double, DoubleInner} = {FixedI64, i64},
821    {IDouble, IDoubleInner} = {FixedI64, i64},
822}
823fixed! {
824    description = "A 64",
825    {Self, Inner} = {FixedI64, i64},
826    Signedness = Signed,
827    LeEqU = LeEqU64,
828    {Unm1, Un} = {U63, U64},
829    [nm4 ..= np1] = [60, 61, 62, 63, 64, 65],
830    {ISelf, IInner} = {FixedI64, i64},
831    {USelf, UInner} = {FixedU64, u64},
832    [LeEqUC0 ..= LeEqUC3] = [U63, U62, U61, U60],
833    nbytes = 8,
834    {bytes_val, rev_bytes_val} = {"0x1234_5678_9ABC_DE0F", "0x0FDE_BC9A_7856_3412"},
835    {be_bytes, le_bytes} = {
836        "[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0x0F]",
837        "[0x0F, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]",
838    },
839    n2 = 128,
840    {Double, DoubleInner} = {FixedI128, i128},
841    {IDouble, IDoubleInner} = {FixedI128, i128},
842}
843fixed! {
844    description = "A 128",
845    {Self, Inner} = {FixedI128, i128},
846    Signedness = Signed,
847    LeEqU = LeEqU128,
848    {Unm1, Un} = {U127, U128},
849    [nm4 ..= np1] = [124, 125, 126, 127, 128, 129],
850    {ISelf, IInner} = {FixedI128, i128},
851    {USelf, UInner} = {FixedU128, u128},
852    [LeEqUC0 ..= LeEqUC3] = [U127, U126, U125, U124],
853    nbytes = 16,
854    {bytes_val, rev_bytes_val} = {
855        "0x1234_5678_9ABC_DEF0_0102_0304_0506_0708",
856        "0x0807_0605_0403_0201_F0DE_BC9A_7856_3412",
857    },
858    {be_bytes, le_bytes} = {
859        "[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, \
860         0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]",
861        "[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, \
862         0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]",
863    },
864}
865
866/// The bit representation of a *binary128* floating-point number (`f128`).
867///
868/// This type can be used to
869///
870///   * convert between fixed-point numbers and the bit representation of
871///     128-bit floating-point numbers.
872///   * compare fixed-point numbers and the bit representation of 128-bit
873///     floating-point numbers.
874///
875/// This is deprecated, and [`F128`] should be used instead. There are two main
876/// differences to keep in mind when switching to [`F128`]:
877///
878///   * The ordering for `F128Bits` is total ordering, not regular
879///     floating-point number ordering, while the ordering for [`F128`] is
880///     similar to ordering for standard floating-point numbers.
881///   * The underlying [`u128`] value for `F128Bits` is accessible as a public
882///     field, while for [`F128`] it is accessible only through the [`to_bits`]
883///     and [`from_bits`] methods.
884///
885/// [`from_bits`]: F128::from_bits
886/// [`to_bits`]: F128::to_bits
887#[deprecated(since = "1.18.0", note = "use `F128` instead")]
888#[repr(transparent)]
889#[derive(Clone, Copy, Default, Hash, Debug, Eq, PartialEq, Ord, PartialOrd)]
890pub struct F128Bits(pub u128);
891
892#[allow(deprecated)]
893impl F128Bits {
894    #[inline]
895    pub(crate) fn to_bits(self) -> u128 {
896        self.0
897    }
898
899    #[inline]
900    pub(crate) fn from_bits(bits: u128) -> F128Bits {
901        F128Bits(bits)
902    }
903}
904
905/// Defines constant fixed-point numbers from integer expressions.
906///
907/// This macro was useful because [`from_num`][FixedI32::from_num] cannot be
908/// used in constant expressions. Now constant fixed-point numbers can be
909/// created using the [`const_from_int`][FixedI32::const_from_int] method or the
910/// [`lit`][FixedI32::lit] method, so this macro is deprecated.
911///
912/// # Examples
913///
914/// ```rust
915/// # #![allow(deprecated)]
916/// use fixed::const_fixed_from_int;
917/// use fixed::types::I16F16;
918/// const_fixed_from_int! {
919///     // define a constant using an integer
920///     const FIVE: I16F16 = 5;
921///     // define a constant using an integer expression
922///     const SUM: I16F16 = 3 + 2;
923/// }
924/// assert_eq!(FIVE, 5);
925/// assert_eq!(SUM, 5);
926/// ```
927///
928/// This can now be rewritten as
929///
930/// ```rust
931/// use fixed::types::I16F16;
932/// const FIVE: I16F16 = I16F16::const_from_int(5);
933/// const SUM: I16F16 = I16F16::const_from_int(3 + 2);
934/// assert_eq!(FIVE, 5);
935/// assert_eq!(SUM, 5);
936/// ```
937#[macro_export]
938#[deprecated(since = "1.20.0", note = "use the `const_from_int` method instead")]
939macro_rules! const_fixed_from_int {
940    ($($vis:vis const $NAME:ident: $Fixed:ty = $int:expr;)*) => { $(
941        $vis const $NAME: $Fixed = <$Fixed>::const_from_int($int);
942    )* };
943}
944
945/// These are doc tests that should not appear in the docs, but are useful as
946/// doc tests can check to ensure compilation failure.
947///
948/// The first snippet succeeds, and acts as a control.
949///
950/// ```rust
951/// use fixed::types::*;
952/// const ZERO_I0: I0F32 = I0F32::const_from_int(0);
953/// const ZERO_I1: I32F0 = I32F0::const_from_int(0);
954/// const ZERO_U0: U0F32 = U0F32::const_from_int(0);
955/// const ZERO_U1: U32F0 = U32F0::const_from_int(0);
956///
957/// const ONE_I0: I2F30 = I2F30::const_from_int(1);
958/// const ONE_I1: I32F0 = I32F0::const_from_int(1);
959/// const ONE_U0: U1F31 = U1F31::const_from_int(1);
960/// const ONE_U1: U32F0 = U32F0::const_from_int(1);
961///
962/// const MINUS_ONE_I0: I1F31 = I1F31::const_from_int(-1);
963/// const MINUS_ONE_I1: I32F0 = I32F0::const_from_int(-1);
964///
965/// const MINUS_TWO_I0: I2F30 = I2F30::const_from_int(-2);
966/// const MINUS_TWO_I1: I32F0 = I32F0::const_from_int(-2);
967///
968/// mod test_pub {
969///     use fixed::types::*;
970///
971///     pub const PUB: I32F0 = I32F0::const_from_int(0);
972/// }
973///
974/// assert_eq!(ZERO_I0, 0);
975/// assert_eq!(ZERO_I1, 0);
976/// assert_eq!(ZERO_U0, 0);
977/// assert_eq!(ZERO_U1, 0);
978///
979/// assert_eq!(ONE_I0, 1);
980/// assert_eq!(ONE_I1, 1);
981/// assert_eq!(ONE_U0, 1);
982/// assert_eq!(ONE_U1, 1);
983///
984/// assert_eq!(MINUS_ONE_I0, -1);
985/// assert_eq!(MINUS_ONE_I1, -1);
986///
987/// assert_eq!(MINUS_TWO_I0, -2);
988/// assert_eq!(MINUS_TWO_I1, -2);
989///
990/// assert_eq!(test_pub::PUB, 0);
991/// ```
992///
993/// The rest of the tests should all fail compilation.
994///
995/// Not enough integer bits for 1.
996/// ```rust,compile_fail
997/// use fixed::types::*;
998/// const _ONE: I0F32 = I0F32::const_from_int(1);
999/// ```
1000/// ```rust,compile_fail
1001/// use fixed::types::*;
1002/// const _ONE: I1F31 = I1F31::const_from_int(1);
1003/// ```
1004/// ```rust,compile_fail
1005/// use fixed::types::*;
1006/// const _ONE: U0F32 = U0F32::const_from_int(1);
1007/// ```
1008///
1009/// Not enough integer bits for -1.
1010/// ```rust,compile_fail
1011/// use fixed::types::*;
1012/// const _MINUS_ONE: I0F32 = I0F32::const_from_int(-1);
1013/// ```
1014///
1015/// Not enough integer bits for -2.
1016/// ```rust,compile_fail
1017/// use fixed::types::*;
1018/// const _MINUS_TWO: I1F31 = I1F31::const_from_int(-2);
1019/// ```
1020fn _compile_fail_tests() {}
1021
1022#[cfg(test)]
1023mod tests {
1024    use crate::types::{I0F32, I1F31, I16F16, U0F32, U16F16};
1025
1026    #[test]
1027    fn rounding_signed() {
1028        // -0.5
1029        let f = I0F32::from_bits(-1 << 31);
1030        assert_eq!(f.to_num::<i32>(), -1);
1031        assert_eq!(f.round_to_zero(), 0);
1032        assert_eq!(f.overflowing_ceil(), (I0F32::ZERO, false));
1033        assert_eq!(f.overflowing_floor(), (I0F32::ZERO, true));
1034        assert_eq!(f.overflowing_round(), (I0F32::ZERO, true));
1035        assert_eq!(f.overflowing_round_ties_even(), (I0F32::ZERO, false));
1036
1037        // -0.5 + Δ
1038        let f = I0F32::from_bits((-1 << 31) + 1);
1039        assert_eq!(f.to_num::<i32>(), -1);
1040        assert_eq!(f.round_to_zero(), 0);
1041        assert_eq!(f.overflowing_ceil(), (I0F32::ZERO, false));
1042        assert_eq!(f.overflowing_floor(), (I0F32::ZERO, true));
1043        assert_eq!(f.overflowing_round(), (I0F32::ZERO, false));
1044        assert_eq!(f.overflowing_round_ties_even(), (I0F32::ZERO, false));
1045
1046        // 0
1047        let f = I0F32::from_bits(0);
1048        assert_eq!(f.to_num::<i32>(), 0);
1049        assert_eq!(f.round_to_zero(), 0);
1050        assert_eq!(f.overflowing_ceil(), (I0F32::ZERO, false));
1051        assert_eq!(f.overflowing_floor(), (I0F32::ZERO, false));
1052        assert_eq!(f.overflowing_round(), (I0F32::ZERO, false));
1053        assert_eq!(f.overflowing_round_ties_even(), (I0F32::ZERO, false));
1054
1055        // 0.5 - Δ
1056        let f = I0F32::from_bits((1 << 30) - 1 + (1 << 30));
1057        assert_eq!(f.to_num::<i32>(), 0);
1058        assert_eq!(f.round_to_zero(), 0);
1059        assert_eq!(f.overflowing_ceil(), (I0F32::ZERO, true));
1060        assert_eq!(f.overflowing_floor(), (I0F32::ZERO, false));
1061        assert_eq!(f.overflowing_round(), (I0F32::ZERO, false));
1062        assert_eq!(f.overflowing_round_ties_even(), (I0F32::ZERO, false));
1063
1064        // -1
1065        let f = I1F31::from_bits((-1) << 31);
1066        assert_eq!(f.to_num::<i32>(), -1);
1067        assert_eq!(f.round_to_zero(), -1);
1068        assert_eq!(f.overflowing_ceil(), (I1F31::NEG_ONE, false));
1069        assert_eq!(f.overflowing_floor(), (I1F31::NEG_ONE, false));
1070        assert_eq!(f.overflowing_round(), (I1F31::NEG_ONE, false));
1071        assert_eq!(f.overflowing_round_ties_even(), (I1F31::NEG_ONE, false));
1072
1073        // -0.5 - Δ
1074        let f = I1F31::from_bits(((-1) << 30) - 1);
1075        assert_eq!(f.to_num::<i32>(), -1);
1076        assert_eq!(f.round_to_zero(), 0);
1077        assert_eq!(f.overflowing_ceil(), (I1F31::ZERO, false));
1078        assert_eq!(f.overflowing_floor(), (I1F31::NEG_ONE, false));
1079        assert_eq!(f.overflowing_round(), (I1F31::NEG_ONE, false));
1080        assert_eq!(f.overflowing_round_ties_even(), (I1F31::NEG_ONE, false));
1081
1082        // -0.5
1083        let f = I1F31::from_bits((-1) << 30);
1084        assert_eq!(f.to_num::<i32>(), -1);
1085        assert_eq!(f.round_to_zero(), 0);
1086        assert_eq!(f.overflowing_ceil(), (I1F31::ZERO, false));
1087        assert_eq!(f.overflowing_floor(), (I1F31::NEG_ONE, false));
1088        assert_eq!(f.overflowing_round(), (I1F31::NEG_ONE, false));
1089        assert_eq!(f.overflowing_round_ties_even(), (I1F31::ZERO, false));
1090
1091        // -0.5 + Δ
1092        let f = I1F31::from_bits(((-1) << 30) + 1);
1093        assert_eq!(f.to_num::<i32>(), -1);
1094        assert_eq!(f.round_to_zero(), 0);
1095        assert_eq!(f.overflowing_ceil(), (I1F31::ZERO, false));
1096        assert_eq!(f.overflowing_floor(), (I1F31::NEG_ONE, false));
1097        assert_eq!(f.overflowing_round(), (I1F31::ZERO, false));
1098        assert_eq!(f.overflowing_round_ties_even(), (I1F31::ZERO, false));
1099
1100        // 0.5 - Δ
1101        let f = I1F31::from_bits((1 << 30) - 1);
1102        assert_eq!(f.to_num::<i32>(), 0);
1103        assert_eq!(f.round_to_zero(), 0);
1104        assert_eq!(f.overflowing_ceil(), (I1F31::NEG_ONE, true));
1105        assert_eq!(f.overflowing_floor(), (I1F31::ZERO, false));
1106        assert_eq!(f.overflowing_round(), (I1F31::ZERO, false));
1107        assert_eq!(f.overflowing_round_ties_even(), (I1F31::ZERO, false));
1108
1109        // 0.5
1110        let f = I1F31::from_bits(1 << 30);
1111        assert_eq!(f.to_num::<i32>(), 0);
1112        assert_eq!(f.round_to_zero(), 0);
1113        assert_eq!(f.overflowing_ceil(), (I1F31::NEG_ONE, true));
1114        assert_eq!(f.overflowing_floor(), (I1F31::ZERO, false));
1115        assert_eq!(f.overflowing_round(), (I1F31::NEG_ONE, true));
1116        assert_eq!(f.overflowing_round_ties_even(), (I1F31::ZERO, false));
1117
1118        // 0
1119        let f = I1F31::from_bits(0);
1120        assert_eq!(f.to_num::<i32>(), 0);
1121        assert_eq!(f.round_to_zero(), 0);
1122        assert_eq!(f.overflowing_ceil(), (I1F31::ZERO, false));
1123        assert_eq!(f.overflowing_floor(), (I1F31::ZERO, false));
1124        assert_eq!(f.overflowing_round(), (I1F31::ZERO, false));
1125        assert_eq!(f.overflowing_round_ties_even(), (I1F31::ZERO, false));
1126
1127        // 0.5 + Δ
1128        let f = I1F31::from_bits((1 << 30) + 1);
1129        assert_eq!(f.to_num::<i32>(), 0);
1130        assert_eq!(f.round_to_zero(), 0);
1131        assert_eq!(f.overflowing_ceil(), (I1F31::NEG_ONE, true));
1132        assert_eq!(f.overflowing_floor(), (I1F31::ZERO, false));
1133        assert_eq!(f.overflowing_round(), (I1F31::NEG_ONE, true));
1134        assert_eq!(f.overflowing_round_ties_even(), (I1F31::NEG_ONE, true));
1135
1136        // -3.5 - Δ
1137        let f = I16F16::from_bits(((-7) << 15) - 1);
1138        assert_eq!(f.to_num::<i32>(), -4);
1139        assert_eq!(f.round_to_zero(), -3);
1140        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(-3), false));
1141        assert_eq!(f.overflowing_floor(), (I16F16::from_num(-4), false));
1142        assert_eq!(f.overflowing_round(), (I16F16::from_num(-4), false));
1143        assert_eq!(
1144            f.overflowing_round_ties_even(),
1145            (I16F16::from_num(-4), false)
1146        );
1147
1148        // -3.5
1149        let f = I16F16::from_bits((-7) << 15);
1150        assert_eq!(f.to_num::<i32>(), -4);
1151        assert_eq!(f.round_to_zero(), -3);
1152        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(-3), false));
1153        assert_eq!(f.overflowing_floor(), (I16F16::from_num(-4), false));
1154        assert_eq!(f.overflowing_round(), (I16F16::from_num(-4), false));
1155        assert_eq!(
1156            f.overflowing_round_ties_even(),
1157            (I16F16::from_num(-4), false)
1158        );
1159
1160        // -3.5 + Δ
1161        let f = I16F16::from_bits(((-7) << 15) + 1);
1162        assert_eq!(f.to_num::<i32>(), -4);
1163        assert_eq!(f.round_to_zero(), -3);
1164        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(-3), false));
1165        assert_eq!(f.overflowing_floor(), (I16F16::from_num(-4), false));
1166        assert_eq!(f.overflowing_round(), (I16F16::from_num(-3), false));
1167        assert_eq!(
1168            f.overflowing_round_ties_even(),
1169            (I16F16::from_num(-3), false)
1170        );
1171
1172        // -2.5 - Δ
1173        let f = I16F16::from_bits(((-5) << 15) - 1);
1174        assert_eq!(f.to_num::<i32>(), -3);
1175        assert_eq!(f.round_to_zero(), -2);
1176        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(-2), false));
1177        assert_eq!(f.overflowing_floor(), (I16F16::from_num(-3), false));
1178        assert_eq!(f.overflowing_round(), (I16F16::from_num(-3), false));
1179        assert_eq!(
1180            f.overflowing_round_ties_even(),
1181            (I16F16::from_num(-3), false)
1182        );
1183
1184        // -2.5
1185        let f = I16F16::from_bits((-5) << 15);
1186        assert_eq!(f.to_num::<i32>(), -3);
1187        assert_eq!(f.round_to_zero(), -2);
1188        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(-2), false));
1189        assert_eq!(f.overflowing_floor(), (I16F16::from_num(-3), false));
1190        assert_eq!(f.overflowing_round(), (I16F16::from_num(-3), false));
1191        assert_eq!(
1192            f.overflowing_round_ties_even(),
1193            (I16F16::from_num(-2), false)
1194        );
1195
1196        // -2.5 + Δ
1197        let f = I16F16::from_bits(((-5) << 15) + 1);
1198        assert_eq!(f.to_num::<i32>(), -3);
1199        assert_eq!(f.round_to_zero(), -2);
1200        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(-2), false));
1201        assert_eq!(f.overflowing_floor(), (I16F16::from_num(-3), false));
1202        assert_eq!(f.overflowing_round(), (I16F16::from_num(-2), false));
1203        assert_eq!(
1204            f.overflowing_round_ties_even(),
1205            (I16F16::from_num(-2), false)
1206        );
1207
1208        // -1
1209        let f = I16F16::from_bits((-1) << 16);
1210        assert_eq!(f.to_num::<i32>(), -1);
1211        assert_eq!(f.round_to_zero(), -1);
1212        assert_eq!(f.overflowing_ceil(), (I16F16::NEG_ONE, false));
1213        assert_eq!(f.overflowing_floor(), (I16F16::NEG_ONE, false));
1214        assert_eq!(f.overflowing_round(), (I16F16::NEG_ONE, false));
1215        assert_eq!(f.overflowing_round_ties_even(), (I16F16::NEG_ONE, false));
1216
1217        // -0.5 - Δ
1218        let f = I16F16::from_bits(((-1) << 15) - 1);
1219        assert_eq!(f.to_num::<i32>(), -1);
1220        assert_eq!(f.round_to_zero(), 0);
1221        assert_eq!(f.overflowing_ceil(), (I16F16::ZERO, false));
1222        assert_eq!(f.overflowing_floor(), (I16F16::NEG_ONE, false));
1223        assert_eq!(f.overflowing_round(), (I16F16::NEG_ONE, false));
1224        assert_eq!(f.overflowing_round_ties_even(), (I16F16::NEG_ONE, false));
1225
1226        // -0.5
1227        let f = I16F16::from_bits((-1) << 15);
1228        assert_eq!(f.to_num::<i32>(), -1);
1229        assert_eq!(f.round_to_zero(), 0);
1230        assert_eq!(f.overflowing_ceil(), (I16F16::ZERO, false));
1231        assert_eq!(f.overflowing_floor(), (I16F16::NEG_ONE, false));
1232        assert_eq!(f.overflowing_round(), (I16F16::NEG_ONE, false));
1233        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ZERO, false));
1234
1235        // -0.5 + Δ
1236        let f = I16F16::from_bits(((-1) << 15) + 1);
1237        assert_eq!(f.to_num::<i32>(), -1);
1238        assert_eq!(f.round_to_zero(), 0);
1239        assert_eq!(f.overflowing_ceil(), (I16F16::ZERO, false));
1240        assert_eq!(f.overflowing_floor(), (I16F16::NEG_ONE, false));
1241        assert_eq!(f.overflowing_round(), (I16F16::ZERO, false));
1242        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ZERO, false));
1243
1244        // 0
1245        let f = I16F16::from_bits(0);
1246        assert_eq!(f.to_num::<i32>(), 0);
1247        assert_eq!(f.round_to_zero(), 0);
1248        assert_eq!(f.overflowing_ceil(), (I16F16::ZERO, false));
1249        assert_eq!(f.overflowing_floor(), (I16F16::ZERO, false));
1250        assert_eq!(f.overflowing_round(), (I16F16::ZERO, false));
1251        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ZERO, false));
1252
1253        // 0.5 - Δ
1254        let f = I16F16::from_bits((1 << 15) - 1);
1255        assert_eq!(f.to_num::<i32>(), 0);
1256        assert_eq!(f.round_to_zero(), 0);
1257        assert_eq!(f.overflowing_ceil(), (I16F16::ONE, false));
1258        assert_eq!(f.overflowing_floor(), (I16F16::ZERO, false));
1259        assert_eq!(f.overflowing_round(), (I16F16::ZERO, false));
1260        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ZERO, false));
1261
1262        // 0.5
1263        let f = I16F16::from_bits(1 << 15);
1264        assert_eq!(f.to_num::<i32>(), 0);
1265        assert_eq!(f.round_to_zero(), 0);
1266        assert_eq!(f.overflowing_ceil(), (I16F16::ONE, false));
1267        assert_eq!(f.overflowing_floor(), (I16F16::ZERO, false));
1268        assert_eq!(f.overflowing_round(), (I16F16::ONE, false));
1269        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ZERO, false));
1270
1271        // 0.5 + Δ
1272        let f = I16F16::from_bits((1 << 15) + 1);
1273        assert_eq!(f.to_num::<i32>(), 0);
1274        assert_eq!(f.round_to_zero(), 0);
1275        assert_eq!(f.overflowing_ceil(), (I16F16::ONE, false));
1276        assert_eq!(f.overflowing_floor(), (I16F16::ZERO, false));
1277        assert_eq!(f.overflowing_round(), (I16F16::ONE, false));
1278        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ONE, false));
1279
1280        // 1
1281        let f = I16F16::from_bits(1 << 16);
1282        assert_eq!(f.to_num::<i32>(), 1);
1283        assert_eq!(f.round_to_zero(), 1);
1284        assert_eq!(f.overflowing_ceil(), (I16F16::ONE, false));
1285        assert_eq!(f.overflowing_floor(), (I16F16::ONE, false));
1286        assert_eq!(f.overflowing_round(), (I16F16::ONE, false));
1287        assert_eq!(f.overflowing_round_ties_even(), (I16F16::ONE, false));
1288
1289        // 2.5 - Δ
1290        let f = I16F16::from_bits((5 << 15) - 1);
1291        assert_eq!(f.to_num::<i32>(), 2);
1292        assert_eq!(f.round_to_zero(), 2);
1293        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(3), false));
1294        assert_eq!(f.overflowing_floor(), (I16F16::from_num(2), false));
1295        assert_eq!(f.overflowing_round(), (I16F16::from_num(2), false));
1296        assert_eq!(
1297            f.overflowing_round_ties_even(),
1298            (I16F16::from_num(2), false)
1299        );
1300
1301        // 2.5
1302        let f = I16F16::from_bits(5 << 15);
1303        assert_eq!(f.to_num::<i32>(), 2);
1304        assert_eq!(f.round_to_zero(), 2);
1305        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(3), false));
1306        assert_eq!(f.overflowing_floor(), (I16F16::from_num(2), false));
1307        assert_eq!(f.overflowing_round(), (I16F16::from_num(3), false));
1308        assert_eq!(
1309            f.overflowing_round_ties_even(),
1310            (I16F16::from_num(2), false)
1311        );
1312
1313        // 2.5 + Δ
1314        let f = I16F16::from_bits((5 << 15) + 1);
1315        assert_eq!(f.to_num::<i32>(), 2);
1316        assert_eq!(f.round_to_zero(), 2);
1317        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(3), false));
1318        assert_eq!(f.overflowing_floor(), (I16F16::from_num(2), false));
1319        assert_eq!(f.overflowing_round(), (I16F16::from_num(3), false));
1320        assert_eq!(
1321            f.overflowing_round_ties_even(),
1322            (I16F16::from_num(3), false)
1323        );
1324
1325        // 3.5 - Δ
1326        let f = I16F16::from_bits((7 << 15) - 1);
1327        assert_eq!(f.to_num::<i32>(), 3);
1328        assert_eq!(f.round_to_zero(), 3);
1329        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(4), false));
1330        assert_eq!(f.overflowing_floor(), (I16F16::from_num(3), false));
1331        assert_eq!(f.overflowing_round(), (I16F16::from_num(3), false));
1332        assert_eq!(
1333            f.overflowing_round_ties_even(),
1334            (I16F16::from_num(3), false)
1335        );
1336
1337        // 3.5
1338        let f = I16F16::from_bits(7 << 15);
1339        assert_eq!(f.to_num::<i32>(), 3);
1340        assert_eq!(f.round_to_zero(), 3);
1341        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(4), false));
1342        assert_eq!(f.overflowing_floor(), (I16F16::from_num(3), false));
1343        assert_eq!(f.overflowing_round(), (I16F16::from_num(4), false));
1344        assert_eq!(
1345            f.overflowing_round_ties_even(),
1346            (I16F16::from_num(4), false)
1347        );
1348
1349        // 3.5 + Δ
1350        let f = I16F16::from_bits((7 << 15) + 1);
1351        assert_eq!(f.to_num::<i32>(), 3);
1352        assert_eq!(f.round_to_zero(), 3);
1353        assert_eq!(f.overflowing_ceil(), (I16F16::from_num(4), false));
1354        assert_eq!(f.overflowing_floor(), (I16F16::from_num(3), false));
1355        assert_eq!(f.overflowing_round(), (I16F16::from_num(4), false));
1356        assert_eq!(
1357            f.overflowing_round_ties_even(),
1358            (I16F16::from_num(4), false)
1359        );
1360    }
1361
1362    #[test]
1363    fn rounding_unsigned() {
1364        // 0
1365        let f = U0F32::from_bits(0);
1366        assert_eq!(f.to_num::<i32>(), 0);
1367        assert_eq!(f.round_to_zero(), 0);
1368        assert_eq!(f.overflowing_ceil(), (U0F32::ZERO, false));
1369        assert_eq!(f.overflowing_floor(), (U0F32::ZERO, false));
1370        assert_eq!(f.overflowing_round(), (U0F32::ZERO, false));
1371        assert_eq!(f.overflowing_round_ties_even(), (U0F32::ZERO, false));
1372
1373        // 0.5 - Δ
1374        let f = U0F32::from_bits((1 << 31) - 1);
1375        assert_eq!(f.to_num::<i32>(), 0);
1376        assert_eq!(f.round_to_zero(), 0);
1377        assert_eq!(f.overflowing_ceil(), (U0F32::ZERO, true));
1378        assert_eq!(f.overflowing_floor(), (U0F32::ZERO, false));
1379        assert_eq!(f.overflowing_round(), (U0F32::ZERO, false));
1380        assert_eq!(f.overflowing_round_ties_even(), (U0F32::ZERO, false));
1381
1382        // 0.5
1383        let f = U0F32::from_bits(1 << 31);
1384        assert_eq!(f.to_num::<i32>(), 0);
1385        assert_eq!(f.round_to_zero(), 0);
1386        assert_eq!(f.overflowing_ceil(), (U0F32::ZERO, true));
1387        assert_eq!(f.overflowing_floor(), (U0F32::ZERO, false));
1388        assert_eq!(f.overflowing_round(), (U0F32::ZERO, true));
1389        assert_eq!(f.overflowing_round_ties_even(), (U0F32::ZERO, false));
1390
1391        // 0.5 + Δ
1392        let f = U0F32::from_bits((1 << 31) + 1);
1393        assert_eq!(f.to_num::<i32>(), 0);
1394        assert_eq!(f.round_to_zero(), 0);
1395        assert_eq!(f.overflowing_ceil(), (U0F32::ZERO, true));
1396        assert_eq!(f.overflowing_floor(), (U0F32::ZERO, false));
1397        assert_eq!(f.overflowing_round(), (U0F32::ZERO, true));
1398        assert_eq!(f.overflowing_round_ties_even(), (U0F32::ZERO, true));
1399
1400        // 0
1401        let f = U16F16::from_bits(0);
1402        assert_eq!(f.to_num::<i32>(), 0);
1403        assert_eq!(f.round_to_zero(), 0);
1404        assert_eq!(f.overflowing_ceil(), (U16F16::ZERO, false));
1405        assert_eq!(f.overflowing_floor(), (U16F16::ZERO, false));
1406        assert_eq!(f.overflowing_round(), (U16F16::ZERO, false));
1407        assert_eq!(f.overflowing_round_ties_even(), (U16F16::ZERO, false));
1408
1409        // 0.5 - Δ
1410        let f = U16F16::from_bits((1 << 15) - 1);
1411        assert_eq!(f.to_num::<i32>(), 0);
1412        assert_eq!(f.round_to_zero(), 0);
1413        assert_eq!(f.overflowing_ceil(), (U16F16::ONE, false));
1414        assert_eq!(f.overflowing_floor(), (U16F16::ZERO, false));
1415        assert_eq!(f.overflowing_round(), (U16F16::ZERO, false));
1416        assert_eq!(f.overflowing_round_ties_even(), (U16F16::ZERO, false));
1417
1418        // 0.5
1419        let f = U16F16::from_bits(1 << 15);
1420        assert_eq!(f.to_num::<i32>(), 0);
1421        assert_eq!(f.round_to_zero(), 0);
1422        assert_eq!(f.overflowing_ceil(), (U16F16::ONE, false));
1423        assert_eq!(f.overflowing_floor(), (U16F16::ZERO, false));
1424        assert_eq!(f.overflowing_round(), (U16F16::ONE, false));
1425        assert_eq!(f.overflowing_round_ties_even(), (U16F16::ZERO, false));
1426
1427        // 0.5 + Δ
1428        let f = U16F16::from_bits((1 << 15) + 1);
1429        assert_eq!(f.to_num::<i32>(), 0);
1430        assert_eq!(f.round_to_zero(), 0);
1431        assert_eq!(f.overflowing_ceil(), (U16F16::ONE, false));
1432        assert_eq!(f.overflowing_floor(), (U16F16::ZERO, false));
1433        assert_eq!(f.overflowing_round(), (U16F16::ONE, false));
1434        assert_eq!(f.overflowing_round_ties_even(), (U16F16::ONE, false));
1435
1436        // 1
1437        let f = U16F16::from_bits(1 << 16);
1438        assert_eq!(f.to_num::<i32>(), 1);
1439        assert_eq!(f.round_to_zero(), 1);
1440        assert_eq!(f.overflowing_ceil(), (U16F16::ONE, false));
1441        assert_eq!(f.overflowing_floor(), (U16F16::ONE, false));
1442        assert_eq!(f.overflowing_round(), (U16F16::ONE, false));
1443        assert_eq!(f.overflowing_round_ties_even(), (U16F16::ONE, false));
1444
1445        // 2.5 - Δ
1446        let f = U16F16::from_bits((5 << 15) - 1);
1447        assert_eq!(f.to_num::<i32>(), 2);
1448        assert_eq!(f.round_to_zero(), 2);
1449        assert_eq!(f.overflowing_ceil(), (U16F16::from_num(3), false));
1450        assert_eq!(f.overflowing_floor(), (U16F16::from_num(2), false));
1451        assert_eq!(f.overflowing_round(), (U16F16::from_num(2), false));
1452        assert_eq!(
1453            f.overflowing_round_ties_even(),
1454            (U16F16::from_num(2), false)
1455        );
1456
1457        // 2.5
1458        let f = U16F16::from_bits(5 << 15);
1459        assert_eq!(f.to_num::<i32>(), 2);
1460        assert_eq!(f.round_to_zero(), 2);
1461        assert_eq!(f.overflowing_ceil(), (U16F16::from_num(3), false));
1462        assert_eq!(f.overflowing_floor(), (U16F16::from_num(2), false));
1463        assert_eq!(f.overflowing_round(), (U16F16::from_num(3), false));
1464        assert_eq!(
1465            f.overflowing_round_ties_even(),
1466            (U16F16::from_num(2), false)
1467        );
1468
1469        // 2.5 + Δ
1470        let f = U16F16::from_bits((5 << 15) + 1);
1471        assert_eq!(f.to_num::<i32>(), 2);
1472        assert_eq!(f.round_to_zero(), 2);
1473        assert_eq!(f.overflowing_ceil(), (U16F16::from_num(3), false));
1474        assert_eq!(f.overflowing_floor(), (U16F16::from_num(2), false));
1475        assert_eq!(f.overflowing_round(), (U16F16::from_num(3), false));
1476        assert_eq!(
1477            f.overflowing_round_ties_even(),
1478            (U16F16::from_num(3), false)
1479        );
1480
1481        // 3.5 - Δ
1482        let f = U16F16::from_bits((7 << 15) - 1);
1483        assert_eq!(f.to_num::<i32>(), 3);
1484        assert_eq!(f.round_to_zero(), 3);
1485        assert_eq!(f.overflowing_ceil(), (U16F16::from_num(4), false));
1486        assert_eq!(f.overflowing_floor(), (U16F16::from_num(3), false));
1487        assert_eq!(f.overflowing_round(), (U16F16::from_num(3), false));
1488        assert_eq!(
1489            f.overflowing_round_ties_even(),
1490            (U16F16::from_num(3), false)
1491        );
1492
1493        // 3.5
1494        let f = U16F16::from_bits(7 << 15);
1495        assert_eq!(f.to_num::<i32>(), 3);
1496        assert_eq!(f.round_to_zero(), 3);
1497        assert_eq!(f.overflowing_ceil(), (U16F16::from_num(4), false));
1498        assert_eq!(f.overflowing_floor(), (U16F16::from_num(3), false));
1499        assert_eq!(f.overflowing_round(), (U16F16::from_num(4), false));
1500        assert_eq!(
1501            f.overflowing_round_ties_even(),
1502            (U16F16::from_num(4), false)
1503        );
1504
1505        // 3.5 + Δ
1506        let f = U16F16::from_bits((7 << 15) + 1);
1507        assert_eq!(f.to_num::<i32>(), 3);
1508        assert_eq!(f.round_to_zero(), 3);
1509        assert_eq!(f.overflowing_ceil(), (U16F16::from_num(4), false));
1510        assert_eq!(f.overflowing_floor(), (U16F16::from_num(3), false));
1511        assert_eq!(f.overflowing_round(), (U16F16::from_num(4), false));
1512        assert_eq!(
1513            f.overflowing_round_ties_even(),
1514            (U16F16::from_num(4), false)
1515        );
1516    }
1517
1518    #[test]
1519    fn reciprocals() {
1520        // 4/3 wraps to 1/3 = 0x0.5555_5555
1521        assert_eq!(
1522            U0F32::from_num(0.75).overflowing_recip(),
1523            (U0F32::from_bits(0x5555_5555), true)
1524        );
1525        // 8/3 wraps to 2/3 = 0x0.AAAA_AAAA
1526        assert_eq!(
1527            U0F32::from_num(0.375).overflowing_recip(),
1528            (U0F32::from_bits(0xAAAA_AAAA), true)
1529        );
1530
1531        // 8/3 wraps to 2/3 = 0x0.AAAA_AAAA, which is -0x0.5555_5556
1532        assert_eq!(
1533            I0F32::from_num(0.375).overflowing_recip(),
1534            (I0F32::from_bits(-0x5555_5556), true)
1535        );
1536        assert_eq!(
1537            I0F32::from_num(-0.375).overflowing_recip(),
1538            (I0F32::from_bits(0x5555_5556), true)
1539        );
1540        // -2 wraps to 0
1541        assert_eq!(
1542            I0F32::from_num(-0.5).overflowing_recip(),
1543            (I0F32::ZERO, true)
1544        );
1545
1546        // 8/3 wraps to 2/3 = 0x0.AAAA_AAAA (bits 0x5555_5555)
1547        assert_eq!(
1548            I1F31::from_num(0.375).overflowing_recip(),
1549            (I1F31::from_bits(0x5555_5555), true)
1550        );
1551        assert_eq!(
1552            I1F31::from_num(-0.375).overflowing_recip(),
1553            (I1F31::from_bits(-0x5555_5555), true)
1554        );
1555        // 4/3 = 0x1.5555_5554 (bits 0xAAAA_AAAA, or -0x5555_5556)
1556        assert_eq!(
1557            I1F31::from_num(0.75).overflowing_recip(),
1558            (I1F31::from_bits(-0x5555_5556), true)
1559        );
1560        assert_eq!(
1561            I1F31::from_num(-0.75).overflowing_recip(),
1562            (I1F31::from_bits(0x5555_5556), true)
1563        );
1564        // -2 wraps to 0
1565        assert_eq!(
1566            I1F31::from_num(-0.5).overflowing_recip(),
1567            (I1F31::ZERO, true)
1568        );
1569        // -1 does not overflow
1570        assert_eq!(I1F31::NEG_ONE.overflowing_recip(), (I1F31::NEG_ONE, false));
1571    }
1572
1573    #[test]
1574    fn wide_mul_mixed() {
1575        // +7FFF.FFFF * 7FFF.FFFF = +3FFF_FFFE.0000_0001
1576        // 7FFF.FFFF * 7FFF.FFFF = 3FFF_FFFE.0000_0001
1577        // +7FFF.FFFF * +7FFF.FFFF = +3FFF_FFFE.0000_0001
1578        let s = I16F16::MAX;
1579        let u = U16F16::MAX >> 1u32;
1580        let t = U16F16::from_bits(s.to_bits() as u32);
1581        let v = I16F16::from_bits(u.to_bits() as i32);
1582        assert_eq!(s.wide_mul_unsigned(u).to_bits(), 0x3FFF_FFFF_0000_0001);
1583        assert_eq!(t.wide_mul(u).to_bits(), 0x3FFF_FFFF_0000_0001);
1584        assert_eq!(s.wide_mul(v).to_bits(), 0x3FFF_FFFF_0000_0001);
1585        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1586        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1587        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1588
1589        // +7FFF.FFFF * 8000.0000 = +3FFF_FFFF.8000_0000
1590        // 7FFF.FFFF * 8000.0000 = 3FFF_FFFF.8000_0000
1591        // +7FFF.FFFF * -8000.0000 = -3FFF_FFFF.8000_0000
1592        let s = I16F16::MAX;
1593        let u = !(U16F16::MAX >> 1u32);
1594        let t = U16F16::from_bits(s.to_bits() as u32);
1595        let v = I16F16::from_bits(u.to_bits() as i32);
1596        assert_eq!(s.wide_mul_unsigned(u).to_bits(), 0x3FFF_FFFF_8000_0000);
1597        assert_eq!(t.wide_mul(u).to_bits(), 0x3FFF_FFFF_8000_0000);
1598        assert_eq!(s.wide_mul(v).to_bits(), -0x3FFF_FFFF_8000_0000);
1599        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1600        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1601        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1602
1603        // +7FFF.FFFF * FFFF.FFFF = +7FFF_FFFE.8000_0001
1604        // 7FFF.FFFF * FFFF.FFFF = 7FFF_FFFE.8000_0001
1605        // +7FFF.FFFF * -0000.0001 = -0000_0000.7FFF_FFFF
1606        let s = I16F16::MAX;
1607        let u = U16F16::MAX;
1608        let t = U16F16::from_bits(s.to_bits() as u32);
1609        let v = I16F16::from_bits(u.to_bits() as i32);
1610        assert_eq!(s.wide_mul_unsigned(u).to_bits(), 0x7FFF_FFFE_8000_0001);
1611        assert_eq!(t.wide_mul(u).to_bits(), 0x7FFF_FFFE_8000_0001);
1612        assert_eq!(s.wide_mul(v).to_bits(), -0x0000_0000_7FFF_FFFF);
1613        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1614        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1615        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1616
1617        // -8000.0000 * 7FFF.FFFF = -3FFF_FFFF.8000_0000
1618        // 8000.0000 * 7FFF.FFFF = 3FFF_FFFF.8000_0000
1619        // -8000.0000 * +7FFF.FFFF = -3FFF_FFFF.8000_0000
1620        let s = I16F16::MIN;
1621        let u = U16F16::MAX >> 1u32;
1622        let t = U16F16::from_bits(s.to_bits() as u32);
1623        let v = I16F16::from_bits(u.to_bits() as i32);
1624        assert_eq!(s.wide_mul_unsigned(u).to_bits(), -0x3FFF_FFFF_8000_0000);
1625        assert_eq!(t.wide_mul(u).to_bits(), 0x3FFF_FFFF_8000_0000);
1626        assert_eq!(s.wide_mul(v).to_bits(), -0x3FFF_FFFF_8000_0000);
1627        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1628        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1629        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1630
1631        // -8000.0000 * 8000.0000 = -4000_0000.0000_0000
1632        // 8000.0000 * 8000.0000 = 4000_0000.0000_0000
1633        // -8000.0000 * -8000.0000 = +4000_0000.0000_0000
1634        let s = I16F16::MIN;
1635        let u = !(U16F16::MAX >> 1u32);
1636        let t = U16F16::from_bits(s.to_bits() as u32);
1637        let v = I16F16::from_bits(u.to_bits() as i32);
1638        assert_eq!(s.wide_mul_unsigned(u).to_bits(), -0x4000_0000_0000_0000);
1639        assert_eq!(t.wide_mul(u).to_bits(), 0x4000_0000_0000_0000);
1640        assert_eq!(s.wide_mul(v).to_bits(), 0x4000_0000_0000_0000);
1641        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1642        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1643        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1644
1645        // -8000.0000 * FFFF.FFFF = -7FFF_FFFF.8000_0000
1646        // 8000.0000 * FFFF.FFFF = 7FFF_FFFF.8000_0000
1647        // -8000.0000 * -0000.0001 = +0000_0000.8000_0000
1648        let s = I16F16::MIN;
1649        let u = U16F16::MAX;
1650        let t = U16F16::from_bits(s.to_bits() as u32);
1651        let v = I16F16::from_bits(u.to_bits() as i32);
1652        assert_eq!(s.wide_mul_unsigned(u).to_bits(), -0x7FFF_FFFF_8000_0000);
1653        assert_eq!(t.wide_mul(u).to_bits(), 0x7FFF_FFFF_8000_0000);
1654        assert_eq!(s.wide_mul(v).to_bits(), 0x8000_0000);
1655        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1656        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1657        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1658
1659        // -0000.0001 * 7FFF.FFFF = -0000_0000.7FFF_FFFF
1660        // FFFF.FFFF * 7FFF.FFFF = 7FFF_FFFE.8000_0001
1661        // -0000.0001 * +7FFF.FFFF = -0000_0000.7FFF_FFFF
1662        let s = -I16F16::DELTA;
1663        let u = U16F16::MAX >> 1u32;
1664        let t = U16F16::from_bits(s.to_bits() as u32);
1665        let v = I16F16::from_bits(u.to_bits() as i32);
1666        assert_eq!(s.wide_mul_unsigned(u).to_bits(), -0x0000_0000_7FFF_FFFF);
1667        assert_eq!(t.wide_mul(u).to_bits(), 0x7FFF_FFFE_8000_0001);
1668        assert_eq!(s.wide_mul(v).to_bits(), -0x0000_0000_7FFF_FFFF);
1669        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1670        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1671        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1672
1673        // -0000.0001 * 8000.0000 = -0000_0000.8000_0000
1674        // FFFF.FFFF * 8000.0000 = 7FFF_FFFF.8000_0000
1675        // -0000.0001 * -8000.0000 = +0000_0000.8000_0000
1676        let s = -I16F16::DELTA;
1677        let u = !(U16F16::MAX >> 1u32);
1678        let t = U16F16::from_bits(s.to_bits() as u32);
1679        let v = I16F16::from_bits(u.to_bits() as i32);
1680        assert_eq!(s.wide_mul_unsigned(u).to_bits(), -0x0000_0000_8000_0000);
1681        assert_eq!(t.wide_mul(u).to_bits(), 0x7FFF_FFFF_8000_0000);
1682        assert_eq!(s.wide_mul(v).to_bits(), 0x0000_0000_8000_0000);
1683        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1684        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1685        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1686
1687        // -0000.0001 * FFFF.FFFF = -0000_0000.FFFF_FFFF
1688        // FFFF.FFFF * FFFF.FFFF = FFFF_FFFE.0000_0001
1689        // -0000.0001 * -0000.0001 = +0000_0000.0000_0001
1690        let s = -I16F16::DELTA;
1691        let u = U16F16::MAX;
1692        let t = U16F16::from_bits(s.to_bits() as u32);
1693        let v = I16F16::from_bits(u.to_bits() as i32);
1694        assert_eq!(s.wide_mul_unsigned(u).to_bits(), -0x0000_0000_FFFF_FFFF);
1695        assert_eq!(t.wide_mul(u).to_bits(), 0xFFFF_FFFE_0000_0001);
1696        assert_eq!(s.wide_mul(v).to_bits(), 0x0000_0000_0000_0001);
1697        assert_eq!(s.wide_mul_unsigned(u), u.wide_mul_signed(s));
1698        assert_eq!(t.wide_mul(u), u.wide_mul(t));
1699        assert_eq!(s.wide_mul(v), v.wide_mul(s));
1700    }
1701}