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
364unsafe impl Array for MapArray {
366 fn as_any(&self) -> &dyn Any {
367 self
368 }
369
370 fn to_data(&self) -> ArrayData {
371 self.clone().into_data()
372 }
373
374 fn into_data(self) -> ArrayData {
375 self.into()
376 }
377
378 fn data_type(&self) -> &DataType {
379 &self.data_type
380 }
381
382 fn slice(&self, offset: usize, length: usize) -> ArrayRef {
383 Arc::new(self.slice(offset, length))
384 }
385
386 fn len(&self) -> usize {
387 self.value_offsets.len() - 1
388 }
389
390 fn is_empty(&self) -> bool {
391 self.value_offsets.len() <= 1
392 }
393
394 fn shrink_to_fit(&mut self) {
395 if let Some(nulls) = &mut self.nulls {
396 nulls.shrink_to_fit();
397 }
398 self.entries.shrink_to_fit();
399 self.value_offsets.shrink_to_fit();
400 }
401
402 fn offset(&self) -> usize {
403 0
404 }
405
406 fn nulls(&self) -> Option<&NullBuffer> {
407 self.nulls.as_ref()
408 }
409
410 fn logical_null_count(&self) -> usize {
411 self.null_count()
413 }
414
415 fn get_buffer_memory_size(&self) -> usize {
416 let mut size = self.entries.get_buffer_memory_size();
417 size += self.value_offsets.inner().inner().capacity();
418 if let Some(n) = self.nulls.as_ref() {
419 size += n.buffer().capacity();
420 }
421 size
422 }
423
424 fn get_array_memory_size(&self) -> usize {
425 let mut size = std::mem::size_of::<Self>() + self.entries.get_array_memory_size();
426 size += self.value_offsets.inner().inner().capacity();
427 if let Some(n) = self.nulls.as_ref() {
428 size += n.buffer().capacity();
429 }
430 size
431 }
432}
433
434impl ArrayAccessor for &MapArray {
435 type Item = StructArray;
436
437 fn value(&self, index: usize) -> Self::Item {
438 MapArray::value(self, index)
439 }
440
441 unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
442 MapArray::value(self, index)
443 }
444}
445
446impl std::fmt::Debug for MapArray {
447 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
448 write!(f, "MapArray\n[\n")?;
449 print_long_array(self, f, |array, index, f| {
450 std::fmt::Debug::fmt(&array.value(index), f)
451 })?;
452 write!(f, "]")
453 }
454}
455
456impl From<MapArray> for ListArray {
457 fn from(value: MapArray) -> Self {
458 let field = match value.data_type() {
459 DataType::Map(field, _) => field,
460 _ => unreachable!("This should be a map type."),
461 };
462 let data_type = DataType::List(field.clone());
463 let builder = value.into_data().into_builder().data_type(data_type);
464 let array_data = unsafe { builder.build_unchecked() };
465
466 ListArray::from(array_data)
467 }
468}
469
470#[cfg(test)]
471mod tests {
472 use crate::cast::AsArray;
473 use crate::types::UInt32Type;
474 use crate::{Int32Array, UInt32Array};
475 use arrow_schema::Fields;
476
477 use super::*;
478
479 fn create_from_buffers() -> MapArray {
480 let keys_data = ArrayData::builder(DataType::Int32)
482 .len(8)
483 .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
484 .build()
485 .unwrap();
486 let values_data = ArrayData::builder(DataType::UInt32)
487 .len(8)
488 .add_buffer(Buffer::from(
489 [0u32, 10, 20, 30, 40, 50, 60, 70].to_byte_slice(),
490 ))
491 .build()
492 .unwrap();
493
494 let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
497
498 let keys = Arc::new(Field::new("keys", DataType::Int32, false));
499 let values = Arc::new(Field::new("values", DataType::UInt32, false));
500 let entry_struct = StructArray::from(vec![
501 (keys, make_array(keys_data)),
502 (values, make_array(values_data)),
503 ]);
504
505 let map_data_type = DataType::Map(
507 Arc::new(Field::new(
508 "entries",
509 entry_struct.data_type().clone(),
510 false,
511 )),
512 false,
513 );
514 let map_data = ArrayData::builder(map_data_type)
515 .len(3)
516 .add_buffer(entry_offsets)
517 .add_child_data(entry_struct.into_data())
518 .build()
519 .unwrap();
520 MapArray::from(map_data)
521 }
522
523 #[test]
524 fn test_map_array() {
525 let key_data = ArrayData::builder(DataType::Int32)
527 .len(8)
528 .add_buffer(Buffer::from([0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
529 .build()
530 .unwrap();
531 let value_data = ArrayData::builder(DataType::UInt32)
532 .len(8)
533 .add_buffer(Buffer::from(
534 [0u32, 10, 20, 0, 40, 0, 60, 70].to_byte_slice(),
535 ))
536 .null_bit_buffer(Some(Buffer::from(&[0b11010110])))
537 .build()
538 .unwrap();
539
540 let entry_offsets = Buffer::from([0, 3, 6, 8].to_byte_slice());
543
544 let keys_field = Arc::new(Field::new("keys", DataType::Int32, false));
545 let values_field = Arc::new(Field::new("values", DataType::UInt32, true));
546 let entry_struct = StructArray::from(vec![
547 (keys_field.clone(), make_array(key_data)),
548 (values_field.clone(), make_array(value_data.clone())),
549 ]);
550
551 let map_data_type = DataType::Map(
553 Arc::new(Field::new(
554 "entries",
555 entry_struct.data_type().clone(),
556 false,
557 )),
558 false,
559 );
560 let map_data = ArrayData::builder(map_data_type)
561 .len(3)
562 .add_buffer(entry_offsets)
563 .add_child_data(entry_struct.into_data())
564 .build()
565 .unwrap();
566 let map_array = MapArray::from(map_data);
567
568 assert_eq!(value_data, map_array.values().to_data());
569 assert_eq!(&DataType::UInt32, map_array.value_type());
570 assert_eq!(3, map_array.len());
571 assert_eq!(0, map_array.null_count());
572 assert_eq!(6, map_array.value_offsets()[2]);
573 assert_eq!(2, map_array.value_length(2));
574
575 let key_array = Arc::new(Int32Array::from(vec![0, 1, 2])) as ArrayRef;
576 let value_array =
577 Arc::new(UInt32Array::from(vec![None, Some(10u32), Some(20)])) as ArrayRef;
578 let struct_array = StructArray::from(vec![
579 (keys_field.clone(), key_array),
580 (values_field.clone(), value_array),
581 ]);
582 assert_eq!(
583 struct_array,
584 StructArray::from(map_array.value(0).into_data())
585 );
586 assert_eq!(
587 &struct_array,
588 unsafe { map_array.value_unchecked(0) }
589 .as_any()
590 .downcast_ref::<StructArray>()
591 .unwrap()
592 );
593 for i in 0..3 {
594 assert!(map_array.is_valid(i));
595 assert!(!map_array.is_null(i));
596 }
597
598 let map_array = map_array.slice(1, 2);
600
601 assert_eq!(value_data, map_array.values().to_data());
602 assert_eq!(&DataType::UInt32, map_array.value_type());
603 assert_eq!(2, map_array.len());
604 assert_eq!(0, map_array.null_count());
605 assert_eq!(6, map_array.value_offsets()[1]);
606 assert_eq!(2, map_array.value_length(1));
607
608 let key_array = Arc::new(Int32Array::from(vec![3, 4, 5])) as ArrayRef;
609 let value_array = Arc::new(UInt32Array::from(vec![None, Some(40), None])) as ArrayRef;
610 let struct_array =
611 StructArray::from(vec![(keys_field, key_array), (values_field, value_array)]);
612 assert_eq!(
613 &struct_array,
614 map_array
615 .value(0)
616 .as_any()
617 .downcast_ref::<StructArray>()
618 .unwrap()
619 );
620 assert_eq!(
621 &struct_array,
622 unsafe { map_array.value_unchecked(0) }
623 .as_any()
624 .downcast_ref::<StructArray>()
625 .unwrap()
626 );
627 }
628
629 #[test]
630 #[ignore = "Test fails because slice of <list<struct>> is still buggy"]
631 fn test_map_array_slice() {
632 let map_array = create_from_buffers();
633
634 let sliced_array = map_array.slice(1, 2);
635 assert_eq!(2, sliced_array.len());
636 assert_eq!(1, sliced_array.offset());
637 let sliced_array_data = sliced_array.to_data();
638 for array_data in sliced_array_data.child_data() {
639 assert_eq!(array_data.offset(), 1);
640 }
641
642 let sliced_map_array = sliced_array.as_any().downcast_ref::<MapArray>().unwrap();
644 assert_eq!(3, sliced_map_array.value_offsets()[0]);
645 assert_eq!(3, sliced_map_array.value_length(0));
646 assert_eq!(6, sliced_map_array.value_offsets()[1]);
647 assert_eq!(2, sliced_map_array.value_length(1));
648
649 let keys_data = ArrayData::builder(DataType::Int32)
651 .len(5)
652 .add_buffer(Buffer::from([3, 4, 5, 6, 7].to_byte_slice()))
653 .build()
654 .unwrap();
655 let values_data = ArrayData::builder(DataType::UInt32)
656 .len(5)
657 .add_buffer(Buffer::from([30u32, 40, 50, 60, 70].to_byte_slice()))
658 .build()
659 .unwrap();
660
661 let entry_offsets = Buffer::from([0, 3, 5].to_byte_slice());
664
665 let keys = Arc::new(Field::new("keys", DataType::Int32, false));
666 let values = Arc::new(Field::new("values", DataType::UInt32, false));
667 let entry_struct = StructArray::from(vec![
668 (keys, make_array(keys_data)),
669 (values, make_array(values_data)),
670 ]);
671
672 let map_data_type = DataType::Map(
674 Arc::new(Field::new(
675 "entries",
676 entry_struct.data_type().clone(),
677 false,
678 )),
679 false,
680 );
681 let expected_map_data = ArrayData::builder(map_data_type)
682 .len(2)
683 .add_buffer(entry_offsets)
684 .add_child_data(entry_struct.into_data())
685 .build()
686 .unwrap();
687 let expected_map_array = MapArray::from(expected_map_data);
688
689 assert_eq!(&expected_map_array, sliced_map_array)
690 }
691
692 #[test]
693 #[should_panic(expected = "index out of bounds: the len is ")]
694 fn test_map_array_index_out_of_bound() {
695 let map_array = create_from_buffers();
696
697 map_array.value(map_array.len());
698 }
699
700 #[test]
701 #[should_panic(expected = "MapArray expected ArrayData with DataType::Map got Dictionary")]
702 fn test_from_array_data_validation() {
703 let struct_t = DataType::Struct(Fields::from(vec![
706 Field::new("keys", DataType::Int32, true),
707 Field::new("values", DataType::UInt32, true),
708 ]));
709 let dict_t = DataType::Dictionary(Box::new(DataType::Int32), Box::new(struct_t));
710 let _ = MapArray::from(ArrayData::new_empty(&dict_t));
711 }
712
713 #[test]
714 fn test_new_from_strings() {
715 let keys = vec!["a", "b", "c", "d", "e", "f", "g", "h"];
716 let values_data = UInt32Array::from(vec![0u32, 10, 20, 30, 40, 50, 60, 70]);
717
718 let entry_offsets = [0, 3, 6, 8];
721
722 let map_array =
723 MapArray::new_from_strings(keys.clone().into_iter(), &values_data, &entry_offsets)
724 .unwrap();
725
726 assert_eq!(
727 &values_data,
728 map_array.values().as_primitive::<UInt32Type>()
729 );
730 assert_eq!(&DataType::UInt32, map_array.value_type());
731 assert_eq!(3, map_array.len());
732 assert_eq!(0, map_array.null_count());
733 assert_eq!(6, map_array.value_offsets()[2]);
734 assert_eq!(2, map_array.value_length(2));
735
736 let key_array = Arc::new(StringArray::from(vec!["a", "b", "c"])) as ArrayRef;
737 let value_array = Arc::new(UInt32Array::from(vec![0u32, 10, 20])) as ArrayRef;
738 let keys_field = Arc::new(Field::new("keys", DataType::Utf8, false));
739 let values_field = Arc::new(Field::new("values", DataType::UInt32, false));
740 let struct_array =
741 StructArray::from(vec![(keys_field, key_array), (values_field, value_array)]);
742 assert_eq!(
743 struct_array,
744 StructArray::from(map_array.value(0).into_data())
745 );
746 assert_eq!(
747 &struct_array,
748 unsafe { map_array.value_unchecked(0) }
749 .as_any()
750 .downcast_ref::<StructArray>()
751 .unwrap()
752 );
753 for i in 0..3 {
754 assert!(map_array.is_valid(i));
755 assert!(!map_array.is_null(i));
756 }
757 }
758
759 #[test]
760 fn test_try_new() {
761 let offsets = OffsetBuffer::new(vec![0, 1, 4, 5].into());
762 let fields = Fields::from(vec![
763 Field::new("key", DataType::Int32, false),
764 Field::new("values", DataType::Int32, false),
765 ]);
766 let columns = vec![
767 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
768 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
769 ];
770
771 let entries = StructArray::new(fields.clone(), columns, None);
772 let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
773
774 MapArray::new(field.clone(), offsets.clone(), entries.clone(), None, false);
775
776 let nulls = NullBuffer::new_null(3);
777 MapArray::new(field.clone(), offsets, entries.clone(), Some(nulls), false);
778
779 let nulls = NullBuffer::new_null(3);
780 let offsets = OffsetBuffer::new(vec![0, 1, 2, 4, 5].into());
781 let err = MapArray::try_new(
782 field.clone(),
783 offsets.clone(),
784 entries.clone(),
785 Some(nulls),
786 false,
787 )
788 .unwrap_err();
789
790 assert_eq!(
791 err.to_string(),
792 "Invalid argument error: Incorrect length of null buffer for MapArray, expected 4 got 3"
793 );
794
795 let err = MapArray::try_new(field, offsets.clone(), entries.slice(0, 2), None, false)
796 .unwrap_err();
797
798 assert_eq!(
799 err.to_string(),
800 "Invalid argument error: Max offset of 5 exceeds length of entries 2"
801 );
802
803 let field = Arc::new(Field::new("element", DataType::Int64, false));
804 let err = MapArray::try_new(field, offsets.clone(), entries, None, false)
805 .unwrap_err()
806 .to_string();
807
808 assert!(
809 err.starts_with("Invalid argument error: MapArray expected data type Int64 got Struct"),
810 "{err}"
811 );
812
813 let fields = Fields::from(vec![
814 Field::new("a", DataType::Int32, false),
815 Field::new("b", DataType::Int32, false),
816 Field::new("c", DataType::Int32, false),
817 ]);
818 let columns = vec![
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 Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as _,
822 ];
823
824 let s = StructArray::new(fields.clone(), columns, None);
825 let field = Arc::new(Field::new("entries", DataType::Struct(fields), false));
826 let err = MapArray::try_new(field, offsets, s, None, false).unwrap_err();
827
828 assert_eq!(
829 err.to_string(),
830 "Invalid argument error: MapArray entries must contain two children, got 3"
831 );
832 }
833}