1use std::sync::Arc;
7
8use vortex_buffer::BufferString;
9use vortex_buffer::ByteBuffer;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure_eq;
14use vortex_error::vortex_err;
15use vortex_error::vortex_panic;
16
17use crate::dtype::DType;
18use crate::dtype::DecimalDType;
19use crate::dtype::NativePType;
20use crate::dtype::Nullability;
21use crate::dtype::PType;
22use crate::dtype::UnionVariants;
23use crate::dtype::extension::ExtDType;
24use crate::dtype::extension::ExtDTypeRef;
25use crate::dtype::extension::ExtVTable;
26use crate::scalar::DecimalValue;
27use crate::scalar::PValue;
28use crate::scalar::Scalar;
29use crate::scalar::ScalarValue;
30use crate::scalar::UnionValue;
31
32impl Scalar {
34 pub fn bool(value: bool, nullability: Nullability) -> Self {
36 unsafe { Self::new_unchecked(DType::Bool(nullability), Some(ScalarValue::Bool(value))) }
38 }
39
40 pub fn primitive<T: NativePType + Into<PValue>>(value: T, nullability: Nullability) -> Self {
42 Self::primitive_value(value.into(), T::PTYPE, nullability)
43 }
44
45 pub fn primitive_value(value: PValue, ptype: PType, nullability: Nullability) -> Self {
50 if value.ptype() != ptype {
51 return Self::try_new(
52 DType::Primitive(ptype, nullability),
53 Some(ScalarValue::Primitive(value)),
54 )
55 .vortex_expect("unable to construct a primitive `Scalar`");
56 }
57
58 unsafe {
60 Self::new_unchecked(
61 DType::Primitive(ptype, nullability),
62 Some(ScalarValue::Primitive(value)),
63 )
64 }
65 }
66
67 pub fn decimal(
74 value: DecimalValue,
75 decimal_type: DecimalDType,
76 nullability: Nullability,
77 ) -> Self {
78 Self::try_decimal(value, decimal_type, nullability)
79 .vortex_expect("decimal value must fit the precision of `decimal_type`")
80 }
81
82 pub fn try_decimal(
89 value: DecimalValue,
90 decimal_type: DecimalDType,
91 nullability: Nullability,
92 ) -> VortexResult<Self> {
93 Self::try_new(
94 DType::Decimal(decimal_type, nullability),
95 Some(ScalarValue::Decimal(value)),
96 )
97 }
98
99 pub fn utf8<B>(str: B, nullability: Nullability) -> Self
105 where
106 B: Into<BufferString>,
107 {
108 Self::try_utf8(str, nullability).unwrap()
109 }
110
111 pub fn try_utf8<B>(
117 str: B,
118 nullability: Nullability,
119 ) -> Result<Self, <B as TryInto<BufferString>>::Error>
120 where
121 B: TryInto<BufferString>,
122 {
123 let value = ScalarValue::Utf8(str.try_into()?);
124
125 Ok(unsafe { Self::new_unchecked(DType::Utf8(nullability), Some(value)) })
127 }
128
129 pub fn binary(buffer: impl Into<ByteBuffer>, nullability: Nullability) -> Self {
131 unsafe {
133 Self::new_unchecked(
134 DType::Binary(nullability),
135 Some(ScalarValue::Binary(buffer.into())),
136 )
137 }
138 }
139
140 pub fn list(
147 element_dtype: impl Into<Arc<DType>>,
148 children: Vec<Scalar>,
149 nullability: Nullability,
150 ) -> Self {
151 Self::create_list(element_dtype, children, nullability, ListKind::Variable)
152 }
153
154 pub fn list_empty(element_dtype: Arc<DType>, nullability: Nullability) -> Self {
156 Self::create_list(element_dtype, vec![], nullability, ListKind::Variable)
157 }
158
159 pub fn fixed_size_list(
166 element_dtype: impl Into<Arc<DType>>,
167 children: Vec<Scalar>,
168 nullability: Nullability,
169 ) -> Self {
170 Self::create_list(element_dtype, children, nullability, ListKind::FixedSize)
171 }
172
173 pub fn map(dtype: DType, entries: impl IntoIterator<Item = (Scalar, Scalar)>) -> Self {
179 Self::try_map(dtype, entries).vortex_expect("unable to construct a map `Scalar`")
180 }
181
182 pub fn try_map(
189 dtype: DType,
190 entries: impl IntoIterator<Item = (Scalar, Scalar)>,
191 ) -> VortexResult<Self> {
192 let map = dtype
193 .as_map_opt()
194 .ok_or_else(|| vortex_error::vortex_err!("Expected map dtype, found {dtype}"))?;
195 let key_dtype = map.key_dtype();
196 let value_dtype = map.value_dtype();
197
198 let entries = entries
199 .into_iter()
200 .enumerate()
201 .map(|(index, (key, value))| {
202 if key.dtype() != &key_dtype {
203 vortex_bail!(
204 "map entry {index} expected key dtype {key_dtype}, got {}",
205 key.dtype()
206 );
207 }
208 if value.dtype() != &value_dtype {
209 vortex_bail!(
210 "map entry {index} expected value dtype {value_dtype}, got {}",
211 value.dtype()
212 );
213 }
214
215 Ok(Some(ScalarValue::Tuple(vec![
216 key.into_value(),
217 value.into_value(),
218 ])))
219 })
220 .collect::<VortexResult<Vec<_>>>()?;
221
222 Self::try_new(dtype, Some(ScalarValue::Tuple(entries)))
223 }
224
225 fn create_list(
227 element_dtype: impl Into<Arc<DType>>,
228 children: Vec<Scalar>,
229 nullability: Nullability,
230 list_kind: ListKind,
231 ) -> Self {
232 let element_dtype = element_dtype.into();
233
234 let children: Vec<Option<ScalarValue>> = children
235 .into_iter()
236 .map(|child| {
237 if child.dtype() != &*element_dtype {
238 vortex_panic!(
239 "tried to create list of {} with values of type {}",
240 element_dtype,
241 child.dtype()
242 );
243 }
244 child.into_value()
245 })
246 .collect();
247 let size: u32 = children
248 .len()
249 .try_into()
250 .vortex_expect("tried to create a list that was too large");
251
252 let dtype = match list_kind {
253 ListKind::Variable => DType::List(element_dtype, nullability),
254 ListKind::FixedSize => DType::FixedSizeList(element_dtype, size, nullability),
255 };
256
257 Self::try_new(dtype, Some(ScalarValue::Tuple(children)))
258 .vortex_expect("unable to construct a list `Scalar`")
259 }
260
261 pub fn extension<V: ExtVTable + Default>(options: V::Metadata, storage_scalar: Scalar) -> Self {
263 let ext_dtype = ExtDType::<V>::try_new(options, storage_scalar.dtype().clone())
264 .vortex_expect("Failed to create extension dtype");
265
266 Self::extension_ref(ext_dtype.erased(), storage_scalar)
267 }
268
269 pub fn extension_ref(ext_dtype: ExtDTypeRef, storage_scalar: Scalar) -> Self {
275 Self::try_extension_ref(ext_dtype, storage_scalar)
276 .vortex_expect("unable to construct an extension `Scalar`")
277 }
278
279 pub fn try_extension_ref(ext_dtype: ExtDTypeRef, storage_scalar: Scalar) -> VortexResult<Self> {
286 vortex_ensure_eq!(ext_dtype.storage_dtype(), storage_scalar.dtype());
287
288 Self::try_new(DType::Extension(ext_dtype), storage_scalar.into_value())
289 }
290
291 pub fn union(
303 variants: UnionVariants,
304 type_id: u8,
305 child: Scalar,
306 nullability: Nullability,
307 ) -> VortexResult<Self> {
308 let child_index = variants.tag_to_child_index(type_id).ok_or_else(|| {
309 vortex_err!(
310 "union type ID {type_id} is not present in {:?}",
311 variants.type_ids()
312 )
313 })?;
314
315 let expected_dtype = variants
316 .variant_by_index(child_index)
317 .vortex_expect("type ID resolved to a valid child index");
318
319 vortex_ensure_eq!(
320 child.dtype(),
321 &expected_dtype,
322 "union type ID {type_id} selects a different child dtype"
323 );
324
325 Self::try_new(
326 DType::Union(variants, nullability),
327 Some(ScalarValue::Union(UnionValue::new(
328 type_id,
329 child.into_value(),
330 ))),
331 )
332 }
333
334 pub fn variant(value: Scalar) -> Self {
340 Self::try_new(
341 DType::Variant(Nullability::NonNullable),
342 Some(ScalarValue::Variant(Box::new(value))),
343 )
344 .vortex_expect("unable to construct a variant `Scalar`")
345 }
346}
347
348enum ListKind {
350 Variable,
352 FixedSize,
354}