Skip to main content

arrow_array/array/
primitive_array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::array::print_long_array;
6use crate::builder::{BooleanBufferBuilder, PrimitiveBuilder};
7use crate::iterator::PrimitiveIter;
8use crate::temporal_conversions::{
9    as_datetime, as_datetime_with_data_type, as_datetime_with_timezone,
10    as_datetime_with_timezone_and_data_type, as_duration, as_time, as_time_with_data_type,
11};
12use crate::timezone::Tz;
13use crate::trusted_len::trusted_len_unzip;
14use crate::types::*;
15use crate::{Array, ArrayAccessor, ArrayRef, Scalar};
16use arrow_buffer::{ArrowNativeType, Buffer, NullBuffer, NullBufferBuilder, ScalarBuffer, i256};
17use arrow_data::bit_iterator::try_for_each_valid_idx;
18use arrow_data::{ArrayData, ArrayDataBuilder};
19use arrow_schema::{ArrowError, DataType};
20use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime};
21use half::f16;
22use std::any::Any;
23use std::sync::Arc;
24
25/// A [`PrimitiveArray`] of `i8`
26///
27/// # Examples
28///
29/// Construction
30///
31/// ```
32/// # use arrow_array::Int8Array;
33/// // Create from Vec<Option<i8>>
34/// let arr = Int8Array::from(vec![Some(1), None, Some(2)]);
35/// // Create from Vec<i8>
36/// let arr = Int8Array::from(vec![1, 2, 3]);
37/// // Create iter/collect
38/// let arr: Int8Array = std::iter::repeat(42).take(10).collect();
39/// ```
40///
41/// See [`PrimitiveArray`] for more information and examples
42pub type Int8Array = PrimitiveArray<Int8Type>;
43
44/// A [`PrimitiveArray`] of `i16`
45///
46/// # Examples
47///
48/// Construction
49///
50/// ```
51/// # use arrow_array::Int16Array;
52/// // Create from Vec<Option<i16>>
53/// let arr = Int16Array::from(vec![Some(1), None, Some(2)]);
54/// // Create from Vec<i16>
55/// let arr = Int16Array::from(vec![1, 2, 3]);
56/// // Create iter/collect
57/// let arr: Int16Array = std::iter::repeat(42).take(10).collect();
58/// ```
59///
60/// See [`PrimitiveArray`] for more information and examples
61pub type Int16Array = PrimitiveArray<Int16Type>;
62
63/// A [`PrimitiveArray`] of `i32`
64///
65/// # Examples
66///
67/// Construction
68///
69/// ```
70/// # use arrow_array::Int32Array;
71/// // Create from Vec<Option<i32>>
72/// let arr = Int32Array::from(vec![Some(1), None, Some(2)]);
73/// // Create from Vec<i32>
74/// let arr = Int32Array::from(vec![1, 2, 3]);
75/// // Create iter/collect
76/// let arr: Int32Array = std::iter::repeat(42).take(10).collect();
77/// ```
78///
79/// See [`PrimitiveArray`] for more information and examples
80pub type Int32Array = PrimitiveArray<Int32Type>;
81
82/// A [`PrimitiveArray`] of `i64`
83///
84/// # Examples
85///
86/// Construction
87///
88/// ```
89/// # use arrow_array::Int64Array;
90/// // Create from Vec<Option<i64>>
91/// let arr = Int64Array::from(vec![Some(1), None, Some(2)]);
92/// // Create from Vec<i64>
93/// let arr = Int64Array::from(vec![1, 2, 3]);
94/// // Create iter/collect
95/// let arr: Int64Array = std::iter::repeat(42).take(10).collect();
96/// ```
97///
98/// See [`PrimitiveArray`] for more information and examples
99pub type Int64Array = PrimitiveArray<Int64Type>;
100
101/// A [`PrimitiveArray`] of `u8`
102///
103/// # Examples
104///
105/// Construction
106///
107/// ```
108/// # use arrow_array::UInt8Array;
109/// // Create from Vec<Option<u8>>
110/// let arr = UInt8Array::from(vec![Some(1), None, Some(2)]);
111/// // Create from Vec<u8>
112/// let arr = UInt8Array::from(vec![1, 2, 3]);
113/// // Create iter/collect
114/// let arr: UInt8Array = std::iter::repeat(42).take(10).collect();
115/// ```
116///
117/// See [`PrimitiveArray`] for more information and examples
118pub type UInt8Array = PrimitiveArray<UInt8Type>;
119
120/// A [`PrimitiveArray`] of `u16`
121///
122/// # Examples
123///
124/// Construction
125///
126/// ```
127/// # use arrow_array::UInt16Array;
128/// // Create from Vec<Option<u16>>
129/// let arr = UInt16Array::from(vec![Some(1), None, Some(2)]);
130/// // Create from Vec<u16>
131/// let arr = UInt16Array::from(vec![1, 2, 3]);
132/// // Create iter/collect
133/// let arr: UInt16Array = std::iter::repeat(42).take(10).collect();
134/// ```
135///
136/// See [`PrimitiveArray`] for more information and examples
137pub type UInt16Array = PrimitiveArray<UInt16Type>;
138
139/// A [`PrimitiveArray`] of `u32`
140///
141/// # Examples
142///
143/// Construction
144///
145/// ```
146/// # use arrow_array::UInt32Array;
147/// // Create from Vec<Option<u32>>
148/// let arr = UInt32Array::from(vec![Some(1), None, Some(2)]);
149/// // Create from Vec<u32>
150/// let arr = UInt32Array::from(vec![1, 2, 3]);
151/// // Create iter/collect
152/// let arr: UInt32Array = std::iter::repeat(42).take(10).collect();
153/// ```
154///
155/// See [`PrimitiveArray`] for more information and examples
156pub type UInt32Array = PrimitiveArray<UInt32Type>;
157
158/// A [`PrimitiveArray`] of `u64`
159///
160/// # Examples
161///
162/// Construction
163///
164/// ```
165/// # use arrow_array::UInt64Array;
166/// // Create from Vec<Option<u64>>
167/// let arr = UInt64Array::from(vec![Some(1), None, Some(2)]);
168/// // Create from Vec<u64>
169/// let arr = UInt64Array::from(vec![1, 2, 3]);
170/// // Create iter/collect
171/// let arr: UInt64Array = std::iter::repeat(42).take(10).collect();
172/// ```
173///
174/// See [`PrimitiveArray`] for more information and examples
175pub type UInt64Array = PrimitiveArray<UInt64Type>;
176
177/// A [`PrimitiveArray`] of `f16`
178///
179/// # Examples
180///
181/// Construction
182///
183/// ```
184/// # use arrow_array::Float16Array;
185/// use half::f16;
186/// // Create from Vec<Option<f16>>
187/// let arr = Float16Array::from(vec![Some(f16::from_f64(1.0)), Some(f16::from_f64(2.0))]);
188/// // Create from Vec<i8>
189/// let arr = Float16Array::from(vec![f16::from_f64(1.0), f16::from_f64(2.0), f16::from_f64(3.0)]);
190/// // Create iter/collect
191/// let arr: Float16Array = std::iter::repeat(f16::from_f64(1.0)).take(10).collect();
192/// ```
193///
194/// # Example: Using `collect`
195/// ```
196/// # use arrow_array::Float16Array;
197/// use half::f16;
198/// let arr : Float16Array = [Some(f16::from_f64(1.0)), Some(f16::from_f64(2.0))].into_iter().collect();
199/// ```
200///
201/// See [`PrimitiveArray`] for more information and examples
202pub type Float16Array = PrimitiveArray<Float16Type>;
203
204/// A [`PrimitiveArray`] of `f32`
205///
206/// # Examples
207///
208/// Construction
209///
210/// ```
211/// # use arrow_array::Float32Array;
212/// // Create from Vec<Option<f32>>
213/// let arr = Float32Array::from(vec![Some(1.0), None, Some(2.0)]);
214/// // Create from Vec<f32>
215/// let arr = Float32Array::from(vec![1.0, 2.0, 3.0]);
216/// // Create iter/collect
217/// let arr: Float32Array = std::iter::repeat(42.0).take(10).collect();
218/// ```
219///
220/// See [`PrimitiveArray`] for more information and examples
221pub type Float32Array = PrimitiveArray<Float32Type>;
222
223/// A [`PrimitiveArray`] of `f64`
224///
225/// # Examples
226///
227/// Construction
228///
229/// ```
230/// # use arrow_array::Float64Array;
231/// // Create from Vec<Option<f32>>
232/// let arr = Float64Array::from(vec![Some(1.0), None, Some(2.0)]);
233/// // Create from Vec<f32>
234/// let arr = Float64Array::from(vec![1.0, 2.0, 3.0]);
235/// // Create iter/collect
236/// let arr: Float64Array = std::iter::repeat(42.0).take(10).collect();
237/// ```
238///
239/// See [`PrimitiveArray`] for more information and examples
240pub type Float64Array = PrimitiveArray<Float64Type>;
241
242/// A [`PrimitiveArray`] of seconds since UNIX epoch stored as `i64`
243///
244/// This type is similar to the [`chrono::DateTime`] type and can hold
245/// values such as `1970-05-09 14:25:11 +01:00`
246///
247/// See also [`Timestamp`](arrow_schema::DataType::Timestamp).
248///
249/// # Example: UTC timestamps post epoch
250/// ```
251/// # use arrow_array::TimestampSecondArray;
252/// use arrow_array::timezone::Tz;
253/// // Corresponds to single element array with entry 1970-05-09T14:25:11+0:00
254/// let arr = TimestampSecondArray::from(vec![11111111]);
255/// // OR
256/// let arr = TimestampSecondArray::from(vec![Some(11111111)]);
257/// let utc_tz: Tz = "+00:00".parse().unwrap();
258///
259/// assert_eq!(arr.value_as_datetime_with_tz(0, utc_tz).map(|v| v.to_string()).unwrap(), "1970-05-09 14:25:11 +00:00")
260/// ```
261///
262/// # Example: UTC timestamps pre epoch
263/// ```
264/// # use arrow_array::TimestampSecondArray;
265/// use arrow_array::timezone::Tz;
266/// // Corresponds to single element array with entry 1969-08-25T09:34:49+0:00
267/// let arr = TimestampSecondArray::from(vec![-11111111]);
268/// // OR
269/// let arr = TimestampSecondArray::from(vec![Some(-11111111)]);
270/// let utc_tz: Tz = "+00:00".parse().unwrap();
271///
272/// assert_eq!(arr.value_as_datetime_with_tz(0, utc_tz).map(|v| v.to_string()).unwrap(), "1969-08-25 09:34:49 +00:00")
273/// ```
274///
275/// # Example: With timezone specified
276/// ```
277/// # use arrow_array::TimestampSecondArray;
278/// use arrow_array::timezone::Tz;
279/// // Corresponds to single element array with entry 1970-05-10T00:25:11+10:00
280/// let arr = TimestampSecondArray::from(vec![11111111]).with_timezone("+10:00".to_string());
281/// // OR
282/// let arr = TimestampSecondArray::from(vec![Some(11111111)]).with_timezone("+10:00".to_string());
283/// let sydney_tz: Tz = "+10:00".parse().unwrap();
284///
285/// assert_eq!(arr.value_as_datetime_with_tz(0, sydney_tz).map(|v| v.to_string()).unwrap(), "1970-05-10 00:25:11 +10:00")
286/// ```
287///
288/// See [`PrimitiveArray`] for more information and examples
289pub type TimestampSecondArray = PrimitiveArray<TimestampSecondType>;
290
291/// A [`PrimitiveArray`] of milliseconds since UNIX epoch stored as `i64`
292///
293/// See examples for [`TimestampSecondArray`]
294pub type TimestampMillisecondArray = PrimitiveArray<TimestampMillisecondType>;
295
296/// A [`PrimitiveArray`] of microseconds since UNIX epoch stored as `i64`
297///
298/// See examples for [`TimestampSecondArray`]
299pub type TimestampMicrosecondArray = PrimitiveArray<TimestampMicrosecondType>;
300
301/// A [`PrimitiveArray`] of nanoseconds since UNIX epoch stored as `i64`
302///
303/// See examples for [`TimestampSecondArray`]
304pub type TimestampNanosecondArray = PrimitiveArray<TimestampNanosecondType>;
305
306/// A [`PrimitiveArray`] of days since UNIX epoch stored as `i32`
307///
308/// This type is similar to the [`chrono::NaiveDate`] type and can hold
309/// values such as `2018-11-13`
310pub type Date32Array = PrimitiveArray<Date32Type>;
311
312/// A [`PrimitiveArray`] of milliseconds since UNIX epoch stored as `i64`
313///
314/// This type is similar to the [`chrono::NaiveDate`] type and can hold
315/// values such as `2018-11-13`
316pub type Date64Array = PrimitiveArray<Date64Type>;
317
318/// A [`PrimitiveArray`] of seconds since midnight stored as `i32`
319///
320/// This type is similar to the [`chrono::NaiveTime`] type and can
321/// hold values such as `00:02:00`
322pub type Time32SecondArray = PrimitiveArray<Time32SecondType>;
323
324/// A [`PrimitiveArray`] of milliseconds since midnight stored as `i32`
325///
326/// This type is similar to the [`chrono::NaiveTime`] type and can
327/// hold values such as `00:02:00.123`
328pub type Time32MillisecondArray = PrimitiveArray<Time32MillisecondType>;
329
330/// A [`PrimitiveArray`] of microseconds since midnight stored as `i64`
331///
332/// This type is similar to the [`chrono::NaiveTime`] type and can
333/// hold values such as `00:02:00.123456`
334pub type Time64MicrosecondArray = PrimitiveArray<Time64MicrosecondType>;
335
336/// A [`PrimitiveArray`] of nanoseconds since midnight stored as `i64`
337///
338/// This type is similar to the [`chrono::NaiveTime`] type and can
339/// hold values such as `00:02:00.123456789`
340pub type Time64NanosecondArray = PrimitiveArray<Time64NanosecondType>;
341
342/// A [`PrimitiveArray`] of “calendar” intervals in whole months
343///
344/// See [`IntervalYearMonthType`] for details on representation and caveats.
345///
346/// # Example
347/// ```
348/// # use arrow_array::IntervalYearMonthArray;
349/// let array = IntervalYearMonthArray::from(vec![
350///   2,  // 2 months
351///   25, // 2 years and 1 month
352///   -1  // -1 months
353/// ]);
354/// ```
355pub type IntervalYearMonthArray = PrimitiveArray<IntervalYearMonthType>;
356
357/// A [`PrimitiveArray`] of “calendar” intervals in days and milliseconds
358///
359/// See [`IntervalDayTime`] for details on representation and caveats.
360///
361/// # Example
362/// ```
363/// # use arrow_array::IntervalDayTimeArray;
364/// use arrow_array::types::IntervalDayTime;
365/// let array = IntervalDayTimeArray::from(vec![
366///   IntervalDayTime::new(1, 1000),                 // 1 day, 1000 milliseconds
367///   IntervalDayTime::new(33, 0),                  // 33 days, 0 milliseconds
368///   IntervalDayTime::new(0, 12 * 60 * 60 * 1000), // 0 days, 12 hours
369/// ]);
370/// ```
371pub type IntervalDayTimeArray = PrimitiveArray<IntervalDayTimeType>;
372
373/// A [`PrimitiveArray`] of “calendar” intervals in  months, days, and nanoseconds.
374///
375/// See [`IntervalMonthDayNano`] for details on representation and caveats.
376///
377/// # Example
378/// ```
379/// # use arrow_array::IntervalMonthDayNanoArray;
380/// use arrow_array::types::IntervalMonthDayNano;
381/// let array = IntervalMonthDayNanoArray::from(vec![
382///   IntervalMonthDayNano::new(1, 2, 1000),             // 1 month, 2 days, 1 nanosecond
383///   IntervalMonthDayNano::new(12, 1, 0),               // 12 months, 1 days, 0 nanoseconds
384///   IntervalMonthDayNano::new(0, 0, 12 * 1000 * 1000), // 0 days, 12 milliseconds
385/// ]);
386/// ```
387pub type IntervalMonthDayNanoArray = PrimitiveArray<IntervalMonthDayNanoType>;
388
389/// A [`PrimitiveArray`] of elapsed durations in seconds
390pub type DurationSecondArray = PrimitiveArray<DurationSecondType>;
391
392/// A [`PrimitiveArray`] of elapsed durations in milliseconds
393pub type DurationMillisecondArray = PrimitiveArray<DurationMillisecondType>;
394
395/// A [`PrimitiveArray`] of elapsed durations in microseconds
396pub type DurationMicrosecondArray = PrimitiveArray<DurationMicrosecondType>;
397
398/// A [`PrimitiveArray`] of elapsed durations in nanoseconds
399pub type DurationNanosecondArray = PrimitiveArray<DurationNanosecondType>;
400
401/// A [`PrimitiveArray`] of 32-bit fixed point decimals
402///
403/// # Examples
404///
405/// Construction
406///
407/// ```
408/// # use arrow_array::Decimal32Array;
409/// // Create from Vec<Option<i32>>
410/// let arr = Decimal32Array::from(vec![Some(1), None, Some(2)]);
411/// // Create from Vec<i32>
412/// let arr = Decimal32Array::from(vec![1, 2, 3]);
413/// // Create iter/collect
414/// let arr: Decimal32Array = std::iter::repeat(42).take(10).collect();
415/// ```
416///
417/// See [`PrimitiveArray`] for more information and examples
418pub type Decimal32Array = PrimitiveArray<Decimal32Type>;
419
420/// A [`PrimitiveArray`] of 64-bit fixed point decimals
421///
422/// # Examples
423///
424/// Construction
425///
426/// ```
427/// # use arrow_array::Decimal64Array;
428/// // Create from Vec<Option<i64>>
429/// let arr = Decimal64Array::from(vec![Some(1), None, Some(2)]);
430/// // Create from Vec<i64>
431/// let arr = Decimal64Array::from(vec![1, 2, 3]);
432/// // Create iter/collect
433/// let arr: Decimal64Array = std::iter::repeat(42).take(10).collect();
434/// ```
435///
436/// See [`PrimitiveArray`] for more information and examples
437pub type Decimal64Array = PrimitiveArray<Decimal64Type>;
438
439/// A [`PrimitiveArray`] of 128-bit fixed point decimals
440///
441/// # Examples
442///
443/// Construction
444///
445/// ```
446/// # use arrow_array::Decimal128Array;
447/// // Create from Vec<Option<i128>>
448/// let arr = Decimal128Array::from(vec![Some(1), None, Some(2)]);
449/// // Create from Vec<i128>
450/// let arr = Decimal128Array::from(vec![1, 2, 3]);
451/// // Create iter/collect
452/// let arr: Decimal128Array = std::iter::repeat(42).take(10).collect();
453/// ```
454///
455/// See [`PrimitiveArray`] for more information and examples
456pub type Decimal128Array = PrimitiveArray<Decimal128Type>;
457
458/// A [`PrimitiveArray`] of 256-bit fixed point decimals
459///
460/// # Examples
461///
462/// Construction
463///
464/// ```
465/// # use arrow_array::Decimal256Array;
466/// use arrow_buffer::i256;
467/// // Create from Vec<Option<i256>>
468/// let arr = Decimal256Array::from(vec![Some(i256::from(1)), None, Some(i256::from(2))]);
469/// // Create from Vec<i256>
470/// let arr = Decimal256Array::from(vec![i256::from(1), i256::from(2), i256::from(3)]);
471/// // Create iter/collect
472/// let arr: Decimal256Array = std::iter::repeat(i256::from(42)).take(10).collect();
473/// ```
474///
475/// See [`PrimitiveArray`] for more information and examples
476pub type Decimal256Array = PrimitiveArray<Decimal256Type>;
477
478pub use crate::types::ArrowPrimitiveType;
479
480/// An array of primitive values, of type [`ArrowPrimitiveType`]
481///
482/// # Example: From a Vec
483///
484/// *Note*: Converting a `Vec` to a `PrimitiveArray` does not copy the data.
485/// The new `PrimitiveArray` uses the same underlying allocation from the `Vec`.
486///
487/// ```
488/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
489/// let arr: PrimitiveArray<Int32Type> = vec![1, 2, 3, 4].into();
490/// assert_eq!(4, arr.len());
491/// assert_eq!(0, arr.null_count());
492/// assert_eq!(arr.values(), &[1, 2, 3, 4])
493/// ```
494///
495/// # Example: To a `Vec<T>`
496///
497/// *Note*: In some cases, converting `PrimitiveArray` to a `Vec` is zero-copy
498/// and does not copy the data (see [`Buffer::into_vec`] for conditions). In
499/// such cases, the `Vec` will use the same underlying memory allocation from
500/// the `PrimitiveArray`.
501///
502/// The Rust compiler generates highly optimized code for operations on
503/// Vec, so using a Vec can often be faster than using a PrimitiveArray directly.
504///
505/// ```
506/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
507/// let arr = PrimitiveArray::<Int32Type>::from(vec![1, 2, 3, 4]);
508/// let starting_ptr = arr.values().as_ptr();
509/// // split into its parts
510/// let (datatype, buffer, nulls) = arr.into_parts();
511/// // Convert the buffer to a Vec<i32> (zero copy)
512/// // (note this requires that there are no other references)
513/// let mut vec: Vec<i32> = buffer.into();
514/// vec[2] = 300;
515/// // put the parts back together
516/// let arr = PrimitiveArray::<Int32Type>::try_new(vec.into(), nulls).unwrap();
517/// assert_eq!(arr.values(), &[1, 2, 300, 4]);
518/// // The same allocation was used
519/// assert_eq!(starting_ptr, arr.values().as_ptr());
520/// ```
521///
522/// # Example: From an optional Vec
523///
524/// ```
525/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
526/// let arr: PrimitiveArray<Int32Type> = vec![Some(1), None, Some(3), None].into();
527/// assert_eq!(4, arr.len());
528/// assert_eq!(2, arr.null_count());
529/// // Note: values for null indexes are arbitrary
530/// assert_eq!(arr.values(), &[1, 0, 3, 0])
531/// ```
532///
533/// # Example: From an iterator of values
534///
535/// ```
536/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
537/// let arr: PrimitiveArray<Int32Type> = (0..10).map(|x| x + 1).collect();
538/// assert_eq!(10, arr.len());
539/// assert_eq!(0, arr.null_count());
540/// for i in 0..10i32 {
541///     assert_eq!(i + 1, arr.value(i as usize));
542/// }
543/// ```
544///
545/// # Example: From an iterator of option
546///
547/// ```
548/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
549/// let arr: PrimitiveArray<Int32Type> = (0..10).map(|x| (x % 2 == 0).then_some(x)).collect();
550/// assert_eq!(10, arr.len());
551/// assert_eq!(5, arr.null_count());
552/// // Note: values for null indexes are arbitrary
553/// assert_eq!(arr.values(), &[0, 0, 2, 0, 4, 0, 6, 0, 8, 0])
554/// ```
555///
556/// # Example: Using Builder
557///
558/// ```
559/// # use arrow_array::Array;
560/// # use arrow_array::builder::PrimitiveBuilder;
561/// # use arrow_array::types::Int32Type;
562/// let mut builder = PrimitiveBuilder::<Int32Type>::new();
563/// builder.append_value(1);
564/// builder.append_null();
565/// builder.append_value(2);
566/// let array = builder.finish();
567/// // Note: values for null indexes are arbitrary
568/// assert_eq!(array.values(), &[1, 0, 2]);
569/// assert!(array.is_null(1));
570/// ```
571///
572/// # Performance: Choosing Between `from` and [`PrimitiveBuilder`]
573///
574/// Rust's `Vec` is highly optimized, and Arrow's conversion from `Vec` to
575/// `PrimitiveArray` is zero-copy. Prefer [`PrimitiveArray::from`] or
576/// [`PrimitiveArray::new`] whenever values are already in a `Vec` or can be collected
577/// into one. [`PrimitiveBuilder`] is backed by a `Vec` and a `NullBufferBuilder`
578/// internally, so it offers no performance advantage. Use it when the array may
579/// contain nulls whose positions aren't known upfront, since it keeps values and the
580/// null bitmask in sync automatically.
581///
582/// # Example: Get a `PrimitiveArray` from an [`ArrayRef`]
583/// ```
584/// # use std::sync::Arc;
585/// # use arrow_array::{Array, cast::AsArray, ArrayRef, Float32Array, PrimitiveArray};
586/// # use arrow_array::types::{Float32Type};
587/// # use arrow_schema::DataType;
588/// # let array: ArrayRef =  Arc::new(Float32Array::from(vec![1.2, 2.3]));
589/// // will panic if the array is not a Float32Array
590/// assert_eq!(&DataType::Float32, array.data_type());
591/// let f32_array: Float32Array  = array.as_primitive().clone();
592/// assert_eq!(f32_array, Float32Array::from(vec![1.2, 2.3]));
593/// ```
594pub struct PrimitiveArray<T: ArrowPrimitiveType> {
595    data_type: DataType,
596    /// Values data
597    values: ScalarBuffer<T::Native>,
598    nulls: Option<NullBuffer>,
599}
600
601impl<T: ArrowPrimitiveType> Clone for PrimitiveArray<T> {
602    fn clone(&self) -> Self {
603        Self {
604            data_type: self.data_type.clone(),
605            values: self.values.clone(),
606            nulls: self.nulls.clone(),
607        }
608    }
609}
610
611impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
612    /// Create a new [`PrimitiveArray`] from the provided values and nulls
613    ///
614    /// # Panics
615    ///
616    /// Panics if [`Self::try_new`] returns an error
617    ///
618    /// # Example
619    ///
620    /// Creating a [`PrimitiveArray`] directly from a [`ScalarBuffer`] and [`NullBuffer`] using
621    /// this constructor is the most performant approach, avoiding any additional allocations
622    ///
623    /// ```
624    /// # use arrow_array::Int32Array;
625    /// # use arrow_array::types::Int32Type;
626    /// # use arrow_buffer::NullBuffer;
627    /// // [1, 2, 3, 4]
628    /// let array = Int32Array::new(vec![1, 2, 3, 4].into(), None);
629    /// // [1, null, 3, 4]
630    /// let nulls = NullBuffer::from(vec![true, false, true, true]);
631    /// let array = Int32Array::new(vec![1, 2, 3, 4].into(), Some(nulls));
632    /// ```
633    pub fn new(values: ScalarBuffer<T::Native>, nulls: Option<NullBuffer>) -> Self {
634        Self::try_new(values, nulls).unwrap()
635    }
636
637    /// Create a new [`PrimitiveArray`] from the provided values and nulls without validation.
638    ///
639    /// # Safety
640    /// - `values.len() == nulls.len()` if `nulls` is `Some`
641    pub unsafe fn new_unchecked(
642        values: ScalarBuffer<T::Native>,
643        nulls: Option<NullBuffer>,
644    ) -> Self {
645        if cfg!(feature = "force_validate") {
646            return Self::new(values, nulls);
647        }
648        Self {
649            data_type: T::DATA_TYPE,
650            values,
651            nulls,
652        }
653    }
654
655    /// Create a new [`PrimitiveArray`] of the given length where all values are null
656    pub fn new_null(length: usize) -> Self {
657        Self {
658            data_type: T::DATA_TYPE,
659            values: vec![T::Native::usize_as(0); length].into(),
660            nulls: Some(NullBuffer::new_null(length)),
661        }
662    }
663
664    /// Create a new [`PrimitiveArray`] from the provided values and nulls
665    ///
666    /// # Errors
667    ///
668    /// Errors if:
669    /// - `values.len() != nulls.len()`
670    pub fn try_new(
671        values: ScalarBuffer<T::Native>,
672        nulls: Option<NullBuffer>,
673    ) -> Result<Self, ArrowError> {
674        if let Some(n) = nulls.as_ref()
675            && n.len() != values.len()
676        {
677            return Err(ArrowError::InvalidArgumentError(format!(
678                "Incorrect length of null buffer for PrimitiveArray, expected {} got {}",
679                values.len(),
680                n.len(),
681            )));
682        }
683
684        Ok(Self {
685            data_type: T::DATA_TYPE,
686            values,
687            nulls,
688        })
689    }
690
691    /// Create a new [`Scalar`] from `value`
692    pub fn new_scalar(value: T::Native) -> Scalar<Self> {
693        Scalar::new(Self {
694            data_type: T::DATA_TYPE,
695            values: vec![value].into(),
696            nulls: None,
697        })
698    }
699
700    /// Deconstruct this array into its constituent parts
701    pub fn into_parts(self) -> (DataType, ScalarBuffer<T::Native>, Option<NullBuffer>) {
702        (self.data_type, self.values, self.nulls)
703    }
704
705    /// Overrides the [`DataType`] of this [`PrimitiveArray`]
706    ///
707    /// Prefer using [`Self::with_timezone`] or [`Self::with_precision_and_scale`] where
708    /// the primitive type is suitably constrained, as these cannot panic
709    ///
710    /// # Panics
711    ///
712    /// Panics if ![Self::is_compatible]
713    pub fn with_data_type(self, data_type: DataType) -> Self {
714        Self::assert_compatible(&data_type);
715        Self { data_type, ..self }
716    }
717
718    /// Asserts that `data_type` is compatible with `Self`
719    fn assert_compatible(data_type: &DataType) {
720        assert!(
721            Self::is_compatible(data_type),
722            "PrimitiveArray expected data type {} got {}",
723            T::DATA_TYPE,
724            data_type
725        );
726    }
727
728    /// Returns the length of this array.
729    #[inline]
730    pub fn len(&self) -> usize {
731        self.values.len()
732    }
733
734    /// Returns whether this array is empty.
735    pub fn is_empty(&self) -> bool {
736        self.values.is_empty()
737    }
738
739    /// Returns the values of this array
740    #[inline]
741    pub fn values(&self) -> &ScalarBuffer<T::Native> {
742        &self.values
743    }
744
745    /// Returns a new primitive array builder
746    pub fn builder(capacity: usize) -> PrimitiveBuilder<T> {
747        PrimitiveBuilder::<T>::with_capacity(capacity)
748    }
749
750    /// Returns if this [`PrimitiveArray`] is compatible with the provided [`DataType`]
751    ///
752    /// This is equivalent to `data_type == T::DATA_TYPE`, however ignores timestamp
753    /// timezones and decimal precision and scale
754    pub fn is_compatible(data_type: &DataType) -> bool {
755        match T::DATA_TYPE {
756            DataType::Timestamp(t1, _) => {
757                matches!(data_type, DataType::Timestamp(t2, _) if &t1 == t2)
758            }
759            DataType::Decimal32(_, _) => matches!(data_type, DataType::Decimal32(_, _)),
760            DataType::Decimal64(_, _) => matches!(data_type, DataType::Decimal64(_, _)),
761            DataType::Decimal128(_, _) => matches!(data_type, DataType::Decimal128(_, _)),
762            DataType::Decimal256(_, _) => matches!(data_type, DataType::Decimal256(_, _)),
763            _ => T::DATA_TYPE.eq(data_type),
764        }
765    }
766
767    /// Returns the primitive value at index `i`.
768    ///
769    /// Note: This method does not check for nulls and the value is arbitrary
770    /// if [`is_null`](Self::is_null) returns true for the index.
771    ///
772    /// # Safety
773    ///
774    /// caller must ensure that the passed in offset is less than the array len()
775    #[inline]
776    pub unsafe fn value_unchecked(&self, i: usize) -> T::Native {
777        unsafe { *self.values.get_unchecked(i) }
778    }
779
780    /// Returns the primitive value at index `i`.
781    ///
782    /// Note: This method does not check for nulls and the value is arbitrary
783    /// if [`is_null`](Self::is_null) returns true for the index.
784    ///
785    /// # Panics
786    /// Panics if index `i` is out of bounds
787    #[inline]
788    pub fn value(&self, i: usize) -> T::Native {
789        assert!(
790            i < self.len(),
791            "Trying to access an element at index {} from a PrimitiveArray of length {}",
792            i,
793            self.len()
794        );
795        unsafe { self.value_unchecked(i) }
796    }
797
798    /// Creates a PrimitiveArray based on an iterator of values without nulls
799    pub fn from_iter_values<I: IntoIterator<Item = T::Native>>(iter: I) -> Self {
800        let val_buf: Buffer = iter.into_iter().collect();
801        let len = val_buf.len() / std::mem::size_of::<T::Native>();
802        Self {
803            data_type: T::DATA_TYPE,
804            values: ScalarBuffer::new(val_buf, 0, len),
805            nulls: None,
806        }
807    }
808
809    /// Creates a PrimitiveArray based on an iterator of values with provided nulls
810    pub fn from_iter_values_with_nulls<I: IntoIterator<Item = T::Native>>(
811        iter: I,
812        nulls: Option<NullBuffer>,
813    ) -> Self {
814        let val_buf: Buffer = iter.into_iter().collect();
815        let len = val_buf.len() / std::mem::size_of::<T::Native>();
816        Self {
817            data_type: T::DATA_TYPE,
818            values: ScalarBuffer::new(val_buf, 0, len),
819            nulls,
820        }
821    }
822
823    /// Creates a PrimitiveArray based on a constant value with `count` elements
824    pub fn from_value(value: T::Native, count: usize) -> Self {
825        let val_buf: Vec<_> = vec![value; count];
826        Self::new(val_buf.into(), None)
827    }
828
829    /// Returns an iterator that returns the values of `array.value(i)` for an iterator with each element `i`
830    pub fn take_iter<'a>(
831        &'a self,
832        indexes: impl Iterator<Item = Option<usize>> + 'a,
833    ) -> impl Iterator<Item = Option<T::Native>> + 'a {
834        indexes.map(|opt_index| opt_index.map(|index| self.value(index)))
835    }
836
837    /// Returns an iterator that returns the values of `array.value(i)` for an iterator with each element `i`
838    /// # Safety
839    ///
840    /// caller must ensure that the offsets in the iterator are less than the array len()
841    pub unsafe fn take_iter_unchecked<'a>(
842        &'a self,
843        indexes: impl Iterator<Item = Option<usize>> + 'a,
844    ) -> impl Iterator<Item = Option<T::Native>> + 'a {
845        indexes.map(|opt_index| opt_index.map(|index| unsafe { self.value_unchecked(index) }))
846    }
847
848    /// Returns a zero-copy slice of this array with the indicated offset and length.
849    ///
850    /// # Panics
851    /// Panics if `offset + length > self.len()`
852    pub fn slice(&self, offset: usize, length: usize) -> Self {
853        Self {
854            data_type: self.data_type.clone(),
855            values: self.values.slice(offset, length),
856            nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
857        }
858    }
859
860    /// Reinterprets this array's contents as a different data type without copying
861    ///
862    /// This can be used to efficiently convert between primitive arrays with the
863    /// same underlying representation
864    ///
865    /// Note: this will not modify the underlying values, and therefore may change
866    /// the semantic values of the array, e.g. 100 milliseconds in a [`TimestampNanosecondArray`]
867    /// will become 100 seconds in a [`TimestampSecondArray`].
868    ///
869    /// For casts that preserve the semantic value, check out the
870    /// [compute kernels](https://docs.rs/arrow/latest/arrow/compute/kernels/cast/index.html).
871    ///
872    /// ```
873    /// # use arrow_array::{Int64Array, TimestampNanosecondArray};
874    /// let a = Int64Array::from_iter_values([1, 2, 3, 4]);
875    /// let b: TimestampNanosecondArray = a.reinterpret_cast();
876    /// ```
877    pub fn reinterpret_cast<K>(&self) -> PrimitiveArray<K>
878    where
879        K: ArrowPrimitiveType<Native = T::Native>,
880    {
881        PrimitiveArray::new(self.values.clone(), self.nulls.clone())
882    }
883
884    /// Applies a unary infallible function to a primitive array, producing a
885    /// new array of potentially different type.
886    ///
887    /// This is the fastest way to perform an operation on a primitive array
888    /// when the benefits of a vectorized operation outweigh the cost of
889    /// branching nulls and non-nulls.
890    ///
891    /// See also
892    /// * [`Self::unary_mut`] for in place modification.
893    /// * [`Self::try_unary`] for fallible operations.
894    /// * [`arrow::compute::binary`] for binary operations
895    ///
896    /// [`arrow::compute::binary`]: https://docs.rs/arrow/latest/arrow/compute/fn.binary.html
897    /// # Null Handling
898    ///
899    /// Applies the function for all values, including those on null slots. This
900    /// will often allow the compiler to generate faster vectorized code, but
901    /// requires that the operation must be infallible (not error/panic) for any
902    /// value of the corresponding type or this function may panic.
903    ///
904    /// # Example
905    /// ```rust
906    /// # use arrow_array::{Int32Array, Float32Array, types::Int32Type};
907    /// # fn main() {
908    /// let array = Int32Array::from(vec![Some(5), Some(7), None]);
909    /// // Create a new array with the value of applying sqrt
910    /// let c = array.unary(|x| f32::sqrt(x as f32));
911    /// assert_eq!(c, Float32Array::from(vec![Some(2.236068), Some(2.6457512), None]));
912    /// # }
913    /// ```
914    pub fn unary<F, O>(&self, op: F) -> PrimitiveArray<O>
915    where
916        O: ArrowPrimitiveType,
917        F: Fn(T::Native) -> O::Native,
918    {
919        let nulls = self.nulls().cloned();
920        // `move` puts `op`'s captures in the iterator rather than behind a reference, so the
921        // loop doesn't reload them for each value when `collect` isn't inlined
922        let values = self.values().into_iter().map(move |v| op(*v));
923        let buffer: Vec<_> = values.collect();
924        PrimitiveArray::new(buffer.into(), nulls)
925    }
926
927    /// Applies a unary and infallible function to the array in place if possible.
928    ///
929    /// # Buffer Reuse
930    ///
931    /// If the underlying buffers are not shared with other arrays,  mutates the
932    /// underlying buffer in place, without allocating.
933    ///
934    /// If the underlying buffer is shared, returns Err(self)
935    ///
936    /// # Null Handling
937    ///
938    /// See [`Self::unary`] for more information on null handling.
939    ///
940    /// # Example
941    ///
942    /// ```rust
943    /// # use arrow_array::{Int32Array, types::Int32Type};
944    /// let array = Int32Array::from(vec![Some(5), Some(7), None]);
945    /// // Apply x*2+1 to the data in place, no allocations
946    /// let c = array.unary_mut(|x| x * 2 + 1).unwrap();
947    /// assert_eq!(c, Int32Array::from(vec![Some(11), Some(15), None]));
948    /// ```
949    ///
950    /// # Example: modify [`ArrayRef`] in place, if not shared
951    ///
952    /// It is also possible to modify an [`ArrayRef`] if there are no other
953    /// references to the underlying buffer.
954    ///
955    /// ```rust
956    /// # use std::sync::Arc;
957    /// # use arrow_array::{Array, cast::AsArray, ArrayRef, Int32Array, PrimitiveArray, types::Int32Type};
958    /// # let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(5), Some(7), None]));
959    /// // Convert to Int32Array (panic's if array.data_type is not Int32)
960    /// let a = array.as_primitive::<Int32Type>().clone();
961    /// // Try to apply x*2+1 to the data in place, fails because array is still shared
962    /// a.unary_mut(|x| x * 2 + 1).unwrap_err();
963    /// // Try again, this time dropping the last remaining reference
964    /// let a = array.as_primitive::<Int32Type>().clone();
965    /// drop(array);
966    /// // Now we can apply the operation in place
967    /// let c = a.unary_mut(|x| x * 2 + 1).unwrap();
968    /// assert_eq!(c, Int32Array::from(vec![Some(11), Some(15), None]));
969    /// ```
970    pub fn unary_mut<F>(self, op: F) -> Result<PrimitiveArray<T>, PrimitiveArray<T>>
971    where
972        F: Fn(T::Native) -> T::Native,
973    {
974        let mut builder = self.into_builder()?;
975        builder
976            .values_slice_mut()
977            .iter_mut()
978            .for_each(|v| *v = op(*v));
979        Ok(builder.finish())
980    }
981
982    /// Applies a unary fallible function to all valid values in a primitive
983    /// array, producing a new array of potentially different type.
984    ///
985    /// Applies `op` to only rows that are valid, which is often significantly
986    /// slower than [`Self::unary`], which should be preferred if `op` is
987    /// fallible.
988    ///
989    /// Note: LLVM is currently unable to effectively vectorize fallible operations
990    pub fn try_unary<F, O, E>(&self, op: F) -> Result<PrimitiveArray<O>, E>
991    where
992        O: ArrowPrimitiveType,
993        F: Fn(T::Native) -> Result<O::Native, E>,
994    {
995        let len = self.len();
996
997        let nulls = self.nulls().cloned();
998        let mut values = vec![O::Native::default(); len];
999        let slice = values.as_mut_slice();
1000
1001        let f = |idx| {
1002            unsafe { *slice.get_unchecked_mut(idx) = op(self.value_unchecked(idx))? };
1003            Ok::<_, E>(())
1004        };
1005
1006        match &nulls {
1007            Some(nulls) => nulls.try_for_each_valid_idx(f)?,
1008            None => (0..len).try_for_each(f)?,
1009        }
1010
1011        let values = values.into();
1012        Ok(PrimitiveArray::new(values, nulls))
1013    }
1014
1015    /// Applies a unary fallible function to all valid values in a mutable
1016    /// primitive array.
1017    ///
1018    /// # Null Handling
1019    ///
1020    /// See [`Self::try_unary`] for more information on null handling.
1021    ///
1022    /// # Buffer Reuse
1023    ///
1024    /// See [`Self::unary_mut`] for more information on buffer reuse.
1025    ///
1026    /// This returns an `Err` when the input array is shared buffer with other
1027    /// array. In the case, returned `Err` wraps input array. If the function
1028    /// encounters an error during applying on values. In the case, this returns an `Err` within
1029    /// an `Ok` which wraps the actual error.
1030    ///
1031    /// Note: LLVM is currently unable to effectively vectorize fallible operations
1032    pub fn try_unary_mut<F, E>(
1033        self,
1034        op: F,
1035    ) -> Result<Result<PrimitiveArray<T>, E>, PrimitiveArray<T>>
1036    where
1037        F: Fn(T::Native) -> Result<T::Native, E>,
1038    {
1039        let len = self.len();
1040        let null_count = self.null_count();
1041        let mut builder = self.into_builder()?;
1042
1043        let (slice, null_buffer) = builder.slices_mut();
1044
1045        let r = try_for_each_valid_idx(len, 0, null_count, null_buffer.as_deref(), |idx| {
1046            unsafe { *slice.get_unchecked_mut(idx) = op(*slice.get_unchecked(idx))? };
1047            Ok::<_, E>(())
1048        });
1049
1050        if let Err(err) = r {
1051            return Ok(Err(err));
1052        }
1053
1054        Ok(Ok(builder.finish()))
1055    }
1056
1057    /// Applies a unary and nullable function to all valid values in a primitive array
1058    ///
1059    /// Applies `op` to only rows that are valid, which is often significantly
1060    /// slower than [`Self::unary`], which should be preferred if `op` is
1061    /// fallible.
1062    ///
1063    /// Note: LLVM is currently unable to effectively vectorize fallible operations
1064    pub fn unary_opt<F, O>(&self, op: F) -> PrimitiveArray<O>
1065    where
1066        O: ArrowPrimitiveType,
1067        F: Fn(T::Native) -> Option<O::Native>,
1068    {
1069        let len = self.len();
1070        let (nulls, null_count, offset) = match self.nulls() {
1071            Some(n) => (Some(n.validity()), n.null_count(), n.offset()),
1072            None => (None, 0, 0),
1073        };
1074
1075        let mut null_builder = BooleanBufferBuilder::new(len);
1076        match nulls {
1077            Some(b) => null_builder.append_packed_range(offset..offset + len, b),
1078            None => null_builder.append_n(len, true),
1079        }
1080
1081        let mut values = vec![O::Native::default(); len];
1082        let slice = values.as_mut_slice();
1083
1084        let mut out_null_count = null_count;
1085
1086        let _ = try_for_each_valid_idx(len, offset, null_count, nulls, |idx| {
1087            match op(unsafe { self.value_unchecked(idx) }) {
1088                Some(v) => unsafe { *slice.get_unchecked_mut(idx) = v },
1089                None => {
1090                    out_null_count += 1;
1091                    null_builder.set_bit(idx, false);
1092                }
1093            }
1094            Ok::<_, ()>(())
1095        });
1096
1097        let nulls = null_builder.finish();
1098        let values = values.into();
1099        let nulls = unsafe { NullBuffer::new_unchecked(nulls, out_null_count) };
1100        PrimitiveArray::new(values, Some(nulls))
1101    }
1102
1103    /// Applies a unary infallible function to each value in an array, producing a
1104    /// new primitive array.
1105    ///
1106    /// # Null Handling
1107    ///
1108    /// See [`Self::unary`] for more information on null handling.
1109    ///
1110    /// # Example: create an [`Int16Array`] from an [`ArrayAccessor`] with item type `&[u8]`
1111    /// ```
1112    /// use arrow_array::{Array, FixedSizeBinaryArray, Int16Array};
1113    /// let input_arg = vec![ vec![1, 0], vec![2, 0], vec![3, 0] ];
1114    /// let arr = FixedSizeBinaryArray::try_from_iter(input_arg.into_iter()).unwrap();
1115    /// let c = Int16Array::from_unary(&arr, |x| i16::from_le_bytes(x[..2].try_into().unwrap()));
1116    /// assert_eq!(c, Int16Array::from(vec![Some(1i16), Some(2i16), Some(3i16)]));
1117    /// ```
1118    pub fn from_unary<U: ArrayAccessor, F>(left: U, mut op: F) -> Self
1119    where
1120        F: FnMut(U::Item) -> T::Native,
1121    {
1122        let nulls = left.logical_nulls();
1123        let buffer: Vec<_> = (0..left.len())
1124            // SAFETY: i in range 0..left.len()
1125            .map(|i| op(unsafe { left.value_unchecked(i) }))
1126            .collect();
1127        PrimitiveArray::new(buffer.into(), nulls)
1128    }
1129
1130    /// Returns a `PrimitiveBuilder` for this array, suitable for mutating values
1131    /// in place.
1132    ///
1133    /// # Buffer Reuse
1134    ///
1135    /// If the underlying data buffer has no other outstanding references, the
1136    /// buffer is used without copying.
1137    ///
1138    /// If the underlying data buffer does have outstanding references, returns
1139    /// `Err(self)`
1140    pub fn into_builder(self) -> Result<PrimitiveBuilder<T>, Self> {
1141        let len = self.len();
1142        let data_type = self.data_type.clone();
1143        let data = self.into_data();
1144        let null_bit_buffer = data.nulls().map(|b| b.inner().sliced());
1145
1146        let element_len = std::mem::size_of::<T::Native>();
1147        let buffer =
1148            data.buffers()[0].slice_with_length(data.offset() * element_len, len * element_len);
1149
1150        drop(data);
1151
1152        let try_mutable_null_buffer = match null_bit_buffer {
1153            None => Ok(None),
1154            Some(null_buffer) => {
1155                // Null buffer exists, tries to make it mutable
1156                null_buffer.into_mutable().map(Some)
1157            }
1158        };
1159
1160        let try_mutable_buffers = match try_mutable_null_buffer {
1161            Ok(mutable_null_buffer) => {
1162                // Got mutable null buffer, tries to get mutable value buffer
1163                let try_mutable_buffer = buffer.into_mutable();
1164
1165                // try_mutable_buffer.map(...).map_err(...) doesn't work as the compiler complains
1166                // mutable_null_buffer is moved into map closure.
1167                match try_mutable_buffer {
1168                    Ok(mutable_buffer) => Ok(PrimitiveBuilder::<T>::new_from_buffer(
1169                        mutable_buffer,
1170                        mutable_null_buffer,
1171                    )),
1172                    Err(buffer) => Err((buffer, mutable_null_buffer.map(|b| b.into()))),
1173                }
1174            }
1175            Err(mutable_null_buffer) => {
1176                // Unable to get mutable null buffer
1177                Err((buffer, Some(mutable_null_buffer)))
1178            }
1179        };
1180
1181        match try_mutable_buffers {
1182            Ok(builder) => Ok(builder.with_data_type(data_type)),
1183            Err((buffer, null_bit_buffer)) => {
1184                let builder = ArrayData::builder(data_type)
1185                    .len(len)
1186                    .add_buffer(buffer)
1187                    .null_bit_buffer(null_bit_buffer);
1188
1189                let array_data = unsafe { builder.build_unchecked() };
1190                let array = PrimitiveArray::<T>::from(array_data);
1191
1192                Err(array)
1193            }
1194        }
1195    }
1196}
1197
1198impl<T: ArrowPrimitiveType> From<PrimitiveArray<T>> for ArrayData {
1199    fn from(array: PrimitiveArray<T>) -> Self {
1200        /// Converts the parts of a `PrimitiveArray` into [`ArrayData`].
1201        /// Use an inner function to avoid code duplication over all
1202        /// generic callsites as the body is the same.
1203        ///
1204        /// # Safety
1205        /// The parts must come from a valid `PrimitiveArray`
1206        unsafe fn inner(
1207            data_type: DataType,
1208            len: usize,
1209            values: Buffer,
1210            nulls: Option<NullBuffer>,
1211        ) -> ArrayData {
1212            let builder = ArrayDataBuilder::new(data_type)
1213                .len(len)
1214                .nulls(nulls)
1215                .buffers(vec![values]);
1216
1217            // SAFETY: arguments are valid, per contract
1218            unsafe { builder.build_unchecked() }
1219        }
1220        let len = array.values.len();
1221        // SAFETY: the parts come from a valid PrimitiveArray
1222        unsafe { inner(array.data_type, len, array.values.into_inner(), array.nulls) }
1223    }
1224}
1225
1226/// SAFETY: Correctly implements the contract of Arrow Arrays
1227unsafe impl<T: ArrowPrimitiveType> Array for PrimitiveArray<T> {
1228    fn as_any(&self) -> &dyn Any {
1229        self
1230    }
1231
1232    fn to_arc(&self) -> ArrayRef {
1233        Arc::new(self.clone())
1234    }
1235
1236    fn to_data(&self) -> ArrayData {
1237        self.clone().into()
1238    }
1239
1240    fn into_data(self) -> ArrayData {
1241        self.into()
1242    }
1243
1244    fn data_type(&self) -> &DataType {
1245        &self.data_type
1246    }
1247
1248    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
1249        Arc::new(self.slice(offset, length))
1250    }
1251
1252    fn len(&self) -> usize {
1253        self.values.len()
1254    }
1255
1256    fn is_empty(&self) -> bool {
1257        self.values.is_empty()
1258    }
1259
1260    fn shrink_to_fit(&mut self) {
1261        self.values.shrink_to_fit();
1262        if let Some(nulls) = &mut self.nulls {
1263            nulls.shrink_to_fit();
1264        }
1265    }
1266
1267    fn offset(&self) -> usize {
1268        0
1269    }
1270
1271    fn nulls(&self) -> Option<&NullBuffer> {
1272        self.nulls.as_ref()
1273    }
1274
1275    fn logical_null_count(&self) -> usize {
1276        self.null_count()
1277    }
1278
1279    fn get_buffer_memory_size(&self) -> usize {
1280        let mut size = self.values.inner().capacity();
1281        if let Some(n) = self.nulls.as_ref() {
1282            size += n.buffer().capacity();
1283        }
1284        size
1285    }
1286
1287    fn get_array_memory_size(&self) -> usize {
1288        std::mem::size_of::<Self>() + self.get_buffer_memory_size()
1289    }
1290
1291    #[cfg(feature = "pool")]
1292    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
1293        self.values.claim(pool);
1294        if let Some(nulls) = &self.nulls {
1295            nulls.claim(pool);
1296        }
1297    }
1298}
1299
1300impl<T: ArrowPrimitiveType> ArrayAccessor for &PrimitiveArray<T> {
1301    type Item = T::Native;
1302
1303    fn value(&self, index: usize) -> Self::Item {
1304        PrimitiveArray::value(self, index)
1305    }
1306
1307    #[inline]
1308    unsafe fn value_unchecked(&self, index: usize) -> Self::Item {
1309        unsafe { PrimitiveArray::value_unchecked(self, index) }
1310    }
1311}
1312
1313impl<T: ArrowTemporalType> PrimitiveArray<T>
1314where
1315    i64: From<T::Native>,
1316{
1317    /// Returns value as a chrono `NaiveDateTime`, handling time resolution
1318    ///
1319    /// If a data type cannot be converted to `NaiveDateTime`, a `None` is returned.
1320    /// A valid value is expected, thus the user should first check for validity.
1321    ///
1322    /// See notes on [`PrimitiveArray::value`] regarding nulls and panics
1323    ///
1324    /// # Panics
1325    ///
1326    /// Panics if `i >= self.len()`
1327    pub fn value_as_datetime(&self, i: usize) -> Option<NaiveDateTime> {
1328        as_datetime::<T>(i64::from(self.value(i)))
1329    }
1330
1331    /// Returns value as a chrono `NaiveDateTime`, handling time resolution with the provided tz
1332    ///
1333    /// functionally it is same as `value_as_datetime`, however it adds
1334    /// the passed tz to the to-be-returned NaiveDateTime
1335    ///
1336    /// See notes on [`PrimitiveArray::value`] regarding nulls and panics
1337    ///
1338    /// # Panics
1339    ///
1340    /// Panics if `i >= self.len()`
1341    pub fn value_as_datetime_with_tz(&self, i: usize, tz: Tz) -> Option<DateTime<Tz>> {
1342        as_datetime_with_timezone::<T>(i64::from(self.value(i)), tz)
1343    }
1344
1345    /// Returns value as a chrono `NaiveDate` by using `Self::datetime()`
1346    ///
1347    /// If a data type cannot be converted to `NaiveDate`, a `None` is returned
1348    ///
1349    /// See notes on [`PrimitiveArray::value`] regarding nulls and panics
1350    ///
1351    /// # Panics
1352    ///
1353    /// Panics if `i >= self.len()`
1354    pub fn value_as_date(&self, i: usize) -> Option<NaiveDate> {
1355        self.value_as_datetime(i).map(|datetime| datetime.date())
1356    }
1357
1358    /// Returns a value as a chrono `NaiveTime`
1359    ///
1360    /// `Date32` and `Date64` return UTC midnight as they do not have time resolution
1361    ///
1362    /// See notes on [`PrimitiveArray::value`] regarding nulls and panics
1363    ///
1364    /// # Panics
1365    ///
1366    /// Panics if `i >= self.len()`
1367    pub fn value_as_time(&self, i: usize) -> Option<NaiveTime> {
1368        as_time::<T>(i64::from(self.value(i)))
1369    }
1370
1371    /// Returns a value as a chrono `Duration`
1372    ///
1373    /// If a data type cannot be converted to `Duration`, a `None` is returned
1374    ///
1375    /// See notes on [`PrimitiveArray::value`] regarding nulls and panics
1376    ///
1377    /// # Panics
1378    ///
1379    /// Panics if `i >= self.len()`
1380    pub fn value_as_duration(&self, i: usize) -> Option<Duration> {
1381        as_duration::<T>(i64::from(self.value(i)))
1382    }
1383}
1384
1385/// Writes the `Debug` representation of a single temporal value (converted to
1386/// `i64`) of the given [`DataType`] to `f`
1387fn write_temporal_value(
1388    f: &mut std::fmt::Formatter,
1389    data_type: &DataType,
1390    v: i64,
1391) -> std::fmt::Result {
1392    match data_type {
1393        DataType::Date32 | DataType::Date64 => {
1394            match as_datetime_with_data_type(data_type, v).map(|datetime| datetime.date()) {
1395                Some(date) => write!(f, "{date:?}"),
1396                None => {
1397                    write!(
1398                        f,
1399                        "Cast error: Failed to convert {v} to temporal for {data_type}"
1400                    )
1401                }
1402            }
1403        }
1404        DataType::Time32(_) | DataType::Time64(_) => match as_time_with_data_type(data_type, v) {
1405            Some(time) => write!(f, "{time:?}"),
1406            None => {
1407                write!(
1408                    f,
1409                    "Cast error: Failed to convert {v} to temporal for {data_type}"
1410                )
1411            }
1412        },
1413        DataType::Timestamp(_, tz_string_opt) => {
1414            match tz_string_opt {
1415                // for Timestamp with TimeZone
1416                Some(tz_string) => {
1417                    match tz_string.parse::<Tz>() {
1418                        // if the time zone is valid, construct a DateTime<Tz> and format it as rfc3339
1419                        Ok(tz) => match as_datetime_with_timezone_and_data_type(data_type, v, tz) {
1420                            Some(datetime) => write!(f, "{}", datetime.to_rfc3339()),
1421                            None => write!(
1422                                f,
1423                                "Cast error: Failed to convert {v} to timestamp for {data_type}"
1424                            ),
1425                        },
1426                        // if the time zone is invalid, shows NaiveDateTime with an error message
1427                        Err(_) => match as_datetime_with_data_type(data_type, v) {
1428                            Some(datetime) => {
1429                                write!(f, "{datetime:?} (Unknown Time Zone '{tz_string}')")
1430                            }
1431                            None => write!(
1432                                f,
1433                                "Cast error: Failed to convert {v} to timestamp for {data_type}"
1434                            ),
1435                        },
1436                    }
1437                }
1438                // for Timestamp without TimeZone
1439                None => match as_datetime_with_data_type(data_type, v) {
1440                    Some(datetime) => write!(f, "{datetime:?}"),
1441                    None => write!(
1442                        f,
1443                        "Cast error: Failed to convert {v} to timestamp for {data_type}"
1444                    ),
1445                },
1446            }
1447        }
1448        _ => unreachable!("write_temporal_value called with non-temporal type {data_type}"),
1449    }
1450}
1451
1452impl<T: ArrowPrimitiveType> std::fmt::Debug for PrimitiveArray<T> {
1453    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1454        let data_type = self.data_type();
1455
1456        write!(f, "PrimitiveArray<{data_type}>\n[\n")?;
1457        // Keep the per-value closure as small as possible: temporal formatting
1458        // is dispatched to the non-generic `write_temporal_value` so it is not
1459        // instantiated for every primitive type (see #10889)
1460        print_long_array(self, f, &mut |index, f| match data_type {
1461            DataType::Date32
1462            | DataType::Date64
1463            | DataType::Time32(_)
1464            | DataType::Time64(_)
1465            | DataType::Timestamp(_, _) => {
1466                write_temporal_value(f, data_type, self.value(index).to_i64().unwrap())
1467            }
1468            _ => std::fmt::Debug::fmt(&self.value(index), f),
1469        })?;
1470        write!(f, "]")
1471    }
1472}
1473
1474impl<'a, T: ArrowPrimitiveType> IntoIterator for &'a PrimitiveArray<T> {
1475    type Item = Option<<T as ArrowPrimitiveType>::Native>;
1476    type IntoIter = PrimitiveIter<'a, T>;
1477
1478    fn into_iter(self) -> Self::IntoIter {
1479        PrimitiveIter::<'a, T>::new(self)
1480    }
1481}
1482
1483impl<'a, T: ArrowPrimitiveType> PrimitiveArray<T> {
1484    /// constructs a new iterator
1485    pub fn iter(&'a self) -> PrimitiveIter<'a, T> {
1486        PrimitiveIter::<'a, T>::new(self)
1487    }
1488}
1489
1490/// An optional primitive value
1491///
1492/// This struct is used as an adapter when creating `PrimitiveArray` from an iterator.
1493/// `FromIterator` for `PrimitiveArray` takes an iterator where the elements can be `into`
1494/// this struct. So once implementing `From` or `Into` trait for a type, an iterator of
1495/// the type can be collected to `PrimitiveArray`.
1496#[derive(Debug)]
1497pub struct NativeAdapter<T: ArrowPrimitiveType> {
1498    /// Corresponding Rust native type if available
1499    pub native: Option<T::Native>,
1500}
1501
1502macro_rules! def_from_for_primitive {
1503    ( $ty:ident, $tt:tt) => {
1504        impl From<$tt> for NativeAdapter<$ty> {
1505            fn from(value: $tt) -> Self {
1506                NativeAdapter {
1507                    native: Some(value),
1508                }
1509            }
1510        }
1511    };
1512}
1513
1514def_from_for_primitive!(Int8Type, i8);
1515def_from_for_primitive!(Int16Type, i16);
1516def_from_for_primitive!(Int32Type, i32);
1517def_from_for_primitive!(Int64Type, i64);
1518def_from_for_primitive!(UInt8Type, u8);
1519def_from_for_primitive!(UInt16Type, u16);
1520def_from_for_primitive!(UInt32Type, u32);
1521def_from_for_primitive!(UInt64Type, u64);
1522def_from_for_primitive!(Float16Type, f16);
1523def_from_for_primitive!(Float32Type, f32);
1524def_from_for_primitive!(Float64Type, f64);
1525def_from_for_primitive!(Decimal32Type, i32);
1526def_from_for_primitive!(Decimal64Type, i64);
1527def_from_for_primitive!(Decimal128Type, i128);
1528def_from_for_primitive!(Decimal256Type, i256);
1529
1530impl<T: ArrowPrimitiveType> From<Option<<T as ArrowPrimitiveType>::Native>> for NativeAdapter<T> {
1531    fn from(value: Option<<T as ArrowPrimitiveType>::Native>) -> Self {
1532        NativeAdapter { native: value }
1533    }
1534}
1535
1536impl<T: ArrowPrimitiveType> From<&Option<<T as ArrowPrimitiveType>::Native>> for NativeAdapter<T> {
1537    fn from(value: &Option<<T as ArrowPrimitiveType>::Native>) -> Self {
1538        NativeAdapter { native: *value }
1539    }
1540}
1541
1542impl<T: ArrowPrimitiveType, Ptr: Into<NativeAdapter<T>>> FromIterator<Ptr> for PrimitiveArray<T> {
1543    fn from_iter<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
1544        let iter = iter.into_iter();
1545        let (lower, _) = iter.size_hint();
1546
1547        let mut null_builder = NullBufferBuilder::new(lower);
1548
1549        let buffer: Buffer = iter
1550            .map(|item| {
1551                if let Some(a) = item.into().native {
1552                    null_builder.append_non_null();
1553                    a
1554                } else {
1555                    null_builder.append_null();
1556                    // this ensures that null items on the buffer are not arbitrary.
1557                    // This is important because fallible operations can use null values (e.g. a vectorized "add")
1558                    // which may panic (e.g. overflow if the number on the slots happen to be very large).
1559                    T::Native::default()
1560                }
1561            })
1562            .collect();
1563
1564        let maybe_nulls = null_builder.finish();
1565        PrimitiveArray::new(ScalarBuffer::from(buffer), maybe_nulls)
1566    }
1567}
1568
1569impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
1570    /// Creates a [`PrimitiveArray`] from an iterator of trusted length.
1571    /// # Safety
1572    /// The iterator must be [`TrustedLen`](https://doc.rust-lang.org/std/iter/trait.TrustedLen.html).
1573    /// I.e. that `size_hint().1` correctly reports its length.
1574    #[inline]
1575    pub unsafe fn from_trusted_len_iter<I, P>(iter: I) -> Self
1576    where
1577        P: std::borrow::Borrow<Option<<T as ArrowPrimitiveType>::Native>>,
1578        I: IntoIterator<Item = P>,
1579    {
1580        let iterator = iter.into_iter();
1581        let (_, upper) = iterator.size_hint();
1582        let len = upper.expect("trusted_len_unzip requires an upper limit");
1583
1584        let (null, buffer) = unsafe { trusted_len_unzip(iterator) };
1585
1586        let nulls = NullBuffer::from_unsliced_buffer(null, len);
1587        PrimitiveArray::new(ScalarBuffer::from(buffer), nulls)
1588    }
1589}
1590
1591// TODO: the macro is needed here because we'd get "conflicting implementations" error
1592// otherwise with both `From<Vec<T::Native>>` and `From<Vec<Option<T::Native>>>`.
1593// We should revisit this in future.
1594macro_rules! def_numeric_from_vec {
1595    ( $ty:ident ) => {
1596        impl From<Vec<<$ty as ArrowPrimitiveType>::Native>> for PrimitiveArray<$ty> {
1597            fn from(data: Vec<<$ty as ArrowPrimitiveType>::Native>) -> Self {
1598                let buffer = ScalarBuffer::from(Buffer::from_vec(data));
1599                let nulls = None;
1600                PrimitiveArray::new(buffer, nulls)
1601            }
1602        }
1603
1604        // Constructs a primitive array from a vector. Should only be used for testing.
1605        impl From<Vec<Option<<$ty as ArrowPrimitiveType>::Native>>> for PrimitiveArray<$ty> {
1606            fn from(data: Vec<Option<<$ty as ArrowPrimitiveType>::Native>>) -> Self {
1607                PrimitiveArray::from_iter(data.iter())
1608            }
1609        }
1610    };
1611}
1612
1613def_numeric_from_vec!(Int8Type);
1614def_numeric_from_vec!(Int16Type);
1615def_numeric_from_vec!(Int32Type);
1616def_numeric_from_vec!(Int64Type);
1617def_numeric_from_vec!(UInt8Type);
1618def_numeric_from_vec!(UInt16Type);
1619def_numeric_from_vec!(UInt32Type);
1620def_numeric_from_vec!(UInt64Type);
1621def_numeric_from_vec!(Float16Type);
1622def_numeric_from_vec!(Float32Type);
1623def_numeric_from_vec!(Float64Type);
1624def_numeric_from_vec!(Decimal32Type);
1625def_numeric_from_vec!(Decimal64Type);
1626def_numeric_from_vec!(Decimal128Type);
1627def_numeric_from_vec!(Decimal256Type);
1628
1629def_numeric_from_vec!(Date32Type);
1630def_numeric_from_vec!(Date64Type);
1631def_numeric_from_vec!(Time32SecondType);
1632def_numeric_from_vec!(Time32MillisecondType);
1633def_numeric_from_vec!(Time64MicrosecondType);
1634def_numeric_from_vec!(Time64NanosecondType);
1635def_numeric_from_vec!(IntervalYearMonthType);
1636def_numeric_from_vec!(IntervalDayTimeType);
1637def_numeric_from_vec!(IntervalMonthDayNanoType);
1638def_numeric_from_vec!(DurationSecondType);
1639def_numeric_from_vec!(DurationMillisecondType);
1640def_numeric_from_vec!(DurationMicrosecondType);
1641def_numeric_from_vec!(DurationNanosecondType);
1642def_numeric_from_vec!(TimestampSecondType);
1643def_numeric_from_vec!(TimestampMillisecondType);
1644def_numeric_from_vec!(TimestampMicrosecondType);
1645def_numeric_from_vec!(TimestampNanosecondType);
1646
1647impl<T: ArrowTimestampType> PrimitiveArray<T> {
1648    /// Returns the timezone of this array if any
1649    pub fn timezone(&self) -> Option<&str> {
1650        match self.data_type() {
1651            DataType::Timestamp(_, tz) => tz.as_deref(),
1652            _ => unreachable!(),
1653        }
1654    }
1655
1656    /// Construct a timestamp array with new timezone
1657    pub fn with_timezone(self, timezone: impl Into<Arc<str>>) -> Self {
1658        self.with_timezone_opt(Some(timezone.into()))
1659    }
1660
1661    /// Construct a timestamp array with UTC
1662    pub fn with_timezone_utc(self) -> Self {
1663        self.with_timezone("+00:00")
1664    }
1665
1666    /// Construct a timestamp array with an optional timezone
1667    pub fn with_timezone_opt<S: Into<Arc<str>>>(self, timezone: Option<S>) -> Self {
1668        Self {
1669            data_type: DataType::Timestamp(T::UNIT, timezone.map(Into::into)),
1670            ..self
1671        }
1672    }
1673}
1674
1675/// Constructs a `PrimitiveArray` from an array data reference.
1676impl<T: ArrowPrimitiveType> From<ArrayData> for PrimitiveArray<T> {
1677    fn from(data: ArrayData) -> Self {
1678        let (data_type, len, nulls, offset, mut buffers, _child_data) = data.into_parts();
1679
1680        Self::assert_compatible(&data_type);
1681        assert_eq!(
1682            buffers.len(),
1683            1,
1684            "PrimitiveArray data should contain a single buffer only (values buffer)"
1685        );
1686        let buffer = buffers.pop().expect("checked above");
1687
1688        let values = ScalarBuffer::new(buffer, offset, len);
1689        Self {
1690            data_type,
1691            values,
1692            nulls,
1693        }
1694    }
1695}
1696
1697impl<T: DecimalType + ArrowPrimitiveType> PrimitiveArray<T> {
1698    /// Returns a Decimal array with the same data as self, with the
1699    /// specified precision and scale.
1700    ///
1701    /// See [`validate_decimal_precision_and_scale`]
1702    pub fn with_precision_and_scale(self, precision: u8, scale: i8) -> Result<Self, ArrowError> {
1703        validate_decimal_precision_and_scale::<T>(precision, scale)?;
1704        Ok(Self {
1705            data_type: T::TYPE_CONSTRUCTOR(precision, scale),
1706            ..self
1707        })
1708    }
1709
1710    /// Validates values in this array can be properly interpreted
1711    /// with the specified precision.
1712    pub fn validate_decimal_precision(&self, precision: u8) -> Result<(), ArrowError> {
1713        if self.scale() > 0 && precision < self.scale() as u8 {
1714            return Err(ArrowError::InvalidArgumentError(format!(
1715                "Decimal precision {precision} is less than scale {}",
1716                self.scale()
1717            )));
1718        }
1719        // A null slot can hold any value, so read the validity bit only for a value that
1720        // doesn't fit
1721        for (idx, &value) in self.values().iter().enumerate() {
1722            if !T::is_valid_decimal_precision(value, precision) && self.is_valid(idx) {
1723                return T::validate_decimal_precision(value, precision, self.scale());
1724            }
1725        }
1726        Ok(())
1727    }
1728
1729    /// Validates the Decimal Array, if the value of slot is overflow for the specified precision, and
1730    /// will be casted to Null
1731    pub fn null_if_overflow_precision(&self, precision: u8) -> Self {
1732        self.unary_opt::<_, T>(|v| T::is_valid_decimal_precision(v, precision).then_some(v))
1733            .with_data_type(self.data_type().clone())
1734    }
1735
1736    /// Returns [`Self::value`] formatted as a string
1737    pub fn value_as_string(&self, row: usize) -> String {
1738        T::format_decimal(self.value(row), self.precision(), self.scale())
1739    }
1740
1741    /// Returns the decimal precision of this array
1742    pub fn precision(&self) -> u8 {
1743        match T::BYTE_LENGTH {
1744            4 => {
1745                if let DataType::Decimal32(p, _) = self.data_type() {
1746                    *p
1747                } else {
1748                    unreachable!(
1749                        "Decimal32Array datatype is not DataType::Decimal32 but {}",
1750                        self.data_type()
1751                    )
1752                }
1753            }
1754            8 => {
1755                if let DataType::Decimal64(p, _) = self.data_type() {
1756                    *p
1757                } else {
1758                    unreachable!(
1759                        "Decimal64Array datatype is not DataType::Decimal64 but {}",
1760                        self.data_type()
1761                    )
1762                }
1763            }
1764            16 => {
1765                if let DataType::Decimal128(p, _) = self.data_type() {
1766                    *p
1767                } else {
1768                    unreachable!(
1769                        "Decimal128Array datatype is not DataType::Decimal128 but {}",
1770                        self.data_type()
1771                    )
1772                }
1773            }
1774            32 => {
1775                if let DataType::Decimal256(p, _) = self.data_type() {
1776                    *p
1777                } else {
1778                    unreachable!(
1779                        "Decimal256Array datatype is not DataType::Decimal256 but {}",
1780                        self.data_type()
1781                    )
1782                }
1783            }
1784            other => unreachable!("Unsupported byte length for decimal array {}", other),
1785        }
1786    }
1787
1788    /// Returns the decimal scale of this array
1789    pub fn scale(&self) -> i8 {
1790        match T::BYTE_LENGTH {
1791            4 => {
1792                if let DataType::Decimal32(_, s) = self.data_type() {
1793                    *s
1794                } else {
1795                    unreachable!(
1796                        "Decimal32Array datatype is not DataType::Decimal32 but {}",
1797                        self.data_type()
1798                    )
1799                }
1800            }
1801            8 => {
1802                if let DataType::Decimal64(_, s) = self.data_type() {
1803                    *s
1804                } else {
1805                    unreachable!(
1806                        "Decimal64Array datatype is not DataType::Decimal64 but {}",
1807                        self.data_type()
1808                    )
1809                }
1810            }
1811            16 => {
1812                if let DataType::Decimal128(_, s) = self.data_type() {
1813                    *s
1814                } else {
1815                    unreachable!(
1816                        "Decimal128Array datatype is not DataType::Decimal128 but {}",
1817                        self.data_type()
1818                    )
1819                }
1820            }
1821            32 => {
1822                if let DataType::Decimal256(_, s) = self.data_type() {
1823                    *s
1824                } else {
1825                    unreachable!(
1826                        "Decimal256Array datatype is not DataType::Decimal256 but {}",
1827                        self.data_type()
1828                    )
1829                }
1830            }
1831            other => unreachable!("Unsupported byte length for decimal array {}", other),
1832        }
1833    }
1834}
1835
1836#[cfg(test)]
1837mod tests {
1838    use super::*;
1839    use crate::BooleanArray;
1840    use crate::builder::{
1841        Decimal32Builder, Decimal64Builder, Decimal128Builder, Decimal256Builder,
1842    };
1843    use crate::cast::downcast_array;
1844    use arrow_buffer::{IntervalDayTime, IntervalMonthDayNano};
1845    use arrow_schema::TimeUnit;
1846    use rstest::rstest;
1847
1848    #[test]
1849    fn test_primitive_array_from_vec() {
1850        let buf = Buffer::from_slice_ref([0, 1, 2, 3, 4]);
1851        let arr = Int32Array::from(vec![0, 1, 2, 3, 4]);
1852        assert_eq!(&buf, arr.values.inner());
1853        assert_eq!(5, arr.len());
1854        assert_eq!(0, arr.offset());
1855        assert_eq!(0, arr.null_count());
1856        for i in 0..5 {
1857            assert!(!arr.is_null(i));
1858            assert!(arr.is_valid(i));
1859            assert_eq!(i as i32, arr.value(i));
1860        }
1861    }
1862
1863    #[test]
1864    fn test_primitive_array_from_vec_option() {
1865        // Test building a primitive array with null values
1866        let arr = Int32Array::from(vec![Some(0), None, Some(2), None, Some(4)]);
1867        assert_eq!(5, arr.len());
1868        assert_eq!(0, arr.offset());
1869        assert_eq!(2, arr.null_count());
1870        for i in 0..5 {
1871            if i % 2 == 0 {
1872                assert!(!arr.is_null(i));
1873                assert!(arr.is_valid(i));
1874                assert_eq!(i as i32, arr.value(i));
1875            } else {
1876                assert!(arr.is_null(i));
1877                assert!(!arr.is_valid(i));
1878            }
1879        }
1880    }
1881
1882    #[test]
1883    fn test_date64_array_from_vec_option() {
1884        // Test building a primitive array with null values
1885        // we use Int32 and Int64 as a backing array, so all Int32 and Int64 conventions
1886        // work
1887        let arr: PrimitiveArray<Date64Type> =
1888            vec![Some(1550902545147), None, Some(1550902545147)].into();
1889        assert_eq!(3, arr.len());
1890        assert_eq!(0, arr.offset());
1891        assert_eq!(1, arr.null_count());
1892        for i in 0..3 {
1893            if i % 2 == 0 {
1894                assert!(!arr.is_null(i));
1895                assert!(arr.is_valid(i));
1896                assert_eq!(1550902545147, arr.value(i));
1897                // roundtrip to and from datetime
1898                assert_eq!(
1899                    1550902545147,
1900                    arr.value_as_datetime(i)
1901                        .unwrap()
1902                        .and_utc()
1903                        .timestamp_millis()
1904                );
1905            } else {
1906                assert!(arr.is_null(i));
1907                assert!(!arr.is_valid(i));
1908            }
1909        }
1910    }
1911
1912    #[test]
1913    fn test_time32_millisecond_array_from_vec() {
1914        // 1:        00:00:00.001
1915        // 37800005: 10:30:00.005
1916        // 86399210: 23:59:59.210
1917        let arr: PrimitiveArray<Time32MillisecondType> = vec![1, 37_800_005, 86_399_210].into();
1918        assert_eq!(3, arr.len());
1919        assert_eq!(0, arr.offset());
1920        assert_eq!(0, arr.null_count());
1921        let formatted = ["00:00:00.001", "10:30:00.005", "23:59:59.210"];
1922        for (i, formatted) in formatted.iter().enumerate().take(3) {
1923            // check that we can't create dates or datetimes from time instances
1924            assert_eq!(None, arr.value_as_datetime(i));
1925            assert_eq!(None, arr.value_as_date(i));
1926            let time = arr.value_as_time(i).unwrap();
1927            assert_eq!(*formatted, time.format("%H:%M:%S%.3f").to_string());
1928        }
1929    }
1930
1931    #[test]
1932    fn test_time64_nanosecond_array_from_vec() {
1933        // Test building a primitive array with null values
1934        // we use Int32 and Int64 as a backing array, so all Int32 and Int64 conventions
1935        // work
1936
1937        // 1e6:        00:00:00.001
1938        // 37800005e6: 10:30:00.005
1939        // 86399210e6: 23:59:59.210
1940        let arr: PrimitiveArray<Time64NanosecondType> =
1941            vec![1_000_000, 37_800_005_000_000, 86_399_210_000_000].into();
1942        assert_eq!(3, arr.len());
1943        assert_eq!(0, arr.offset());
1944        assert_eq!(0, arr.null_count());
1945        let formatted = ["00:00:00.001", "10:30:00.005", "23:59:59.210"];
1946        for (i, item) in formatted.iter().enumerate().take(3) {
1947            // check that we can't create dates or datetimes from time instances
1948            assert_eq!(None, arr.value_as_datetime(i));
1949            assert_eq!(None, arr.value_as_date(i));
1950            let time = arr.value_as_time(i).unwrap();
1951            assert_eq!(*item, time.format("%H:%M:%S%.3f").to_string());
1952        }
1953    }
1954
1955    #[test]
1956    fn test_interval_array_from_vec() {
1957        // intervals are currently not treated specially, but are Int32 and Int64 arrays
1958        let arr = IntervalYearMonthArray::from(vec![Some(1), None, Some(-5)]);
1959        assert_eq!(3, arr.len());
1960        assert_eq!(0, arr.offset());
1961        assert_eq!(1, arr.null_count());
1962        assert_eq!(1, arr.value(0));
1963        assert_eq!(1, arr.values()[0]);
1964        assert!(arr.is_null(1));
1965        assert_eq!(-5, arr.value(2));
1966        assert_eq!(-5, arr.values()[2]);
1967
1968        let v0 = IntervalDayTime {
1969            days: 34,
1970            milliseconds: 1,
1971        };
1972        let v2 = IntervalDayTime {
1973            days: -2,
1974            milliseconds: -5,
1975        };
1976
1977        let arr = IntervalDayTimeArray::from(vec![Some(v0), None, Some(v2)]);
1978
1979        assert_eq!(3, arr.len());
1980        assert_eq!(0, arr.offset());
1981        assert_eq!(1, arr.null_count());
1982        assert_eq!(v0, arr.value(0));
1983        assert_eq!(v0, arr.values()[0]);
1984        assert!(arr.is_null(1));
1985        assert_eq!(v2, arr.value(2));
1986        assert_eq!(v2, arr.values()[2]);
1987
1988        let v0 = IntervalMonthDayNano {
1989            months: 2,
1990            days: 34,
1991            nanoseconds: -1,
1992        };
1993        let v2 = IntervalMonthDayNano {
1994            months: -3,
1995            days: -2,
1996            nanoseconds: 4,
1997        };
1998
1999        let arr = IntervalMonthDayNanoArray::from(vec![Some(v0), None, Some(v2)]);
2000        assert_eq!(3, arr.len());
2001        assert_eq!(0, arr.offset());
2002        assert_eq!(1, arr.null_count());
2003        assert_eq!(v0, arr.value(0));
2004        assert_eq!(v0, arr.values()[0]);
2005        assert!(arr.is_null(1));
2006        assert_eq!(v2, arr.value(2));
2007        assert_eq!(v2, arr.values()[2]);
2008    }
2009
2010    #[test]
2011    fn test_duration_array_from_vec() {
2012        let arr = DurationSecondArray::from(vec![Some(1), None, Some(-5)]);
2013        assert_eq!(3, arr.len());
2014        assert_eq!(0, arr.offset());
2015        assert_eq!(1, arr.null_count());
2016        assert_eq!(1, arr.value(0));
2017        assert_eq!(1, arr.values()[0]);
2018        assert!(arr.is_null(1));
2019        assert_eq!(-5, arr.value(2));
2020        assert_eq!(-5, arr.values()[2]);
2021
2022        let arr = DurationMillisecondArray::from(vec![Some(1), None, Some(-5)]);
2023        assert_eq!(3, arr.len());
2024        assert_eq!(0, arr.offset());
2025        assert_eq!(1, arr.null_count());
2026        assert_eq!(1, arr.value(0));
2027        assert_eq!(1, arr.values()[0]);
2028        assert!(arr.is_null(1));
2029        assert_eq!(-5, arr.value(2));
2030        assert_eq!(-5, arr.values()[2]);
2031
2032        let arr = DurationMicrosecondArray::from(vec![Some(1), None, Some(-5)]);
2033        assert_eq!(3, arr.len());
2034        assert_eq!(0, arr.offset());
2035        assert_eq!(1, arr.null_count());
2036        assert_eq!(1, arr.value(0));
2037        assert_eq!(1, arr.values()[0]);
2038        assert!(arr.is_null(1));
2039        assert_eq!(-5, arr.value(2));
2040        assert_eq!(-5, arr.values()[2]);
2041
2042        let arr = DurationNanosecondArray::from(vec![Some(1), None, Some(-5)]);
2043        assert_eq!(3, arr.len());
2044        assert_eq!(0, arr.offset());
2045        assert_eq!(1, arr.null_count());
2046        assert_eq!(1, arr.value(0));
2047        assert_eq!(1, arr.values()[0]);
2048        assert!(arr.is_null(1));
2049        assert_eq!(-5, arr.value(2));
2050        assert_eq!(-5, arr.values()[2]);
2051    }
2052
2053    #[test]
2054    fn test_timestamp_array_from_vec() {
2055        let arr = TimestampSecondArray::from(vec![1, -5]);
2056        assert_eq!(2, arr.len());
2057        assert_eq!(0, arr.offset());
2058        assert_eq!(0, arr.null_count());
2059        assert_eq!(1, arr.value(0));
2060        assert_eq!(-5, arr.value(1));
2061        assert_eq!(&[1, -5], arr.values());
2062
2063        let arr = TimestampMillisecondArray::from(vec![1, -5]);
2064        assert_eq!(2, arr.len());
2065        assert_eq!(0, arr.offset());
2066        assert_eq!(0, arr.null_count());
2067        assert_eq!(1, arr.value(0));
2068        assert_eq!(-5, arr.value(1));
2069        assert_eq!(&[1, -5], arr.values());
2070
2071        let arr = TimestampMicrosecondArray::from(vec![1, -5]);
2072        assert_eq!(2, arr.len());
2073        assert_eq!(0, arr.offset());
2074        assert_eq!(0, arr.null_count());
2075        assert_eq!(1, arr.value(0));
2076        assert_eq!(-5, arr.value(1));
2077        assert_eq!(&[1, -5], arr.values());
2078
2079        let arr = TimestampNanosecondArray::from(vec![1, -5]);
2080        assert_eq!(2, arr.len());
2081        assert_eq!(0, arr.offset());
2082        assert_eq!(0, arr.null_count());
2083        assert_eq!(1, arr.value(0));
2084        assert_eq!(-5, arr.value(1));
2085        assert_eq!(&[1, -5], arr.values());
2086    }
2087
2088    #[test]
2089    fn test_primitive_array_slice() {
2090        let arr = Int32Array::from(vec![
2091            Some(0),
2092            None,
2093            Some(2),
2094            None,
2095            Some(4),
2096            Some(5),
2097            Some(6),
2098            None,
2099            None,
2100        ]);
2101        assert_eq!(9, arr.len());
2102        assert_eq!(0, arr.offset());
2103        assert_eq!(4, arr.null_count());
2104
2105        let arr2 = arr.slice(2, 5);
2106        assert_eq!(5, arr2.len());
2107        assert_eq!(1, arr2.null_count());
2108
2109        for i in 0..arr2.len() {
2110            assert_eq!(i == 1, arr2.is_null(i));
2111            assert_eq!(i != 1, arr2.is_valid(i));
2112        }
2113        let int_arr2 = arr2.as_any().downcast_ref::<Int32Array>().unwrap();
2114        assert_eq!(2, int_arr2.values()[0]);
2115        assert_eq!(&[4, 5, 6], &int_arr2.values()[2..5]);
2116
2117        let arr3 = arr2.slice(2, 3);
2118        assert_eq!(3, arr3.len());
2119        assert_eq!(0, arr3.null_count());
2120
2121        let int_arr3 = arr3.as_any().downcast_ref::<Int32Array>().unwrap();
2122        assert_eq!(&[4, 5, 6], int_arr3.values());
2123        assert_eq!(4, int_arr3.value(0));
2124        assert_eq!(5, int_arr3.value(1));
2125        assert_eq!(6, int_arr3.value(2));
2126    }
2127
2128    #[test]
2129    fn test_boolean_array_slice() {
2130        let arr = BooleanArray::from(vec![
2131            Some(true),
2132            None,
2133            Some(false),
2134            None,
2135            Some(true),
2136            Some(false),
2137            Some(true),
2138            Some(false),
2139            None,
2140            Some(true),
2141        ]);
2142
2143        assert_eq!(10, arr.len());
2144        assert_eq!(0, arr.offset());
2145        assert_eq!(3, arr.null_count());
2146
2147        let arr2 = arr.slice(3, 5);
2148        assert_eq!(5, arr2.len());
2149        assert_eq!(3, arr2.offset());
2150        assert_eq!(1, arr2.null_count());
2151
2152        let bool_arr = arr2.as_any().downcast_ref::<BooleanArray>().unwrap();
2153
2154        assert!(!bool_arr.is_valid(0));
2155
2156        assert!(bool_arr.is_valid(1));
2157        assert!(bool_arr.value(1));
2158
2159        assert!(bool_arr.is_valid(2));
2160        assert!(!bool_arr.value(2));
2161
2162        assert!(bool_arr.is_valid(3));
2163        assert!(bool_arr.value(3));
2164
2165        assert!(bool_arr.is_valid(4));
2166        assert!(!bool_arr.value(4));
2167    }
2168
2169    #[test]
2170    fn test_int32_fmt_debug() {
2171        let arr = Int32Array::from(vec![0, 1, 2, 3, 4]);
2172        assert_eq!(
2173            "PrimitiveArray<Int32>\n[\n  0,\n  1,\n  2,\n  3,\n  4,\n]",
2174            format!("{arr:?}")
2175        );
2176    }
2177
2178    #[test]
2179    fn test_fmt_debug_up_to_20_elements() {
2180        (1..=20).for_each(|i| {
2181            let values = (0..i).collect::<Vec<i16>>();
2182            let array_expected = format!(
2183                "PrimitiveArray<Int16>\n[\n{}\n]",
2184                values
2185                    .iter()
2186                    .map(|v| { format!("  {v},") })
2187                    .collect::<Vec<String>>()
2188                    .join("\n")
2189            );
2190            let array = Int16Array::from(values);
2191
2192            assert_eq!(array_expected, format!("{array:?}"));
2193        })
2194    }
2195
2196    #[test]
2197    fn test_int32_with_null_fmt_debug() {
2198        let mut builder = Int32Array::builder(3);
2199        builder.append_slice(&[0, 1]);
2200        builder.append_null();
2201        builder.append_slice(&[3, 4]);
2202        let arr = builder.finish();
2203        assert_eq!(
2204            "PrimitiveArray<Int32>\n[\n  0,\n  1,\n  null,\n  3,\n  4,\n]",
2205            format!("{arr:?}")
2206        );
2207    }
2208
2209    #[test]
2210    fn test_timestamp_fmt_debug() {
2211        let arr: PrimitiveArray<TimestampMillisecondType> =
2212            TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000]);
2213        assert_eq!(
2214            "PrimitiveArray<Timestamp(ms)>\n[\n  2018-12-31T00:00:00,\n  2018-12-31T00:00:00,\n  1921-01-02T00:00:00,\n]",
2215            format!("{arr:?}")
2216        );
2217    }
2218
2219    #[test]
2220    fn test_timestamp_fmt_debug_out_of_range() {
2221        // Include a true null into dataset to ensure we don't write that as an error
2222        let data = Int64Array::new(
2223            vec![i64::MAX, i64::MIN, i64::MAX].into(),
2224            Some(vec![true, true, false].into()),
2225        );
2226
2227        let arr = data.reinterpret_cast::<TimestampSecondType>();
2228        assert_eq!(
2229            "PrimitiveArray<Timestamp(s)>
2230[
2231  Cast error: Failed to convert 9223372036854775807 to timestamp for Timestamp(s),
2232  Cast error: Failed to convert -9223372036854775808 to timestamp for Timestamp(s),
2233  null,
2234]",
2235            format!("{arr:?}")
2236        );
2237
2238        let arr = data.reinterpret_cast::<TimestampMillisecondType>();
2239        assert_eq!(
2240            "PrimitiveArray<Timestamp(ms)>
2241[
2242  Cast error: Failed to convert 9223372036854775807 to timestamp for Timestamp(ms),
2243  Cast error: Failed to convert -9223372036854775808 to timestamp for Timestamp(ms),
2244  null,
2245]",
2246            format!("{arr:?}")
2247        );
2248
2249        let arr = data.reinterpret_cast::<TimestampMicrosecondType>();
2250        assert_eq!(
2251            "PrimitiveArray<Timestamp(µs)>
2252[
2253  Cast error: Failed to convert 9223372036854775807 to timestamp for Timestamp(µs),
2254  Cast error: Failed to convert -9223372036854775808 to timestamp for Timestamp(µs),
2255  null,
2256]",
2257            format!("{arr:?}")
2258        );
2259
2260        // Nanoseconds always in range
2261        let arr = data.reinterpret_cast::<TimestampNanosecondType>();
2262        assert_eq!(
2263            "PrimitiveArray<Timestamp(ns)>
2264[
2265  2262-04-11T23:47:16.854775807,
2266  1677-09-21T00:12:43.145224192,
2267  null,
2268]",
2269            format!("{arr:?}")
2270        );
2271    }
2272
2273    #[test]
2274    fn test_timestamp_utc_fmt_debug() {
2275        let arr: PrimitiveArray<TimestampMillisecondType> =
2276            TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000])
2277                .with_timezone_utc();
2278        assert_eq!(
2279            "PrimitiveArray<Timestamp(ms, \"+00:00\")>\n[\n  2018-12-31T00:00:00+00:00,\n  2018-12-31T00:00:00+00:00,\n  1921-01-02T00:00:00+00:00,\n]",
2280            format!("{arr:?}")
2281        );
2282    }
2283
2284    #[test]
2285    #[cfg(any(feature = "chrono-tz", feature = "jiff"))]
2286    fn test_timestamp_with_named_tz_fmt_debug() {
2287        let arr: PrimitiveArray<TimestampMillisecondType> =
2288            TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000])
2289                .with_timezone("Asia/Taipei".to_string());
2290        assert_eq!(
2291            "PrimitiveArray<Timestamp(ms, \"Asia/Taipei\")>\n[\n  2018-12-31T08:00:00+08:00,\n  2018-12-31T08:00:00+08:00,\n  1921-01-02T08:00:00+08:00,\n]",
2292            format!("{arr:?}")
2293        );
2294    }
2295
2296    #[test]
2297    #[cfg(not(any(feature = "chrono-tz", feature = "jiff")))]
2298    fn test_timestamp_with_named_tz_fmt_debug() {
2299        let arr: PrimitiveArray<TimestampMillisecondType> =
2300            TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000])
2301                .with_timezone("Asia/Taipei".to_string());
2302
2303        println!("{arr:?}");
2304
2305        assert_eq!(
2306            "PrimitiveArray<Timestamp(ms, \"Asia/Taipei\")>\n[\n  2018-12-31T00:00:00 (Unknown Time Zone 'Asia/Taipei'),\n  2018-12-31T00:00:00 (Unknown Time Zone 'Asia/Taipei'),\n  1921-01-02T00:00:00 (Unknown Time Zone 'Asia/Taipei'),\n]",
2307            format!("{arr:?}")
2308        );
2309    }
2310
2311    #[test]
2312    fn test_timestamp_with_fixed_offset_tz_fmt_debug() {
2313        let arr: PrimitiveArray<TimestampMillisecondType> =
2314            TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000])
2315                .with_timezone("+08:00".to_string());
2316        assert_eq!(
2317            "PrimitiveArray<Timestamp(ms, \"+08:00\")>\n[\n  2018-12-31T08:00:00+08:00,\n  2018-12-31T08:00:00+08:00,\n  1921-01-02T08:00:00+08:00,\n]",
2318            format!("{arr:?}")
2319        );
2320    }
2321
2322    #[test]
2323    fn test_timestamp_with_incorrect_tz_fmt_debug() {
2324        let arr: PrimitiveArray<TimestampMillisecondType> =
2325            TimestampMillisecondArray::from(vec![1546214400000, 1546214400000, -1546214400000])
2326                .with_timezone("xxx".to_string());
2327        assert_eq!(
2328            "PrimitiveArray<Timestamp(ms, \"xxx\")>\n[\n  2018-12-31T00:00:00 (Unknown Time Zone 'xxx'),\n  2018-12-31T00:00:00 (Unknown Time Zone 'xxx'),\n  1921-01-02T00:00:00 (Unknown Time Zone 'xxx'),\n]",
2329            format!("{arr:?}")
2330        );
2331    }
2332
2333    #[test]
2334    #[cfg(any(feature = "chrono-tz", feature = "jiff"))]
2335    fn test_timestamp_with_tz_with_daylight_saving_fmt_debug() {
2336        let arr: PrimitiveArray<TimestampMillisecondType> = TimestampMillisecondArray::from(vec![
2337            1647161999000,
2338            1647162000000,
2339            1667717999000,
2340            1667718000000,
2341        ])
2342        .with_timezone("America/Denver".to_string());
2343        assert_eq!(
2344            "PrimitiveArray<Timestamp(ms, \"America/Denver\")>\n[\n  2022-03-13T01:59:59-07:00,\n  2022-03-13T03:00:00-06:00,\n  2022-11-06T00:59:59-06:00,\n  2022-11-06T01:00:00-06:00,\n]",
2345            format!("{arr:?}")
2346        );
2347    }
2348
2349    #[test]
2350    fn test_date32_fmt_debug() {
2351        let arr: PrimitiveArray<Date32Type> = vec![12356, 13548, -365].into();
2352        assert_eq!(
2353            "PrimitiveArray<Date32>\n[\n  2003-10-31,\n  2007-02-04,\n  1969-01-01,\n]",
2354            format!("{arr:?}")
2355        );
2356    }
2357
2358    #[test]
2359    fn test_time32second_fmt_debug() {
2360        let arr: PrimitiveArray<Time32SecondType> = vec![7201, 60054].into();
2361        assert_eq!(
2362            "PrimitiveArray<Time32(s)>\n[\n  02:00:01,\n  16:40:54,\n]",
2363            format!("{arr:?}")
2364        );
2365    }
2366
2367    #[test]
2368    fn test_time32second_invalid_neg() {
2369        // chrono::NaiveDatetime::from_timestamp_opt returns None while input is invalid
2370        let arr: PrimitiveArray<Time32SecondType> = vec![-7201, -60054].into();
2371        assert_eq!(
2372            "PrimitiveArray<Time32(s)>\n[\n  Cast error: Failed to convert -7201 to temporal for Time32(s),\n  Cast error: Failed to convert -60054 to temporal for Time32(s),\n]",
2373            // "PrimitiveArray<Time32(s)>\n[\n  null,\n  null,\n]",
2374            format!("{arr:?}")
2375        )
2376    }
2377
2378    #[test]
2379    fn test_primitive_array_builder() {
2380        // Test building a primitive array with ArrayData builder and offset
2381        let buf = Buffer::from_slice_ref([0i32, 1, 2, 3, 4, 5, 6]);
2382        let buf2 = buf.slice_with_length(8, 20);
2383        let data = ArrayData::builder(DataType::Int32)
2384            .len(5)
2385            .offset(2)
2386            .add_buffer(buf)
2387            .build()
2388            .unwrap();
2389        let arr = Int32Array::from(data);
2390        assert_eq!(&buf2, arr.values.inner());
2391        assert_eq!(5, arr.len());
2392        assert_eq!(0, arr.null_count());
2393        for i in 0..3 {
2394            assert_eq!((i + 2) as i32, arr.value(i));
2395        }
2396    }
2397
2398    #[test]
2399    fn test_primitive_from_iter_values() {
2400        // Test building a primitive array with from_iter_values
2401        let arr: PrimitiveArray<Int32Type> = PrimitiveArray::from_iter_values(0..10);
2402        assert_eq!(10, arr.len());
2403        assert_eq!(0, arr.null_count());
2404        for i in 0..10i32 {
2405            assert_eq!(i, arr.value(i as usize));
2406        }
2407    }
2408
2409    #[test]
2410    fn test_primitive_array_from_unbound_iter() {
2411        // iterator that doesn't declare (upper) size bound
2412        let value_iter = (0..)
2413            .scan(0usize, |pos, i| {
2414                if *pos < 10 {
2415                    *pos += 1;
2416                    Some(Some(i))
2417                } else {
2418                    // actually returns up to 10 values
2419                    None
2420                }
2421            })
2422            // limited using take()
2423            .take(100);
2424
2425        let (_, upper_size_bound) = value_iter.size_hint();
2426        // the upper bound, defined by take above, is 100
2427        assert_eq!(upper_size_bound, Some(100));
2428        let primitive_array: PrimitiveArray<Int32Type> = value_iter.collect();
2429        // but the actual number of items in the array should be 10
2430        assert_eq!(primitive_array.len(), 10);
2431    }
2432
2433    #[test]
2434    fn test_primitive_array_from_non_null_iter() {
2435        let iter = (0..10_i32).map(Some);
2436        let primitive_array = PrimitiveArray::<Int32Type>::from_iter(iter);
2437        assert_eq!(primitive_array.len(), 10);
2438        assert_eq!(primitive_array.null_count(), 0);
2439        assert!(primitive_array.nulls().is_none());
2440        assert_eq!(primitive_array.values(), &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
2441    }
2442
2443    #[test]
2444    #[should_panic(expected = "PrimitiveArray data should contain a single buffer only \
2445                               (values buffer)")]
2446    // Different error messages, so skip for now
2447    // https://github.com/apache/arrow-rs/issues/1545
2448    #[cfg(not(feature = "force_validate"))]
2449    fn test_primitive_array_invalid_buffer_len() {
2450        let buffer = Buffer::from_slice_ref([0i32, 1, 2, 3, 4]);
2451        let data = unsafe {
2452            ArrayData::builder(DataType::Int32)
2453                .add_buffer(buffer.clone())
2454                .add_buffer(buffer)
2455                .len(5)
2456                .build_unchecked()
2457        };
2458
2459        drop(Int32Array::from(data));
2460    }
2461
2462    #[test]
2463    fn test_access_array_concurrently() {
2464        let a = Int32Array::from(vec![5, 6, 7, 8, 9]);
2465        let ret = std::thread::spawn(move || a.value(3)).join();
2466
2467        assert!(ret.is_ok());
2468        assert_eq!(8, ret.ok().unwrap());
2469    }
2470
2471    #[test]
2472    fn test_primitive_array_creation() {
2473        let array1: Int8Array = [10_i8, 11, 12, 13, 14].into_iter().collect();
2474        let array2: Int8Array = [10_i8, 11, 12, 13, 14].into_iter().map(Some).collect();
2475
2476        assert_eq!(array1, array2);
2477    }
2478
2479    #[test]
2480    #[should_panic(
2481        expected = "Trying to access an element at index 4 from a PrimitiveArray of length 3"
2482    )]
2483    fn test_string_array_get_value_index_out_of_bound() {
2484        let array: Int8Array = [10_i8, 11, 12].into_iter().collect();
2485
2486        array.value(4);
2487    }
2488
2489    #[test]
2490    #[should_panic(expected = "PrimitiveArray expected data type Int64 got Int32")]
2491    fn test_from_array_data_validation() {
2492        let foo = PrimitiveArray::<Int32Type>::from_iter([1, 2, 3]);
2493        let _ = PrimitiveArray::<Int64Type>::from(foo.into_data());
2494    }
2495
2496    #[test]
2497    fn test_decimal32() {
2498        let values: Vec<_> = vec![0, 1, -1, i32::MIN, i32::MAX];
2499        let array: PrimitiveArray<Decimal32Type> =
2500            PrimitiveArray::from_iter(values.iter().copied());
2501        assert_eq!(array.values(), &values);
2502
2503        let array: PrimitiveArray<Decimal32Type> =
2504            PrimitiveArray::from_iter_values(values.iter().copied());
2505        assert_eq!(array.values(), &values);
2506
2507        let array = PrimitiveArray::<Decimal32Type>::from(values.clone());
2508        assert_eq!(array.values(), &values);
2509
2510        let array = PrimitiveArray::<Decimal32Type>::from(array.to_data());
2511        assert_eq!(array.values(), &values);
2512    }
2513
2514    #[test]
2515    fn test_decimal64() {
2516        let values: Vec<_> = vec![0, 1, -1, i64::MIN, i64::MAX];
2517        let array: PrimitiveArray<Decimal64Type> =
2518            PrimitiveArray::from_iter(values.iter().copied());
2519        assert_eq!(array.values(), &values);
2520
2521        let array: PrimitiveArray<Decimal64Type> =
2522            PrimitiveArray::from_iter_values(values.iter().copied());
2523        assert_eq!(array.values(), &values);
2524
2525        let array = PrimitiveArray::<Decimal64Type>::from(values.clone());
2526        assert_eq!(array.values(), &values);
2527
2528        let array = PrimitiveArray::<Decimal64Type>::from(array.to_data());
2529        assert_eq!(array.values(), &values);
2530    }
2531
2532    #[test]
2533    fn test_decimal128() {
2534        let values: Vec<_> = vec![0, 1, -1, i128::MIN, i128::MAX];
2535        let array: PrimitiveArray<Decimal128Type> =
2536            PrimitiveArray::from_iter(values.iter().copied());
2537        assert_eq!(array.values(), &values);
2538
2539        let array: PrimitiveArray<Decimal128Type> =
2540            PrimitiveArray::from_iter_values(values.iter().copied());
2541        assert_eq!(array.values(), &values);
2542
2543        let array = PrimitiveArray::<Decimal128Type>::from(values.clone());
2544        assert_eq!(array.values(), &values);
2545
2546        let array = PrimitiveArray::<Decimal128Type>::from(array.to_data());
2547        assert_eq!(array.values(), &values);
2548    }
2549
2550    #[test]
2551    fn test_decimal256() {
2552        let values: Vec<_> = vec![i256::ZERO, i256::ONE, i256::MINUS_ONE, i256::MIN, i256::MAX];
2553
2554        let array: PrimitiveArray<Decimal256Type> =
2555            PrimitiveArray::from_iter(values.iter().copied());
2556        assert_eq!(array.values(), &values);
2557
2558        let array: PrimitiveArray<Decimal256Type> =
2559            PrimitiveArray::from_iter_values(values.iter().copied());
2560        assert_eq!(array.values(), &values);
2561
2562        let array = PrimitiveArray::<Decimal256Type>::from(values.clone());
2563        assert_eq!(array.values(), &values);
2564
2565        let array = PrimitiveArray::<Decimal256Type>::from(array.to_data());
2566        assert_eq!(array.values(), &values);
2567    }
2568
2569    #[test]
2570    fn test_decimal_array() {
2571        // let val_8887: [u8; 16] = [192, 219, 180, 17, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
2572        // let val_neg_8887: [u8; 16] = [64, 36, 75, 238, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255];
2573        let values: [u8; 32] = [
2574            192, 219, 180, 17, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 36, 75, 238, 253, 255, 255,
2575            255, 255, 255, 255, 255, 255, 255, 255, 255,
2576        ];
2577        let array_data = ArrayData::builder(DataType::Decimal128(38, 6))
2578            .len(2)
2579            .add_buffer(Buffer::from(&values))
2580            .build()
2581            .unwrap();
2582        let decimal_array = Decimal128Array::from(array_data);
2583        assert_eq!(8_887_000_000_i128, decimal_array.value(0));
2584        assert_eq!(-8_887_000_000_i128, decimal_array.value(1));
2585    }
2586
2587    #[test]
2588    fn test_decimal_append_error_value() {
2589        let mut decimal_builder = Decimal128Builder::with_capacity(10);
2590        decimal_builder.append_value(123456);
2591        decimal_builder.append_value(12345);
2592        let result = decimal_builder.finish().with_precision_and_scale(5, 3);
2593        assert!(result.is_ok());
2594        let arr = result.unwrap();
2595        assert_eq!("12.345", arr.value_as_string(1));
2596
2597        // Validate it explicitly
2598        let result = arr.validate_decimal_precision(5);
2599        let error = result.unwrap_err();
2600        assert_eq!(
2601            "Invalid argument error: 123.456 is too large to store in a Decimal128 of precision 5. Max is 99.999",
2602            error.to_string()
2603        );
2604
2605        decimal_builder = Decimal128Builder::new();
2606        decimal_builder.append_value(100);
2607        decimal_builder.append_value(99);
2608        decimal_builder.append_value(-100);
2609        decimal_builder.append_value(-99);
2610        let result = decimal_builder.finish().with_precision_and_scale(2, 1);
2611        assert!(result.is_ok());
2612        let arr = result.unwrap();
2613        assert_eq!("9.9", arr.value_as_string(1));
2614        assert_eq!("-9.9", arr.value_as_string(3));
2615
2616        // Validate it explicitly
2617        let result = arr.validate_decimal_precision(2);
2618        let error = result.unwrap_err();
2619        assert_eq!(
2620            "Invalid argument error: 10.0 is too large to store in a Decimal128 of precision 2. Max is 9.9",
2621            error.to_string()
2622        );
2623    }
2624
2625    #[rstest]
2626    #[case::decimal32(Decimal32Type {})]
2627    #[case::decimal64(Decimal64Type {})]
2628    #[case::decimal128(Decimal128Type {})]
2629    #[case::decimal256(Decimal256Type {})]
2630    fn test_decimal_validate_precision_with_negative_scale<T: DecimalType>(
2631        #[case] decimal_type: T,
2632        #[values(i8::MIN, -2, -1, 0, 2)] scale: i8,
2633    ) where
2634        T::Native: From<i32>,
2635    {
2636        let _ = decimal_type;
2637        let array = PrimitiveArray::<T>::from_iter(
2638            [Some(-99), Some(0), Some(1), Some(99), None]
2639                .into_iter()
2640                .map(|v| v.map(T::Native::from)),
2641        )
2642        .with_precision_and_scale(2, scale)
2643        .unwrap();
2644        array.validate_decimal_precision(2).unwrap();
2645
2646        for value in [-100, 100] {
2647            let array = PrimitiveArray::<T>::from_iter_values([T::Native::from(value)])
2648                .with_precision_and_scale(3, scale)
2649                .unwrap();
2650            assert!(array.validate_decimal_precision(2).is_err());
2651        }
2652    }
2653
2654    #[rstest]
2655    #[case::decimal32(Decimal32Type {})]
2656    #[case::decimal64(Decimal64Type {})]
2657    #[case::decimal128(Decimal128Type {})]
2658    #[case::decimal256(Decimal256Type {})]
2659    fn test_decimal_negative_scale_error_message<T: DecimalType>(#[case] decimal_type: T)
2660    where
2661        T::Native: From<i32>,
2662    {
2663        let _ = decimal_type;
2664        let array = PrimitiveArray::<T>::from_iter_values([T::Native::from(100)])
2665            .with_precision_and_scale(3, -2)
2666            .unwrap();
2667        assert_eq!(
2668            array.validate_decimal_precision(2).unwrap_err().to_string(),
2669            format!(
2670                "Invalid argument error: 10000 is too large to store in a {} of precision 2. Max is 9900",
2671                T::PREFIX
2672            )
2673        );
2674    }
2675
2676    #[rstest]
2677    #[case::decimal32(Decimal32Type {})]
2678    #[case::decimal64(Decimal64Type {})]
2679    #[case::decimal128(Decimal128Type {})]
2680    #[case::decimal256(Decimal256Type {})]
2681    fn test_decimal_precision_less_than_scale<T: DecimalType>(#[case] decimal_type: T)
2682    where
2683        T::Native: From<i32>,
2684    {
2685        let _ = decimal_type;
2686        let array = PrimitiveArray::<T>::from_iter_values([T::Native::from(0)])
2687            .with_precision_and_scale(2, 2)
2688            .unwrap();
2689        assert_eq!(
2690            array.validate_decimal_precision(1).unwrap_err().to_string(),
2691            "Invalid argument error: Decimal precision 1 is less than scale 2"
2692        );
2693    }
2694
2695    #[test]
2696    fn test_decimal_validate_precision_ignores_null_slots() {
2697        fn check<T: DecimalType>()
2698        where
2699            T::Native: From<i32>,
2700        {
2701            // Rows 1 and 3 are null and hold values that don't fit precision 3
2702            let values = [1, -1000, 2, -2000, 3, 1000, 4].map(T::Native::from);
2703            let nulls = NullBuffer::from(&[true, false, true, false, true, true, true]);
2704            let array = PrimitiveArray::<T>::new(values.into_iter().collect(), Some(nulls))
2705                .with_precision_and_scale(4, 0)
2706                .unwrap();
2707            let too_large = format!(
2708                "Invalid argument error: 1000 is too large to store in a {} of precision 3. Max is 999",
2709                T::PREFIX
2710            );
2711            for array in [array.clone(), array.slice(2, 5)] {
2712                let error = array.validate_decimal_precision(3).unwrap_err();
2713                assert_eq!(error.to_string(), too_large);
2714            }
2715            array.slice(0, 5).validate_decimal_precision(3).unwrap();
2716            array.slice(1, 3).validate_decimal_precision(3).unwrap();
2717        }
2718
2719        check::<Decimal32Type>();
2720        check::<Decimal64Type>();
2721        check::<Decimal128Type>();
2722        check::<Decimal256Type>();
2723    }
2724
2725    #[test]
2726    fn test_decimal_from_iter_values() {
2727        let array = Decimal128Array::from_iter_values(vec![-100, 0, 101]);
2728        assert_eq!(array.len(), 3);
2729        assert_eq!(array.data_type(), &DataType::Decimal128(38, 10));
2730        assert_eq!(-100_i128, array.value(0));
2731        assert!(!array.is_null(0));
2732        assert_eq!(0_i128, array.value(1));
2733        assert!(!array.is_null(1));
2734        assert_eq!(101_i128, array.value(2));
2735        assert!(!array.is_null(2));
2736    }
2737
2738    #[test]
2739    fn test_decimal_from_iter() {
2740        let array: Decimal128Array = vec![Some(-100), None, Some(101)].into_iter().collect();
2741        assert_eq!(array.len(), 3);
2742        assert_eq!(array.data_type(), &DataType::Decimal128(38, 10));
2743        assert_eq!(-100_i128, array.value(0));
2744        assert!(!array.is_null(0));
2745        assert!(array.is_null(1));
2746        assert_eq!(101_i128, array.value(2));
2747        assert!(!array.is_null(2));
2748    }
2749
2750    #[test]
2751    fn test_decimal_iter_sized() {
2752        let data = vec![Some(-100), None, Some(101)];
2753        let array: Decimal128Array = data.into_iter().collect();
2754        let mut iter = array.into_iter();
2755
2756        // is exact sized
2757        assert_eq!(array.len(), 3);
2758
2759        // size_hint is reported correctly
2760        assert_eq!(iter.size_hint(), (3, Some(3)));
2761        iter.next().unwrap();
2762        assert_eq!(iter.size_hint(), (2, Some(2)));
2763        iter.next().unwrap();
2764        iter.next().unwrap();
2765        assert_eq!(iter.size_hint(), (0, Some(0)));
2766        assert!(iter.next().is_none());
2767        assert_eq!(iter.size_hint(), (0, Some(0)));
2768    }
2769
2770    #[test]
2771    fn test_decimal_array_value_as_string() {
2772        let arr = [123450, -123450, 100, -100, 10, -10, 0]
2773            .into_iter()
2774            .map(Some)
2775            .collect::<Decimal128Array>()
2776            .with_precision_and_scale(6, 3)
2777            .unwrap();
2778
2779        assert_eq!("123.450", arr.value_as_string(0));
2780        assert_eq!("-123.450", arr.value_as_string(1));
2781        assert_eq!("0.100", arr.value_as_string(2));
2782        assert_eq!("-0.100", arr.value_as_string(3));
2783        assert_eq!("0.010", arr.value_as_string(4));
2784        assert_eq!("-0.010", arr.value_as_string(5));
2785        assert_eq!("0.000", arr.value_as_string(6));
2786    }
2787
2788    #[test]
2789    fn test_decimal_array_with_precision_and_scale() {
2790        let arr = Decimal128Array::from_iter_values([12345, 456, 7890, -123223423432432])
2791            .with_precision_and_scale(20, 2)
2792            .unwrap();
2793
2794        assert_eq!(arr.data_type(), &DataType::Decimal128(20, 2));
2795        assert_eq!(arr.precision(), 20);
2796        assert_eq!(arr.scale(), 2);
2797
2798        let actual: Vec<_> = (0..arr.len()).map(|i| arr.value_as_string(i)).collect();
2799        let expected = vec!["123.45", "4.56", "78.90", "-1232234234324.32"];
2800
2801        assert_eq!(actual, expected);
2802    }
2803
2804    #[test]
2805    #[should_panic(
2806        expected = "-1232234234324.32 is too small to store in a Decimal128 of precision 5. Min is -999.99"
2807    )]
2808    fn test_decimal_array_with_precision_and_scale_out_of_range() {
2809        let arr = Decimal128Array::from_iter_values([12345, 456, 7890, -123223423432432])
2810            // precision is too small to hold value
2811            .with_precision_and_scale(5, 2)
2812            .unwrap();
2813        arr.validate_decimal_precision(5).unwrap();
2814    }
2815
2816    #[test]
2817    #[should_panic(expected = "precision cannot be 0, has to be between [1, 38]")]
2818    fn test_decimal_array_with_precision_zero() {
2819        Decimal128Array::from_iter_values([12345, 456])
2820            .with_precision_and_scale(0, 2)
2821            .unwrap();
2822    }
2823
2824    #[test]
2825    #[should_panic(expected = "precision 40 is greater than max 38")]
2826    fn test_decimal_array_with_precision_and_scale_invalid_precision() {
2827        Decimal128Array::from_iter_values([12345, 456])
2828            .with_precision_and_scale(40, 2)
2829            .unwrap();
2830    }
2831
2832    #[test]
2833    #[should_panic(expected = "scale 40 is greater than max 38")]
2834    fn test_decimal_array_with_precision_and_scale_invalid_scale() {
2835        Decimal128Array::from_iter_values([12345, 456])
2836            .with_precision_and_scale(20, 40)
2837            .unwrap();
2838    }
2839
2840    #[test]
2841    #[should_panic(expected = "scale 10 is greater than precision 4")]
2842    fn test_decimal_array_with_precision_and_scale_invalid_precision_and_scale() {
2843        Decimal128Array::from_iter_values([12345, 456])
2844            .with_precision_and_scale(4, 10)
2845            .unwrap();
2846    }
2847
2848    #[test]
2849    fn test_decimal_array_set_null_if_overflow_with_precision() {
2850        let array = Decimal128Array::from(vec![Some(123456), Some(123), None, Some(123456)]);
2851        let result = array.null_if_overflow_precision(5);
2852        let expected = Decimal128Array::from(vec![None, Some(123), None, None]);
2853        assert_eq!(result, expected);
2854    }
2855
2856    #[test]
2857    fn test_null_if_overflow_precision_keeps_data_type() {
2858        let array = Decimal32Array::from(vec![99])
2859            .with_precision_and_scale(2, 1)
2860            .unwrap();
2861        assert_eq!(array.null_if_overflow_precision(2), array);
2862
2863        let array = Decimal64Array::from(vec![99])
2864            .with_precision_and_scale(2, 1)
2865            .unwrap();
2866        assert_eq!(array.null_if_overflow_precision(2), array);
2867
2868        let array = Decimal128Array::from(vec![99])
2869            .with_precision_and_scale(2, 1)
2870            .unwrap();
2871        assert_eq!(array.null_if_overflow_precision(2), array);
2872
2873        let array = Decimal256Array::from(vec![i256::from(99)])
2874            .with_precision_and_scale(2, 1)
2875            .unwrap();
2876        assert_eq!(array.null_if_overflow_precision(2), array);
2877    }
2878
2879    #[test]
2880    fn test_decimal256_iter() {
2881        let mut builder = Decimal256Builder::with_capacity(30);
2882        let decimal1 = i256::from_i128(12345);
2883        builder.append_value(decimal1);
2884
2885        builder.append_null();
2886
2887        let decimal2 = i256::from_i128(56789);
2888        builder.append_value(decimal2);
2889
2890        let array: Decimal256Array = builder.finish().with_precision_and_scale(76, 6).unwrap();
2891
2892        let collected: Vec<_> = array.iter().collect();
2893        assert_eq!(vec![Some(decimal1), None, Some(decimal2)], collected);
2894    }
2895
2896    #[test]
2897    fn test_from_iter_decimal256array() {
2898        let value1 = i256::from_i128(12345);
2899        let value2 = i256::from_i128(56789);
2900
2901        let mut array: Decimal256Array =
2902            vec![Some(value1), None, Some(value2)].into_iter().collect();
2903        array = array.with_precision_and_scale(76, 10).unwrap();
2904        assert_eq!(array.len(), 3);
2905        assert_eq!(array.data_type(), &DataType::Decimal256(76, 10));
2906        assert_eq!(value1, array.value(0));
2907        assert!(!array.is_null(0));
2908        assert!(array.is_null(1));
2909        assert_eq!(value2, array.value(2));
2910        assert!(!array.is_null(2));
2911    }
2912
2913    #[test]
2914    fn test_from_iter_decimal128array() {
2915        let mut array: Decimal128Array = vec![Some(-100), None, Some(101)].into_iter().collect();
2916        array = array.with_precision_and_scale(38, 10).unwrap();
2917        assert_eq!(array.len(), 3);
2918        assert_eq!(array.data_type(), &DataType::Decimal128(38, 10));
2919        assert_eq!(-100_i128, array.value(0));
2920        assert!(!array.is_null(0));
2921        assert!(array.is_null(1));
2922        assert_eq!(101_i128, array.value(2));
2923        assert!(!array.is_null(2));
2924    }
2925
2926    #[test]
2927    fn test_decimal64_iter() {
2928        let mut builder = Decimal64Builder::with_capacity(30);
2929        let decimal1 = 12345;
2930        builder.append_value(decimal1);
2931
2932        builder.append_null();
2933
2934        let decimal2 = 56789;
2935        builder.append_value(decimal2);
2936
2937        let array: Decimal64Array = builder.finish().with_precision_and_scale(18, 4).unwrap();
2938
2939        let collected: Vec<_> = array.iter().collect();
2940        assert_eq!(vec![Some(decimal1), None, Some(decimal2)], collected);
2941    }
2942
2943    #[test]
2944    fn test_from_iter_decimal64array() {
2945        let value1 = 12345;
2946        let value2 = 56789;
2947
2948        let mut array: Decimal64Array =
2949            vec![Some(value1), None, Some(value2)].into_iter().collect();
2950        array = array.with_precision_and_scale(18, 4).unwrap();
2951        assert_eq!(array.len(), 3);
2952        assert_eq!(array.data_type(), &DataType::Decimal64(18, 4));
2953        assert_eq!(value1, array.value(0));
2954        assert!(!array.is_null(0));
2955        assert!(array.is_null(1));
2956        assert_eq!(value2, array.value(2));
2957        assert!(!array.is_null(2));
2958    }
2959
2960    #[test]
2961    fn test_decimal32_iter() {
2962        let mut builder = Decimal32Builder::with_capacity(30);
2963        let decimal1 = 12345;
2964        builder.append_value(decimal1);
2965
2966        builder.append_null();
2967
2968        let decimal2 = 56789;
2969        builder.append_value(decimal2);
2970
2971        let array: Decimal32Array = builder.finish().with_precision_and_scale(9, 2).unwrap();
2972
2973        let collected: Vec<_> = array.iter().collect();
2974        assert_eq!(vec![Some(decimal1), None, Some(decimal2)], collected);
2975    }
2976
2977    #[test]
2978    fn test_from_iter_decimal32array() {
2979        let value1 = 12345;
2980        let value2 = 56789;
2981
2982        let mut array: Decimal32Array =
2983            vec![Some(value1), None, Some(value2)].into_iter().collect();
2984        array = array.with_precision_and_scale(9, 2).unwrap();
2985        assert_eq!(array.len(), 3);
2986        assert_eq!(array.data_type(), &DataType::Decimal32(9, 2));
2987        assert_eq!(value1, array.value(0));
2988        assert!(!array.is_null(0));
2989        assert!(array.is_null(1));
2990        assert_eq!(value2, array.value(2));
2991        assert!(!array.is_null(2));
2992    }
2993
2994    #[test]
2995    fn test_unary_opt() {
2996        let array = Int32Array::from(vec![1, 2, 3, 4, 5, 6, 7]);
2997        let r = array.unary_opt::<_, Int32Type>(|x| (x % 2 != 0).then_some(x));
2998
2999        let expected = Int32Array::from(vec![Some(1), None, Some(3), None, Some(5), None, Some(7)]);
3000        assert_eq!(r, expected);
3001
3002        let r = expected.unary_opt::<_, Int32Type>(|x| (x % 3 != 0).then_some(x));
3003        let expected = Int32Array::from(vec![Some(1), None, None, None, Some(5), None, Some(7)]);
3004        assert_eq!(r, expected);
3005    }
3006
3007    #[test]
3008    #[should_panic(
3009        expected = "Trying to access an element at index 4 from a PrimitiveArray of length 3"
3010    )]
3011    fn test_fixed_size_binary_array_get_value_index_out_of_bound() {
3012        let array = Decimal128Array::from(vec![-100, 0, 101]);
3013        array.value(4);
3014    }
3015
3016    #[test]
3017    fn test_into_builder() {
3018        let array: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
3019
3020        let boxed: ArrayRef = Arc::new(array);
3021        let col: Int32Array = downcast_array(&boxed);
3022        drop(boxed);
3023
3024        let mut builder = col.into_builder().unwrap();
3025
3026        let slice = builder.values_slice_mut();
3027        assert_eq!(slice, &[1, 2, 3]);
3028
3029        slice[0] = 4;
3030        slice[1] = 2;
3031        slice[2] = 1;
3032
3033        let expected: Int32Array = vec![Some(4), Some(2), Some(1)].into_iter().collect();
3034
3035        let new_array = builder.finish();
3036        assert_eq!(expected, new_array);
3037    }
3038
3039    #[test]
3040    fn test_into_builder_cloned_array() {
3041        let array: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
3042
3043        let boxed: ArrayRef = Arc::new(array);
3044
3045        let col: Int32Array = PrimitiveArray::<Int32Type>::from(boxed.to_data());
3046        let err = col.into_builder();
3047
3048        match err {
3049            Ok(_) => panic!("Should not get builder from cloned array"),
3050            Err(returned) => {
3051                let expected: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
3052                assert_eq!(expected, returned)
3053            }
3054        }
3055    }
3056
3057    #[test]
3058    fn test_into_builder_keeps_data_type() {
3059        let array = Decimal128Array::from(vec![1, 2])
3060            .with_precision_and_scale(10, 2)
3061            .unwrap();
3062        let data_type = array.data_type().clone();
3063
3064        // Shared buffers: the array is returned
3065        let shared = array.clone();
3066        let array = array.into_builder().unwrap_err();
3067        assert_eq!(array.data_type(), &data_type);
3068        drop(shared);
3069
3070        // Unshared buffers: the buffers are reused by the builder
3071        let mut builder = array.into_builder().unwrap();
3072        builder.append_value(3);
3073        assert_eq!(builder.finish().data_type(), &data_type);
3074    }
3075
3076    #[test]
3077    fn test_into_builder_on_sliced_array() {
3078        let array: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
3079        let slice = array.slice(1, 2);
3080        let col: Int32Array = downcast_array(&slice);
3081
3082        drop(slice);
3083
3084        col.into_builder()
3085            .expect_err("Should not build builder from sliced array");
3086    }
3087
3088    #[test]
3089    fn test_unary_mut() {
3090        let array: Int32Array = vec![1, 2, 3].into_iter().map(Some).collect();
3091
3092        let c = array.unary_mut(|x| x * 2 + 1).unwrap();
3093        let expected: Int32Array = vec![3, 5, 7].into_iter().map(Some).collect();
3094
3095        assert_eq!(expected, c);
3096
3097        let array: Int32Array = Int32Array::from(vec![Some(5), Some(7), None]);
3098        let c = array.unary_mut(|x| x * 2 + 1).unwrap();
3099        assert_eq!(c, Int32Array::from(vec![Some(11), Some(15), None]));
3100    }
3101
3102    #[test]
3103    #[should_panic(
3104        expected = "PrimitiveArray expected data type Interval(MonthDayNano) got Interval(DayTime)"
3105    )]
3106    fn test_invalid_interval_type() {
3107        let array = IntervalDayTimeArray::from(vec![IntervalDayTime::ZERO]);
3108        let _ = IntervalMonthDayNanoArray::from(array.into_data());
3109    }
3110
3111    #[test]
3112    fn test_timezone() {
3113        let array = TimestampNanosecondArray::from_iter_values([1, 2]);
3114        assert_eq!(array.timezone(), None);
3115
3116        let array = array.with_timezone("+02:00");
3117        assert_eq!(array.timezone(), Some("+02:00"));
3118    }
3119
3120    #[test]
3121    fn test_try_new() {
3122        Int32Array::new(vec![1, 2, 3, 4].into(), None);
3123        Int32Array::new(vec![1, 2, 3, 4].into(), Some(NullBuffer::new_null(4)));
3124
3125        let err = Int32Array::try_new(vec![1, 2, 3, 4].into(), Some(NullBuffer::new_null(3)))
3126            .unwrap_err();
3127
3128        assert_eq!(
3129            err.to_string(),
3130            "Invalid argument error: Incorrect length of null buffer for PrimitiveArray, expected 4 got 3"
3131        );
3132
3133        TimestampNanosecondArray::new(vec![1, 2, 3, 4].into(), None).with_data_type(
3134            DataType::Timestamp(TimeUnit::Nanosecond, Some("03:00".into())),
3135        );
3136    }
3137
3138    #[test]
3139    #[should_panic(expected = "PrimitiveArray expected data type Int32 got Date32")]
3140    fn test_with_data_type() {
3141        Int32Array::new(vec![1, 2, 3, 4].into(), None).with_data_type(DataType::Date32);
3142    }
3143
3144    #[test]
3145    fn test_time_32second_output() {
3146        let array: Time32SecondArray = vec![
3147            Some(-1),
3148            Some(0),
3149            Some(86_399),
3150            Some(86_400),
3151            Some(86_401),
3152            None,
3153        ]
3154        .into();
3155        let debug_str = format!("{array:?}");
3156        assert_eq!(
3157            "PrimitiveArray<Time32(s)>\n[\n  Cast error: Failed to convert -1 to temporal for Time32(s),\n  00:00:00,\n  23:59:59,\n  Cast error: Failed to convert 86400 to temporal for Time32(s),\n  Cast error: Failed to convert 86401 to temporal for Time32(s),\n  null,\n]",
3158            debug_str
3159        );
3160    }
3161
3162    #[test]
3163    fn test_time_32millisecond_debug_output() {
3164        let array: Time32MillisecondArray = vec![
3165            Some(-1),
3166            Some(0),
3167            Some(86_399_000),
3168            Some(86_400_000),
3169            Some(86_401_000),
3170            None,
3171        ]
3172        .into();
3173        let debug_str = format!("{array:?}");
3174        assert_eq!(
3175            "PrimitiveArray<Time32(ms)>\n[\n  Cast error: Failed to convert -1 to temporal for Time32(ms),\n  00:00:00,\n  23:59:59,\n  Cast error: Failed to convert 86400000 to temporal for Time32(ms),\n  Cast error: Failed to convert 86401000 to temporal for Time32(ms),\n  null,\n]",
3176            debug_str
3177        );
3178    }
3179
3180    #[test]
3181    fn test_time_64nanosecond_debug_output() {
3182        let array: Time64NanosecondArray = vec![
3183            Some(-1),
3184            Some(0),
3185            Some(86_399 * 1_000_000_000),
3186            Some(86_400 * 1_000_000_000),
3187            Some(86_401 * 1_000_000_000),
3188            None,
3189        ]
3190        .into();
3191        let debug_str = format!("{array:?}");
3192        assert_eq!(
3193            "PrimitiveArray<Time64(ns)>\n[\n  Cast error: Failed to convert -1 to temporal for Time64(ns),\n  00:00:00,\n  23:59:59,\n  Cast error: Failed to convert 86400000000000 to temporal for Time64(ns),\n  Cast error: Failed to convert 86401000000000 to temporal for Time64(ns),\n  null,\n]",
3194            debug_str
3195        );
3196    }
3197
3198    #[test]
3199    fn test_time_64microsecond_debug_output() {
3200        let array: Time64MicrosecondArray = vec![
3201            Some(-1),
3202            Some(0),
3203            Some(86_399 * 1_000_000),
3204            Some(86_400 * 1_000_000),
3205            Some(86_401 * 1_000_000),
3206            None,
3207        ]
3208        .into();
3209        let debug_str = format!("{array:?}");
3210        assert_eq!(
3211            "PrimitiveArray<Time64(µs)>\n[\n  Cast error: Failed to convert -1 to temporal for Time64(µs),\n  00:00:00,\n  23:59:59,\n  Cast error: Failed to convert 86400000000 to temporal for Time64(µs),\n  Cast error: Failed to convert 86401000000 to temporal for Time64(µs),\n  null,\n]",
3212            debug_str
3213        );
3214    }
3215
3216    #[test]
3217    fn test_primitive_with_nulls_into_builder() {
3218        let array: Int32Array = vec![
3219            Some(1),
3220            None,
3221            Some(3),
3222            Some(4),
3223            None,
3224            Some(7),
3225            None,
3226            Some(8),
3227        ]
3228        .into_iter()
3229        .collect();
3230        let _ = array.into_builder();
3231    }
3232}