1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::fmt;
7
8pub mod prelude;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum PressureError {
12 NonPositiveArea,
13}
14
15impl fmt::Display for PressureError {
16 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
17 match self {
18 Self::NonPositiveArea => formatter.write_str("area must be greater than zero"),
19 }
20 }
21}
22
23impl std::error::Error for PressureError {}
24
25#[must_use]
26pub const fn hydrostatic_pressure(density: f64, gravity: f64, depth: f64) -> f64 {
27 density * gravity * depth
28}
29
30#[must_use]
31pub const fn gauge_pressure(absolute_pressure: f64, atmospheric_pressure: f64) -> f64 {
32 absolute_pressure - atmospheric_pressure
33}
34
35pub fn pressure(force: f64, area: f64) -> Result<f64, PressureError> {
41 if area <= 0.0 {
42 Err(PressureError::NonPositiveArea)
43 } else {
44 Ok(force / area)
45 }
46}
47
48#[cfg(test)]
49#[allow(clippy::float_cmp)]
50mod tests {
51 use super::{PressureError, gauge_pressure, hydrostatic_pressure, pressure};
52
53 #[test]
54 fn pressure_helpers_cover_common_calculations() -> Result<(), PressureError> {
55 assert_eq!(pressure(100.0, 4.0)?, 25.0);
56 assert_eq!(hydrostatic_pressure(1000.0, 10.0, 2.0), 20_000.0);
57 assert_eq!(gauge_pressure(120.0, 101.0), 19.0);
58 Ok(())
59 }
60
61 #[test]
62 fn pressure_requires_positive_area() {
63 assert_eq!(pressure(100.0, 0.0), Err(PressureError::NonPositiveArea));
64 }
65}