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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use std::fmt::{Display, Write};
use std::sync::Arc;

use vortex_buffer::{Buffer, BufferString};
use vortex_dtype::DType;
use vortex_error::{vortex_err, VortexResult};

use crate::pvalue::PValue;

/// Represents the internal data of a scalar value. Must be interpreted by wrapping
/// up with a DType to make a Scalar.
///
/// Note that these values can be deserialized from JSON or other formats. So a PValue may not
/// have the correct width for what the DType expects. Primitive values should therefore be
/// read using [crate::PrimitiveScalar] which will handle the conversion.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ScalarValue(pub(crate) InnerScalarValue);

#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub(crate) enum InnerScalarValue {
    Bool(bool),
    Primitive(PValue),
    Buffer(Buffer),
    BufferString(BufferString),
    List(Arc<[ScalarValue]>),
    // It's significant that Null is last in this list. As a result generated PartialOrd sorts Scalar
    // values such that Nulls are last (greatest)
    Null,
}

fn to_hex(slice: &[u8]) -> Result<String, std::fmt::Error> {
    let mut output = String::new();
    for byte in slice {
        write!(output, "{:02x}", byte)?;
    }
    Ok(output)
}

impl Display for ScalarValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Display for InnerScalarValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bool(b) => write!(f, "{}", b),
            Self::Primitive(pvalue) => write!(f, "{}", pvalue),
            Self::Buffer(buf) => {
                if buf.len() > 10 {
                    write!(
                        f,
                        "{}..{}",
                        to_hex(&buf[0..5])?,
                        to_hex(&buf[buf.len() - 5..buf.len()])?,
                    )
                } else {
                    write!(f, "{}", to_hex(buf.as_slice())?)
                }
            }
            Self::BufferString(bufstr) => {
                if bufstr.len() > 10 {
                    write!(
                        f,
                        "{}..{}",
                        &bufstr.as_str()[0..5],
                        &bufstr.as_str()[bufstr.len() - 5..bufstr.len()],
                    )
                } else {
                    write!(f, "{}", bufstr.as_str())
                }
            }
            Self::List(_) => todo!(),
            Self::Null => write!(f, "null"),
        }
    }
}

impl ScalarValue {
    pub(crate) fn is_null(&self) -> bool {
        self.0.is_null()
    }

    pub fn is_instance_of(&self, dtype: &DType) -> bool {
        self.0.is_instance_of(dtype)
    }

    pub(crate) fn as_null(&self) -> VortexResult<()> {
        self.0.as_null()
    }

    pub(crate) fn as_bool(&self) -> VortexResult<Option<bool>> {
        self.0.as_bool()
    }

    /// FIXME(ngates): PValues are such a footgun... we should probably remove this.
    ///  But the other accessors can sometimes be useful? e.g. as_buffer. But maybe we just force
    ///  the user to switch over Utf8 and Binary and use the correct Scalar wrapper?
    pub(crate) fn as_pvalue(&self) -> VortexResult<Option<PValue>> {
        self.0.as_pvalue()
    }

    pub(crate) fn as_buffer(&self) -> VortexResult<Option<Buffer>> {
        self.0.as_buffer()
    }

    pub(crate) fn as_buffer_string(&self) -> VortexResult<Option<BufferString>> {
        self.0.as_buffer_string()
    }

    pub(crate) fn as_list(&self) -> VortexResult<Option<&Arc<[ScalarValue]>>> {
        self.0.as_list()
    }
}

impl InnerScalarValue {
    pub(crate) fn is_null(&self) -> bool {
        matches!(self, InnerScalarValue::Null)
    }

