### 2 releases

0.4.0 | Oct 6, 2024 |
---|---|

0.4.0-alpha.1 | Dec 29, 2023 |

#**287** in Rust patterns

**37** downloads per month

**MIT**license

66KB

966 lines

is a fork of `conv2`

,
written by Daniel Keep. It's in the progress of being updated to modern
idiomatic Rust.`conv`

This crate provides a number of conversion traits with more specific
semantics than those provided by

or `as`

/`From`

.`Into`

The goal with the traits provided here is to be more specific about what
generic code can rely on, as well as provide reasonably self-describing
alternatives to the standard

/`From`

traits. For example, the
although `Into`

might be satisfied, it imposes no restrictions on
the `T : From<U>`

*kind*of conversion being implemented. As such, the traits in this crate try to be very specific about what conversions are allowed. This makes them less generally applicable, but more useful where they

*do*apply.

In addition,

/`From`

requires all conversions to succeed or panic.
All conversion traits in this crate define an associated error type,
allowing code to react to failed conversions as appropriate.`Into`

## Compatibility

is compatible with Rust 1.61 and higher.`conv2`

# Overview

The following traits are used to define various conversion semantics:

- approximate conversions, with selectable approximation scheme (see`ApproxFrom`

).`ApproxScheme`

- exact, value-preserving conversions.`ValueFrom`

When *defining* a conversion, try to implement the

trait variant
where possible. When `*``From`*using* a conversion, try to depend on the

trait variant where possible. This is because the `*``Into`

traits
automatically use `*``Into`

implementations, but not the reverse.
Implementing `*``From`

and using `*``From`

ensures conversions work in as many
contexts as possible.`*``Into`

These extension methods are provided to help with some common cases:

- approximates to`ConvUtil`approx_as`::`

with the`Dst`

scheme.`DefaultApprox`

- approximates to`ConvUtil`approx_as_by`::`

with the scheme`Dst`

.`S`

- converts to`ConvUtil`into_as`::``<`Dst`>`

using`Dst`

.`Into`into`::`

- converts to`ConvUtil`try_as`::``<`Dst`>`

using`Dst`

.`TryInto`try_into`::`

- converts to`ConvUtil`value_as`::``<`Dst`>`

using`Dst`

.`ValueInto`value_into`::`

- approximates to an inferred destination type with the`ConvAsUtil`approx`::`

scheme.`DefaultApprox`

- approximates to an inferred destination type with the scheme`ConvAsUtil`approx_by`::`

.`S`

- saturates on overflow.`Saturate`saturate`::`

- unwraps results from conversions that cannot fail.`UnwrapOk`unwrap_ok`::`

- saturates to ±∞ on failure.`UnwrapOrInf`unwrap_or_inf`::`

- substitutes the target type's "invalid" sentinel value on failure.`UnwrapOrInvalid`unwrap_or_invalid`::`

- saturates to the maximum or minimum value of the target type on failure.`UnwrapOrSaturate`unwrap_or_saturate`::`

## Provided Implementations

The crate provides several blanket implementations:

(all types can be converted from and into themselves).`*``From``<`A`>``for`A

(`*``Into``<`Dst`>``for`Src`where`Dst`:``*``From``<`Src`>`

implementations imply a matching`*``From`

implementation).`*``Into`

Conversions for the builtin numeric (integer and floating point) types are
provided. In general,

conversions exist for all pairs except
for float → integer (since such a conversion is generally unlikely to
`ValueFrom`*exactly* succeed) and

(for the same reason). `f64` → `f32`

conversions with the `ApproxFrom`

scheme exist between all pairs.
`DefaultApprox`

with the `ApproxFrom`

scheme exist between integers.`Wrapping`

## Errors

A number of error types are defined in the

module. Generally,
conversions use whichever error type most `errors`*narrowly* defines the kinds of
failures that can occur. For example:

cannot possibly fail, and as such it uses`ValueFrom``<``u8``>``for``u16`

.`NoError`

can`ValueFrom``<``i8``>``for``u16`*only*fail with a negative overflow, thus it uses the

