[Feature] Unified type convert api of U256 and I256
Component
primitives
Describe the feature you would like
Now we could use U256::to::<u64>() and I256::as_u64(), but not vice visa.
In addition
- There's no
I256::as_u128/I256::as_i128 - We have to use
f64::from(U256), but notU256::to::<f64>() - There's even no
f64::from(I128)
Additional context
No response
What are use cases for them? @clouds56
I'm using alloy-rs to collect events/logs for some contract.
After SolEvent::decode_log_data I would get U256 or I256 and sometimes U24 depends on the contract.
Then I'd like to convert then into an arrow::Array for further processing.
Currently, I wrote a wrapper to do the convert like this
trait ToNum {
fn to_u128(self) -> Option<u128>;
fn to_u64(self) -> Option<u64>;
fn to_u32(self) -> Option<u32>;
fn to_i128(self) -> Option<i128>;
...
fn to_f64(self) -> Option<f64>;
}
Ideally, I'm expecting the U256 (alias of Uint<256, 4>) and I256 (alias of Signed<256, 4>) to provide these interface
Uint::to<T>(&self) -> T/Signed::to<T>(&self)(now missing)- T could be any number like types, e.g.
Uint,Signed,u128,i128and as well asf64(f64 is now missing) - Panics if the conversion fails (overflow)
- T could be any number like types, e.g.
Uint::wrapping_to<T>(&self) -> T/Signed::to<T>(&self) -> T(now missing)- T could be any int like type, e.g.
Uint,Signed,u128,i128 - This would follow
wrappingbehavior when overflow
- T could be any int like type, e.g.
Uint::saturating_to<T>(&self) -> T/Signed::saturating_to<T> -> T(now missing)- T could be any number like types, e.g.
Uint,Signed,u128,i128and as well asf64(f64 is now missing) - This would return
T::MIN/T::MAXif data not fitting inT
- T could be any number like types, e.g.
Uint::checked_to<T>(&self) -> Option<T>(now missing) /Signed::checked_to<T>(&self) -> Option<T>(now missing)- T could be any number like types, e.g.
Uint,Signed,u128,i128and as well asf64(f64 is now missing) - This would return
T::MIN/T::MAXif data not fitting inT
- T could be any number like types, e.g.
- And their "from" version:
from,wrapping_from,saturating_from,checked_from, I currently do not depend onfrom-family but the API would be more completed if provided.
Makes some sense. I guess, I can do it if the task gets approved
I would also appreciate this.