Trait conv::ApproxFrom [] [src]

pub trait ApproxFrom<Src, Scheme = DefaultApprox>: Sized where
    Scheme: ApproxScheme
{ type Err: Error; fn approx_from(src: Src) -> Result<Self, Self::Err>; }

This trait is used to perform a conversion that is permitted to approximate the result, but not to wrap or saturate the result to fit into the destination type's representable range.

Where possible, prefer implementing this trait over ApproxInto, but prefer using ApproxInto for generic constraints.

Details

All implementations of this trait must provide a conversion that can be separated into two logical steps: an approximation transform, and a representation transform.

The "approximation transform" step involves transforming the input value into an approximately equivalent value which is supported by the target type without taking the target type's representable range into account. For example, this might involve rounding or truncating a floating point value to an integer, or reducing the accuracy of a floating point value.

The "representation transform" step exactly rewrites the value from the source type's binary representation into the destination type's binary representation. This step may not transform the value in any way. If the result of the approximation is not representable, the conversion must fail.

The major reason for this formulation is to exactly define what happens when converting between floating point and integer types. Often, it is unclear what happens to floating point values beyond the range of the target integer type. Do they saturate, wrap, or cause a failure?

With this formulation, it is well-defined: if a floating point value is outside the representable range, the conversion fails. This allows users to distinguish between approximation and range violation, and act accordingly.

Associated Types

The error type produced by a failed conversion.

Required Methods

Convert the given value into an approximately equivalent representation.

Implementors