type.`NegOverflow`

can overflow in either direction, hence it uses`ValueFrom``<``i32``>``for``u16`

.`RangeError`- Finally,

can overflow (positive or negative), or attempt to convert NaN;`ApproxFrom``<``f32``>``for``u16`

covers those three cases.`FloatError`

Because there are *numerous* error types, the

enum is
provided. `GeneralError`

exists for each error type
`From``<`E, T`>``for` `GeneralError <T>`

`E``<`T`>`

defined by this crate (even for `NoError`

!), allowing errors to be
translated automatically by the `?`

operator. In fact, all errors can be
"expanded" to *all*more general forms (

*e.g.*

`NoError`

→ `NegOverflow`

,
`PosOverflow`

→ `RangeError`

→ `FloatError`

).Aside from

, the various error types wrap the input value that you
attempted to convert. This is so that non-`NoError`

types do not need to be
pre-emptively cloned prior to conversion, just in case the conversion
fails. A downside is that this means there are many, `Copy`*many* incompatible
error types.

To help alleviate this, there is also

, which is simply
`GeneralErrorKind`

without the payload, and all errors can be converted
into it directly.`GeneralError <T>`

The reason for not just using

in the first place is to
statically reduce the number of potential error cases you need to deal
with. It also allows the `GeneralErrorKind`

extension traits to be defined `Unwrap *`

*without*the possibility for runtime failure (

*e.g.*you cannot use

`unwrap_or_saturate`

with a `FloatError`

, because what do you do if the
error is `NotANumber`

; saturate to max or to min? Or panic?).# Examples

