ranch 0.6.0

Ranged integer types and math
Documentation
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use core::num::NonZero;

use as_repr::AsRepr;

use crate::{Error, Quotient, RangedI32, RangedU32, Result};

/// [`i32`] not to equal zero with a specified minimum and maximum value
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[repr(transparent)]
pub struct RangedNonZeroI32<const MIN: i32, const MAX: i32>(
    pub(crate) NonZero<i32>,
);

impl<const MIN: i32, const MAX: i32> RangedNonZeroI32<MIN, MAX> {
    /// The size of this integer type in bits.
    pub const BITS: u32 = i32::BITS;
    /// The largest value that can be represented by this integer type.
    pub const MAX: Self = Self::new::<MAX>();
    /// The smallest value that can be represented by this integer type.
    pub const MIN: Self = Self::new::<MIN>();

    /// Create a new ranged integer.
    ///
    /// Won't compile if out of bounds.
    ///
    /// Compiles:
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// RangedNonZeroI32::<-1, 3>::new::<1>();
    /// RangedNonZeroI32::<-1, 3>::new::<2>();
    /// RangedNonZeroI32::<-1, 3>::new::<3>();
    /// ```
    ///
    /// Does not compile:
    ///
    /// ```compile_fail
    /// RangedNonZeroI32::<-1, 3>::new::<-2>();
    /// ```
    ///
    /// ```compile_fail
    /// RangedNonZeroI32::<-1, 3>::new::<0>();
    /// ```
    ///
    /// ```compile_fail
    /// RangedNonZeroI32::<-1, 3>::new::<4>();
    /// ```
    #[must_use]
    pub const fn new<const N: i32>() -> Self {
        const {
            Self::assert_range();

            if N < MIN || N > MAX {
                panic!("Out of bounds");
            }

            Self(NonZero::new(N).unwrap())
        }
    }

    /// Try to create a new ranged integer.
    ///
    /// Returns `Err` if out of bounds, `Ok(None)` if zero.
    ///
    /// ```rust
    /// # use ranch::{RangedNonZeroI32, Error};
    /// RangedNonZeroI32::<-1, 1>::with_i32(-1).unwrap().unwrap();
    /// RangedNonZeroI32::<-1, 1>::with_i32(1).unwrap().unwrap();
    /// assert_eq!(RangedNonZeroI32::<-1, 1>::with_i32(0), Ok(None));
    /// assert_eq!(RangedNonZeroI32::<-1, 1>::with_i32(-2).unwrap_err(), Error::NegOverflow);
    /// assert_eq!(RangedNonZeroI32::<-1, 1>::with_i32(2).unwrap_err(), Error::PosOverflow);
    /// ```
    pub const fn with_i32(value: impl AsRepr<i32>) -> Result<Option<Self>> {
        const { Self::assert_range() };

        let value = as_repr::as_repr(value);
        let Some(value) = NonZero::new(value) else {
            return Ok(None);
        };

        match Self::with_nonzero(value) {
            Ok(v) => Ok(Some(v)),
            Err(e) => Err(e),
        }
    }

    /// Convert from [`NonZero`].
    ///
    /// ```rust
    /// # use std::num::NonZero;
    /// # use ranch::RangedNonZeroI32;
    /// assert_eq!(
    ///     RangedNonZeroI32::<1, 100>::with_nonzero(NonZero::new(42).unwrap()).unwrap(),
    ///     RangedNonZeroI32::<1, 100>::new::<42>(),
    /// );
    /// ```
    pub const fn with_nonzero(
        nonzero: impl AsRepr<NonZero<i32>>,
    ) -> Result<Self> {
        const { Self::assert_range() };

        let nonzero = as_repr::as_repr(nonzero);

        if nonzero.get() < MIN {
            return Err(Error::NegOverflow);
        }

        if nonzero.get() > MAX {
            return Err(Error::PosOverflow);
        }

        Ok(Self(nonzero))
    }

