Skip to main content

scratch_test_value/arithmetic/
multiplication.rs

1use crate::{
2    QuirkSink, SNumber, SValue,
3    quirks::{SNumberToFloatQ, SValueToNumberQ},
4};
5
6/// A multiplication of two integers would overflow/underflow so they're treated as
7/// floating point numbers for multiplication, a float is then produced instead of an int.
8///
9/// Generated by [`SNumber::q_mul_numbers`]
10pub struct IntegerMulWouldFailQ(());
11
12impl SValue {
13    /// See [`SNumber::q_mul_numbers`]
14    pub fn q_mul_numbers<Q>(&self, other: &SValue, sink: &mut Q) -> SValue
15    where
16        Q: QuirkSink<SValueToNumberQ>
17            + QuirkSink<SNumberToFloatQ>
18            + QuirkSink<IntegerMulWouldFailQ>,
19    {
20        self.q_as_number(sink)
21            .q_mul_numbers(&other.q_as_number(sink), sink)
22            .svalue()
23    }
24}
25
26impl SNumber {
27    /// If both numbers are finite integers numbers are multiplied as integers
28    /// if the result fits into an [`i64`].
29    ///
30    /// Otherwise, the below table applys. p and q are arbitraty finite floats.
31    ///
32    /// (line * column is shown in cell)
33    ///
34    /// | `*`   |    | `NaN` | `+∞`  | `-∞`  |  +q       |  -q       | `+0`  | `-0`  |
35    /// | ----- | -- | ----- | ----- | ----- | --------- | --------- | ----- | ----- |
36    /// |       |    |       |       |       |           |           |       |       |
37    /// | `NaN` |    | `0`   | `0`   | `0`   | `0`       | `0`       |  `0`  |  `0`  |
38    /// | `+∞`  |    | `0`   | `+∞`  | `-∞`  | `+∞`      | `-∞`      | `NaN` | `NaN` |
39    /// | `-∞`  |    | `0`   | `-∞`  | `+∞`  | `-∞`      | `+∞`      | `NaN` | `NaN` |
40    /// |  +p   |    | `0`   | `+∞`  | `-∞`  | (+p)*(+q) | (+p)*(-q) |  `0`  |  `0`  |
41    /// |  -p   |    | `0`   | `-∞`  | `+∞`  | (-p)*(+q) | (-p)*(-q) |  `0`  |  `0`  |
42    /// | `+0`  |    | `0`   | `NaN` | `NaN` |  `0`      | `0`       |  `0`  |  `0`  |
43    /// | `-0`  |    | `0`   | `NaN` | `NaN` |  `0`      | `0`       |  `0`  |  `0`  |
44    pub fn q_mul_numbers<Q>(&self, other: &SNumber, sink: &mut Q) -> SNumber
45    where
46        Q: QuirkSink<SNumberToFloatQ> + QuirkSink<IntegerMulWouldFailQ>,
47    {
48        if let (SNumber::Int(a), SNumber::Int(b)) = (self, other) {
49            if let Some(prod) = a.checked_mul(*b) {
50                return SNumber::Int(prod);
51            } else {
52                sink.put(IntegerMulWouldFailQ(()));
53            }
54        }
55
56        let a = self.q_as_float(sink);
57        let b = other.q_as_float(sink);
58
59        // NaN is treated as 0
60        if a.is_nan() || b.is_nan() {
61            return if a.is_infinite() || b.is_infinite() {
62                SNumber::NAN
63            } else {
64                SNumber::Int(0)
65            };
66        }
67
68        SNumber::Float(a * b)
69    }
70}