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