num-traits icon indicating copy to clipboard operation
num-traits copied to clipboard

IDEA: Add Trait For Corresponding Signed Version of Unsigned and Vice-Versa

Open brunoczim opened this issue 5 years ago • 4 comments

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

brunoczim avatar Apr 22 '20 00:04 brunoczim

You want just associated types, without any methods? How would this be used?

cuviper avatar Apr 22 '20 22:04 cuviper

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;
}

brunoczim avatar Apr 23 '20 02:04 brunoczim

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?

cuviper avatar Apr 23 '20 17:04 cuviper

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

Pardoxa avatar Aug 31 '20 11:08 Pardoxa