core icon indicating copy to clipboard operation
core copied to clipboard

[Feature] Unified type convert api of U256 and I256

Open clouds56 opened this issue 9 months ago • 4 comments

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 not U256::to::<f64>()
  • There's even no f64::from(I128)

Additional context

No response

clouds56 avatar Mar 12 '25 07:03 clouds56

What are use cases for them? @clouds56

nadtech-hub avatar Apr 05 '25 19:04 nadtech-hub

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, i128 and as well as f64 (f64 is now missing)
    • Panics if the conversion fails (overflow)
  • 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 wrapping behavior when overflow
  • 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, i128 and as well as f64 (f64 is now missing)
    • This would return T::MIN/T::MAX if data not fitting in T
  • 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, i128 and as well as f64 (f64 is now missing)
    • This would return T::MIN/T::MAX if data not fitting in T
  • And their "from" version: from, wrapping_from, saturating_from, checked_from, I currently do not depend on from-family but the API would be more completed if provided.

clouds56 avatar Apr 25 '25 04:04 clouds56

Makes some sense. I guess, I can do it if the task gets approved

nadtech-hub avatar Apr 25 '25 06:04 nadtech-hub

I would also appreciate this.

pistomat avatar Jun 16 '25 12:06 pistomat