conv2 0.4.2

This crate provides a number of conversion traits with more specific semantics than those provided by 'as' or 'From'/'Into'.
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
#![allow(unused_macros)]

/// Detects floating point NaN; which is not equal to itself.
#[cfg(test)]
#[allow(dead_code)] // This module is a submodule of multiple test modules.
#[allow(clippy::eq_op)] // `val != val` looks wrong, but is correct.
pub fn is_nan<T>(val: T) -> bool
where
    T: PartialEq,
{
    val != val
}

/// Detects floating point +/- infinity by checking if `value` is greater than T::MAX or less than T::MIN.
macro_rules! is_infinite {
    ($value:expr, $type:ty) => {{
        let v = $value;
        // I'm not sure this would be improved by using .contains()
        #[allow(clippy::manual_range_contains)]
        ((v > <$type>::MAX) || (v < <$type>::MIN))
    }};
}

macro_rules! SL {
    ($($tts:tt)*) => { stringify!($($tts)*) };
}

macro_rules! as_expr {
    ($e:expr) => {
        $e
    };
}

macro_rules! check {
    (@ $from:ty, $to:ty=> $(;)*) => {};

    // To unsigned int
    (@ $from:ty, $to:ty=> uident; $($tail:tt)*) => {
        check!(@ $from, $to=> v: 0;);
        check!(@ $from, $to=> v: 1;);
        check!(@ $from, $to=> $($tail)*);
    };

    // To signed int
    (@ $from:ty, $to:ty=> sident; $($tail:tt)*) => {
        check!(@ $from, $to=> v: -1;);
        check!(@ $from, $to=> v: 0;);
        check!(@ $from, $to=> v: 1;);
        check!(@ $from, $to=> $($tail)*);
    };

    // To floating point
    (@ $from:ty, $to:ty=> fident; $($tail:tt)*) => {
        check!(@ $from, $to=> v: -1.0;);
        check!(@ $from, $to=> v:  0.0;);
        check!(@ $from, $to=> v:  1.0;);
        check!(@ $from, $to=> $($tail)*);
    };

    // To unsigned int (approx), with rounding checks
    (@ $from:ty, $to:ty=> uidenta; $($tail:tt)*) => {
        check!(@ $from, $to=> a: 0.0;);
        check!(@ $from, $to=> a: 1.0;);

        check!(@ $from, $to=> aRTN: 0.00, 0;);
        check!(@ $from, $to=> aRTN: 0.25, 0;);
        check!(@ $from, $to=> aRTN: 0.50, 1;);
        check!(@ $from, $to=> aRTN: 0.75, 1;);
        check!(@ $from, $to=> aRTN: 1.00, 1;);

        check!(@ $from, $to=> aRNI:  0.00,  0;);
        check!(@ $from, $to=> aRNI:  0.25,  0;);
        check!(@ $from, $to=> aRNI:  0.50,  0;);
        check!(@ $from, $to=> aRNI:  0.75,  0;);
        check!(@ $from, $to=> aRNI:  1.00,  1;);

        check!(@ $from, $to=> aRPI:  0.00,  0;);
        check!(@ $from, $to=> aRPI:  0.25,  1;);
        check!(@ $from, $to=> aRPI:  0.50,  1;);
        check!(@ $from, $to=> aRPI:  0.75,  1;);
        check!(@ $from, $to=> aRPI:  1.00,  1;);

        check!(@ $from, $to=> aRTZ:  0.00,  0;);
        check!(@ $from, $to=> aRTZ:  0.25,  0;);
        check!(@ $from, $to=> aRTZ:  0.50,  0;);
        check!(@ $from, $to=> aRTZ:  0.75,  0;);
        check!(@ $from, $to=> aRTZ:  1.00,  1;);

        check!(@ $from, $to=> $($tail)*);
    };

    // To signed int (approx), with rounding checks
    (@ $from:ty, $to:ty=> sidenta; $($tail:tt)*) => {
        check!(@ $from, $to=> a: -1.0;);
        check!(@ $from, $to=> a:  0.0;);
        check!(@ $from, $to=> a:  1.0;);

        check!(@ $from, $to=> aRTN: -1.00, -1;);
        check!(@ $from, $to=> aRTN: -0.75, -1;);
        check!(@ $from, $to=> aRTN: -0.50, -1;);
        check!(@ $from, $to=> aRTN: -0.25,  0;);
        check!(@ $from, $to=> aRTN:  0.00,  0;);
        check!(@ $from, $to=> aRTN:  0.25,  0;);
        check!(@ $from, $to=> aRTN:  0.50,  1;);
        check!(@ $from, $to=> aRTN:  0.75,  1;);
        check!(@ $from, $to=> aRTN:  1.00,  1;);

        check!(@ $from, $to=> aRNI: -1.00, -1;);
        check!(@ $from, $to=> aRNI: -0.75, -1;);
        check!(@ $from, $to=> aRNI: -0.50, -1;);
        check!(@ $from, $to=> aRNI: -0.25, -1;);
        check!(@ $from, $to=> aRNI:  0.00,  0;);
        check!(@ $from, $to=> aRNI:  0.25,  0;);
        check!(@ $from, $to=> aRNI:  0.50,  0;);
        check!(@ $from, $to=> aRNI:  0.75,  0;);
        check!(@ $from, $to=> aRNI:  1.00,  1;);

        check!(@ $from, $to=> aRPI: -1.00, -1;);
        check!(@ $from, $to=> aRPI: -0.75,  0;);
        check!(@ $from, $to=> aRPI: -0.50,  0;);
        check!(@ $from, $to=> aRPI: -0.25,  0;);
        check!(@ $from, $to=> aRPI:  0.00,  0;);
        check!(@ $from, $to=> aRPI:  0.25,  1;);
        check!(@ $from, $to=> aRPI:  0.50,  1;);
        check!(@ $from, $to=> aRPI:  0.75,  1;);
        check!(@ $from, $to=> aRPI:  1.00,  1;);

        check!(@ $from, $to=> aRTZ: -1.00, -1;);
        check!(@ $from, $to=> aRTZ: -0.75,  0;);
        check!(@ $from, $to=> aRTZ: -0.50,  0;);
        check!(@ $from, $to=> aRTZ: -0.25,  0;);
        check!(@ $from, $to=> aRTZ:  0.00,  0;);
        check!(@ $from, $to=> aRTZ:  0.25,  0;);
        check!(@ $from, $to=> aRTZ:  0.50,  0;);
        check!(@ $from, $to=> aRTZ:  0.75,  0;);
        check!(@ $from, $to=> aRTZ:  1.00,  1;);

        check!(@ $from, $to=> $($tail)*);
    };

    // To floating point (approx)
    (@ $from:ty, $to:ty=> fidenta; $($tail:tt)*) => {
        check!(@ $from, $to=> a: -1.0;);
        check!(@ $from, $to=> a:  0.0;);
        check!(@ $from, $to=> a:  1.0;);
        check!(@ $from, $to=> $($tail)*);
    };

    // Single check using `value_into`
    (@ $from:ty, $to:ty=> v: $src:expr, !$dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, v: {}, !{}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.value_into();
            assert_eq!(dst, Err($dst(src)));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Single check using `value_into`; destination value computed using `as`
    (@ $from:ty, $to:ty=> v: $src:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, v: {}", SL!($from), SL!($to), SL!($src));
            let src: $from = $src;
            let dst: Result<$to, _> = src.value_into();
            if util::is_nan(src) {
                assert!(util::is_nan(dst.expect("error but expected NaN")));
            } else {
                assert_eq!(dst, Ok($src as $to));
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into`; destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: *; $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: *", SL!($from), SL!($to));

            fn property(v: $from) -> bool {
                let dst: Result<$to, _> = v.value_into();
                if util::is_nan(v) {
                    util::is_nan(dst)
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv1 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into` (may over/underflow bound); destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: (+-$bound:expr); $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: (+- {})", SL!($from), SL!($to), SL!($bound));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.value_into().map_err(From::from);
                if v < -$bound as $from {
                    dst == Err(conv2::FloatError::NegOverflow(v))
                } else if v > $bound as $from {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv2 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into` (may overflow bound); destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: (, $bound:expr); $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: (, {})", SL!($from), SL!($to), SL!($bound));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.value_into().map_err(From::from);
                if v > $bound as $from {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv3 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into` (positive only); destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: +; $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: +", SL!($from), SL!($to));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.value_into().map_err(From::from);
                if v < 0 {
                    dst == Err(conv2::FloatError::NegOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv4 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into` (may overflow); destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: +$max:ty=> $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: +{}", SL!($from), SL!($to), SL!($max));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.value_into().map_err(From::from);
                let max = <$max>::MAX as $from;
                if v > max {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv5 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into` (may over/underflow); destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: $bound:ty=> $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: {}", SL!($from), SL!($to), SL!($bound));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.value_into().map_err(From::from);
                let min = <$bound>::MIN as $from;
                let max = <$bound>::MAX as $from;
                if v < min {
                    dst == Err(conv2::FloatError::NegOverflow(v))
                } else if v > max {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv6 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `value_into` (may over/underflow); destination value computed using `as`
    (@ $from:ty, $to:ty=> qv: $min:ty, $max:ty=> $($tail:tt)*) => {
        {
            println!("? {} => {}, qv: {}, {}", SL!($from), SL!($to), SL!($min), SL!($max));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.value_into().map_err(From::from);
                let min = <$min>::MIN as $from;
                let max = <$max>::MAX as $from;
                if v < min {
                    dst == Err(conv2::FloatError::NegOverflow(v))
                } else if v > max {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qv7 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Single check using `approx_as`; Expects error.
    (@ $from:ty, $to:ty=> a: $src:expr, !$dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, a: {}, !{}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_as();
            assert_eq!(dst, Err($dst(src)));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Single check using `approx_as`.
    (@ $from:ty, $to:ty=> a: $src:expr, $dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, a: {}, {}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_as();
            assert_eq!(dst, Ok($dst));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Single check using `approx_as`; destination value computed using `as`.
    (@ $from:ty, $to:ty=> a: $src:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, a: {}", SL!($from), SL!($to), SL!($src));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_as();
            assert_eq!(dst, Ok($src as $to));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `approx_as`; destination value computed using `as`
    (@ $from:ty, $to:ty=> qa: *; $($tail:tt)*) => {
        {
            println!("? {} => {}, qa: *", SL!($from), SL!($to));

            fn property(v: $from) -> bool {
                let dst: Result<$to, _> = v.approx_as();
                if util::is_nan(v) {
                    util::is_nan(dst.expect("error but expected NaN"))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qa1 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `approx_as` (positive only) destination value computed using `as`.
    (@ $from:ty, $to:ty=> qa: +; $($tail:tt)*) => {
        {
            println!("? {} => {}, qa: +", SL!($from), SL!($to));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.approx_as().map_err(From::from);
                if v < 0 {
                    dst == Err(conv2::FloatError::NegOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qa2 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `approx_as` (may overflow); destination value computed using `as`
    (@ $from:ty, $to:ty=> qa: +$max:ty=> $($tail:tt)*) => {
        {
            println!("? {} => {}, qa: +{}", SL!($from), SL!($to), SL!($max));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.approx_as().map_err(From::from);
                let max = <$max>::MAX as $from;
                if v > max {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qa3 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `approx_as` (may over/overflow bound); destination value computed using `as`
    (@ $from:ty, $to:ty=> qa: $bound:ty=> $($tail:tt)*) => {
        {
            println!("? {} => {}, qa: {}", SL!($from), SL!($to), SL!($bound));

            fn property(v: $from) -> bool {
                let dst: Result<$to, conv2::FloatError<_>> = v.approx_as().map_err(From::from);
                let min = <$bound>::MIN as $from;
                let max = <$bound>::MAX as $from;
                if util::is_nan(v) {
                    // float NaN -> integer is Err; f64::NAN -> f32::NAN.
                    dst.is_err() || util::is_nan(dst)
                } else if is_infinite!(v, $from) && dst.is_ok() {
                    dst == Ok(v as $to)
                } else if v < min {
                    dst == Err(conv2::FloatError::NegOverflow(v))
                } else if v > max {
                    dst == Err(conv2::FloatError::PosOverflow(v))
                } else {
                    dst == Ok(v as $to)
                }
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qa4 {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    // Quickcheck using `approx_as` with wrapping; destination value computed using `as`
    (@ $from:ty, $to:ty=> qaW: *; $($tail:tt)*) => {
        {
            println!("? {} => {}, qaW: *", SL!($from), SL!($to));

            fn property(v: $from) -> bool {
                let dst: Result<$to, _> = v.approx_as_by::<_, Wrapping>();
                dst == Ok(v as $to)
            }

            let mut qc = quickcheck::QuickCheck::new();
            match qc.quicktest(property as fn($from) -> bool) {
                Ok(_) => (),
                Err(err) => panic!("qaW {err:?}")
            }
        }
        check!(@ $from, $to=> $($tail)*);
    };

    (@ $from:ty, $to:ty=> aRTN: $src:expr, $dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, aRTN: {}, {}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_by::<conv2::RoundToNearest>();
            assert_eq!(dst, Ok($dst));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    (@ $from:ty, $to:ty=> aRNI: $src:expr, $dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, aRNI: {}, {}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_by::<conv2::RoundToNegInf>();
            assert_eq!(dst, Ok($dst));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    (@ $from:ty, $to:ty=> aRPI: $src:expr, $dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, aRPI: {}, {}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_by::<conv2::RoundToPosInf>();
            assert_eq!(dst, Ok($dst));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    (@ $from:ty, $to:ty=> aRTZ: $src:expr, $dst:expr; $($tail:tt)*) => {
        {
            println!("? {} => {}, aRTZ: {}, {}", SL!($from), SL!($to), SL!($src), SL!($dst));
            let src: $from = $src;
            let dst: Result<$to, _> = src.approx_by::<conv2::RoundToZero>();
            assert_eq!(dst, Ok($dst));
        }
        check!(@ $from, $to=> $($tail)*);
    };

    ($from:ty, $to:ty=> $($tail:tt)*) => {
        check! { @ $from, $to=> $($tail)*; }
    };
}

macro_rules! for_bitness {
    (32 {$($bits32:tt)*} 64 {$($bits64:tt)*}) => {
        as_expr!(
            {
                #[cfg(target_pointer_width="32")]
                fn for_bitness() {
                    $($bits32)*
                }

                #[cfg(target_pointer_width="64")]
                fn for_bitness() {
                    $($bits64)*
                }

                for_bitness()
            }
        )
    };
}