    /// Return the contained value as a primitive type.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// assert_eq!(42, RangedNonZeroI32::<1, 100>::new::<42>().get());
    /// ```
    #[must_use]
    pub const fn get(self) -> i32 {
        self.0.get()
    }

    /// Convert to [`NonZero`].
    ///
    /// ```rust
    /// # use std::num::NonZero;
    /// # use ranch::RangedNonZeroI32;
    /// assert_eq!(
    ///     NonZero::new(42).unwrap(),
    ///     RangedNonZeroI32::<1, 100>::new::<42>().to_nonzero(),
    /// );
    /// ```
    #[must_use]
    pub const fn to_nonzero(self) -> NonZero<i32> {
        self.0
    }

    /// Convert to [`RangedI32`].
    ///
    /// ```rust
    /// # use ranch::{RangedNonZeroI32, RangedI32};
    /// assert_eq!(
    ///     RangedI32::<1, 100>::new::<42>(),
    ///     RangedNonZeroI32::<1, 100>::new::<42>().to_ranged(),
    /// );
    /// ```
    #[must_use]
    pub const fn to_ranged(self) -> RangedI32<MIN, MAX> {
        RangedI32(self.get())
    }

    /// Return the number of leading zeros in the binary representation of
    /// `self`.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// let n = RangedNonZeroI32::<{ i32::MIN }, { i32::MAX }>::MAX;
    ///
    /// assert_eq!(n.leading_zeros().get(), 1);
    /// ```
    #[must_use]
    pub const fn leading_zeros(self) -> RangedU32<0, { i32::BITS }> {
        RangedU32(self.get().leading_zeros())
    }

    /// Return the number of trailing zeros in the binary representation of
    /// `self`.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// let n = RangedNonZeroI32::<-128, 127>::new::<0b0101000>();
    ///
    /// assert_eq!(n.trailing_zeros().get(), 3);
    /// ```
    #[must_use]
    pub const fn trailing_zeros(self) -> RangedU32<0, { i32::BITS }> {
        RangedU32(self.get().trailing_zeros())
    }

    /// Return the number of ones in the binary representation of `self`.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// let a = RangedNonZeroI32::<-128, 127>::new::<0b100_0000>();
    /// let b = RangedNonZeroI32::<-128, 127>::new::<0b100_0011>();
    ///
    /// assert_eq!(a.count_ones().get(), 1);
    /// assert_eq!(b.count_ones().get(), 3);
    /// ```
    #[must_use]
    pub const fn count_ones(self) -> RangedU32<0, { i32::BITS }> {
        RangedU32(self.get().count_ones())
    }

