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
use crate::assert_positive_float;
use core::{cmp, fmt, ops};

/// Represents a current value, stored as whole microamps (μA) stored in a `u64` value.
/// This value can only be positive.
///
/// **Reminder:** `1000 μA = 1 mA, 1000 mA = 1 A`
///
/// This is an immutable type. Any math operators return a new `Current` value.
///
/// # Creating a Current value
/// You can create a `Current` value using the `from_micro_amps` method, or using one of the
/// extension methods on integer and floating-point types:
///
/// ```rust
/// use ohms::prelude::*;
///
/// let c1 = Current::from_micro_amps(1000); // 1mA
///
/// // More ergonomic:
/// let c2 = 100.milli_amps(); // 0.1A
/// let c3 = 3.2.amps(); // 3.2A
/// ```
///
/// # Comparing Current values
/// You can compare two `Current` values using the `==`, `!=`, `<`, `>`, `<=` and `>=` operators.
///
/// ```rust
/// use ohms::prelude::*;
///
/// let c1 = 220.milli_amps(); // 220mA
/// let c2 = 1.2.amps(); // 1.2A
///
/// if c1 > c2 {
///     println!("{:?} is greater than {:?}", c1, c2);
/// } else {
///     println!("{:?} is less than or equal to {:?}", c1, c2);
/// }
/// ```
///
/// # Combining Current values
/// You can use the `+` and `-` operators to add and subtract `Current` values from each other.
/// The result is a new `Current` value, rounded down to the nearest whole microamp (μA).
///
/// If the result of the operation would overflow or underflow, the operation will panic.
///
/// ```rust
/// use ohms::prelude::*;
///
/// let c1 = 500.amps(); // 0.5A
/// let c2 = 1.1.amps(); // 1.1A
///
/// let c3 = c1 + c2; // 1.6A
/// let c4 = c2 - 300.milli_amps(); // 0.8A
/// ```
///
/// # Scaling Current values
/// You can use the `*` and `/` operators to scale `Current` values by a scalar `u32` or `f32` value.
/// The result is a new `Current` value, rounded down to the nearest whole microamp (μA).
///
/// If the result of operation would overflow or underflow, the operation will panic.
///
/// If the result of the operation would be infinite or NaN, the operation will panic.
///
/// ```rust
/// use ohms::prelude::*;
///
/// let c1 = 200.milli_amps(); // 200mA
/// let c2 = c1 * 3; // 660mA
///
/// let r3 = 1.5.amps(); // 1.5A
/// let r4 = r3 / 2.5; // 0.6A
/// ```
///
/// # Converting to other denominations
/// You can use the `micro_amps`, `milli_amps`, and `amps`, methods to convert a `Current`
/// value to a numeric value in the specified denomination.
///
/// ```rust
/// use ohms::prelude::*;
///
/// let c1 = 1.2.amps(); // 1.2A
///
/// println!("{:.3}A is {:.1}A", c1.amps(), c1.milli_amps());
/// ```
///
#[derive(Clone, Copy, Debug)]
pub struct Current {
    raw: u64,
}

impl Current {
    /// Creates a new `Current` from a number of whole microamps (μA).
    ///
    /// It is recommended to use the `micro_amps`, `milli_amps`, and `amps`, extension
    /// methods on integer and floating-point types instead.
    #[inline]
    pub const fn from_micro_amps(value: u64) -> Current {
        Current { raw: value }
    }

    /// Returns the current value in whole microamps (μA).
    #[inline]
    pub const fn micro_amps(&self) -> u64 {
        self.raw
    }

    /// Returns the current value in fractional milliamps (A).
    #[inline]
    pub fn milli_amps(&self) -> f64 {
        self.raw as f64 / 1_000f64
    }

    /// Returns the current value in fractional amps (A).
    #[inline]
    pub fn amps(&self) -> f64 {
        self.raw as f64 / 1_000_000f64
    }

    /// Returns whether the current value is zero amps (0A).
    #[inline]
    pub const fn is_zero(&self) -> bool {
        self.raw == 0
    }

