Skip to main content

mz_expr/scalar/func/impls/
uint32.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::fmt;
11
12use mz_expr_derive::sqlfunc;
13use mz_lowertest::MzReflect;
14use mz_repr::adt::numeric::{self, Numeric, NumericMaxScale};
15use mz_repr::{SqlColumnType, SqlScalarType, strconv};
16use serde::{Deserialize, Serialize};
17
18use crate::EvalError;
19use crate::scalar::func::EagerUnaryFunc;
20
21#[sqlfunc(
22    sqlname = "~",
23    preserves_uniqueness = true,
24    inverse = to_unary!(super::BitNotUint32)
25)]
26fn bit_not_uint32(a: u32) -> u32 {
27    !a
28}
29
30#[sqlfunc(
31    sqlname = "uint4_to_real",
32    preserves_uniqueness = false,
33    inverse = to_unary!(super::CastFloat32ToUint32),
34    is_monotone = true
35)]
36fn cast_uint32_to_float32(a: u32) -> f32 {
37    // TODO(benesch): remove potentially dangerous usage of `as`.
38    #[allow(clippy::as_conversions)]
39    {
40        a as f32
41    }
42}
43
44#[sqlfunc(
45    sqlname = "uint4_to_double",
46    preserves_uniqueness = true,
47    inverse = to_unary!(super::CastFloat64ToUint32),
48    is_monotone = true
49)]
50fn cast_uint32_to_float64(a: u32) -> f64 {
51    f64::from(a)
52}
53
54#[sqlfunc(
55    sqlname = "uint4_to_uint2",
56    // Partial: errors for `u32` values above `u16::MAX`. Marking this as
57    // uniqueness-preserving would let cast inversion rewrite `col::uint2 = lit`
58    // into an index lookup on `col`, skipping the cast and dropping its
59    // out-of-range error.
60    preserves_uniqueness = false,
61    inverse = to_unary!(super::CastUint16ToUint32),
62    is_monotone = true
63)]
64fn cast_uint32_to_uint16(a: u32) -> Result<u16, EvalError> {
65    u16::try_from(a).or_else(|_| Err(EvalError::UInt16OutOfRange(a.to_string().into())))
66}
67
68#[sqlfunc(
69    sqlname = "uint4_to_uint8",
70    preserves_uniqueness = true,
71    inverse = to_unary!(super::CastUint64ToUint32),
72    is_monotone = true
73)]
74fn cast_uint32_to_uint64(a: u32) -> u64 {
75    u64::from(a)
76}
77
78#[sqlfunc(
79    sqlname = "uint4_to_smallint",
80    // Partial: errors for `u32` values above `i16::MAX`. See `uint4_to_uint2`.
81    preserves_uniqueness = false,
82    inverse = to_unary!(super::CastInt16ToUint32),
83    is_monotone = true
84)]
85fn cast_uint32_to_int16(a: u32) -> Result<i16, EvalError> {
86    i16::try_from(a).or_else(|_| Err(EvalError::Int16OutOfRange(a.to_string().into())))
87}
88
89#[sqlfunc(
90    sqlname = "uint4_to_integer",
91    // Partial: errors for `u32` values above `i32::MAX`. See `uint4_to_uint2`.
92    preserves_uniqueness = false,
93    inverse = to_unary!(super::CastInt32ToUint32),
94    is_monotone = true
95)]
96fn cast_uint32_to_int32(a: u32) -> Result<i32, EvalError> {
97    i32::try_from(a).or_else(|_| Err(EvalError::Int32OutOfRange(a.to_string().into())))
98}
99
100#[sqlfunc(
101    sqlname = "uint4_to_bigint",
102    preserves_uniqueness = true,
103    inverse = to_unary!(super::CastInt64ToUint32),
104    is_monotone = true
105)]
106fn cast_uint32_to_int64(a: u32) -> i64 {
107    i64::from(a)
108}
109
110#[sqlfunc(
111    sqlname = "uint4_to_text",
112    preserves_uniqueness = true,
113    inverse = to_unary!(super::CastStringToUint32)
114)]
115fn cast_uint32_to_string(a: u32) -> String {
116    let mut buf = String::new();
117    strconv::format_uint32(&mut buf, a);
118    buf
119}
120
121#[derive(
122    Ord,
123    PartialOrd,
124    Clone,
125    Debug,
126    Eq,
127    PartialEq,
128    Serialize,
129    Deserialize,
130    Hash,
131    MzReflect
132)]
133pub struct CastUint32ToNumeric(pub Option<NumericMaxScale>);
134
135impl EagerUnaryFunc for CastUint32ToNumeric {
136    type Input<'a> = u32;
137    type Output<'a> = Result<Numeric, EvalError>;
138
139    fn call<'a>(&self, a: Self::Input<'a>) -> Self::Output<'a> {
140        let mut a = Numeric::from(a);
141        if let Some(scale) = self.0 {
142            if numeric::rescale(&mut a, scale.into_u8()).is_err() {
143                return Err(EvalError::NumericFieldOverflow);
144            }
145        }
146        // Besides `rescale`, cast is infallible.
147        Ok(a)
148    }
149
150    fn output_sql_type(&self, input: SqlColumnType) -> SqlColumnType {
151        SqlScalarType::Numeric { max_scale: self.0 }.nullable(input.nullable)
152    }
153
154    fn could_error(&self) -> bool {
155        self.0.is_some()
156    }
157
158    fn inverse(&self) -> Option<crate::UnaryFunc> {
159        to_unary!(super::CastNumericToUint32)
160    }
161
162    fn is_monotone(&self) -> bool {
163        true
164    }
165}
166
167impl fmt::Display for CastUint32ToNumeric {
168    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169        f.write_str("uint4_to_numeric")
170    }
171}