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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright © 2019–2020 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>.

/*!
# Numeric casts

This crate provides casts and checked casts.

## Quick examples

```rust
use az::{Az, OverflowingAs, WrappingAs};
use core::num::Wrapping;

// Panics on overflow with `debug_assertions`, otherwise wraps
assert_eq!(12i32.az::<u32>(), 12u32);

// Always wraps
let wrapped = 1u32.wrapping_neg();
assert_eq!((-1).wrapping_as::<u32>(), wrapped);
assert_eq!((-1).overflowing_as::<u32>(), (wrapped, true));

// Wrapping can also be obtained using `Wrapping`
assert_eq!((-1).az::<Wrapping<u32>>().0, wrapped);
```

Conversions from floating-point to integers are also supported.
Numbers are rounded towards zero, but the [`Round`] wrapper can be
used to convert floating-point numbers to integers with rounding to
the nearest, with ties rounded to even.

```rust
use az::{Az, CheckedAs, Round, SaturatingAs};
use core::f32;

assert_eq!(15.7.az::<i32>(), 15);
assert_eq!(Round(15.5).az::<i32>(), 16);
assert_eq!(1.5e20.saturating_as::<i32>(), i32::max_value());
assert_eq!(f32::NAN.checked_as::<i32>(), None);
```

## Using the *az* crate

The *az* crate is available on [crates.io][*az* crate]. To use it in
your crate, add it as a dependency inside [*Cargo.toml*]:

```toml
[dependencies]
az = "1"
```

The crate requires rustc version 1.31.0 or later.

## License

This crate is free software: you can redistribute it and/or modify it
under the terms of either

  * the [Apache License, Version 2.0][LICENSE-APACHE] or
  * the [MIT License][LICENSE-MIT]

at your option.

### Contribution

Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you, as defined in the Apache
License, Version 2.0, shall be dual licensed as above, without any
additional terms or conditions.

[*Cargo.toml*]: https://doc.rust-lang.org/cargo/guide/dependencies.html
[*az* crate]: https://crates.io/crates/az
[LICENSE-APACHE]: https://www.apache.org/licenses/LICENSE-2.0
[LICENSE-MIT]: https://opensource.org/licenses/MIT
[`Round`]: struct.Round.html
*/
#![no_std]
#![warn(missing_docs)]
#![doc(html_root_url = "https://docs.rs/az/1")]
#![doc(test(attr(deny(warnings))))]
#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]

#[cfg(test)]
extern crate std;

mod float;
mod int;
#[cfg(test)]
mod tests;

/**
Used to cast values.

It is normally easier to use the [`Az`] trait instead of this trait.

# Panics

When debug assertions are enabled, this trait’s method panics if the
value does not fit in the destination. When debug assertions are *not*
enabled (usual in release mode), the wrapped value can be returned,
but it is not considered a breaking change if in the future it panics;
if wrapping is required use [`WrappingCast`] instead.

This trait’s method also panics with no debug assertions if the value
does not fit and cannot be wrapped, for example when trying to cast
floating-point ∞ into an integer type.

# Examples

```rust
use az::Cast;
let a: u32 = 5i32.cast();
assert_eq!(a, 5);
assert_eq!(Cast::<u8>::cast(17.1f32), 17);
```

[`Az`]: trait.Az.html
[`WrappingCast`]: trait.WrappingCast.html
*/
pub trait Cast<Dst> {
    /// Casts the value.
    fn cast(self) -> Dst;
}

/**
Used for checked casts.

This trait’s method returns [`None`] if the value does not fit.

It is normally easier to use the [`CheckedAs`] trait instead of this trait.

# Examples

```rust
use az::CheckedCast;
use core::f32;

let a: Option<u32> = 5i32.checked_cast();
assert_eq!(a, Some(5));
assert_eq!(CheckedCast::<u32>::checked_cast(-5i32), None);
assert_eq!(CheckedCast::<u8>::checked_cast(17.1f32), Some(17));
let b: Option<u8> = f32::NAN.checked_cast();
assert_eq!(b, None);
```

[`CheckedAs`]: trait.CheckedAs.html
[`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
*/
pub trait CheckedCast<Dst> {
    /// Casts the value.
    fn checked_cast(self) -> Option<Dst>;
}

