1use crate::array::{get_offsets, 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#[derive(Clone)]
36pub struct MapArray {
37 data_type: DataType,
38 nulls: Option<NullBuffer>,
39 entries: StructArray,
41 value_offsets: OffsetBuffer<i32>,
43}
44
45impl MapArray {
46 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; let end_offset = offsets.last().unwrap().as_usize();
70 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 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 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 #[inline]
157 pub fn offsets(&self) -> &OffsetBuffer<i32> {
158 &self.value_offsets
159 }
160
161 pub fn keys(&self) -> &ArrayRef {
163 self.entries.column(0)
164 }
165
166 pub fn values(&self) -> &ArrayRef {
168 self.entries.column(1)
169 }
170
171 pub fn entries(&self) -> &StructArray {
173 &self.entries
174 }
175
176 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 pub fn key_type(&self) -> &DataType {
187 self.keys().data_type()
188 }
189
190 pub fn value_type(&self) -> &DataType {
192 self.values().data_type()
193 }
194
195 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 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 #[inline]
226 pub fn value_offsets(&self) -> &[i32] {
227 &self.value_offsets
228 }
229
230 #[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 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 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 if !matches!(data.data_type(), DataType::Map(_, _)) {
276 return Err(ArrowError::InvalidArgumentError(format!(
277 "MapArray expected ArrayData with DataType::Map got {}",
278 data.data_type()
279 )));
280 }
281
282 if data.buffers().len() != 1 {
283 return Err(ArrowError::InvalidArgumentError(format!(
284 "MapArray data should contain a single buffer only (value offsets), had {}",
285 data.len()
286 )));
287 }
288
289 if data.child_data().len() != 1 {
290 return Err(ArrowError::InvalidArgumentError(format!(
291 "MapArray should contain a single child array (values array), had {}",
292 data.child_data().len()
293 )));
294 }
295
296 let entries = data.child_data()[0].clone();
297
298 if let DataType::Struct(fields) = entries.data_type() {
299 if fields.len() != 2 {
300 return Err(ArrowError::InvalidArgumentError(format!(
301 "MapArray should contain a struct array with 2 fields, have {} fields",
302 fields.len()
303 )));
304 }
305 } else {
306 return Err(ArrowError::InvalidArgumentError(format!(
307 "MapArray should contain a struct array child, found {:?}",
308 entries.data_type()
309 )));
310 }
311 let entries = entries.into();
312
313 let value_offsets = unsafe { get_offsets(&data) };
316
317 Ok(Self {
318 data_type: data.data_type().clone(),
319 nulls: data.nulls().cloned(),
320 entries,
321 value_offsets,
322 })
323 }
324
325 pub fn new_from_strings<'a>(
327 keys: impl Iterator<Item = &'a str>,
328 values: &dyn Array,
329 entry_offsets: &[u32],
330 ) -> Result<Self, ArrowError> {
331 let entry_offsets_buffer = Buffer::from(entry_offsets.to_byte_slice());
332 let keys_data = StringArray::from_iter_values(keys);
333
334 let keys_field = Arc::new(Field::new("keys", DataType::Utf8, false));
335 let values_field = Arc::new(Field::new(
336 "values",
337 values.data_type().clone(),
338 values.null_count() > 0,
339 ));
340
341 let entry_struct = StructArray::from(vec![
342 (keys_field, Arc::new(keys_data) as ArrayRef),
343 (values_field, make_array(values.to_data())),
344 ]);
345
346 let map_data_type = DataType::Map(
347 Arc::new(Field::new(
348 "entries",
349 entry_struct.data_type().clone(),
350 false,
351 )),
352 false,
353 );
354 let map_data = ArrayData::builder(map_data_type)
355 .len(entry_offsets.len() - 1)
356 .add_buffer(entry_offsets_buffer)
357 .add_child_data(entry_struct.into_data())
358 .build()?;
359
360 Ok(MapArray::from(map_data))
361 }
362}
363
364impl Array for MapArray {
365 fn as_any(&self) -> &dyn Any {
366 self
367 }
368
369 fn to_data(&self) -> ArrayData {
370 self.clone().into_data()
371 }
372
373 fn into_data(self) -> ArrayData {
374 self.into()
375 }
376
377 fn data_type(&self) -> &DataType {
378 &self.data_type
379 }
380
381 fn slice(&self, offset: usize, length: usize) -> ArrayRef {
382 Arc::new(self.slice(offset, length))
383 }
384
385 fn len(&self) -> usize {
386 self.value_offsets.len() - 1
387 }
388
389 fn is_empty(&self) -> bool {
390 self.value_offsets.len() <= 1
391 }
392
393 fn shrink_to_fit(&mut self) {
394 if let Some(nulls) = &mut self.nulls {
395 nulls.shrink_to_fit();
396 }
397 self.entries.shrink_to_fit();
398 self.value_offsets.shrink_to_fit();
399 }
400
401 fn offset(&self) -> usize {
402 0
403 }
404
405 fn nulls(&self) -> Option<&NullBuffer> {
406 self.nulls.as_ref()
407 }
408
409 fn logical_null_count(&self) -> usize {
410 self.null_count()
412 }
413
414 fn get_buffer_memory_size(&self) -> usize {
415 let mut size = self.entries.get_buffer_memory_size();
416 size += self.value_offsets.inner().inner().capacity();
417 if let Some(n) = self.nulls.as_ref() {
418 size += n.buffer().capacity();
419 }
420 size
421 }
422
423 fn get_array_memory_size(&self) -> usize {
424 let mut size = std::mem::size_of::<Self>() + self.entries.get_array_memory_size();
425 size += self.value_offsets.inner().inner().capacity();
426 if let Some(n) = self.nulls.as_ref() {
427 size += n.buffer().capacity();
428 }
429 size
430 }
431}
432
433impl ArrayAccessor for &MapArray {
434 type Item = StructArray;
435
436 fn value(&self, index: usize) -> Self::Item {
437 MapArray::value(self, index)
438 }
439
440 unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
441 MapArray::value(self, index)
442 }
443}
444
445impl std::fmt::Debug for MapArray {
446 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
447 write!(f, "MapArray\n[\n")?;
448 print_long_array(self, f, |array, index, f| {
449 std::fmt::Debug::fmt(&array.value(index), f)
450 })?;
451 write!(f, "]")
452 }
453}
454
455impl From<MapArray> for ListArray {
456 fn from(value: MapArray) -> Self {
457 let field = match value.data_type() {
458 DataType::Map(field, _) => field,
459 _ => unreachable!("This should be a map type."),
460 };
461 let data_type = DataType::List(field.clone());
462 let builder = value.into_data().into_builder().data_type(data_type);
463 let array_data = unsafe { builder.build_unchecked() };
464
465 ListArray::from(array_data)
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use crate::cast::AsArray;
472 use crate::types::UInt32Type;
473 use crate::{Int32Array, UInt32Array};
474 use arrow_schema::Fields;
475
476 use super::*;
477
478 fn create_from_buffers() -> MapArray {
479 let keys_data = ArrayData::builder(DataType::Int32)
481 .len(8)
482 .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
483 .build()
484 .unwrap();
485 let values_data = ArrayData::builder(DataType::UInt32)
486 .len(8)
487 .add_buffer(Buffer::from(
488 [0u32, 10, 20, 30, 40, 50, 60, 70].to_byte_slice(),
489 ))
490 .build()
491 .unwrap();
492
493 let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
496
497 let keys = Arc::new(Field::new("keys", DataType::Int32, false));
498 let values = Arc::new(Field::new("values", DataType::UInt32, false));
499 let entry_struct = StructArray::from(vec![
500 (keys, make_array(keys_data)),
501 (values, make_array(values_data)),
502 ]);
503
504 let map_data_type = DataType::Map(
506 Arc::new(Field::new(
507 "entries",
508 entry_struct.data_type().clone(),
509 false,
510 )),
511 false,
512 );
513 let map_data = ArrayData::builder(map_data_type)
514 .len(3)
515 .add_buffer(entry_offsets)
516 .add_child_data(entry_struct.into_data())
517 .build()
518 .unwrap();
519 MapArray::from(map_data)
520 }
521
522 #[test]
523 fn test_map_array() {
524 let key_data = ArrayData::builder(DataType::Int32)
526 .len(8)
527 .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
528 .build()
529 .unwrap();
530 let value_data = ArrayData::builder(DataType::UInt32)
531 .len(8)
532 .add_buffer(Buffer::from(
533 [0u32, 10, 20, 0, 40, 0, 60, 70].to_byte_slice(),
534 ))
535 .null_bit_buffer(Some(Buffer::from(&[0b11010110])))
536 .build()
537 .unwrap();
538
539 let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
542
543 let keys_field = Arc::new(Field::new("keys", DataType::Int32, false));
544 let values_field = Arc::new(Field::new("values", DataType::UInt32, true));
545 let entry_struct = StructArray::from(vec![
546 (keys_field.clone(), make_array(key_data)),
547 (values_field.clone(), make_array(value_data.clone())),
548 ]);
549
550 let map_data_type = DataType::Map(
552 Arc::new(Field::new(
553 "entries",
554 entry_struct.data_type().clone(),
555 false,
556 )),
557 false,
558 );
559 let map_data = ArrayData::builder(map_data_type)
560 .len(3)
561 .add_buffer(entry_offsets)
562 .add_child_data(entry_struct.into_data())
563 .build()
564 .unwrap();
565 let map_array = MapArray::from(map_data);
566
567 assert_eq!(value_data, map_array.values().to_data());
568 assert_eq!(&DataType::UInt32, map_array.value_type());
569 assert_eq!(3, map_array.len());
570 assert_eq!(0, map_array.null_count());
571 assert_eq!(6, map_array.value_offsets()[2]);
572 assert_eq!(2, map_array.value_length(2));
573
574 let key_array = Arc::new(Int32Array::from(vec![0, 1, 2])) as ArrayRef;
575 let value_array =
576 Arc::new(UInt32Array::from(vec![None, Some(10u32), Some(20)])) as ArrayRef;
577 let struct_array = StructArray::from(vec![
578 (keys_field.clone(), key_array),
579 (values_field.clone(), value_array),
580 ]);
581 assert_eq!(
582 struct_array,
583 StructArray::from(map_array.value(0).into_data())
584 );
585 assert_eq!(
586 &struct_array,
587 unsafe { map_array.value_unchecked(0) }
588 .as_any()
589 .downcast_ref::<StructArray>()
590 .unwrap()
591 );
592 for i in 0..3 {
593 assert!(map_array.is_valid(i));
594 assert!(!map_array.is_null(i));
595 }
596
597 let map_array = map_array.slice(1, 2);
599
600 assert_eq!(value_data, map_array.values().to_data());
601 assert_eq!(&DataType::UInt32, map_array.value_type());
602 assert_eq!(2, map_array.len());
603 assert_eq!(0, map_array.null_count());
604 assert_eq!(6, map_array.value_offsets()[1]);
605 assert_eq!(2, map_array.value_length(1));
606
607 let key_array = Arc::new(Int32Array::from(vec![3, 4, 5])) as ArrayRef;
608 let value_array = Arc::new(UInt32Array::from(vec![None, Some(40), None])) as ArrayRef;
609 let struct_array =
610 StructArray::from(vec![(keys_field, key_array), (values_field, value_array)]);
611 assert_eq!(
612 &struct_array,
613 map_array
614 .value(0)
615 .as_any()
616 .downcast_ref::<StructArray>()
617 .unwrap()
618 );
619 assert_eq!(
620 &struct_array,
621 unsafe { map_array.value_unchecked(0) }
622 .as_any()
623 .downcast_ref::<StructArray>()
624 .unwrap()
625 );
626 }
627
628 #[test]
629 #[ignore = "Test fails because slice of <list<struct>> is still buggy"]
630 fn test_map_array_slice() {
631 let map_array = create_from_buffers();
632
633 let sliced_array = map_array.slice(1, 2);
634 assert_eq!(2, sliced_array.len());
635 assert_eq!(1, sliced_array.offset());
636 let sliced_array_data = sliced_array.to_data();
637 for array_data in sliced_array_data.child_data() {
638 assert_eq!(array_data.offset(), 1);
639 }
640
641 let sliced_map_array = sliced_array.as_any().downcast_ref::<MapArray>().unwrap();
643 assert_eq!(3, sliced_map_array.value_offsets()[0]);
644 assert_eq!(3, sliced_map_array.value_length(0));
645 assert_eq!(6, sliced_map_array.value_offsets()[1]);
646 assert_eq!(2, sliced_map_array.value_length(1));
647
648 let keys_data = ArrayData::builder(DataType::Int32)
650 .len(5)
651 .add_buffer(Buffer::from([3, 4, 5, 6, 7].to_byte_slice()))
652 .build()
653 .unwrap();
654 let values_data = ArrayData::builder(DataType::UInt32)
655 .len(5)
656 .add_buffer(Buffer::from([30u32, 40, 50, 60, 70].to_byte_slice()))
657 .build()
658 .unwrap();
659
660 let entry_offsets = Buffer::from([0, 3, 5].to_byte_slice());
663
664 let keys = Arc::new(Field::new("keys", DataType::Int32, false));
665 let values = Arc::new(Field::new("values", DataType::UInt32, false));
666 let entry_struct = StructArray::from(vec![
667 (keys, make_array(keys_data)),
668 (values, make_array(values_data)),
669 ]);
670
671 let map_data_type = DataType::Map(
673 Arc::new(Field::new(
674 "entries",
675 entry_struct.data_type().clone(),
676 false,
677 )),
678 false,
679 );
680 let expected_map_data = ArrayData::builder(map_data_type)
681 .len(2)
682 .add_buffer(entry_offsets)
683 .add_child_data(entry_struct.into_data())
684 .build()
685 .unwrap();
686 let expected_map_array = MapArray::from(expected_map_data);
687
688 assert_eq!(&expected_map_array, sliced_map_array)
689 }
690
691 #[test]
692 #[should_panic(expected = "index out of bounds: the len is ")]
693 fn test_map_array_index_out_of_bound() {
694 let map_array = create_from_buffers();
695
696 map_array.value(map_array.len());
697 }
698
699 #[test]
700 #[should_panic(expected = "MapArray expected ArrayData with DataType::Map got Dictionary")]
701 fn test_from_array_data_validation() {
702 let struct_t = DataType::Struct(Fields::from(vec![
705 Field::new("keys", DataType::Int32, true),
706 Field::new("values", DataType::UInt32, true),
707 ]));
708 let dict_t = DataType::Dictionary(Box::new(DataType::Int32), Box::new(struct_t));
709 let _ = MapArray::from(ArrayData::new_empty(&dict_t));
710 }
711
712 #[test]
713 fn test_new_from_strings() {
714 let keys = vec!["a", "b", "c", "d", "e", "f", "g", "h"];
715 let values_data = UInt32Array::from(vec![0u32, 10, 20, 30, 40, 50, 60, 70]);
716
717 let entry_offsets = [0, 3, 6, 8];
720
721 let map_array =
722 MapArray::new_from_strings(keys.clone().into_iter(), &values_data, &entry_offsets)
723 .unwrap();
724
725 assert_eq!(
726 &values_data,
727 map_array.values().as_primitive::<UInt32Type>()
728 );
729 assert_eq!(&DataType::UInt32, map_array.value_type());
730 assert_eq!(3, map_array.len());
731 assert_eq!(0, map_array.null_count());
732 assert_eq!(6, map_array.value_offsets()[2]);
733 assert_eq!(2, map_array.value_length(2));
734
735 let key_array = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
736 let value_array = Arc::new(UInt32Array::from(vec![0u32, 10, 20])) as ArrayRef;
737 let keys_field = Arc::new(Field::new("keys", DataType::Utf8, false));
738 let values_field = Arc::new(Field::new("values", DataType::UInt32, false));
739 let struct_array =
740 StructArray::from(vec![(keys_field, key_array), (values_field, value_array)]);
741 assert_eq!(
742 struct_array,
743 StructArray::from(map_array.value(0).into_data())
744 );
745 assert_eq!(
746 &struct_array,
747 unsafe { map_array.value_unchecked(0) }
748 .as_any()
749 .downcast_ref::<StructArray>()
750 .unwrap()
751 );
752 for i in 0..3 {
753 assert!(map_array.is_valid(i));
754 assert!(!map_array.is_null(i));
755 }
756 }
757
758 #[test]
759 fn test_try_new() {
760 let offsets = OffsetBuffer::new(vec![0, 1, 4, 5].into());
761 let fields = Fields::from(vec![
762 Field::new("key", DataType::Int32, false),
763 Field::new("values", DataType::Int32, false),
764 ]);
765 let columns = vec![
766 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
767 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
768 ];
769
770 let entries = StructArray::new(fields.clone(), columns, None);
771 let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
772
773 MapArray::new(field.clone(), offsets.clone(), entries.clone(), None, false);
774
775 let nulls = NullBuffer::new_null(3);
776 MapArray::new(field.clone(), offsets, entries.clone(), Some(nulls), false);
777
778 let nulls = NullBuffer::new_null(3);
779 let offsets = OffsetBuffer::new(vec![0, 1, 2, 4, 5].into());
780 let err = MapArray::try_new(
781 field.clone(),
782 offsets.clone(),
783 entries.clone(),
784 Some(nulls),
785 false,
786 )
787 .unwrap_err();
788
789 assert_eq!(
790 err.to_string(),
791 "Invalid argument error: Incorrect length of null buffer for MapArray, expected 4 got 3"
792 );
793
794 let err = MapArray::try_new(field, offsets.clone(), entries.slice(0, 2), None, false)
795 .unwrap_err();
796
797 assert_eq!(
798 err.to_string(),
799 "Invalid argument error: Max offset of 5 exceeds length of entries 2"
800 );
801
802 let field = Arc::new(Field::new("element", DataType::Int64, false));
803 let err = MapArray::try_new(field, offsets.clone(), entries, None, false)
804 .unwrap_err()
805 .to_string();
806
807 assert!(
808 err.starts_with("Invalid argument error: MapArray expected data type Int64 got Struct"),
809 "{err}"
810 );
811
812 let fields = Fields::from(vec![
813 Field::new("a", DataType::Int32, false),
814 Field::new("b", DataType::Int32, false),
815 Field::new("c", DataType::Int32, false),
816 ]);
817 let columns = vec![
818 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
819 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
820 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
821 ];
822
823 let s = StructArray::new(fields.clone(), columns, None);
824 let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
825 let err = MapArray::try_new(field, offsets, s, None, false).unwrap_err();
826
827 assert_eq!(
828 err.to_string(),
829 "Invalid argument error: MapArray entries must contain two children, got 3"
830 );
831 }
832}