    /// Returns a `Current` value of zero amps (0A).
    #[inline]
    pub const fn zero() -> Self {
        Current::from_micro_amps(0)
    }
}

impl PartialEq for Current {
    #[inline]
    fn eq(&self, other: &Current) -> bool {
        self.raw == other.raw
    }
}

impl Eq for Current {}

impl PartialOrd for Current {
    #[inline]
    fn partial_cmp(&self, other: &Current) -> Option<cmp::Ordering> {
        self.raw.partial_cmp(&other.raw)
    }
}

impl Ord for Current {
    #[inline]
    fn cmp(&self, other: &Current) -> cmp::Ordering {
        self.raw.cmp(&other.raw)
    }
}

impl ops::Add for Current {
    type Output = Current;

    /// Adds two `Current` values together, returning a new `Current` value.
    #[inline]
    fn add(self, other: Current) -> Current {
        self.raw
            .checked_add(other.raw)
            .map(Current::from_micro_amps)
            .expect("Overflow when adding current values")
    }
}

impl ops::Sub for Current {
    type Output = Current;

    /// Subtracts one `Current` value from another, returning a new `Current` value.
    #[inline]
    fn sub(self, other: Current) -> Current {
        self.raw
            .checked_sub(other.raw)
            .map(Current::from_micro_amps)
            .expect("Overflow when subtracting current values")
    }
}

macro_rules! impl_mul_for_integer {
    ($i:ty) => {
        impl ops::Mul<$i> for Current {
            type Output = Current;

            #[inline]
            #[allow(unused_comparisons)]
            fn mul(self, scale_factor: $i) -> Current {
                if scale_factor < 0 {
                    panic!("Cannot multiply current value by negative value")
                }
                self.raw
                    .checked_mul(scale_factor as u64)
                    .map(Current::from_micro_amps)
                    .expect("Overflow when multiplying current value")
            }
        }
    };
}

impl_mul_for_integer!(u8);
impl_mul_for_integer!(u16);
impl_mul_for_integer!(u32);
impl_mul_for_integer!(u64);
impl_mul_for_integer!(i8);
impl_mul_for_integer!(i16);
impl_mul_for_integer!(i32);
impl_mul_for_integer!(i64);

impl ops::Mul<f32> for Current {
    type Output = Current;

    /// Multiplies a `Current` value by a floating-point value, returning a new `Current` value.
    #[inline]
    fn mul(self, scale_factor: f32) -> Current {
        self * scale_factor as f64
    }
}

impl ops::Mul<f64> for Current {
    type Output = Current;

    /// Multiplies a `Current` value by a floating-point value, returning a new `Current` value.
    #[inline]
    fn mul(self, scale_factor: f64) -> Current {
        let result = match scale_factor {
            _ if scale_factor.is_infinite() => {
                panic!("Cannot multiply current value by infinity")
            }
            _ if scale_factor.is_nan() => panic!("Cannot multiply current value by NaN"),
            _ if scale_factor.is_sign_negative() => {
                panic!("Cannot multiply current value by negative value")
            }
            _ => self.raw as f64 * scale_factor,
        };

        Current::from_micro_amps(result as u64)
    }
}

macro_rules! impl_div_for_integer {
    ($i:ty) => {
        impl ops::Div<$i> for Current {
            type Output = Current;

            /// Divides a `Current` value by an integer value, returning a new `Current` value.
            #[inline]
            #[allow(unused_comparisons)]
            fn div(self, divisor: $i) -> Current {
                if divisor == 0 {
                    panic!("Cannot divide current value by zero");
                } else if divisor < 0 {
                    panic!("Cannot divide current value by negative value");
                }
                self.raw
                    .checked_div(divisor as u64)
                    .map(Current::from_micro_amps)
                    .expect("Overflow when dividing current value")
            }
        }
    };
}

impl_div_for_integer!(u8);
impl_div_for_integer!(u16);
impl_div_for_integer!(u32);
impl_div_for_integer!(u64);
impl_div_for_integer!(i8);
impl_div_for_integer!(i16);
impl_div_for_integer!(i32);
impl_div_for_integer!(i64);

impl ops::Div<f32> for Current {
    type Output = Current;