/**
Used to cast into the destination type, saturating if the value does not fit.

It is normally easier to use the [`SaturatingAs`] trait instead of this trait.

# Panics

This trait’s method panics if the value does not fit and saturation
does not make sense, for example when trying to cast floating-point
NaN into an integer type.

# Examples

```rust
use az::SaturatingCast;
let a: u32 = (-1).saturating_cast();
assert_eq!(a, 0);
assert_eq!(SaturatingCast::<u8>::saturating_cast(17.0 + 256.0), 255);
```

[`SaturatingAs`]: trait.SaturatingAs.html
*/
pub trait SaturatingCast<Dst> {
    /// Casts the value.
    fn saturating_cast(self) -> Dst;
}

/**
Wrapping cast.

It is normally easier to use the [`WrappingAs`] trait instead of this trait.

# Panics

This trait’s method panics if the value does not fit and cannot be
wrapped, for example when trying to cast floating-point ∞ into an
integer type.

# Examples

```rust
use az::WrappingCast;
let a: u32 = (-1).wrapping_cast();
assert_eq!(a, u32::max_value());
assert_eq!(WrappingCast::<u8>::wrapping_cast(17.0 + 256.0), 17);
```

[`WrappingAs`]: trait.WrappingAs.html
*/
pub trait WrappingCast<Dst> {
    /// Casts the value.
    fn wrapping_cast(self) -> Dst;
}

/**
Used for overflowing casts.

This trait’s method returns a [tuple] of the value and a [`bool`],
indicating whether an overflow has occurred. On overflow, the wrapped
value is returned.

It is normally easier to use the [`OverflowingAs`] trait instead of this trait.

# Examples

```rust
use az::OverflowingCast;
let a: (u8, bool) = 17i32.overflowing_cast();
assert_eq!(a, (17, false));
assert_eq!(OverflowingCast::<u32>::overflowing_cast(-1), (u32::max_value(), true));
assert_eq!(OverflowingCast::<u8>::overflowing_cast(17.0 + 256.0), (17, true));
```

# Panics

This trait’s method panics if the value does not fit and cannot be
wrapped, for example when trying to cast floating-point ∞ into an
integer type.

[`OverflowingAs`]: trait.OverflowingAs.html
[`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
[tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
 */
pub trait OverflowingCast<Dst> {
    /// Casts the value.
    fn overflowing_cast(self) -> (Dst, bool);
}

/**
Used to cast values.

This is a convenience trait to enable writing `src.az::<Dst>()`. This
would not work with the <code>[Cast][`Cast`]::[cast][`cast`]</code>
method because the [`Cast`] trait is generic while the [`cast`] method
is not generic.

This trait’s method is suitable for chaining.

# Panics

When debug assertions are enabled, this trait’s method panics if the
value does not fit in the destination. When debug assertions are *not*
enabled (usual in release mode), the wrapped value can be returned,
but it is not considered a breaking change if in the future it panics;
if wrapping is required use [`WrappingAs`] instead.

This trait’s method also panics with no debug assertions if the value
does not fit and cannot be wrapped, for example when trying to cast
floating-point ∞ into an integer type.

# Examples

```rust
use az::Az;
assert_eq!(5i32.az::<u32>(), 5);
assert_eq!(17.1f32.az::<u8>(), 17);
```

[`Cast`]: trait.Cast.html
[`WrappingAs`]: trait.WrappingAs.html
[`cast`]: trait.Cast.html#tymethod.cast
*/
pub trait Az {
    /// Casts the value.
    fn az<Dst>(self) -> Dst
    where
        Self: Cast<Dst>;
}

impl<T> Az for T {
    #[inline]
    fn az<Dst>(self) -> Dst
    where
        Self: Cast<Dst>,
    {
        self.cast()
    }
}

/**
Used for checked casts.

This trait’s method returns [`None`] if the value does not fit.

This is a convenience trait to enable writing
`src.checked_as::<Dst>()`. This would not work with the
<code>[CheckedCast][`CheckedCast`]::[checked_cast][`checked_cast`]</code>
method because the [`CheckedCast`] trait is generic while the
[`checked_cast`] method is not generic.

This trait’s method is suitable for chaining.

# Examples

```rust
use az::CheckedAs;
use core::f32;

assert_eq!(5i32.checked_as::<u32>(), Some(5));
assert_eq!((-5i32).checked_as::<u32>(), None);
assert_eq!(17.1f32.checked_as::<u8>(), Some(17));
assert_eq!(f32::NAN.checked_as::<u8>(), None);
```

[`CheckedCast`]: trait.CheckedCast.html
[`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
[`checked_cast`]: trait.CheckedCast.html#tymethod.checked_cast
*/
pub trait CheckedAs {
    /// Casts the value.
    fn checked_as<Dst>(self) -> Option<Dst>
    where
        Self: CheckedCast<Dst>;
}

