tank_core/
value.rs

1use crate::{AsValue, Error, Result, interval::Interval};
2use proc_macro2::TokenStream;
3use quote::{ToTokens, quote};
4use rust_decimal::Decimal;
5use std::{collections::HashMap, hash::Hash, mem::discriminant};
6use time::{Date, OffsetDateTime, PrimitiveDateTime, Time};
7use uuid::Uuid;
8
9#[derive(Default, Debug, Clone)]
10pub enum Value {
11    #[default]
12    Null,
13    Boolean(Option<bool>),
14    Int8(Option<i8>),
15    Int16(Option<i16>),
16    Int32(Option<i32>),
17    Int64(Option<i64>),
18    Int128(Option<i128>),
19    UInt8(Option<u8>),
20    UInt16(Option<u16>),
21    UInt32(Option<u32>),
22    UInt64(Option<u64>),
23    UInt128(Option<u128>),
24    Float32(Option<f32>),
25    Float64(Option<f64>),
26    Decimal(Option<Decimal>, /* width: */ u8, /* scale: */ u8),
27    Char(Option<char>),
28    Varchar(Option<String>),
29    Blob(Option<Box<[u8]>>),
30    Date(Option<Date>),
31    Time(Option<Time>),
32    Timestamp(Option<PrimitiveDateTime>),
33    TimestampWithTimezone(Option<OffsetDateTime>),
34    Interval(Option<Interval>),
35    Uuid(Option<Uuid>),
36    Array(
37        Option<Box<[Value]>>,
38        /* type: */ Box<Value>,
39        /* len: */ u32,
40    ),
41    List(Option<Vec<Value>>, /* type: */ Box<Value>),
42    Map(
43        Option<HashMap<Value, Value>>,
44        /* key: */ Box<Value>,
45        /* value: */ Box<Value>,
46    ),
47    Struct(
48        Option<Vec<(String, Value)>>,
49        /* type: */ Vec<(String, Value)>,
50    ),
51    Unknown(Option<String>),
52}
53
54impl Value {
55    pub fn same_type(&self, other: &Self) -> bool {
56        match (self, other) {
57            (Self::Decimal(.., l_width, l_scale), Self::Decimal(.., r_width, r_scale)) => {
58                (*l_width == 0 || *r_width == 0 || l_width == r_width)
59                    && (*l_scale == 0 || *r_scale == 0 || l_scale == r_scale)
60            }
61            (Self::Array(.., l_type, l_len), Self::Array(.., r_type, r_len)) => {
62                l_len == r_len && l_type.same_type(&r_type)
63            }
64            (Self::List(.., l), Self::List(.., r)) => l.same_type(r),
65            (Self::Map(.., l_key, l_value), Self::Map(.., r_key, r_value)) => {
66                l_key.same_type(r_key) && l_value.same_type(&r_value)
67            }
68            _ => discriminant(self) == discriminant(other),
69        }
70    }
71
72    pub fn is_null(&self) -> bool {
73        match self {
74            Value::Null
75            | Value::Boolean(None, ..)
76            | Value::Int8(None, ..)
77            | Value::Int16(None, ..)
78            | Value::Int32(None, ..)
79            | Value::Int64(None, ..)
80            | Value::Int128(None, ..)
81            | Value::UInt8(None, ..)
82            | Value::UInt16(None, ..)
83            | Value::UInt32(None, ..)
84            | Value::UInt64(None, ..)
85            | Value::UInt128(None, ..)
86            | Value::Float32(None, ..)
87            | Value::Float64(None, ..)
88            | Value::Decimal(None, ..)
89            | Value::Char(None, ..)
90            | Value::Varchar(None, ..)
91            | Value::Blob(None, ..)
92            | Value::Date(None, ..)
93            | Value::Time(None, ..)
94            | Value::Timestamp(None, ..)
95            | Value::TimestampWithTimezone(None, ..)
96            | Value::Interval(None, ..)
97            | Value::Uuid(None, ..)
98            | Value::Array(None, ..)
99            | Value::List(None, ..)
100            | Value::Map(None, ..)
101            | Value::Struct(None, ..)
102            | Value::Unknown(None, ..) => true,
103            _ => false,
104        }
105    }
106
107    pub fn as_null(&self) -> Value {
108        match self {
109            Value::Null => Value::Null,
110            Value::Boolean(..) => Value::Boolean(None),
111            Value::Int8(..) => Value::Int8(None),
112            Value::Int16(..) => Value::Int16(None),
113            Value::Int32(..) => Value::Int32(None),
114            Value::Int64(..) => Value::Int64(None),
115            Value::Int128(..) => Value::Int128(None),
116            Value::UInt8(..) => Value::UInt8(None),
117            Value::UInt16(..) => Value::UInt16(None),
118            Value::UInt32(..) => Value::UInt32(None),
119            Value::UInt64(..) => Value::UInt64(None),
120            Value::UInt128(..) => Value::UInt128(None),
121            Value::Float32(..) => Value::Float32(None),
122            Value::Float64(..) => Value::Float64(None),
123            Value::Decimal(.., w, s) => Value::Decimal(None, *w, *s),
124            Value::Char(..) => Value::Char(None),
125            Value::Varchar(..) => Value::Varchar(None),
126            Value::Blob(..) => Value::Blob(None),
127            Value::Date(..) => Value::Date(None),
128            Value::Time(..) => Value::Time(None),
129            Value::Timestamp(..) => Value::Timestamp(None),
130            Value::TimestampWithTimezone(..) => Value::TimestampWithTimezone(None),
131            Value::Interval(..) => Value::Interval(None),
132            Value::Uuid(..) => Value::Uuid(None),
133            Value::Array(.., t, len) => Value::Array(None, t.clone(), *len),
134            Value::List(.., t) => Value::List(None, t.clone()),
135            Value::Map(.., k, v) => Value::Map(None, k.clone(), v.clone()),
136            Value::Struct(.., t) => Value::Struct(None, t.clone()),
137            Value::Unknown(..) => Value::Unknown(None),
138        }
139    }
140
141    pub fn try_as(self, value: &Value) -> Result<Value> {
142        if self.same_type(value) {
143            return Ok(self);
144        }
145        match value {
146            Value::Boolean(..) => bool::try_from_value(self).map(AsValue::as_value),
147            Value::Int8(..) => i8::try_from_value(self).map(AsValue::as_value),
148            Value::Int16(..) => i16::try_from_value(self).map(AsValue::as_value),
149            Value::Int32(..) => i32::try_from_value(self).map(AsValue::as_value),
150            Value::Int64(..) => i64::try_from_value(self).map(AsValue::as_value),
151            Value::Int128(..) => i128::try_from_value(self).map(AsValue::as_value),
152            Value::UInt8(..) => u8::try_from_value(self).map(AsValue::as_value),
153            Value::UInt16(..) => u16::try_from_value(self).map(AsValue::as_value),
154            Value::UInt32(..) => u32::try_from_value(self).map(AsValue::as_value),
155            Value::UInt64(..) => u64::try_from_value(self).map(AsValue::as_value),
156            Value::UInt128(..) => u128::try_from_value(self).map(AsValue::as_value),
157            Value::Float32(..) => f32::try_from_value(self).map(AsValue::as_value),
158            Value::Float64(..) => f64::try_from_value(self).map(AsValue::as_value),
159            Value::Decimal(..) => Decimal::try_from_value(self).map(AsValue::as_value),
160            Value::Char(..) => char::try_from_value(self).map(AsValue::as_value),
161            Value::Varchar(..) => String::try_from_value(self).map(AsValue::as_value),
162            Value::Blob(..) => Box::<[u8]>::try_from_value(self).map(AsValue::as_value),
163            Value::Date(..) => Date::try_from_value(self).map(AsValue::as_value),
164            Value::Time(..) => Time::try_from_value(self).map(AsValue::as_value),
165            Value::Timestamp(..) => PrimitiveDateTime::try_from_value(self).map(AsValue::as_value),
166            Value::TimestampWithTimezone(..) => {
167                OffsetDateTime::try_from_value(self).map(AsValue::as_value)
168            }
169            Value::Interval(..) => Interval::try_from_value(self).map(AsValue::as_value),
170            Value::Uuid(..) => Uuid::try_from_value(self).map(AsValue::as_value),
171            // Value::Array(.., ty, len) => {
172            //     Box::<[Value]>::try_from_value(self).map(AsValue::as_value)
173            // }
174            // Value::List(..) => Box::<[Value]>::try_from_value(self).map(AsValue::as_value),
175            // Value::Map(..) => Date::try_from_value(self).map(AsValue::as_value),
176            _ => {
177                return Err(Error::msg(format!(
178                    "Cannot convert value {:?} into value {:?}",
179                    self, value
180                )));
181            }
182        }
183    }
184}
185
186impl PartialEq for Value {
187    fn eq(&self, other: &Self) -> bool {
188        match (self, other) {
189            (Self::Null, Self::Null) => true,
190            (Self::Boolean(l), Self::Boolean(r)) => l == r,
191            (Self::Int8(l), Self::Int8(r)) => l == r,
192            (Self::Int16(l), Self::Int16(r)) => l == r,
193            (Self::Int32(l), Self::Int32(r)) => l == r,
194            (Self::Int64(l), Self::Int64(r)) => l == r,
195            (Self::Int128(l), Self::Int128(r)) => l == r,
196            (Self::UInt8(l), Self::UInt8(r)) => l == r,
197            (Self::UInt16(l), Self::UInt16(r)) => l == r,
198            (Self::UInt32(l), Self::UInt32(r)) => l == r,
199            (Self::UInt64(l), Self::UInt64(r)) => l == r,
200            (Self::UInt128(l), Self::UInt128(r)) => l == r,
201            (Self::Float32(l), Self::Float32(r)) => {
202                l == r
203                    || l.and_then(|l| r.and_then(|r| Some(l.is_nan() && r.is_nan())))
204                        .unwrap_or_default()
205            }
206            (Self::Float64(l), Self::Float64(r)) => {
207                l == r
208                    || l.and_then(|l| r.and_then(|r| Some(l.is_nan() && r.is_nan())))
209                        .unwrap_or_default()
210            }
211            (Self::Decimal(l, l_width, l_scale), Self::Decimal(r, r_width, r_scale)) => {
212                l == r && l_width == r_width && l_scale == r_scale
213            }
214            (Self::Char(l), Self::Char(r)) => l == r,
215            (Self::Varchar(l), Self::Varchar(r)) => l == r,
216            (Self::Blob(l), Self::Blob(r)) => l == r,
217            (Self::Date(l), Self::Date(r)) => l == r,
218            (Self::Time(l), Self::Time(r)) => l == r,
219            (Self::Timestamp(l), Self::Timestamp(r)) => l == r,
220            (Self::TimestampWithTimezone(l), Self::TimestampWithTimezone(r)) => l == r,
221            (Self::Interval(l), Self::Interval(r)) => l == r,
222            (Self::Uuid(l), Self::Uuid(r)) => l == r,
223            (Self::Array(l, ..), Self::Array(r, ..)) => l == r && self.same_type(other),
224            (Self::List(l, ..), Self::List(r, ..)) => l == r && self.same_type(other),
225            (Self::Map(None, ..), Self::Map(None, ..)) => self.same_type(other),
226            (Self::Map(Some(l), ..), Self::Map(Some(r), ..)) => {
227                l.is_empty() == r.is_empty() && self.same_type(other)
228            }
229            (Self::Map(..), Self::Map(..)) => self.same_type(other),
230            (Self::Unknown(..), Self::Unknown(..)) => false,
231            _ => false,
232        }
233    }
234}
235
236impl Eq for Value {}
237
238impl Hash for Value {
239    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
240        use Value::*;
241        discriminant(self).hash(state);
242        match self {
243            Null => {}
244            Boolean(v) => v.hash(state),
245            Int8(v) => v.hash(state),
246            Int16(v) => v.hash(state),
247            Int32(v) => v.hash(state),
248            Int64(v) => v.hash(state),
249            Int128(v) => v.hash(state),
250
251            UInt8(v) => v.hash(state),
252            UInt16(v) => v.hash(state),
253            UInt32(v) => v.hash(state),
254            UInt64(v) => v.hash(state),
255            UInt128(v) => v.hash(state),
256            Float32(Some(v)) => {
257                v.to_bits().hash(state);
258            }
259            Float32(None) => None::<u32>.hash(state),
260            Float64(Some(v)) => {
261                v.to_bits().hash(state);
262            }
263            Float64(None) => None::<u64>.hash(state),
264            Decimal(v, width, scale) => {
265                v.hash(state);
266                width.hash(state);
267                scale.hash(state);
268            }
269            Char(v) => v.hash(state),
270            Varchar(v) => v.hash(state),
271            Blob(v) => v.hash(state),
272            Date(v) => v.hash(state),
273            Time(v) => v.hash(state),
274            Timestamp(v) => v.hash(state),
275            TimestampWithTimezone(v) => v.hash(state),
276            Interval(v) => v.hash(state),
277            Uuid(v) => v.hash(state),
278            Array(v, typ, len) => {
279                v.hash(state);
280                typ.hash(state);
281                len.hash(state);
282            }
283            List(v, typ) => {
284                v.hash(state);
285                typ.hash(state);
286            }
287            Map(v, key, val) => {
288                match v {
289                    Some(map) => {
290                        for (key, val) in map {
291                            key.hash(state);
292                            val.hash(state);
293                        }
294                    }
295                    None => {}
296                }
297                key.hash(state);
298                val.hash(state);
299            }
300            Struct(v, t) => {
301                match v {
302                    Some(v) => v.hash(state),
303                    None => {}
304                }
305                t.hash(state);
306            }
307            Unknown(v) => v.hash(state),
308        }
309    }
310}
311
312#[derive(Default)]
313pub struct TypeDecoded {
314    pub value: Value,
315    pub nullable: bool,
316    pub passive: bool,
317}
318
319pub type CheckPassive = Box<dyn Fn(TokenStream) -> TokenStream>;
320
321impl ToTokens for Value {
322    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
323        let ts = match self {
324            Value::Null => quote!(::tank::Value::Null),
325            Value::Boolean(..) => quote!(::tank::Value::Boolean(None)),
326            Value::Int8(..) => quote!(::tank::Value::Int8(None)),
327            Value::Int16(..) => quote!(::tank::Value::Int16(None)),
328            Value::Int32(..) => quote!(::tank::Value::Int32(None)),
329            Value::Int64(..) => quote!(::tank::Value::Int64(None)),
330            Value::Int128(..) => quote!(::tank::Value::Int128(None)),
331            Value::UInt8(..) => quote!(::tank::Value::UInt8(None)),
332            Value::UInt16(..) => quote!(::tank::Value::UInt16(None)),
333            Value::UInt32(..) => quote!(::tank::Value::UInt32(None)),
334            Value::UInt64(..) => quote!(::tank::Value::UInt64(None)),
335            Value::UInt128(..) => quote!(::tank::Value::UInt128(None)),
336            Value::Float32(..) => quote!(::tank::Value::Float32(None)),
337            Value::Float64(..) => quote!(::tank::Value::Float64(None)),
338            Value::Decimal(.., width, scale) => {
339                quote!(::tank::Value::Decimal(None, #width, #scale))
340            }
341            Value::Char(..) => quote!(tank::Value::Char(None)),
342            Value::Varchar(..) => quote!(::tank::Value::Varchar(None)),
343            Value::Blob(..) => quote!(::tank::Value::Blob(None)),
344            Value::Date(..) => quote!(::tank::Value::Date(None)),
345            Value::Time(..) => quote!(::tank::Value::Time(None)),
346            Value::Timestamp(..) => quote!(::tank::Value::Timestamp(None)),
347            Value::TimestampWithTimezone(..) => quote!(::tank::Value::TimestampWithTimezone(None)),
348            Value::Interval(..) => quote!(::tank::Value::Interval(None)),
349            Value::Uuid(..) => quote!(::tank::Value::Uuid(None)),
350            Value::Array(.., inner, size) => {
351                quote!(::tank::Value::Array(None, Box::new(#inner), #size))
352            }
353            Value::List(.., inner) => {
354                let inner = inner.as_ref().to_token_stream();
355                quote!(::tank::Value::List(None, Box::new(#inner)))
356            }
357            Value::Map(.., key, value) => {
358                let key = key.as_ref().to_token_stream();
359                let value = value.as_ref().to_token_stream();
360                quote!(::tank::Value::Map(None, Box::new(#key), Box::new(#value)))
361            }
362            Value::Struct(.., t) => {
363                let values = t.into_iter().map(|(k, v)| quote!((#k.into(), #v)));
364                quote!(::tank::Value::Struct(None, vec!(#(#values),*)))
365            }
366            Value::Unknown(..) => quote!(::tank::Value::Unknown(None)),
367        };
368        tokens.extend(ts);
369    }
370}