num-traits
num-traits copied to clipboard
IDEA: Add Trait For Corresponding Signed Version of Unsigned and Vice-Versa
My Idea is something like this (I am not good with names, feel free to suggest better names):
pub trait HasSignedVersion: Unsigned {
type Signed: Signed;
}
impl HasSignedVersion for u8 {
type Signed = i8;
}
impl HasSignedVersion for u16 {
type Signed = i16;
}
impl HasSignedVersion for u32 { ... }
impl HasSignedVersion for u64 { ... }
impl HasSignedVersion for u128 { ... }
impl HasSignedVersion for usize { ... }
//...etc
pub trait HasUnsignedVersion: Signed {
type Unsigned: Unsigned;
}
impl HasUnsignedVersion for i8 {
type Unsigned = u8;
}
impl HasUnsignedVersion for i16 {
type Unsigned = u16;
}
impl HasUnsignedVersion for i32 { ... }
impl HasUnsignedVersion for i64 { ... }
impl HasUnsignedVersion for i128 { ... }
impl HasUnsignedVersion for isize { ... }
//...etc
You want just associated types, without any methods? How would this be used?
I was going to say I would use AsPrimitive, but I realised that is too specific on primitives signed/unsigned pairs.
So, I propose we add methods to these traits:
pub trait HasSignedVersion: Unsigned {
type Signed: Signed;
fn to_signed(self) -> Option<Self::Signed>;
fn to_signed_bits(self) -> Self::Signed;
}
pub trait HasUnsignedVersion: Signed {
type Unsigned: Unsigned;
fn to_unsigned(self) -> Option<Self::Unsigned>;
fn to_unsigned_bits(self) -> Self::Unsigned;
}
What would be the expected semantics of the bits methods -- 2's complement cast? Implementation defined? Think of something like BigInt which stores sign+magnitude, not 2's complement, then what is this expected to return here?
You want just associated types, without any methods? How would this be used?
Just want to add, that I would have a usecase for that. I have a function
pub fn to_u(i: i64) -> u64{
let u: u64 = u64::from_le_bytes(i.to_le_bytes());
u.wrapping_add(u64::from_le_bytes(i64::MIN.to_le_bytes()))
}
And it would be nice to be able to implement that for all integers at once (nothing would happen, if the number was previously unsigned).
It would require that HasUnsignedVersion would be implemented for the unsigned ints as well