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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use num_traits::{ops::wrapping::*, Bounded};
use std::mem;

/// Helper trait for efficient calculations in other implementations
pub trait HasUnsignedVersion {
    /// which unsigned type corresponds to this type?
    type Unsigned;
    /// Type returned by `self.to_le_bytes()`. 
    /// Depends on how many bytes are needed, to represent the number
    type LeBytes;

    /// to little endian. See implementation for integers in the standard library
    fn to_le_bytes(self) -> Self::LeBytes;

    /// from little endian. See implementation for integers in the standard library
    fn from_le_bytes(bytes: Self::LeBytes) -> Self;
}

// see link for other, somewhat more general solution
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=579199c02611a20cdbfc9928c00befe7
macro_rules! has_unsigned_version {
    (
        $u:ty, $t:ty $(,)?
    ) => (
        impl HasUnsignedVersion for $t {
            type Unsigned = $u;
            type LeBytes = [u8; mem::size_of::<Self>()];

            #[inline(always)]
            fn to_le_bytes(self) -> Self::LeBytes {
                self.to_le_bytes()
            }

            #[inline(always)]
            fn from_le_bytes(bytes: Self::LeBytes) -> Self {
                Self::from_le_bytes(bytes)
            }
        }   
    );
    (
        $(
            ($u:ty, $i:ty)
        ),* $(,)?
    ) => (
        $(
            has_unsigned_version!($u, $u);
            has_unsigned_version!($u, $i);
        )*
    );
}

has_unsigned_version! {
    (u8, i8),
    (u16, i16),
    (u32, i32),
    (u64, i64),
    (u128, i128),
    (usize, isize),
}

#[inline(always)]
pub(crate) fn to_u<T>(v: T) -> T::Unsigned
where T: num_traits::Bounded + HasUnsignedVersion,
    T::Unsigned: num_traits::Bounded + HasUnsignedVersion<LeBytes=T::LeBytes> + WrappingAdd
{
    let u = T::Unsigned::from_le_bytes(v.to_le_bytes());
    u.wrapping_add(&T::Unsigned::from_le_bytes(T::min_value().to_le_bytes()))
}

#[inline(always)]
pub(crate) fn from_u<T, V>(u: T) -> V
where T: num_traits::Bounded + HasUnsignedVersion + WrappingSub + Bounded,
    T::Unsigned: num_traits::Bounded + HasUnsignedVersion<LeBytes=T::LeBytes> + WrappingAdd,
    V: HasUnsignedVersion<LeBytes=T::LeBytes> + Bounded
{
    let u = u.wrapping_sub(&T::from_le_bytes(V::min_value().to_le_bytes()));
    V::from_le_bytes(u.to_le_bytes())
}


#[cfg(test)]
mod tests{
    use rand_pcg::Pcg64Mcg;
    use rand::{SeedableRng, distributions::*};
    use super::*;


    #[test]
    fn convert_and_back_ord()
    {
        let rng = Pcg64Mcg::seed_from_u64(2747);
        let dist = Uniform::new_inclusive(i8::MIN, i8::MAX);
        let mut iter = dist.sample_iter(rng);

        for _ in 0..1000
        {
            let a = iter.next().unwrap();
            let b = iter.next().unwrap();
            assert_eq!(a < b, to_u(a) < to_u(b));
        }
    }
    #[test]
    fn convert_and_back_i8()
    {
        let rng = Pcg64Mcg::seed_from_u64(2747);
        let dist = Uniform::new_inclusive(i8::MIN, i8::MAX);
        let iter = dist.sample_iter(rng);

        for i in iter.take(10000)
        {
            assert_eq!(i, from_u::<_, i8>(to_u(i)));
        }
    }
    #[test]
    fn convert_and_back_i16()
    {
        let rng = Pcg64Mcg::seed_from_u64(2736746347);
        let dist = Uniform::new_inclusive(i16::MIN, i16::MAX);
        let iter = dist.sample_iter(rng);

        for i in iter.take(10000)
        {
            assert_eq!(i, from_u::<_, i16>(to_u(i)));
        }
    }

    #[test]
    fn convert_and_back_isize()
    {
        let rng = Pcg64Mcg::seed_from_u64(27367463247);
        let dist = Uniform::new_inclusive(isize::MIN, isize::MAX);
        let iter = dist.sample_iter(rng);

        for i in iter.take(10000)
        {
            assert_eq!(i, from_u::<_, isize>(to_u(i)));
        }
    }

    #[test]
    fn convert_and_back_u128()
    {
        let rng = Pcg64Mcg::seed_from_u64(273674693247);
        let dist = Uniform::new_inclusive(u128::MIN, u128::MAX);
        let iter = dist.sample_iter(rng);

        for i in iter.take(10000)
        {
            assert_eq!(i, from_u::<_, u128>(to_u(i)));
        }
    }



    #[test]
    fn convert_and_back_i128()
    {
        let rng = Pcg64Mcg::seed_from_u64(2723674693247);
        let dist = Uniform::new_inclusive(i128::MIN, i128::MAX);
        let iter = dist.sample_iter(rng);

        for i in iter.take(10000)
        {
            assert_eq!(i, from_u::<_, i128>(to_u(i)));
        }
    }
}