fixed/
lib.rs

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