Skip to main content

force_electric/
lib.rs

1//! Typed calculations for ideal scalar DC electricity.
2//!
3//! [`DcOperatingPoint`] applies Ohm's law and DC power relationships, while
4//! [`series_resistance`], [`parallel_resistance`], and [`Energy`] connect the
5//! same validated quantities to resistance networks and usage over time.
6
7#![forbid(unsafe_code)]
8#![warn(missing_docs)]
9
10use std::error::Error;
11use std::fmt;
12
13/// A finite, non-negative electric potential in volts.
14#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
15pub struct Voltage(f64);
16
17impl Voltage {
18    /// Creates a voltage magnitude in volts.
19    pub fn volts(value: f64) -> Result<Self, ElectricError> {
20        validate_non_negative_finite(value, "voltage")?;
21        Ok(Self(value))
22    }
23
24    /// Returns the voltage magnitude in volts.
25    pub const fn as_volts(self) -> f64 {
26        self.0
27    }
28}
29
30/// A finite, non-negative electric current in amperes.
31#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
32pub struct Current(f64);
33
34impl Current {
35    /// Creates a current magnitude in amperes.
36    pub fn amperes(value: f64) -> Result<Self, ElectricError> {
37        validate_non_negative_finite(value, "current")?;
38        Ok(Self(value))
39    }
40
41    /// Returns the current magnitude in amperes.
42    pub const fn as_amperes(self) -> f64 {
43        self.0
44    }
45}
46
47/// A finite, positive electrical resistance in ohms.
48#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
49pub struct Resistance(f64);
50
51impl Resistance {
52    /// Creates a positive resistance in ohms.
53    pub fn ohms(value: f64) -> Result<Self, ElectricError> {
54        validate_positive_finite(value, "resistance")?;
55        Ok(Self(value))
56    }
57
58    /// Returns resistance in ohms.
59    pub const fn as_ohms(self) -> f64 {
60        self.0
61    }
62}
63
64/// A finite, non-negative power in watts.
65#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
66pub struct Power(f64);
67
68impl Power {
69    /// Creates a power magnitude in watts.
70    pub fn watts(value: f64) -> Result<Self, ElectricError> {
71        validate_non_negative_finite(value, "power")?;
72        Ok(Self(value))
73    }
74
75    /// Calculates ideal DC power as voltage multiplied by current.
76    pub fn from_voltage_and_current(
77        voltage: Voltage,
78        current: Current,
79    ) -> Result<Self, ElectricError> {
80        let watts = voltage.0 * current.0;
81        ensure_finite(watts)?;
82        Ok(Self(watts))
83    }
84
85    /// Returns power in watts.
86    pub const fn as_watts(self) -> f64 {
87        self.0
88    }
89}
90
91/// A finite, non-negative duration stored in seconds.
92#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
93pub struct Duration(f64);
94
95impl Duration {
96    /// Creates a duration in seconds.
97    pub fn seconds(value: f64) -> Result<Self, ElectricError> {
98        validate_non_negative_finite(value, "duration")?;
99        Ok(Self(value))
100    }
101
102    /// Creates a duration in hours.
103    pub fn hours(value: f64) -> Result<Self, ElectricError> {
104        validate_non_negative_finite(value, "duration")?;
105        let seconds = value * 3_600.0;
106        ensure_finite(seconds)?;
107        Ok(Self(seconds))
108    }
109
110    /// Returns the duration in seconds.
111    pub const fn as_seconds(self) -> f64 {
112        self.0
113    }
114
115    /// Returns the duration in hours.
116    pub fn as_hours(self) -> f64 {
117        self.0 / 3_600.0
118    }
119}
120
121/// A finite, non-negative amount of energy stored in joules.
122#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
123pub struct Energy(f64);
124
125impl Energy {
126    /// Creates an energy amount in joules.
127    pub fn joules(value: f64) -> Result<Self, ElectricError> {
128        validate_non_negative_finite(value, "energy")?;
129        Ok(Self(value))
130    }
131
132    /// Creates an energy amount in watt-hours.
133    pub fn watt_hours(value: f64) -> Result<Self, ElectricError> {
134        validate_non_negative_finite(value, "energy")?;
135        let joules = value * 3_600.0;
136        ensure_finite(joules)?;
137        Ok(Self(joules))
138    }
139
140    /// Calculates energy consumed by constant power over a duration.
141    pub fn from_power_over(power: Power, duration: Duration) -> Result<Self, ElectricError> {
142        let joules = power.0 * duration.0;
143        ensure_finite(joules)?;
144        Ok(Self(joules))
145    }
146
147    /// Returns energy in joules.
148    pub const fn as_joules(self) -> f64 {
149        self.0
150    }
151
152    /// Returns energy in watt-hours.
153    pub fn as_watt_hours(self) -> f64 {
154        self.0 / 3_600.0
155    }
156
157    /// Calculates how long this energy can supply constant, positive power.
158    pub fn runtime_at(self, power: Power) -> Result<Duration, ElectricError> {
159        if power.0 == 0.0 {
160            return Err(ElectricError::ZeroPower);
161        }
162        let seconds = self.0 / power.0;
163        ensure_finite(seconds)?;
164        Ok(Duration(seconds))
165    }
166}
167
168/// A complete ideal DC operating point satisfying Ohm's law.
169#[derive(Debug, Clone, Copy, PartialEq)]
170pub struct DcOperatingPoint {
171    voltage: Voltage,
172    current: Current,
173    resistance: Resistance,
174    power: Power,
175}
176
177impl DcOperatingPoint {
178    /// Derives current and power from voltage and resistance.
179    pub fn from_voltage_and_resistance(
180        voltage: Voltage,
181        resistance: Resistance,
182    ) -> Result<Self, ElectricError> {
183        let current = Current(voltage.0 / resistance.0);
184        ensure_finite(current.0)?;
185        Self::assemble(voltage, current, resistance)
186    }
187
188    /// Derives voltage and power from current and resistance.
189    pub fn from_current_and_resistance(
190        current: Current,
191        resistance: Resistance,
192    ) -> Result<Self, ElectricError> {
193        let voltage = Voltage(current.0 * resistance.0);
194        ensure_finite(voltage.0)?;
195        Self::assemble(voltage, current, resistance)
196    }
197
198    /// Derives resistance and power from positive voltage and current.
199    pub fn from_voltage_and_current(
200        voltage: Voltage,
201        current: Current,
202    ) -> Result<Self, ElectricError> {
203        if voltage.0 == 0.0 || current.0 == 0.0 {
204            return Err(ElectricError::UnderdeterminedResistance);
205        }
206        let resistance = Resistance(voltage.0 / current.0);
207        ensure_finite(resistance.0)?;
208        Self::assemble(voltage, current, resistance)
209    }
210
211    fn assemble(
212        voltage: Voltage,
213        current: Current,
214        resistance: Resistance,
215    ) -> Result<Self, ElectricError> {
216        let power = Power::from_voltage_and_current(voltage, current)?;
217        Ok(Self {
218            voltage,
219            current,
220            resistance,
221            power,
222        })
223    }
224
225    /// Returns voltage.
226    pub const fn voltage(self) -> Voltage {
227        self.voltage
228    }
229
230    /// Returns current.
231    pub const fn current(self) -> Current {
232        self.current
233    }
234
235    /// Returns resistance.
236    pub const fn resistance(self) -> Resistance {
237        self.resistance
238    }
239
240    /// Returns ideal DC power.
241    pub const fn power(self) -> Power {
242        self.power
243    }
244}
245
246/// Calculates the equivalent resistance of a non-empty series network.
247pub fn series_resistance(resistors: &[Resistance]) -> Result<Resistance, ElectricError> {
248    if resistors.is_empty() {
249        return Err(ElectricError::EmptyResistanceNetwork);
250    }
251    let mut total = 0.0;
252    for resistor in resistors {
253        total += resistor.0;
254        ensure_finite(total)?;
255    }
256    Ok(Resistance(total))
257}
258
259/// Calculates the equivalent resistance of a non-empty parallel network.
260pub fn parallel_resistance(resistors: &[Resistance]) -> Result<Resistance, ElectricError> {
261    if resistors.is_empty() {
262        return Err(ElectricError::EmptyResistanceNetwork);
263    }
264    let mut reciprocal_sum = 0.0;
265    for resistor in resistors {
266        reciprocal_sum += 1.0 / resistor.0;
267        ensure_finite(reciprocal_sum)?;
268    }
269    let equivalent = 1.0 / reciprocal_sum;
270    ensure_finite(equivalent)?;
271    if equivalent == 0.0 {
272        return Err(ElectricError::CalculationOutOfRange);
273    }
274    Ok(Resistance(equivalent))
275}
276
277/// Invalid electrical input or a calculation outside finite numeric range.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub enum ElectricError {
280    /// A named input was not finite.
281    NonFinite(&'static str),
282    /// A named input was negative.
283    Negative(&'static str),
284    /// A named input had to be positive but was zero.
285    Zero(&'static str),
286    /// Zero voltage or current could not determine a finite positive resistance.
287    UnderdeterminedResistance,
288    /// Runtime cannot be calculated at zero power.
289    ZeroPower,
290    /// An equivalent resistance was requested for no resistors.
291    EmptyResistanceNetwork,
292    /// Arithmetic produced a non-finite or unrepresentable result.
293    CalculationOutOfRange,
294}
295
296impl fmt::Display for ElectricError {
297    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
298        match self {
299            Self::NonFinite(name) => write!(formatter, "{name} must be finite"),
300            Self::Negative(name) => write!(formatter, "{name} must not be negative"),
301            Self::Zero(name) => write!(formatter, "{name} must be greater than zero"),
302            Self::UnderdeterminedResistance => formatter
303                .write_str("voltage and current must both be positive to derive resistance"),
304            Self::ZeroPower => formatter.write_str("runtime at zero power is undefined"),
305            Self::EmptyResistanceNetwork => {
306                formatter.write_str("resistance network must not be empty")
307            }
308            Self::CalculationOutOfRange => {
309                formatter.write_str("calculation exceeded representable finite range")
310            }
311        }
312    }
313}
314
315impl Error for ElectricError {}
316
317fn validate_non_negative_finite(value: f64, name: &'static str) -> Result<(), ElectricError> {
318    if !value.is_finite() {
319        return Err(ElectricError::NonFinite(name));
320    }
321    if value < 0.0 {
322        return Err(ElectricError::Negative(name));
323    }
324    Ok(())
325}
326
327fn validate_positive_finite(value: f64, name: &'static str) -> Result<(), ElectricError> {
328    validate_non_negative_finite(value, name)?;
329    if value == 0.0 {
330        return Err(ElectricError::Zero(name));
331    }
332    Ok(())
333}
334
335fn ensure_finite(value: f64) -> Result<(), ElectricError> {
336    if value.is_finite() {
337        Ok(())
338    } else {
339        Err(ElectricError::CalculationOutOfRange)
340    }
341}
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    #[test]
348    fn voltage_and_resistance_derive_current_and_power() {
349        let point = DcOperatingPoint::from_voltage_and_resistance(
350            Voltage::volts(12.0).unwrap(),
351            Resistance::ohms(6.0).unwrap(),
352        )
353        .unwrap();
354        assert_eq!(point.current().as_amperes(), 2.0);
355        assert_eq!(point.power().as_watts(), 24.0);
356    }
357
358    #[test]
359    fn current_and_resistance_derive_voltage() {
360        let point = DcOperatingPoint::from_current_and_resistance(
361            Current::amperes(0.5).unwrap(),
362            Resistance::ohms(20.0).unwrap(),
363        )
364        .unwrap();
365        assert_eq!(point.voltage().as_volts(), 10.0);
366        assert_eq!(point.power().as_watts(), 5.0);
367    }
368
369    #[test]
370    fn voltage_and_current_derive_resistance() {
371        let point = DcOperatingPoint::from_voltage_and_current(
372            Voltage::volts(9.0).unwrap(),
373            Current::amperes(0.3).unwrap(),
374        )
375        .unwrap();
376        assert_eq!(point.resistance().as_ohms(), 30.0);
377    }
378
379    #[test]
380    fn equivalent_resistances_are_calculated() {
381        let resistors = [
382            Resistance::ohms(100.0).unwrap(),
383            Resistance::ohms(100.0).unwrap(),
384        ];
385        assert_eq!(series_resistance(&resistors).unwrap().as_ohms(), 200.0);
386        assert!((parallel_resistance(&resistors).unwrap().as_ohms() - 50.0).abs() < 1e-12);
387    }
388
389    #[test]
390    fn power_over_time_produces_energy_and_runtime() {
391        let energy =
392            Energy::from_power_over(Power::watts(24.0).unwrap(), Duration::hours(3.0).unwrap())
393                .unwrap();
394        assert_eq!(energy.as_watt_hours(), 72.0);
395        assert_eq!(
396            energy
397                .runtime_at(Power::watts(36.0).unwrap())
398                .unwrap()
399                .as_hours(),
400            2.0
401        );
402    }
403
404    #[test]
405    fn invalid_inputs_are_rejected() {
406        assert_eq!(
407            Voltage::volts(f64::NAN),
408            Err(ElectricError::NonFinite("voltage"))
409        );
410        assert_eq!(
411            Current::amperes(-1.0),
412            Err(ElectricError::Negative("current"))
413        );
414        assert_eq!(
415            Resistance::ohms(0.0),
416            Err(ElectricError::Zero("resistance"))
417        );
418        assert_eq!(
419            parallel_resistance(&[]),
420            Err(ElectricError::EmptyResistanceNetwork)
421        );
422        assert_eq!(
423            Energy::joules(10.0)
424                .unwrap()
425                .runtime_at(Power::watts(0.0).unwrap()),
426            Err(ElectricError::ZeroPower)
427        );
428    }
429
430    #[test]
431    fn zero_pair_cannot_derive_resistance() {
432        assert_eq!(
433            DcOperatingPoint::from_voltage_and_current(
434                Voltage::volts(0.0).unwrap(),
435                Current::amperes(0.0).unwrap()
436            ),
437            Err(ElectricError::UnderdeterminedResistance)
438        );
439    }
440
441    #[test]
442    fn calculation_overflow_is_reported() {
443        assert_eq!(
444            Power::from_voltage_and_current(
445                Voltage::volts(f64::MAX).unwrap(),
446                Current::amperes(2.0).unwrap()
447            ),
448            Err(ElectricError::CalculationOutOfRange)
449        );
450    }
451}