arrow_array/array/
map_array.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::array::{get_offsets_from_buffer, print_long_array};
19use crate::iterator::MapArrayIter;
20use crate::{Array, ArrayAccessor, ArrayRef, ListArray, StringArray, StructArray, make_array};
21use arrow_buffer::{ArrowNativeType, Buffer, NullBuffer, OffsetBuffer, ToByteSlice};
22use arrow_data::{ArrayData, ArrayDataBuilder};
23use arrow_schema::{ArrowError, DataType, Field, FieldRef};
24use std::any::Any;
25use std::sync::Arc;
26
27/// An array of key-value maps
28///
29/// Keys should always be non-null, but values can be null.
30///
31/// [`MapArray`] is physically a [`ListArray`] of key values pairs stored as an `entries`
32/// [`StructArray`] with 2 child fields.
33///
34/// See [`MapBuilder`](crate::builder::MapBuilder) for how to construct a [`MapArray`]
35#[derive(Clone)]
36pub struct MapArray {
37    data_type: DataType,
38    nulls: Option<NullBuffer>,
39    /// The [`StructArray`] that is the direct child of this array
40    entries: StructArray,
41    /// The start and end offsets of each entry
42    value_offsets: OffsetBuffer<i32>,
43}
44
45impl MapArray {
46    /// Create a new [`MapArray`] from the provided parts
47    ///
48    /// See [`MapBuilder`](crate::builder::MapBuilder) for a higher-level interface
49    /// to construct a [`MapArray`]
50    ///
51    /// # Errors
52    ///
53    /// Errors if
54    ///
55    /// * `offsets.len() - 1 != nulls.len()`
56    /// * `offsets.last() > entries.len()`
57    /// * `field.is_nullable()`
58    /// * `entries.null_count() != 0`
59    /// * `entries.columns().len() != 2`
60    /// * `field.data_type() != entries.data_type()`
61    pub fn try_new(
62        field: FieldRef,
63        offsets: OffsetBuffer<i32>,
64        entries: StructArray,
65        nulls: Option<NullBuffer>,
66        ordered: bool,
67    ) -> Result<Self, ArrowError> {
68        let len = offsets.len() - 1; // Offsets guaranteed to not be empty
69        let end_offset = offsets.last().unwrap().as_usize();
70        // don't need to check other values of `offsets` because they are checked
71        // during construction of `OffsetBuffer`
72        if end_offset > entries.len() {
73            return Err(ArrowError::InvalidArgumentError(format!(
74                "Max offset of {end_offset} exceeds length of entries {}",
75                entries.len()
76            )));
77        }
78
79        if let Some(n) = nulls.as_ref() {
80            if n.len() != len {
81                return Err(ArrowError::InvalidArgumentError(format!(
82                    "Incorrect length of null buffer for MapArray, expected {len} got {}",
83                    n.len(),
84                )));
85            }
86        }
87        if field.is_nullable() || entries.null_count() != 0 {
88            return Err(ArrowError::InvalidArgumentError(
89                "MapArray entries cannot contain nulls".to_string(),
90            ));
91        }
92
93        if field.data_type() != entries.data_type() {
94            return Err(ArrowError::InvalidArgumentError(format!(
95                "MapArray expected data type {} got {} for {:?}",
96                field.data_type(),
97                entries.data_type(),
98                field.name()
99            )));
100        }
101
102        if entries.columns().len() != 2 {
103            return Err(ArrowError::InvalidArgumentError(format!(
104                "MapArray entries must contain two children, got {}",
105                entries.columns().len()
106            )));
107        }
108
109        Ok(Self {
110            data_type: DataType::Map(field, ordered),
111            nulls,
112            entries,
113            value_offsets: offsets,
114        })
115    }
116
117    /// Create a new [`MapArray`] from the provided parts
118    ///
119    /// See [`MapBuilder`](crate::builder::MapBuilder) for a higher-level interface
120    /// to construct a [`MapArray`]
121    ///
122    /// # Panics
123    ///
124    /// Panics if [`Self::try_new`] returns an error
125    pub fn new(
126        field: FieldRef,
127        offsets: OffsetBuffer<i32>,
128        entries: StructArray,
129        nulls: Option<NullBuffer>,
130        ordered: bool,
131    ) -> Self {
132        Self::try_new(field, offsets, entries, nulls, ordered).unwrap()
133    }
134
135    /// Deconstruct this array into its constituent parts
136    pub fn into_parts(
137        self,
138    ) -> (
139        FieldRef,
140        OffsetBuffer<i32>,
141        StructArray,
142        Option<NullBuffer>,
143        bool,
144    ) {
145        let (f, ordered) = match self.data_type {
146            DataType::Map(f, ordered) => (f, ordered),
147            _ => unreachable!(),
148        };
149        (f, self.value_offsets, self.entries, self.nulls, ordered)
150    }
151
152    /// Returns a reference to the offsets of this map
153    ///
154    /// Unlike [`Self::value_offsets`] this returns the [`OffsetBuffer`]
155    /// allowing for zero-copy cloning
156    #[inline]
157    pub fn offsets(&self) -> &OffsetBuffer<i32> {
158        &self.value_offsets
159    }
160
161    /// Returns a reference to the keys of this map
162    pub fn keys(&self) -> &ArrayRef {
163        self.entries.column(0)
164    }
165
166    /// Returns a reference to the values of this map
167    pub fn values(&self) -> &ArrayRef {
168        self.entries.column(1)
169    }
170
171    /// Returns a reference to the [`StructArray`] entries of this map
172    pub fn entries(&self) -> &StructArray {
173        &self.entries
174    }
175
176    /// Returns a reference to the fields of the [`StructArray`] that backs this map.
177    pub fn entries_fields(&self) -> (&Field, &Field) {
178        let fields = self.entries.fields().iter().collect::<Vec<_>>();
179        let fields = TryInto::<[&FieldRef; 2]>::try_into(fields)
180            .expect("Every map has a key and value field");
181
182        (fields[0].as_ref(), fields[1].as_ref())
183    }
184
185    /// Returns the data type of the map's keys.
186    pub fn key_type(&self) -> &DataType {
187        self.keys().data_type()
188    }
189
190    /// Returns the data type of the map's values.
191    pub fn value_type(&self) -> &DataType {
192        self.values().data_type()
193    }
194
195    /// Returns ith value of this map array.
196    ///
197    /// Note: This method does not check for nulls and the value is arbitrary
198    /// if [`is_null`](Self::is_null) returns true for the index.
199    ///
200    /// # Safety
201    /// Caller must ensure that the index is within the array bounds
202    pub unsafe fn value_unchecked(&self, i: usize) -> StructArray {
203        let end = *unsafe { self.value_offsets().get_unchecked(i + 1) };
204        let start = *unsafe { self.value_offsets().get_unchecked(i) };
205        self.entries
206            .slice(start.to_usize().unwrap(), (end - start).to_usize().unwrap())
207    }
208
209    /// Returns ith value of this map array.
210    ///
211    /// This is a [`StructArray`] containing two fields
212    ///
213    /// Note: This method does not check for nulls and the value is arbitrary
214    /// (but still well-defined) if [`is_null`](Self::is_null) returns true for the index.
215    ///
216    /// # Panics
217    /// Panics if index `i` is out of bounds
218    pub fn value(&self, i: usize) -> StructArray {
219        let end = self.value_offsets()[i + 1] as usize;
220        let start = self.value_offsets()[i] as usize;
221        self.entries.slice(start, end - start)
222    }
223
224    /// Returns the offset values in the offsets buffer
225    #[inline]
226    pub fn value_offsets(&self) -> &[i32] {
227        &self.value_offsets
228    }
229
230    /// Returns the length for value at index `i`.
231    #[inline]
232    pub fn value_length(&self, i: usize) -> i32 {
233        let offsets = self.value_offsets();
234        offsets[i + 1] - offsets[i]
235    }
236
237    /// Returns a zero-copy slice of this array with the indicated offset and length.
238    pub fn slice(&self, offset: usize, length: usize) -> Self {
239        Self {
240            data_type: self.data_type.clone(),
241            nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
242            entries: self.entries.clone(),
243            value_offsets: self.value_offsets.slice(offset, length),
244        }
245    }
246
247    /// constructs a new iterator
248    pub fn iter(&self) -> MapArrayIter<'_> {
249        MapArrayIter::new(self)
250    }
251}
252
253impl From<ArrayData> for MapArray {
254    fn from(data: ArrayData) -> Self {
255        Self::try_new_from_array_data(data)
256            .expect("Expected infallible creation of MapArray from ArrayData failed")
257    }
258}
259
260impl From<MapArray> for ArrayData {
261    fn from(array: MapArray) -> Self {
262        let len = array.len();
263        let builder = ArrayDataBuilder::new(array.data_type)
264            .len(len)
265            .nulls(array.nulls)
266            .buffers(vec![array.value_offsets.into_inner().into_inner()])
267            .child_data(vec![array.entries.to_data()]);
268
269        unsafe { builder.build_unchecked() }
270    }
271}
272
273impl MapArray {
274    fn try_new_from_array_data(data: ArrayData) -> Result<Self, ArrowError> {
275        let (data_type, len, nulls, offset, mut buffers, mut child_data) = data.into_parts();
276
277        if !matches!(data_type, DataType::Map(_, _)) {
278            return Err(ArrowError::InvalidArgumentError(format!(
279                "MapArray expected ArrayData with DataType::Map got {data_type}",
280            )));
281        }
282
283        if buffers.len() != 1 {
284            return Err(ArrowError::InvalidArgumentError(format!(
285                "MapArray data should contain a single buffer only (value offsets), had {}",
286                buffers.len(),
287            )));
288        }
289        let buffer = buffers.pop().expect("checked above");
290
291        if child_data.len() != 1 {
292            return Err(ArrowError::InvalidArgumentError(format!(
293                "MapArray should contain a single child array (values array), had {}",
294                child_data.len()
295            )));
296        }
297        let entries = child_data.pop().expect("checked above");
298
299        if let DataType::Struct(fields) = entries.data_type() {
300            if fields.len() != 2 {
301                return Err(ArrowError::InvalidArgumentError(format!(
302                    "MapArray should contain a struct array with 2 fields, have {} fields",
303                    fields.len()
304                )));
305            }
306        } else {
307            return Err(ArrowError::InvalidArgumentError(format!(
308                "MapArray should contain a struct array child, found {:?}",
309                entries.data_type()
310            )));
311        }
312        let entries = entries.into();
313
314        // SAFETY:
315        // ArrayData is valid, and verified type above
316        let value_offsets = unsafe { get_offsets_from_buffer(buffer, offset, len) };
317
318        Ok(Self {
319            data_type,
320            nulls,
321            entries,
322            value_offsets,
323        })
324    }
325
326    /// Creates map array from provided keys, values and entry_offsets.
327    pub fn new_from_strings<'a>(
328        keys: impl Iterator<Item = &'a str>,
329        values: &dyn Array,
330        entry_offsets: &[u32],
331    ) -> Result<Self, ArrowError> {
332        let entry_offsets_buffer = Buffer::from(entry_offsets.to_byte_slice());
333        let keys_data = StringArray::from_iter_values(keys);
334
335        let keys_field = Arc::new(Field::new("keys", DataType::Utf8, false));
336        let values_field = Arc::new(Field::new(
337            "values",
338            values.data_type().clone(),
339            values.null_count() > 0,
340        ));
341
342        let entry_struct = StructArray::from(vec![
343            (keys_field, Arc::new(keys_data) as ArrayRef),
344            (values_field, make_array(values.to_data())),
345        ]);
346
347        let map_data_type = DataType::Map(
348            Arc::new(Field::new(
349                "entries",
350                entry_struct.data_type().clone(),
351                false,
352            )),
353            false,
354        );
355        let map_data = ArrayData::builder(map_data_type)
356            .len(entry_offsets.len() - 1)
357            .add_buffer(entry_offsets_buffer)
358            .add_child_data(entry_struct.into_data())
359            .build()?;
360
361        Ok(MapArray::from(map_data))
362    }
363}
364
365impl super::private::Sealed for MapArray {}
366
367impl Array for MapArray {
368    fn as_any(&self) -> &dyn Any {
369        self
370    }
371
372    fn to_data(&self) -> ArrayData {
373        self.clone().into_data()
374    }
375
376    fn into_data(self) -> ArrayData {
377        self.into()
378    }
379
380    fn data_type(&self) -> &DataType {
381        &self.data_type
382    }
383
384    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
385        Arc::new(self.slice(offset, length))
386    }
387
388    fn len(&self) -> usize {
389        self.value_offsets.len() - 1
390    }
391
392    fn is_empty(&self) -> bool {
393        self.value_offsets.len() <= 1
394    }
395
396    fn shrink_to_fit(&mut self) {
397        if let Some(nulls) = &mut self.nulls {
398            nulls.shrink_to_fit();
399        }
400        self.entries.shrink_to_fit();
401        self.value_offsets.shrink_to_fit();
402    }
403
404    fn offset(&self) -> usize {
405        0
406    }
407
408    fn nulls(&self) -> Option<&NullBuffer> {
409        self.nulls.as_ref()
410    }
411
412    fn logical_null_count(&self) -> usize {
413        // More efficient that the default implementation
414        self.null_count()
415    }
416
417    fn get_buffer_memory_size(&self) -> usize {
418        let mut size = self.entries.get_buffer_memory_size();
419        size += self.value_offsets.inner().inner().capacity();
420        if let Some(n) = self.nulls.as_ref() {
421            size += n.buffer().capacity();
422        }
423        size
424    }
425
426    fn get_array_memory_size(&self) -> usize {
427        let mut size = std::mem::size_of::<Self>() + self.entries.get_array_memory_size();
428        size += self.value_offsets.inner().inner().capacity();
429        if let Some(n) = self.nulls.as_ref() {
430            size += n.buffer().capacity();
431        }
432        size
433    }
434}
435
436impl ArrayAccessor for &MapArray {
437    type Item = StructArray;
438
439    fn value(&self, index: usize) -> Self::Item {
440        MapArray::value(self, index)
441    }
442
443    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
444        MapArray::value(self, index)
445    }
446}
447
448impl std::fmt::Debug for MapArray {
449    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
450        write!(f, "MapArray\n[\n")?;
451        print_long_array(self, f, |array, index, f| {
452            std::fmt::Debug::fmt(&array.value(index), f)
453        })?;
454        write!(f, "]")
455    }
456}
457
458impl From<MapArray> for ListArray {
459    fn from(value: MapArray) -> Self {
460        let field = match value.data_type() {
461            DataType::Map(field, _) => field,
462            _ => unreachable!("This should be a map type."),
463        };
464        let data_type = DataType::List(field.clone());
465        let builder = value.into_data().into_builder().data_type(data_type);
466        let array_data = unsafe { builder.build_unchecked() };
467
468        ListArray::from(array_data)
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use crate::cast::AsArray;
475    use crate::types::UInt32Type;
476    use crate::{Int32Array, UInt32Array};
477    use arrow_schema::Fields;
478
479    use super::*;
480
481    fn create_from_buffers() -> MapArray {
482        // Construct key and values
483        let keys_data = ArrayData::builder(DataType::Int32)
484            .len(8)
485            .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
486            .build()
487            .unwrap();
488        let values_data = ArrayData::builder(DataType::UInt32)
489            .len(8)
490            .add_buffer(Buffer::from(
491                [0u32, 10, 20, 30, 40, 50, 60, 70].to_byte_slice(),
492            ))
493            .build()
494            .unwrap();
495
496        // Construct a buffer for value offsets, for the nested array:
497        //  [[0, 1, 2], [3, 4, 5], [6, 7]]
498        let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
499
500        let keys = Arc::new(Field::new("keys", DataType::Int32, false));
501        let values = Arc::new(Field::new("values", DataType::UInt32, false));
502        let entry_struct = StructArray::from(vec![
503            (keys, make_array(keys_data)),
504            (values, make_array(values_data)),
505        ]);
506
507        // Construct a map array from the above two
508        let map_data_type = DataType::Map(
509            Arc::new(Field::new(
510                "entries",
511                entry_struct.data_type().clone(),
512                false,
513            )),
514            false,
515        );
516        let map_data = ArrayData::builder(map_data_type)
517            .len(3)
518            .add_buffer(entry_offsets)
519            .add_child_data(entry_struct.into_data())
520            .build()
521            .unwrap();
522        MapArray::from(map_data)
523    }
524
525    #[test]
526    fn test_map_array() {
527        // Construct key and values
528        let key_data = ArrayData::builder(DataType::Int32)
529            .len(8)
530            .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
531            .build()
532            .unwrap();
533        let value_data = ArrayData::builder(DataType::UInt32)
534            .len(8)
535            .add_buffer(Buffer::from(
536                [0u32, 10, 20, 0, 40, 0, 60, 70].to_byte_slice(),
537            ))
538            .null_bit_buffer(Some(Buffer::from(&[0b11010110])))
539            .build()
540            .unwrap();
541
542        // Construct a buffer for value offsets, for the nested array:
543        //  [[0, 1, 2], [3, 4, 5], [6, 7]]
544        let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
545
546        let keys_field = Arc::new(Field::new("keys", DataType::Int32, false));
547        let values_field = Arc::new(Field::new("values", DataType::UInt32, true));
548        let entry_struct = StructArray::from(vec![
549            (keys_field.clone(), make_array(key_data)),
550            (values_field.clone(), make_array(value_data.clone())),
551        ]);
552
553        // Construct a map array from the above two
554        let map_data_type = DataType::Map(
555            Arc::new(Field::new(
556                "entries",
557                entry_struct.data_type().clone(),
558                false,
559            )),
560            false,
561        );
562        let map_data = ArrayData::builder(map_data_type)
563            .len(3)
564            .add_buffer(entry_offsets)
565            .add_child_data(entry_struct.into_data())
566            .build()
567            .unwrap();
568        let map_array = MapArray::from(map_data);
569
570        assert_eq!(value_data, map_array.values().to_data());
571        assert_eq!(&DataType::UInt32, map_array.value_type());
572        assert_eq!(3, map_array.len());
573        assert_eq!(0, map_array.null_count());
574        assert_eq!(6, map_array.value_offsets()[2]);
575        assert_eq!(2, map_array.value_length(2));
576
577        let key_array = Arc::new(Int32Array::from(vec![0, 1, 2])) as ArrayRef;
578        let value_array =
579            Arc::new(UInt32Array::from(vec![None, Some(10u32), Some(20)])) as ArrayRef;
580        let struct_array = StructArray::from(vec![
581            (keys_field.clone(), key_array),
582            (values_field.clone(), value_array),
583        ]);
584        assert_eq!(
585            struct_array,
586            StructArray::from(map_array.value(0).into_data())
587        );
588        assert_eq!(
589            &struct_array,
590            unsafe { map_array.value_unchecked(0) }
591                .as_any()
592                .downcast_ref::<StructArray>()
593                .unwrap()
594        );
595        for i in 0..3 {
596            assert!(map_array.is_valid(i));
597            assert!(!map_array.is_null(i));
598        }
599
600        // Now test with a non-zero offset
601        let map_array = map_array.slice(1, 2);
602
603        assert_eq!(value_data, map_array.values().to_data());
604        assert_eq!(&DataType::UInt32, map_array.value_type());
605        assert_eq!(2, map_array.len());
606        assert_eq!(0, map_array.null_count());
607        assert_eq!(6, map_array.value_offsets()[1]);
608        assert_eq!(2, map_array.value_length(1));
609
610        let key_array = Arc::new(Int32Array::from(vec![3, 4, 5])) as ArrayRef;
611        let value_array = Arc::new(UInt32Array::from(vec![None, Some(40), None])) as ArrayRef;
612        let struct_array =
613            StructArray::from(vec![(keys_field, key_array), (values_field, value_array)]);
614        assert_eq!(
615            &struct_array,
616            map_array
617                .value(0)
618                .as_any()
619                .downcast_ref::<StructArray>()
620                .unwrap()
621        );
622        assert_eq!(
623            &struct_array,
624            unsafe { map_array.value_unchecked(0) }
625                .as_any()
626                .downcast_ref::<StructArray>()
627                .unwrap()
628        );
629    }
630
631    #[test]
632    #[ignore = "Test fails because slice of <list<struct>> is still buggy"]
633    fn test_map_array_slice() {
634        let map_array = create_from_buffers();
635
636        let sliced_array = map_array.slice(1, 2);
637        assert_eq!(2, sliced_array.len());
638        assert_eq!(1, sliced_array.offset());
639        let sliced_array_data = sliced_array.to_data();
640        for array_data in sliced_array_data.child_data() {
641            assert_eq!(array_data.offset(), 1);
642        }
643
644        // Check offset and length for each non-null value.
645        let sliced_map_array = sliced_array.as_any().downcast_ref::<MapArray>().unwrap();
646        assert_eq!(3, sliced_map_array.value_offsets()[0]);
647        assert_eq!(3, sliced_map_array.value_length(0));
648        assert_eq!(6, sliced_map_array.value_offsets()[1]);
649        assert_eq!(2, sliced_map_array.value_length(1));
650
651        // Construct key and values
652        let keys_data = ArrayData::builder(DataType::Int32)
653            .len(5)
654            .add_buffer(Buffer::from([3, 4, 5, 6, 7].to_byte_slice()))
655            .build()
656            .unwrap();
657        let values_data = ArrayData::builder(DataType::UInt32)
658            .len(5)
659            .add_buffer(Buffer::from([30u32, 40, 50, 60, 70].to_byte_slice()))
660            .build()
661            .unwrap();
662
663        // Construct a buffer for value offsets, for the nested array:
664        //  [[3, 4, 5], [6, 7]]
665        let entry_offsets = Buffer::from([0, 3, 5].to_byte_slice());
666
667        let keys = Arc::new(Field::new("keys", DataType::Int32, false));
668        let values = Arc::new(Field::new("values", DataType::UInt32, false));
669        let entry_struct = StructArray::from(vec![
670            (keys, make_array(keys_data)),
671            (values, make_array(values_data)),
672        ]);
673
674        // Construct a map array from the above two
675        let map_data_type = DataType::Map(
676            Arc::new(Field::new(
677                "entries",
678                entry_struct.data_type().clone(),
679                false,
680            )),
681            false,
682        );
683        let expected_map_data = ArrayData::builder(map_data_type)
684            .len(2)
685            .add_buffer(entry_offsets)
686            .add_child_data(entry_struct.into_data())
687            .build()
688            .unwrap();
689        let expected_map_array = MapArray::from(expected_map_data);
690
691        assert_eq!(&expected_map_array, sliced_map_array)
692    }
693
694    #[test]
695    #[should_panic(expected = "index out of bounds: the len is ")]
696    fn test_map_array_index_out_of_bound() {
697        let map_array = create_from_buffers();
698
699        map_array.value(map_array.len());
700    }
701
702    #[test]
703    #[should_panic(expected = "MapArray expected ArrayData with DataType::Map got Dictionary")]
704    fn test_from_array_data_validation() {
705        // A DictionaryArray has similar buffer layout to a MapArray
706        // but the meaning of the values differs
707        let struct_t = DataType::Struct(Fields::from(vec![
708            Field::new("keys", DataType::Int32, true),
709            Field::new("values", DataType::UInt32, true),
710        ]));
711        let dict_t = DataType::Dictionary(Box::new(DataType::Int32), Box::new(struct_t));
712        let _ = MapArray::from(ArrayData::new_empty(&dict_t));
713    }
714
715    #[test]
716    fn test_new_from_strings() {
717        let keys = vec!["a", "b", "c", "d", "e", "f", "g", "h"];
718        let values_data = UInt32Array::from(vec![0u32, 10, 20, 30, 40, 50, 60, 70]);
719
720        // Construct a buffer for value offsets, for the nested array:
721        //  [[a, b, c], [d, e, f], [g, h]]
722        let entry_offsets = [0, 3, 6, 8];
723
724        let map_array =
725            MapArray::new_from_strings(keys.clone().into_iter(), &values_data, &entry_offsets)
726                .unwrap();
727
728        assert_eq!(
729            &values_data,
730            map_array.values().as_primitive::<UInt32Type>()
731        );
732        assert_eq!(&DataType::UInt32, map_array.value_type());
733        assert_eq!(3, map_array.len());
734        assert_eq!(0, map_array.null_count());
735        assert_eq!(6, map_array.value_offsets()[2]);
736        assert_eq!(2, map_array.value_length(2));
737
738        let key_array = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
739        let value_array = Arc::new(UInt32Array::from(vec![0u32, 10, 20])) as ArrayRef;
740        let keys_field = Arc::new(Field::new("keys", DataType::Utf8, false));
741        let values_field = Arc::new(Field::new("values", DataType::UInt32, false));
742        let struct_array =
743            StructArray::from(vec![(keys_field, key_array), (values_field, value_array)]);
744        assert_eq!(
745            struct_array,
746            StructArray::from(map_array.value(0).into_data())
747        );
748        assert_eq!(
749            &struct_array,
750            unsafe { map_array.value_unchecked(0) }
751                .as_any()
752                .downcast_ref::<StructArray>()
753                .unwrap()
754        );
755        for i in 0..3 {
756            assert!(map_array.is_valid(i));
757            assert!(!map_array.is_null(i));
758        }
759    }
760
761    #[test]
762    fn test_try_new() {
763        let offsets = OffsetBuffer::new(vec![0, 1, 4, 5].into());
764        let fields = Fields::from(vec![
765            Field::new("key", DataType::Int32, false),
766            Field::new("values", DataType::Int32, false),
767        ]);
768        let columns = vec![
769            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
770            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
771        ];
772
773        let entries = StructArray::new(fields.clone(), columns, None);
774        let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
775
776        MapArray::new(field.clone(), offsets.clone(), entries.clone(), None, false);
777
778        let nulls = NullBuffer::new_null(3);
779        MapArray::new(field.clone(), offsets, entries.clone(), Some(nulls), false);
780
781        let nulls = NullBuffer::new_null(3);
782        let offsets = OffsetBuffer::new(vec![0, 1, 2, 4, 5].into());
783        let err = MapArray::try_new(
784            field.clone(),
785            offsets.clone(),
786            entries.clone(),
787            Some(nulls),
788            false,
789        )
790        .unwrap_err();
791
792        assert_eq!(
793            err.to_string(),
794            "Invalid argument error: Incorrect length of null buffer for MapArray, expected 4 got 3"
795        );
796
797        let err = MapArray::try_new(field, offsets.clone(), entries.slice(0, 2), None, false)
798            .unwrap_err();
799
800        assert_eq!(
801            err.to_string(),
802            "Invalid argument error: Max offset of 5 exceeds length of entries 2"
803        );
804
805        let field = Arc::new(Field::new("element", DataType::Int64, false));
806        let err = MapArray::try_new(field, offsets.clone(), entries, None, false)
807            .unwrap_err()
808            .to_string();
809
810        assert!(
811            err.starts_with("Invalid argument error: MapArray expected data type Int64 got Struct"),
812            "{err}"
813        );
814
815        let fields = Fields::from(vec![
816            Field::new("a", DataType::Int32, false),
817            Field::new("b", DataType::Int32, false),
818            Field::new("c", DataType::Int32, false),
819        ]);
820        let columns = vec![
821            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
822            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
823            Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
824        ];
825
826        let s = StructArray::new(fields.clone(), columns, None);
827        let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
828        let err = MapArray::try_new(field, offsets, s, None, false).unwrap_err();
829
830        assert_eq!(
831            err.to_string(),
832            "Invalid argument error: MapArray entries must contain two children, got 3"
833        );
834    }
835}