forked from apache/arrow-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathffi.rs
More file actions
1985 lines (1696 loc) · 70.9 KB
/
Copy pathffi.rs
File metadata and controls
1985 lines (1696 loc) · 70.9 KB
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.
//! Contains declarations to bind to the [C Data Interface](https://arrow.apache.org/docs/format/CDataInterface.html).
//!
//! Generally, this module is divided in two main interfaces:
//! One interface maps C ABI to native Rust types, i.e. convert c-pointers, c_char, to native rust.
//! This is handled by [FFI_ArrowSchema] and [FFI_ArrowArray].
//!
//! The second interface maps native Rust types to the Rust-specific implementation of Arrow such as `format` to `Datatype`,
//! `Buffer`, etc. This is handled by `from_ffi` and `to_ffi`.
//!
//!
//! Export to FFI
//!
//! ```rust
//! # use std::sync::Arc;
//! # use arrow_array::{Int32Array, Array, make_array};
//! # use arrow_data::ArrayData;
//! # use arrow_array::ffi::{to_ffi, from_ffi};
//! # use arrow_schema::ArrowError;
//! # fn main() -> Result<(), ArrowError> {
//! // create an array natively
//!
//! let array = Int32Array::from(vec![Some(1), None, Some(3)]);
//! let data = array.into_data();
//!
//! // Export it
//! let (out_array, out_schema) = to_ffi(&data)?;
//!
//! // import it
//! let data = unsafe { from_ffi(out_array, &out_schema) }?;
//! let array = Int32Array::from(data);
//!
//! // verify
//! assert_eq!(array, Int32Array::from(vec![Some(1), None, Some(3)]));
//! #
//! # Ok(())
//! # }
//! ```
//!
//! Import from FFI
//!
//! ```
//! # use std::ptr::addr_of_mut;
//! # use arrow_array::ffi::{from_ffi, FFI_ArrowArray};
//! # use arrow_array::{ArrayRef, make_array};
//! # use arrow_schema::{ArrowError, ffi::FFI_ArrowSchema};
//! #
//! /// A foreign data container that can export to C Data interface
//! struct ForeignArray {};
//!
//! impl ForeignArray {
//! /// Export from foreign array representation to C Data interface
//! /// e.g. <https://github.com/apache/arrow/blob/fc1f9ebbc4c3ae77d5cfc2f9322f4373d3d19b8a/python/pyarrow/array.pxi#L1552>
//! fn export_to_c(&self, array: *mut FFI_ArrowArray, schema: *mut FFI_ArrowSchema) {
//! // ...
//! }
//! }
//!
//! /// Import an [`ArrayRef`] from a [`ForeignArray`]
//! fn import_array(foreign: &ForeignArray) -> Result<ArrayRef, ArrowError> {
//! let mut schema = FFI_ArrowSchema::empty();
//! let mut array = FFI_ArrowArray::empty();
//! foreign.export_to_c(addr_of_mut!(array), addr_of_mut!(schema));
//! Ok(make_array(unsafe { from_ffi(array, &schema) }?))
//! }
//! ```
/*
# Design:
Main assumptions:
* A memory region is deallocated according it its own release mechanism.
* Rust shares memory regions between arrays.
* A memory region should be deallocated when no-one is using it.
The design of this module is as follows:
`ArrowArray` contains two `Arc`s, one per ABI-compatible `struct`, each containing data
according to the C Data Interface. These Arcs are used for ref counting of the structs
within Rust and lifetime management.
Each ABI-compatible `struct` knowns how to `drop` itself, calling `release`.
To import an array, unsafely create an `ArrowArray` from two pointers using [ArrowArray::try_from_raw].
To export an array, create an `ArrowArray` using [ArrowArray::try_new].
*/
use std::{mem::size_of, ptr::NonNull, sync::Arc};
use arrow_buffer::{Buffer, MutableBuffer, bit_util};
pub use arrow_data::ffi::FFI_ArrowArray;
use arrow_data::{ArrayData, ArrayDataBuilder, layout};
pub use arrow_schema::ffi::FFI_ArrowSchema;
use arrow_schema::{ArrowError, DataType, UnionMode};
use crate::array::ArrayRef;
type Result<T> = std::result::Result<T, ArrowError>;
/// Exports an array to raw pointers of the C Data Interface provided by the consumer.
/// # Safety
/// Assumes that these pointers represent valid C Data Interfaces, both in memory
/// representation and lifetime via the `release` mechanism.
///
/// This function copies the content of two FFI structs [arrow_data::ffi::FFI_ArrowArray] and
/// [arrow_schema::ffi::FFI_ArrowSchema] in the array to the location pointed by the raw pointers.
/// Usually the raw pointers are provided by the array data consumer.
#[deprecated(
since = "52.0.0",
note = "Use FFI_ArrowArray::new and FFI_ArrowSchema::try_from"
)]
pub unsafe fn export_array_into_raw(
src: ArrayRef,
out_array: *mut FFI_ArrowArray,
out_schema: *mut FFI_ArrowSchema,
) -> Result<()> {
let data = src.to_data();
let array = FFI_ArrowArray::new(&data);
let schema = FFI_ArrowSchema::try_from(data.data_type())?;
unsafe { std::ptr::write_unaligned(out_array, array) };
unsafe { std::ptr::write_unaligned(out_schema, schema) };
Ok(())
}
/// returns the number of bits that buffer `i` (in the C data interface) is expected to have.
/// This is set by the Arrow specification
fn bit_width(data_type: &DataType, i: usize) -> Result<usize> {
if let Some(primitive) = data_type.primitive_width() {
return match i {
0 => Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" doesn't expect buffer at index 0. Please verify that the C data interface is correctly implemented."
))),
1 => Ok(primitive * 8),
i => Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 2 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
))),
};
}
Ok(match (data_type, i) {
(DataType::Boolean, 1) => 1,
(DataType::Boolean, _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 2 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
(DataType::FixedSizeBinary(num_bytes), 1) => {
TryInto::<usize>::try_into(*num_bytes).map_err(|_| {
ArrowError::InvalidArgumentError(format!(
"cannot determine bit_width for FixedSizeBinary({num_bytes})"
))
})? * u8::BITS as usize
}
(DataType::FixedSizeList(f, num_elems), 1) => {
let child_bit_width = bit_width(f.data_type(), 1)?;
child_bit_width * (*num_elems as usize)
}
(DataType::FixedSizeBinary(_), _) | (DataType::FixedSizeList(_, _), _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 2 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
// Variable-size list and map have one i32 buffer.
// Variable-sized binaries: have two buffers.
// "small": first buffer is i32, second is in bytes
(DataType::Utf8, 1)
| (DataType::Binary, 1)
| (DataType::List(_), 1)
| (DataType::Map(_, _), 1) => i32::BITS as _,
(DataType::Utf8, 2) | (DataType::Binary, 2) => u8::BITS as _,
// List views have two i32 buffers, offsets and sizes
(DataType::ListView(_), 1) | (DataType::ListView(_), 2) => i32::BITS as _,
// Large list views have two i64 buffers, offsets and sizes
(DataType::LargeListView(_), 1) | (DataType::LargeListView(_), 2) => i64::BITS as _,
(DataType::List(_), _) | (DataType::Map(_, _), _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 2 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
(DataType::Utf8, _) | (DataType::Binary, _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 3 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
// Variable-sized binaries: have two buffers.
// LargeUtf8: first buffer is i64, second is in bytes
(DataType::LargeUtf8, 1) | (DataType::LargeBinary, 1) | (DataType::LargeList(_), 1) => {
i64::BITS as _
}
(DataType::LargeUtf8, 2) | (DataType::LargeBinary, 2) | (DataType::LargeList(_), 2) => {
u8::BITS as _
}
(DataType::LargeUtf8, _) | (DataType::LargeBinary, _) | (DataType::LargeList(_), _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 3 buffers, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
// Variable-sized views: have 3 or more buffers.
// Buffer 1 are the u128 views
// Buffers 2...N-1 are u8 byte buffers
(DataType::Utf8View, 1) | (DataType::BinaryView, 1) => u128::BITS as _,
(DataType::Utf8View, _) | (DataType::BinaryView, _) => u8::BITS as _,
// type ids. UnionArray doesn't have null bitmap so buffer index begins with 0.
(DataType::Union(_, _), 0) => i8::BITS as _,
// Only DenseUnion has 2nd buffer
(DataType::Union(_, UnionMode::Dense), 1) => i32::BITS as _,
(DataType::Union(_, UnionMode::Sparse), _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 1 buffer, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
(DataType::Union(_, UnionMode::Dense), _) => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" expects 2 buffer, but requested {i}. Please verify that the C data interface is correctly implemented."
)));
}
(_, 0) => {
// We don't call this `bit_width` to compute buffer length for null buffer. If any types that don't have null buffer like
// UnionArray, they should be handled above.
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" doesn't expect buffer at index 0. Please verify that the C data interface is correctly implemented."
)));
}
_ => {
return Err(ArrowError::CDataInterface(format!(
"The datatype \"{data_type}\" is still not supported in Rust implementation"
)));
}
})
}
/// returns a new buffer corresponding to the index `i` of the FFI array. It may not exist (null pointer).
/// `bits` is the number of bits that the native type of this buffer has.
/// The size of the buffer will be `ceil(self.length * bits, 8)`.
/// # Panic
/// This function panics if `i` is larger or equal to `n_buffers`.
/// # Safety
/// This function assumes that `ceil(self.length * bits, 8)` is the size of the buffer
unsafe fn create_buffer(
owner: Arc<FFI_ArrowArray>,
array: &FFI_ArrowArray,
index: usize,
len: usize,
) -> Option<Buffer> {
if array.num_buffers() == 0 {
return None;
}
NonNull::new(array.buffer(index) as _)
.map(|ptr| unsafe { Buffer::from_custom_allocation(ptr, len, owner) })
}
/// Export to the C Data Interface
pub fn to_ffi(data: &ArrayData) -> Result<(FFI_ArrowArray, FFI_ArrowSchema)> {
let array = FFI_ArrowArray::new(data);
let schema = FFI_ArrowSchema::try_from(data.data_type())?;
Ok((array, schema))
}
/// Import [ArrayData] from the C Data Interface
///
/// # Safety
///
/// This struct assumes that the incoming data agrees with the C data interface.
pub unsafe fn from_ffi(array: FFI_ArrowArray, schema: &FFI_ArrowSchema) -> Result<ArrayData> {
let dt = DataType::try_from(schema)?;
let array = Arc::new(array);
let tmp = ImportedArrowArray {
array: &array,
data_type: dt,
owner: &array,
};
// `consume` realigns buffers before validating (see #10034), so no
// separate `align_buffers()` is needed here.
tmp.consume()
}
/// Import [ArrayData] from the C Data Interface
///
/// # Safety
///
/// This struct assumes that the incoming data agrees with the C data interface.
pub unsafe fn from_ffi_and_data_type(
array: FFI_ArrowArray,
data_type: DataType,
) -> Result<ArrayData> {
let array = Arc::new(array);
let tmp = ImportedArrowArray {
array: &array,
data_type,
owner: &array,
};
// `consume` realigns buffers before validating (see #10034), so no
// separate `align_buffers()` is needed here.
tmp.consume()
}
#[derive(Debug)]
struct ImportedArrowArray<'a> {
array: &'a FFI_ArrowArray,
data_type: DataType,
owner: &'a Arc<FFI_ArrowArray>,
}
impl ImportedArrowArray<'_> {
fn consume(self) -> Result<ArrayData> {
let len = self.array.len();
let offset = self.array.offset();
let null_count = match &self.data_type {
DataType::Null => Some(0),
_ => self.array.null_count_opt(),
};
let data_layout = layout(&self.data_type);
let buffers = self.buffers(data_layout.can_contain_null_mask, data_layout.variadic)?;
let null_bit_buffer = if data_layout.can_contain_null_mask {
self.null_bit_buffer()
} else {
None
};
let mut child_data = self.consume_children()?;
if let Some(d) = self.dictionary()? {
// For dictionary type there should only be a single child, so we don't need to worry if
// there are other children added above.
assert!(child_data.is_empty());
child_data.push(d.consume()?);
}
// 8-byte alignment is legal over the C Data Interface but violates
// arrow-rs's stricter `ArrayData` alignment invariant, so realign the
// imported buffers *before* validating them. `align_buffers(true)`
// realigns and then `build` validates (or skips validation on the FFI
// hot path, except under `force_validate` which always validates). This
// ordering is what makes import work under `force_validate`; see #10034.
let mut builder = ArrayDataBuilder::new(self.data_type)
.len(len)
.offset(offset)
.null_bit_buffer(null_bit_buffer)
.buffers(buffers)
.child_data(child_data)
.align_buffers(true);
if let Some(null_count) = null_count {
builder = builder.null_count(null_count);
}
// SAFETY: `skip_validation` only skips the redundant FFI validation on
// the hot path; `align_buffers(true)` above guarantees the buffers meet
// arrow-rs's alignment invariant, and under `force_validate` `build`
// still runs full validation after realignment.
unsafe { builder.skip_validation(true) }.build()
}
fn consume_children(&self) -> Result<Vec<ArrayData>> {
match &self.data_type {
DataType::List(field)
| DataType::FixedSizeList(field, _)
| DataType::LargeList(field)
| DataType::ListView(field)
| DataType::LargeListView(field)
| DataType::Map(field, _) => Ok([self.consume_child(0, field.data_type())?].to_vec()),
DataType::Struct(fields) => {
assert!(fields.len() == self.array.num_children());
fields
.iter()
.enumerate()
.map(|(i, field)| self.consume_child(i, field.data_type()))
.collect::<Result<Vec<_>>>()
}
DataType::Union(union_fields, _) => {
assert!(union_fields.len() == self.array.num_children());
union_fields
.iter()
.enumerate()
.map(|(i, (_, field))| self.consume_child(i, field.data_type()))
.collect::<Result<Vec<_>>>()
}
DataType::RunEndEncoded(run_ends_field, values_field) => Ok([
self.consume_child(0, run_ends_field.data_type())?,
self.consume_child(1, values_field.data_type())?,
]
.to_vec()),
_ => Ok(Vec::new()),
}
}
fn consume_child(&self, index: usize, child_type: &DataType) -> Result<ArrayData> {
ImportedArrowArray {
array: self.array.child(index),
data_type: child_type.clone(),
owner: self.owner,
}
.consume()
}
/// returns all buffers, as organized by Rust (i.e. null buffer is skipped if it's present
/// in the spec of the type)
fn buffers(&self, can_contain_null_mask: bool, variadic: bool) -> Result<Vec<Buffer>> {
// + 1: skip null buffer
let buffer_begin = can_contain_null_mask as usize;
let buffer_end = self.array.num_buffers() - usize::from(variadic);
let variadic_buffer_lens = if variadic {
// Each views array has 1 (optional) null buffer, 1 views buffer, 1 lengths buffer.
// Rest are variadic.
let num_variadic_buffers =
self.array.num_buffers() - (2 + usize::from(can_contain_null_mask));
if num_variadic_buffers == 0 {
&[]
} else {
let lengths = self.array.buffer(self.array.num_buffers() - 1);
// SAFETY: is lengths is non-null, then it must be valid for up to num_variadic_buffers.
unsafe { std::slice::from_raw_parts(lengths.cast::<i64>(), num_variadic_buffers) }
}
} else {
&[]
};
(buffer_begin..buffer_end)
.map(|index| {
let len = self.buffer_len(index, variadic_buffer_lens, &self.data_type)?;
match unsafe { create_buffer(self.owner.clone(), self.array, index, len) } {
Some(buf) => {
// External libraries may use a dangling pointer for a buffer with length 0.
// We respect the array length specified in the C Data Interface. Actually,
// if the length is incorrect, we cannot create a correct buffer even if
// the pointer is valid.
if buf.is_empty() {
Ok(MutableBuffer::new(0).into())
} else {
Ok(buf)
}
}
None if len == 0 => {
// Null data buffer, which Rust doesn't allow. So create
// an empty buffer.
Ok(MutableBuffer::new(0).into())
}
None => Err(ArrowError::CDataInterface(format!(
"The external buffer at position {index} is null."
))),
}
})
.collect()
}
/// Returns the length, in bytes, of the buffer `i` (indexed according to the C data interface)
/// Rust implementation uses fixed-sized buffers, which require knowledge of their `len`.
/// for variable-sized buffers, such as the second buffer of a stringArray, we need
/// to fetch offset buffer's len to build the second buffer.
fn buffer_len(
&self,
i: usize,
variadic_buffer_lengths: &[i64],
dt: &DataType,
) -> Result<usize> {
// Special handling for dictionary type as we only care about the key type in the case.
let data_type = match dt {
DataType::Dictionary(key_data_type, _) => key_data_type.as_ref(),
dt => dt,
};
// `ffi::ArrowArray` records array offset, we need to add it back to the
// buffer length to get the actual buffer length.
let length = self.array.len() + self.array.offset();
// Inner type is not important for buffer length.
Ok(match (&data_type, i) {
(DataType::Utf8, 1)
| (DataType::LargeUtf8, 1)
| (DataType::Binary, 1)
| (DataType::LargeBinary, 1)
| (DataType::List(_), 1)
| (DataType::LargeList(_), 1)
| (DataType::Map(_, _), 1) => {
// the len of the offset buffer (buffer 1) equals length + 1
let bits = bit_width(data_type, i)?;
debug_assert_eq!(bits % 8, 0);
(length + 1) * (bits / 8)
}
(DataType::ListView(_), 1)
| (DataType::ListView(_), 2)
| (DataType::LargeListView(_), 1)
| (DataType::LargeListView(_), 2) => {
let bits = bit_width(data_type, i)?;
debug_assert_eq!(bits % 8, 0);
length * (bits / 8)
}
(DataType::Utf8, 2) | (DataType::Binary, 2) => {
if self.array.is_empty() {
return Ok(0);
}
// the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1)
let len = self.buffer_len(1, variadic_buffer_lengths, dt)?;
// first buffer is the null buffer => add(1)
// we assume that pointer is aligned for `i32`, as Utf8 uses `i32` offsets.
#[allow(clippy::cast_ptr_alignment)]
let offset_buffer = self.array.buffer(1) as *const i32;
// get last offset
(unsafe { *offset_buffer.add(len / size_of::<i32>() - 1) }) as usize
}
(DataType::LargeUtf8, 2) | (DataType::LargeBinary, 2) => {
if self.array.is_empty() {
return Ok(0);
}
// the len of the data buffer (buffer 2) equals the last value of the offset buffer (buffer 1)
let len = self.buffer_len(1, variadic_buffer_lengths, dt)?;
// first buffer is the null buffer => add(1)
// we assume that pointer is aligned for `i64`, as Large uses `i64` offsets.
#[allow(clippy::cast_ptr_alignment)]
let offset_buffer = self.array.buffer(1) as *const i64;
// get last offset
(unsafe { *offset_buffer.add(len / size_of::<i64>() - 1) }) as usize
}
// View types: these have variadic buffers.
// Buffer 1 is the views buffer, which stores 1 u128 per length of the array.
// Buffers 2..N-1 are the buffers holding the byte data. Their lengths are variable.
// Buffer N is of length (N - 2) and stores i64 containing the lengths of buffers 2..N-1
(DataType::Utf8View, 1) | (DataType::BinaryView, 1) => {
std::mem::size_of::<u128>() * length
}
(DataType::Utf8View, i) | (DataType::BinaryView, i) => {
variadic_buffer_lengths[i - 2] as usize
}
// buffer len of primitive types
_ => {
let bits = bit_width(data_type, i)?;
bit_util::ceil(length * bits, 8)
}
})
}
/// returns the null bit buffer.
/// Rust implementation uses a buffer that is not part of the array of buffers.
/// The C Data interface's null buffer is part of the array of buffers.
fn null_bit_buffer(&self) -> Option<Buffer> {
// similar to `self.buffer_len(0)`, but without `Result`.
// `ffi::ArrowArray` records array offset, we need to add it back to the
// buffer length to get the actual buffer length.
let length = self.array.len() + self.array.offset();
let buffer_len = bit_util::ceil(length, 8);
unsafe { create_buffer(self.owner.clone(), self.array, 0, buffer_len) }
}
fn dictionary(&self) -> Result<Option<ImportedArrowArray<'_>>> {
match (self.array.dictionary(), &self.data_type) {
(Some(array), DataType::Dictionary(_, value_type)) => Ok(Some(ImportedArrowArray {
array,
data_type: value_type.as_ref().clone(),
owner: self.owner,
})),
(Some(_), _) => Err(ArrowError::CDataInterface(
"Got dictionary in FFI_ArrowArray for non-dictionary data type".to_string(),
)),
(None, DataType::Dictionary(_, _)) => Err(ArrowError::CDataInterface(
"Missing dictionary in FFI_ArrowArray for dictionary data type".to_string(),
)),
(_, _) => Ok(None),
}
}
}
#[cfg(test)]
mod tests_to_then_from_ffi {
use std::collections::HashMap;
use std::mem::ManuallyDrop;
use arrow_buffer::{ArrowNativeType, NullBuffer};
use arrow_schema::Field;
use crate::builder::UnionBuilder;
use crate::cast::AsArray;
use crate::types::{Float64Type, Int8Type, Int32Type};
use crate::*;
use super::*;
#[test]
fn test_round_trip() {
// create an array natively
let array = Int32Array::from(vec![1, 2, 3]);
// export it
let (array, schema) = to_ffi(&array.into_data()).unwrap();
// (simulate consumer) import it
let array = Int32Array::from(unsafe { from_ffi(array, &schema) }.unwrap());
// verify
assert_eq!(array, Int32Array::from(vec![1, 2, 3]));
}
#[test]
fn test_import() {
// Model receiving const pointers from an external system
// Create an array natively
let data = Int32Array::from(vec![1, 2, 3]).into_data();
let schema = FFI_ArrowSchema::try_from(data.data_type()).unwrap();
let array = FFI_ArrowArray::new(&data);
// Use ManuallyDrop to avoid Box:Drop recursing
let schema = Box::new(ManuallyDrop::new(schema));
let array = Box::new(ManuallyDrop::new(array));
let schema_ptr = &**schema as *const _;
let array_ptr = &**array as *const _;
// We can read them back to memory
// SAFETY:
// Pointers are aligned and valid
let data =
unsafe { from_ffi(std::ptr::read(array_ptr), &std::ptr::read(schema_ptr)).unwrap() };
let array = Int32Array::from(data);
assert_eq!(array, Int32Array::from(vec![1, 2, 3]));
}
#[test]
fn test_round_trip_with_offset() -> Result<()> {
// create an array natively
let array = Int32Array::from(vec![Some(1), Some(2), None, Some(3), None]);
let array = array.slice(1, 2);
// export it
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
let array = array.as_any().downcast_ref::<Int32Array>().unwrap();
assert_eq!(array, &Int32Array::from(vec![Some(2), None]));
// (drop/release)
Ok(())
}
#[test]
#[cfg(not(feature = "force_validate"))]
fn test_decimal_round_trip() -> Result<()> {
// create an array natively
let original_array = [Some(12345_i128), Some(-12345_i128), None]
.into_iter()
.collect::<Decimal128Array>()
.with_precision_and_scale(6, 2)
.unwrap();
// export it
let (array, schema) = to_ffi(&original_array.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
let array = array.as_any().downcast_ref::<Decimal128Array>().unwrap();
// verify
assert_eq!(array, &original_array);
// (drop/release)
Ok(())
}
// case with nulls is tested in the docs, through the example on this module.
// Functional round-trip coverage of importing an under-aligned `Decimal128`
// buffer over the C Data Interface. NOTE: this is *not* the `force_validate`
// regression guard for #10034 — `arrow-array`'s `force_validate` feature is
// empty and does not forward to `arrow-data/force_validate`, so under
// `force_validate` this test does not actually reach `arrow-data`'s
// validation gate, and under default features the import succeeds even with
// an unfixed `consume` (the buffer still ends up realigned). The true
// CI-reachable regression guard lives in `arrow/tests/ffi_from_ffi.rs`,
// which runs under `cargo test -p arrow --features=force_validate,...,ffi`.
#[test]
fn test_decimal128_under_aligned_round_trip() -> Result<()> {
// Model an FFI producer that only guarantees the C Data Interface's
// recommended 8-byte alignment (e.g. arrow-java): an i128 data buffer
// that is 8-aligned but not 16-aligned.
let aligned = Buffer::from_vec(vec![0_i128, 1_i128, 2_i128]);
let under_aligned = aligned.slice(8);
assert_eq!(under_aligned.as_ptr().align_offset(8), 0);
assert_ne!(under_aligned.as_ptr().align_offset(16), 0);
// Export the under-aligned bytes as a `UInt8` array (alignment 1, so it
// is valid Arrow data even under `force_validate`), then re-import them
// as `Decimal128`. This reproduces an under-aligned `Decimal128` buffer
// arriving over the C Data Interface without first having to construct
// an (invalid) under-aligned `Decimal128` `ArrayData` on the producer
// side, which `force_validate` would reject before export. See #10034.
let producer = ArrayData::builder(DataType::UInt8)
.len(under_aligned.len())
.add_buffer(under_aligned)
.build()?;
let mut array = FFI_ArrowArray::new(&producer);
// Re-describe the exported 32 data bytes as 2 `Decimal128` elements.
// The data pointer (`buffers[1]`) is unchanged and still 8-aligned.
array.length = 2;
array.null_count = 0;
// SAFETY: the exported buffer holds 32 bytes = 2 little-endian i128
// values; reinterpreting it as `Decimal128(10, 2)` of length 2 matches.
let imported = unsafe { from_ffi_and_data_type(array, DataType::Decimal128(10, 2)) }?;
// Import must realign the under-aligned buffer to satisfy arrow-rs's
// 16-byte `i128` alignment invariant, regardless of `force_validate`.
assert_eq!(imported.buffers()[0].as_ptr().align_offset(16), 0);
let array = Decimal128Array::from(imported);
// The little-endian byte layout of [0i128, 1, 2] sliced 8 bytes in
// yields elements `1 << 64` and `2 << 64`.
assert_eq!(array.len(), 2);
assert_eq!(array.value(0), 1_i128 << 64);
assert_eq!(array.value(1), 2_i128 << 64);
Ok(())
}
#[test]
fn test_null_count_handling() {
let int32_data = ArrayData::builder(DataType::Int32)
.len(10)
.add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
.null_bit_buffer(Some(Buffer::from([0b01011111, 0b00000001])))
.build()
.unwrap();
let mut ffi_array = FFI_ArrowArray::new(&int32_data);
assert_eq!(3, ffi_array.null_count());
assert_eq!(Some(3), ffi_array.null_count_opt());
// Simulating uninitialized state
unsafe {
ffi_array.set_null_count(-1);
}
assert_eq!(None, ffi_array.null_count_opt());
let int32_data = unsafe { from_ffi_and_data_type(ffi_array, DataType::Int32) }.unwrap();
assert_eq!(3, int32_data.null_count());
let null_data = &ArrayData::new_null(&DataType::Null, 10);
let mut ffi_array = FFI_ArrowArray::new(null_data);
assert_eq!(10, ffi_array.null_count());
assert_eq!(Some(10), ffi_array.null_count_opt());
// Simulating uninitialized state
unsafe {
ffi_array.set_null_count(-1);
}
assert_eq!(None, ffi_array.null_count_opt());
let null_data = unsafe { from_ffi_and_data_type(ffi_array, DataType::Null) }.unwrap();
assert_eq!(0, null_data.null_count());
}
fn test_generic_string<Offset: OffsetSizeTrait>() -> Result<()> {
// create an array natively
let array = GenericStringArray::<Offset>::from(vec![Some("a"), None, Some("aaa")]);
// export it
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// perform some operation
let array = array
.as_any()
.downcast_ref::<GenericStringArray<Offset>>()
.unwrap();
// verify
let expected = GenericStringArray::<Offset>::from(vec![Some("a"), None, Some("aaa")]);
assert_eq!(array, &expected);
// (drop/release)
Ok(())
}
#[test]
fn test_string() -> Result<()> {
test_generic_string::<i32>()
}
#[test]
fn test_large_string() -> Result<()> {
test_generic_string::<i64>()
}
fn test_generic_list<Offset: OffsetSizeTrait>() -> Result<()> {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from_slice_ref([0, 1, 2, 3, 4, 5, 6, 7]))
.build()
.unwrap();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
let value_offsets = [0_usize, 3, 6, 8]
.iter()
.map(|i| Offset::from_usize(*i).unwrap())
.collect::<Buffer>();
// Construct a list array from the above two
let list_data_type = GenericListArray::<Offset>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new_list_field(DataType::Int32, false),
));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
.add_child_data(value_data)
.build()
.unwrap();
// create an array natively
let array = GenericListArray::<Offset>::from(list_data.clone());
// export it
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// downcast
let array = array
.as_any()
.downcast_ref::<GenericListArray<Offset>>()
.unwrap();
// verify
let expected = GenericListArray::<Offset>::from(list_data);
assert_eq!(&array.value(0), &expected.value(0));
assert_eq!(&array.value(1), &expected.value(1));
assert_eq!(&array.value(2), &expected.value(2));
// (drop/release)
Ok(())
}
#[test]
fn test_list() -> Result<()> {
test_generic_list::<i32>()
}
#[test]
fn test_large_list() -> Result<()> {
test_generic_list::<i64>()
}
fn test_generic_list_view<Offset: OffsetSizeTrait + ArrowNativeType>() -> Result<()> {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int16)
.len(8)
.add_buffer(Buffer::from_slice_ref([0_i16, 1, 2, 3, 4, 5, 6, 7]))
.build()
.unwrap();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
let value_offsets = [0_usize, 3, 6]
.iter()
.map(|i| Offset::from_usize(*i).unwrap())
.collect::<Buffer>();
let sizes_buffer = [3_usize, 3, 2]
.iter()
.map(|i| Offset::from_usize(*i).unwrap())
.collect::<Buffer>();
// Construct a list array from the above two
let list_view_dt = GenericListViewArray::<Offset>::DATA_TYPE_CONSTRUCTOR(Arc::new(
Field::new_list_field(DataType::Int16, false),
));
let list_data = ArrayData::builder(list_view_dt)
.len(3)
.add_buffer(value_offsets)
.add_buffer(sizes_buffer)
.add_child_data(value_data)
.build()
.unwrap();
let original = GenericListViewArray::<Offset>::from(list_data.clone());
// export it
let (array, schema) = to_ffi(&original.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
// downcast
let array = array
.as_any()
.downcast_ref::<GenericListViewArray<Offset>>()
.unwrap();
assert_eq!(&array.value(0), &original.value(0));
assert_eq!(&array.value(1), &original.value(1));
assert_eq!(&array.value(2), &original.value(2));
Ok(())
}
#[test]
fn test_list_view() -> Result<()> {
test_generic_list_view::<i32>()
}
#[test]
fn test_large_list_view() -> Result<()> {
test_generic_list_view::<i64>()
}
fn test_generic_binary<Offset: OffsetSizeTrait>() -> Result<()> {
// create an array natively
let array: Vec<Option<&[u8]>> = vec![Some(b"a"), None, Some(b"aaa")];
let array = GenericBinaryArray::<Offset>::from(array);
// export it
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
let array = array
.as_any()
.downcast_ref::<GenericBinaryArray<Offset>>()
.unwrap();
// verify
let expected: Vec<Option<&[u8]>> = vec![Some(b"a"), None, Some(b"aaa")];
let expected = GenericBinaryArray::<Offset>::from(expected);
assert_eq!(array, &expected);
// (drop/release)
Ok(())
}
#[test]
fn test_binary() -> Result<()> {
test_generic_binary::<i32>()
}
#[test]
fn test_large_binary() -> Result<()> {
test_generic_binary::<i64>()
}
#[test]
fn test_bool() -> Result<()> {
// create an array natively
let array = BooleanArray::from(vec![None, Some(true), Some(false)]);
// export it
let (array, schema) = to_ffi(&array.to_data())?;
// (simulate consumer) import it
let data = unsafe { from_ffi(array, &schema) }?;
let array = make_array(data);
let array = array.as_any().downcast_ref::<BooleanArray>().unwrap();
// verify
assert_eq!(
array,
&BooleanArray::from(vec![None, Some(true), Some(false)])
);
// (drop/release)
Ok(())
}
#[test]
fn test_time32() -> Result<()> {
// create an array natively
let array = Time32MillisecondArray::from(vec![None, Some(1), Some(2)]);
// export it
let (array, schema) = to_ffi(&array.to_data())?;