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
// Copyright © 2019 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 checked, overflowing and static casts.

## Quick examples

```rust
use core::num::Wrapping;

// Panics on overflow with `debug_assertions`, otherwise wraps.
let a: u32 = az::cast(12i32);
assert_eq!(a, 12);

// Always wraps.
let b: u32 = az::wrapping_cast(-1i32);
assert_eq!(b, u32::max_value());
let c = az::overflowing_cast::<i32, u32>(-1i32);
assert_eq!(c, (u32::max_value(), true));

// Wrapping can also be obtained using `Wrapping`
let d: Wrapping<u32> = az::cast(-1);
assert_eq!(d.0, u32::max_value());
```

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::Round;
use core::f32;

assert_eq!(az::cast::<_, i32>(15.7), 15);
assert_eq!(az::cast::<_, i32>(Round(15.5)), 16);
assert_eq!(az::saturating_cast::<_, i32>(1.5e20), i32::max_value());
assert_eq!(az::checked_cast::<_, i32>(f32::NAN), 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 = "0.1.0"
```

## 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/0.1.0")]
#![doc(test(attr(deny(warnings))))]
#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]

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

/**
Used to cast values.

# 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.

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

/**
Used for checked casts.

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

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

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

# 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.
*/
pub trait SaturatingAs<Dst> {
    /// Casts the value.
    fn saturating_as(self) -> Dst;
}

/**
Wrapping cast.

# 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.
*/
pub trait WrappingAs<Dst> {
    /// Casts the value.
    fn wrapping_as(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.

# 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.

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

/**
Casts into the destination type, returning [`()`] if the
destination type cannot hold all values of the source type.

[`()`]: https://doc.rust-lang.org/nightly/std/primitive.unit.html

For most cases, using [`From`] makes more sense than using this trait.
The main differences are

  * This trait is implemented even when the conversion cannot always
    take place, in which case the output will always be [`()`].
  * This trait converts all integer and floating-point primitives to
    floating-point primitives, even if some precision is lost. For
    example you can use `StaticAs` to convert [`i64`] to [`f32`] even
    though some precision may be lost.

[`()`]: https://doc.rust-lang.org/nightly/std/primitive.unit.html
[`From`]: https://doc.rust-lang.org/nightly/core/convert/trait.From.html
[`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
[`i64`]: https://doc.rust-lang.org/nightly/std/primitive.i64.html
*/
pub trait StaticAs<Dst> {
    /// `Dst` if the cast always works, otherwise [`()`].
    ///
    /// [`()`]: https://doc.rust-lang.org/nightly/std/primitive.unit.html
    type Output;

    /// Casts if the conversion works for all source type values,
    /// otherwise returns [`()`].
    ///
    /// [`()`]: https://doc.rust-lang.org/nightly/std/primitive.unit.html
    fn static_as(self) -> Self::Output;
}

/// 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: Az<Dst>, Dst>(src: Src) -> Dst {
    src.az()
}

/// 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: CheckedAs<Dst>, Dst>(src: Src) -> Option<Dst> {
    src.checked_as()
}

/// 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: SaturatingAs<Dst>, Dst>(src: Src) -> Dst {
    src.saturating_as()
}

/// 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: WrappingAs<Dst>, Dst>(src: Src) -> Dst {
    src.wrapping_as()
}

/// 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: OverflowingAs<Dst>, Dst>(src: Src) -> (Dst, bool) {
    src.overflowing_as()
}

/// Casts the value.
///
/// Since the bound specifies that
/// <code>&lt;Src as [StaticAs][`StaticAs`]&lt;Dst&gt;&gt;::[Output][`Output`] = Dst</code>,
/// the cast should always work.
///
/// For most cases, using <code>src.[into][`into`]()</code> makes more
/// sense than using this function. The main differences is that this
/// function can be used to convert all integer and floating-point
/// primitives to floating-point primitives, even if some precision is
/// lost. For example you can use `static_cast` to convert [`i64`] to
/// [`f32`] even though some precision may be lost.
///
/// # Examples
///
/// ```rust
/// assert_eq!(az::static_cast::<u32, i64>(15), 15);
/// assert_eq!(az::static_cast::<i32, f32>(-12), -12.0);
/// // 20_000_003 in f32 is rounded to 20_000_004 (24 bits of precision)
/// assert_eq!(az::static_cast::<u32, f32>(20_000_003), 20_000_004.0);
/// ```
///
/// The following would fail to compile because the conversions would
/// not work for all values, even though 0 fits in all types.
///
/// ```compile_fail
/// // i32 to u64 would fail for negative numbers
/// assert_eq!(az::static_cast::<i32, u64>(0), 0);
/// // f32 to i32 would fail for infinite or NaN
/// assert_eq!(az::static_cast::<f32, i32>(0.0), 0);
/// ```
///
/// [`()`]: https://doc.rust-lang.org/nightly/std/primitive.unit.html
/// [`StaticAs`]: trait.StaticAs.html
/// [`Output`]: trait.StaticAs.html#associatedtype.Output
/// [`f32`]: https://doc.rust-lang.org/nightly/std/primitive.f32.html
/// [`i64`]: https://doc.rust-lang.org/nightly/std/primitive.i64.html
/// [`into`]: https://doc.rust-lang.org/nightly/core/convert/trait.Into.html#tymethod.into
#[inline]
pub fn static_cast<Src, Dst>(src: Src) -> Dst
where
    Src: StaticAs<Dst, Output = Dst>,
{
    src.static_as()
}

/// 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);