artichoke_core/coerce_to_numeric.rs
1//! Coerce Ruby values to native numerics.
2
3use crate::value::Value;
4
5/// Coerce Ruby values to native numerics (floats and integers).
6pub trait CoerceToNumeric {
7 /// Concrete type of boxed Ruby value as inputs to coerce functions.
8 type Value: Value;
9
10 /// Concrete float type to coerce values into, e.g. [`f64`].
11 type Float;
12
13 /// Concrete error type for errors encountered when coercing values.
14 type Error;
15
16 /// Coerce the given Ruby value to a `Float`.
17 ///
18 /// This coercion mechanism is used by Ruby to handle mixed-type numeric
19 /// operations: it is intended to find a compatible common type between the two
20 /// operands of the operator.
21 ///
22 /// See [`Numeric#coerce`].
23 ///
24 /// # Errors
25 ///
26 /// If a Ruby `nil` is given, an error is returned.
27 ///
28 /// If the given value does not subclass [`Numeric`], an error is returned.
29 ///
30 /// If the [`Numeric` class] is not defined, an error is returned.
31 ///
32 /// If the underlying interpreter returns an error when calling `#to_f` or
33 /// [`Numeric#coerce`], the error is returned.
34 ///
35 /// [`Numeric`]: https://ruby-doc.org/core-3.1.2/Numeric.html
36 /// [`Numeric` class]: https://ruby-doc.org/core-3.1.2/Numeric.html
37 /// [`Numeric#coerce`]: https://ruby-doc.org/core-3.1.2/Numeric.html#method-i-coerce
38 fn coerce_to_float(&mut self, value: Self::Value) -> Result<Self::Float, Self::Error>;
39}