Skip to main content

vortex_array/builders/
map.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::sync::Arc;
6
7use vortex_buffer::BufferAllocatorRef;
8use vortex_error::VortexResult;
9use vortex_error::vortex_ensure_eq;
10
11use crate::ArrayRef;
12use crate::Canonical;
13use crate::ExecutionCtx;
14use crate::IntoArray;
15use crate::array::ArrayView;
16use crate::arrays::ListView;
17use crate::arrays::Map;
18use crate::arrays::MapArray;
19use crate::arrays::map::MapArraySlotsExt;
20use crate::builders::ArrayBuilder;
21use crate::builders::DEFAULT_BUILDER_CAPACITY;
22use crate::builders::ListViewBuilder;
23use crate::dtype::DType;
24use crate::dtype::MapDType;
25use crate::dtype::Nullability;
26use crate::dtype::OffsetBuilderPType;
27use crate::scalar::MapScalar;
28use crate::scalar::Scalar;
29
30/// A builder for canonical [`MapArray`] values.
31///
32/// The builder owns a [`ListViewBuilder`] whose elements are non-nullable `{key, value}` structs.
33/// It preserves the map dtype's `keys_sorted` assertion while delegating offsets, sizes, and outer
34/// validity to that list-view builder.
35pub struct MapBuilder<O: OffsetBuilderPType, S: OffsetBuilderPType> {
36    dtype: DType,
37    map_dtype: MapDType,
38    entries_builder: ListViewBuilder<O, S>,
39}
40
41impl<O: OffsetBuilderPType, S: OffsetBuilderPType> MapBuilder<O, S> {
42    /// Creates a map builder with the default capacity.
43    #[deprecated(note = "use `new_in` with an explicit allocator")]
44    pub fn new(map_dtype: MapDType, nullability: Nullability) -> Self {
45        Self::new_in(map_dtype, nullability, BufferAllocatorRef::static_ref())
46    }
47
48    /// Creates a map builder with the default capacity using `allocator`.
49    pub fn new_in(
50        map_dtype: MapDType,
51        nullability: Nullability,
52        allocator: &BufferAllocatorRef,
53    ) -> Self {
54        Self::with_capacity_in(map_dtype, nullability, DEFAULT_BUILDER_CAPACITY, allocator)
55    }
56
57    /// Creates a map builder with space for `capacity` map rows.
58    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
59    pub fn with_capacity(map_dtype: MapDType, nullability: Nullability, capacity: usize) -> Self {
60        Self::with_capacity_in(
61            map_dtype,
62            nullability,
63            capacity,
64            BufferAllocatorRef::static_ref(),
65        )
66    }
67
68    /// Creates a map builder with space for `capacity` rows using `allocator`.
69    pub fn with_capacity_in(
70        map_dtype: MapDType,
71        nullability: Nullability,
72        capacity: usize,
73        allocator: &BufferAllocatorRef,
74    ) -> Self {
75        let entries_builder = ListViewBuilder::with_capacity_in(
76            Arc::new(map_dtype.entries_dtype()),
77            nullability,
78            capacity,
79            allocator,
80        );
81        let dtype = DType::Map(map_dtype.clone(), nullability);
82        Self {
83            dtype,
84            map_dtype,
85            entries_builder,
86        }
87    }
88
89    /// Appends one map scalar.
90    pub fn append_value(&mut self, value: MapScalar<'_>) -> VortexResult<()> {
91        vortex_ensure_eq!(
92            value.dtype(),
93            &self.dtype,
94            "MapBuilder received a map scalar with the wrong dtype"
95        );
96
97        if value.is_null() {
98            self.entries_builder.append_null();
99            return Ok(());
100        }
101
102        let entry_dtype = self.map_dtype.entries_dtype();
103        let entries = value
104            .entries()
105            .map(|(key, value)| Scalar::struct_(entry_dtype.clone(), vec![key, value]))
106            .collect();
107        let entries = Scalar::list(Arc::new(entry_dtype), entries, self.dtype.nullability());
108        self.entries_builder.append_value(entries.as_list())
109    }
110
111    /// Finishes the builder directly into a [`MapArray`].
112    pub fn finish_into_map(&mut self) -> MapArray {
113        // SAFETY: the entries builder was constructed from `map_dtype.entries_dtype()` with the
114        // map's nullability, so its lists hold exactly that entry struct.
115        unsafe {
116            MapArray::new_unchecked(
117                self.map_dtype.clone(),
118                self.entries_builder.finish_into_listview(),
119            )
120        }
121    }
122
123    /// Appends the values of a [`Map`]-encoded `array` to this builder.
124    pub fn append_map_array(
125        &mut self,
126        array: ArrayView<'_, Map>,
127        ctx: &mut ExecutionCtx,
128    ) -> VortexResult<()> {
129        vortex_ensure_eq!(
130            array.dtype(),
131            self.dtype(),
132            "MapBuilder received a map array with the wrong dtype"
133        );
134        self.entries_builder
135            .append_listview_array(array.entries().as_::<ListView>(), ctx)
136    }
137}
138
139impl<O: OffsetBuilderPType, S: OffsetBuilderPType> ArrayBuilder for MapBuilder<O, S> {
140    fn as_any(&self) -> &dyn Any {
141        self
142    }
143
144    fn as_any_mut(&mut self) -> &mut dyn Any {
145        self
146    }
147
148    fn dtype(&self) -> &DType {
149        &self.dtype
150    }
151
152    fn len(&self) -> usize {
153        self.entries_builder.len()
154    }
155
156    fn append_zeros(&mut self, n: usize) {
157        self.entries_builder.append_zeros(n);
158    }
159
160    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
161        unsafe { self.entries_builder.append_nulls_unchecked(n) };
162    }
163
164    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
165        vortex_ensure_eq!(
166            scalar.dtype(),
167            self.dtype(),
168            "MapBuilder received a scalar with the wrong dtype"
169        );
170        self.append_value(scalar.as_map())
171    }
172
173    fn reserve_chunks(&mut self, additional: usize) {
174        self.entries_builder.reserve_chunks(additional);
175    }
176
177    fn reserve_exact(&mut self, additional: usize) {
178        self.entries_builder.reserve_exact(additional);
179    }
180
181    fn finish(&mut self) -> ArrayRef {
182        self.finish_into_map().into_array()
183    }
184
185    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
186        Canonical::Map(self.finish_into_map())
187    }
188}