aboutsummaryrefslogtreecommitdiffstats
path: root/components/script/dom/bindings/num.rs
blob: 03b0c743f9f55e9f9ba84ae673eaa9e269dd8238 (plain) (blame)
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
/* 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 http://mozilla.org/MPL/2.0/. */

//! The `Finite<T>` struct.

use heapsize::HeapSizeOf;
use num_traits::Float;
use std::ops::Deref;

/// Encapsulates the IDL restricted float type.
#[derive(JSTraceable, Clone, Copy, Eq, PartialEq)]
pub struct Finite<T: Float>(T);

impl<T: Float> Finite<T> {
    /// Create a new `Finite<T: Float>` safely.
    pub fn new(value: T) -> Option<Finite<T>> {
        if value.is_finite() {
            Some(Finite(value))
        } else {
            None
        }
    }

    /// Create a new `Finite<T: Float>`.
    #[inline]
    pub fn wrap(value: T) -> Finite<T> {
        assert!(value.is_finite(),
                "Finite<T> doesn't encapsulate unrestricted value.");
        Finite(value)
    }
}

impl<T: Float> Deref for Finite<T> {
    type Target = T;

    fn deref(&self) -> &T {
        let &Finite(ref value) = self;
        value
    }
}

impl<T: Float + HeapSizeOf> HeapSizeOf for Finite<T> {
    fn heap_size_of_children(&self) -> usize {
        (**self).heap_size_of_children()
    }
}