    /// Divides a `Current` value by a floating-point value, returning a new `Current` value.
    #[inline]
    fn div(self, divisor: f32) -> Current {
        self / divisor as f64
    }
}

impl ops::Div<f64> for Current {
    type Output = Current;

    /// Divides a `Current` value by a floating-point value, returning a new `Current` value.
    #[inline]
    fn div(self, divisor: f64) -> Current {
        let result = match divisor {
            _ if divisor == 0f64 => panic!("Cannot divide current value by zero"),
            _ if divisor.is_infinite() => {
                panic!("Cannot divide current value by infinity")
            }
            _ if divisor.is_nan() => panic!("Cannot divide current value by NaN"),
            _ if divisor.is_sign_negative() => {
                panic!("Cannot divide current value by negative value")
            }
            _ => (self.raw as f64) / divisor,
        };

        Current::from_micro_amps(result as u64)
    }
}

/// Extension trait for simple short-hands for creating `Current` values from `u32` values.
pub trait FromInteger {
    /// Creates a new `Current` from a number of whole microamps (μA).
    fn micro_amps(self) -> Current;

    /// Creates a new `Current` from a number of whole milliamps (mA).
    fn milli_amps(self) -> Current;

    /// Creates a new `Current` from a number of whole amps (A).
    fn amps(self) -> Current;
}

macro_rules! impl_current_from_integer {
    ($i:ty) => {
        impl FromInteger for $i {
            #[inline]
            fn micro_amps(self) -> Current {
                Current::from_micro_amps(self as u64)
            }

            #[inline]
            fn milli_amps(self) -> Current {
                let milliamps = (self as u64)
                    .checked_mul(1_000)
                    .expect("Overflow when converting milliamps to microamps");
                Current::from_micro_amps(milliamps)
            }

            #[inline]
            fn amps(self) -> Current {
                let milliamps = (self as u64)
                    .checked_mul(1_000_000)
                    .expect("Overflow when converting amps to microamps");
                Current::from_micro_amps(milliamps)
            }
        }
    };
}

impl_current_from_integer!(u8);
impl_current_from_integer!(u16);
impl_current_from_integer!(u32);
impl_current_from_integer!(u64);
impl_current_from_integer!(i8);
impl_current_from_integer!(i16);
impl_current_from_integer!(i32);
impl_current_from_integer!(i64);

/// Extension trait for simple short-hands for creating `Current` values from `f32` values.
pub trait FromFloat {
    /// Creates a new `Current` from a number of fractional microamps (μA).
    ///
    /// The fractional part is rounded down to the nearest whole microamp (μA).
    fn micro_amps(self) -> Current;

    /// Creates a new `Current` from a number of fractional milliamps (mA).
    ///
    /// The fractional part is rounded down to the nearest whole microamp (μA).
    fn milli_amps(self) -> Current;

    /// Creates a new `Current` from a number of fractional amps (A).
    ///
    /// The fractional part is rounded down to the nearest whole microamp (μA).
    fn amps(self) -> Current;
}

macro_rules! impl_current_from_float {
    ($f:ty) => {
        impl FromFloat for $f {
            #[inline]
            fn micro_amps(self) -> Current {
                assert_positive_float!(self);
                Current::from_micro_amps(self as u64)
            }

            #[inline]
            fn milli_amps(self) -> Current {
                assert_positive_float!(self);
                let milliamps = (self as f64) * 1_000f64;
                Current::from_micro_amps(milliamps as u64)
            }

            #[inline]
            fn amps(self) -> Current {
                assert_positive_float!(self);
                let milliamps = (self as f64) * 1_000_000f64;
                Current::from_micro_amps(milliamps as u64)
            }
        }
    };
}

impl_current_from_float!(f32);
impl_current_from_float!(f64);

impl fmt::Display for Current {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (value, unit) = match self.raw {
            0..=999 => (self.raw as f64, "μA"),
            1_000..=999_999 => ((self.raw as f64) / 1_000f64, "mA"),
            _ => ((self.raw as f64) / 1_000_000f64, "A"),
        };

        write!(f, "{value:.2} {unit}")
    }
}