/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! The `Finite` struct. use std::default::Default; use std::ops::Deref; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use num_traits::Float; /// Encapsulates the IDL restricted float type. #[derive(Clone, Copy, Eq, JSTraceable, PartialEq)] pub struct Finite(T); impl Finite { /// Create a new `Finite` safely. pub fn new(value: T) -> Option> { if value.is_finite() { Some(Finite(value)) } else { None } } /// Create a new `Finite`. #[inline] pub fn wrap(value: T) -> Finite { assert!( value.is_finite(), "Finite doesn't encapsulate unrestricted value." ); Finite(value) } } impl Deref for Finite { type Target = T; fn deref(&self) -> &T { let Finite(value) = self; value } } impl MallocSizeOf for Finite { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { (**self).size_of(ops) } } impl Default for Finite { fn default() -> Finite { Finite::wrap(T::default()) } }