rutie/class/float.rs
1use std::convert::From;
2
3use crate::{
4 binding::float,
5 types::{Value, ValueType},
6 AnyException, AnyObject, Object, VerifiedObject, VM,
7};
8
9/// `Float`
10#[derive(Debug)]
11#[repr(C)]
12pub struct Float {
13 value: Value,
14}
15
16impl Float {
17 /// Creates a new `Float`.
18 ///
19 /// # Examples
20 ///
21 /// ```
22 /// use rutie::{Float, VM};
23 /// # VM::init();
24 ///
25 /// let float = Float::new(1.23);
26 ///
27 /// assert_eq!(float.to_f64(), 1.23);
28 /// ```
29 ///
30 /// Ruby:
31 ///
32 /// ```ruby
33 /// 1.23 == 1.23
34 /// ```
35 pub fn new(num: f64) -> Self {
36 Self::from(float::float_to_num(num))
37 }
38
39 /// Retrieves an `f64` value from `Float`.
40 ///
41 /// # Examples
42 ///
43 /// ```
44 /// use rutie::{Float, VM};
45 /// # VM::init();
46 ///
47 /// let float = Float::new(1.23);
48 ///
49 /// assert_eq!(float.to_f64(), 1.23);
50 /// ```
51 ///
52 /// Ruby:
53 ///
54 /// ```ruby
55 /// 1.23 == 1.23
56 /// ```
57 pub fn to_f64(&self) -> f64 {
58 float::num_to_float(self.value())
59 }
60
61 /// Cast any object to a `Float` implicitly, otherwise
62 /// returns an `AnyException`
63 ///
64 /// # Examples
65 ///
66 /// ```
67 /// use rutie::{Integer, Float, Object, VM};
68 /// # VM::init();
69 ///
70 /// let integer = Integer::new(3);
71 ///
72 /// assert_eq!(Float::implicit_to_f(integer), Ok(Float::new(3.0)));
73 /// ```
74 ///
75 /// Ruby:
76 ///
77 /// ```ruby
78 /// Float(3) == 3.0
79 /// ```
80 pub fn implicit_to_f(object: impl Object) -> Result<Float, AnyException> {
81 float::implicit_to_f(object.value())
82 }
83}
84
85impl From<Value> for Float {
86 fn from(value: Value) -> Self {
87 Float { value }
88 }
89}
90
91impl Into<Value> for Float {
92 fn into(self) -> Value {
93 self.value
94 }
95}
96
97impl Into<AnyObject> for Float {
98 fn into(self) -> AnyObject {
99 AnyObject::from(self.value)
100 }
101}
102
103impl Object for Float {
104 #[inline]
105 fn value(&self) -> Value {
106 self.value
107 }
108}
109
110impl VerifiedObject for Float {
111 fn is_correct_type<T: Object>(object: &T) -> bool {
112 object.value().ty() == ValueType::Float
113 }
114
115 fn error_message() -> &'static str {
116 "Error converting to Float"
117 }
118}
119
120impl PartialEq for Float {
121 fn eq(&self, other: &Self) -> bool {
122 self.equals(other)
123 }
124}