impl<T> CheckedAs for T {
    #[inline]
    fn checked_as<Dst>(self) -> Option<Dst>
    where
        Self: CheckedCast<Dst>,
    {
        self.checked_cast()
    }
}

/**
Used to cast into the destination type, saturating if the value does not fit.

This is a convenience trait to enable writing
`src.saturating_as::<Dst>()`. This would not work with the
<code>[SaturatingCast][`SaturatingCast`]::[saturating_cast][`saturating_cast`]</code>
method because the [`SaturatingCast`] trait is generic while the
[`saturating_cast`] method is not generic.

This trait’s method is suitable for chaining.

# Panics

This trait’s method panics if the value does not fit and saturation
does not make sense, for example when trying to cast floating-point
NaN into an integer type.

# Examples

```rust
use az::SaturatingAs;
assert_eq!((-1).saturating_as::<u32>(), 0);
assert_eq!((17.0 + 256.0).saturating_as::<u8>(), 255);
```

[`SaturatingCast`]: trait.SaturatingCast.html
[`saturating_cast`]: trait.SaturatingCast.html#tymethod.saturating_cast
*/
pub trait SaturatingAs {
    /// Casts the value.
    fn saturating_as<Dst>(self) -> Dst
    where
        Self: SaturatingCast<Dst>;
}

impl<T> SaturatingAs for T {
    #[inline]
    fn saturating_as<Dst>(self) -> Dst
    where
        Self: SaturatingCast<Dst>,
    {
        self.saturating_cast()
    }
}

/**
Wrapping cast.

This is a convenience trait to enable writing
`src.wrapping_as::<Dst>()`. This would not work with the
<code>[WrappingCast][`WrappingCast`]::[wrapping_cast][`wrapping_cast`]</code>
method because the [`WrappingCast`] trait is generic while the
[`wrapping_cast`] method is not generic.

This trait’s method is suitable for chaining.

# Panics

This trait’s method panics if the value does not fit and cannot be
wrapped, for example when trying to cast floating-point ∞ into an
integer type.

# Examples

```rust
use az::WrappingAs;
assert_eq!((-1).wrapping_as::<u32>(), u32::max_value());
assert_eq!((17.0 + 256.0).wrapping_as::<u8>(), 17);
```

[`WrappingCast`]: trait.WrappingCast.html
[`wrapping_cast`]: trait.WrappingCast.html#tymethod.wrapping_cast
*/
pub trait WrappingAs {
    /// Casts the value.
    fn wrapping_as<Dst>(self) -> Dst
    where
        Self: WrappingCast<Dst>;
}

impl<T> WrappingAs for T {
    #[inline]
    fn wrapping_as<Dst>(self) -> Dst
    where
        Self: WrappingCast<Dst>,
    {
        self.wrapping_cast()
    }
}

/**
Used for overflowing casts.

This trait’s method returns a [tuple] of the value and a [`bool`],
indicating whether an overflow has occurred. On overflow, the wrapped
value is returned.

This is a convenience trait to enable writing
`src.overflowing_as::<Dst>()`. This would not work with the
<code>[OverflowingCast][`OverflowingCast`]::[overflowing_cast][`overflowing_cast`]</code>
method because the [`OverflowingCast`] trait is generic while the
[`overflowing_cast`] method is not generic.

This trait’s method is suitable for chaining.

# Panics

This trait’s method panics if the value does not fit and cannot be
wrapped, for example when trying to cast floating-point ∞ into an
integer type.

# Examples

```rust
use az::OverflowingAs;
assert_eq!(17i32.overflowing_as::<u8>(), (17, false));
assert_eq!((-1).overflowing_as::<u32>(), (u32::max_value(), true));
assert_eq!((17.0 + 256.0).overflowing_as::<u8>(), (17, true));
```

[`OverflowingCast`]: trait.OverflowingCast.html
[`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
[`overflowing_cast`]: trait.OverflowingCast.html#tymethod.overflowing_cast
[tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
*/
pub trait OverflowingAs {
    /// Casts the value.
    fn overflowing_as<Dst>(self) -> (Dst, bool)
    where
        Self: OverflowingCast<Dst>;
}

impl<T> OverflowingAs for T {
    #[inline]
    fn overflowing_as<Dst>(self) -> (Dst, bool)
    where
        Self: OverflowingCast<Dst>,
    {
        self.overflowing_cast()
    }
}

