TryCast

Trait TryCast 

Source
pub trait TryCast<T> {
    type Error;

    // Required method
    fn try_cast(self) -> Result<T, Self::Error>;
}
Expand description

Fallible conversion between fastnum numeric types (akin to TryFrom, but for fastnum).

TryCast returns Result<T, Error>, where Error describes why the conversion failed (e.g., out-of-range for the target type or invalid sign conversion).

Use TryCast when:

  • the value may not fit into the target type (overflow/underflow);
  • information could be lost (e.g., negative to unsigned);
  • you need explicit error handling rather than silent truncation.

§Examples:

use fastnum::*;

// Successful conversion (value fits in the target type)
let x = u256!(42);
let y: U128 = x.try_cast().unwrap();
assert_eq!(u128!(42), y);

// Failing conversion (negative to unsigned)
let neg = i256!(-1);
assert!(<I256 as TryCast<U64>>::try_cast(neg).is_err());

Tips:

  • If the conversion is always valid by design — prefer Cast.
  • If range/sign must be checked — prefer TryCast.

Required Associated Types§

Source

type Error

The type returned in the event of a conversion error.

Required Methods§

Source

fn try_cast(self) -> Result<T, Self::Error>

Attempts to convert self into T, returning an error on failure.

Use this method when the conversion may be lossy or out-of-range.

§Examples:
use fastnum::*;

// In-range: succeeds
let a = u256!(18446744073709551615);
let b: U64 = a.try_cast().unwrap();
assert_eq!(u64!(18446744073709551615), b);

// Out-of-range: fails with an error
let big = u256!(18446744073709551616);
let _ = <U256 as TryCast<U64>>::try_cast(big).unwrap_err();

Implementors§

Source§

impl<const N: usize> TryCast<Int<N>> for UInt<N>

Source§

impl<const N: usize, const M: usize> TryCast<Int<N>> for Int<M>
where Dimension<N, M>: Narrow,

Source§

impl<const N: usize, const M: usize> TryCast<Int<N>> for UInt<M>
where Dimension<N, M>: Narrow,

Source§

impl<const N: usize, const M: usize> TryCast<UInt<N>> for Int<M>

Source§

impl<const N: usize, const M: usize> TryCast<UInt<N>> for UInt<M>
where Dimension<N, M>: Narrow,

Source§

impl<const N: usize, const M: usize> TryCast<Decimal<N>> for Decimal<N>
where Dimension<N, M>: Narrow,

Source§

impl<const N: usize, const M: usize> TryCast<Decimal<N>> for UnsignedDecimal<N>
where Dimension<N, M>: Narrow,

Source§

impl<const N: usize, const M: usize> TryCast<UnsignedDecimal<N>> for Decimal<N>

Source§

impl<const N: usize, const M: usize> TryCast<UnsignedDecimal<N>> for UnsignedDecimal<N>
where Dimension<N, M>: Narrow,