    pub fn is_instance_of(&self, dtype: &DType) -> bool {
        match (&self, dtype) {
            (InnerScalarValue::Bool(_), DType::Bool(_)) => true,
            (InnerScalarValue::Primitive(pvalue), DType::Primitive(ptype, _)) => {
                pvalue.is_instance_of(ptype)
            }
            (InnerScalarValue::Buffer(_), DType::Binary(_)) => true,
            (InnerScalarValue::BufferString(_), DType::Utf8(_)) => true,
            (InnerScalarValue::List(values), DType::List(dtype, _)) => {
                values.iter().all(|v| v.is_instance_of(dtype))
            }
            (InnerScalarValue::List(values), DType::Struct(structdt, _)) => values
                .iter()
                .zip(structdt.dtypes().to_vec())
                .all(|(v, dt)| v.is_instance_of(&dt)),
            (InnerScalarValue::Null, dtype) => dtype.is_nullable(),
            (_, DType::Extension(ext_dtype)) => self.is_instance_of(ext_dtype.storage_dtype()),
            _ => false,
        }
    }

    pub(crate) fn as_null(&self) -> VortexResult<()> {
        match self {
            InnerScalarValue::Null => Ok(()),
            _ => Err(vortex_err!("Expected a Null scalar, found {:?}", self)),
        }
    }

    pub(crate) fn as_bool(&self) -> VortexResult<Option<bool>> {
        match &self {
            InnerScalarValue::Null => Ok(None),
            InnerScalarValue::Bool(b) => Ok(Some(*b)),
            _ => Err(vortex_err!("Expected a bool scalar, found {:?}", self)),
        }
    }

    /// FIXME(ngates): PValues are such a footgun... we should probably remove this.
    ///  But the other accessors can sometimes be useful? e.g. as_buffer. But maybe we just force
    ///  the user to switch over Utf8 and Binary and use the correct Scalar wrapper?
    pub(crate) fn as_pvalue(&self) -> VortexResult<Option<PValue>> {
        match &self {
            InnerScalarValue::Null => Ok(None),
            InnerScalarValue::Primitive(p) => Ok(Some(*p)),
            _ => Err(vortex_err!("Expected a primitive scalar, found {:?}", self)),
        }
    }

    pub(crate) fn as_buffer(&self) -> VortexResult<Option<Buffer>> {
        match &self {
            InnerScalarValue::Null => Ok(None),
            InnerScalarValue::Buffer(b) => Ok(Some(b.clone())),
            _ => Err(vortex_err!("Expected a binary scalar, found {:?}", self)),
        }
    }

    pub(crate) fn as_buffer_string(&self) -> VortexResult<Option<BufferString>> {
        match &self {
            InnerScalarValue::Null => Ok(None),
            InnerScalarValue::Buffer(b) => Ok(Some(BufferString::try_from(b.clone())?)),
            InnerScalarValue::BufferString(b) => Ok(Some(b.clone())),
            _ => Err(vortex_err!("Expected a string scalar, found {:?}", self)),
        }
    }

    pub(crate) fn as_list(&self) -> VortexResult<Option<&Arc<[ScalarValue]>>> {
        match &self {
            InnerScalarValue::Null => Ok(None),
            InnerScalarValue::List(l) => Ok(Some(l)),
            _ => Err(vortex_err!("Expected a list scalar, found {:?}", self)),
        }
    }
}

#[cfg(test)]
mod test {
    use vortex_dtype::{DType, Nullability, PType, StructDType};

    use crate::{InnerScalarValue, PValue, ScalarValue};

    #[test]
    pub fn test_is_instance_of_bool() {
        assert!(ScalarValue(InnerScalarValue::Bool(true))
            .is_instance_of(&DType::Bool(Nullability::Nullable)));
        assert!(ScalarValue(InnerScalarValue::Bool(true))
            .is_instance_of(&DType::Bool(Nullability::NonNullable)));
        assert!(ScalarValue(InnerScalarValue::Bool(false))
            .is_instance_of(&DType::Bool(Nullability::Nullable)));
        assert!(ScalarValue(InnerScalarValue::Bool(false))
            .is_instance_of(&DType::Bool(Nullability::NonNullable)));
    }