/// Casts the value.
///
/// # Panics
///
/// When debug assertions are enabled, panics if the value does not
/// fit in the destination. When debug assertions are *not* enabled
/// (usual in release mode), the wrapped value can be returned, but it
/// is not considered a breaking change if in the future it panics; if
/// wrapping is required use [`wrapping_cast`] instead.
///
/// This function also panics with no debug assertions if the value
/// does not fit and cannot be wrapped, for example when trying to
/// cast floating-point ∞ into an integer type.
///
/// [`wrapping_cast`]: fn.wrapping_cast.html
///
/// # Examples
///
/// ```rust
/// assert_eq!(az::cast::<i32, u32>(5), 5);
/// assert_eq!(az::cast::<f32, u8>(17.1), 17);
/// ```
#[inline]
pub fn cast<Src: Cast<Dst>, Dst>(src: Src) -> Dst {
    src.cast()
}

/// Casts the value, returning [`None`] if the value does not fit.
///
/// [`None`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.None
///
/// # Examples
///
/// ```rust
/// use core::f32;
///
/// assert_eq!(az::checked_cast::<i32, u32>(5), Some(5));
/// assert_eq!(az::checked_cast::<i32, u32>(-5), None);
/// assert_eq!(az::checked_cast::<f32, u8>(17.1), Some(17));
/// assert_eq!(az::checked_cast::<f32, u8>(f32::NAN), None);
/// ```
#[inline]
pub fn checked_cast<Src: CheckedCast<Dst>, Dst>(src: Src) -> Option<Dst> {
    src.checked_cast()
}

/// Casts the value, saturating if the value does not fit.
///
/// # Panics
///
/// Panics if the value does not fit and saturation does not make
/// sense, for example when trying to cast floating-point NaN into an
/// integer type.
///
/// # Examples
///
/// ```rust
/// assert_eq!(az::saturating_cast::<i32, u32>(-1), 0);
/// assert_eq!(az::saturating_cast::<f32, u8>(17.0 + 256.0), 255);
/// ```
#[inline]
pub fn saturating_cast<Src: SaturatingCast<Dst>, Dst>(src: Src) -> Dst {
    src.saturating_cast()
}

/// Casts the value, wrapping on overflow.
///
/// # Panics
///
/// Panics if the value does not fit and cannot be wrapped, for
/// example when trying to cast floating-point ∞ into an integer type.
///
/// # Examples
///
/// ```rust
/// assert_eq!(az::wrapping_cast::<i32, u32>(-1), u32::max_value());
/// assert_eq!(az::wrapping_cast::<f32, u8>(17.0 + 256.0), 17);
/// ```
#[inline]
pub fn wrapping_cast<Src: WrappingCast<Dst>, Dst>(src: Src) -> Dst {
    src.wrapping_cast()
}

/// Overflowing cast.
///
/// Returns a [tuple] of the value and a [`bool`], indicating whether
/// an overflow has occurred. On overflow, the wrapped value is
/// returned.
///
/// # Panics
///
/// Panics if the value does not fit and cannot be wrapped, for
/// example when trying to cast floating-point ∞ into an integer type.
///
/// # Examples
///
/// ```rust
/// assert_eq!(az::overflowing_cast::<i32, u32>(-1), (u32::max_value(), true));
/// assert_eq!(az::overflowing_cast::<f32, u8>(17.0 + 256.0), (17, true));
/// ```
///
/// [`bool`]: https://doc.rust-lang.org/nightly/std/primitive.bool.html
/// [tuple]: https://doc.rust-lang.org/nightly/std/primitive.tuple.html
#[inline]
pub fn overflowing_cast<Src: OverflowingCast<Dst>, Dst>(src: Src) -> (Dst, bool) {
    src.overflowing_cast()
}

/// Used to convert floating-point numbers to integers with rounding
/// to the nearest, with ties rounded to even.
///
/// The underlying value can be retrieved through the `.0` index.
///
/// # Examples
///
/// ```rust
/// use az::Round;
/// assert_eq!(az::cast::<_, i32>(Round(0.4)), 0);
/// assert_eq!(az::cast::<_, i32>(Round(0.6)), 1);
/// // ties rounded to even
/// assert_eq!(az::cast::<_, i32>(Round(-0.5)), 0);
/// assert_eq!(az::cast::<_, i32>(Round(-1.5)), -2);
/// ```
#[repr(transparent)]
#[derive(Clone, Copy, Default, Debug, PartialEq, PartialOrd)]
pub struct Round<T>(pub T);