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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! This module implements a very opinionated approach to converting numbers.
//!
//! Imagine you have a function `return_u32`, and you would like to pass its return value into some
//! other function take_i8:
//!
//! ```
//! fn return_u32() -> u32 {
//!     257
//! }
//! fn take_i8(i: i8) {
//! }
//! ```
//!
//! Then, the compiler (correctly) complains as soon as you write `take_i8(return_u32())`.
//! I came into those situations frequently, so I simply changed it to 
//! `take_i8(return_u32() as i8)`. However, when doing so, I implicitly assumed that the semantic
//! meaning of the number does not change, i.e. I assume that `i8` is capable of representing the
//! exact same value that `return_u32` gives me (which is not the case in the example shown).
//!
//! This module enables you to write the following:
//!
//! ```
//! use as_num::TAsNum; // TAsNum is the trait enabling the conversions
//! take_i8(return_u32().as_num())
//! ```
//!
//! `as_num` converts its argument into the destination type, thereby checking whether the
//! conversion can be done without loss of data.
//!
//! It tries to follow a similar approach to the one that is chosen with e.g. "normal addition" and `checked_add`:
//! It offers one method `as_num` that does the conversion (at last going down to Rust's `as`), and
//! `debug_assert`s that the conversion is lossless.
//! In addition to `as_num`, it offers a method `checked_as_num`, returning an `Option`.
//!
//! This module implements conversion for any combination of the following types:
//! `i8`, `i16`, `i32`, `i64`, `isize`, `u8`, `u16`, `u32`, `u64`, `usize`, `f32`, `f64`.
//!
//! The function `as_num` `debug_assert`s that the destination value is convertible back to the
//! exact same source value.
//!
//! That, in particular, means that converting floating-point to integral numbers can only be done
//! with `as_num` if the source is already been rounded to some integral number.

use std::mem;
use std::fmt::Debug;

// heavily inspired by http://rust-num.github.io/num/src/num_traits/cast.rs.html

// TODO rust i128/u128
type LargestSignedType = i64;
type LargestUnsignedType = u64;

pub trait TSignedInt : Sized + Copy {
    fn min() -> LargestSignedType;
    fn max() -> LargestSignedType;
}

pub trait TUnsignedInt : Sized + Copy {
    fn min() -> LargestUnsignedType;
    fn max() -> LargestUnsignedType;
}

macro_rules! impl_min_max {
    ($num_trait: ident, $largest_type_same_signedness: ty,) => {};
    ($num_trait: ident, $largest_type_same_signedness: ty, $t: ident, $($ts: ident,)*) => {
        impl $num_trait for $t {
            fn min() -> $largest_type_same_signedness {
                use std::$t;
                $t::MIN as $largest_type_same_signedness
            }
            fn max() -> $largest_type_same_signedness {
                use std::$t;
                $t::MAX as $largest_type_same_signedness
            }
        }
        impl_min_max!($num_trait, $largest_type_same_signedness, $($ts,)*);
    };
}

impl_min_max!(TSignedInt, LargestSignedType, i8, i16, i32, i64, isize,);
impl_min_max!(TUnsignedInt, LargestUnsignedType, u8, u16, u32, u64, usize,);

pub trait TAsNumInternal<Dest> : Copy {
    fn is_safely_convertible(self) -> bool;
    fn as_num_internal(self) -> Dest;
}

pub trait TAsNum : Copy {
    fn as_num<Dest>(self) -> Dest
        where Self: TAsNumInternal<Dest>,
              Dest: TAsNumInternal<Self>,
              Dest: Debug;
    fn checked_as_num<Dest>(self) -> Option<Dest>
        where Self: TAsNumInternal<Dest>,
              Dest: TAsNumInternal<Self>,
              Dest: Debug;
    fn assert_convertible_back<Dest>(self)
        where Self: TAsNumInternal<Dest>,
              Dest: TAsNumInternal<Self>,
              Dest: Debug;
}

