python/
float.rs

1#![allow(unused_imports)]
2
3use std::fmt;
4
5use unindent::{
6    unindent,
7    Unindent,
8};
9
10use std::hash::Hash;
11use crate::_Object;
12use crate::type_of;
13
14#[derive(Copy)]
15#[derive(Clone)]
16/// Float struct that handles f32 and f64
17pub struct Float<T: Sized> {
18    // this can be f32 or f64
19    _float: T,
20}
21
22
23impl<T> Float<T>
24where
25    T: Sized,
26{
27    /// constructor
28    /// creates a Float object from any float (f32, f64)
29    pub fn new(_float: T) -> Self {
30        Float {
31            _float,
32        }
33    }
34}
35
36impl<T> From<T> for Float<T>
37where
38    T: Sized,
39{
40    fn from(_float: T) -> Self {
41        Float {
42            _float,
43        }
44    }
45}
46
47
48impl Default for Float<f32> {
49    fn default() -> Self {
50        Float {
51            _float: 0.0f32
52        }
53    }
54}
55
56impl Default for Float<f64> {
57    fn default() -> Self {
58        Float {
59            _float: 0.0f64
60        }
61    }
62}
63
64
65impl<T> _Object for Float<T>
66where
67    T: Sized + fmt::Display,
68{
69    fn __repr__(&self) -> String {
70        format!("{}", self._float)
71    }
72
73    fn __str__(&self) -> String {
74        format!("{}", self._float)
75    }
76}
77
78
79/// T cannot be formatted with the default formatter
80/// thats why there are implementations for every float possible
81impl<T> fmt::Display for Float<T>
82where
83    T: Sized + fmt::Display,
84{
85    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
86        let _type = type_of(&self._float);
87        if formatter.alternate() {
88            write!(formatter, "{} -> <{}>", self._float, _type)
89        } else {
90            write!(formatter, "{}", self._float)
91        }
92    }
93}
94
95
96// https://doc.rust-lang.org/std/fmt/struct.Formatter.html
97// TODO make something like rich inspect with colors and stuff
98impl<T> fmt::Debug for Float<T>
99where
100    T: Sized + fmt::Display,
101{
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        // https://doc.rust-lang.org/std/fmt/struct.Formatter.html#method.alternate
104        let _type = type_of(&self._float);
105
106        if f.alternate() {
107            let _fmt = format!(
108                "Float<{}> {{
109                _float: {}
110            }}",
111                _type, self._float
112            );
113            let _fmt = _fmt.unindent();
114            write!(f, "{}", _fmt)
115        } else {
116            write!(
117                f,
118                "Float<{}> {{ _float: {} }}",
119                _type, self._float
120            )
121        }
122    }
123}
124
125
126impl<T> PartialEq<T> for Float<T>
127where
128    T: Sized + std::cmp::PartialEq,
129{
130    fn eq(&self, other: &T) -> bool {
131        self._float == *other
132    }
133}