Module fraction::convert

source ·
Expand description

Optimistic type conversion

When std::convert::TryFrom and std::convert::TryInto get stabilised they should be used instead. However, at this point we need our own implementation for optional conversion between types.

The particular use case is when we have a data type claiming more space than it’s using and we want to move the value into another, smaller data type. Such operation may only be performed at runtime with particular checks that the value fits into the smaller data type. Otherwise we cannot perform safe cast.

§Examples

Integer conversion

use fraction::convert::TryToConvertFrom;

assert_eq!(Some(255u8), u8::try_to_convert_from(255u16));
assert_eq!(None, u8::try_to_convert_from(256u16));

Fraction conversion

use fraction::{GenericFraction, convert::TryToConvertFrom, One};

type F8 = GenericFraction<u8>;
type F16 = GenericFraction<u16>;

let f8_255 = F8::new(255u8, 1u8);
let f16_255 = F16::try_to_convert_from(f8_255).unwrap();
let f16_256 = f16_255 + F16::one();

assert_eq!(Some(f8_255), F8::try_to_convert_from(f16_255));
assert_eq!(None, F8::try_to_convert_from(f16_256));

Traits§