macro_rules! impl_TAsNum {
    () => {};
    ($t: ident, $($ts: ident,)*) => {
        impl TAsNum for $t {
            fn assert_convertible_back<Dest>(self)
                where Self: TAsNumInternal<Dest>,
                      Dest: TAsNumInternal<Self>,
                      Dest: Debug,
            {
                let dst : Dest = self.as_num_internal();
                let src : Self = dst.as_num_internal();
                debug_assert!(self==src, "{:?} {:?} was converted to {:?}, whose back-conversion yields {:?}", self, stringify!($t), dst, src);
            }
            fn as_num<Dest>(self) -> Dest
                where Self: TAsNumInternal<Dest>,
                      Dest: TAsNumInternal<Self>,
                      Dest: Debug,
            {
                debug_assert!(self.is_safely_convertible(), "{} not safely convertible", self);
                self.assert_convertible_back::<Dest>();
                self.as_num_internal()
            }
            fn checked_as_num<Dest>(self) -> Option<Dest>
                where Self: TAsNumInternal<Dest>,
                      Dest: TAsNumInternal<Self>,
                      Dest: Debug,
            {
                if self.is_safely_convertible() {
                    self.assert_convertible_back::<Dest>();
                    Some(self.as_num_internal())
                } else {
                    None
                }
            }
        }
        impl_TAsNum!($($ts,)*);
    };
}
impl_TAsNum!(
    i8, i16, i32, i64, isize,
    u8, u16, u32, u64, usize,
    f32, f64,
);

macro_rules! impl_signed_to_signed_internal {
    ($src: ident, $dest: ident) => {
        impl TAsNumInternal<$dest> for $src {
            fn is_safely_convertible(self) -> bool {
                mem::size_of::<$src>() <= mem::size_of::<$dest>()
                || {
                    debug_assert!(mem::size_of::<Self>() <= mem::size_of::<LargestSignedType>());
                    let n = self as LargestSignedType;
                    $dest::min() <= n && n <= $dest::max()
                }
            }
            fn as_num_internal(self) -> $dest {
                self as $dest
            }
        }
    };
}

macro_rules! impl_signed_to_signed {
    ($src: ident,) => {};
    ($src: ident, $dest: ident, $($dests: ident,)*) => {
        impl_signed_to_signed_internal!($src, $dest);
        impl_signed_to_signed_internal!($dest, $src);
        impl_signed_to_signed!($src, $($dests,)*);
    };
}

macro_rules! impl_signed_to_unsigned_internal {
    ($src: ident, $dest: ident) => {
        impl TAsNumInternal<$dest> for $src {
            fn is_safely_convertible(self) -> bool {
                0<=self && self as LargestUnsignedType <= $dest::max()
            }
            fn as_num_internal(self) -> $dest {
                self as $dest
            }
        }
    }
}

macro_rules! impl_signed_to_unsigned {
    ($src: ident,) => {};
    ($src: ident, $dest: ident, $($dests: ident,)*) => {
        impl_signed_to_unsigned_internal!($src, $dest);
        impl_unsigned_to_signed_internal!($dest, $src);
        impl_signed_to_unsigned!($src, $($dests,)*);
    }
}

macro_rules! impl_unsigned_to_signed_internal {
    ($src: ident, $dest: ident) => {
        impl TAsNumInternal<$dest> for $src {
            fn is_safely_convertible(self) -> bool {
                self as LargestSignedType <= $dest::max()
            }
            fn as_num_internal(self) -> $dest {
                self as $dest
            }
        }
    };
}

macro_rules! impl_unsigned_to_signed {
    ($src: ident,) => {};
    ($src: ident, $dest: ident, $($dests: ident,)*) => {
        impl_unsigned_to_signed_internal!($src, $dest);
        impl_signed_to_unsigned_internal!($dest, $src);
        impl_unsigned_to_signed!($src, $($dests,)*);
    };
}

macro_rules! impl_unsigned_to_unsigned_internal {
    ($src: ident, $dest: ident) => {
        impl TAsNumInternal<$dest> for $src {
            fn is_safely_convertible(self) -> bool {
                mem::size_of::<$src>() <= mem::size_of::<$dest>()
                    || self as LargestUnsignedType <= $dest::max()
            }
            fn as_num_internal(self) -> $dest {
                self as $dest
            }
        }
    };
}

