math_ops/
conversion.rs

1//! Module for type conversions between integers and floating-point types,
2//! and between `f32` and `f64`.
3
4/// Trait to convert integer types to floating-point types.
5pub trait IntToFloat {
6  fn to_f32(&self) -> f32;
7  fn to_f64(&self) -> f64;
8}
9
10/// Trait to convert floating-point types to integer types.
11pub trait FloatToInt {
12  fn to_i8(&self) -> i8;
13  fn to_i16(&self) -> i16;
14  fn to_i32(&self) -> i32;
15  fn to_i64(&self) -> i64;
16  fn to_u8(&self) -> u8;
17  fn to_u16(&self) -> u16;
18  fn to_u32(&self) -> u32;
19  fn to_u64(&self) -> u64;
20}
21
22/// Implement `IntToFloat` for all integer types.
23macro_rules! impl_int_to_float {
24  ($($t:ty)*) => ($(
25    impl IntToFloat for $t {
26      fn to_f32(&self) -> f32 {
27        *self as f32
28      }
29      fn to_f64(&self) -> f64 {
30        *self as f64
31      }
32    }
33  )*)
34}
35
36impl_int_to_float!(i8 i16 i32 i64 isize u8 u16 u32 u64 usize);
37
38/// Implement `FloatToInt` for `f32` and `f64`.
39impl FloatToInt for f32 {
40  fn to_i8(&self) -> i8 {
41    *self as i8
42  }
43
44  fn to_i16(&self) -> i16 {
45    *self as i16
46  }
47
48  fn to_i32(&self) -> i32 {
49    *self as i32
50  }
51
52  fn to_i64(&self) -> i64 {
53    *self as i64
54  }
55
56  fn to_u8(&self) -> u8 {
57    *self as u8
58  }
59
60  fn to_u16(&self) -> u16 {
61    *self as u16
62  }
63
64  fn to_u32(&self) -> u32 {
65    *self as u32
66  }
67
68  fn to_u64(&self) -> u64 {
69    *self as u64
70  }
71}
72
73impl FloatToInt for f64 {
74  fn to_i8(&self) -> i8 {
75    *self as i8
76  }
77
78  fn to_i16(&self) -> i16 {
79    *self as i16
80  }
81
82  fn to_i32(&self) -> i32 {
83    *self as i32
84  }
85
86  fn to_i64(&self) -> i64 {
87    *self as i64
88  }
89
90  fn to_u8(&self) -> u8 {
91    *self as u8
92  }
93
94  fn to_u16(&self) -> u16 {
95    *self as u16
96  }
97
98  fn to_u32(&self) -> u32 {
99    *self as u32
100  }
101
102  fn to_u64(&self) -> u64 {
103    *self as u64
104  }
105}
106
107/// Trait to convert between `f32` and `f64`.
108pub trait FloatCast {
109  fn to_f32_cast(&self) -> f32;
110  fn to_f64_cast(&self) -> f64;
111}
112
113impl FloatCast for f32 {
114  fn to_f32_cast(&self) -> f32 {
115    *self
116  }
117
118  fn to_f64_cast(&self) -> f64 {
119    *self as f64
120  }
121}
122
123impl FloatCast for f64 {
124  fn to_f32_cast(&self) -> f32 {
125    *self as f32
126  }
127
128  fn to_f64_cast(&self) -> f64 {
129    *self
130  }
131}