rune/core/object/
float.rs

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
48
49
50
51
use super::{CloneIn, IntoObject};
use crate::core::gc::{Block, GcHeap, GcState, Trace};
use crate::NewtypeMarkable;
use macro_attr_2018::macro_attr;
use newtype_derive_2018::*;
use rune_macros::Trace;
use std::fmt::{Debug, Display};

macro_attr! {
    /// A wrapper type for floats to work around issues with Eq. Rust only allows
    /// types to be used in match statements if they derive Eq. Even if you never
    /// actually use that field in a match. So we need a float wrapper that
    /// implements that trait.
    #[derive(PartialEq, NewtypeDeref!, NewtypeMarkable!, Trace)]
    pub(crate) struct LispFloat(GcHeap<f64>);
}

impl LispFloat {
    pub fn new(float: f64, constant: bool) -> Self {
        LispFloat(GcHeap::new(float, constant))
    }
}

impl Trace for f64 {
    fn trace(&self, _: &mut GcState) {}
}

impl Eq for LispFloat {}

impl<'new> CloneIn<'new, &'new LispFloat> for LispFloat {
    fn clone_in<const C: bool>(&self, bk: &'new Block<C>) -> super::Gc<&'new Self> {
        (**self).into_obj(bk)
    }
}

impl Display for LispFloat {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let float = **self;
        if float.fract() == 0.0_f64 {
            write!(f, "{float:.1}")
        } else {
            write!(f, "{float}")
        }
    }
}

impl Debug for LispFloat {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{self}")
    }
}