Path: blob/main/crates/polars-arrow/src/array/list/mod.rs
6939 views
use super::specification::try_check_offsets_bounds;1use super::{Array, Splitable, new_empty_array};2use crate::bitmap::Bitmap;3use crate::datatypes::{ArrowDataType, Field};4use crate::offset::{Offset, Offsets, OffsetsBuffer};56mod builder;7pub use builder::*;8mod ffi;9pub(super) mod fmt;10mod iterator;11pub use iterator::*;12mod mutable;13pub use mutable::*;14use polars_error::{PolarsResult, polars_bail};15use polars_utils::pl_str::PlSmallStr;16#[cfg(feature = "proptest")]17pub mod proptest;1819/// Name used for the values array within List/FixedSizeList arrays.20pub const LIST_VALUES_NAME: PlSmallStr = PlSmallStr::from_static("item");2122/// An [`Array`] semantically equivalent to `Vec<Option<Vec<Option<T>>>>` with Arrow's in-memory.23#[derive(Clone)]24pub struct ListArray<O: Offset> {25dtype: ArrowDataType,26offsets: OffsetsBuffer<O>,27values: Box<dyn Array>,28validity: Option<Bitmap>,29}3031impl<O: Offset> ListArray<O> {32/// Creates a new [`ListArray`].33///34/// # Errors35/// This function returns an error iff:36/// * `offsets.last()` is greater than `values.len()`.37/// * the validity's length is not equal to `offsets.len_proxy()`.38/// * The `dtype`'s [`crate::datatypes::PhysicalType`] is not equal to either [`crate::datatypes::PhysicalType::List`] or [`crate::datatypes::PhysicalType::LargeList`].39/// * The `dtype`'s inner field's data type is not equal to `values.dtype`.40/// # Implementation41/// This function is `O(1)`42pub fn try_new(43dtype: ArrowDataType,44offsets: OffsetsBuffer<O>,45values: Box<dyn Array>,46validity: Option<Bitmap>,47) -> PolarsResult<Self> {48try_check_offsets_bounds(&offsets, values.len())?;4950if validity51.as_ref()52.is_some_and(|validity| validity.len() != offsets.len_proxy())53{54polars_bail!(ComputeError: "validity mask length must match the number of values")55}5657let child_dtype = Self::try_get_child(&dtype)?.dtype();58let values_dtype = values.dtype();59if child_dtype != values_dtype {60polars_bail!(ComputeError: "ListArray's child's DataType must match. However, the expected DataType is {child_dtype:?} while it got {values_dtype:?}.");61}6263Ok(Self {64dtype,65offsets,66values,67validity,68})69}7071/// Creates a new [`ListArray`].72///73/// # Panics74/// This function panics iff:75/// * `offsets.last()` is greater than `values.len()`.76/// * the validity's length is not equal to `offsets.len_proxy()`.77/// * The `dtype`'s [`crate::datatypes::PhysicalType`] is not equal to either [`crate::datatypes::PhysicalType::List`] or [`crate::datatypes::PhysicalType::LargeList`].78/// * The `dtype`'s inner field's data type is not equal to `values.dtype`.79/// # Implementation80/// This function is `O(1)`81pub fn new(82dtype: ArrowDataType,83offsets: OffsetsBuffer<O>,84values: Box<dyn Array>,85validity: Option<Bitmap>,86) -> Self {87Self::try_new(dtype, offsets, values, validity).unwrap()88}8990/// Returns a new empty [`ListArray`].91pub fn new_empty(dtype: ArrowDataType) -> Self {92let values = new_empty_array(Self::get_child_type(&dtype).clone());93Self::new(dtype, OffsetsBuffer::default(), values, None)94}9596/// Returns a new null [`ListArray`].97#[inline]98pub fn new_null(dtype: ArrowDataType, length: usize) -> Self {99let child = Self::get_child_type(&dtype).clone();100Self::new(101dtype,102Offsets::new_zeroed(length).into(),103new_empty_array(child),104Some(Bitmap::new_zeroed(length)),105)106}107}108109impl<O: Offset> ListArray<O> {110/// Slices this [`ListArray`].111/// # Panics112/// panics iff `offset + length > self.len()`113pub fn slice(&mut self, offset: usize, length: usize) {114assert!(115offset + length <= self.len(),116"the offset of the new Buffer cannot exceed the existing length"117);118unsafe { self.slice_unchecked(offset, length) }119}120121/// Slices this [`ListArray`].122///123/// # Safety124/// The caller must ensure that `offset + length < self.len()`.125pub unsafe fn slice_unchecked(&mut self, offset: usize, length: usize) {126self.validity = self127.validity128.take()129.map(|bitmap| bitmap.sliced_unchecked(offset, length))130.filter(|bitmap| bitmap.unset_bits() > 0);131self.offsets.slice_unchecked(offset, length + 1);132}133134impl_sliced!();135impl_mut_validity!();136impl_into_array!();137}138139// Accessors140impl<O: Offset> ListArray<O> {141/// Returns the length of this array142#[inline]143pub fn len(&self) -> usize {144self.offsets.len_proxy()145}146147/// Returns the element at index `i`148/// # Panic149/// Panics iff `i >= self.len()`150#[inline]151pub fn value(&self, i: usize) -> Box<dyn Array> {152assert!(i < self.len());153// SAFETY: invariant of this function154unsafe { self.value_unchecked(i) }155}156157/// Returns the element at index `i` as &str158///159/// # Safety160/// Assumes that the `i < self.len`.161#[inline]162pub unsafe fn value_unchecked(&self, i: usize) -> Box<dyn Array> {163// SAFETY: the invariant of the function164let (start, end) = self.offsets.start_end_unchecked(i);165let length = end - start;166167// SAFETY: the invariant of the struct168self.values.sliced_unchecked(start, length)169}170171/// The optional validity.172#[inline]173pub fn validity(&self) -> Option<&Bitmap> {174self.validity.as_ref()175}176177/// The offsets [`Buffer`].178#[inline]179pub fn offsets(&self) -> &OffsetsBuffer<O> {180&self.offsets181}182183/// The values.184#[inline]185pub fn values(&self) -> &Box<dyn Array> {186&self.values187}188}189190impl<O: Offset> ListArray<O> {191/// Returns a default [`ArrowDataType`]: inner field is named "item" and is nullable192pub fn default_datatype(dtype: ArrowDataType) -> ArrowDataType {193let field = Box::new(Field::new(LIST_VALUES_NAME, dtype, true));194if O::IS_LARGE {195ArrowDataType::LargeList(field)196} else {197ArrowDataType::List(field)198}199}200201/// Returns a the inner [`Field`]202/// # Panics203/// Panics iff the logical type is not consistent with this struct.204pub fn get_child_field(dtype: &ArrowDataType) -> &Field {205Self::try_get_child(dtype).unwrap()206}207208/// Returns a the inner [`Field`]209/// # Errors210/// Panics iff the logical type is not consistent with this struct.211pub fn try_get_child(dtype: &ArrowDataType) -> PolarsResult<&Field> {212if O::IS_LARGE {213match dtype.to_logical_type() {214ArrowDataType::LargeList(child) => Ok(child.as_ref()),215_ => polars_bail!(ComputeError: "ListArray<i64> expects DataType::LargeList"),216}217} else {218match dtype.to_logical_type() {219ArrowDataType::List(child) => Ok(child.as_ref()),220_ => polars_bail!(ComputeError: "ListArray<i32> expects DataType::List"),221}222}223}224225/// Returns a the inner [`ArrowDataType`]226/// # Panics227/// Panics iff the logical type is not consistent with this struct.228pub fn get_child_type(dtype: &ArrowDataType) -> &ArrowDataType {229Self::get_child_field(dtype).dtype()230}231}232233impl<O: Offset> Array for ListArray<O> {234impl_common_array!();235236fn validity(&self) -> Option<&Bitmap> {237self.validity.as_ref()238}239240#[inline]241fn with_validity(&self, validity: Option<Bitmap>) -> Box<dyn Array> {242Box::new(self.clone().with_validity(validity))243}244}245246impl<O: Offset> Splitable for ListArray<O> {247fn check_bound(&self, offset: usize) -> bool {248offset <= self.len()249}250251unsafe fn _split_at_unchecked(&self, offset: usize) -> (Self, Self) {252let (lhs_offsets, rhs_offsets) = unsafe { self.offsets.split_at_unchecked(offset) };253let (lhs_validity, rhs_validity) = unsafe { self.validity.split_at_unchecked(offset) };254255(256Self {257dtype: self.dtype.clone(),258offsets: lhs_offsets,259validity: lhs_validity,260values: self.values.clone(),261},262Self {263dtype: self.dtype.clone(),264offsets: rhs_offsets,265validity: rhs_validity,266values: self.values.clone(),267},268)269}270}271272273