Skip to main content

osom_lib_primitives/fraction/
fraction32.rs

1use super::FractionError;
2
3/// Represents a fraction value.
4///
5/// This is an `f32` value under the hood, which is in `0.0 .. 1.0`
6/// range.
7#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
8#[repr(transparent)]
9#[must_use]
10pub struct Fraction32 {
11    value: f32,
12}
13
14impl Fraction32 {
15    /// Creates a new [`Fraction32`] instance out of passed `value`.
16    ///
17    /// # Safety
18    ///
19    /// This function does not verify that `value` is in the expected
20    /// `0.0 .. 1.0` range.
21    #[inline(always)]
22    pub const unsafe fn new_unchecked(value: f32) -> Self {
23        Self { value }
24    }
25
26    /// Creates a new [`Fraction32`] instance out of passed value.
27    ///
28    /// # Errors
29    ///
30    /// Return [`FractionError::NotAFraction`] if the passed `value`
31    /// is outside of `0.0 .. 1.0` range.
32    #[inline(always)]
33    pub const fn new(value: f32) -> Result<Self, FractionError> {
34        if value >= 0.0 && value < 1.0 {
35            Ok(unsafe { Self::new_unchecked(value) })
36        } else {
37            Err(FractionError::NotAFraction)
38        }
39    }
40
41    /// Returns the underlying `f32` value.
42    #[inline(always)]
43    #[must_use]
44    pub const fn value(&self) -> f32 {
45        self.value
46    }
47}