This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-11912-a1e8df8214ee95f9f0aa14c7efaebeefe7ada69d in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
commit 2be63535ed0a7f47439bee51c03b90949bfae00b Author: RIchard Baah <[email protected]> AuthorDate: Fri Nov 6 01:53:42 2026 +0000 Use fallible MutableBuffer methods in fallible APIs (#11912) # Which issue does this PR address? Part of #11900. The fallible `MutableArrayData` extension work remains split into #11973 and #11986. # Rationale for this change Several `Result`-returning paths still used infallible `MutableBuffer` allocation or growth, so oversized outputs and allocation failures could panic instead of reaching the caller as an error. # What changes are included in this PR? Array construction, row decoding, selection and string kernels, and the Parquet fixed-size-list reader now use fallible allocation with checked size arithmetic. Once capacity has been reserved successfully, pre-sized hot loops keep their existing unchecked or infallible writes rather than repeating capacity checks for every value. `MutableArrayData` construction is made fallible here; its extension implementation and type-specific callers remain in the follow-up PRs. # Are these changes tested? The added tests cover overflow in buffer sizes, offsets, and `MutableArrayData` construction. # Are there any significant user-facing changes? Fallible APIs return allocation and overflow errors in cases that previously panicked. Existing infallible APIs keep their panic behavior. --- arrow-arith/src/arity.rs | 6 +- arrow-array/src/array/fixed_size_binary_array.rs | 30 +++-- arrow-array/src/ffi.rs | 8 +- arrow-buffer/src/buffer/null.rs | 10 +- arrow-buffer/src/buffer/offset.rs | 11 +- arrow-cast/src/cast/list.rs | 32 ++++-- arrow-data/src/data.rs | 105 ++++++++++++------ arrow-data/src/transform/mod.rs | 123 ++++++++++++++------- arrow-row/src/fixed.rs | 49 +++++--- arrow-row/src/lib.rs | 18 +-- arrow-row/src/list.rs | 9 +- arrow-row/src/variable.rs | 38 ++++--- arrow-select/src/concat.rs | 55 ++++++--- arrow-select/src/filter.rs | 39 ++++--- arrow-select/src/interleave.rs | 32 +++--- arrow-select/src/take.rs | 55 ++++++--- arrow-select/src/union_extract.rs | 29 +++-- arrow-select/src/zip.rs | 16 ++- arrow-string/src/concat_elements.rs | 17 +-- arrow-string/src/substring.rs | 33 ++---- .../arrow/array_reader/fixed_size_list_array.rs | 17 ++- 21 files changed, 473 insertions(+), 259 deletions(-) diff --git a/arrow-arith/src/arity.rs b/arrow-arith/src/arity.rs index 816576fbd5..772b834fb8 100644 --- a/arrow-arith/src/arity.rs +++ b/arrow-arith/src/arity.rs @@ -377,7 +377,11 @@ where O: ArrowPrimitiveType, F: Fn(A::Item, B::Item) -> Result<O::Native, ArrowError>, { - let mut buffer = MutableBuffer::new(len * O::Native::get_byte_width()); + let capacity = len + .checked_mul(O::Native::get_byte_width()) + .ok_or_else(|| ArrowError::MemoryError("binary output size overflow".to_string()))?; + let mut buffer = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; for idx in 0..len { unsafe { buffer.push_unchecked(op(a.value_unchecked(idx), b.value_unchecked(idx))?); diff --git a/arrow-array/src/array/fixed_size_binary_array.rs b/arrow-array/src/array/fixed_size_binary_array.rs index b21862e937..cb14445b7a 100644 --- a/arrow-array/src/array/fixed_size_binary_array.rs +++ b/arrow-array/src/array/fixed_size_binary_array.rs @@ -527,7 +527,10 @@ impl FixedSizeBinaryArray { /// /// # Errors /// - /// Returns error if argument has length zero, or sizes of nested slices don't match. + /// - `value_length` is negative + /// - A byte slice has a different length + /// - Size arithmetic overflows + /// - Buffer allocation fails pub fn try_from_sparse_iter_with_size<T, U>( mut iter: T, value_length: i32, @@ -545,18 +548,22 @@ impl FixedSizeBinaryArray { let mut byte = 0; let iter_size_hint = iter.size_hint().0; - let mut null_buf = MutableBuffer::new(bit_util::ceil(iter_size_hint, 8)); + let mut null_buf = MutableBuffer::try_with_capacity(bit_util::ceil(iter_size_hint, 8)) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let capacity = iter_size_hint.checked_mul(value_size).ok_or_else(|| { ArrowError::InvalidArgumentError(format!( "FixedSizeBinaryArray error: value size {value_size} * len hint {iter_size_hint} exceeds usize" )) })?; - let mut buffer = MutableBuffer::new(capacity); + let mut buffer = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; iter.try_for_each(|item| -> Result<(), ArrowError> { // extend null bitmask by one byte per each 8 items if byte == 0 { - null_buf.push(0u8); + null_buf + .try_extend_from_slice(&[0u8]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; byte = 8; } byte -= 1; @@ -572,9 +579,13 @@ impl FixedSizeBinaryArray { } bit_util::set_bit(null_buf.as_slice_mut(), len); - buffer.extend_from_slice(slice); + buffer + .try_extend_from_slice(slice) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; } else { - buffer.extend_zeros(value_size); + buffer + .try_extend_zeros(value_size) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; } len += 1; @@ -609,7 +620,10 @@ impl FixedSizeBinaryArray { /// /// # Errors /// - /// Returns error if argument has length zero, or sizes of nested slices don't match. + /// - The iterator is empty + /// - The byte slices have different lengths + /// - The value length exceeds `i32` + /// - Buffer allocation fails pub fn try_from_iter<T, U>(mut iter: T) -> Result<Self, ArrowError> where T: Iterator<Item = U>, @@ -618,7 +632,7 @@ impl FixedSizeBinaryArray { let mut len = 0; let mut value_size = None; let iter_size_hint = iter.size_hint().0; - let mut buffer = MutableBuffer::new(0); + let mut buffer = MutableBuffer::default(); iter.try_for_each(|item| -> Result<(), ArrowError> { let slice = item.as_ref(); diff --git a/arrow-array/src/ffi.rs b/arrow-array/src/ffi.rs index 5eeb576687..a84d3cb47f 100644 --- a/arrow-array/src/ffi.rs +++ b/arrow-array/src/ffi.rs @@ -291,7 +291,9 @@ impl ImportedArrowArray<'_> { DataType::Utf8 | DataType::Binary | DataType::LargeUtf8 | DataType::LargeBinary ) { - buffers[0] = MutableBuffer::from_len_zeroed(buffers[0].len()).into(); + buffers[0] = MutableBuffer::try_from_len_zeroed(buffers[0].len()) + .map_err(|e| ArrowError::MemoryError(e.to_string()))? + .into(); } let null_bit_buffer = if data_layout.can_contain_null_mask { @@ -409,7 +411,7 @@ impl ImportedArrowArray<'_> { // if the length is incorrect, we cannot create a correct buffer even if // the pointer is valid. if buf.is_empty() { - Ok(MutableBuffer::new(0).into()) + Ok(MutableBuffer::default().into()) } else { Ok(buf) } @@ -417,7 +419,7 @@ impl ImportedArrowArray<'_> { None if len == 0 => { // Null data buffer, which Rust doesn't allow. So create // an empty buffer. - Ok(MutableBuffer::new(0).into()) + Ok(MutableBuffer::default().into()) } None => Err(ArrowError::CDataInterface(format!( "The external buffer at position {index} is null." diff --git a/arrow-buffer/src/buffer/null.rs b/arrow-buffer/src/buffer/null.rs index 12be64a87a..48f385f0e8 100644 --- a/arrow-buffer/src/buffer/null.rs +++ b/arrow-buffer/src/buffer/null.rs @@ -3,6 +3,7 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use crate::bit_iterator::{BitIndexIterator, BitIterator, BitSliceIterator}; +use crate::bit_util; use crate::buffer::BooleanBuffer; use crate::{Buffer, MutableBuffer, OverflowError}; @@ -108,7 +109,8 @@ impl NullBuffer { /// /// # Panics /// - /// Panics if `self.len() * count` overflows `usize`. + /// Panics if `self.len() * count` overflows `usize` or if the required + /// buffer cannot be allocated. /// Use [`Self::try_expand`] for a fallible version. pub fn expand(&self, count: usize) -> Self { self.try_expand(count).unwrap_or_else(|err| panic!("{err}")) @@ -120,14 +122,16 @@ impl NullBuffer { /// /// # Errors /// - /// Errors if `self.len() * count` overflows `usize` + /// Errors if `self.len() * count` overflows `usize` or if the required + /// buffer cannot be allocated. pub fn try_expand(&self, count: usize) -> Result<Self, OverflowError> { let capacity = self .buffer .len() .checked_mul(count) .ok_or_else(|| OverflowError::new::<usize>("buffer length"))?; - let mut buffer = MutableBuffer::new_null(capacity); + let mut buffer = MutableBuffer::try_from_len_zeroed(bit_util::ceil(capacity, 8)) + .map_err(|_| OverflowError::new::<usize>("buffer length"))?; if count.is_multiple_of(8) { // When count is a multiple of 8 every expanded run starts on a byte diff --git a/arrow-buffer/src/buffer/offset.rs b/arrow-buffer/src/buffer/offset.rs index 49b9f9281d..fa7df6e95d 100644 --- a/arrow-buffer/src/buffer/offset.rs +++ b/arrow-buffer/src/buffer/offset.rs @@ -85,7 +85,8 @@ impl<O: ArrowNativeType> OffsetBuffer<O> { /// /// # Panics /// - /// Panics if `(len + 1) * size_of::<O>()` overflows `usize`. + /// Panics if `(len + 1) * size_of::<O>()` overflows `usize` or if the + /// required buffer cannot be allocated. /// Use [`Self::try_new_zeroed`] for a fallible version. pub fn new_zeroed(len: usize) -> Self { Self::try_new_zeroed(len).unwrap_or_else(|err| panic!("{err}")) @@ -95,13 +96,15 @@ impl<O: ArrowNativeType> OffsetBuffer<O> { /// /// # Errors /// - /// Errors if `(len + 1) * size_of::<O>()` overflows `usize` + /// Errors if `(len + 1) * size_of::<O>()` overflows `usize` or if the + /// required buffer cannot be allocated. pub fn try_new_zeroed(len: usize) -> Result<Self, OverflowError> { let len_bytes = len .checked_add(1) .and_then(|o| o.checked_mul(std::mem::size_of::<O>())) .ok_or_else(|| OverflowError::new::<usize>("buffer length"))?; - let buffer = MutableBuffer::from_len_zeroed(len_bytes); + let buffer = MutableBuffer::try_from_len_zeroed(len_bytes) + .map_err(|_| OverflowError::new::<usize>("buffer length"))?; Ok(Self(buffer.into_buffer().into())) } @@ -568,6 +571,8 @@ mod tests { .to_string(), "buffer length overflow: does not fit in usize" ); + let max_layout_len = isize::MAX as usize / std::mem::size_of::<i64>(); + assert!(OffsetBuffer::<i64>::try_new_zeroed(max_layout_len).is_err()); assert_eq!( OffsetBuffer::<i32>::try_new_zeroed(3).unwrap().as_ref(), &[0; 4] diff --git a/arrow-cast/src/cast/list.rs b/arrow-cast/src/cast/list.rs index a825582cd6..0f1ec3f750 100644 --- a/arrow-cast/src/cast/list.rs +++ b/arrow-cast/src/cast/list.rs @@ -129,7 +129,15 @@ where { let array = array.as_list::<OffsetSize>(); - let cap = array.len() * size as usize; + let size_usize = usize::try_from(size).map_err(|_| { + ArrowError::CastError(format!( + "Cannot cast to FixedSizeList({size}): size must be non-negative" + )) + })?; + let cap = array + .len() + .checked_mul(size_usize) + .ok_or_else(|| ArrowError::MemoryError("fixed-size list capacity overflow".into()))?; let mut null_builder = NullBufferBuilder::new(array.len()); if let Some(nulls) = array.nulls().filter(|b| b.null_count() > 0) { @@ -142,7 +150,7 @@ where let nullable = cast_options.safe || array.null_count() != 0; // Nulls in FixedSizeListArray take up space and so we must pad the values let values = array.values().to_data(); - let mut mutable = MutableArrayData::new(vec![&values], nullable, cap); + let mut mutable = MutableArrayData::try_new(vec![&values], nullable, cap)?; let first_pos = array.offsets()[0].as_usize(); // The end position in values of the last incorrectly-sized list slice, // or None if no padding has been needed (including for empty slices). @@ -153,7 +161,7 @@ where let end_pos = w[1].as_usize(); let len = end_pos - start_pos; - if len != size as usize { + if len != size_usize { if cast_options.safe || array.is_null(idx) { let copy_start = last_pos.unwrap_or(first_pos); if copy_start != start_pos { @@ -164,7 +172,7 @@ where } // Pad this slice with nulls mutable - .try_extend_nulls(size as _) + .try_extend_nulls(size_usize) .map_err(|e| ArrowError::CastError(e.to_string()))?; null_builder.set_bit(idx, false); // Set last_pos to the end of this slice's values @@ -223,18 +231,26 @@ pub(crate) fn cast_list_view_to_fixed_size_list<O: OffsetSizeTrait>( let nullable = cast_options.safe || array.null_count() != 0; let values = array.values().to_data(); - let cap = array.len() * size as usize; - let mut mutable = MutableArrayData::new(vec![&values], nullable, cap); + let size_usize = usize::try_from(size).map_err(|_| { + ArrowError::CastError(format!( + "Cannot cast to FixedSizeList({size}): size must be non-negative" + )) + })?; + let cap = array + .len() + .checked_mul(size_usize) + .ok_or_else(|| ArrowError::MemoryError("fixed-size list capacity overflow".into()))?; + let mut mutable = MutableArrayData::try_new(vec![&values], nullable, cap)?; for idx in 0..array.len() { let offset = array.value_offset(idx).as_usize(); let len = array.value_size(idx).as_usize(); - if len != size as usize { + if len != size_usize { // Nulls in FixedSizeListArray take up space and so we must pad the values if cast_options.safe || array.is_null(idx) { mutable - .try_extend_nulls(size as _) + .try_extend_nulls(size_usize) .map_err(|e| ArrowError::CastError(e.to_string()))?; null_builder.set_bit(idx, false); } else { diff --git a/arrow-data/src/data.rs b/arrow-data/src/data.rs index 59aa855c2b..cc30a9557a 100644 --- a/arrow-data/src/data.rs +++ b/arrow-data/src/data.rs @@ -48,16 +48,27 @@ pub(crate) fn count_nulls( } } -/// creates 2 [`MutableBuffer`]s with a given `capacity` (in slots). +/// Creates 2 [`MutableBuffer`]s with a given `capacity` (in slots). #[inline] -pub(crate) fn new_buffers(data_type: &DataType, capacity: usize) -> [MutableBuffer; 2] { - let empty_buffer = MutableBuffer::new(0); - match data_type { - DataType::Null => [empty_buffer, MutableBuffer::new(0)], +pub(crate) fn new_buffers( + data_type: &DataType, + capacity: usize, +) -> Result<[MutableBuffer; 2], ArrowError> { + let new_buffer = |len| { + MutableBuffer::try_with_capacity(len).map_err(|e| ArrowError::MemoryError(e.to_string())) + }; + let sized_buffer = |width: usize| { + let len = capacity + .checked_mul(width) + .ok_or_else(|| ArrowError::MemoryError("buffer size overflow".into()))?; + new_buffer(len) + }; + + Ok(match data_type { + DataType::Null => [MutableBuffer::default(), MutableBuffer::default()], DataType::Boolean => { let bytes = bit_util::ceil(capacity, 8); - let buffer = MutableBuffer::new(bytes); - [buffer, empty_buffer] + [new_buffer(bytes)?, MutableBuffer::default()] } DataType::UInt8 | DataType::UInt16 @@ -81,69 +92,93 @@ pub(crate) fn new_buffers(data_type: &DataType, capacity: usize) -> [MutableBuff | DataType::Duration(_) | DataType::Timestamp(_, _) | DataType::Interval(_) => [ - MutableBuffer::new(capacity * data_type.primitive_width().unwrap()), - empty_buffer, + sized_buffer(data_type.primitive_width().unwrap())?, + MutableBuffer::default(), ], DataType::Utf8 | DataType::Binary => { - let mut buffer = MutableBuffer::new((1 + capacity) * mem::size_of::<i32>()); + let offset_capacity = capacity + .checked_add(1) + .and_then(|len| len.checked_mul(mem::size_of::<i32>())) + .ok_or_else(|| ArrowError::MemoryError("offset buffer size overflow".into()))?; + let mut buffer = new_buffer(offset_capacity)?; // safety: `unsafe` code assumes that this buffer is initialized with one element - buffer.push(0i32); - [buffer, MutableBuffer::new(capacity * mem::size_of::<u8>())] + buffer + .try_extend_from_slice(&[0i32]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + [buffer, sized_buffer(mem::size_of::<u8>())?] } DataType::LargeUtf8 | DataType::LargeBinary => { - let mut buffer = MutableBuffer::new((1 + capacity) * mem::size_of::<i64>()); + let offset_capacity = capacity + .checked_add(1) + .and_then(|len| len.checked_mul(mem::size_of::<i64>())) + .ok_or_else(|| ArrowError::MemoryError("offset buffer size overflow".into()))?; + let mut buffer = new_buffer(offset_capacity)?; // safety: `unsafe` code assumes that this buffer is initialized with one element - buffer.push(0i64); - [buffer, MutableBuffer::new(capacity * mem::size_of::<u8>())] + buffer + .try_extend_from_slice(&[0i64]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + [buffer, sized_buffer(mem::size_of::<u8>())?] } DataType::BinaryView | DataType::Utf8View => [ - MutableBuffer::new(capacity * mem::size_of::<u128>()), - empty_buffer, + sized_buffer(mem::size_of::<u128>())?, + MutableBuffer::default(), ], DataType::List(_) | DataType::Map(_, _) => { // offset buffer always starts with a zero - let mut buffer = MutableBuffer::new((1 + capacity) * mem::size_of::<i32>()); - buffer.push(0i32); - [buffer, empty_buffer] + let offset_capacity = capacity + .checked_add(1) + .and_then(|len| len.checked_mul(mem::size_of::<i32>())) + .ok_or_else(|| ArrowError::MemoryError("offset buffer size overflow".into()))?; + let mut buffer = new_buffer(offset_capacity)?; + buffer + .try_extend_from_slice(&[0i32]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + [buffer, MutableBuffer::default()] } DataType::ListView(_) => [ - MutableBuffer::new(capacity * mem::size_of::<i32>()), - MutableBuffer::new(capacity * mem::size_of::<i32>()), + sized_buffer(mem::size_of::<i32>())?, + sized_buffer(mem::size_of::<i32>())?, ], DataType::LargeList(_) => { // offset buffer always starts with a zero - let mut buffer = MutableBuffer::new((1 + capacity) * mem::size_of::<i64>()); - buffer.push(0i64); - [buffer, empty_buffer] + let offset_capacity = capacity + .checked_add(1) + .and_then(|len| len.checked_mul(mem::size_of::<i64>())) + .ok_or_else(|| ArrowError::MemoryError("offset buffer size overflow".into()))?; + let mut buffer = new_buffer(offset_capacity)?; + buffer + .try_extend_from_slice(&[0i64]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + [buffer, MutableBuffer::default()] } DataType::LargeListView(_) => [ - MutableBuffer::new(capacity * mem::size_of::<i64>()), - MutableBuffer::new(capacity * mem::size_of::<i64>()), + sized_buffer(mem::size_of::<i64>())?, + sized_buffer(mem::size_of::<i64>())?, ], DataType::FixedSizeBinary(size) => { if *size < 0 { panic!("cannot construct buffers from FixedSizeBinary({size})"); } - [MutableBuffer::new(capacity * *size as usize), empty_buffer] + [sized_buffer(*size as usize)?, MutableBuffer::default()] } DataType::Dictionary(k, _) => [ - MutableBuffer::new(capacity * k.primitive_width().unwrap()), - empty_buffer, + sized_buffer(k.primitive_width().unwrap())?, + MutableBuffer::default(), ], DataType::FixedSizeList(_, _) | DataType::Struct(_) | DataType::RunEndEncoded(_, _) => { - [empty_buffer, MutableBuffer::new(0)] + [MutableBuffer::default(), MutableBuffer::default()] } DataType::Union(_, mode) => { - let type_ids = MutableBuffer::new(capacity * mem::size_of::<i8>()); + let type_ids = sized_buffer(mem::size_of::<i8>())?; match mode { - UnionMode::Sparse => [type_ids, empty_buffer], + UnionMode::Sparse => [type_ids, MutableBuffer::default()], UnionMode::Dense => { - let offsets = MutableBuffer::new(capacity * mem::size_of::<i32>()); + let offsets = sized_buffer(mem::size_of::<i32>())?; [type_ids, offsets] } } } - } + }) } /// A generic representation of Arrow array data which encapsulates common attributes diff --git a/arrow-data/src/transform/mod.rs b/arrow-data/src/transform/mod.rs index 842827d0e1..5dd1032a3c 100644 --- a/arrow-data/src/transform/mod.rs +++ b/arrow-data/src/transform/mod.rs @@ -348,16 +348,24 @@ fn build_extend_nulls(data_type: &DataType) -> ExtendNulls { fn preallocate_offset_and_binary_buffer<Offset: ArrowNativeType + Integer>( capacity: usize, binary_size: usize, -) -> [MutableBuffer; 2] { +) -> Result<[MutableBuffer; 2], ArrowError> { // offsets - let mut buffer = MutableBuffer::new((1 + capacity) * mem::size_of::<Offset>()); + let offset_capacity = capacity + .checked_add(1) + .and_then(|len| len.checked_mul(mem::size_of::<Offset>())) + .ok_or_else(|| ArrowError::MemoryError("offset buffer size overflow".into()))?; + let mut buffer = MutableBuffer::try_with_capacity(offset_capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; // safety: `unsafe` code assumes that this buffer is initialized with one element - buffer.push(Offset::zero()); + buffer + .try_extend_from_slice(&[Offset::zero()]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; - [ + Ok([ buffer, - MutableBuffer::new(binary_size * mem::size_of::<u8>()), - ] + MutableBuffer::try_with_capacity(binary_size) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?, + ]) } /// Define capacities to pre-allocate for child data or data buffers. @@ -404,18 +412,22 @@ impl<'a> MutableArrayData<'a> { /// Note: null-handling is enabled automatically if any source array contains nulls. /// * `capacity` - the preallocated capacity of the output array, in slots (number of elements) /// - /// if `use_nulls` is `false` and no source arrays contains nulls, calling - /// [MutableArrayData::extend_nulls] or [MutableArrayData::try_extend_nulls] will panic. + /// If `use_nulls` is `false` and no source array contains nulls, calling + /// [MutableArrayData::extend_nulls] will panic and + /// [MutableArrayData::try_extend_nulls] will return an error. + /// + /// # Panics + /// + /// Panics if a buffer cannot be allocated or if merged dictionary values overflow the + /// dictionary key type. See [MutableArrayData::try_new] for a fallible variant. pub fn new(arrays: Vec<&'a ArrayData>, use_nulls: bool, capacity: usize) -> Self { Self::with_capacities(arrays, use_nulls, Capacities::Array(capacity)) } /// Fallible variant of [MutableArrayData::new]. /// - /// Unlike [MutableArrayData::new], this does not panic when merging dictionary - /// arrays whose combined values would overflow the dictionary key type. Instead, - /// it returns an error, letting callers (e.g. [`interleave`](crate) / `concat`) - /// surface it as a normal error. + /// Unlike [MutableArrayData::new], this returns an error if a buffer cannot be allocated or + /// merged dictionary values overflow the dictionary key type. pub fn try_new( arrays: Vec<&'a ArrayData>, use_nulls: bool, @@ -436,21 +448,23 @@ impl<'a> MutableArrayData<'a> { /// * when merging dictionary arrays whose combined values overflow the /// dictionary key type — see [MutableArrayData::try_with_capacities] for a /// fallible variant + /// * if a buffer cannot be allocated pub fn with_capacities( arrays: Vec<&'a ArrayData>, use_nulls: bool, capacities: Capacities, ) -> Self { Self::try_with_capacities(arrays, use_nulls, capacities) - .expect("MutableArrayData::new is infallible") + .expect("MutableArrayData construction failed") } /// Fallible variant of [MutableArrayData::with_capacities]. /// - /// Returns an error instead of panicking when merging dictionary arrays whose - /// combined values would overflow the dictionary key type. Still panics for - /// other unsupported combinations (inconsistent input types, unsupported - /// `Capacities` variants) as documented on [MutableArrayData::with_capacities]. + /// Returns an error instead of panicking when allocating buffers or merging + /// dictionary arrays whose combined values would overflow the dictionary key + /// type. Still panics for other unsupported combinations (inconsistent input + /// types, unsupported `Capacities` variants) as documented on + /// [MutableArrayData::with_capacities]. pub fn try_with_capacities( arrays: Vec<&'a ArrayData>, use_nulls: bool, @@ -478,15 +492,15 @@ impl<'a> MutableArrayData<'a> { Capacities::Binary(capacity, Some(value_cap)), ) => { array_capacity = *capacity; - preallocate_offset_and_binary_buffer::<i64>(*capacity, *value_cap) + preallocate_offset_and_binary_buffer::<i64>(*capacity, *value_cap)? } (DataType::Utf8 | DataType::Binary, Capacities::Binary(capacity, Some(value_cap))) => { array_capacity = *capacity; - preallocate_offset_and_binary_buffer::<i32>(*capacity, *value_cap) + preallocate_offset_and_binary_buffer::<i32>(*capacity, *value_cap)? } (_, Capacities::Array(capacity)) => { array_capacity = *capacity; - new_buffers(data_type, *capacity) + new_buffers(data_type, *capacity)? } ( DataType::List(_) @@ -498,11 +512,11 @@ impl<'a> MutableArrayData<'a> { Capacities::List(capacity, _), ) => { array_capacity = *capacity; - new_buffers(data_type, *capacity) + new_buffers(data_type, *capacity)? } (DataType::Struct(_), Capacities::Struct(capacity, _)) => { array_capacity = *capacity; - new_buffers(data_type, *capacity) + new_buffers(data_type, *capacity)? } _ => panic!("Capacities: {capacities:?} not yet supported"), }; @@ -624,15 +638,22 @@ impl<'a> MutableArrayData<'a> { .iter() .map(|array| &array.child_data()[0]) .collect::<Vec<_>>(); - let capacities = - if let Capacities::List(capacity, ref child_capacities) = capacities { - child_capacities - .clone() - .map(|c| *c) - .unwrap_or(Capacities::Array(capacity * *size as usize)) - } else { - Capacities::Array(array_capacity * *size as usize) - }; + let capacities = if let Capacities::List(capacity, ref child_capacities) = + capacities + { + match child_capacities.clone() { + Some(capacity) => *capacity, + None => Capacities::Array( + capacity.checked_mul(*size as usize).ok_or_else(|| { + ArrowError::MemoryError("fixed-size list capacity overflow".into()) + })?, + ), + } + } else { + Capacities::Array(array_capacity.checked_mul(*size as usize).ok_or_else( + || ArrowError::MemoryError("fixed-size list capacity overflow".into()), + )?) + }; vec![MutableArrayData::try_with_capacities( children, use_nulls, capacities, )?] @@ -668,15 +689,16 @@ impl<'a> MutableArrayData<'a> { .iter() .map(|dictionary| dictionary.len()) .collect(); - let capacity = lengths.iter().sum(); + let capacity = lengths.iter().try_fold(0usize, |acc, len| { + acc.checked_add(*len).ok_or_else(|| { + ArrowError::MemoryError("dictionary size overflow".into()) + }) + })?; - let mut mutable = MutableArrayData::new(dictionaries, false, capacity); + let mut mutable = MutableArrayData::try_new(dictionaries, false, capacity)?; for (i, len) in lengths.iter().enumerate() { - mutable.try_extend(i, 0, *len).expect( - "extend failed while building dictionary; \ - this is a bug in MutableArrayData", - ) + mutable.try_extend(i, 0, *len)?; } (Some(mutable.freeze()), true) @@ -702,10 +724,13 @@ impl<'a> MutableArrayData<'a> { .map(|array| build_extend_null_bits(array, use_nulls)) .collect(); - let null_buffer = use_nulls.then(|| { - let null_bytes = bit_util::ceil(array_capacity, 8); - MutableBuffer::from_len_zeroed(null_bytes) - }); + let null_buffer = use_nulls + .then(|| { + let null_bytes = bit_util::ceil(array_capacity, 8); + MutableBuffer::try_from_len_zeroed(null_bytes) + .map_err(|e| ArrowError::MemoryError(e.to_string())) + }) + .transpose()?; let extend_values = match &data_type { DataType::Dictionary(_, _) => { @@ -977,6 +1002,22 @@ mod test { .unwrap() } + #[test] + fn test_try_with_capacities_buffer_size_overflow() { + let int64 = ArrayData::new_empty(&DataType::Int64); + let err = MutableArrayData::try_new(vec![&int64], false, usize::MAX).unwrap_err(); + assert!(matches!(err, ArrowError::MemoryError(_))); + + let binary = ArrayData::new_empty(&DataType::Binary); + let err = MutableArrayData::try_with_capacities( + vec![&binary], + false, + Capacities::Binary(usize::MAX, Some(0)), + ) + .unwrap_err(); + assert!(matches!(err, ArrowError::MemoryError(_))); + } + #[test] fn test_try_extend_invalid_index_and_range() { let array = int64_array_data(vec![1, 2, 3]); diff --git a/arrow-row/src/fixed.rs b/arrow-row/src/fixed.rs index 32b29a597a..de18635514 100644 --- a/arrow-row/src/fixed.rs +++ b/arrow-row/src/fixed.rs @@ -8,7 +8,7 @@ use arrow_array::{ArrowPrimitiveType, BooleanArray, FixedSizeBinaryArray}; use arrow_buffer::{ BooleanBuffer, IntervalDayTime, IntervalMonthDayNano, MutableBuffer, NullBuffer, bit_util, i256, }; -use arrow_schema::{DataType, SortOptions}; +use arrow_schema::{ArrowError, DataType, SortOptions}; use half::f16; pub trait FromSlice { @@ -343,7 +343,10 @@ fn split_off<'a>(src: &mut &'a [u8], len: usize) -> &'a [u8] { } /// Decodes a `BooleanArray` from rows -pub fn decode_bool(rows: &mut [&[u8]], options: SortOptions) -> BooleanArray { +pub(crate) fn try_decode_bool( + rows: &mut [&[u8]], + options: SortOptions, +) -> Result<BooleanArray, ArrowError> { let true_val = match options.descending { true => !1, false => 1, @@ -351,8 +354,11 @@ pub fn decode_bool(rows: &mut [&[u8]], options: SortOptions) -> BooleanArray { let len = rows.len(); - let mut nulls = MutableBuffer::new(bit_util::ceil(len, 64) * 8); - let mut values = MutableBuffer::new(bit_util::ceil(len, 64) * 8); + let capacity = bit_util::ceil(len, 64) * 8; + let mut nulls = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + let mut values = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let chunks = len / 64; let remainder = len % 64; @@ -389,30 +395,35 @@ pub fn decode_bool(rows: &mut [&[u8]], options: SortOptions) -> BooleanArray { let nulls = NullBuffer::new(BooleanBuffer::new(nulls.into(), 0, len)); let nulls = (nulls.null_count() > 0).then_some(nulls); - BooleanArray::new(BooleanBuffer::new(values.into(), 0, len), nulls) + Ok(BooleanArray::new( + BooleanBuffer::new(values.into(), 0, len), + nulls, + )) } /// Decodes a single byte from each row, interpreting `0x01` as a valid value /// and all other values as a null. Optionally returns `None` if there are no /// null values. -pub fn decode_nulls(rows: &[&[u8]]) -> Option<NullBuffer> { - let nulls = BooleanBuffer::collect_bool(rows.len(), |idx| rows[idx][0] == 1); +pub(crate) fn try_decode_nulls(rows: &[&[u8]]) -> Result<Option<NullBuffer>, ArrowError> { + let nulls = MutableBuffer::try_collect_bool(rows.len(), |idx| rows[idx][0] == 1) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + let nulls = BooleanBuffer::new(nulls.into(), 0, rows.len()); let nulls = NullBuffer::new(nulls); - (nulls.null_count() > 0).then_some(nulls) + Ok((nulls.null_count() > 0).then_some(nulls)) } /// Decodes a `PrimitiveArray` from rows -pub fn decode_primitive<T: ArrowPrimitiveType>( +pub(crate) fn try_decode_primitive<T: ArrowPrimitiveType>( rows: &mut [&[u8]], data_type: DataType, options: SortOptions, -) -> PrimitiveArray<T> +) -> Result<PrimitiveArray<T>, ArrowError> where T::Native: FixedLengthEncoding, { assert!(PrimitiveArray::<T>::is_compatible(&data_type)); - let nulls = decode_nulls(rows); + let nulls = try_decode_nulls(rows)?; let values = rows .iter_mut() .map(|row| { @@ -425,24 +436,28 @@ where }) .collect::<Vec<_>>(); - PrimitiveArray::new(values.into(), nulls).with_data_type(data_type) + Ok(PrimitiveArray::new(values.into(), nulls).with_data_type(data_type)) } /// Decodes a `FixedLengthBinary` from rows /// /// # Panics: /// Panics if `size` is negative -pub fn decode_fixed_size_binary( +pub(crate) fn try_decode_fixed_size_binary( rows: &mut [&[u8]], size: i32, options: SortOptions, -) -> FixedSizeBinaryArray { +) -> Result<FixedSizeBinaryArray, ArrowError> { if size < 0 { panic!("cannot decode FixedSizeBinary({size})"); } let num_rows = rows.len(); - let mut values = MutableBuffer::new(size as usize * num_rows); - let nulls = decode_nulls(rows); + let capacity = (size as usize) + .checked_mul(num_rows) + .ok_or_else(|| ArrowError::MemoryError("decoded values size overflow".into()))?; + let mut values = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + let nulls = try_decode_nulls(rows)?; let encoded_len = size as usize + 1; @@ -458,5 +473,5 @@ pub fn decode_fixed_size_binary( } // Need to set the length since when size is 0 and no nulls the length could not be determined by FixedSizeBinaryArray - FixedSizeBinaryArray::try_new_with_len(size, values.into(), nulls, num_rows).unwrap() + FixedSizeBinaryArray::try_new_with_len(size, values.into(), nulls, num_rows) } diff --git a/arrow-row/src/lib.rs b/arrow-row/src/lib.rs index abe1b6320f..4bb5f29719 100644 --- a/arrow-row/src/lib.rs +++ b/arrow-row/src/lib.rs @@ -167,7 +167,7 @@ use arrow_data::transform::MutableArrayData; use arrow_schema::*; use variable::{decode_binary_view, decode_string_view}; -use crate::fixed::{decode_bool, decode_fixed_size_binary, decode_primitive}; +use crate::fixed::{try_decode_bool, try_decode_fixed_size_binary, try_decode_primitive}; use crate::list::{compute_lengths_fixed_size_list, encode_fixed_size_list}; use crate::variable::{decode_binary, decode_string}; use arrow_array::types::{Int16Type, Int32Type, Int64Type}; @@ -2323,7 +2323,7 @@ fn encode_dictionary_rows<K: ArrowDictionaryKeyType>( macro_rules! decode_primitive_helper { ($t:ty, $rows:ident, $data_type:ident, $options:ident) => { - Arc::new(decode_primitive::<$t>($rows, $data_type, $options)) + Arc::new(try_decode_primitive::<$t>($rows, $data_type, $options)?) }; } @@ -2349,13 +2349,13 @@ unsafe fn decode_column( variable::decode_null_value(rows, options); Arc::new(NullArray::new(rows.len())) } - DataType::Boolean => Arc::new(decode_bool(rows, options)), - DataType::Binary => Arc::new(decode_binary::<i32>(rows, options)), - DataType::LargeBinary => Arc::new(decode_binary::<i64>(rows, options)), + DataType::Boolean => Arc::new(try_decode_bool(rows, options)?), + DataType::Binary => Arc::new(decode_binary::<i32>(rows, options)?), + DataType::LargeBinary => Arc::new(decode_binary::<i64>(rows, options)?), DataType::BinaryView => Arc::new(decode_binary_view(rows, options)?), - DataType::FixedSizeBinary(size) => Arc::new(decode_fixed_size_binary(rows, size, options)), - DataType::Utf8 => Arc::new(unsafe{ decode_string::<i32>(rows, options, validate_utf8) }), - DataType::LargeUtf8 => Arc::new(unsafe { decode_string::<i64>(rows, options, validate_utf8) }), + DataType::FixedSizeBinary(size) => Arc::new(try_decode_fixed_size_binary(rows, size, options)?), + DataType::Utf8 => Arc::new(unsafe{ decode_string::<i32>(rows, options, validate_utf8) }?), + DataType::LargeUtf8 => Arc::new(unsafe { decode_string::<i64>(rows, options, validate_utf8) }?), DataType::Utf8View => Arc::new(unsafe { decode_string_view(rows, options, validate_utf8) }?), _ => return Err(ArrowError::NotYetImplemented(format!("unsupported data type: {data_type}" ))) } @@ -2365,7 +2365,7 @@ unsafe fn decode_column( cols.into_iter().next().unwrap() } Codec::Struct(converter, _) => { - let nulls = fixed::decode_nulls(rows); + let nulls = fixed::try_decode_nulls(rows)?; rows.iter_mut().for_each(|row| *row = &row[1..]); let children = unsafe { converter.convert_raw(rows, validate_utf8) }?; diff --git a/arrow-row/src/list.rs b/arrow-row/src/list.rs index cf8ecd6d05..012b793ddc 100644 --- a/arrow-row/src/list.rs +++ b/arrow-row/src/list.rs @@ -207,7 +207,7 @@ pub(crate) unsafe fn decode<ListLikeImpl: GenericListArrayOrMap>( } ListLikeImpl::Offset::from_usize(offset).expect("overflow"); - let nulls = crate::variable::decode_nulls_sentinel(rows, opts); + let nulls = crate::variable::decode_nulls_sentinel(rows, opts)?; let mut values_offsets = Vec::with_capacity(offset); let mut values_bytes = Vec::with_capacity(values_bytes); @@ -376,7 +376,7 @@ pub unsafe fn decode_fixed_size_list( }; let num_rows = rows.len(); - let nulls = fixed::decode_nulls(rows); + let nulls = fixed::try_decode_nulls(rows)?; let null_element_encoded = converter.convert_columns(&[new_null_array(element_field.data_type(), 1)])?; @@ -544,11 +544,12 @@ pub unsafe fn decode_list_view<O: OffsetSizeTrait>( let null_sentinel = null_sentinel(opts); let mut null_count = 0; - let nulls = MutableBuffer::collect_bool(rows.len(), |x| { + let nulls = MutableBuffer::try_collect_bool(rows.len(), |x| { let valid = rows[x][0] != null_sentinel; null_count += !valid as usize; valid - }); + }) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut values_offsets_vec = Vec::with_capacity(child_count); let mut values_bytes = Vec::with_capacity(values_bytes); diff --git a/arrow-row/src/variable.rs b/arrow-row/src/variable.rs index 9f2ac2406f..6612114ba7 100644 --- a/arrow-row/src/variable.rs +++ b/arrow-row/src/variable.rs @@ -59,11 +59,16 @@ pub(crate) fn non_null_padded_length(len: usize) -> usize { /// Decodes a single byte from each row, where a valid value is determined via /// a configurable sentinel. Optionally returns `None` if there are no null values. -pub(crate) fn decode_nulls_sentinel(rows: &[&[u8]], options: SortOptions) -> Option<NullBuffer> { +pub(crate) fn decode_nulls_sentinel( + rows: &[&[u8]], + options: SortOptions, +) -> Result<Option<NullBuffer>, ArrowError> { let null_sentinel = null_sentinel(options); - let nulls = BooleanBuffer::collect_bool(rows.len(), |x| rows[x][0] != null_sentinel); + let nulls = MutableBuffer::try_collect_bool(rows.len(), |x| rows[x][0] != null_sentinel) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + let nulls = BooleanBuffer::new(nulls.into(), 0, rows.len()); let nulls = NullBuffer::new(nulls); - (nulls.null_count() > 0).then_some(nulls) + Ok((nulls.null_count() > 0).then_some(nulls)) } /// Variable length values are encoded as @@ -264,19 +269,21 @@ fn decoded_len(row: &[u8], options: SortOptions) -> usize { pub fn decode_binary<I: OffsetSizeTrait>( rows: &mut [&[u8]], options: SortOptions, -) -> GenericBinaryArray<I> { +) -> Result<GenericBinaryArray<I>, ArrowError> { let len = rows.len(); - let nulls = decode_nulls_sentinel(rows, options); + let nulls = decode_nulls_sentinel(rows, options)?; let values_capacity = rows.iter().map(|row| decoded_len(row, options)).sum(); + I::from_usize(values_capacity).ok_or(ArrowError::OffsetOverflowError(values_capacity))?; let mut offsets = Vec::<I>::with_capacity(len + 1); offsets.push(I::zero()); - let mut values = MutableBuffer::new(values_capacity); + let mut values = MutableBuffer::try_with_capacity(values_capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; for row in rows { let offset = decode_blocks(row, options, |b| values.extend_from_slice(b)); *row = &row[offset..]; - offsets.push(I::from_usize(values.len()).expect("offset overflow")) + offsets.push(I::usize_as(values.len())) } if options.descending { @@ -285,13 +292,13 @@ pub fn decode_binary<I: OffsetSizeTrait>( // SAFETY: // Valid by construction above - unsafe { + Ok(unsafe { GenericBinaryArray::new_unchecked( OffsetBuffer::new(ScalarBuffer::from(offsets)), values.into(), nulls, ) - } + }) } fn decode_binary_view_inner<const VALIDATE_UTF8: bool>( @@ -301,7 +308,7 @@ fn decode_binary_view_inner<const VALIDATE_UTF8: bool>( let len = rows.len(); let inline_str_max_len = MAX_INLINE_VIEW_LEN as usize; - let nulls = decode_nulls_sentinel(rows, options); + let nulls = decode_nulls_sentinel(rows, options)?; // Capacity for all long strings plus room for one short string let mut values_capacity = inline_str_max_len; @@ -323,7 +330,8 @@ fn decode_binary_view_inner<const VALIDATE_UTF8: bool>( "{long_values_len} bytes of non-inlined values too long to decode into a view array with a single data buffer" ))); } - let mut values = MutableBuffer::new(values_capacity); + let mut values = MutableBuffer::try_with_capacity(values_capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut view_utf8_validation_buffer = if VALIDATE_UTF8 { Vec::with_capacity(inline_capacity) } else { @@ -392,18 +400,18 @@ pub unsafe fn decode_string<I: OffsetSizeTrait>( rows: &mut [&[u8]], options: SortOptions, validate_utf8: bool, -) -> GenericStringArray<I> { - let decoded = decode_binary::<I>(rows, options); +) -> Result<GenericStringArray<I>, ArrowError> { + let decoded = decode_binary::<I>(rows, options)?; if validate_utf8 { - return GenericStringArray::from(decoded); + return Ok(GenericStringArray::from(decoded)); } let (offsets, values, nulls) = decoded.into_parts(); // SAFETY: // Row data must have come from a valid UTF-8 array - unsafe { GenericStringArray::new_unchecked(offsets, values, nulls) } + Ok(unsafe { GenericStringArray::new_unchecked(offsets, values, nulls) }) } /// Decodes a string view array from `rows` with the provided `options` diff --git a/arrow-select/src/concat.rs b/arrow-select/src/concat.rs index ce91249024..7a96644578 100644 --- a/arrow-select/src/concat.rs +++ b/arrow-select/src/concat.rs @@ -32,26 +32,36 @@ use arrow_data::transform::{Capacities, MutableArrayData}; use arrow_schema::{ArrowError, DataType, FieldRef, Fields, SchemaRef}; use std::{collections::HashSet, ops::Add, sync::Arc}; -fn binary_capacity<T: ByteArrayType>(arrays: &[&dyn Array]) -> Capacities { - let mut item_capacity = 0; - let mut bytes_capacity = 0; +fn binary_capacity<T: ByteArrayType>(arrays: &[&dyn Array]) -> Result<Capacities, ArrowError> { + let mut item_capacity = 0usize; + let mut bytes_capacity = 0usize; for array in arrays { let a = array.as_bytes::<T>(); // Guaranteed to always have at least one element let offsets = a.value_offsets(); - bytes_capacity += offsets[offsets.len() - 1].as_usize() - offsets[0].as_usize(); - item_capacity += a.len() + bytes_capacity = bytes_capacity + .checked_add(offsets[offsets.len() - 1].as_usize() - offsets[0].as_usize()) + .ok_or_else(|| ArrowError::MemoryError("concatenated values overflow".into()))?; + item_capacity = item_capacity + .checked_add(a.len()) + .ok_or_else(|| ArrowError::MemoryError("concatenated length overflow".into()))?; } - Capacities::Binary(item_capacity, Some(bytes_capacity)) + Ok(Capacities::Binary(item_capacity, Some(bytes_capacity))) } -fn fixed_size_list_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capacities { +fn fixed_size_list_capacity( + arrays: &[&dyn Array], + data_type: &DataType, +) -> Result<Capacities, ArrowError> { if let DataType::FixedSizeList(f, _) = data_type { - let item_capacity = arrays.iter().map(|a| a.len()).sum(); + let item_capacity = arrays + .iter() + .try_fold(0usize, |total, array| total.checked_add(array.len())) + .ok_or_else(|| ArrowError::MemoryError("concatenated length overflow".into()))?; let child_data_type = f.data_type(); - match child_data_type { + Ok(match child_data_type { // These types should match the types that `get_capacity` // has special handling for. DataType::Utf8 @@ -65,11 +75,11 @@ fn fixed_size_list_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capa .collect(); Capacities::List( item_capacity, - Some(Box::new(get_capacity(&values, child_data_type))), + Some(Box::new(get_capacity(&values, child_data_type)?)), ) } _ => Capacities::Array(item_capacity), - } + }) } else { unreachable!("illegal data type for fixed size list") } @@ -336,7 +346,13 @@ fn concat_list_view<OffsetSize: OffsetSizeTrait>( let sizes: ScalarBuffer<OffsetSize> = lists.iter().flat_map(|x| x.sizes()).copied().collect(); - let mut offsets = MutableBuffer::with_capacity(lists.iter().map(|l| l.offsets().len()).sum()); + let offsets_capacity = lists + .iter() + .try_fold(0usize, |acc, l| acc.checked_add(l.offsets().len())) + .and_then(|len| len.checked_mul(std::mem::size_of::<OffsetSize>())) + .ok_or_else(|| ArrowError::MemoryError("concatenated offsets size overflow".into()))?; + let mut offsets = MutableBuffer::try_with_capacity(offsets_capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut global_offset = OffsetSize::zero(); for l in &lists { for &offset in l.offsets() { @@ -382,7 +398,7 @@ fn concat_boolean(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> { } fn concat_bytes<T: ByteArrayType>(arrays: &[&dyn Array]) -> Result<ArrayRef, ArrowError> { - let Capacities::Binary(item_capacity, Some(bytes_capacity)) = binary_capacity::<T>(arrays) + let Capacities::Binary(item_capacity, Some(bytes_capacity)) = binary_capacity::<T>(arrays)? else { unreachable!() }; @@ -518,14 +534,18 @@ macro_rules! primitive_concat { }; } -fn get_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Capacities { +fn get_capacity(arrays: &[&dyn Array], data_type: &DataType) -> Result<Capacities, ArrowError> { match data_type { DataType::Utf8 => binary_capacity::<Utf8Type>(arrays), DataType::LargeUtf8 => binary_capacity::<LargeUtf8Type>(arrays), DataType::Binary => binary_capacity::<BinaryType>(arrays), DataType::LargeBinary => binary_capacity::<LargeBinaryType>(arrays), DataType::FixedSizeList(_, _) => fixed_size_list_capacity(arrays, data_type), - _ => Capacities::Array(arrays.iter().map(|a| a.len()).sum()), + _ => arrays + .iter() + .try_fold(0usize, |total, array| total.checked_add(array.len())) + .map(Capacities::Array) + .ok_or_else(|| ArrowError::MemoryError("concatenated length overflow".into())), } } @@ -610,7 +630,7 @@ fn concat_same_type(arrays: &[&dyn Array], d: &DataType) -> Result<ArrayRef, Arr DataType::Utf8View => concat_byte_view::<StringViewType>(arrays), DataType::BinaryView => concat_byte_view::<BinaryViewType>(arrays), _ => { - let capacity = get_capacity(arrays, d); + let capacity = get_capacity(arrays, d)?; concat_fallback(arrays, capacity) } } @@ -1125,7 +1145,8 @@ mod tests { fn test_concat_fixed_size_list_matches_fallback() { let check = |arrays: &[&dyn Array]| { let expected = - concat_fallback(arrays, get_capacity(arrays, arrays[0].data_type())).unwrap(); + concat_fallback(arrays, get_capacity(arrays, arrays[0].data_type()).unwrap()) + .unwrap(); let got = concat(arrays).unwrap(); assert_eq!(got.as_ref(), expected.as_ref()); got.to_data().validate_full().unwrap(); diff --git a/arrow-select/src/filter.rs b/arrow-select/src/filter.rs index 122e0a9aa5..db71418453 100644 --- a/arrow-select/src/filter.rs +++ b/arrow-select/src/filter.rs @@ -619,7 +619,10 @@ fn filter_array(values: &dyn Array, predicate: &FilterPredicate) -> Result<Array Ok(Arc::new(filter_byte_view(values.as_binary_view(), predicate))) } DataType::FixedSizeBinary(_) => { - Ok(Arc::new(filter_fixed_size_binary(values.as_fixed_size_binary(), predicate))) + Ok(Arc::new(filter_fixed_size_binary( + values.as_fixed_size_binary(), + predicate, + )?)) } DataType::ListView(_) => { Ok(Arc::new(filter_list_view::<i32>(values.as_list_view(), predicate))) @@ -646,11 +649,11 @@ fn filter_array(values: &dyn Array, predicate: &FilterPredicate) -> Result<Array _ => { let data = values.to_data(); // fallback to using MutableArrayData - let mut mutable = MutableArrayData::new( + let mut mutable = MutableArrayData::try_new( vec![&data], false, predicate.count, - ); + )?; match &predicate.strategy { IterationStrategy::Slices(slices) => { @@ -1092,16 +1095,19 @@ fn filter_byte_view<T: ByteViewType>( } /// Copies fixed-size binary elements at `indices` from `values` into a new `MutableBuffer`. -/// Uses raw pointer writes and `with_capacity` to avoid zero-initialization and per-call overhead. +/// Raw writes avoid zero-initializing the destination before every byte is overwritten. #[inline(always)] fn copy_fsb_indices( values: &[u8], value_length: usize, indices: impl Iterator<Item = usize>, count: usize, -) -> MutableBuffer { - let total = count * value_length; - let mut buffer = MutableBuffer::with_capacity(total); +) -> Result<MutableBuffer, ArrowError> { + let total = count + .checked_mul(value_length) + .ok_or_else(|| ArrowError::MemoryError("filter output size overflow".into()))?; + let mut buffer = MutableBuffer::try_with_capacity(total) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let dst_base = buffer.as_mut_ptr(); let mut write_offset = 0usize; for idx in indices { @@ -1119,19 +1125,24 @@ fn copy_fsb_indices( } // SAFETY: we wrote exactly `count * value_length` bytes into the buffer. unsafe { buffer.set_len(total) }; - buffer + Ok(buffer) } fn filter_fixed_size_binary( array: &FixedSizeBinaryArray, predicate: &FilterPredicate, -) -> FixedSizeBinaryArray { +) -> Result<FixedSizeBinaryArray, ArrowError> { let values: &[u8] = array.values(); let value_length = array.value_length() as usize; let calculate_offset_from_index = |index: usize| index * value_length; + let capacity = predicate + .count + .checked_mul(value_length) + .ok_or_else(|| ArrowError::MemoryError("filter output size overflow".into()))?; let buffer = match &predicate.strategy { IterationStrategy::SlicesIterator => { - let mut buffer = MutableBuffer::with_capacity(predicate.count * value_length); + let mut buffer = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; for (start, end) in SlicesIterator::new(&predicate.filter) { buffer.extend_from_slice( &values[calculate_offset_from_index(start)..calculate_offset_from_index(end)], @@ -1140,7 +1151,8 @@ fn filter_fixed_size_binary( buffer } IterationStrategy::Slices(slices) => { - let mut buffer = MutableBuffer::with_capacity(predicate.count * value_length); + let mut buffer = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; for (start, end) in slices { buffer.extend_from_slice( &values[calculate_offset_from_index(*start)..calculate_offset_from_index(*end)], @@ -1153,13 +1165,13 @@ fn filter_fixed_size_binary( value_length, IndexIterator::new(&predicate.filter, predicate.count), predicate.count, - ), + )?, IterationStrategy::Indices(indices) => copy_fsb_indices( values, value_length, indices.iter().copied(), predicate.count, - ), + )?, IterationStrategy::All | IterationStrategy::None => unreachable!(), }; @@ -1171,7 +1183,6 @@ fn filter_fixed_size_binary( nulls, predicate.count, ) - .unwrap() } /// `filter` implementation for dictionaries diff --git a/arrow-select/src/interleave.rs b/arrow-select/src/interleave.rs index d82fb9a90c..a9b88867cf 100644 --- a/arrow-select/src/interleave.rs +++ b/arrow-select/src/interleave.rs @@ -272,21 +272,21 @@ fn interleave_dictionaries<K: ArrowDictionaryKeyType>( }; } - let masks: Vec<_> = dictionaries + let masks: Result<Vec<_>, ArrowError> = dictionaries .iter() .enumerate() .map(|(a_idx, dictionary)| { - let mut key_mask = BooleanBufferBuilder::new_from_buffer( - MutableBuffer::new_null(dictionary.len()), - dictionary.len(), - ); + let buffer = MutableBuffer::try_from_len_zeroed(bit_util::ceil(dictionary.len(), 8)) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + let mut key_mask = BooleanBufferBuilder::new_from_buffer(buffer, dictionary.len()); for (_, key_idx) in indices.iter().filter(|(a, _)| *a == a_idx) { key_mask.set_bit(*key_idx, true); } - key_mask.finish() + Ok(key_mask.finish()) }) .collect(); + let masks = masks?; let merged = merge_dictionary_values(&dictionaries, Some(&masks))?; @@ -420,7 +420,7 @@ fn interleave_list_like_primitive_child<L: ListLikeArray, T: ArrowPrimitiveType> indices: &[(usize, usize)], capacity: usize, data_type: &DataType, -) -> ArrayRef { +) -> Result<ArrayRef, ArrowError> { let child_arrays: Vec<&PrimitiveArray<T>> = interleaved .arrays .iter() @@ -443,7 +443,8 @@ fn interleave_list_like_primitive_child<L: ListLikeArray, T: ArrowPrimitiveType> // - Sources without nulls: set the bit range to all 1s directly. let nulls = if has_child_nulls { let null_byte_len = bit_util::ceil(capacity, 8); - let mut output_null_buf = MutableBuffer::from_len_zeroed(null_byte_len); + let mut output_null_buf = MutableBuffer::try_from_len_zeroed(null_byte_len) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut offset_write = 0; let mut output_null_count = 0usize; @@ -482,7 +483,9 @@ fn interleave_list_like_primitive_child<L: ListLikeArray, T: ArrowPrimitiveType> None }; - Arc::new(PrimitiveArray::<T>::new(values.into(), nulls).with_data_type(data_type.clone())) + Ok(Arc::new( + PrimitiveArray::<T>::new(values.into(), nulls).with_data_type(data_type.clone()), + )) } /// Interleave child values for non-primitive child types, shared by List and FixedSizeList. @@ -533,7 +536,7 @@ fn interleave_list<O: OffsetSizeTrait>( indices, capacity, field.data_type(), - ) + )? }; } @@ -561,7 +564,10 @@ fn interleave_fixed_size_list( size: i32, ) -> Result<ArrayRef, ArrowError> { let interleaved = Interleave::<'_, FixedSizeListArray>::new(values, indices); - let capacity = indices.len() * size as usize; + let capacity = indices + .len() + .checked_mul(size as usize) + .ok_or_else(|| ArrowError::MemoryError("interleave output size overflow".into()))?; macro_rules! fsl_primitive_helper { ($t:ty) => { @@ -570,7 +576,7 @@ fn interleave_fixed_size_list( indices, capacity, field.data_type(), - ) + )? }; } @@ -745,7 +751,7 @@ fn interleave_list_view_copy<O: OffsetSizeTrait>( .map(|list| list.values().to_data()) .collect(); let child_data_refs: Vec<_> = child_data.iter().collect(); - let mut mutable_child = MutableArrayData::new(child_data_refs, false, capacity); + let mut mutable_child = MutableArrayData::try_new(child_data_refs, false, capacity)?; for &(array_idx, row_idx) in indices { let list = interleaved.arrays[array_idx]; let start = list.offsets()[row_idx].as_usize(); diff --git a/arrow-select/src/take.rs b/arrow-select/src/take.rs index 8002b9338c..2fc6a3520e 100644 --- a/arrow-select/src/take.rs +++ b/arrow-select/src/take.rs @@ -1033,7 +1033,9 @@ where let values_buf = &child_data.buffers()[0]; let child_buf_offset = child_data.offset() * bytes_per_value; - let mut dst_buf = MutableBuffer::new(estimated_child_len.saturating_mul(bytes_per_value)); + let capacity = estimated_child_len.saturating_mul(bytes_per_value); + let mut dst_buf = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut child_len = OffsetType::Native::zero(); @@ -1043,7 +1045,9 @@ where let row = idx.as_usize(); let start = child_buf_offset + src_offsets[row].as_usize() * bytes_per_value; let end = child_buf_offset + src_offsets[row + 1].as_usize() * bytes_per_value; - dst_buf.extend_from_slice(&values_buf[start..end]); + dst_buf + .try_extend_from_slice(&values_buf[start..end]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; child_len = child_len .checked_add(&(src_offsets[row + 1] - src_offsets[row])) .ok_or_else(|| ArrowError::OffsetOverflowError(child_len.as_usize()))?; @@ -1076,7 +1080,9 @@ where ) } }; - dst_buf.extend_from_slice(&values_buf[start..end]); + dst_buf + .try_extend_from_slice(&values_buf[start..end]) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; child_len = child_len .checked_add(&(src_offsets[row + 1] - src_offsets[row])) .ok_or_else(|| ArrowError::OffsetOverflowError(child_len.as_usize()))?; @@ -1106,11 +1112,11 @@ where return GenericListArray::<OffsetType::Native>::try_new(field, offsets, child, nulls); } - let mut mutable = MutableArrayData::new( + let mut mutable = MutableArrayData::try_new( vec![&child_data], child_data.null_count() > 0, estimated_child_len, - ); + )?; match nulls.as_ref().filter(|n| n.null_count() > 0) { None => { @@ -1225,7 +1231,7 @@ fn take_fixed_size_list<IndexType: ArrowPrimitiveType, const VALIDATE_INDICES: b length as usize, element_size, nulls.as_ref(), - ) + )? } else { let list_indices = take_value_indices_from_fixed_size_list(values, indices, length)?; take_impl::<UInt32Type, VALIDATE_INDICES>(child.as_ref(), &list_indices)? @@ -1247,19 +1253,25 @@ fn take_fixed_size_list_primitive<IndexType: ArrowPrimitiveType>( list_size: usize, element_size: usize, taken_row_nulls: Option<&NullBuffer>, -) -> ArrayRef { - let row_bytes = list_size * element_size; +) -> Result<ArrayRef, ArrowError> { + let row_bytes = list_size + .checked_mul(element_size) + .ok_or_else(|| ArrowError::MemoryError("take output size overflow".into()))?; let child_data = child.to_data(); let src = child_data.buffers()[0].as_slice(); let child_byte_offset = child_data.offset() * element_size; - debug_assert!( - indices.len().checked_mul(row_bytes).is_some(), - "take_fixed_size_list_primitive: output buffer size overflows usize" - ); - let out_len = indices.len() * list_size; - - let mut out = MutableBuffer::from_len_zeroed(indices.len() * row_bytes); + let out_len = indices + .len() + .checked_mul(list_size) + .ok_or_else(|| ArrowError::MemoryError("take output size overflow".into()))?; + let out_byte_len = indices + .len() + .checked_mul(row_bytes) + .ok_or_else(|| ArrowError::MemoryError("take output size overflow".into()))?; + + let mut out = MutableBuffer::try_from_len_zeroed(out_byte_len) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let out_slice = out.as_slice_mut(); if indices.null_count() == 0 { @@ -1278,12 +1290,19 @@ fn take_fixed_size_list_primitive<IndexType: ArrowPrimitiveType>( } } // Expand the per-row null bitmap to per-element: each null row produces `list_size` null elements. - let child_null_buf = taken_row_nulls.map(|n| n.expand(list_size).buffer().clone()); + let child_null_buf = taken_row_nulls + .map(|n| { + n.try_expand(list_size) + .map(|n| n.buffer().clone()) + .map_err(|e| ArrowError::MemoryError(e.to_string())) + }) + .transpose()?; // SAFETY: // - The data buffer has `indices.len() * row_bytes` bytes = `out_len` elements of a // primitive type, matching `.len(out_len)`. - // - The null buffer (when present) is `ceil(out_len, 8)` bytes via `expand(list_size).buffer()`. + // - The null buffer (when present) is `ceil(out_len, 8)` bytes via + // `try_expand(list_size).buffer()`. // - Primitive types have exactly one value buffer. let array_data = unsafe { ArrayData::builder(child.data_type().clone()) @@ -1292,7 +1311,7 @@ fn take_fixed_size_list_primitive<IndexType: ArrowPrimitiveType>( .null_bit_buffer(child_null_buf) .build_unchecked() }; - make_array(array_data) + Ok(make_array(array_data)) } /// The take kernel implementation for `FixedSizeBinaryArray`. diff --git a/arrow-select/src/union_extract.rs b/arrow-select/src/union_extract.rs index fd032217f5..e15b907815 100644 --- a/arrow-select/src/union_extract.rs +++ b/arrow-select/src/union_extract.rs @@ -128,7 +128,7 @@ fn extract_sparse( { Ok(Arc::clone(target)) } else { - match eq_scalar(union_array.type_ids(), target_type_id) { + match eq_scalar(union_array.type_ids(), target_type_id)? { // case 2: all type ids equals our target, and since unions doesn't have a null mask, the result array is exactly the same as our target BoolValue::Scalar(true) => Ok(Arc::clone(target)), // case 3: none type_id matches our target, the result is a null array @@ -227,7 +227,7 @@ fn extract_dense( // case 4: every type id matches our target Ok(extract_dense_all_selected(union_array, target, offsets)?) } else { - match eq_scalar(union_array.type_ids(), target_type_id) { + match eq_scalar(union_array.type_ids(), target_type_id)? { // case 4C: all type ids matches our target. // Non empty sibling without any selected value may happen after slicing the parent union, // since only type_ids and offsets are sliced, not the children @@ -318,7 +318,7 @@ enum BoolValue { Buffer(BooleanBuffer), } -fn eq_scalar(type_ids: &[i8], target: i8) -> BoolValue { +fn eq_scalar(type_ids: &[i8], target: i8) -> Result<BoolValue, ArrowError> { eq_scalar_inner(EQ_SCALAR_CHUNK_SIZE, type_ids, target) } @@ -331,16 +331,20 @@ fn count_first_run(chunk_size: usize, type_ids: &[i8], mut f: impl FnMut(i8) -> } // This is like MutableBuffer::collect_bool(type_ids.len(), |i| type_ids[i] == target) with fast paths for all true or all false values. -fn eq_scalar_inner(chunk_size: usize, type_ids: &[i8], target: i8) -> BoolValue { +fn eq_scalar_inner( + chunk_size: usize, + type_ids: &[i8], + target: i8, +) -> Result<BoolValue, ArrowError> { let true_bits = count_first_run(chunk_size, type_ids, |v| v == target); let (set_bits, val) = if true_bits == type_ids.len() { - return BoolValue::Scalar(true); + return Ok(BoolValue::Scalar(true)); } else if true_bits == 0 { let false_bits = count_first_run(chunk_size, type_ids, |v| v != target); if false_bits == type_ids.len() { - return BoolValue::Scalar(false); + return Ok(BoolValue::Scalar(false)); } (false_bits, false) } else { @@ -350,8 +354,9 @@ fn eq_scalar_inner(chunk_size: usize, type_ids: &[i8], target: i8) -> BoolValue // restrict to chunk boundaries let set_bits = set_bits - set_bits % 64; - let mut buffer = - MutableBuffer::new(bit_util::ceil(type_ids.len(), 8)).with_bitset(set_bits / 8, val); + let mut buffer = MutableBuffer::try_with_capacity(bit_util::ceil(type_ids.len(), 8)) + .map_err(|e| ArrowError::MemoryError(e.to_string()))? + .with_bitset(set_bits / 8, val); buffer.extend(type_ids[set_bits..].chunks(64).map(|chunk| { chunk @@ -363,7 +368,11 @@ fn eq_scalar_inner(chunk_size: usize, type_ids: &[i8], target: i8) -> BoolValue }) })); - BoolValue::Buffer(BooleanBuffer::new(buffer.into(), 0, type_ids.len())) + Ok(BoolValue::Buffer(BooleanBuffer::new( + buffer.into(), + 0, + type_ids.len(), + ))) } const IS_SEQUENTIAL_CHUNK_SIZE: usize = 64; @@ -431,7 +440,7 @@ mod tests { const EQ_SCALAR_CHUNK_SIZE: usize = 3; fn eq_scalar(type_ids: &[i8], target: i8) -> BoolValue { - eq_scalar_inner(EQ_SCALAR_CHUNK_SIZE, type_ids, target) + eq_scalar_inner(EQ_SCALAR_CHUNK_SIZE, type_ids, target).unwrap() } fn cross_check(left: &[i8], right: i8) -> BooleanBuffer { diff --git a/arrow-select/src/zip.rs b/arrow-select/src/zip.rs index 44aedf7267..8f08b8de3e 100644 --- a/arrow-select/src/zip.rs +++ b/arrow-select/src/zip.rs @@ -713,7 +713,7 @@ impl<T: ByteArrayType> BytesScalarImpl<T> { predicate.iter().map(|b| if b { value_length } else { 0 }), ); - let mut bytes = MutableBuffer::with_capacity(0); + let mut bytes = MutableBuffer::default(); bytes .try_repeat_slice_n_times(value, number_of_true) .map_err(|e| ArrowError::MemoryError(e.to_string()))?; @@ -738,7 +738,7 @@ impl<T: ByteArrayType> BytesScalarImpl<T> { let offsets = OffsetBuffer::<T::Offset>::from_repeated_length(value_length, number_of_values); - let mut bytes = MutableBuffer::with_capacity(0); + let mut bytes = MutableBuffer::default(); bytes .try_repeat_slice_n_times(value, number_of_values) .map_err(|e| ArrowError::MemoryError(e.to_string()))?; @@ -778,7 +778,8 @@ impl<T: ByteArrayType> BytesScalarImpl<T> { .ok_or_else(|| ArrowError::MemoryError("zip output size overflow".to_string()))?; T::Offset::from_usize(total_number_of_bytes) .ok_or(ArrowError::OffsetOverflowError(total_number_of_bytes))?; - let mut mutable = MutableBuffer::with_capacity(total_number_of_bytes); + let mut mutable = MutableBuffer::try_with_capacity(total_number_of_bytes) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut offsets = Vec::<T::Offset>::with_capacity(predicate.len() + 1); offsets.push(T::Offset::usize_as(0)); let mut current_offset: usize = 0; @@ -985,7 +986,6 @@ impl<T: ByteViewType> ByteViewScalarImpl<T> { Ok((vec![truthy_view; result_len].into(), truthy_buffers, None)) } _ => { - let true_count = predicate.count_set_bits(); let mut buffers: Vec<Buffer> = truthy_buffers.to_vec(); // Check if we need to keep falsy buffer in case view isn't inline @@ -1001,8 +1001,12 @@ impl<T: ByteViewType> ByteViewScalarImpl<T> { byte_view_falsy.as_u128() }; - let total_number_of_bytes = true_count * 16 + (predicate.len() - true_count) * 16; - let mut mutable = MutableBuffer::new(total_number_of_bytes); + let total_number_of_bytes = predicate + .len() + .checked_mul(std::mem::size_of::<u128>()) + .ok_or_else(|| ArrowError::MemoryError("zip output size overflow".into()))?; + let mut mutable = MutableBuffer::try_with_capacity(total_number_of_bytes) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; let mut filled = 0; SlicesIterator::from(&predicate).try_for_each( diff --git a/arrow-string/src/concat_elements.rs b/arrow-string/src/concat_elements.rs index c6ff1d0334..d6ce8a9b02 100644 --- a/arrow-string/src/concat_elements.rs +++ b/arrow-string/src/concat_elements.rs @@ -203,7 +203,11 @@ pub fn concat_elements_fixed_size_binary( right.value_length() )) })?; - let output_size = left_size + right_size; + let output_size = left_size.checked_add(right_size).ok_or_else(|| { + ArrowError::InvalidArgumentError( + "Concatenated FixedSizeBinary value length overflow".into(), + ) + })?; let output_value_length = i32::try_from(output_size).map_err(|_| { ArrowError::InvalidArgumentError(format!( "Concatenated FixedSizeBinary value length {output_size} exceeds i32" @@ -214,18 +218,15 @@ pub fn concat_elements_fixed_size_binary( let nulls = NullBuffer::union(left.nulls(), right.nulls()); let mut result = FixedSizeBinaryBuilder::with_capacity(left.len(), output_value_length); - let mut buffer = MutableBuffer::with_capacity(output_size); + let mut buffer = MutableBuffer::try_with_capacity(output_size) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; for i in 0..left.len() { if nulls.as_ref().is_some_and(|n| n.is_null(i)) { result.append_null(); } else { buffer.clear(); - buffer - .try_extend_from_slice(left.value(i)) - .map_err(|e| ArrowError::MemoryError(e.to_string()))?; - buffer - .try_extend_from_slice(right.value(i)) - .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + buffer.extend_from_slice(left.value(i)); + buffer.extend_from_slice(right.value(i)); result.append_value(&buffer)?; } } diff --git a/arrow-string/src/substring.rs b/arrow-string/src/substring.rs index 7af68f2017..ad51b995c4 100644 --- a/arrow-string/src/substring.rs +++ b/arrow-string/src/substring.rs @@ -393,20 +393,14 @@ where })?; // concatenate substrings into a buffer - let mut new_values = MutableBuffer::new(new_offsets.last().unwrap().as_usize()); - - new_starts_ends - .iter() - .map(|(start, end)| { - let start = start.as_usize(); - let end = end.as_usize(); - &data[start..end] - }) - .try_for_each(|slice| { - new_values - .try_extend_from_slice(slice) - .map_err(|e| ArrowError::MemoryError(e.to_string())) - })?; + let mut new_values = MutableBuffer::try_with_capacity(new_offsets.last().unwrap().as_usize()) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; + + new_starts_ends.iter().for_each(|(start, end)| { + let start = start.as_usize(); + let end = end.as_usize(); + new_values.extend_from_slice(&data[start..end]); + }); let offsets = OffsetBuffer::new(new_offsets.into()); let values = new_values.into(); @@ -444,18 +438,15 @@ fn fixed_size_binary_substring( let data = array.value_data(); let capacity = num_of_elements .checked_mul(new_len) - .expect("capacity overflow"); - let mut new_values = MutableBuffer::new(capacity); + .ok_or_else(|| ArrowError::MemoryError("substring output size overflow".into()))?; + let mut new_values = MutableBuffer::try_with_capacity(capacity) + .map_err(|e| ArrowError::MemoryError(e.to_string()))?; (0..num_of_elements) .map(|idx| { let offset = idx * array.value_size(); (offset + new_start, offset + new_start + new_len) }) - .try_for_each(|(start, end)| { - new_values - .try_extend_from_slice(&data[start..end]) - .map_err(|e| ArrowError::MemoryError(e.to_string())) - })?; + .for_each(|(start, end)| new_values.extend_from_slice(&data[start..end])); let mut nulls = array .nulls() diff --git a/parquet/src/arrow/array_reader/fixed_size_list_array.rs b/parquet/src/arrow/array_reader/fixed_size_list_array.rs index 4649157321..e9483da500 100644 --- a/parquet/src/arrow/array_reader/fixed_size_list_array.rs +++ b/parquet/src/arrow/array_reader/fixed_size_list_array.rs @@ -139,11 +139,17 @@ impl ArrayReader for FixedSizeListArrayReader { .iter() .filter(|&&d| d >= self.def_level) .count(); - - if child_array.len() != items_count * self.fixed_size { + let expected_items = items_count + .checked_mul(self.fixed_size) + .ok_or_else(|| general_err!("Fixed-size list child length overflow"))?; + let output_items = list_len + .checked_mul(self.fixed_size) + .ok_or_else(|| general_err!("Fixed-size list child length overflow"))?; + + if child_array.len() != expected_items { return Err(general_err!( "Fixed-size list child mismatch: expected {} entries but got {}", - items_count * self.fixed_size, + expected_items, child_array.len() )); } @@ -154,7 +160,8 @@ impl ArrayReader for FixedSizeListArrayReader { child_array.to_data() } else { let data = child_array.to_data(); - let mut builder = MutableArrayData::new(vec![&data], true, list_len * self.fixed_size); + let mut builder = MutableArrayData::try_new(vec![&data], true, output_items) + .map_err(|e| general_err!("{}", e))?; let mut src_idx = 0; for &d in &boundary_defs { if d >= self.def_level { @@ -171,7 +178,7 @@ impl ArrayReader for FixedSizeListArrayReader { builder.freeze() }; - debug_assert_eq!(child_data.len(), list_len * self.fixed_size); + debug_assert_eq!(child_data.len(), output_items); let mut list_builder = ArrayData::builder(self.get_data_type().clone()) .len(list_len)
