substrate_fixed/traits.rs
1// Copyright © 2018–2019 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/*!
17This module contains traits.
18*/
19
20use crate::{
21 helpers::{FloatHelper, FloatKind, FromFloatHelper, IntHelper, Sealed, Widest},
22 types::extra::{LeEqU128, LeEqU16, LeEqU32, LeEqU64, LeEqU8, Unsigned},
23 FixedI128, FixedI16, FixedI32, FixedI64, FixedI8, FixedU128, FixedU16, FixedU32, FixedU64,
24 FixedU8, ParseFixedError,
25};
26use core::{
27 fmt::{Binary, Debug, Display, LowerHex, Octal, UpperHex},
28 hash::Hash,
29 mem,
30 ops::{
31 Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div,
32 DivAssign, Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,
33 SubAssign,
34 },
35 str::FromStr,
36};
37#[cfg(feature = "f16")]
38use half::{bf16, f16};
39#[cfg(feature = "serde")]
40use serde::{de::Deserialize, ser::Serialize};
41
42macro_rules! comment_features {
43 ($comment:expr) => {
44 #[cfg(all(not(feature = "f16"), not(feature = "serde")))]
45 doc_comment! {
46 $comment;
47 pub trait FixedOptionalFeatures {}
48 }
49 #[cfg(all(feature = "f16", not(feature = "serde")))]
50 doc_comment! {
51 $comment;
52 pub trait FixedOptionalFeatures: PartialOrd<f16> + PartialOrd<bf16> {}
53 }
54 #[cfg(all(not(feature = "f16"), feature = "serde"))]
55 doc_comment! {
56 $comment;
57 pub trait FixedOptionalFeatures: Serialize + for<'de> Deserialize<'de> {}
58 }
59 #[cfg(all(feature = "f16", feature = "serde"))]
60 doc_comment! {
61 $comment;
62 pub trait FixedOptionalFeatures
63 where
64 Self: PartialOrd<f16> + PartialOrd<bf16>,
65 Self: Serialize + for<'de> Deserialize<'de>,
66 {
67 }
68 }
69 };
70}
71
72comment_features! {
73 "This trait is used to provide supertraits to the [`Fixed`] trait
74depending on the crate’s [optional features].
75
76 1. If the `f16` feature is enabled,
77 <code>[PartialOrd][`PartialOrd`]<[f16][`f16`]></code> and
78 <code>[PartialOrd][`PartialOrd`]<[bf16][`bf16`]></code> are
79 supertraits of [`Fixed`].
80 2. If the `serde` feature is enabled, [`Serialize`] and
81 [`Deserialize`] are supertraits of [`Fixed`].
82
83[`Deserialize`]: https://docs.rs/serde/^1/serde/de/trait.Deserialize.html
84[`Fixed`]: trait.Fixed.html
85[`PartialOrd`]: https://doc.rust-lang.org/nightly/core/cmp/trait.PartialOrd.html
86[`Serialize`]: https://docs.rs/serde/^1/serde/ser/trait.Serialize.html
87[`bf16`]: https://docs.rs/half/^1/half/struct.bf16.html
88[`f16`]: https://docs.rs/half/^1/half/struct.f16.html
89[optional features]: ../index.html#optional-features
90"
91}
92
93/// This trait provides methods common to all fixed-point numbers.
94///
95/// It can be helpful when writing generic code that makes use of
96/// fixed-point numbers. For methods only available on signed
97/// fixed-point numbers, use the [`FixedSigned`] trait instead, and
98/// for methods only available on unsigned fixed-point numbers, use
99/// [`FixedUnsigned`].
100///
101/// This trait is sealed and cannot be implemented for more types; it
102/// is implemented for [`FixedI8`], [`FixedI16`], [`FixedI32`],
103/// [`FixedI64`], [`FixedI128`], [`FixedU8`], [`FixedU16`],
104/// [`FixedU32`], [`FixedU64`], and [`FixedU128`].
105///
106/// # Examples
107///
108/// ```rust
109/// use substrate_fixed::{
110/// traits::Fixed,
111/// types::{I8F8, I16F16},
112/// };
113///
114/// fn checked_add_twice<F: Fixed>(lhs: F, rhs: F) -> Option<F> {
115/// lhs.checked_add(rhs)?.checked_add(rhs)
116/// }
117///
118/// let val1 = checked_add_twice(I8F8::from_num(5), Fixed::from_num(1.75));
119/// assert_eq!(val1, Some(Fixed::from_num(8.5)));
120/// // can use with different fixed-point type
121/// let val2 = checked_add_twice(I16F16::from_num(5), Fixed::from_num(1.75));
122/// assert_eq!(val2, Some(Fixed::from_num(8.5)));
123/// ```
124///
125/// The following example fails to compile, since the compiler cannot
126/// infer that 500 in the `checked_mul_int` call is of type `F::Bits`.
127///
128/// ```compile_fail
129/// use substrate_fixed::traits::Fixed;
130///
131/// fn checked_add_times_500<F: Fixed>(lhs: F, rhs: F) -> Option<F> {
132/// rhs.checked_mul_int(500)?.checked_add(lhs)
133/// }
134/// ```
135///
136/// One way to fix this is to add a trait bound indicating that any
137/// [`u16`] (which can represent 500) can be converted into `F::Bits`.
138///
139/// ```rust
140/// use substrate_fixed::{traits::Fixed, types::U12F4};
141///
142/// fn checked_add_times_500<F: Fixed>(lhs: F, rhs: F) -> Option<F>
143/// where
144/// u16: Into<F::Bits>,
145/// {
146/// rhs.checked_mul_int(500.into())?.checked_add(lhs)
147/// }
148///
149/// let val = checked_add_times_500(U12F4::from_num(0.25), Fixed::from_num(1.5));
150/// assert_eq!(val, Some(Fixed::from_num(750.25)));
151/// ```
152///
153/// While this works in most cases, [`u16`] cannot be converted to
154/// [`i16`], even if the value 500 does fit in [`i16`], so that the
155/// following example would fail to compile.
156///
157/// ```compile_fail
158/// use substrate_fixed::{traits::Fixed, types::I12F4};
159///
160/// fn checked_add_times_500<F: Fixed>(lhs: F, rhs: F) -> Option<F>
161/// where
162/// u16: Into<F::Bits>,
163/// {
164/// rhs.checked_mul_int(500.into())?.checked_add(lhs)
165/// }
166///
167/// // I12F4::Bits is i16, and u16 does not implement Into<i16>
168/// let val = checked_add_times_500(I12F4::from_num(0.25), Fixed::from_num(1.5));
169/// # let _ = val;
170/// ```
171///
172/// We can use [`TryFrom`] to fix this, as we know that
173/// `F::Bits::try_from(500_u16)` will work for both [`u16`] and
174/// [`i16`]. (The function will always return [`None`] when `F::Bits`
175/// is [`u8`] or [`i8`].)
176///
177/// ```rust
178/// use substrate_fixed::{traits::Fixed, types::I12F4};
179/// use core::convert::TryInto;
180///
181/// fn checked_add_times_500<F: Fixed>(lhs: F, rhs: F) -> Option<F>
182/// where
183/// u16: TryInto<F::Bits>,
184/// {
185/// rhs.checked_mul_int(500.try_into().ok()?)?.checked_add(lhs)
186/// }
187///
188/// let val = checked_add_times_500(I12F4::from_num(0.25), Fixed::from_num(1.5));
189/// assert_eq!(val, Some(Fixed::from_num(750.25)));
190/// ```
191///
192/// [`FixedI128`]: ../struct.FixedI128.html
193/// [`FixedI16`]: ../struct.FixedI16.html
194/// [`FixedI32`]: ../struct.FixedI32.html
195/// [`FixedI64`]: ../struct.FixedI64.html
196/// [`FixedI8`]: ../struct.FixedI8.html
197/// [`FixedSigned`]: trait.FixedSigned.html
198/// [`FixedU128`]: ../struct.FixedU128.html
199/// [`FixedU16`]: ../struct.FixedU16.html
200/// [`FixedU32`]: ../struct.FixedU32.html
201/// [`FixedU64`]: ../struct.FixedU64.html
202/// [`FixedU8`]: ../struct.FixedU8.html
203/// [`FixedUnsigned`]: trait.FixedUnsigned.html
204/// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
205/// [`TryFrom`]: https://doc.rust-lang.org/nightly/core/convert/trait.TryFrom.html
206/// [`i16`]: https://doc.rust-lang.org/nightly/std/primitive.i16.html
207/// [`i8`]: https://doc.rust-lang.org/nightly/std/primitive.i8.html
208/// [`u16`]: https://doc.rust-lang.org/nightly/std/primitive.u16.html
209/// [`u8`]: https://doc.rust-lang.org/nightly/std/primitive.u8.html
210pub trait Fixed
211where
212 Self: Copy + Default + Hash + Ord,
213 Self: Debug + Display + Binary + Octal + LowerHex + UpperHex,
214 Self: FromStr<Err = ParseFixedError>,
215 Self: FromFixed + ToFixed,
216 Self: Add<Output = Self> + AddAssign + Sub<Output = Self> + SubAssign,
217 Self: Mul<Output = Self> + MulAssign + Div<Output = Self> + DivAssign,
218 Self: Rem<Output = Self> + RemAssign,
219 Self: Mul<<Self as Fixed>::Bits, Output = Self> + MulAssign<<Self as Fixed>::Bits>,
220 Self: Div<<Self as Fixed>::Bits, Output = Self> + DivAssign<<Self as Fixed>::Bits>,
221 Self: Rem<<Self as Fixed>::Bits, Output = Self> + RemAssign<<Self as Fixed>::Bits>,
222 Self: Not<Output = Self> + BitAnd<Output = Self> + BitAndAssign,
223 Self: BitOr<Output = Self> + BitOrAssign + BitXor<Output = Self> + BitXorAssign,
224 Self: Shl<u32, Output = Self> + ShlAssign<u32> + Shr<u32, Output = Self> + ShrAssign<u32>,
225 Self: PartialOrd<i8> + PartialOrd<i16> + PartialOrd<i32>,
226 Self: PartialOrd<i64> + PartialOrd<i128> + PartialOrd<isize>,
227 Self: PartialOrd<u8> + PartialOrd<u16> + PartialOrd<u32>,
228 Self: PartialOrd<u64> + PartialOrd<u128> + PartialOrd<usize>,
229 Self: PartialOrd<f32> + PartialOrd<f64>,
230 Self: FixedOptionalFeatures,
231 Self: Sealed,
232{
233 /// The primitive integer underlying type.
234 type Bits;
235
236 /// A byte array with the same size as the type.
237 type Bytes;
238
239 /// The number of fractional bits.
240 ///
241 /// <code><F as [Fixed]>::Frac::[U32]</code> is equivalent to
242 /// <code><F as [Fixed]>::[frac_nbits][`frac_nbits`]()</code>.
243 ///
244 /// [Fixed]: trait.Fixed.html
245 /// [U32]: ../types/extra/trait.Unsigned.html#associatedconstant.U32
246 /// [`frac_nbits`]: #tymethod.frac_nbits
247 type Frac: Unsigned;
248
249 /// Returns the smallest value that can be represented.
250 fn min_value() -> Self;
251
252 /// Returns the largest value that can be represented.
253 fn max_value() -> Self;
254
255 /// Returns the number of integer bits.
256 fn int_nbits() -> u32;
257
258 /// Returns the number of fractional bits.
259 fn frac_nbits() -> u32;
260
261 /// Creates a fixed-point number that has a bitwise representation
262 /// identical to the given integer.
263 fn from_bits(bits: Self::Bits) -> Self;
264
265 /// Creates an integer that has a bitwise representation identical
266 /// to the given fixed-point number.
267 fn to_bits(self) -> Self::Bits;
268
269 /// Creates a fixed-point number from its representation as a byte
270 /// array in big endian.
271 fn from_be_bytes(bytes: Self::Bytes) -> Self;
272
273 /// Creates a fixed-point number from its representation as a byte
274 /// array in little endian.
275 fn from_le_bytes(bytes: Self::Bytes) -> Self;
276
277 /// Creates a fixed-point number from its representation as a byte
278 /// array in native endian.
279 fn from_ne_bytes(bytes: Self::Bytes) -> Self;
280
281 /// Returns the memory representation of this fixed-point number
282 /// as a byte array in big-endian byte order.
283 fn to_be_bytes(self) -> Self::Bytes;
284
285 /// Returns the memory representation of this fixed-point number
286 /// as a byte array in little-endian byte order.
287 fn to_le_bytes(self) -> Self::Bytes;
288
289 /// Returns the memory representation of this fixed-point number
290 /// as a byte array in native byte order.
291 fn to_ne_bytes(self) -> Self::Bytes;
292
293 /// Creates a fixed-point number from another number.
294 ///
295 /// Returns the same value as [`src.to_fixed()`][`to_fixed`].
296 ///
297 /// [`to_fixed`]: trait.ToFixed.html#tymethod.to_fixed
298 fn from_num<Src: ToFixed>(src: Src) -> Self;
299
300 /// Converts a fixed-point number to another number.
301 ///
302 /// Returns the same value as [`Dst::from_fixed(self)`][`from_fixed`].
303 ///
304 /// [`from_fixed`]: trait.FromFixed.html#tymethod.from_fixed
305 fn to_num<Dst: FromFixed>(self) -> Dst;
306
307 /// Creates a fixed-point number from another number if it fits,
308 /// otherwise returns [`None`].
309 ///
310 /// Returns the same value as [`src.checked_to_fixed()`][`checked_to_fixed`].
311 ///
312 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
313 /// [`checked_to_fixed`]: trait.ToFixed.html#tymethod.checked_to_fixed
314 fn checked_from_num<Src: ToFixed>(src: Src) -> Option<Self>;
315
316 /// Converts a fixed-point number to another number if it fits,
317 /// otherwise returns [`None`].
318 ///
319 /// Returns the same value as [`Dst::checked_from_fixed(self)`][`checked_from_fixed`].
320 ///
321 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
322 /// [`checked_from_fixed`]: trait.FromFixed.html#tymethod.checked_from_fixed
323 fn checked_to_num<Dst: FromFixed>(self) -> Option<Dst>;
324
325 /// Creates a fixed-point number from another number, saturating the
326 /// value if it does not fit.
327 ///
328 /// Returns the same value as [`src.saturating_to_fixed()`][`saturating_to_fixed`].
329 ///
330 /// [`saturating_to_fixed`]: trait.ToFixed.html#tymethod.saturating_to_fixed
331 fn saturating_from_num<Src: ToFixed>(src: Src) -> Self;
332
333 /// Converts a fixed-point number to another number, saturating the
334 /// value if it does not fit.
335 ///
336 /// Returns the same value as [`Dst::saturating_from_fixed(self)`][`saturating_from_fixed`].
337 ///
338 /// [`saturating_from_fixed`]: trait.FromFixed.html#tymethod.saturating_from_fixed
339 fn saturating_to_num<Dst: FromFixed>(self) -> Dst;
340
341 /// Creates a fixed-point number from another number, wrapping the
342 /// value on overflow.
343 ///
344 /// Returns the same value as [`src.wrapping_to_fixed()`][`wrapping_to_fixed`].
345 ///
346 /// [`wrapping_to_fixed`]: trait.ToFixed.html#tymethod.wrapping_to_fixed
347 fn wrapping_from_num<Src: ToFixed>(src: Src) -> Self;
348
349 /// Converts a fixed-point number to another number, wrapping the
350 /// value on overflow.
351 ///
352 /// Returns the same value as [`Src::wrapping_from_fixed(self)`][`wrapping_from_fixed`].
353 ///
354 /// [`wrapping_from_fixed`]: trait.FromFixed.html#tymethod.wrapping_from_fixed
355 fn wrapping_to_num<Dst: FromFixed>(self) -> Dst;
356
357 /// Creates a fixed-point number from another number.
358 ///
359 /// Returns the same value as [`src.overflowing_to_fixed()`][`overflowing_to_fixed`].
360 ///
361 /// [`overflowing_to_fixed`]: trait.ToFixed.html#tymethod.overflowing_to_fixed
362 fn overflowing_from_num<Src: ToFixed>(src: Src) -> (Self, bool);
363
364 /// Converts a fixed-point number to another number.
365 ///
366 /// Returns the same value as [`Dst::overflowing_from_fixed(self)`][`overflowing_from_fixed`].
367 ///
368 /// [`overflowing_from_fixed`]: trait.FromFixed.html#tymethod.overflowing_from_fixed
369 fn overflowing_to_num<Dst: FromFixed>(self) -> (Dst, bool);
370
371 /// Parses a string slice containing binary digits to return a fixed-point number.
372 ///
373 /// Rounding is to the nearest, with ties rounded to even.
374 fn from_str_binary(src: &str) -> Result<Self, ParseFixedError>;
375
376 /// Parses a string slice containing octal digits to return a fixed-point number.
377 ///
378 /// Rounding is to the nearest, with ties rounded to even.
379 fn from_str_octal(src: &str) -> Result<Self, ParseFixedError>;
380
381 /// Parses a string slice containing hexadecimal digits to return a fixed-point number.
382 ///
383 /// Rounding is to the nearest, with ties rounded to even.
384 fn from_str_hex(src: &str) -> Result<Self, ParseFixedError>;
385
386 /// Parses a string slice containing decimal digits to return a
387 /// fixed-point number, saturating on overflow.
388 ///
389 /// Rounding is to the nearest, with ties rounded to even.
390 fn saturating_from_str(src: &str) -> Result<Self, ParseFixedError>;
391
392 /// Parses a string slice containing binary digits to return a
393 /// fixed-point number, saturating on overflow.
394 ///
395 /// Rounding is to the nearest, with ties rounded to even.
396 fn saturating_from_str_binary(src: &str) -> Result<Self, ParseFixedError>;
397
398 /// Parses a string slice containing octal digits to return a
399 /// fixed-point number, saturating on overflow.
400 ///
401 /// Rounding is to the nearest, with ties rounded to even.
402 fn saturating_from_str_octal(src: &str) -> Result<Self, ParseFixedError>;
403
404 /// Parses a string slice containing hexadecimal digits to return a
405 /// fixed-point number, saturating on overflow.
406 ///
407 /// Rounding is to the nearest, with ties rounded to even.
408 fn saturating_from_str_hex(src: &str) -> Result<Self, ParseFixedError>;
409
410 /// Parses a string slice containing decimal digits to return a
411 /// fixed-point number, wrapping on overflow.
412 ///
413 /// Rounding is to the nearest, with ties rounded to even.
414 fn wrapping_from_str(src: &str) -> Result<Self, ParseFixedError>;
415
416 /// Parses a string slice containing binary digits to return a
417 /// fixed-point number, wrapping on overflow.
418 ///
419 /// Rounding is to the nearest, with ties rounded to even.
420 fn wrapping_from_str_binary(src: &str) -> Result<Self, ParseFixedError>;
421
422 /// Parses a string slice containing octal digits to return a
423 /// fixed-point number, wrapping on overflow.
424 ///
425 /// Rounding is to the nearest, with ties rounded to even.
426 fn wrapping_from_str_octal(src: &str) -> Result<Self, ParseFixedError>;
427
428 /// Parses a string slice containing hexadecimal digits to return a
429 /// fixed-point number, wrapping on overflow.
430 ///
431 /// Rounding is to the nearest, with ties rounded to even.
432 fn wrapping_from_str_hex(src: &str) -> Result<Self, ParseFixedError>;
433
434 /// Parses a string slice containing decimal digits to return a
435 /// fixed-point number.
436 ///
437 /// Returns a [tuple] of the fixed-point number and a [`bool`],
438 /// indicating whether an overflow has occurred. On overflow, the
439 /// wrapped value is returned.
440 ///
441 /// Rounding is to the nearest, with ties rounded to even.
442 ///
443 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
444 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
445 fn overflowing_from_str(src: &str) -> Result<(Self, bool), ParseFixedError>;
446
447 /// Parses a string slice containing binary digits to return a
448 /// fixed-point number.
449 ///
450 /// Returns a [tuple] of the fixed-point number and a [`bool`],
451 /// indicating whether an overflow has occurred. On overflow, the
452 /// wrapped value is returned.
453 ///
454 /// Rounding is to the nearest, with ties rounded to even.
455 ///
456 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
457 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
458 fn overflowing_from_str_binary(src: &str) -> Result<(Self, bool), ParseFixedError>;
459
460 /// Parses a string slice containing octal digits to return a
461 /// fixed-point number.
462 ///
463 /// Returns a [tuple] of the fixed-point number and a [`bool`],
464 /// indicating whether an overflow has occurred. On overflow, the
465 /// wrapped value is returned.
466 ///
467 /// Rounding is to the nearest, with ties rounded to even.
468 ///
469 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
470 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
471 fn overflowing_from_str_octal(src: &str) -> Result<(Self, bool), ParseFixedError>;
472
473 /// Parses a string slice containing hexadecimal digits to return a
474 /// fixed-point number.
475 ///
476 /// Returns a [tuple] of the fixed-point number and a [`bool`],
477 /// indicating whether an overflow has occurred. On overflow, the
478 /// wrapped value is returned.
479 ///
480 /// Rounding is to the nearest, with ties rounded to even.
481 ///
482 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
483 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
484 fn overflowing_from_str_hex(src: &str) -> Result<(Self, bool), ParseFixedError>;
485
486 /// Returns the integer part.
487 fn int(self) -> Self;
488
489 /// Returns the fractional part.
490 fn frac(self) -> Self;
491
492 /// Rounds to the next integer towards 0.
493 fn round_to_zero(self) -> Self;
494
495 /// Rounds to the next integer towards +∞.
496 fn ceil(self) -> Self;
497
498 /// Rounds to the next integer towards −∞.
499 fn floor(self) -> Self;
500
501 /// Rounds to the nearest integer, with ties rounded away from zero.
502 fn round(self) -> Self;
503
504 /// Rounds to the nearest integer, with ties rounded to even.
505 fn round_ties_to_even(self) -> Self;
506
507 /// Checked ceil. Rounds to the next integer towards +∞, returning
508 /// [`None`] on overflow.
509 ///
510 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
511 fn checked_ceil(self) -> Option<Self>;
512
513 /// Checked floor. Rounds to the next integer towards −∞, returning
514 /// [`None`] on overflow.
515 ///
516 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
517 fn checked_floor(self) -> Option<Self>;
518
519 /// Checked round. Rounds to the nearest integer, with ties
520 /// rounded away from zero, returning [`None`] on overflow.
521 ///
522 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
523 fn checked_round(self) -> Option<Self>;
524
525 /// Checked round. Rounds to the nearest integer, with ties
526 /// rounded to even, returning [`None`] on overflow.
527 ///
528 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
529 fn checked_round_ties_to_even(self) -> Option<Self>;
530
531 /// Saturating ceil. Rounds to the next integer towards +∞,
532 /// saturating on overflow.
533 fn saturating_ceil(self) -> Self;
534
535 /// Saturating floor. Rounds to the next integer towards −∞,
536 /// saturating on overflow.
537 fn saturating_floor(self) -> Self;
538
539 /// Saturating round. Rounds to the nearest integer, with ties
540 /// rounded away from zero, and saturating on overflow.
541 fn saturating_round(self) -> Self;
542
543 /// Saturating round. Rounds to the nearest integer, with ties
544 /// rounded to_even, and saturating on overflow.
545 fn saturating_round_ties_to_even(self) -> Self;
546
547 /// Wrapping ceil. Rounds to the next integer towards +∞, wrapping
548 /// on overflow.
549 fn wrapping_ceil(self) -> Self;
550
551 /// Wrapping floor. Rounds to the next integer towards −∞,
552 /// wrapping on overflow.
553 fn wrapping_floor(self) -> Self;
554
555 /// Wrapping round. Rounds to the next integer to the nearest,
556 /// with ties rounded away from zero, and wrapping on overflow.
557 fn wrapping_round(self) -> Self;
558
559 /// Wrapping round. Rounds to the next integer to the nearest,
560 /// with ties rounded to even, and wrapping on overflow.
561 fn wrapping_round_ties_to_even(self) -> Self;
562
563 /// Overflowing ceil. Rounds to the next integer towards +∞.
564 ///
565 /// Returns a [tuple] of the fixed-point number and a [`bool`],
566 /// indicating whether an overflow has occurred. On overflow, the
567 /// wrapped value is returned.
568 ///
569 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
570 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
571 fn overflowing_ceil(self) -> (Self, bool);
572
573 /// Overflowing floor. Rounds to the next integer towards −∞.
574 ///
575 /// Returns a [tuple] of the fixed-point number and a [`bool`],
576 /// indicating whether an overflow has occurred. On overflow, the
577 /// wrapped value is returned.
578 ///
579 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
580 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
581 fn overflowing_floor(self) -> (Self, bool);
582
583 /// Overflowing round. Rounds to the next integer to the nearest,
584 /// with ties rounded away from zero.
585 ///
586 /// Returns a [tuple] of the fixed-point number and a [`bool`],
587 /// indicating whether an overflow has occurred. On overflow, the
588 /// wrapped value is returned.
589 ///
590 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
591 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
592 fn overflowing_round(self) -> (Self, bool);
593
594 /// Overflowing round. Rounds to the next integer to the nearest,
595 /// with ties rounded to even.
596 ///
597 /// Returns a [tuple] of the fixed-point number and a [`bool`],
598 /// indicating whether an overflow has occurred. On overflow, the
599 /// wrapped value is returned.
600 ///
601 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
602 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
603 fn overflowing_round_ties_to_even(self) -> (Self, bool);
604
605 /// Returns the number of ones in the binary representation.
606 fn count_ones(self) -> u32;
607
608 /// Returns the number of zeros in the binary representation.
609 fn count_zeros(self) -> u32;
610
611 /// Returns the number of leading zeros in the binary representation.
612 fn leading_zeros(self) -> u32;
613
614 /// Returns the number of trailing zeros in the binary representation.
615 fn trailing_zeros(self) -> u32;
616
617 /// Shifts to the left by `n` bits, wrapping the truncated bits to the right end.
618 fn rotate_left(self, n: u32) -> Self;
619
620 /// Shifts to the right by `n` bits, wrapping the truncated bits to the left end.
621 fn rotate_right(self, n: u32) -> Self;
622
623 /// Euclidean division by an integer.
624 ///
625 /// # Panics
626 ///
627 /// Panics if the divisor is zero or if the division results in overflow.
628 fn div_euclid(self, rhs: Self) -> Self;
629
630 /// Remainder for Euclidean division.
631 ///
632 /// # Panics
633 ///
634 /// Panics if the divisor is zero.
635 fn rem_euclid(self, rhs: Self) -> Self;
636
637 /// Euclidean division by an integer.
638 ///
639 /// # Panics
640 ///
641 /// Panics if the divisor is zero or if the division results in overflow.
642 fn div_euclid_int(self, rhs: Self::Bits) -> Self;
643
644 /// Remainder for Euclidean division by an integer.
645 ///
646 /// # Panics
647 ///
648 /// Panics if the divisor is zero or if the division results in overflow.
649 fn rem_euclid_int(self, rhs: Self::Bits) -> Self;
650
651 /// Checked negation. Returns the negated value, or [`None`] on overflow.
652 ///
653 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
654 fn checked_neg(self) -> Option<Self>;
655
656 /// Checked addition. Returns the sum, or [`None`] on overflow.
657 ///
658 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
659 fn checked_add(self, rhs: Self) -> Option<Self>;
660
661 /// Checked subtraction. Returns the difference, or [`None`] on overflow.
662 ///
663 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
664 fn checked_sub(self, rhs: Self) -> Option<Self>;
665
666 /// Checked multiplication. Returns the product, or [`None`] on overflow.
667 ///
668 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
669 fn checked_mul(self, rhs: Self) -> Option<Self>;
670
671 /// Checked division. Returns the quotient, or [`None`] if the
672 /// divisor is zero or on overflow.
673 ///
674 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
675 fn checked_div(self, rhs: Self) -> Option<Self>;
676
677 /// Checked remainder. Returns the remainder, or [`None`] if the
678 /// divisor is zero.
679 ///
680 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
681 fn checked_rem(self, rhs: Self) -> Option<Self>;
682
683 /// Checked remainder for Euclidean division. Returns the
684 /// remainder, or [`None`] if the divisor is zero or the division
685 /// results in overflow.
686 ///
687 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
688 fn checked_div_euclid(self, rhs: Self) -> Option<Self>;
689
690 /// Checked remainder for Euclidean division. Returns the
691 /// remainder, or [`None`] if the divisor is zero.
692 ///
693 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
694 fn checked_rem_euclid(self, rhs: Self) -> Option<Self>;
695
696 /// Checked multiplication by an integer. Returns the product, or
697 /// [`None`] on overflow.
698 ///
699 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
700 fn checked_mul_int(self, rhs: Self::Bits) -> Option<Self>;
701
702 /// Checked division by an integer. Returns the quotient, or
703 /// [`None`] if the divisor is zero or if the division results in
704 /// overflow.
705 ///
706 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
707 fn checked_div_int(self, rhs: Self::Bits) -> Option<Self>;
708
709 /// Checked fixed-point remainder for division by an integer.
710 /// Returns the remainder, or [`None`] if the divisor is zero or
711 /// if the division results in overflow.
712 ///
713 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
714 fn checked_rem_int(self, rhs: Self::Bits) -> Option<Self>;
715
716 /// Checked Euclidean division by an integer. Returns the
717 /// quotient, or [`None`] if the divisor is zero or if the
718 /// division results in overflow.
719 ///
720 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
721 fn checked_div_euclid_int(self, rhs: Self::Bits) -> Option<Self>;
722
723 /// Checked remainder for Euclidean division by an integer.
724 /// Returns the remainder, or [`None`] if the divisor is zero or
725 /// if the remainder results in overflow.
726 ///
727 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
728 fn checked_rem_euclid_int(self, rhs: Self::Bits) -> Option<Self>;
729
730 /// Checked shift left. Returns the shifted number, or [`None`] if
731 /// `rhs` ≥ the number of bits.
732 ///
733 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
734 fn checked_shl(self, rhs: u32) -> Option<Self>;
735
736 /// Checked shift right. Returns the shifted number, or [`None`]
737 /// if `rhs` ≥ the number of bits.
738 ///
739 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
740 fn checked_shr(self, rhs: u32) -> Option<Self>;
741
742 /// Saturated negation. Returns the negated value, saturating on overflow.
743 fn saturating_neg(self) -> Self;
744
745 /// Saturating addition. Returns the sum, saturating on overflow.
746 fn saturating_add(self, rhs: Self) -> Self;
747
748 /// Saturating subtraction. Returns the difference, saturating on overflow.
749 fn saturating_sub(self, rhs: Self) -> Self;
750
751 /// Saturating multiplication. Returns the product, saturating on overflow.
752 fn saturating_mul(self, rhs: Self) -> Self;
753
754 /// Saturating division. Returns the quotient, saturating on overflow.
755 ///
756 /// # Panics
757 ///
758 /// Panics if the divisor is zero.
759 fn saturating_div(self, rhs: Self) -> Self;
760
761 /// Saturating Euclidean division. Returns the quotient, saturating on overflow.
762 ///
763 /// # Panics
764 ///
765 /// Panics if the divisor is zero.
766 fn saturating_div_euclid(self, rhs: Self) -> Self;
767
768 /// Saturating multiplication by an integer. Returns the product, saturating on overflow.
769 fn saturating_mul_int(self, rhs: Self::Bits) -> Self;
770
771 /// Wrapping negation. Returns the negated value, wrapping on overflow.
772 fn wrapping_neg(self) -> Self;
773
774 /// Wrapping addition. Returns the sum, wrapping on overflow.
775 fn wrapping_add(self, rhs: Self) -> Self;
776
777 /// Wrapping subtraction. Returns the difference, wrapping on overflow.
778 fn wrapping_sub(self, rhs: Self) -> Self;
779
780 /// Wrapping multiplication. Returns the product, wrapping on overflow.
781 fn wrapping_mul(self, rhs: Self) -> Self;
782
783 /// Wrapping division. Returns the quotient, wrapping on overflow.
784 ///
785 /// # Panics
786 ///
787 /// Panics if the divisor is zero.
788 fn wrapping_div(self, rhs: Self) -> Self;
789
790 /// Wrapping Euclidean division. Returns the quotient, wrapping on overflow.
791 ///
792 /// # Panics
793 ///
794 /// Panics if the divisor is zero.
795 fn wrapping_div_euclid(self, rhs: Self) -> Self;
796
797 /// Wrapping multiplication by an integer. Returns the product, wrapping on overflow.
798 fn wrapping_mul_int(self, rhs: Self::Bits) -> Self;
799
800 /// Wrapping division by an integer. Returns the quotient, wrapping on overflow.
801 ///
802 /// Overflow can only occur when dividing the minimum value by −1.
803 ///
804 /// # Panics
805 ///
806 /// Panics if the divisor is zero.
807 fn wrapping_div_int(self, rhs: Self::Bits) -> Self;
808
809 /// Wrapping Euclidean division by an integer. Returns the
810 /// quotient, wrapping on overflow.
811 ///
812 /// Overflow can only occur when dividing the minimum value by −1.
813 ///
814 /// # Panics
815 ///
816 /// Panics if the divisor is zero.
817 fn wrapping_div_euclid_int(self, rhs: Self::Bits) -> Self;
818
819 /// Wrapping remainder for Euclidean division by an integer.
820 /// Returns the remainder, wrapping on overflow.
821 ///
822 /// # Panics
823 ///
824 /// Panics if the divisor is zero.
825 fn wrapping_rem_euclid_int(self, rhs: Self::Bits) -> Self;
826
827 /// Wrapping shift left. Wraps `rhs` if `rhs` ≥ the number of
828 /// bits, then shifts and returns the number.
829 fn wrapping_shl(self, rhs: u32) -> Self;
830
831 /// Wrapping shift right. Wraps `rhs` if `rhs` ≥ the number of
832 /// bits, then shifts and returns the number.
833 fn wrapping_shr(self, rhs: u32) -> Self;
834
835 /// Overflowing negation.
836 ///
837 /// Returns a [tuple] of the negated value and a [`bool`],
838 /// indicating whether an overflow has occurred. On overflow, the
839 /// wrapped value is returned.
840 ///
841 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
842 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
843 fn overflowing_neg(self) -> (Self, bool);
844
845 /// Overflowing addition.
846 ///
847 /// Returns a [tuple] of the sum and a [`bool`], indicating whether
848 /// an overflow has occurred. On overflow, the wrapped value is
849 /// returned.
850 ///
851 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
852 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
853 fn overflowing_add(self, rhs: Self) -> (Self, bool);
854
855 /// Overflowing subtraction.
856 ///
857 /// Returns a [tuple] of the difference and a [`bool`], indicating
858 /// whether an overflow has occurred. On overflow, the wrapped
859 /// value is returned.
860 ///
861 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
862 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
863 fn overflowing_sub(self, rhs: Self) -> (Self, bool);
864
865 /// Overflowing multiplication.
866 ///
867 /// Returns a [tuple] of the product and a [`bool`], indicating
868 /// whether an overflow has occurred. On overflow, the wrapped
869 /// value is returned.
870 ///
871 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
872 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
873 fn overflowing_mul(self, rhs: Self) -> (Self, bool);
874
875 /// Overflowing division.
876 ///
877 /// Returns a [tuple] of the quotient and a [`bool`], indicating
878 /// whether an overflow has occurred. On overflow, the wrapped
879 /// value is returned.
880 ///
881 /// # Panics
882 ///
883 /// Panics if the divisor is zero.
884 ///
885 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
886 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
887 fn overflowing_div(self, rhs: Self) -> (Self, bool);
888
889 /// Overflowing Euclidean division.
890 ///
891 /// Returns a [tuple] of the quotient and a [`bool`], indicating
892 /// whether an overflow has occurred. On overflow, the wrapped
893 /// value is returned.
894 ///
895 /// # Panics
896 ///
897 /// Panics if the divisor is zero.
898 ///
899 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
900 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
901 fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool);
902
903 /// Overflowing multiplication by an integer.
904 ///
905 /// Returns a [tuple] of the product and a [`bool`], indicating
906 /// whether an overflow has occurred. On overflow, the wrapped
907 /// value is returned.
908 ///
909 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
910 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
911 fn overflowing_mul_int(self, rhs: Self::Bits) -> (Self, bool);
912
913 /// Overflowing division by an integer.
914 ///
915 /// Returns a [tuple] of the quotient and a [`bool`], indicating
916 /// whether an overflow has occurred. On overflow, the wrapped
917 /// value is returned.
918 ///
919 /// # Panics
920 ///
921 /// Panics if the divisor is zero.
922 ///
923 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
924 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
925 fn overflowing_div_int(self, rhs: Self::Bits) -> (Self, bool);
926
927 /// Overflowing Euclidean division by an integer.
928 ///
929 /// Returns a [tuple] of the quotient and a [`bool`], indicating
930 /// whether an overflow has occurred. On overflow, the wrapped
931 /// value is returned.
932 ///
933 /// # Panics
934 ///
935 /// Panics if the divisor is zero.
936 ///
937 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
938 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
939 fn overflowing_div_euclid_int(self, rhs: Self::Bits) -> (Self, bool);
940
941 /// Overflowing remainder for Euclidean division by an integer.
942 ///
943 /// Returns a [tuple] of the remainder and a [`bool`], indicating
944 /// whether an overflow has occurred. On overflow, the wrapped
945 /// value is returned.
946 ///
947 /// # Panics
948 ///
949 /// Panics if the divisor is zero.
950 ///
951 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
952 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
953 fn overflowing_rem_euclid_int(self, rhs: Self::Bits) -> (Self, bool);
954
955 /// Overflowing shift left.
956 ///
957 /// Returns a [tuple] of the shifted value and a [`bool`],
958 /// indicating whether an overflow has occurred. On overflow, the
959 /// wrapped value is returned.
960 ///
961 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
962 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
963 fn overflowing_shl(self, rhs: u32) -> (Self, bool);
964
965 /// Overflowing shift right.
966 ///
967 /// Returns a [tuple] of the shifted value and a [`bool`],
968 /// indicating whether an overflow has occurred. On overflow, the
969 /// wrapped value is returned.
970 ///
971 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
972 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
973 fn overflowing_shr(self, rhs: u32) -> (Self, bool);
974
975 /// Remainder for division by an integer.
976 ///
977 /// # Panics
978 ///
979 /// Panics if the divisor is zero.
980 #[deprecated(
981 since = "0.5.3",
982 note = "cannot overflow, use `%` or `Rem::rem` instead"
983 )]
984 fn wrapping_rem_int(self, rhs: Self::Bits) -> Self {
985 self % rhs
986 }
987
988 /// Remainder for division by an integer.
989 ///
990 /// # Panics
991 ///
992 /// Panics if the divisor is zero.
993 #[deprecated(
994 since = "0.5.3",
995 note = "cannot overflow, use `%` or `Rem::rem` instead"
996 )]
997 fn overflowing_rem_int(self, rhs: Self::Bits) -> (Self, bool) {
998 (self % rhs, false)
999 }
1000}
1001
1002/// This trait provides methods common to all signed fixed-point numbers.
1003///
1004/// Methods common to all fixed-point numbers including unsigned
1005/// fixed-point numbers are provided by the [`Fixed`] supertrait.
1006///
1007/// This trait is sealed and cannot be implemented for more types; it
1008/// is implemented for [`FixedI8`], [`FixedI16`], [`FixedI32`],
1009/// [`FixedI64`], and [`FixedI128`].
1010///
1011/// [`FixedI128`]: ../struct.FixedI128.html
1012/// [`FixedI16`]: ../struct.FixedI16.html
1013/// [`FixedI32`]: ../struct.FixedI32.html
1014/// [`FixedI64`]: ../struct.FixedI64.html
1015/// [`FixedI8`]: ../struct.FixedI8.html
1016/// [`Fixed`]: trait.Fixed.html
1017pub trait FixedSigned: Fixed + Neg<Output = Self> {
1018 /// Returns [`true`][`bool`] if the number is > 0.
1019 ///
1020 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1021 fn is_positive(self) -> bool;
1022
1023 /// Returns [`true`][`bool`] if the number is < 0.
1024 ///
1025 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1026 fn is_negative(self) -> bool;
1027
1028 /// Returns the absolute value.
1029 fn abs(self) -> Self;
1030
1031 /// Returns a number representing the sign of `self`.
1032 ///
1033 /// # Panics
1034 ///
1035 /// When debug assertions are enabled, this method panics
1036 /// * if the value is positive and the fixed-point number has
1037 /// zero or one integer bits such that it cannot hold the
1038 /// value 1.
1039 /// * if the value is negative and the fixed-point number has
1040 /// zero integer bits, such that it cannot hold the value −1.
1041 ///
1042 /// When debug assertions are not enabled, the wrapped value can
1043 /// be returned in those cases, but it is not considered a
1044 /// breaking change if in the future it panics; using this method
1045 /// when 1 and −1 cannot be represented is almost certainly a bug.
1046 fn signum(self) -> Self;
1047
1048 /// Checked absolute value. Returns the absolute value, or [`None`] on overflow.
1049 ///
1050 /// Overflow can only occur when trying to find the absolute value of the minimum value.
1051 ///
1052 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1053 fn checked_abs(self) -> Option<Self>;
1054
1055 /// Saturating absolute value. Returns the absolute value, saturating on overflow.
1056 ///
1057 /// Overflow can only occur when trying to find the absolute value of the minimum value.
1058 fn saturating_abs(self) -> Self;
1059
1060 /// Wrapping absolute value. Returns the absolute value, wrapping on overflow.
1061 ///
1062 /// Overflow can only occur when trying to find the absolute value of the minimum value.
1063 fn wrapping_abs(self) -> Self;
1064
1065 /// Overflowing absolute value.
1066 ///
1067 /// Returns a [tuple] of the fixed-point number and a [`bool`],
1068 /// indicating whether an overflow has occurred. On overflow, the
1069 /// wrapped value is returned.
1070 ///
1071 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1072 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1073 fn overflowing_abs(self) -> (Self, bool);
1074}
1075
1076/// This trait provides methods common to all unsigned fixed-point numbers.
1077///
1078/// Methods common to all fixed-point numbers including signed
1079/// fixed-point numbers are provided by the [`Fixed`] supertrait.
1080///
1081/// This trait is sealed and cannot be implemented for more types; it
1082/// is implemented for [`FixedU8`], [`FixedU16`], [`FixedU32`],
1083/// [`FixedU64`], and [`FixedU128`].
1084///
1085/// [`FixedU128`]: ../struct.FixedU128.html
1086/// [`FixedU16`]: ../struct.FixedU16.html
1087/// [`FixedU32`]: ../struct.FixedU32.html
1088/// [`FixedU64`]: ../struct.FixedU64.html
1089/// [`FixedU8`]: ../struct.FixedU8.html
1090/// [`Fixed`]: trait.Fixed.html
1091pub trait FixedUnsigned: Fixed {
1092 /// Returns [`true`][`bool`] if the fixed-point number is
1093 /// 2<sup><i>k</i></sup> for some integer <i>k</i>.
1094 ///
1095 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1096 fn is_power_of_two(self) -> bool;
1097
1098 /// Returns the smallest power of two that is ≥ `self`.
1099 fn next_power_of_two(self) -> Self;
1100
1101 /// Returns the smallest power of two that is ≥ `self`, or [`None`] if the
1102 /// next power of two is too large to represent.
1103 ///
1104 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1105 fn checked_next_power_of_two(self) -> Option<Self>;
1106}
1107
1108/// This trait provides infallible conversions that might be lossy.
1109///
1110/// This trait is implemented for conversions between integer
1111/// primitives, floating-point primitives and fixed-point numbers.
1112///
1113/// # Examples
1114///
1115/// ```rust
1116/// use substrate_fixed::traits::LossyFrom;
1117/// use substrate_fixed::types::{I12F4, I4F60};
1118/// // original is 0x1.234
1119/// let original = I4F60::from_bits(0x1234i64 << (60 - 12));
1120/// let lossy = I12F4::lossy_from(original);
1121/// assert_eq!(lossy, I12F4::from_bits(0x0012));
1122/// ```
1123pub trait LossyFrom<Src> {
1124 /// Performs the conversion.
1125 fn lossy_from(src: Src) -> Self;
1126}
1127
1128/// This trait provides infallible conversions that might be lossy.
1129/// This is the reciprocal of [`LossyFrom`].
1130///
1131/// Usually [`LossyFrom`] should be implemented instead of this trait;
1132/// there is a blanket implementation which provides this trait when
1133/// [`LossyFrom`] is implemented (similar to [`Into`] and [`From`]).
1134///
1135/// # Examples
1136///
1137/// ```rust
1138/// use substrate_fixed::traits::LossyInto;
1139/// use substrate_fixed::types::{I12F4, I4F12};
1140/// // original is 0x1.234
1141/// let original = I4F12::from_bits(0x1234);
1142/// let lossy: I12F4 = original.lossy_into();
1143/// assert_eq!(lossy, I12F4::from_bits(0x0012));
1144/// ```
1145///
1146/// [`From`]: https://doc.rust-lang.org/nightly/core/convert/trait.From.html
1147/// [`Into`]: https://doc.rust-lang.org/nightly/core/convert/trait.Into.html
1148/// [`LossyFrom`]: trait.LossyFrom.html
1149pub trait LossyInto<Dst> {
1150 /// Performs the conversion.
1151 fn lossy_into(self) -> Dst;
1152}
1153
1154impl<Src, Dst> LossyInto<Dst> for Src
1155where
1156 Dst: LossyFrom<Src>,
1157{
1158 fn lossy_into(self) -> Dst {
1159 Dst::lossy_from(self)
1160 }
1161}
1162
1163/// This trait provides checked conversions from fixed-point numbers.
1164///
1165/// This trait is implemented for conversions between integer
1166/// primitives, floating-point primitives and fixed-point numbers.
1167///
1168/// # Examples
1169///
1170/// ```rust
1171/// use substrate_fixed::traits::FromFixed;
1172/// use substrate_fixed::types::U8F8;
1173/// // 0x87.65
1174/// let f = U8F8::from_bits(0x8765);
1175/// assert_eq!(f32::from_fixed(f), f32::from(0x8765u16) / 256.0);
1176/// assert_eq!(i32::checked_from_fixed(f), Some(0x87));
1177/// assert_eq!(u8::saturating_from_fixed(f), 0x87);
1178/// // no fit
1179/// assert_eq!(i8::checked_from_fixed(f), None);
1180/// assert_eq!(i8::saturating_from_fixed(f), i8::max_value());
1181/// assert_eq!(i8::wrapping_from_fixed(f), 0x87u8 as i8);
1182/// assert_eq!(i8::overflowing_from_fixed(f), (0x87u8 as i8, true));
1183/// ```
1184pub trait FromFixed {
1185 /// Converts from a fixed-point number.
1186 ///
1187 /// Any extra fractional bits are truncated.
1188 ///
1189 /// # Panics
1190 ///
1191 /// When debug assertions are enabled, panics if the value does
1192 /// not fit. When debug assertions are not enabled, the wrapped
1193 /// value can be returned, but it is not considered a breaking
1194 /// change if in the future it panics; if wrapping is required use
1195 /// [`wrapping_from_fixed`] instead.
1196 ///
1197 /// [`wrapping_from_fixed`]: #method.wrapping_from_fixed
1198 fn from_fixed<F: Fixed>(src: F) -> Self;
1199
1200 /// Converts from a fixed-point number if it fits, otherwise returns [`None`].
1201 ///
1202 /// Any extra fractional bits are truncated.
1203 ///
1204 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1205 fn checked_from_fixed<F: Fixed>(src: F) -> Option<Self>
1206 where
1207 Self: Sized;
1208
1209 /// Converts from a fixed-point number, saturating if it does not fit.
1210 ///
1211 /// Any extra fractional bits are truncated.
1212 fn saturating_from_fixed<F: Fixed>(src: F) -> Self;
1213
1214 /// Converts from a fixed-point number, wrapping if it does not fit.
1215 ///
1216 /// Any extra fractional bits are truncated.
1217 fn wrapping_from_fixed<F: Fixed>(src: F) -> Self;
1218
1219 /// Converts from a fixed-point number.
1220 ///
1221 /// Returns a [tuple] of the value and a [`bool`] indicating whether
1222 /// an overflow has occurred. On overflow, the wrapped value is
1223 /// returned.
1224 ///
1225 /// Any extra fractional bits are truncated.
1226 ///
1227 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1228 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1229 fn overflowing_from_fixed<F: Fixed>(src: F) -> (Self, bool)
1230 where
1231 Self: Sized;
1232}
1233
1234/// This trait provides checked conversions to fixed-point numbers.
1235///
1236/// This trait is implemented for conversions between integer
1237/// primitives, floating-point primitives and fixed-point numbers.
1238///
1239/// # Examples
1240///
1241/// ```rust
1242/// use substrate_fixed::traits::ToFixed;
1243/// use substrate_fixed::types::{U8F8, U16F16};
1244/// let f: U8F8 = 13.5f32.to_fixed();
1245/// assert_eq!(f, U8F8::from_bits((13 << 8) | (1 << 7)));
1246/// // 0x1234.5678 is too large and can be wrapped to 0x34.56
1247/// let too_large = U16F16::from_bits(0x1234_5678);
1248/// let checked: Option<U8F8> = too_large.checked_to_num();
1249/// assert_eq!(checked, None);
1250/// let saturating: U8F8 = too_large.saturating_to_num();
1251/// assert_eq!(saturating, U8F8::max_value());
1252/// let wrapping: U8F8 = too_large.wrapping_to_num();
1253/// assert_eq!(wrapping, U8F8::from_bits(0x3456));
1254/// let overflowing: (U8F8, bool) = too_large.overflowing_to_num();
1255/// assert_eq!(overflowing, (U8F8::from_bits(0x3456), true));
1256/// ```
1257pub trait ToFixed {
1258 /// Converts to a fixed-point number.
1259 ///
1260 /// Any extra fractional bits are truncated.
1261 ///
1262 /// # Panics
1263 ///
1264 /// Panics if `self` is a floating-point number that is not [finite].
1265 ///
1266 /// When debug assertions are enabled, also panics if the value
1267 /// does not fit. When debug assertions are not enabled, the
1268 /// wrapped value can be returned, but it is not considered a
1269 /// breaking change if in the future it panics; if wrapping is
1270 /// required use [`wrapping_to_fixed`] instead.
1271 ///
1272 /// [`wrapping_to_fixed`]: #method.wrapping_to_fixed
1273 /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
1274 fn to_fixed<F: Fixed>(self) -> F;
1275
1276 /// Converts to a fixed-point number if it fits, otherwise returns [`None`].
1277 ///
1278 /// Any extra fractional bits are truncated.
1279 ///
1280 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1281 fn checked_to_fixed<F: Fixed>(self) -> Option<F>;
1282
1283 /// Converts to a fixed-point number, saturating if it does not fit.
1284 ///
1285 /// Any extra fractional bits are truncated.
1286 ///
1287 /// # Panics
1288 ///
1289 /// Panics if `self` is a floating-point number that is [NaN].
1290 ///
1291 /// [NaN]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_nan
1292 fn saturating_to_fixed<F: Fixed>(self) -> F;
1293
1294 /// Converts to a fixed-point number, wrapping if it does not fit.
1295 ///
1296 /// Any extra fractional bits are truncated.
1297 ///
1298 /// # Panics
1299 ///
1300 /// Panics if `self` is a floating-point number that is not [finite].
1301 ///
1302 /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
1303 fn wrapping_to_fixed<F: Fixed>(self) -> F;
1304
1305 /// Converts to a fixed-point number.
1306 ///
1307 /// Returns a [tuple] of the fixed-point number and a [`bool`]
1308 /// indicating whether an overflow has occurred. On overflow, the
1309 /// wrapped value is returned.
1310 ///
1311 /// Any extra fractional bits are truncated.
1312 ///
1313 /// # Panics
1314 ///
1315 /// Panics if `self` is a floating-point number that is not [finite].
1316 ///
1317 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1318 /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
1319 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1320 fn overflowing_to_fixed<F: Fixed>(self) -> (F, bool);
1321}
1322
1323impl ToFixed for bool {
1324 /// Converts a [`bool`] to a fixed-point number.
1325 ///
1326 /// # Panics
1327 ///
1328 /// When debug assertions are enabled, panics if the value does
1329 /// not fit. When debug assertions are not enabled, the wrapped
1330 /// value can be returned, but it is not considered a breaking
1331 /// change if in the future it panics; if wrapping is required use
1332 /// [`wrapping_to_fixed`] instead.
1333 ///
1334 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1335 /// [`wrapping_to_fixed`]: #method.wrapping_to_fixed
1336 #[inline]
1337 fn to_fixed<F: Fixed>(self) -> F {
1338 ToFixed::to_fixed(self as u8)
1339 }
1340
1341 /// Converts a [`bool`] to a fixed-point number if it fits, otherwise returns [`None`].
1342 ///
1343 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1344 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1345 #[inline]
1346 fn checked_to_fixed<F: Fixed>(self) -> Option<F> {
1347 ToFixed::checked_to_fixed(self as u8)
1348 }
1349
1350 /// Convert a [`bool`] to a fixed-point number, saturating if it does not fit.
1351 ///
1352 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1353 #[inline]
1354 fn saturating_to_fixed<F: Fixed>(self) -> F {
1355 ToFixed::saturating_to_fixed(self as u8)
1356 }
1357
1358 /// Converts a [`bool`] to a fixed-point number, wrapping if it does not fit.
1359 ///
1360 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1361 #[inline]
1362 fn wrapping_to_fixed<F: Fixed>(self) -> F {
1363 ToFixed::wrapping_to_fixed(self as u8)
1364 }
1365
1366 /// Converts a [`bool`] to a fixed-point number.
1367 ///
1368 /// Returns a [tuple] of the fixed-point number and a [`bool`]
1369 /// indicating whether an overflow has occurred. On overflow, the
1370 /// wrapped value is returned.
1371 ///
1372 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1373 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1374 #[inline]
1375 fn overflowing_to_fixed<F: Fixed>(self) -> (F, bool) {
1376 ToFixed::overflowing_to_fixed(self as u8)
1377 }
1378}
1379
1380macro_rules! impl_int {
1381 ($Int:ident) => {
1382 impl FromFixed for $Int {
1383 /// Converts a fixed-point number to an integer.
1384 ///
1385 /// Any fractional bits are truncated.
1386 ///
1387 /// # Panics
1388 ///
1389 /// When debug assertions are enabled, panics if the value
1390 /// does not fit. When debug assertions are not enabled,
1391 /// the wrapped value can be returned, but it is not
1392 /// considered a breaking change if in the future it
1393 /// panics; if wrapping is required use
1394 /// [`wrapping_from_fixed`] instead.
1395 ///
1396 /// [`wrapping_from_fixed`]: #method.wrapping_from_fixed
1397 #[inline]
1398 fn from_fixed<F: Fixed>(src: F) -> Self {
1399 $Int::from_repr_fixed(FromFixed::from_fixed(src))
1400 }
1401
1402 /// Converts a fixed-point number to an integer if it fits, otherwise returns [`None`].
1403 ///
1404 /// Any fractional bits are truncated.
1405 ///
1406 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1407 #[inline]
1408 fn checked_from_fixed<F: Fixed>(src: F) -> Option<Self> {
1409 FromFixed::checked_from_fixed(src).map($Int::from_repr_fixed)
1410 }
1411
1412 /// Converts a fixed-point number to an integer, saturating if it does not fit.
1413 ///
1414 /// Any fractional bits are truncated.
1415 #[inline]
1416 fn saturating_from_fixed<F: Fixed>(src: F) -> Self {
1417 $Int::from_repr_fixed(FromFixed::saturating_from_fixed(src))
1418 }
1419
1420 /// Converts a fixed-point number to an integer, wrapping if it does not fit.
1421 ///
1422 /// Any fractional bits are truncated.
1423 #[inline]
1424 fn wrapping_from_fixed<F: Fixed>(src: F) -> Self {
1425 $Int::from_repr_fixed(FromFixed::wrapping_from_fixed(src))
1426 }
1427
1428 /// Converts a fixed-point number to an integer.
1429 ///
1430 /// Returns a [tuple] of the value and a [`bool`] indicating whether
1431 /// an overflow has occurred. On overflow, the wrapped value is
1432 /// returned.
1433 ///
1434 /// Any fractional bits are truncated.
1435 ///
1436 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1437 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1438 #[inline]
1439 fn overflowing_from_fixed<F: Fixed>(src: F) -> (Self, bool) {
1440 let (repr_fixed, overflow) = FromFixed::overflowing_from_fixed(src);
1441 ($Int::from_repr_fixed(repr_fixed), overflow)
1442 }
1443 }
1444
1445 impl ToFixed for $Int {
1446 /// Converts an integer to a fixed-point number.
1447 ///
1448 /// # Panics
1449 ///
1450 /// When debug assertions are enabled, panics if the value
1451 /// does not fit. When debug assertions are not enabled,
1452 /// the wrapped value can be returned, but it is not
1453 /// considered a breaking change if in the future it
1454 /// panics; if wrapping is required use
1455 /// [`wrapping_to_fixed`] instead.
1456 ///
1457 /// [`wrapping_to_fixed`]: #method.wrapping_to_fixed
1458 #[inline]
1459 fn to_fixed<F: Fixed>(self) -> F {
1460 ToFixed::to_fixed(self.to_repr_fixed())
1461 }
1462
1463 /// Converts an integer to a fixed-point number if it fits, otherwise returns [`None`].
1464 ///
1465 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1466 #[inline]
1467 fn checked_to_fixed<F: Fixed>(self) -> Option<F> {
1468 ToFixed::checked_to_fixed(self.to_repr_fixed())
1469 }
1470
1471 /// Converts an integer to a fixed-point number, saturating if it does not fit.
1472 #[inline]
1473 fn saturating_to_fixed<F: Fixed>(self) -> F {
1474 ToFixed::saturating_to_fixed(self.to_repr_fixed())
1475 }
1476
1477 /// Converts an integer to a fixed-point number, wrapping if it does not fit.
1478 #[inline]
1479 fn wrapping_to_fixed<F: Fixed>(self) -> F {
1480 ToFixed::wrapping_to_fixed(self.to_repr_fixed())
1481 }
1482
1483 /// Converts an integer to a fixed-point number.
1484 ///
1485 /// Returns a [tuple] of the fixed-point number and a [`bool`]
1486 /// indicating whether an overflow has occurred. On overflow, the
1487 /// wrapped value is returned.
1488 ///
1489 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1490 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1491 #[inline]
1492 fn overflowing_to_fixed<F: Fixed>(self) -> (F, bool) {
1493 ToFixed::overflowing_to_fixed(self.to_repr_fixed())
1494 }
1495 }
1496 };
1497}
1498
1499impl_int! { i8 }
1500impl_int! { i16 }
1501impl_int! { i32 }
1502impl_int! { i64 }
1503impl_int! { i128 }
1504impl_int! { isize }
1505impl_int! { u8 }
1506impl_int! { u16 }
1507impl_int! { u32 }
1508impl_int! { u64 }
1509impl_int! { u128 }
1510impl_int! { usize }
1511
1512macro_rules! impl_float {
1513 ($Float:ty) => {
1514 impl FromFixed for $Float {
1515 /// Converts a fixed-point number to a floating-point number.
1516 ///
1517 /// Rounding is to the nearest, with ties rounded to even.
1518 ///
1519 /// # Panics
1520 ///
1521 /// When debug assertions are enabled, panics if the value
1522 /// does not fit. When debug assertions are not enabled,
1523 /// the wrapped value can be returned, but it is not
1524 /// considered a breaking change if in the future it
1525 /// panics; if wrapping is required use
1526 /// [`wrapping_from_fixed`] instead.
1527 ///
1528 /// [`wrapping_from_fixed`]: #method.wrapping_from_fixed
1529 #[inline]
1530 fn from_fixed<F: Fixed>(src: F) -> Self {
1531 let helper = src.private_to_float_helper();
1532 FloatHelper::from_to_float_helper(helper, F::frac_nbits(), F::int_nbits())
1533 }
1534
1535 /// Converts a fixed-point number to a floating-point
1536 /// number if it fits, otherwise returns [`None`].
1537 ///
1538 /// Rounding is to the nearest, with ties rounded to even.
1539 ///
1540 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1541 #[inline]
1542 fn checked_from_fixed<F: Fixed>(src: F) -> Option<Self> {
1543 Some(FromFixed::from_fixed(src))
1544 }
1545
1546 /// Converts a fixed-point number to a floating-point
1547 /// number, saturating if it does not fit.
1548 ///
1549 /// Rounding is to the nearest, with ties rounded to even.
1550 #[inline]
1551 fn saturating_from_fixed<F: Fixed>(src: F) -> Self {
1552 FromFixed::from_fixed(src)
1553 }
1554
1555 /// Converts a fixed-point number to a floating-point
1556 /// number, wrapping if it does not fit.
1557 ///
1558 /// Rounding is to the nearest, with ties rounded to even.
1559 #[inline]
1560 fn wrapping_from_fixed<F: Fixed>(src: F) -> Self {
1561 FromFixed::from_fixed(src)
1562 }
1563
1564 /// Converts a fixed-point number to a floating-point number.
1565 ///
1566 /// Returns a [tuple] of the value and a [`bool`]
1567 /// indicating whether an overflow has occurred. On
1568 /// overflow, the wrapped value is returned.
1569 ///
1570 /// Rounding is to the nearest, with ties rounded to even.
1571 ///
1572 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1573 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1574 #[inline]
1575 fn overflowing_from_fixed<F: Fixed>(src: F) -> (Self, bool) {
1576 (FromFixed::from_fixed(src), false)
1577 }
1578 }
1579
1580 impl ToFixed for $Float {
1581 /// Converts a floating-point number to a fixed-point number.
1582 ///
1583 /// Rounding is to the nearest, with ties rounded to even.
1584 ///
1585 /// # Panics
1586 ///
1587 /// Panics if `self` is not [finite].
1588 ///
1589 /// When debug assertions are enabled, also panics if the
1590 /// value does not fit. When debug assertions are not
1591 /// enabled, the wrapped value can be returned, but it is
1592 /// not considered a breaking change if in the future it
1593 /// panics; if wrapping is required use
1594 /// [`wrapping_to_fixed`] instead.
1595 ///
1596 /// [`wrapping_to_fixed`]: #method.wrapping_to_fixed
1597 /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
1598 #[inline]
1599 fn to_fixed<F: Fixed>(self) -> F {
1600 let (wrapped, overflow) = ToFixed::overflowing_to_fixed(self);
1601 debug_assert!(!overflow, "{} overflows", self);
1602 let _ = overflow;
1603 wrapped
1604 }
1605
1606 /// Converts a floating-point number to a fixed-point
1607 /// number if it fits, otherwise returns [`None`].
1608 ///
1609 /// Rounding is to the nearest, with ties rounded to even.
1610 ///
1611 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1612 #[inline]
1613 fn checked_to_fixed<F: Fixed>(self) -> Option<F> {
1614 let kind = self.to_float_kind(F::frac_nbits(), F::int_nbits());
1615 match kind {
1616 FloatKind::Finite { .. } => {
1617 let helper = FromFloatHelper { kind };
1618 match F::private_overflowing_from_float_helper(helper) {
1619 (_, true) => None,
1620 (wrapped, false) => Some(wrapped),
1621 }
1622 }
1623 _ => None,
1624 }
1625 }
1626
1627 /// Converts a floating-point number to a fixed-point
1628 /// number, saturating if it does not fit.
1629 ///
1630 /// Rounding is to the nearest, with ties rounded to even.
1631 ///
1632 /// # Panics
1633 ///
1634 /// Panics if `self` is [NaN].
1635 ///
1636 /// [NaN]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_nan
1637 #[inline]
1638 fn saturating_to_fixed<F: Fixed>(self) -> F {
1639 let kind = self.to_float_kind(F::frac_nbits(), F::int_nbits());
1640 let helper = FromFloatHelper { kind };
1641 F::private_saturating_from_float_helper(helper)
1642 }
1643
1644 /// Converts a floating-point number to a fixed-point
1645 /// number, wrapping if it does not fit.
1646 ///
1647 /// Rounding is to the nearest, with ties rounded to even.
1648 ///
1649 /// # Panics
1650 ///
1651 /// Panics if `self` is not [finite].
1652 ///
1653 /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
1654 #[inline]
1655 fn wrapping_to_fixed<F: Fixed>(self) -> F {
1656 let (wrapped, _) = ToFixed::overflowing_to_fixed(self);
1657 wrapped
1658 }
1659
1660 /// Converts a floating-point number to a fixed-point number.
1661 ///
1662 /// Returns a [tuple] of the fixed-point number and a [`bool`]
1663 /// indicating whether an overflow has occurred. On overflow, the
1664 /// wrapped value is returned.
1665 ///
1666 /// Rounding is to the nearest, with ties rounded to even.
1667 ///
1668 /// # Panics
1669 ///
1670 /// Panics if `self` is not [finite].
1671 ///
1672 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1673 /// [finite]: https://doc.rust-lang.org/nightly/std/primitive.f64.html#method.is_finite
1674 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1675 #[inline]
1676 fn overflowing_to_fixed<F: Fixed>(self) -> (F, bool) {
1677 let kind = self.to_float_kind(F::frac_nbits(), F::int_nbits());
1678 let helper = FromFloatHelper { kind };
1679 F::private_overflowing_from_float_helper(helper)
1680 }
1681 }
1682 };
1683}
1684
1685#[cfg(feature = "f16")]
1686impl_float! { f16 }
1687#[cfg(feature = "f16")]
1688impl_float! { bf16 }
1689impl_float! { f32 }
1690impl_float! { f64 }
1691
1692macro_rules! trait_delegate {
1693 (fn $method:ident($($param:ident: $Param:ty),*) -> $Ret:ty) => {
1694 #[inline]
1695 fn $method($($param: $Param),*) -> $Ret {
1696 Self::$method($($param),*)
1697 }
1698 };
1699 (fn $method:ident(self $(, $param:ident: $Param:ty)*) -> $Ret:ty) => {
1700 #[inline]
1701 fn $method(self $(, $param: $Param)*) -> $Ret {
1702 self.$method($($param),*)
1703 }
1704 };
1705 (fn $method:ident<$Gen:ident: $Trait:ident>($($param:ident: $Param:ty),*) -> $Ret:ty) => {
1706 #[inline]
1707 fn $method<$Gen: $Trait>($($param: $Param),*) -> $Ret {
1708 Self::$method($($param),*)
1709 }
1710 };
1711 (fn $method:ident<$Gen:ident: $Trait:ident>(self $(, $param:ident: $Param:ty)*) -> $Ret:ty) => {
1712 #[inline]
1713 fn $method<$Gen: $Trait>(self $(, $param: $Param)*) -> $Ret {
1714 self.$method($($param),*)
1715 }
1716 };
1717}
1718
1719macro_rules! impl_fixed {
1720 ($Fixed:ident, $LeEqU:ident, $Bits:ident, $Signedness:tt) => {
1721 impl<Frac: $LeEqU> FixedOptionalFeatures for $Fixed<Frac> {}
1722
1723 impl<Frac: $LeEqU> Fixed for $Fixed<Frac> {
1724 type Bits = $Bits;
1725 type Bytes = [u8; mem::size_of::<$Bits>()];
1726 type Frac = Frac;
1727 trait_delegate! { fn min_value() -> Self }
1728 trait_delegate! { fn max_value() -> Self }
1729 trait_delegate! { fn int_nbits() -> u32 }
1730 trait_delegate! { fn frac_nbits() -> u32 }
1731 trait_delegate! { fn from_bits(bits: Self::Bits) -> Self }
1732 trait_delegate! { fn to_bits(self) -> Self::Bits }
1733 trait_delegate! { fn from_be_bytes(bits: Self::Bytes) -> Self }
1734 trait_delegate! { fn from_le_bytes(bits: Self::Bytes) -> Self }
1735 trait_delegate! { fn from_ne_bytes(bits: Self::Bytes) -> Self }
1736 trait_delegate! { fn to_be_bytes(self) -> Self::Bytes }
1737 trait_delegate! { fn to_le_bytes(self) -> Self::Bytes }
1738 trait_delegate! { fn to_ne_bytes(self) -> Self::Bytes }
1739 trait_delegate! { fn from_num<Src: ToFixed>(src: Src) -> Self }
1740 trait_delegate! { fn to_num<Dst: FromFixed>(self) -> Dst }
1741 trait_delegate! { fn checked_from_num<Src: ToFixed>(val: Src) -> Option<Self> }
1742 trait_delegate! { fn checked_to_num<Dst: FromFixed>(self) -> Option<Dst> }
1743 trait_delegate! { fn saturating_from_num<Src: ToFixed>(val: Src) -> Self }
1744 trait_delegate! { fn saturating_to_num<Dst: FromFixed>(self) -> Dst }
1745 trait_delegate! { fn wrapping_from_num<Src: ToFixed>(val: Src) -> Self }
1746 trait_delegate! { fn wrapping_to_num<Dst: FromFixed>(self) -> Dst }
1747 trait_delegate! { fn overflowing_from_num<Src: ToFixed>(val: Src) -> (Self, bool) }
1748 trait_delegate! { fn overflowing_to_num<Dst: FromFixed>(self) -> (Dst, bool) }
1749 trait_delegate! { fn from_str_binary(src: &str) -> Result<Self, ParseFixedError> }
1750 trait_delegate! { fn from_str_octal(src: &str) -> Result<Self, ParseFixedError> }
1751 trait_delegate! { fn from_str_hex(src: &str) -> Result<Self, ParseFixedError> }
1752 trait_delegate! {
1753 fn saturating_from_str(src: &str) -> Result<Self, ParseFixedError>
1754 }
1755 trait_delegate! {
1756 fn saturating_from_str_binary(src: &str) -> Result<Self, ParseFixedError>
1757 }
1758 trait_delegate! {
1759 fn saturating_from_str_octal(src: &str) -> Result<Self, ParseFixedError>
1760 }
1761 trait_delegate! {
1762 fn saturating_from_str_hex(src: &str) -> Result<Self, ParseFixedError>
1763 }
1764 trait_delegate! {
1765 fn wrapping_from_str(src: &str) -> Result<Self, ParseFixedError>
1766 }
1767 trait_delegate! {
1768 fn wrapping_from_str_binary(src: &str) -> Result<Self, ParseFixedError>
1769 }
1770 trait_delegate! {
1771 fn wrapping_from_str_octal(src: &str) -> Result<Self, ParseFixedError>
1772 }
1773 trait_delegate! {
1774 fn wrapping_from_str_hex(src: &str) -> Result<Self, ParseFixedError>
1775 }
1776 trait_delegate! {
1777 fn overflowing_from_str(src: &str) -> Result<(Self, bool), ParseFixedError>
1778 }
1779 trait_delegate! {
1780 fn overflowing_from_str_binary(src: &str) -> Result<(Self, bool), ParseFixedError>
1781 }
1782 trait_delegate! {
1783 fn overflowing_from_str_octal(src: &str) -> Result<(Self, bool), ParseFixedError>
1784 }
1785 trait_delegate! {
1786 fn overflowing_from_str_hex(src: &str) -> Result<(Self, bool), ParseFixedError>
1787 }
1788 trait_delegate! { fn int(self) -> Self }
1789 trait_delegate! { fn frac(self) -> Self }
1790 trait_delegate! { fn ceil(self) -> Self }
1791 trait_delegate! { fn floor(self) -> Self }
1792 trait_delegate! { fn round_to_zero(self) -> Self }
1793 trait_delegate! { fn round(self) -> Self }
1794 trait_delegate! { fn round_ties_to_even(self) -> Self }
1795 trait_delegate! { fn checked_ceil(self) -> Option<Self> }
1796 trait_delegate! { fn checked_floor(self) -> Option<Self> }
1797 trait_delegate! { fn checked_round(self) -> Option<Self> }
1798 trait_delegate! { fn checked_round_ties_to_even(self) -> Option<Self> }
1799 trait_delegate! { fn saturating_ceil(self) -> Self }
1800 trait_delegate! { fn saturating_floor(self) -> Self }
1801 trait_delegate! { fn saturating_round(self) -> Self }
1802 trait_delegate! { fn saturating_round_ties_to_even(self) -> Self }
1803 trait_delegate! { fn wrapping_ceil(self) -> Self }
1804 trait_delegate! { fn wrapping_floor(self) -> Self }
1805 trait_delegate! { fn wrapping_round(self) -> Self }
1806 trait_delegate! { fn wrapping_round_ties_to_even(self) -> Self }
1807 trait_delegate! { fn overflowing_ceil(self) -> (Self, bool) }
1808 trait_delegate! { fn overflowing_floor(self) -> (Self, bool) }
1809 trait_delegate! { fn overflowing_round(self) -> (Self, bool) }
1810 trait_delegate! { fn overflowing_round_ties_to_even(self) -> (Self, bool) }
1811 trait_delegate! { fn count_ones(self) -> u32 }
1812 trait_delegate! { fn count_zeros(self) -> u32 }
1813 trait_delegate! { fn leading_zeros(self) -> u32 }
1814 trait_delegate! { fn trailing_zeros(self) -> u32 }
1815 trait_delegate! { fn rotate_left(self, n: u32) -> Self }
1816 trait_delegate! { fn rotate_right(self, n: u32) -> Self }
1817 trait_delegate! { fn div_euclid(self, rhs: Self) -> Self }
1818 trait_delegate! { fn rem_euclid(self, rhs: Self) -> Self }
1819 trait_delegate! { fn div_euclid_int(self, rhs: Self::Bits) -> Self }
1820 trait_delegate! { fn rem_euclid_int(self, rhs: Self::Bits) -> Self }
1821 trait_delegate! { fn checked_neg(self) -> Option<Self> }
1822 trait_delegate! { fn checked_add(self, rhs: Self) -> Option<Self> }
1823 trait_delegate! { fn checked_sub(self, rhs: Self) -> Option<Self> }
1824 trait_delegate! { fn checked_mul(self, rhs: Self) -> Option<Self> }
1825 trait_delegate! { fn checked_div(self, rhs: Self) -> Option<Self> }
1826 trait_delegate! { fn checked_rem(self, rhs: Self) -> Option<Self> }
1827 trait_delegate! { fn checked_div_euclid(self, rhs: Self) -> Option<Self> }
1828 trait_delegate! { fn checked_rem_euclid(self, rhs: Self) -> Option<Self> }
1829 trait_delegate! { fn checked_mul_int(self, rhs: Self::Bits) -> Option<Self> }
1830 trait_delegate! { fn checked_div_int(self, rhs: Self::Bits) -> Option<Self> }
1831 trait_delegate! { fn checked_rem_int(self, rhs: Self::Bits) -> Option<Self> }
1832 trait_delegate! { fn checked_div_euclid_int(self, rhs: Self::Bits) -> Option<Self> }
1833 trait_delegate! { fn checked_rem_euclid_int(self, rhs: Self::Bits) -> Option<Self> }
1834 trait_delegate! { fn checked_shl(self, rhs: u32) -> Option<Self> }
1835 trait_delegate! { fn checked_shr(self, rhs: u32) -> Option<Self> }
1836 trait_delegate! { fn saturating_neg(self) -> Self }
1837 trait_delegate! { fn saturating_add(self, rhs: Self) -> Self }
1838 trait_delegate! { fn saturating_sub(self, rhs: Self) -> Self }
1839 trait_delegate! { fn saturating_mul(self, rhs: Self) -> Self }
1840 trait_delegate! { fn saturating_div(self, rhs: Self) -> Self }
1841 trait_delegate! { fn saturating_div_euclid(self, rhs: Self) -> Self }
1842 trait_delegate! { fn saturating_mul_int(self, rhs: Self::Bits) -> Self }
1843 trait_delegate! { fn wrapping_neg(self) -> Self }
1844 trait_delegate! { fn wrapping_add(self, rhs: Self) -> Self }
1845 trait_delegate! { fn wrapping_sub(self, rhs: Self) -> Self }
1846 trait_delegate! { fn wrapping_mul(self, rhs: Self) -> Self }
1847 trait_delegate! { fn wrapping_div(self, rhs: Self) -> Self }
1848 trait_delegate! { fn wrapping_div_euclid(self, rhs: Self) -> Self }
1849 trait_delegate! { fn wrapping_mul_int(self, rhs: Self::Bits) -> Self }
1850 trait_delegate! { fn wrapping_div_int(self, rhs: Self::Bits) -> Self }
1851 trait_delegate! { fn wrapping_div_euclid_int(self, rhs: Self::Bits) -> Self }
1852 trait_delegate! { fn wrapping_rem_euclid_int(self, rhs: Self::Bits) -> Self }
1853 trait_delegate! { fn wrapping_shl(self, rhs: u32) -> Self }
1854 trait_delegate! { fn wrapping_shr(self, rhs: u32) -> Self }
1855 trait_delegate! { fn overflowing_neg(self) -> (Self, bool) }
1856 trait_delegate! { fn overflowing_add(self, rhs: Self) -> (Self, bool) }
1857 trait_delegate! { fn overflowing_sub(self, rhs: Self) -> (Self, bool) }
1858 trait_delegate! { fn overflowing_mul(self, rhs: Self) -> (Self, bool) }
1859 trait_delegate! { fn overflowing_div(self, rhs: Self) -> (Self, bool) }
1860 trait_delegate! { fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) }
1861 trait_delegate! { fn overflowing_mul_int(self, rhs: Self::Bits) -> (Self, bool) }
1862 trait_delegate! { fn overflowing_div_int(self, rhs: Self::Bits) -> (Self, bool) }
1863 trait_delegate! { fn overflowing_div_euclid_int(self, rhs: Self::Bits) -> (Self, bool) }
1864 trait_delegate! { fn overflowing_rem_euclid_int(self, rhs: Self::Bits) -> (Self, bool) }
1865 trait_delegate! { fn overflowing_shl(self, rhs: u32) -> (Self, bool) }
1866 trait_delegate! { fn overflowing_shr(self, rhs: u32) -> (Self, bool) }
1867 }
1868
1869 impl<Frac: $LeEqU> FromFixed for $Fixed<Frac> {
1870 /// Converts a fixed-point number.
1871 ///
1872 /// Any extra fractional bits are truncated.
1873 #[inline]
1874 fn from_fixed<F: Fixed>(src: F) -> Self {
1875 let (wrapped, overflow) = FromFixed::overflowing_from_fixed(src);
1876 debug_assert!(!overflow, "{} overflows", src);
1877 let _ = overflow;
1878 wrapped
1879 }
1880
1881 /// Converts a fixed-point number if it fits, otherwise returns [`None`].
1882 ///
1883 /// Any extra fractional bits are truncated.
1884 ///
1885 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1886 #[inline]
1887 fn checked_from_fixed<F: Fixed>(src: F) -> Option<Self> {
1888 match FromFixed::overflowing_from_fixed(src) {
1889 (_, true) => None,
1890 (wrapped, false) => Some(wrapped),
1891 }
1892 }
1893
1894 /// Converts a fixed-point number, saturating if it does not fit.
1895 ///
1896 /// Any extra fractional bits are truncated.
1897 #[inline]
1898 fn saturating_from_fixed<F: Fixed>(src: F) -> Self {
1899 let conv = src.private_to_fixed_helper(Self::FRAC_NBITS, Self::INT_NBITS);
1900 if conv.overflow {
1901 return if src < 0 {
1902 Self::min_value()
1903 } else {
1904 Self::max_value()
1905 };
1906 }
1907 let bits = if_signed_unsigned! {
1908 $Signedness,
1909 match conv.bits {
1910 Widest::Unsigned(bits) => {
1911 if (bits as $Bits) < 0 {
1912 return Self::max_value();
1913 }
1914 bits as $Bits
1915 }
1916 Widest::Negative(bits) => bits as $Bits,
1917 },
1918 match conv.bits {
1919 Widest::Unsigned(bits) => bits as $Bits,
1920 Widest::Negative(_) => {
1921 return Self::min_value();
1922 }
1923 },
1924 };
1925 Self::from_bits(bits)
1926 }
1927
1928 /// Converts a fixed-point number, wrapping if it does not fit.
1929 ///
1930 /// Any extra fractional bits are truncated.
1931 #[inline]
1932 fn wrapping_from_fixed<F: Fixed>(src: F) -> Self {
1933 let (wrapped, _) = FromFixed::overflowing_from_fixed(src);
1934 wrapped
1935 }
1936
1937 /// Converts a fixed-point number.
1938 ///
1939 /// Returns a [tuple] of the value and a [`bool`]
1940 /// indicating whether an overflow has occurred. On
1941 /// overflow, the wrapped value is returned.
1942 ///
1943 /// Any extra fractional bits are truncated.
1944 ///
1945 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
1946 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
1947 #[inline]
1948 fn overflowing_from_fixed<F: Fixed>(src: F) -> (Self, bool) {
1949 let conv = src.private_to_fixed_helper(Self::FRAC_NBITS, Self::INT_NBITS);
1950 let mut new_overflow = false;
1951 let bits = if_signed_unsigned! {
1952 $Signedness,
1953 match conv.bits {
1954 Widest::Unsigned(bits) => {
1955 if (bits as $Bits) < 0 {
1956 new_overflow = true;
1957 }
1958 bits as $Bits
1959 }
1960 Widest::Negative(bits) => bits as $Bits,
1961 },
1962 match conv.bits {
1963 Widest::Unsigned(bits) => bits as $Bits,
1964 Widest::Negative(bits) => {
1965 new_overflow = true;
1966 bits as $Bits
1967 }
1968 },
1969 };
1970 (Self::from_bits(bits), conv.overflow || new_overflow)
1971 }
1972 }
1973
1974 impl<Frac: $LeEqU> ToFixed for $Fixed<Frac> {
1975 /// Converts a fixed-point number.
1976 ///
1977 /// Any extra fractional bits are truncated.
1978 #[inline]
1979 fn to_fixed<F: Fixed>(self) -> F {
1980 FromFixed::from_fixed(self)
1981 }
1982
1983 /// Converts a fixed-point number if it fits, otherwise returns [`None`].
1984 ///
1985 /// Any extra fractional bits are truncated.
1986 ///
1987 /// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
1988 #[inline]
1989 fn checked_to_fixed<F: Fixed>(self) -> Option<F> {
1990 FromFixed::checked_from_fixed(self)
1991 }
1992
1993 /// Converts a fixed-point number, saturating if it does not fit.
1994 ///
1995 /// Any extra fractional bits are truncated.
1996 #[inline]
1997 fn saturating_to_fixed<F: Fixed>(self) -> F {
1998 FromFixed::saturating_from_fixed(self)
1999 }
2000
2001 /// Converts a fixed-point number, wrapping if it does not fit.
2002 ///
2003 /// Any extra fractional bits are truncated.
2004 #[inline]
2005 fn wrapping_to_fixed<F: Fixed>(self) -> F {
2006 FromFixed::wrapping_from_fixed(self)
2007 }
2008
2009 /// Converts a fixed-point number.
2010 ///
2011 /// Returns a [tuple] of the value and a [`bool`]
2012 /// indicating whether an overflow has occurred. On
2013 /// overflow, the wrapped value is returned.
2014 ///
2015 /// Any extra fractional bits are truncated.
2016 ///
2017 /// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
2018 /// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
2019 #[inline]
2020 fn overflowing_to_fixed<F: Fixed>(self) -> (F, bool) {
2021 FromFixed::overflowing_from_fixed(self)
2022 }
2023 }
2024
2025 if_signed! {
2026 $Signedness;
2027 impl<Frac: $LeEqU> FixedSigned for $Fixed<Frac> {
2028 trait_delegate! { fn abs(self) -> Self }
2029 trait_delegate! { fn signum(self) -> Self }
2030 trait_delegate! { fn checked_abs(self) -> Option<Self> }
2031 trait_delegate! { fn saturating_abs(self) -> Self }
2032 trait_delegate! { fn wrapping_abs(self) -> Self }
2033 trait_delegate! { fn overflowing_abs(self) -> (Self, bool) }
2034 trait_delegate! { fn is_positive(self) -> bool }
2035 trait_delegate! { fn is_negative(self) -> bool }
2036 }
2037 }
2038
2039 if_unsigned! {
2040 $Signedness;
2041 impl<Frac: $LeEqU> FixedUnsigned for $Fixed<Frac> {
2042 trait_delegate! { fn is_power_of_two(self) -> bool }
2043 trait_delegate! { fn next_power_of_two(self) -> Self }
2044 trait_delegate! { fn checked_next_power_of_two(self) -> Option<Self> }
2045 }
2046 }
2047 };
2048}
2049
2050impl_fixed! { FixedI8, LeEqU8, i8, Signed }
2051impl_fixed! { FixedI16, LeEqU16, i16, Signed }
2052impl_fixed! { FixedI32, LeEqU32, i32, Signed }
2053impl_fixed! { FixedI64, LeEqU64, i64, Signed }
2054impl_fixed! { FixedI128, LeEqU128, i128, Signed }
2055impl_fixed! { FixedU8, LeEqU8, u8, Unsigned }
2056impl_fixed! { FixedU16, LeEqU16, u16, Unsigned }
2057impl_fixed! { FixedU32, LeEqU32, u32, Unsigned }
2058impl_fixed! { FixedU64, LeEqU64, u64, Unsigned }
2059impl_fixed! { FixedU128, LeEqU128, u128, Unsigned }