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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use std::fmt;

use mz_lowertest::MzReflect;
use mz_repr::adt::numeric::{self, Numeric, NumericMaxScale};
use mz_repr::{strconv, ColumnType, ScalarType};
use serde::{Deserialize, Serialize};

use crate::scalar::func::EagerUnaryFunc;
use crate::EvalError;

sqlfunc!(
    #[sqlname = "-"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(NegFloat32)]
    #[is_monotone = true]
    fn neg_float32(a: f32) -> f32 {
        -a
    }
);

sqlfunc!(
    #[sqlname = "abs"]
    fn abs_float32(a: f32) -> f32 {
        a.abs()
    }
);

sqlfunc!(
    #[sqlname = "roundf32"]
    fn round_float32(a: f32) -> f32 {
        // f32::round violates IEEE 754 by rounding ties away from zero rather than
        // to nearest even. There appears to be no way to round ties to nearest even
        // in Rust natively, so bail out to C.
        extern "C" {
            fn rintf(f: f32) -> f32;
        }
        unsafe { rintf(a) }
    }
);

sqlfunc!(
    #[sqlname = "truncf32"]
    fn trunc_float32(a: f32) -> f32 {
        a.trunc()
    }
);

sqlfunc!(
    #[sqlname = "ceilf32"]
    fn ceil_float32(a: f32) -> f32 {
        a.ceil()
    }
);

sqlfunc!(
    #[sqlname = "floorf32"]
    fn floor_float32(a: f32) -> f32 {
        a.floor()
    }
);

sqlfunc!(
    #[sqlname = "real_to_smallint"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastInt16ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_int16(a: f32) -> Result<i16, EvalError> {
        let f = round_float32(a);
        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        if (f >= (i16::MIN as f32)) && (f < -(i16::MIN as f32)) {
            Ok(f as i16)
        } else {
            Err(EvalError::Int16OutOfRange(f.to_string()))
        }
    }
);

sqlfunc!(
    #[sqlname = "real_to_integer"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastInt32ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_int32(a: f32) -> Result<i32, EvalError> {
        let f = round_float32(a);
        // This condition is delicate because i32::MIN can be represented exactly by
        // an f32 but not i32::MAX. We follow PostgreSQL's approach here.
        //
        // See: https://github.com/postgres/postgres/blob/ca3b37487/src/include/c.h#L1074-L1096
        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        if (f >= (i32::MIN as f32)) && (f < -(i32::MIN as f32)) {
            Ok(f as i32)
        } else {
            Err(EvalError::Int32OutOfRange(f.to_string()))
        }
    }
);

sqlfunc!(
    #[sqlname = "real_to_bigint"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastInt64ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_int64(a: f32) -> Result<i64, EvalError> {
        let f = round_float32(a);
        // This condition is delicate because i64::MIN can be represented exactly by
        // an f32 but not i64::MAX. We follow PostgreSQL's approach here.
        //
        // See: https://github.com/postgres/postgres/blob/ca3b37487/src/include/c.h#L1074-L1096
        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        if (f >= (i64::MIN as f32)) && (f < -(i64::MIN as f32)) {
            Ok(f as i64)
        } else {
            Err(EvalError::Int64OutOfRange(f.to_string()))
        }
    }
);

sqlfunc!(
    #[sqlname = "real_to_double"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastFloat64ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_float64(a: f32) -> f64 {
        a.into()
    }
);

sqlfunc!(
    #[sqlname = "real_to_text"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastStringToFloat32)]
    fn cast_float32_to_string(a: f32) -> String {
        let mut s = String::new();
        strconv::format_float32(&mut s, a);
        s
    }
);

sqlfunc!(
    #[sqlname = "real_to_uint2"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastUint16ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_uint16(a: f32) -> Result<u16, EvalError> {
        let f = round_float32(a);
        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        if (f >= 0.0) && (f <= (u16::MAX as f32)) {
            Ok(f as u16)
        } else {
            Err(EvalError::UInt16OutOfRange(f.to_string()))
        }
    }
);

sqlfunc!(
    #[sqlname = "real_to_uint4"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastUint32ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_uint32(a: f32) -> Result<u32, EvalError> {
        let f = round_float32(a);
        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        if (f >= 0.0) && (f <= (u32::MAX as f32)) {
            Ok(f as u32)
        } else {
            Err(EvalError::UInt32OutOfRange(f.to_string()))
        }
    }
);

sqlfunc!(
    #[sqlname = "real_to_uint8"]
    #[preserves_uniqueness = false]
    #[inverse = to_unary!(super::CastUint64ToFloat32)]
    #[is_monotone = true]
    fn cast_float32_to_uint64(a: f32) -> Result<u64, EvalError> {
        let f = round_float32(a);
        // TODO(benesch): remove potentially dangerous usage of `as`.
        #[allow(clippy::as_conversions)]
        if (f >= 0.0) && (f <= (u64::MAX as f32)) {
            Ok(f as u64)
        } else {
            Err(EvalError::UInt64OutOfRange(f.to_string()))
        }
    }
);

#[derive(Ord, PartialOrd, Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Hash, MzReflect)]
pub struct CastFloat32ToNumeric(pub Option<NumericMaxScale>);

impl<'a> EagerUnaryFunc<'a> for CastFloat32ToNumeric {
    type Input = f32;
    type Output = Result<Numeric, EvalError>;

    fn call(&self, a: f32) -> Result<Numeric, EvalError> {
        if a.is_infinite() {
            return Err(EvalError::InfinityOutOfDomain(
                "casting real to numeric".to_owned(),
            ));
        }
        let mut a = Numeric::from(a);
        if let Some(scale) = self.0 {
            if numeric::rescale(&mut a, scale.into_u8()).is_err() {
                return Err(EvalError::NumericFieldOverflow);
            }
        }
        numeric::munge_numeric(&mut a).unwrap();
        Ok(a)
    }

    fn output_type(&self, input: ColumnType) -> ColumnType {
        ScalarType::Numeric { max_scale: self.0 }.nullable(input.nullable)
    }

    fn inverse(&self) -> Option<crate::UnaryFunc> {
        to_unary!(super::CastNumericToFloat32)
    }

    fn is_monotone(&self) -> bool {
        true
    }
}

impl fmt::Display for CastFloat32ToNumeric {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("real_to_numeric")
    }
}