macro_rules! impl_unsigned_to_unsigned {
    ($src: ident,) => {};
    ($src: ident, $dest: ident, $($dests: ident,)*) => {
        impl_unsigned_to_unsigned_internal!($src, $dest);
        impl_unsigned_to_unsigned_internal!($dest, $src);
        impl_unsigned_to_unsigned!($src, $($dests,)*);
    };
}

macro_rules! impl_integral_conversions {
    ((), ($($unsigneds: ident,)*)) => {};
    (($signed: ident, $($signeds: ident,)*), ($unsigned: ident, $($unsigneds: ident,)*)) => {
        impl_signed_to_signed_internal!($signed, $signed);
        impl_signed_to_signed!($signed, $($signeds,)*);
        impl_signed_to_unsigned_internal!($signed, $unsigned);
        impl_signed_to_unsigned!($signed, $($unsigneds,)*);
        impl_unsigned_to_signed_internal!($unsigned, $signed);
        impl_unsigned_to_signed!($unsigned, $($signeds,)*);
        impl_unsigned_to_unsigned_internal!($unsigned, $unsigned);
        impl_unsigned_to_unsigned!($unsigned, $($unsigneds,)*);
        impl_integral_conversions!(($($signeds,)*), ($($unsigneds,)*));
    };
}

impl_integral_conversions!(
    (i8, i16, i32, i64, isize,),
    (u8, u16, u32, u64, usize,)
);

macro_rules! impl_integral_to_float_internal {
    ($flt: ident,) => {};
    ($flt: ident, $int: ident, $($ints: ident,)*) => {
        impl TAsNumInternal<$flt> for $int {
            fn is_safely_convertible(self) -> bool {
                true // assume convertability until we encounter counter example in practice
            }
            fn as_num_internal(self) -> $flt {
                self as $flt
            }
        }
        impl TAsNumInternal<$int> for $flt {
            fn is_safely_convertible(self) -> bool {
                let dst : $int = self.as_num_internal();
                let src : Self = dst.as_num_internal();
                self==src
            }
            fn as_num_internal(self) -> $int {
                self as $int
            }
        }
        impl_integral_to_float_internal!($flt, $($ints,)*);
    };
}
macro_rules! impl_integral_to_float {
    ($flt: ident) => {
        impl_integral_to_float_internal!($flt,
            i8, i16, i32, i64, isize,
            u8, u16, u32, u64, usize,
        );
    };
}
impl_integral_to_float!(f32);
impl_integral_to_float!(f64);

type LargestFloatType = f64;
macro_rules! impl_float_to_float_internal {
    ($src: ident, $dest: ident) => {
        impl TAsNumInternal<$dest> for $src {
            fn is_safely_convertible(self) -> bool {
                mem::size_of::<$src>() <= mem::size_of::<$dest>() 
                || {
                    // Make sure the value is in range for the cast.
                    // NaN and +-inf are cast as they are.
                    let f = self as LargestFloatType;
                    !f.is_finite() || {
                        let max_value: $dest = ::std::$dest::MAX;
                        -max_value as LargestFloatType <= f && f <= max_value as LargestFloatType
                    }
                }
            }
            fn as_num_internal(self) -> $dest {
                self as $dest
            }
        }
    }
}
macro_rules! impl_float_to_float {
    ($src: ident,) => {};
    ($src: ident, $dest: ident, $($dests: ident,)*) => {
        impl_float_to_float_internal!($src, $dest);
        impl_float_to_float_internal!($dest, $src);
        impl_float_to_float!($src, $($dests,)*);
    };
}
impl_float_to_float!(f32, f64,);

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_as_num() {
        // we assume that isize/usize occupy at least 32 bit (i.e. 4 byte)
        // TODO tests: improve
        assert_eq!(4i8, 4i8.checked_as_num().unwrap());
        assert_eq!(4usize, 4u16.as_num());
        assert_eq!(4i32, 4usize.as_num());
        assert_eq!(256isize.checked_as_num::<u8>(), None);
        assert_eq!(4.3.checked_as_num::<isize>(), None);
    }
}