use super::*;
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Value<'a> {
Null,
Bool(bool),
I64(i64),
U64(u64),
F32(f32),
F64(f64),
Decimal(i128, u8, i8),
Str(&'a str),
}
impl<'a> Value<'a> {
#[inline]
pub(super) fn truth(v: VmTriBool) -> Self {
match v {
VmTriBool::True => Self::Bool(true),
VmTriBool::False => Self::Bool(false),
VmTriBool::Unknown => Self::Null,
}
}
#[inline]
pub(super) fn boolean(self) -> Result<VmTriBool, VmError> {
match self {
Self::Null => Ok(VmTriBool::Unknown),
Self::Bool(true) => Ok(VmTriBool::True),
Self::Bool(false) => Ok(VmTriBool::False),
_ => Err(VmError::TypeMismatch),
}
}
pub(super) fn owned<'b>(self) -> Result<Value<'b>, VmError> {
Ok(match self {
Self::Null => Value::Null,
Self::Bool(v) => Value::Bool(v),
Self::I64(v) => Value::I64(v),
Self::U64(v) => Value::U64(v),
Self::F32(v) => Value::F32(v),
Self::F64(v) => Value::F64(v),
Self::Decimal(v, p, s) => Value::Decimal(v, p, s),
Self::Str(_) => return Err(VmError::TypeMismatch),
})
}
pub(super) fn scalar(v: &'a ScalarValue) -> Result<Self, VmError> {
use ScalarValue as S;
if v.is_null() {
return Ok(Self::Null);
}
Ok(match v {
S::Boolean(Some(v)) => Self::Bool(*v),
S::Int8(Some(v)) => Self::I64((*v).into()),
S::Int16(Some(v)) => Self::I64((*v).into()),
S::Int32(Some(v))
| S::Date32(Some(v))
| S::Time32Second(Some(v))
| S::Time32Millisecond(Some(v)) => Self::I64((*v).into()),
S::Int64(Some(v))
| S::Date64(Some(v))
| S::Time64Microsecond(Some(v))
| S::Time64Nanosecond(Some(v))
| S::DurationSecond(Some(v))
| S::DurationMillisecond(Some(v))
| S::DurationMicrosecond(Some(v))
| S::DurationNanosecond(Some(v))
| S::TimestampSecond(Some(v), _)
| S::TimestampMillisecond(Some(v), _)
| S::TimestampMicrosecond(Some(v), _)
| S::TimestampNanosecond(Some(v), _) => Self::I64(*v),
S::UInt8(Some(v)) => Self::U64((*v).into()),
S::UInt16(Some(v)) => Self::U64((*v).into()),
S::UInt32(Some(v)) => Self::U64((*v).into()),
S::UInt64(Some(v)) => Self::U64(*v),
S::Float32(Some(v)) => Self::F32(*v),
S::Float64(Some(v)) => Self::F64(*v),
S::Decimal128(Some(v), p, s) => Self::Decimal(*v, *p, *s),
S::Utf8(Some(v)) | S::LargeUtf8(Some(v)) | S::Utf8View(Some(v)) => {
Self::Str(v)
}
_ => Self::I64(
crate::core::vm::temporal_scalar_to_bits(v)
.ok_or(VmError::TypeMismatch)? as i64,
),
})
}
#[inline]
pub(super) fn word(word: u64, ty: VmScalarType) -> Result<Self, VmError> {
use VmScalarType as T;
Ok(match ty {
T::Bool => Self::Bool(word != 0),
T::UInt8 => Self::U64(word as u8 as u64),
T::UInt16 => Self::U64(word as u16 as u64),
T::UInt32 => Self::U64(word as u32 as u64),
T::UInt64 => Self::U64(word),
T::Float32 => Self::F32(f32::from_bits(word as u32)),
T::Float64 => Self::F64(f64::from_bits(word)),
T::Int8 => Self::I64(word as i8 as i64),
T::Int16 => Self::I64(word as i16 as i64),
T::Int32 | T::Date32 | T::Time32(_) => Self::I64(word as i32 as i64),
T::Int64 | T::MetadataI64 => Self::I64(word as i64),
ty if ty.is_temporal() => Self::I64(word as i64),
_ => return Err(VmError::TypeMismatch),
})
}
pub(super) fn decimal(v: i128, p: u8, s: i8) -> Result<Self, VmError> {
let bound = 10_i128.checked_pow(p.into()).ok_or(VmError::Overflow)?;
if v <= -bound || v >= bound {
return Err(VmError::Overflow);
}
Ok(Self::Decimal(v, p, s))
}
#[inline]
pub(super) fn cast(self, target: VmScalarType) -> Result<Self, VmError> {
use VmScalarType as T;
Ok(match (self, target) {
(Self::Null, _) => Self::Null,
(Self::I64(v), T::Float64) => Self::F64(v as f64),
(Self::U64(v), T::Float64) => Self::F64(v as f64),
(Self::F32(v), T::Float32) => Self::F32(v),
(Self::F32(v), T::Float64) => Self::F64(f64::from(v)),
(Self::Decimal(v, _, s), T::Float64) => Self::F64(f64::from_bits(
crate::execution::storage::bound_columns::decode_decimal128_to_f64_bits(
v, s,
),
)),
(Self::F64(v), T::Decimal128 { precision, scale }) => {
let raw = datafusion::arrow::compute::float_to_decimal::<
datafusion::arrow::datatypes::Decimal128Type,
>(v, precision, scale)
.map_err(VmError::from)?;
Self::Decimal(raw, precision, scale)
}
(Self::Decimal(v, _, s), T::Decimal128 { precision, scale }) => {
let power = u32::try_from(i16::from(scale) - i16::from(s))
.map_err(|_| VmError::TypeMismatch)?;
let v = if v == 0 {
0
} else {
v.checked_mul(10_i128.checked_pow(power).ok_or(VmError::Overflow)?)
.ok_or(VmError::Overflow)?
};
Self::decimal(v, precision, scale)?
}
(Self::F32(_), _) | (_, T::Float32) => return Err(VmError::TypeMismatch),
(v, _) => v,
})
}
#[inline]
pub(super) fn unary(self, op: VmUnaryOp, ty: VmScalarType) -> Result<Self, VmError> {
Ok(match (self, op) {
(Self::Null | Self::Bool(false), VmUnaryOp::IsTrue) => Self::Bool(false),
(Self::Bool(true), VmUnaryOp::IsTrue) => Self::Bool(true),
(Self::Null, _) => Self::Null,
(Self::F64(v), VmUnaryOp::Abs) => Self::F64(v.abs()),
(Self::F64(v), _) => Self::F64(-v),
(Self::Decimal(v, p, s), VmUnaryOp::Abs) => {
Self::Decimal(v.wrapping_abs(), p, s)
}
(Self::Decimal(v, p, s), _) => {
Self::Decimal(v.checked_neg().ok_or(VmError::Overflow)?, p, s)
}
(Self::I64(v), VmUnaryOp::Abs) => {
let n = v.checked_abs().ok_or(VmError::Overflow)?;
Self::I64(check_signed_width(n, ty)?)
}
(Self::I64(v), _) => {
let n = if op == VmUnaryOp::CheckedNeg {
v.checked_neg().ok_or(VmError::Overflow)?
} else {
v.wrapping_neg()
};
let narrowed = match ty {
VmScalarType::Int8 => n as i8 as i64,
VmScalarType::Int16 => n as i16 as i64,
VmScalarType::Int32 => n as i32 as i64,
_ => n,
};
if op == VmUnaryOp::CheckedNeg && narrowed != n {
return Err(VmError::Overflow);
}
Self::I64(narrowed)
}
_ => return Err(VmError::TypeMismatch),
})
}
#[inline]
fn compare_order(self, rhs: Self) -> Result<std::cmp::Ordering, VmError> {
Ok(match (self, rhs) {
(Self::Bool(a), Self::Bool(b)) => a.cmp(&b),
(Self::I64(a), Self::I64(b)) => a.cmp(&b),
(Self::U64(a), Self::U64(b)) => a.cmp(&b),
(Self::Decimal(a, _, s), Self::Decimal(b, _, t)) if s == t => a.cmp(&b),
(Self::Str(a), Self::Str(b)) => a.cmp(b),
(Self::F32(a), Self::F32(b)) => {
let a = if a.to_bits() << 1 == 0 { 0.0 } else { a };
let b = if b.to_bits() << 1 == 0 { 0.0 } else { b };
a.total_cmp(&b)
}
(Self::F64(a), Self::F64(b)) => {
let a = if a.to_bits() << 1 == 0 { 0.0 } else { a };
let b = if b.to_bits() << 1 == 0 { 0.0 } else { b };
a.total_cmp(&b)
}
_ => return Err(VmError::TypeMismatch),
})
}
#[inline]
pub(super) fn binary(
self,
op: VmBinaryOp,
ty: VmScalarType,
rhs: Self,
) -> Result<Self, VmError> {
use VmBinaryOp as O;
if op == O::And {
return Ok(Self::truth(self.boolean()?.and(rhs.boolean()?)));
}
if op == O::Or {
return Ok(Self::truth(self.boolean()?.or(rhs.boolean()?)));
}
if matches!(op, O::IsDistinctFrom | O::IsNotDistinctFrom) {
let distinct = match (self, rhs) {
(Self::Null, Self::Null) => false,
(Self::Null, _) | (_, Self::Null) => true,
(lhs, rhs) => !lhs.compare_order(rhs)?.is_eq(),
};
return Ok(Self::Bool(if op == O::IsDistinctFrom {
distinct
} else {
!distinct
}));
}
if matches!(self, Self::Null) || matches!(rhs, Self::Null) {
return Ok(Self::Null);
}
if matches!(op, O::Eq | O::Ne | O::Lt | O::Le | O::Gt | O::Ge) {
let order = self.compare_order(rhs)?;
return Ok(Self::Bool(match op {
O::Eq => order.is_eq(),
O::Ne => !order.is_eq(),
O::Lt => order.is_lt(),
O::Le => !order.is_gt(),
O::Gt => order.is_gt(),
O::Ge => !order.is_lt(),
_ => unreachable!(),
}));
}
if matches!(op, O::AddInterval | O::SubInterval) {
let (Self::I64(a), Self::I64(b)) = (self, rhs) else {
return Err(VmError::TypeMismatch);
};
return eval_temporal_interval(a, b, op, ty).map(Self::I64);
}
macro_rules! checked {
($a:expr, $b:expr) => {
match op {
O::Add => $a.checked_add($b),
O::Sub => $a.checked_sub($b),
O::Mul => $a.checked_mul($b),
_ => return Err(VmError::TypeMismatch),
}
.ok_or(VmError::Overflow)?
};
}
macro_rules! wrapping {
($a:expr, $b:expr) => {
match op {
O::Add => $a.wrapping_add($b),
O::Sub => $a.wrapping_sub($b),
O::Mul => $a.wrapping_mul($b),
_ => return Err(VmError::TypeMismatch),
}
};
}
Ok(match (self, rhs) {
(Self::I64(a), Self::I64(b)) => Self::I64(match ty {
VmScalarType::Int8 => i64::from(wrapping!(a as i8, b as i8)),
VmScalarType::Int16 => i64::from(wrapping!(a as i16, b as i16)),
VmScalarType::Int32 => i64::from(wrapping!(a as i32, b as i32)),
VmScalarType::Int64 | VmScalarType::MetadataI64 => wrapping!(a, b),
_ => check_signed_width(checked!(a, b), ty)?,
}),
(Self::U64(a), Self::U64(b)) => Self::U64(match ty {
VmScalarType::UInt8 => u64::from(wrapping!(a as u8, b as u8)),
VmScalarType::UInt16 => u64::from(wrapping!(a as u16, b as u16)),
VmScalarType::UInt32 => u64::from(wrapping!(a as u32, b as u32)),
VmScalarType::UInt64 => wrapping!(a, b),
_ => return Err(VmError::TypeMismatch),
}),
(Self::F64(a), Self::F64(b)) => Self::F64(match op {
O::Add => a + b,
O::Sub => a - b,
O::Mul => a * b,
_ => return Err(VmError::TypeMismatch),
}),
(Self::Decimal(a, _, s), Self::Decimal(b, _, t)) => {
let VmScalarType::Decimal128 { precision, scale } = ty else {
return Err(VmError::TypeMismatch);
};
let (lhs, rhs) = if op == O::Mul {
if i16::from(scale) != i16::from(s) + i16::from(t) {
return Err(VmError::TypeMismatch);
}
(a, b)
} else {
if scale != s.max(t) {
return Err(VmError::TypeMismatch);
}
(rescale_decimal(a, s, scale)?, rescale_decimal(b, t, scale)?)
};
Self::Decimal(checked!(lhs, rhs), precision, scale)
}
_ => return Err(VmError::TypeMismatch),
})
}
}
fn rescale_decimal(value: i128, from_scale: i8, to_scale: i8) -> Result<i128, VmError> {
if from_scale == to_scale {
return Ok(value);
}
let diff = u32::try_from(i16::from(to_scale) - i16::from(from_scale))
.map_err(|_| VmError::TypeMismatch)?;
let factor = 10_i128.checked_pow(diff).ok_or(VmError::Overflow)?;
value.checked_mul(factor).ok_or(VmError::Overflow)
}
fn check_signed_width(value: i64, ty: VmScalarType) -> Result<i64, VmError> {
match ty {
VmScalarType::Int8 => i8::try_from(value).map(i64::from),
VmScalarType::Int16 => i16::try_from(value).map(i64::from),
VmScalarType::Int32 | VmScalarType::Date32 => i32::try_from(value).map(i64::from),
_ => Ok(value),
}
.map_err(|_| VmError::Overflow)
}
const SAFE_CALENDAR_DAYS: i64 = 90_000_000;
#[inline]
fn eval_temporal_interval(
a: i64,
b: i64,
op: VmBinaryOp,
ty: VmScalarType,
) -> Result<i64, VmError> {
use datafusion::arrow::temporal_conversions::{
MICROSECONDS_IN_DAY, MILLISECONDS_IN_DAY, SECONDS_IN_DAY,
};
let res = match op {
VmBinaryOp::AddInterval => a.checked_add(b),
VmBinaryOp::SubInterval => a.checked_sub(b),
_ => return Err(VmError::TypeMismatch),
}
.ok_or(VmError::Overflow)?;
let safe_limit = match ty {
VmScalarType::Date32 => SAFE_CALENDAR_DAYS,
VmScalarType::Date64 => {
let safe = SAFE_CALENDAR_DAYS * MILLISECONDS_IN_DAY;
if a % MILLISECONDS_IN_DAY == 0
&& (-safe..=safe).contains(&a)
&& (-safe..=safe).contains(&res)
{
return Ok(res);
}
return eval_temporal_interval_cold(a, b, res, op, ty);
}
VmScalarType::Timestamp {
unit: TimeUnit::Second,
timezone_aware: false,
} => SAFE_CALENDAR_DAYS * SECONDS_IN_DAY,
VmScalarType::Timestamp {
unit: TimeUnit::Millisecond,
timezone_aware: false,
} => SAFE_CALENDAR_DAYS * MILLISECONDS_IN_DAY,
VmScalarType::Timestamp {
unit: TimeUnit::Microsecond,
timezone_aware: false,
} => SAFE_CALENDAR_DAYS * MICROSECONDS_IN_DAY,
VmScalarType::Timestamp {
unit: TimeUnit::Nanosecond,
timezone_aware: false,
} => return Ok(res),
_ => return Err(VmError::TypeMismatch),
};
if (-safe_limit..=safe_limit).contains(&a)
&& (-safe_limit..=safe_limit).contains(&res)
{
return Ok(res);
}
eval_temporal_interval_cold(a, b, res, op, ty)
}
#[cold]
fn eval_temporal_interval_cold(
a: i64,
b: i64,
res: i64,
op: VmBinaryOp,
ty: VmScalarType,
) -> Result<i64, VmError> {
use datafusion::arrow::datatypes::{Date32Type, Date64Type, IntervalDayTime};
use datafusion::arrow::temporal_conversions::{
MILLISECONDS_IN_DAY, timestamp_ms_to_datetime, timestamp_s_to_datetime,
timestamp_us_to_datetime,
};
match ty {
VmScalarType::Date32 => {
let valid = |d: i64| {
i32::try_from(d)
.ok()
.and_then(Date32Type::to_naive_date_opt)
.is_some()
};
(valid(a) && valid(res))
.then_some(res)
.ok_or(VmError::Overflow)
}
VmScalarType::Date64 => {
let days =
i32::try_from(b / MILLISECONDS_IN_DAY).map_err(|_| VmError::Overflow)?;
let iv = IntervalDayTime::new(days, 0);
match op {
VmBinaryOp::AddInterval => Date64Type::add_day_time_opt(a, iv),
VmBinaryOp::SubInterval => Date64Type::subtract_day_time_opt(a, iv),
_ => None,
}
.ok_or(VmError::Overflow)
}
VmScalarType::Timestamp {
unit: TimeUnit::Second,
timezone_aware: false,
} => (timestamp_s_to_datetime(a).is_some()
&& timestamp_s_to_datetime(res).is_some())
.then_some(res)
.ok_or(VmError::Overflow),
VmScalarType::Timestamp {
unit: TimeUnit::Millisecond,
timezone_aware: false,
} => (timestamp_ms_to_datetime(a).is_some()
&& timestamp_ms_to_datetime(res).is_some())
.then_some(res)
.ok_or(VmError::Overflow),
VmScalarType::Timestamp {
unit: TimeUnit::Microsecond,
timezone_aware: false,
} => (timestamp_us_to_datetime(a).is_some()
&& timestamp_us_to_datetime(res).is_some())
.then_some(res)
.ok_or(VmError::Overflow),
_ => Err(VmError::TypeMismatch),
}
}