-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
bridge.cc
1862 lines (1603 loc) · 58.1 KB
/
bridge.cc
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.
#include "arrow/c/bridge.h"
#include <algorithm>
#include <cerrno>
#include <cstring>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/c/helpers.h"
#include "arrow/c/util_internal.h"
#include "arrow/extension_type.h"
#include "arrow/memory_pool.h"
#include "arrow/memory_pool_internal.h" // for kZeroSizeArea
#include "arrow/record_batch.h"
#include "arrow/result.h"
#include "arrow/stl_allocator.h"
#include "arrow/type_traits.h"
#include "arrow/util/bit_util.h"
#include "arrow/util/checked_cast.h"
#include "arrow/util/key_value_metadata.h"
#include "arrow/util/logging.h"
#include "arrow/util/macros.h"
#include "arrow/util/small_vector.h"
#include "arrow/util/string.h"
#include "arrow/util/value_parsing.h"
#include "arrow/visit_type_inline.h"
namespace arrow {
using internal::checked_cast;
using internal::checked_pointer_cast;
using internal::SmallVector;
using internal::StaticVector;
using internal::ArrayExportGuard;
using internal::ArrayExportTraits;
using internal::SchemaExportGuard;
using internal::SchemaExportTraits;
using internal::ToChars;
using memory_pool::internal::kZeroSizeArea;
namespace {
Status ExportingNotImplemented(const DataType& type) {
return Status::NotImplemented("Exporting ", type.ToString(), " array not supported");
}
// Allocate exported private data using MemoryPool,
// to allow accounting memory and checking for memory leaks.
// XXX use Gandiva's SimpleArena?
template <typename Derived>
struct PoolAllocationMixin {
static void* operator new(size_t size) {
DCHECK_EQ(size, sizeof(Derived));
uint8_t* data;
ARROW_CHECK_OK(default_memory_pool()->Allocate(static_cast<int64_t>(size), &data));
return data;
}
static void operator delete(void* ptr) {
default_memory_pool()->Free(reinterpret_cast<uint8_t*>(ptr), sizeof(Derived));
}
};
//////////////////////////////////////////////////////////////////////////
// C schema export
struct ExportedSchemaPrivateData : PoolAllocationMixin<ExportedSchemaPrivateData> {
std::string format_;
std::string name_;
std::string metadata_;
struct ArrowSchema dictionary_;
SmallVector<struct ArrowSchema, 1> children_;
SmallVector<struct ArrowSchema*, 4> child_pointers_;
ExportedSchemaPrivateData() = default;
ARROW_DEFAULT_MOVE_AND_ASSIGN(ExportedSchemaPrivateData);
ARROW_DISALLOW_COPY_AND_ASSIGN(ExportedSchemaPrivateData);
};
void ReleaseExportedSchema(struct ArrowSchema* schema) {
if (ArrowSchemaIsReleased(schema)) {
return;
}
for (int64_t i = 0; i < schema->n_children; ++i) {
struct ArrowSchema* child = schema->children[i];
ArrowSchemaRelease(child);
DCHECK(ArrowSchemaIsReleased(child))
<< "Child release callback should have marked it released";
}
struct ArrowSchema* dict = schema->dictionary;
if (dict != nullptr) {
ArrowSchemaRelease(dict);
DCHECK(ArrowSchemaIsReleased(dict))
<< "Dictionary release callback should have marked it released";
}
DCHECK_NE(schema->private_data, nullptr);
delete reinterpret_cast<ExportedSchemaPrivateData*>(schema->private_data);
ArrowSchemaMarkReleased(schema);
}
template <typename SizeType>
Result<int32_t> DowncastMetadataSize(SizeType size) {
auto res = static_cast<int32_t>(size);
if (res < 0 || static_cast<SizeType>(res) != size) {
return Status::Invalid("Metadata too large (more than 2**31 items or bytes)");
}
return res;
}
Result<std::string> EncodeMetadata(const KeyValueMetadata& metadata) {
ARROW_ASSIGN_OR_RAISE(auto npairs, DowncastMetadataSize(metadata.size()));
std::string exported;
// Pre-compute total string size
size_t total_size = 4;
for (int32_t i = 0; i < npairs; ++i) {
total_size += 8 + metadata.key(i).length() + metadata.value(i).length();
}
exported.resize(total_size);
char* data_start = &exported[0];
char* data = data_start;
auto write_int32 = [&](int32_t v) -> void {
memcpy(data, &v, 4);
data += 4;
};
auto write_string = [&](const std::string& s) -> Status {
ARROW_ASSIGN_OR_RAISE(auto len, DowncastMetadataSize(s.length()));
write_int32(len);
if (len > 0) {
memcpy(data, s.data(), len);
data += len;
}
return Status::OK();
};
write_int32(npairs);
for (int32_t i = 0; i < npairs; ++i) {
RETURN_NOT_OK(write_string(metadata.key(i)));
RETURN_NOT_OK(write_string(metadata.value(i)));
}
DCHECK_EQ(static_cast<size_t>(data - data_start), total_size);
return exported;
}
struct SchemaExporter {
Status ExportField(const Field& field) {
export_.name_ = field.name();
flags_ = field.nullable() ? ARROW_FLAG_NULLABLE : 0;
const DataType* type = UnwrapExtension(field.type().get());
RETURN_NOT_OK(ExportFormat(*type));
RETURN_NOT_OK(ExportChildren(type->fields()));
RETURN_NOT_OK(ExportMetadata(field.metadata().get()));
return Status::OK();
}
Status ExportType(const DataType& orig_type) {
flags_ = ARROW_FLAG_NULLABLE;
const DataType* type = UnwrapExtension(&orig_type);
RETURN_NOT_OK(ExportFormat(*type));
RETURN_NOT_OK(ExportChildren(type->fields()));
// There may be additional metadata to export
RETURN_NOT_OK(ExportMetadata(nullptr));
return Status::OK();
}
Status ExportSchema(const Schema& schema) {
static const StructType dummy_struct_type({});
flags_ = 0;
RETURN_NOT_OK(ExportFormat(dummy_struct_type));
RETURN_NOT_OK(ExportChildren(schema.fields()));
RETURN_NOT_OK(ExportMetadata(schema.metadata().get()));
return Status::OK();
}
// Finalize exporting by setting C struct fields and allocating
// autonomous private data for each schema node.
//
// This function can't fail, as properly reclaiming memory in case of error
// would be too fragile. After this function returns, memory is reclaimed
// by calling the release() pointer in the top level ArrowSchema struct.
void Finish(struct ArrowSchema* c_struct) {
// First, create permanent ExportedSchemaPrivateData
auto pdata = new ExportedSchemaPrivateData(std::move(export_));
// Second, finish dictionary and children.
if (dict_exporter_) {
dict_exporter_->Finish(&pdata->dictionary_);
}
pdata->child_pointers_.resize(child_exporters_.size(), nullptr);
for (size_t i = 0; i < child_exporters_.size(); ++i) {
auto ptr = pdata->child_pointers_[i] = &pdata->children_[i];
child_exporters_[i].Finish(ptr);
}
// Third, fill C struct.
DCHECK_NE(c_struct, nullptr);
memset(c_struct, 0, sizeof(*c_struct));
c_struct->format = pdata->format_.c_str();
c_struct->name = pdata->name_.c_str();
c_struct->metadata = pdata->metadata_.empty() ? nullptr : pdata->metadata_.c_str();
c_struct->flags = flags_;
c_struct->n_children = static_cast<int64_t>(child_exporters_.size());
c_struct->children = c_struct->n_children ? pdata->child_pointers_.data() : nullptr;
c_struct->dictionary = dict_exporter_ ? &pdata->dictionary_ : nullptr;
c_struct->private_data = pdata;
c_struct->release = ReleaseExportedSchema;
}
const DataType* UnwrapExtension(const DataType* type) {
if (type->id() == Type::EXTENSION) {
const auto& ext_type = checked_cast<const ExtensionType&>(*type);
additional_metadata_.reserve(2);
additional_metadata_.emplace_back(kExtensionTypeKeyName, ext_type.extension_name());
additional_metadata_.emplace_back(kExtensionMetadataKeyName, ext_type.Serialize());
return ext_type.storage_type().get();
}
return type;
}
Status ExportFormat(const DataType& type) {
if (type.id() == Type::DICTIONARY) {
const auto& dict_type = checked_cast<const DictionaryType&>(type);
if (dict_type.ordered()) {
flags_ |= ARROW_FLAG_DICTIONARY_ORDERED;
}
// Dictionary type: parent struct describes index type,
// child dictionary struct describes value type.
RETURN_NOT_OK(VisitTypeInline(*dict_type.index_type(), this));
dict_exporter_.reset(new SchemaExporter());
RETURN_NOT_OK(dict_exporter_->ExportType(*dict_type.value_type()));
} else {
RETURN_NOT_OK(VisitTypeInline(type, this));
}
DCHECK(!export_.format_.empty());
return Status::OK();
}
Status ExportChildren(const std::vector<std::shared_ptr<Field>>& fields) {
export_.children_.resize(fields.size());
child_exporters_.resize(fields.size());
for (size_t i = 0; i < fields.size(); ++i) {
RETURN_NOT_OK(child_exporters_[i].ExportField(*fields[i]));
}
return Status::OK();
}
Status ExportMetadata(const KeyValueMetadata* orig_metadata) {
static const KeyValueMetadata empty_metadata;
if (orig_metadata == nullptr) {
orig_metadata = &empty_metadata;
}
if (additional_metadata_.empty()) {
if (orig_metadata->size() > 0) {
ARROW_ASSIGN_OR_RAISE(export_.metadata_, EncodeMetadata(*orig_metadata));
}
return Status::OK();
}
// Additional metadata needs to be appended to the existing
// (for extension types)
KeyValueMetadata metadata(orig_metadata->keys(), orig_metadata->values());
for (const auto& kv : additional_metadata_) {
// The metadata may already be there => ignore
if (metadata.Contains(kv.first)) {
continue;
}
metadata.Append(kv.first, kv.second);
}
ARROW_ASSIGN_OR_RAISE(export_.metadata_, EncodeMetadata(metadata));
return Status::OK();
}
Status SetFormat(std::string s) {
export_.format_ = std::move(s);
return Status::OK();
}
// Type-specific visitors
Status Visit(const DataType& type) { return ExportingNotImplemented(type); }
Status Visit(const NullType& type) { return SetFormat("n"); }
Status Visit(const BooleanType& type) { return SetFormat("b"); }
Status Visit(const Int8Type& type) { return SetFormat("c"); }
Status Visit(const UInt8Type& type) { return SetFormat("C"); }
Status Visit(const Int16Type& type) { return SetFormat("s"); }
Status Visit(const UInt16Type& type) { return SetFormat("S"); }
Status Visit(const Int32Type& type) { return SetFormat("i"); }
Status Visit(const UInt32Type& type) { return SetFormat("I"); }
Status Visit(const Int64Type& type) { return SetFormat("l"); }
Status Visit(const UInt64Type& type) { return SetFormat("L"); }
Status Visit(const HalfFloatType& type) { return SetFormat("e"); }
Status Visit(const FloatType& type) { return SetFormat("f"); }
Status Visit(const DoubleType& type) { return SetFormat("g"); }
Status Visit(const FixedSizeBinaryType& type) {
return SetFormat("w:" + ToChars(type.byte_width()));
}
Status Visit(const DecimalType& type) {
if (type.bit_width() == 128) {
// 128 is the default bit-width
return SetFormat("d:" + ToChars(type.precision()) + "," + ToChars(type.scale()));
} else {
return SetFormat("d:" + ToChars(type.precision()) + "," + ToChars(type.scale()) +
"," + ToChars(type.bit_width()));
}
}
Status Visit(const BinaryType& type) { return SetFormat("z"); }
Status Visit(const LargeBinaryType& type) { return SetFormat("Z"); }
Status Visit(const StringType& type) { return SetFormat("u"); }
Status Visit(const LargeStringType& type) { return SetFormat("U"); }
Status Visit(const Date32Type& type) { return SetFormat("tdD"); }
Status Visit(const Date64Type& type) { return SetFormat("tdm"); }
Status Visit(const Time32Type& type) {
switch (type.unit()) {
case TimeUnit::SECOND:
export_.format_ = "tts";
break;
case TimeUnit::MILLI:
export_.format_ = "ttm";
break;
default:
return Status::Invalid("Invalid time unit for Time32: ", type.unit());
}
return Status::OK();
}
Status Visit(const Time64Type& type) {
switch (type.unit()) {
case TimeUnit::MICRO:
export_.format_ = "ttu";
break;
case TimeUnit::NANO:
export_.format_ = "ttn";
break;
default:
return Status::Invalid("Invalid time unit for Time64: ", type.unit());
}
return Status::OK();
}
Status Visit(const TimestampType& type) {
switch (type.unit()) {
case TimeUnit::SECOND:
export_.format_ = "tss:";
break;
case TimeUnit::MILLI:
export_.format_ = "tsm:";
break;
case TimeUnit::MICRO:
export_.format_ = "tsu:";
break;
case TimeUnit::NANO:
export_.format_ = "tsn:";
break;
default:
return Status::Invalid("Invalid time unit for Timestamp: ", type.unit());
}
export_.format_ += type.timezone();
return Status::OK();
}
Status Visit(const DurationType& type) {
switch (type.unit()) {
case TimeUnit::SECOND:
export_.format_ = "tDs";
break;
case TimeUnit::MILLI:
export_.format_ = "tDm";
break;
case TimeUnit::MICRO:
export_.format_ = "tDu";
break;
case TimeUnit::NANO:
export_.format_ = "tDn";
break;
default:
return Status::Invalid("Invalid time unit for Duration: ", type.unit());
}
return Status::OK();
}
Status Visit(const MonthIntervalType& type) { return SetFormat("tiM"); }
Status Visit(const DayTimeIntervalType& type) { return SetFormat("tiD"); }
Status Visit(const MonthDayNanoIntervalType& type) { return SetFormat("tin"); }
Status Visit(const ListType& type) { return SetFormat("+l"); }
Status Visit(const LargeListType& type) { return SetFormat("+L"); }
Status Visit(const FixedSizeListType& type) {
return SetFormat("+w:" + ToChars(type.list_size()));
}
Status Visit(const StructType& type) { return SetFormat("+s"); }
Status Visit(const MapType& type) {
export_.format_ = "+m";
if (type.keys_sorted()) {
flags_ |= ARROW_FLAG_MAP_KEYS_SORTED;
}
return Status::OK();
}
Status Visit(const UnionType& type) {
std::string& s = export_.format_;
s = "+u";
if (type.mode() == UnionMode::DENSE) {
s += "d:";
} else {
DCHECK_EQ(type.mode(), UnionMode::SPARSE);
s += "s:";
}
bool first = true;
for (const auto code : type.type_codes()) {
if (!first) {
s += ",";
}
s += ToChars(code);
first = false;
}
return Status::OK();
}
ExportedSchemaPrivateData export_;
int64_t flags_ = 0;
std::vector<std::pair<std::string, std::string>> additional_metadata_;
std::unique_ptr<SchemaExporter> dict_exporter_;
std::vector<SchemaExporter> child_exporters_;
};
} // namespace
Status ExportType(const DataType& type, struct ArrowSchema* out) {
SchemaExporter exporter;
RETURN_NOT_OK(exporter.ExportType(type));
exporter.Finish(out);
return Status::OK();
}
Status ExportField(const Field& field, struct ArrowSchema* out) {
SchemaExporter exporter;
RETURN_NOT_OK(exporter.ExportField(field));
exporter.Finish(out);
return Status::OK();
}
Status ExportSchema(const Schema& schema, struct ArrowSchema* out) {
SchemaExporter exporter;
RETURN_NOT_OK(exporter.ExportSchema(schema));
exporter.Finish(out);
return Status::OK();
}
//////////////////////////////////////////////////////////////////////////
// C data export
namespace {
struct ExportedArrayPrivateData : PoolAllocationMixin<ExportedArrayPrivateData> {
// The buffers are owned by the ArrayData member
StaticVector<const void*, 3> buffers_;
struct ArrowArray dictionary_;
SmallVector<struct ArrowArray, 1> children_;
SmallVector<struct ArrowArray*, 4> child_pointers_;
std::shared_ptr<ArrayData> data_;
ExportedArrayPrivateData() = default;
ARROW_DEFAULT_MOVE_AND_ASSIGN(ExportedArrayPrivateData);
ARROW_DISALLOW_COPY_AND_ASSIGN(ExportedArrayPrivateData);
};
void ReleaseExportedArray(struct ArrowArray* array) {
if (ArrowArrayIsReleased(array)) {
return;
}
for (int64_t i = 0; i < array->n_children; ++i) {
struct ArrowArray* child = array->children[i];
ArrowArrayRelease(child);
DCHECK(ArrowArrayIsReleased(child))
<< "Child release callback should have marked it released";
}
struct ArrowArray* dict = array->dictionary;
if (dict != nullptr) {
ArrowArrayRelease(dict);
DCHECK(ArrowArrayIsReleased(dict))
<< "Dictionary release callback should have marked it released";
}
DCHECK_NE(array->private_data, nullptr);
delete reinterpret_cast<ExportedArrayPrivateData*>(array->private_data);
ArrowArrayMarkReleased(array);
}
struct ArrayExporter {
Status Export(const std::shared_ptr<ArrayData>& data) {
// Force computing null count.
// This is because ARROW-9037 is in version 0.17 and 0.17.1, and they are
// not able to import arrays without a null bitmap and null_count == -1.
data->GetNullCount();
// Store buffer pointers
size_t n_buffers = data->buffers.size();
auto buffers_begin = data->buffers.begin();
if (n_buffers > 0 && !internal::HasValidityBitmap(data->type->id())) {
--n_buffers;
++buffers_begin;
}
export_.buffers_.resize(n_buffers);
std::transform(buffers_begin, data->buffers.end(), export_.buffers_.begin(),
[](const std::shared_ptr<Buffer>& buffer) -> const void* {
return buffer ? buffer->data() : nullptr;
});
// Export dictionary
if (data->dictionary != nullptr) {
dict_exporter_.reset(new ArrayExporter());
RETURN_NOT_OK(dict_exporter_->Export(data->dictionary));
}
// Export children
export_.children_.resize(data->child_data.size());
child_exporters_.resize(data->child_data.size());
for (size_t i = 0; i < data->child_data.size(); ++i) {
RETURN_NOT_OK(child_exporters_[i].Export(data->child_data[i]));
}
// Store owning pointer to ArrayData
export_.data_ = data;
return Status::OK();
}
// Finalize exporting by setting C struct fields and allocating
// autonomous private data for each array node.
//
// This function can't fail, as properly reclaiming memory in case of error
// would be too fragile. After this function returns, memory is reclaimed
// by calling the release() pointer in the top level ArrowArray struct.
void Finish(struct ArrowArray* c_struct_) {
// First, create permanent ExportedArrayPrivateData, to make sure that
// child ArrayData pointers don't get invalidated.
auto pdata = new ExportedArrayPrivateData(std::move(export_));
const ArrayData& data = *pdata->data_;
// Second, finish dictionary and children.
if (dict_exporter_) {
dict_exporter_->Finish(&pdata->dictionary_);
}
pdata->child_pointers_.resize(data.child_data.size(), nullptr);
for (size_t i = 0; i < data.child_data.size(); ++i) {
auto ptr = &pdata->children_[i];
pdata->child_pointers_[i] = ptr;
child_exporters_[i].Finish(ptr);
}
// Third, fill C struct.
DCHECK_NE(c_struct_, nullptr);
memset(c_struct_, 0, sizeof(*c_struct_));
c_struct_->length = data.length;
c_struct_->null_count = data.null_count;
c_struct_->offset = data.offset;
c_struct_->n_buffers = static_cast<int64_t>(pdata->buffers_.size());
c_struct_->n_children = static_cast<int64_t>(pdata->child_pointers_.size());
c_struct_->buffers = pdata->buffers_.data();
c_struct_->children = c_struct_->n_children ? pdata->child_pointers_.data() : nullptr;
c_struct_->dictionary = dict_exporter_ ? &pdata->dictionary_ : nullptr;
c_struct_->private_data = pdata;
c_struct_->release = ReleaseExportedArray;
}
ExportedArrayPrivateData export_;
std::unique_ptr<ArrayExporter> dict_exporter_;
std::vector<ArrayExporter> child_exporters_;
};
} // namespace
Status ExportArray(const Array& array, struct ArrowArray* out,
struct ArrowSchema* out_schema) {
SchemaExportGuard guard(out_schema);
if (out_schema != nullptr) {
RETURN_NOT_OK(ExportType(*array.type(), out_schema));
}
ArrayExporter exporter;
RETURN_NOT_OK(exporter.Export(array.data()));
exporter.Finish(out);
guard.Detach();
return Status::OK();
}
Status ExportRecordBatch(const RecordBatch& batch, struct ArrowArray* out,
struct ArrowSchema* out_schema) {
// XXX perhaps bypass ToStructArray() for speed?
ARROW_ASSIGN_OR_RAISE(auto array, batch.ToStructArray());
SchemaExportGuard guard(out_schema);
if (out_schema != nullptr) {
// Export the schema, not the struct type, so as not to lose top-level metadata
RETURN_NOT_OK(ExportSchema(*batch.schema(), out_schema));
}
ArrayExporter exporter;
RETURN_NOT_OK(exporter.Export(array->data()));
exporter.Finish(out);
guard.Detach();
return Status::OK();
}
//////////////////////////////////////////////////////////////////////////
// C schema import
namespace {
static constexpr int64_t kMaxImportRecursionLevel = 64;
Status InvalidFormatString(std::string_view v) {
return Status::Invalid("Invalid or unsupported format string: '", v, "'");
}
class FormatStringParser {
public:
FormatStringParser() {}
explicit FormatStringParser(std::string_view v) : view_(v), index_(0) {}
bool AtEnd() const { return index_ >= view_.length(); }
char Next() { return view_[index_++]; }
std::string_view Rest() { return view_.substr(index_); }
Status CheckNext(char c) {
if (AtEnd() || Next() != c) {
return Invalid();
}
return Status::OK();
}
Status CheckHasNext() {
if (AtEnd()) {
return Invalid();
}
return Status::OK();
}
Status CheckAtEnd() {
if (!AtEnd()) {
return Invalid();
}
return Status::OK();
}
template <typename IntType = int32_t>
Result<IntType> ParseInt(std::string_view v) {
using ArrowIntType = typename CTypeTraits<IntType>::ArrowType;
IntType value;
if (!internal::ParseValue<ArrowIntType>(v.data(), v.size(), &value)) {
return Invalid();
}
return value;
}
Result<TimeUnit::type> ParseTimeUnit() {
RETURN_NOT_OK(CheckHasNext());
switch (Next()) {
case 's':
return TimeUnit::SECOND;
case 'm':
return TimeUnit::MILLI;
case 'u':
return TimeUnit::MICRO;
case 'n':
return TimeUnit::NANO;
default:
return Invalid();
}
}
SmallVector<std::string_view, 2> Split(std::string_view v, char delim = ',') {
SmallVector<std::string_view, 2> parts;
size_t start = 0, end;
while (true) {
end = v.find_first_of(delim, start);
parts.push_back(v.substr(start, end - start));
if (end == std::string_view::npos) {
break;
}
start = end + 1;
}
return parts;
}
template <typename IntType = int32_t>
Result<std::vector<IntType>> ParseInts(std::string_view v) {
std::vector<IntType> result;
if (v.empty()) return result;
auto parts = Split(v);
result.reserve(parts.size());
for (const auto& p : parts) {
ARROW_ASSIGN_OR_RAISE(auto i, ParseInt<IntType>(p));
result.push_back(i);
}
return result;
}
Status Invalid() { return InvalidFormatString(view_); }
protected:
std::string_view view_;
size_t index_;
};
struct DecodedMetadata {
std::shared_ptr<KeyValueMetadata> metadata;
std::string extension_name;
std::string extension_serialized;
};
Result<DecodedMetadata> DecodeMetadata(const char* metadata) {
auto read_int32 = [&](int32_t* out) -> Status {
int32_t v;
memcpy(&v, metadata, 4);
metadata += 4;
*out = v;
if (*out < 0) {
return Status::Invalid("Invalid encoded metadata string");
}
return Status::OK();
};
auto read_string = [&](std::string* out) -> Status {
int32_t len;
RETURN_NOT_OK(read_int32(&len));
out->resize(len);
if (len > 0) {
memcpy(&(*out)[0], metadata, len);
metadata += len;
}
return Status::OK();
};
DecodedMetadata decoded;
if (metadata == nullptr) {
return decoded;
}
int32_t npairs;
RETURN_NOT_OK(read_int32(&npairs));
if (npairs == 0) {
return decoded;
}
std::vector<std::string> keys(npairs);
std::vector<std::string> values(npairs);
for (int32_t i = 0; i < npairs; ++i) {
RETURN_NOT_OK(read_string(&keys[i]));
RETURN_NOT_OK(read_string(&values[i]));
if (keys[i] == kExtensionTypeKeyName) {
decoded.extension_name = values[i];
} else if (keys[i] == kExtensionMetadataKeyName) {
decoded.extension_serialized = values[i];
}
}
decoded.metadata = key_value_metadata(std::move(keys), std::move(values));
return decoded;
}
struct SchemaImporter {
SchemaImporter() : c_struct_(nullptr), guard_(nullptr) {}
Status Import(struct ArrowSchema* src) {
if (ArrowSchemaIsReleased(src)) {
return Status::Invalid("Cannot import released ArrowSchema");
}
guard_.Reset(src);
recursion_level_ = 0;
c_struct_ = src;
return DoImport();
}
Result<std::shared_ptr<Field>> MakeField() const {
const char* name = c_struct_->name ? c_struct_->name : "";
bool nullable = (c_struct_->flags & ARROW_FLAG_NULLABLE) != 0;
return field(name, type_, nullable, std::move(metadata_.metadata));
}
Result<std::shared_ptr<Schema>> MakeSchema() const {
if (type_->id() != Type::STRUCT) {
return Status::Invalid(
"Cannot import schema: ArrowSchema describes non-struct type ",
type_->ToString());
}
return schema(type_->fields(), std::move(metadata_.metadata));
}
Result<std::shared_ptr<DataType>> MakeType() const { return type_; }
protected:
Status ImportChild(const SchemaImporter* parent, struct ArrowSchema* src) {
if (ArrowSchemaIsReleased(src)) {
return Status::Invalid("Cannot import released ArrowSchema");
}
recursion_level_ = parent->recursion_level_ + 1;
if (recursion_level_ >= kMaxImportRecursionLevel) {
return Status::Invalid("Recursion level in ArrowSchema struct exceeded");
}
// The ArrowSchema is owned by its parent, so don't release it ourselves
c_struct_ = src;
return DoImport();
}
Status ImportDict(const SchemaImporter* parent, struct ArrowSchema* src) {
return ImportChild(parent, src);
}
Status DoImport() {
// First import children (required for reconstituting parent type)
child_importers_.resize(c_struct_->n_children);
for (int64_t i = 0; i < c_struct_->n_children; ++i) {
DCHECK_NE(c_struct_->children[i], nullptr);
RETURN_NOT_OK(child_importers_[i].ImportChild(this, c_struct_->children[i]));
}
// Import main type
RETURN_NOT_OK(ProcessFormat());
DCHECK_NE(type_, nullptr);
// Import dictionary type
if (c_struct_->dictionary != nullptr) {
// Check this index type
if (!is_integer(type_->id())) {
return Status::Invalid(
"ArrowSchema struct has a dictionary but is not an integer type: ",
type_->ToString());
}
SchemaImporter dict_importer;
RETURN_NOT_OK(dict_importer.ImportDict(this, c_struct_->dictionary));
bool ordered = (c_struct_->flags & ARROW_FLAG_DICTIONARY_ORDERED) != 0;
type_ = dictionary(type_, dict_importer.type_, ordered);
}
// Import metadata
ARROW_ASSIGN_OR_RAISE(metadata_, DecodeMetadata(c_struct_->metadata));
// Detect extension type
if (!metadata_.extension_name.empty()) {
const auto registered_ext_type = GetExtensionType(metadata_.extension_name);
if (registered_ext_type) {
ARROW_ASSIGN_OR_RAISE(
type_, registered_ext_type->Deserialize(std::move(type_),
metadata_.extension_serialized));
}
}
return Status::OK();
}
Status ProcessFormat() {
f_parser_ = FormatStringParser(c_struct_->format);
RETURN_NOT_OK(f_parser_.CheckHasNext());
switch (f_parser_.Next()) {
case 'n':
return ProcessPrimitive(null());
case 'b':
return ProcessPrimitive(boolean());
case 'c':
return ProcessPrimitive(int8());
case 'C':
return ProcessPrimitive(uint8());
case 's':
return ProcessPrimitive(int16());
case 'S':
return ProcessPrimitive(uint16());
case 'i':
return ProcessPrimitive(int32());
case 'I':
return ProcessPrimitive(uint32());
case 'l':
return ProcessPrimitive(int64());
case 'L':
return ProcessPrimitive(uint64());
case 'e':
return ProcessPrimitive(float16());
case 'f':
return ProcessPrimitive(float32());
case 'g':
return ProcessPrimitive(float64());
case 'u':
return ProcessPrimitive(utf8());
case 'U':
return ProcessPrimitive(large_utf8());
case 'z':
return ProcessPrimitive(binary());
case 'Z':
return ProcessPrimitive(large_binary());
case 'w':
return ProcessFixedSizeBinary();
case 'd':
return ProcessDecimal();
case 't':
return ProcessTemporal();
case '+':
return ProcessNested();
}
return f_parser_.Invalid();
}
Status ProcessTemporal() {
RETURN_NOT_OK(f_parser_.CheckHasNext());
switch (f_parser_.Next()) {
case 'd':
return ProcessDate();
case 't':
return ProcessTime();
case 'D':
return ProcessDuration();
case 'i':
return ProcessInterval();
case 's':
return ProcessTimestamp();
}
return f_parser_.Invalid();
}
Status ProcessNested() {
RETURN_NOT_OK(f_parser_.CheckHasNext());
switch (f_parser_.Next()) {
case 'l':
return ProcessListLike<ListType>();
case 'L':
return ProcessListLike<LargeListType>();
case 'w':
return ProcessFixedSizeList();
case 's':
return ProcessStruct();
case 'm':
return ProcessMap();
case 'u':
return ProcessUnion();
}
return f_parser_.Invalid();
}
Status ProcessDate() {