From b50bc34338e0bedb9a8c9ac8514cf6343a5d9e98 Mon Sep 17 00:00:00 2001 From: Raphael Taylor-Davies Date: Wed, 12 Apr 2023 16:39:08 +0100 Subject: [PATCH] Add PrimitiveArray::try_new (#3879) --- arrow-array/src/array/primitive_array.rs | 45 ++++++++++++++++++++---- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/arrow-array/src/array/primitive_array.rs b/arrow-array/src/array/primitive_array.rs index 3199104382a6..7b50778d80ac 100644 --- a/arrow-array/src/array/primitive_array.rs +++ b/arrow-array/src/array/primitive_array.rs @@ -269,24 +269,55 @@ impl PrimitiveArray { /// /// # Panics /// - /// Panics if: - /// - `values.len() != nulls.len()` - /// - `!Self::is_compatible(data_type)` + /// Panics if [`Self::try_new`] returns an error pub fn new( data_type: DataType, values: ScalarBuffer, nulls: Option, ) -> Self { - Self::assert_compatible(&data_type); + Self::try_new(data_type, values, nulls).unwrap() + } + + /// Create a new [`PrimitiveArray`] from the provided data_type, values, nulls + /// + /// # Errors + /// + /// Errors if: + /// - `values.len() != nulls.len()` + /// - `!Self::is_compatible(data_type)` + pub fn try_new( + data_type: DataType, + values: ScalarBuffer, + nulls: Option, + ) -> Result { + if !Self::is_compatible(&data_type) { + return Err(ArrowError::InvalidArgumentError(format!( + "PrimitiveArray expected data type {} got {}", + T::DATA_TYPE, + data_type + ))); + } + if let Some(n) = nulls.as_ref() { - assert_eq!(values.len(), n.len()); + if n.len() != values.len() { + return Err(ArrowError::InvalidArgumentError(format!( + "Incorrect number of nulls for PrimitiveArray, expected {} got {}", + values.len(), + n.len(), + ))); + } } - Self { + Ok(Self { data_type, values, nulls, - } + }) + } + + /// Deconstruct this array into its constituent parts + pub fn into_parts(self) -> (DataType, ScalarBuffer, Option) { + (self.data_type, self.values, self.nulls) } /// Asserts that `data_type` is compatible with `Self`