1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Copyright © 2018–2024 Trevor Spiteri

// This library is free software: you can redistribute it and/or
// modify it under the terms of either
//
//   * the Apache License, Version 2.0 or
//   * the MIT License
//
// at your option.
//
// You should have recieved copies of the Apache License and the MIT
// License along with the library. If not, see
// <https://www.apache.org/licenses/LICENSE-2.0> and
// <https://opensource.org/licenses/MIT>.

use crate::traits::FixedEquiv;
#[cfg(feature = "arbitrary")]
use arbitrary::Arbitrary;
use az::{
    Cast, CastFrom, CheckedCast, CheckedCastFrom, OverflowingCast, OverflowingCastFrom,
    SaturatingCast, SaturatingCastFrom, UnwrappedCast, UnwrappedCastFrom, WrappingCast,
    WrappingCastFrom,
};
#[cfg(feature = "borsh")]
use borsh::{BorshDeserialize, BorshSerialize};
use bytemuck::{Contiguous, Pod};
use core::{
    fmt::{Binary, Debug, Display, LowerExp, LowerHex, Octal, UpperExp, UpperHex},
    hash::Hash,
    iter::{Product, Sum},
    num::ParseIntError,
    ops::{
        Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div,
        DivAssign, Mul, MulAssign, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub,
        SubAssign,
    },
    str::FromStr,
};
#[cfg(feature = "num-traits")]
use num_traits::{
    cast::{AsPrimitive, FromPrimitive},
    int::PrimInt,
    ops::{
        checked::{CheckedNeg, CheckedRem, CheckedShl, CheckedShr},
        euclid::{CheckedEuclid, Euclid},
        mul_add::{MulAdd, MulAddAssign},
        overflowing::{OverflowingAdd, OverflowingMul, OverflowingSub},
        saturating::{SaturatingAdd, SaturatingMul, SaturatingSub},
        wrapping::{WrappingAdd, WrappingMul, WrappingNeg, WrappingShl, WrappingShr, WrappingSub},
    },
    Num, NumAssignRef, NumRef,
};
#[cfg(feature = "serde")]
use serde::{de::Deserialize, ser::Serialize};

macro_rules! impl_bits {
    ($Bits:ident) => {
        impl FixedBits for $Bits {
            const MIN: $Bits = $Bits::MIN;
            const MAX: $Bits = $Bits::MAX;
            const IS_SIGNED: bool = $Bits::MIN != 0;
            const BITS: u32 = $Bits::BITS;
        }
        impl Sealed for $Bits {}
        impl FixedBitsCast<i8> for $Bits {}
        impl FixedBitsCast<i16> for $Bits {}
        impl FixedBitsCast<i32> for $Bits {}
        impl FixedBitsCast<i64> for $Bits {}
        impl FixedBitsCast<i128> for $Bits {}
        impl FixedBitsCast<isize> for $Bits {}
        impl FixedBitsCast<u8> for $Bits {}
        impl FixedBitsCast<u16> for $Bits {}
        impl FixedBitsCast<u32> for $Bits {}
        impl FixedBitsCast<u64> for $Bits {}
        impl FixedBitsCast<u128> for $Bits {}
        impl FixedBitsCast<usize> for $Bits {}
        impl FixedBitsOptionalArbitrary for $Bits {}
        impl FixedBitsOptionalBorsh for $Bits {}
        impl FixedBitsOptionalNum for $Bits {}
        impl FixedBitsOptionalSerde for $Bits {}
    };
}