    /// Add two ranged integers together.
    ///
    /// Returns an [`Error`] on overflow.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// let a = RangedNonZeroI32::<1, 100>::new::<50>();
    /// let b = RangedNonZeroI32::<1, 100>::new::<5>();
    /// let c = a.checked_add(b).unwrap().unwrap();
    ///
    /// assert!(c.checked_add(a).is_err());
    /// assert_eq!(c.get(), 55);
    /// assert_eq!(a.checked_add(a).unwrap().unwrap().get(), 100);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn checked_add(
        self,
        other: impl AsRepr<i32>,
    ) -> Result<Option<Self>> {
        match self.to_ranged().checked_add(other) {
            Ok(value) => Ok(value.to_ranged_nonzero()),
            Err(e) => Err(e),
        }
    }

    /// Multiply two ranged integers together.
    ///
    /// Returns an [`Error`] on overflow.
    ///
    /// ```rust
    /// # use ranch::{Error, RangedNonZeroI32};
    /// let a = RangedNonZeroI32::<-100, 100>::new::<50>();
    /// let b = RangedNonZeroI32::<-100, 100>::new::<5>();
    /// let c = RangedNonZeroI32::<-100, 100>::new::<-75>();
    ///
    /// assert_eq!(b.checked_mul(b).unwrap().unwrap().get(), 25);
    /// assert_eq!(a.checked_mul(c).unwrap_err(), Error::NegOverflow);
    /// assert_eq!(c.checked_mul(c).unwrap_err(), Error::PosOverflow);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn checked_mul(
        self,
        other: impl AsRepr<i32>,
    ) -> Result<Option<Self>> {
        match self.to_ranged().checked_mul(other) {
            Ok(value) => Ok(value.to_ranged_nonzero()),
            Err(e) => Err(e),
        }
    }

    /// Raise to an integer power.
    ///
    /// Returns an [`Error`] on overflow.
    ///
    /// ```rust
    /// # use ranch::{Error, RangedNonZeroI32};
    /// let a = RangedNonZeroI32::<-100, 100>::new::<50>();
    /// let b = RangedNonZeroI32::<-100, 100>::new::<5>();
    /// let c = RangedNonZeroI32::<-100, 100>::new::<-75>();
    /// let d = RangedNonZeroI32::<-100, 100>::new::<2>();
    ///
    /// assert_eq!(a.checked_pow(2).unwrap_err(), Error::PosOverflow);
    /// assert_eq!(b.checked_pow(2).unwrap().get(), 25);
    /// assert_eq!(c.checked_pow(3).unwrap_err(), Error::NegOverflow);
    /// assert_eq!(d.checked_pow(3).unwrap().get(), 8);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn checked_pow(self, other: impl AsRepr<u32>) -> Result<Self> {
        match self.to_ranged().checked_pow(other) {
            Ok(value) => Ok(value.to_ranged_nonzero().unwrap()),
            Err(e) => Err(e),
        }
    }

    /// Checked integer division.
    ///
    /// Returns an [`Error`] on overflow; [`Quotient::Nan`] if `rhs == 0`.
    ///
    /// ```rust
    /// # use ranch::{Error, RangedNonZeroI32, Quotient};
    /// let a = RangedNonZeroI32::<-100, 10>::new::<-50>();
    /// let b = RangedNonZeroI32::<-10, 100>::new::<50>();
    ///
    /// assert_eq!(
    ///     a.checked_div(2),
    ///     Ok(Some(Quotient::Number(RangedNonZeroI32::new::<-25>()))),
    /// );
    /// assert_eq!(a.checked_div(0), Ok(Some(Quotient::Nan)));
    /// assert_eq!(a.checked_div(-1), Err(Error::PosOverflow));
    /// assert_eq!(b.checked_div(-2), Err(Error::NegOverflow));
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn checked_div(
        self,
        rhs: impl AsRepr<i32>,
    ) -> Result<Option<Quotient<Self>>> {
        let value = match self.to_ranged().checked_div(rhs) {
            Ok(value) => value,
            Err(e) => return Err(e),
        };
        let Quotient::Number(number) = value else {
            return Ok(Some(Quotient::Nan));
        };
        let Some(number) = number.to_ranged_nonzero() else {
            return Ok(None);
        };

        Ok(Some(Quotient::Number(number)))
    }

    /// Subtract a ranged integers from another.
    ///
    /// Returns an [`Error`] on overflow.
    ///
    /// ```rust
    /// # use ranch::{Error, RangedNonZeroI32};
    /// let a = RangedNonZeroI32::<1, 100>::new::<50>();
    /// let b = a.checked_sub(5).unwrap().unwrap();
    ///
    /// assert_eq!(a.checked_sub(-51), Err(Error::PosOverflow));
    /// assert_eq!(b.get(), 45);
    /// assert_eq!(a.checked_sub(a), Err(Error::NegOverflow));
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn checked_sub(
        self,
        other: impl AsRepr<i32>,
    ) -> Result<Option<Self>> {
        match self.to_ranged().checked_sub(other) {
            Ok(value) => Ok(value.to_ranged_nonzero()),
            Err(e) => Err(e),
        }
    }

    /// Return `true` if `self` is negative; `false` if zero or positive.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// assert!(!RangedNonZeroI32::<-100, 100>::new::<10>().is_negative());
    /// assert!(RangedNonZeroI32::<-100, 100>::new::<-10>().is_negative());
    /// ```
    #[must_use]
    pub const fn is_negative(self) -> bool {
        self.get().is_negative()
    }

    /// Return `true` if `self` is positive; `false` if zero or negative.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// assert!(RangedNonZeroI32::<-100, 100>::new::<10>().is_positive());
    /// assert!(!RangedNonZeroI32::<-100, 100>::new::<-10>().is_positive());
    /// ```
    #[must_use]
    pub const fn is_positive(self) -> bool {
        self.get().is_positive()
    }

    /// Multiply two numbers together.
    ///
    /// ```rust
    /// # use ranch::RangedNonZeroI32;
    /// let a = RangedNonZeroI32::<-2, 3>::new::<1>();
    /// let b = RangedNonZeroI32::<-1, 3>::new::<2>();
    /// let output: RangedNonZeroI32::<-6, 9> = a.mul_ranged(b);
    ///
    /// assert_eq!(output.get(), 2);
    /// ```
    ///
    /// Does not compile:
    ///
    /// ```compile_fail
    /// # use ranch::RangedNonZeroI32;
    /// let a = RangedNonZeroI32::<-2, 3>::new::<1>();
    /// let b = RangedNonZeroI32::<-1, 3>::new::<2>();
    /// let output: RangedNonZeroI32::<0, 9> = a.mul_ranged(b);
    ///
    /// assert_eq!(output.get(), 2);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn mul_ranged<
        const RHS_MIN: i32,
        const RHS_MAX: i32,
        const OUTPUT_MIN: i32,
        const OUTPUT_MAX: i32,
    >(
        self,
        rhs: RangedNonZeroI32<RHS_MIN, RHS_MAX>,
    ) -> RangedNonZeroI32<OUTPUT_MIN, OUTPUT_MAX> {
        self.to_ranged()
            .mul_ranged::<RHS_MIN, RHS_MAX, OUTPUT_MIN, OUTPUT_MAX>(
                rhs.to_ranged(),
            )
            .to_ranged_nonzero()
            .unwrap()
    }

    /// Raise to an integer power.
    ///
    /// ```rust
    /// # use ranch::{RangedNonZeroI32, RangedU32};
    /// let a = RangedNonZeroI32::<-1, 3>::new::<2>();
    /// let b = RangedU32::<2, 3>::new::<2>();
    /// let output: RangedNonZeroI32::<-1, 27> = a.pow_ranged(b);
    ///
    /// assert_eq!(output.get(), 4);
    /// ```
    ///
    /// Does not compile:
    ///
    /// ```compile_fail
    /// # use ranch::{RangedNonZeroI32, RangedU32};
    /// let a = RangedNonZeroI32::<1, 3>::new::<2>();
    /// let b = RangedU32::<2, 3>::new::<2>();
    /// let output: RangedNonZeroI32::<0, 27> = a.pow_ranged(b);
    ///
    /// assert_eq!(output.get(), 4);
    /// ```
    #[must_use = "this returns the result of the operation, \
                  without modifying the original"]
    pub const fn pow_ranged<
        const RHS_MIN: u32,
        const RHS_MAX: u32,
        const OUTPUT_MIN: i32,
        const OUTPUT_MAX: i32,
    >(
        self,
        rhs: RangedU32<RHS_MIN, RHS_MAX>,
    ) -> RangedNonZeroI32<OUTPUT_MIN, OUTPUT_MAX> {
        self.to_ranged()
            .pow_ranged::<RHS_MIN, RHS_MAX, OUTPUT_MIN, OUTPUT_MAX>(rhs)
            .to_ranged_nonzero()
            .unwrap()
    }
}

impl<const MIN: i32, const MAX: i32> crate::error::Clamp
    for RangedNonZeroI32<MIN, MAX>
{
    const MAX: Self = Self::MAX;
    const MIN: Self = Self::MIN;
}