-
Notifications
You must be signed in to change notification settings - Fork 829
/
primitive_array.rs
2692 lines (2411 loc) · 93.8 KB
/
primitive_array.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use crate::array::print_long_array;
use crate::builder::{BooleanBufferBuilder, BufferBuilder, PrimitiveBuilder};
use crate::iterator::PrimitiveIter;
use crate::temporal_conversions::{
as_date, as_datetime, as_datetime_with_timezone, as_duration, as_time,
};
use crate::timezone::Tz;
use crate::trusted_len::trusted_len_unzip;
use crate::types::*;
use crate::{Array, ArrayAccessor, ArrayRef, Scalar};
use arrow_buffer::{i256, ArrowNativeType, Buffer, NullBuffer, ScalarBuffer};
use arrow_data::bit_iterator::try_for_each_valid_idx;
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType};
use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime};
use half::f16;
use std::any::Any;
use std::sync::Arc;
/// A [`PrimitiveArray`] of `i8`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Int8Array;
/// // Create from Vec<Option<i8>>
/// let arr = Int8Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<i8>
/// let arr = Int8Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: Int8Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Int8Array = PrimitiveArray<Int8Type>;
/// A [`PrimitiveArray`] of `i16`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Int16Array;
/// // Create from Vec<Option<i16>>
/// let arr = Int16Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<i16>
/// let arr = Int16Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: Int16Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Int16Array = PrimitiveArray<Int16Type>;
/// A [`PrimitiveArray`] of `i32`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Int32Array;
/// // Create from Vec<Option<i32>>
/// let arr = Int32Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<i32>
/// let arr = Int32Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: Int32Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Int32Array = PrimitiveArray<Int32Type>;
/// A [`PrimitiveArray`] of `i64`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Int64Array;
/// // Create from Vec<Option<i64>>
/// let arr = Int64Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<i64>
/// let arr = Int64Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: Int64Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Int64Array = PrimitiveArray<Int64Type>;
/// A [`PrimitiveArray`] of `u8`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::UInt8Array;
/// // Create from Vec<Option<u8>>
/// let arr = UInt8Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<u8>
/// let arr = UInt8Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: UInt8Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type UInt8Array = PrimitiveArray<UInt8Type>;
/// A [`PrimitiveArray`] of `u16`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::UInt16Array;
/// // Create from Vec<Option<u16>>
/// let arr = UInt16Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<u16>
/// let arr = UInt16Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: UInt16Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type UInt16Array = PrimitiveArray<UInt16Type>;
/// A [`PrimitiveArray`] of `u32`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::UInt32Array;
/// // Create from Vec<Option<u32>>
/// let arr = UInt32Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<u32>
/// let arr = UInt32Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: UInt32Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type UInt32Array = PrimitiveArray<UInt32Type>;
/// A [`PrimitiveArray`] of `u64`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::UInt64Array;
/// // Create from Vec<Option<u64>>
/// let arr = UInt64Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<u64>
/// let arr = UInt64Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: UInt64Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type UInt64Array = PrimitiveArray<UInt64Type>;
/// A [`PrimitiveArray`] of `f16`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Float16Array;
/// use half::f16;
/// // Create from Vec<Option<f16>>
/// let arr = Float16Array::from(vec![Some(f16::from_f64(1.0)), Some(f16::from_f64(2.0))]);
/// // Create from Vec<i8>
/// let arr = Float16Array::from(vec![f16::from_f64(1.0), f16::from_f64(2.0), f16::from_f64(3.0)]);
/// // Create iter/collect
/// let arr: Float16Array = std::iter::repeat(f16::from_f64(1.0)).take(10).collect();
/// ```
///
/// # Example: Using `collect`
/// ```
/// # use arrow_array::Float16Array;
/// use half::f16;
/// let arr : Float16Array = [Some(f16::from_f64(1.0)), Some(f16::from_f64(2.0))].into_iter().collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Float16Array = PrimitiveArray<Float16Type>;
/// A [`PrimitiveArray`] of `f32`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Float32Array;
/// // Create from Vec<Option<f32>>
/// let arr = Float32Array::from(vec![Some(1.0), None, Some(2.0)]);
/// // Create from Vec<f32>
/// let arr = Float32Array::from(vec![1.0, 2.0, 3.0]);
/// // Create iter/collect
/// let arr: Float32Array = std::iter::repeat(42.0).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Float32Array = PrimitiveArray<Float32Type>;
/// A [`PrimitiveArray`] of `f64`
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Float64Array;
/// // Create from Vec<Option<f32>>
/// let arr = Float64Array::from(vec![Some(1.0), None, Some(2.0)]);
/// // Create from Vec<f32>
/// let arr = Float64Array::from(vec![1.0, 2.0, 3.0]);
/// // Create iter/collect
/// let arr: Float64Array = std::iter::repeat(42.0).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Float64Array = PrimitiveArray<Float64Type>;
/// A [`PrimitiveArray`] of seconds since UNIX epoch stored as `i64`
///
/// This type is similar to the [`chrono::DateTime`] type and can hold
/// values such as `1970-05-09 14:25:11 +01:00`
///
/// See also [`Timestamp`](arrow_schema::DataType::Timestamp).
///
/// # Example: UTC timestamps post epoch
/// ```
/// # use arrow_array::TimestampSecondArray;
/// use arrow_array::timezone::Tz;
/// // Corresponds to single element array with entry 1970-05-09T14:25:11+0:00
/// let arr = TimestampSecondArray::from(vec![11111111]);
/// // OR
/// let arr = TimestampSecondArray::from(vec![Some(11111111)]);
/// let utc_tz: Tz = "+00:00".parse().unwrap();
///
/// 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")
/// ```
///
/// # Example: UTC timestamps pre epoch
/// ```
/// # use arrow_array::TimestampSecondArray;
/// use arrow_array::timezone::Tz;
/// // Corresponds to single element array with entry 1969-08-25T09:34:49+0:00
/// let arr = TimestampSecondArray::from(vec![-11111111]);
/// // OR
/// let arr = TimestampSecondArray::from(vec![Some(-11111111)]);
/// let utc_tz: Tz = "+00:00".parse().unwrap();
///
/// 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")
/// ```
///
/// # Example: With timezone specified
/// ```
/// # use arrow_array::TimestampSecondArray;
/// use arrow_array::timezone::Tz;
/// // Corresponds to single element array with entry 1970-05-10T00:25:11+10:00
/// let arr = TimestampSecondArray::from(vec![11111111]).with_timezone("+10:00".to_string());
/// // OR
/// let arr = TimestampSecondArray::from(vec![Some(11111111)]).with_timezone("+10:00".to_string());
/// let sydney_tz: Tz = "+10:00".parse().unwrap();
///
/// 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")
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type TimestampSecondArray = PrimitiveArray<TimestampSecondType>;
/// A [`PrimitiveArray`] of milliseconds since UNIX epoch stored as `i64`
///
/// See examples for [`TimestampSecondArray`]
pub type TimestampMillisecondArray = PrimitiveArray<TimestampMillisecondType>;
/// A [`PrimitiveArray`] of microseconds since UNIX epoch stored as `i64`
///
/// See examples for [`TimestampSecondArray`]
pub type TimestampMicrosecondArray = PrimitiveArray<TimestampMicrosecondType>;
/// A [`PrimitiveArray`] of nanoseconds since UNIX epoch stored as `i64`
///
/// See examples for [`TimestampSecondArray`]
pub type TimestampNanosecondArray = PrimitiveArray<TimestampNanosecondType>;
/// A [`PrimitiveArray`] of days since UNIX epoch stored as `i32`
///
/// This type is similar to the [`chrono::NaiveDate`] type and can hold
/// values such as `2018-11-13`
pub type Date32Array = PrimitiveArray<Date32Type>;
/// A [`PrimitiveArray`] of milliseconds since UNIX epoch stored as `i64`
///
/// This type is similar to the [`chrono::NaiveDate`] type and can hold
/// values such as `2018-11-13`
pub type Date64Array = PrimitiveArray<Date64Type>;
/// A [`PrimitiveArray`] of seconds since midnight stored as `i32`
///
/// This type is similar to the [`chrono::NaiveTime`] type and can
/// hold values such as `00:02:00`
pub type Time32SecondArray = PrimitiveArray<Time32SecondType>;
/// A [`PrimitiveArray`] of milliseconds since midnight stored as `i32`
///
/// This type is similar to the [`chrono::NaiveTime`] type and can
/// hold values such as `00:02:00.123`
pub type Time32MillisecondArray = PrimitiveArray<Time32MillisecondType>;
/// A [`PrimitiveArray`] of microseconds since midnight stored as `i64`
///
/// This type is similar to the [`chrono::NaiveTime`] type and can
/// hold values such as `00:02:00.123456`
pub type Time64MicrosecondArray = PrimitiveArray<Time64MicrosecondType>;
/// A [`PrimitiveArray`] of nanoseconds since midnight stored as `i64`
///
/// This type is similar to the [`chrono::NaiveTime`] type and can
/// hold values such as `00:02:00.123456789`
pub type Time64NanosecondArray = PrimitiveArray<Time64NanosecondType>;
/// A [`PrimitiveArray`] of “calendar” intervals in whole months
///
/// See [`IntervalYearMonthType`] for details on representation and caveats.
///
/// # Example
/// ```
/// # use arrow_array::IntervalYearMonthArray;
/// let array = IntervalYearMonthArray::from(vec![
/// 2, // 2 months
/// 25, // 2 years and 1 month
/// -1 // -1 months
/// ]);
/// ```
pub type IntervalYearMonthArray = PrimitiveArray<IntervalYearMonthType>;
/// A [`PrimitiveArray`] of “calendar” intervals in days and milliseconds
///
/// See [`IntervalDayTime`] for details on representation and caveats.
///
/// # Example
/// ```
/// # use arrow_array::IntervalDayTimeArray;
/// use arrow_array::types::IntervalDayTime;
/// let array = IntervalDayTimeArray::from(vec![
/// IntervalDayTime::new(1, 1000), // 1 day, 1000 milliseconds
/// IntervalDayTime::new(33, 0), // 33 days, 0 milliseconds
/// IntervalDayTime::new(0, 12 * 60 * 60 * 1000), // 0 days, 12 hours
/// ]);
/// ```
pub type IntervalDayTimeArray = PrimitiveArray<IntervalDayTimeType>;
/// A [`PrimitiveArray`] of “calendar” intervals in months, days, and nanoseconds.
///
/// See [`IntervalMonthDayNano`] for details on representation and caveats.
///
/// # Example
/// ```
/// # use arrow_array::IntervalMonthDayNanoArray;
/// use arrow_array::types::IntervalMonthDayNano;
/// let array = IntervalMonthDayNanoArray::from(vec![
/// IntervalMonthDayNano::new(1, 2, 1000), // 1 month, 2 days, 1 nanosecond
/// IntervalMonthDayNano::new(12, 1, 0), // 12 months, 1 days, 0 nanoseconds
/// IntervalMonthDayNano::new(0, 0, 12 * 1000 * 1000), // 0 days, 12 milliseconds
/// ]);
/// ```
pub type IntervalMonthDayNanoArray = PrimitiveArray<IntervalMonthDayNanoType>;
/// A [`PrimitiveArray`] of elapsed durations in seconds
pub type DurationSecondArray = PrimitiveArray<DurationSecondType>;
/// A [`PrimitiveArray`] of elapsed durations in milliseconds
pub type DurationMillisecondArray = PrimitiveArray<DurationMillisecondType>;
/// A [`PrimitiveArray`] of elapsed durations in microseconds
pub type DurationMicrosecondArray = PrimitiveArray<DurationMicrosecondType>;
/// A [`PrimitiveArray`] of elapsed durations in nanoseconds
pub type DurationNanosecondArray = PrimitiveArray<DurationNanosecondType>;
/// A [`PrimitiveArray`] of 128-bit fixed point decimals
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Decimal128Array;
/// // Create from Vec<Option<i18>>
/// let arr = Decimal128Array::from(vec![Some(1), None, Some(2)]);
/// // Create from Vec<i128>
/// let arr = Decimal128Array::from(vec![1, 2, 3]);
/// // Create iter/collect
/// let arr: Decimal128Array = std::iter::repeat(42).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Decimal128Array = PrimitiveArray<Decimal128Type>;
/// A [`PrimitiveArray`] of 256-bit fixed point decimals
///
/// # Examples
///
/// Construction
///
/// ```
/// # use arrow_array::Decimal256Array;
/// use arrow_buffer::i256;
/// // Create from Vec<Option<i256>>
/// let arr = Decimal256Array::from(vec![Some(i256::from(1)), None, Some(i256::from(2))]);
/// // Create from Vec<i256>
/// let arr = Decimal256Array::from(vec![i256::from(1), i256::from(2), i256::from(3)]);
/// // Create iter/collect
/// let arr: Decimal256Array = std::iter::repeat(i256::from(42)).take(10).collect();
/// ```
///
/// See [`PrimitiveArray`] for more information and examples
pub type Decimal256Array = PrimitiveArray<Decimal256Type>;
pub use crate::types::ArrowPrimitiveType;
/// An array of primitive values, of type [`ArrowPrimitiveType`]
///
/// # Example: From a Vec
///
/// ```
/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
/// let arr: PrimitiveArray<Int32Type> = vec![1, 2, 3, 4].into();
/// assert_eq!(4, arr.len());
/// assert_eq!(0, arr.null_count());
/// assert_eq!(arr.values(), &[1, 2, 3, 4])
/// ```
///
/// # Example: From an optional Vec
///
/// ```
/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
/// let arr: PrimitiveArray<Int32Type> = vec![Some(1), None, Some(3), None].into();
/// assert_eq!(4, arr.len());
/// assert_eq!(2, arr.null_count());
/// // Note: values for null indexes are arbitrary
/// assert_eq!(arr.values(), &[1, 0, 3, 0])
/// ```
///
/// # Example: From an iterator of values
///
/// ```
/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
/// let arr: PrimitiveArray<Int32Type> = (0..10).map(|x| x + 1).collect();
/// assert_eq!(10, arr.len());
/// assert_eq!(0, arr.null_count());
/// for i in 0..10i32 {
/// assert_eq!(i + 1, arr.value(i as usize));
/// }
/// ```
///
/// # Example: From an iterator of option
///
/// ```
/// # use arrow_array::{Array, PrimitiveArray, types::Int32Type};
/// let arr: PrimitiveArray<Int32Type> = (0..10).map(|x| (x % 2 == 0).then_some(x)).collect();
/// assert_eq!(10, arr.len());
/// assert_eq!(5, arr.null_count());
/// // Note: values for null indexes are arbitrary
/// assert_eq!(arr.values(), &[0, 0, 2, 0, 4, 0, 6, 0, 8, 0])
/// ```
///
/// # Example: Using Builder
///
/// ```
/// # use arrow_array::Array;
/// # use arrow_array::builder::PrimitiveBuilder;
/// # use arrow_array::types::Int32Type;
/// let mut builder = PrimitiveBuilder::<Int32Type>::new();
/// builder.append_value(1);
/// builder.append_null();
/// builder.append_value(2);
/// let array = builder.finish();
/// // Note: values for null indexes are arbitrary
/// assert_eq!(array.values(), &[1, 0, 2]);
/// assert!(array.is_null(1));
/// ```
///
/// # Example: Get a `PrimitiveArray` from an [`ArrayRef`]
/// ```
/// # use std::sync::Arc;
/// # use arrow_array::{Array, cast::AsArray, ArrayRef, Float32Array, PrimitiveArray};
/// # use arrow_array::types::{Float32Type};
/// # use arrow_schema::DataType;
/// # let array: ArrayRef = Arc::new(Float32Array::from(vec![1.2, 2.3]));
/// // will panic if the array is not a Float32Array
/// assert_eq!(&DataType::Float32, array.data_type());
/// let f32_array: Float32Array = array.as_primitive().clone();
/// assert_eq!(f32_array, Float32Array::from(vec![1.2, 2.3]));
/// ```
pub struct PrimitiveArray<T: ArrowPrimitiveType> {
data_type: DataType,
/// Values data
values: ScalarBuffer<T::Native>,
nulls: Option<NullBuffer>,
}
impl<T: ArrowPrimitiveType> Clone for PrimitiveArray<T> {
fn clone(&self) -> Self {
Self {
data_type: self.data_type.clone(),
values: self.values.clone(),
nulls: self.nulls.clone(),
}
}
}
impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
/// Create a new [`PrimitiveArray`] from the provided values and nulls
///
/// # Panics
///
/// Panics if [`Self::try_new`] returns an error
///
/// # Example
///
/// Creating a [`PrimitiveArray`] directly from a [`ScalarBuffer`] and [`NullBuffer`] using
/// this constructor is the most performant approach, avoiding any additional allocations
///
/// ```
/// # use arrow_array::Int32Array;
/// # use arrow_array::types::Int32Type;
/// # use arrow_buffer::NullBuffer;
/// // [1, 2, 3, 4]
/// let array = Int32Array::new(vec![1, 2, 3, 4].into(), None);
/// // [1, null, 3, 4]
/// let nulls = NullBuffer::from(vec![true, false, true, true]);
/// let array = Int32Array::new(vec![1, 2, 3, 4].into(), Some(nulls));
/// ```
pub fn new(values: ScalarBuffer<T::Native>, nulls: Option<NullBuffer>) -> Self {
Self::try_new(values, nulls).unwrap()
}
/// Create a new [`PrimitiveArray`] of the given length where all values are null
pub fn new_null(length: usize) -> Self {
Self {
data_type: T::DATA_TYPE,
values: vec![T::Native::usize_as(0); length].into(),
nulls: Some(NullBuffer::new_null(length)),
}
}
/// Create a new [`PrimitiveArray`] from the provided values and nulls
///
/// # Errors
///
/// Errors if:
/// - `values.len() != nulls.len()`
pub fn try_new(
values: ScalarBuffer<T::Native>,
nulls: Option<NullBuffer>,
) -> Result<Self, ArrowError> {
if let Some(n) = nulls.as_ref() {
if n.len() != values.len() {
return Err(ArrowError::InvalidArgumentError(format!(
"Incorrect length of null buffer for PrimitiveArray, expected {} got {}",
values.len(),
n.len(),
)));
}
}
Ok(Self {
data_type: T::DATA_TYPE,
values,
nulls,
})
}
/// Create a new [`Scalar`] from `value`
pub fn new_scalar(value: T::Native) -> Scalar<Self> {
Scalar::new(Self {
data_type: T::DATA_TYPE,
values: vec![value].into(),
nulls: None,
})
}
/// Deconstruct this array into its constituent parts
pub fn into_parts(self) -> (DataType, ScalarBuffer<T::Native>, Option<NullBuffer>) {
(self.data_type, self.values, self.nulls)
}
/// Overrides the [`DataType`] of this [`PrimitiveArray`]
///
/// Prefer using [`Self::with_timezone`] or [`Self::with_precision_and_scale`] where
/// the primitive type is suitably constrained, as these cannot panic
///
/// # Panics
///
/// Panics if ![Self::is_compatible]
pub fn with_data_type(self, data_type: DataType) -> Self {
Self::assert_compatible(&data_type);
Self { data_type, ..self }
}
/// Asserts that `data_type` is compatible with `Self`
fn assert_compatible(data_type: &DataType) {
assert!(
Self::is_compatible(data_type),
"PrimitiveArray expected data type {} got {}",
T::DATA_TYPE,
data_type
);
}
/// Returns the length of this array.
#[inline]
pub fn len(&self) -> usize {
self.values.len()
}
/// Returns whether this array is empty.
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
/// Returns the values of this array
#[inline]
pub fn values(&self) -> &ScalarBuffer<T::Native> {
&self.values
}
/// Returns a new primitive array builder
pub fn builder(capacity: usize) -> PrimitiveBuilder<T> {
PrimitiveBuilder::<T>::with_capacity(capacity)
}
/// Returns if this [`PrimitiveArray`] is compatible with the provided [`DataType`]
///
/// This is equivalent to `data_type == T::DATA_TYPE`, however ignores timestamp
/// timezones and decimal precision and scale
pub fn is_compatible(data_type: &DataType) -> bool {
match T::DATA_TYPE {
DataType::Timestamp(t1, _) => {
matches!(data_type, DataType::Timestamp(t2, _) if &t1 == t2)
}
DataType::Decimal128(_, _) => matches!(data_type, DataType::Decimal128(_, _)),
DataType::Decimal256(_, _) => matches!(data_type, DataType::Decimal256(_, _)),
_ => T::DATA_TYPE.eq(data_type),
}
}
/// Returns the primitive value at index `i`.
///
/// # Safety
///
/// caller must ensure that the passed in offset is less than the array len()
#[inline]
pub unsafe fn value_unchecked(&self, i: usize) -> T::Native {
*self.values.get_unchecked(i)
}
/// Returns the primitive value at index `i`.
/// # Panics
/// Panics if index `i` is out of bounds
#[inline]
pub fn value(&self, i: usize) -> T::Native {
assert!(
i < self.len(),
"Trying to access an element at index {} from a PrimitiveArray of length {}",
i,
self.len()
);
unsafe { self.value_unchecked(i) }
}
/// Creates a PrimitiveArray based on an iterator of values without nulls
pub fn from_iter_values<I: IntoIterator<Item = T::Native>>(iter: I) -> Self {
let val_buf: Buffer = iter.into_iter().collect();
let len = val_buf.len() / std::mem::size_of::<T::Native>();
Self {
data_type: T::DATA_TYPE,
values: ScalarBuffer::new(val_buf, 0, len),
nulls: None,
}
}
/// Creates a PrimitiveArray based on a constant value with `count` elements
pub fn from_value(value: T::Native, count: usize) -> Self {
unsafe {
let val_buf = Buffer::from_trusted_len_iter((0..count).map(|_| value));
Self::new(val_buf.into(), None)
}
}
/// Returns an iterator that returns the values of `array.value(i)` for an iterator with each element `i`
pub fn take_iter<'a>(
&'a self,
indexes: impl Iterator<Item = Option<usize>> + 'a,
) -> impl Iterator<Item = Option<T::Native>> + 'a {
indexes.map(|opt_index| opt_index.map(|index| self.value(index)))
}
/// Returns an iterator that returns the values of `array.value(i)` for an iterator with each element `i`
/// # Safety
///
/// caller must ensure that the offsets in the iterator are less than the array len()
pub unsafe fn take_iter_unchecked<'a>(
&'a self,
indexes: impl Iterator<Item = Option<usize>> + 'a,
) -> impl Iterator<Item = Option<T::Native>> + 'a {
indexes.map(|opt_index| opt_index.map(|index| self.value_unchecked(index)))
}
/// Returns a zero-copy slice of this array with the indicated offset and length.
pub fn slice(&self, offset: usize, length: usize) -> Self {
Self {
data_type: self.data_type.clone(),
values: self.values.slice(offset, length),
nulls: self.nulls.as_ref().map(|n| n.slice(offset, length)),
}
}
/// Reinterprets this array's contents as a different data type without copying
///
/// This can be used to efficiently convert between primitive arrays with the
/// same underlying representation
///
/// Note: this will not modify the underlying values, and therefore may change
/// the semantic values of the array, e.g. 100 milliseconds in a [`TimestampNanosecondArray`]
/// will become 100 seconds in a [`TimestampSecondArray`].
///
/// For casts that preserve the semantic value, check out the
/// [compute kernels](https://docs.rs/arrow/latest/arrow/compute/kernels/cast/index.html).
///
/// ```
/// # use arrow_array::{Int64Array, TimestampNanosecondArray};
/// let a = Int64Array::from_iter_values([1, 2, 3, 4]);
/// let b: TimestampNanosecondArray = a.reinterpret_cast();
/// ```
pub fn reinterpret_cast<K>(&self) -> PrimitiveArray<K>
where
K: ArrowPrimitiveType<Native = T::Native>,
{
let d = self.to_data().into_builder().data_type(K::DATA_TYPE);
// SAFETY:
// Native type is the same
PrimitiveArray::from(unsafe { d.build_unchecked() })
}
/// Applies a unary infallible function to a primitive array, producing a
/// new array of potentially different type.
///
/// This is the fastest way to perform an operation on a primitive array
/// when the benefits of a vectorized operation outweigh the cost of
/// branching nulls and non-nulls.
///
/// See also
/// * [`Self::unary_mut`] for in place modification.
/// * [`Self::try_unary`] for fallible operations.
/// * [`arrow::compute::binary`] for binary operations
///
/// [`arrow::compute::binary`]: https://docs.rs/arrow/latest/arrow/compute/fn.binary.html
/// # Null Handling
///
/// Applies the function for all values, including those on null slots. This
/// will often allow the compiler to generate faster vectorized code, but
/// requires that the operation must be infallible (not error/panic) for any
/// value of the corresponding type or this function may panic.
///
/// # Example
/// ```rust
/// # use arrow_array::{Int32Array, Float32Array, types::Int32Type};
/// # fn main() {
/// let array = Int32Array::from(vec![Some(5), Some(7), None]);
/// // Create a new array with the value of applying sqrt
/// let c = array.unary(|x| f32::sqrt(x as f32));
/// assert_eq!(c, Float32Array::from(vec![Some(2.236068), Some(2.6457512), None]));
/// # }
/// ```
pub fn unary<F, O>(&self, op: F) -> PrimitiveArray<O>
where
O: ArrowPrimitiveType,
F: Fn(T::Native) -> O::Native,
{
let nulls = self.nulls().cloned();
let values = self.values().iter().map(|v| op(*v));
// JUSTIFICATION
// Benefit
// ~60% speedup
// Soundness
// `values` is an iterator with a known size because arrays are sized.
let buffer = unsafe { Buffer::from_trusted_len_iter(values) };
PrimitiveArray::new(buffer.into(), nulls)
}
/// Applies a unary and infallible function to the array in place if possible.
///
/// # Buffer Reuse
///
/// If the underlying buffers are not shared with other arrays, mutates the
/// underlying buffer in place, without allocating.
///
/// If the underlying buffer is shared, returns Err(self)
///
/// # Null Handling
///
/// See [`Self::unary`] for more information on null handling.
///
/// # Example
///
/// ```rust
/// # use arrow_array::{Int32Array, types::Int32Type};
/// let array = Int32Array::from(vec![Some(5), Some(7), None]);
/// // Apply x*2+1 to the data in place, no allocations
/// let c = array.unary_mut(|x| x * 2 + 1).unwrap();
/// assert_eq!(c, Int32Array::from(vec![Some(11), Some(15), None]));
/// ```
///
/// # Example: modify [`ArrayRef`] in place, if not shared
///
/// It is also possible to modify an [`ArrayRef`] if there are no other
/// references to the underlying buffer.
///
/// ```rust
/// # use std::sync::Arc;
/// # use arrow_array::{Array, cast::AsArray, ArrayRef, Int32Array, PrimitiveArray, types::Int32Type};
/// # let array: ArrayRef = Arc::new(Int32Array::from(vec![Some(5), Some(7), None]));
/// // Convert to Int32Array (panic's if array.data_type is not Int32)
/// let a = array.as_primitive::<Int32Type>().clone();
/// // Try to apply x*2+1 to the data in place, fails because array is still shared
/// a.unary_mut(|x| x * 2 + 1).unwrap_err();
/// // Try again, this time dropping the last remaining reference
/// let a = array.as_primitive::<Int32Type>().clone();
/// drop(array);
/// // Now we can apply the operation in place
/// let c = a.unary_mut(|x| x * 2 + 1).unwrap();
/// assert_eq!(c, Int32Array::from(vec![Some(11), Some(15), None]));
/// ```
pub fn unary_mut<F>(self, op: F) -> Result<PrimitiveArray<T>, PrimitiveArray<T>>
where
F: Fn(T::Native) -> T::Native,
{
let mut builder = self.into_builder()?;
builder
.values_slice_mut()
.iter_mut()
.for_each(|v| *v = op(*v));
Ok(builder.finish())
}
/// Applies a unary fallible function to all valid values in a primitive
/// array, producing a new array of potentially different type.
///
/// Applies `op` to only rows that are valid, which is often significantly
/// slower than [`Self::unary`], which should be preferred if `op` is
/// fallible.
///
/// Note: LLVM is currently unable to effectively vectorize fallible operations
pub fn try_unary<F, O, E>(&self, op: F) -> Result<PrimitiveArray<O>, E>
where
O: ArrowPrimitiveType,
F: Fn(T::Native) -> Result<O::Native, E>,
{
let len = self.len();
let nulls = self.nulls().cloned();
let mut buffer = BufferBuilder::<O::Native>::new(len);
buffer.append_n_zeroed(len);
let slice = buffer.as_slice_mut();
let f = |idx| {
unsafe { *slice.get_unchecked_mut(idx) = op(self.value_unchecked(idx))? };
Ok::<_, E>(())
};
match &nulls {
Some(nulls) => nulls.try_for_each_valid_idx(f)?,
None => (0..len).try_for_each(f)?,
}
let values = buffer.finish().into();
Ok(PrimitiveArray::new(values, nulls))
}
/// Applies a unary fallible function to all valid values in a mutable
/// primitive array.
///
/// # Null Handling
///
/// See [`Self::try_unary`] for more information on null handling.
///
/// # Buffer Reuse
///
/// See [`Self::unary_mut`] for more information on buffer reuse.
///
/// This returns an `Err` when the input array is shared buffer with other
/// array. In the case, returned `Err` wraps input array. If the function
/// encounters an error during applying on values. In the case, this returns an `Err` within
/// an `Ok` which wraps the actual error.
///
/// Note: LLVM is currently unable to effectively vectorize fallible operations
pub fn try_unary_mut<F, E>(
self,
op: F,
) -> Result<Result<PrimitiveArray<T>, E>, PrimitiveArray<T>>
where
F: Fn(T::Native) -> Result<T::Native, E>,
{
let len = self.len();
let null_count = self.null_count();
let mut builder = self.into_builder()?;
let (slice, null_buffer) = builder.slices_mut();
let r = try_for_each_valid_idx(len, 0, null_count, null_buffer.as_deref(), |idx| {
unsafe { *slice.get_unchecked_mut(idx) = op(*slice.get_unchecked(idx))? };
Ok::<_, E>(())
});
if let Err(err) = r {
return Ok(Err(err));
}
Ok(Ok(builder.finish()))
}
/// Applies a unary and nullable function to all valid values in a primitive array
///
/// Applies `op` to only rows that are valid, which is often significantly
/// slower than [`Self::unary`], which should be preferred if `op` is
/// fallible.
///
/// Note: LLVM is currently unable to effectively vectorize fallible operations
pub fn unary_opt<F, O>(&self, op: F) -> PrimitiveArray<O>
where
O: ArrowPrimitiveType,
F: Fn(T::Native) -> Option<O::Native>,
{
let len = self.len();
let (nulls, null_count, offset) = match self.nulls() {
Some(n) => (Some(n.validity()), n.null_count(), n.offset()),
None => (None, 0, 0),
};
let mut null_builder = BooleanBufferBuilder::new(len);
match nulls {
Some(b) => null_builder.append_packed_range(offset..offset + len, b),
None => null_builder.append_n(len, true),
}
let mut buffer = BufferBuilder::<O::Native>::new(len);
buffer.append_n_zeroed(len);
let slice = buffer.as_slice_mut();
let mut out_null_count = null_count;
let _ = try_for_each_valid_idx(len, offset, null_count, nulls, |idx| {
match op(unsafe { self.value_unchecked(idx) }) {
Some(v) => unsafe { *slice.get_unchecked_mut(idx) = v },
None => {
out_null_count += 1;
null_builder.set_bit(idx, false);
}
}
Ok::<_, ()>(())
});
let nulls = null_builder.finish();
let values = buffer.finish().into();