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
use cratedoc;
/// Unified trait for conversions between fastnum numeric types.
///
/// Cast is a total conversion: it never fails and does not return an error.
/// Prefer `Cast` when the conversion is guaranteed to be correct by definition
/// (e.g., widening with preserved value or sign/zero extension that cannot
/// overflow).
///
/// If the conversion may go out of range or lose information (sign/high bits),
/// use [`TryCast`] instead.
///
/// # Examples:
///
/// ```
/// use fastnum::*;
///
/// let a = u128!(123);
///
/// // Lossless widening
/// let b: U256 = a.cast();
/// assert_eq!(u256!(123), b);
/// ```
///
/// See also: [`TryCast`] for fallible conversions.
/// 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`.