`
``//` This *cannot* fail, so we can use `unwrap_ok` to discard the `Result`.
`assert_eq!``(``u8``::`value_from`(``0``u8``)``.``unwrap_ok``(``)``,` `0``u8``)``;`
`//` This *can* fail. Specifically, it can overflow toward negative infinity.
`assert_eq!``(``u8``::`value_from`(``0``i8``)``,` `Ok``(``0``u8``)``)``;`
`assert_eq!``(``u8``::`value_from`(``-``1``i8``)``,` `Err``(`NegOverflow`(``-``1``)``)``)``;`
`//` This can overflow in *either* direction; hence the change to `RangeError`.
`assert_eq!``(``u8``::`value_from`(``-``1``i16``)``,` `Err``(``RangeError``::`NegOverflow`(``-``1``)``)``)``;`
`assert_eq!``(``u8``::`value_from`(``0``i16``)``,` `Ok``(``0``u8``)``)``;`
`assert_eq!``(``u8``::`value_from`(``256``i16``)``,` `Err``(``RangeError``::`PosOverflow`(``256``)``)``)``;`
`//` We can use the extension traits to simplify this a little.
`assert_eq!``(``u8``::`value_from`(``-``1``i16``)``.``unwrap_or_saturate``(``)``,` `0``u8``)``;`
`assert_eq!``(``u8``::`value_from`(``0``i16``)``.``unwrap_or_saturate``(``)``,` `0``u8``)``;`
`assert_eq!``(``u8``::`value_from`(``256``i16``)``.``unwrap_or_saturate``(``)``,` `255``u8``)``;`
`//` Obviously, all integers can be "approximated" using the default scheme (it
`//` doesn't *do* anything), but they can *also* be approximated with the
`//` `Wrapping` scheme.
`assert_eq!``(`
`<``u8` `as` `ApproxFrom``<``_`, DefaultApprox`>``>``::`approx_from`(``400``u16``)``,`
`Err``(`PosOverflow`(``400``)``)``)``;`
`assert_eq!``(`
`<``u8` `as` `ApproxFrom``<``_`, Wrapping`>``>``::`approx_from`(``400``u16``)``,`
`Ok``(``144``u8``)``)``;`
`//` This is rather inconvenient; as such, there are a number of convenience
`//` extension methods available via `ConvUtil` and `ConvAsUtil`.
`assert_eq!``(``400``u16``.``approx``(``)``,` `Err``:``:``<``u8`, `_``>``(`PosOverflow`(``400``)``)``)``;`
`assert_eq!``(``400``u16``.``approx_by``::``<`Wrapping`>``(``)``,` `Ok``:``:``<``u8`, `_``>``(``144``u8``)``)``;`
`assert_eq!``(``400``u16``.``approx_as``::``<``u8``>``(``)``,` `Err``(`PosOverflow`(``400``)``)``)``;`
`assert_eq!``(``400``u16``.``approx_as_by``::``<``u8`, Wrapping`>``(``)``,` `Ok``(``144``)``)``;`
`//` Integer -> float conversions *can* fail due to limited precision.
`//` Once the continuous range of exactly representable integers is exceeded, the
`//` provided implementations fail with overflow errors.
`assert_eq!``(``f32``::`value_from`(``16_777_216``i32``)``,` `Ok``(``16_777_216.``0``f32``)``)``;`
`assert_eq!``(``f32``::`value_from`(``16_777_217``i32``)``,` `Err``(``RangeError``::`PosOverflow`(``16_777_217``)``)``)``;`
`//` Float -> integer conversions have to be done using approximations. Although
`//` exact conversions are *possible*, "advertising" this with an implementation
`//` is misleading.
`//`
`//` Note that `DefaultApprox` for float -> integer uses whatever rounding
`//` mode is currently active (*i.e.* whatever `as` would do).
`assert_eq!``(``41.``0``f32``.``approx``(``)``,` `Ok``(``41``u8``)``)``;`
`assert_eq!``(``41.``3``f32``.``approx``(``)``,` `Ok``(``41``u8``)``)``;`
`assert_eq!``(``41.``5``f32``.``approx``(``)``,` `Ok``(``41``u8``)``)``;`
`assert_eq!``(``41.``8``f32``.``approx``(``)``,` `Ok``(``41``u8``)``)``;`
`assert_eq!``(``42.``0``f32``.``approx``(``)``,` `Ok``(``42``u8``)``)``;`
`assert_eq!``(``255.``0``f32``.``approx``(``)``,` `Ok``(``255``u8``)``)``;`
`assert_eq!``(``256.``0``f32``.``approx``(``)``,` `Err``:``:``<``u8`, `_``>``(``FloatError``::`PosOverflow`(``256.``0``)``)``)``;`
`//` Sometimes, it can be useful to saturate the conversion from float to
`//` integer directly, then account for NaN as input separately. The `Saturate`
`//` extension trait exists for this reason.
`assert_eq!``(``(``-``23.``0``f32``)``.``approx_as``::``<``u8``>``(``)``.``saturate``(``)``,` `Ok``(``0``)``)``;`
`assert_eq!``(``302.``0``f32``.``approx_as``::``<``u8``>``(``)``.``saturate``(``)``,` `Ok``(``255``u8``)``)``;`
`assert!``(``std``::``f32``::``NAN``.``approx_as``::``<``u8``>``(``)``.``saturate``(``)``.``is_err``(``)``)``;`
`//` If you really don't care about the specific kind of error, you can just rely
`//` on automatic conversion to `GeneralErrorKind`.
`fn` `too_many_errors``(``)`` ``->` `Result``<``(``)`, GeneralErrorKind`>` `{`
`let` x`:` `u8` `=` `0``u8``.``value_into``(``)``?``;`
`assert_eq!``(`x`,` `0``)``;`
`let` y`:` `i8` `=` `0``u8``.``value_into``(``)``?``;`
`assert_eq!``(`y`,` `0``)``;`
`let` z`:` `i16` `=` `0``u8``.``value_into``(``)``?``;`
`assert_eq!``(`z`,` `0``)``;`
`let` x`:` `u8` `=` `0.``0``f32``.``approx``(``)``?``;`
`assert_eq!``(`x`,` `0``u8``)``;`
`Ok``(``(``)``)`
`}`
`too_many_errors``(``)``.``unwrap``(``)``;`

#### Dependencies

~260–720KB

~17K SLoC