/// This trait is implemented for <code>[Fixed]::[Bits]</code> for all
/// fixed-point numbers.
///
/// This provides some facilities to manipulate bits in generic functions.
///
/// This trait is sealed and cannot be implemented for more types; it is
/// implemented for [`i8`], [`i16`], [`i32`], [`i64`], [`i128`], [`u8`],
/// [`u16`], [`u32`], [`u64`], and [`u128`].
///
/// # Examples
///
/// ```rust
/// use az::OverflowingAs;
/// use fixed::{traits::Fixed, types::*};
/// fn limited_positive_bits<F: Fixed>(fixed: F) -> Option<u32> {
///     let bits = fixed.to_bits();
///     match bits.overflowing_as::<u32>() {
///         (wrapped, false) => Some(wrapped),
///         (_, true) => None,
///     }
/// }
/// assert_eq!(limited_positive_bits(I16F16::from_bits(100)), Some(100));
/// assert_eq!(limited_positive_bits(I16F16::from_bits(-100)), None);
/// ```
///
/// [Bits]: crate::traits::Fixed::Bits
/// [Fixed]: crate::traits::Fixed
pub trait FixedBits
where
    Self: Default + Hash + Ord,
    Self: Contiguous + Pod,
    Self: Debug + Display + LowerExp + UpperExp,
    Self: Binary + Octal + LowerHex + UpperHex,
    Self: FromStr<Err = ParseIntError>,
    Self: Add<Output = Self> + AddAssign,
    Self: Sub<Output = Self> + SubAssign,
    Self: Mul<Output = Self> + MulAssign,
    Self: Div<Output = Self> + DivAssign,
    Self: Rem<Output = Self> + RemAssign,
    Self: Not<Output = Self>,
    Self: BitAnd<Output = Self> + BitAndAssign,
    Self: BitOr<Output = Self> + BitOrAssign,
    Self: BitXor<Output = Self> + BitXorAssign,
    Self: Shl<u32, Output = Self> + ShlAssign<u32>,
    Self: Shr<u32, Output = Self> + ShrAssign<u32>,
    Self: Sum + Product,
    Self: FixedEquiv,
    Self: FixedBitsCast<i8> + FixedBitsCast<i16> + FixedBitsCast<i32>,
    Self: FixedBitsCast<i64> + FixedBitsCast<i128> + FixedBitsCast<isize>,
    Self: FixedBitsCast<u8> + FixedBitsCast<u16> + FixedBitsCast<u32>,
    Self: FixedBitsCast<u64> + FixedBitsCast<u128> + FixedBitsCast<usize>,
    Self: FixedBitsOptionalArbitrary,
    Self: FixedBitsOptionalBorsh,
    Self: FixedBitsOptionalNum,
    Self: FixedBitsOptionalSerde,
    Self: Sealed,
{
    /// The smallest value that can be represented by this integer type.
    const MIN: Self;

    /// The largest value that can be represented by this integer type.
    const MAX: Self;

    /// [`true`] if this integer type is signed.
    const IS_SIGNED: bool;

    /// The size of this integer type in bits.
    const BITS: u32;
}

/// This trait is used to provide supertraits to the [`FixedBits`] trait, and
/// should not be used directly.
pub trait FixedBitsCast<Prim>
where
    Self: TryInto<Prim> + TryFrom<Prim>,
    Self: Cast<Prim> + CastFrom<Prim>,
    Self: CheckedCast<Prim> + CheckedCastFrom<Prim>,
    Self: SaturatingCast<Prim> + SaturatingCastFrom<Prim>,
    Self: WrappingCast<Prim> + WrappingCastFrom<Prim>,
    Self: UnwrappedCast<Prim> + UnwrappedCastFrom<Prim>,
    Self: OverflowingCast<Prim> + OverflowingCastFrom<Prim>,
    Self: Sealed,
{
}

pub trait Sealed {}

impl_bits! { i8 }
impl_bits! { i16 }
impl_bits! { i32 }
impl_bits! { i64 }
impl_bits! { i128 }
impl_bits! { u8 }
impl_bits! { u16 }
impl_bits! { u32 }
impl_bits! { u64 }
impl_bits! { u128 }

#[cfg(not(feature = "arbitrary"))]
/// This trait is used to provide supertrait to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the `arbitrary` feature is enabled, [`Arbitrary`] is a supertrait of
/// [`FixedBits`].
///
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalArbitrary: Sealed {}

#[cfg(feature = "arbitrary")]
/// This trait is used to provide supertrait to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the `arbitrary` feature is enabled, [`Arbitrary`] is a supertrait of
/// [`FixedBits`].
///
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalArbitrary: Sealed
where
    Self: for<'a> Arbitrary<'a>,
{
}

#[cfg(not(feature = "borsh"))]
/// This trait is used to provide supertraits to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the `borsh` experimental feature is enabled, [`BorshSerialize`] and
/// [`BorshDeserialize`] are supertraits of [`FixedBits`].
///
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalBorsh: Sealed {}

#[cfg(feature = "borsh")]
/// This trait is used to provide supertraits to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the `borsh` experimental feature is enabled, [`BorshSerialize`] and
/// [`BorshDeserialize`] are supertraits of [`FixedBits`].
///
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalBorsh: Sealed
where
    Self: BorshSerialize + BorshDeserialize,
{
}