    #[test]
    pub fn test_is_instance_of_primitive() {
        assert!(ScalarValue(InnerScalarValue::Primitive(PValue::F64(0.0)))
            .is_instance_of(&DType::Primitive(PType::F64, Nullability::NonNullable)));
    }

    #[test]
    pub fn test_is_instance_of_list_and_struct() {
        let tbool = DType::Bool(Nullability::NonNullable);
        let tboolnull = DType::Bool(Nullability::Nullable);
        let tnull = DType::Null;

        let bool_null = ScalarValue(InnerScalarValue::List(
            vec![
                ScalarValue(InnerScalarValue::Bool(true)),
                ScalarValue(InnerScalarValue::Null),
            ]
            .into(),
        ));
        let bool_bool = ScalarValue(InnerScalarValue::List(
            vec![
                ScalarValue(InnerScalarValue::Bool(true)),
                ScalarValue(InnerScalarValue::Bool(false)),
            ]
            .into(),
        ));

        fn tlist(element: &DType) -> DType {
            DType::List(element.clone().into(), Nullability::NonNullable)
        }

        assert!(bool_null.is_instance_of(&tlist(&tboolnull)));
        assert!(!bool_null.is_instance_of(&tlist(&tbool)));
        assert!(bool_bool.is_instance_of(&tlist(&tbool)));
        assert!(bool_bool.is_instance_of(&tlist(&tbool)));

        fn tstruct(left: &DType, right: &DType) -> DType {
            DType::Struct(
                StructDType::new(
                    vec!["left".into(), "right".into()].into(),
                    vec![left.clone(), right.clone()],
                ),
                Nullability::NonNullable,
            )
        }

        assert!(bool_null.is_instance_of(&tstruct(&tboolnull, &tboolnull)));
        assert!(bool_null.is_instance_of(&tstruct(&tbool, &tboolnull)));
        assert!(!bool_null.is_instance_of(&tstruct(&tboolnull, &tbool)));
        assert!(!bool_null.is_instance_of(&tstruct(&tbool, &tbool)));

        assert!(bool_null.is_instance_of(&tstruct(&tbool, &tnull)));
        assert!(!bool_null.is_instance_of(&tstruct(&tnull, &tbool)));

        assert!(bool_bool.is_instance_of(&tstruct(&tboolnull, &tboolnull)));
        assert!(bool_bool.is_instance_of(&tstruct(&tbool, &tboolnull)));
        assert!(bool_bool.is_instance_of(&tstruct(&tboolnull, &tbool)));
        assert!(bool_bool.is_instance_of(&tstruct(&tbool, &tbool)));

        assert!(!bool_bool.is_instance_of(&tstruct(&tbool, &tnull)));
        assert!(!bool_bool.is_instance_of(&tstruct(&tnull, &tbool)));
    }

    #[test]
    pub fn test_is_instance_of_null() {
        assert!(
            ScalarValue(InnerScalarValue::Null).is_instance_of(&DType::Bool(Nullability::Nullable))
        );
        assert!(!ScalarValue(InnerScalarValue::Null)
            .is_instance_of(&DType::Bool(Nullability::NonNullable)));

        assert!(ScalarValue(InnerScalarValue::Null)
            .is_instance_of(&DType::Primitive(PType::U8, Nullability::Nullable)));
        assert!(
            ScalarValue(InnerScalarValue::Null).is_instance_of(&DType::Utf8(Nullability::Nullable))
        );
        assert!(ScalarValue(InnerScalarValue::Null)
            .is_instance_of(&DType::Binary(Nullability::Nullable)));
        assert!(
            ScalarValue(InnerScalarValue::Null).is_instance_of(&DType::Struct(
                StructDType::new([].into(), [].into()),
                Nullability::Nullable,
            ))
        );
        assert!(
            ScalarValue(InnerScalarValue::Null).is_instance_of(&DType::List(
                DType::Utf8(Nullability::NonNullable).into(),
                Nullability::Nullable
            ))
        );
        assert!(ScalarValue(InnerScalarValue::Null).is_instance_of(&DType::Null));
    }
}