#[cfg(not(feature = "num-traits"))]
/// This trait is used to provide supertraits to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the [`num-traits` experimental feature][experimental features] is
/// enabled, the following are supertraits of [`FixedBits`]:
///
///   * [`PrimInt`], [`FromPrimitive`]
///   * <code>[AsPrimitive][`AsPrimitive`]&lt;T></code> where `T` can be [`i8`],
///     [`i16`], [`i32`], [`i64`], [`i128`], [`isize`], [`u8`], [`u16`],
///     [`u32`], [`u64`], [`u128`], [`usize`], [`f32`] or [`f64`]
///   * [`CheckedNeg`], [`CheckedRem`], [`CheckedShl`], [`CheckedShr`]
///   * [`SaturatingAdd`], [`SaturatingSub`], [`SaturatingMul`]
///   * [`WrappingAdd`], [`WrappingSub`], [`WrappingNeg`], [`WrappingMul`],
///     [`WrappingShl`], [`WrappingShr`]
///   * [`OverflowingAdd`], [`OverflowingSub`], [`OverflowingMul`]
///   * [`Euclid`], [`CheckedEuclid`]
///   * [`MulAdd`], [`MulAddAssign`]
///
/// [experimental features]: crate#experimental-optional-features
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalNum: Sealed {}

#[cfg(feature = "num-traits")]
/// This trait is used to provide supertraits to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the [`num-traits` experimental feature][experimental features] is
/// enabled, the following are supertraits of [`FixedBits`]:
///
///   * [`Num`], [`NumRef`], [`NumAssignRef`]
///   * [`PrimInt`], [`FromPrimitive`]
///   * <code>[AsPrimitive][`AsPrimitive`]&lt;T></code> where `T` can be [`i8`],
///     [`i16`], [`i32`], [`i64`], [`i128`], [`isize`], [`u8`], [`u16`],
///     [`u32`], [`u64`], [`u128`], [`usize`], [`f32`] or [`f64`]
///   * [`CheckedNeg`], [`CheckedRem`], [`CheckedShl`], [`CheckedShr`]
///   * [`SaturatingAdd`], [`SaturatingSub`], [`SaturatingMul`]
///   * [`WrappingAdd`], [`WrappingSub`], [`WrappingNeg`], [`WrappingMul`],
///     [`WrappingShl`], [`WrappingShr`]
///   * [`OverflowingAdd`], [`OverflowingSub`], [`OverflowingMul`]
///   * [`Euclid`], [`CheckedEuclid`]
///   * [`MulAdd`], [`MulAddAssign`]
///
/// [experimental features]: crate#experimental-optional-features
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalNum: Sealed
where
    Self: Num<FromStrRadixErr = ParseIntError> + NumRef + NumAssignRef,
    Self: PrimInt + FromPrimitive,
    Self: AsPrimitive<i8> + AsPrimitive<i16> + AsPrimitive<i32>,
    Self: AsPrimitive<i64> + AsPrimitive<i128> + AsPrimitive<isize>,
    Self: AsPrimitive<u8> + AsPrimitive<u16> + AsPrimitive<u32>,
    Self: AsPrimitive<u64> + AsPrimitive<u128> + AsPrimitive<usize>,
    Self: AsPrimitive<f32> + AsPrimitive<f64>,
    Self: CheckedNeg + CheckedRem + CheckedShl + CheckedShr,
    Self: SaturatingAdd + SaturatingSub + SaturatingMul,
    Self: WrappingAdd + WrappingSub + WrappingNeg + WrappingMul,
    Self: WrappingShl + WrappingShr,
    Self: OverflowingAdd + OverflowingSub + OverflowingMul,
    Self: Euclid + CheckedEuclid,
    Self: MulAdd + MulAddAssign,
{
}

#[cfg(not(feature = "serde"))]
/// This trait is used to provide supertraits to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the `serde` feature is enabled, [`Serialize`] and [`Deserialize`] are
/// supertraits of [`FixedBits`].
///
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalSerde: Sealed {}

#[cfg(feature = "serde")]
/// This trait is used to provide supertraits to the [`FixedBits`] trait
/// depending on the crates’s [optional features], and should not be used
/// directly.
///
/// If the `serde` feature is enabled, [`Serialize`] and [`Deserialize`] are
/// supertraits of [`FixedBits`].
///
/// [optional features]: crate#optional-features
pub trait FixedBitsOptionalSerde: Sealed
where
    Self: Serialize + for<'de> Deserialize<'de>,
{
}