/
r_to_arrow.cpp
1500 lines (1258 loc) · 46.7 KB
/
r_to_arrow.cpp
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_types.h"
#include "./arrow_vctrs.h"
#if defined(ARROW_R_WITH_ARROW)
#include <arrow/array/builder_base.h>
#include <arrow/array/builder_binary.h>
#include <arrow/array/builder_decimal.h>
#include <arrow/array/builder_dict.h>
#include <arrow/array/builder_nested.h>
#include <arrow/array/builder_primitive.h>
#include <arrow/array/concatenate.h>
#include <arrow/table.h>
#include <arrow/type_traits.h>
#include <arrow/util/bitmap_writer.h>
#include <arrow/util/checked_cast.h>
#include <arrow/util/converter.h>
#include <arrow/util/logging.h>
#include "./r_task_group.h"
namespace arrow {
using internal::checked_cast;
using internal::checked_pointer_cast;
using internal::Converter;
using internal::DictionaryConverter;
using internal::ListConverter;
using internal::PrimitiveConverter;
using internal::StructConverter;
using internal::MakeChunker;
using internal::MakeConverter;
namespace r {
struct RConversionOptions {
RConversionOptions() = default;
std::shared_ptr<arrow::DataType> type;
bool strict;
int64_t size;
};
enum RVectorType {
BOOLEAN,
UINT8,
INT32,
FLOAT64,
INT64,
COMPLEX,
STRING,
DATAFRAME,
DATE_INT,
DATE_DBL,
TIME,
DURATION,
POSIXCT,
POSIXLT,
BINARY,
LIST,
FACTOR,
OTHER
};
// this flattens out a logical type of what an R object is
// because TYPEOF() is not detailed enough
// we can't use arrow types though as there is no 1-1 mapping
RVectorType GetVectorType(SEXP x) {
switch (TYPEOF(x)) {
case LGLSXP:
return BOOLEAN;
case RAWSXP:
return UINT8;
case INTSXP:
if (Rf_inherits(x, "factor")) {
return FACTOR;
} else if (Rf_inherits(x, "Date")) {
return DATE_INT;
}
return INT32;
case STRSXP:
return STRING;
case CPLXSXP:
return COMPLEX;
case REALSXP: {
if (Rf_inherits(x, "Date")) {
return DATE_DBL;
} else if (Rf_inherits(x, "integer64")) {
return INT64;
} else if (Rf_inherits(x, "POSIXct")) {
return POSIXCT;
} else if (Rf_inherits(x, "hms")) {
return TIME;
} else if (Rf_inherits(x, "difftime")) {
return DURATION;
} else {
return FLOAT64;
}
}
case VECSXP: {
if (Rf_inherits(x, "data.frame")) {
return DATAFRAME;
}
if (Rf_inherits(x, "POSIXlt")) {
return POSIXLT;
}
if (Rf_inherits(x, "arrow_binary")) {
return BINARY;
}
return LIST;
}
default:
break;
}
return OTHER;
}
template <typename T>
bool is_NA(T value);
template <>
bool is_NA<int>(int value) {
return value == NA_INTEGER;
}
template <>
bool is_NA<double>(double value) {
return ISNA(value);
}
template <>
bool is_NA<uint8_t>(uint8_t value) {
return false;
}
template <>
bool is_NA<cpp11::r_bool>(cpp11::r_bool value) {
return value == NA_LOGICAL;
}
template <>
bool is_NA<cpp11::r_string>(cpp11::r_string value) {
return value == NA_STRING;
}
template <>
bool is_NA<SEXP>(SEXP value) {
return Rf_isNull(value);
}
template <>
bool is_NA<int64_t>(int64_t value) {
return value == NA_INT64;
}
template <typename T>
class RVectorIterator {
public:
using value_type = T;
RVectorIterator(SEXP x, int64_t start)
: ptr_x_(reinterpret_cast<const T*>(DATAPTR_RO(x)) + start) {}
RVectorIterator& operator++() {
++ptr_x_;
return *this;
}
const T operator*() const { return *ptr_x_; }
private:
const T* ptr_x_;
};
template <typename T>
class RVectorIterator_ALTREP {
public:
using value_type = T;
using data_type =
typename std::conditional<std::is_same<T, int64_t>::value, double, T>::type;
using r_vector_type = cpp11::r_vector<data_type>;
using r_vector_iterator = typename r_vector_type::const_iterator;
RVectorIterator_ALTREP(SEXP x, int64_t start)
: vector_(x), it_(vector_.begin() + start) {}
RVectorIterator_ALTREP& operator++() {
++it_;
return *this;
}
const T operator*() const { return GetValue(*it_); }
static T GetValue(data_type x) { return x; }
private:
r_vector_type vector_;
r_vector_iterator it_;
};
template <>
int64_t RVectorIterator_ALTREP<int64_t>::GetValue(double x) {
int64_t value;
memcpy(&value, &x, sizeof(int64_t));
return value;
}
template <typename Iterator, typename AppendNull, typename AppendValue>
Status VisitVector(Iterator it, int64_t n, AppendNull&& append_null,
AppendValue&& append_value) {
for (R_xlen_t i = 0; i < n; i++, ++it) {
auto value = *it;
if (is_NA<typename Iterator::value_type>(value)) {
RETURN_NOT_OK(append_null());
} else {
RETURN_NOT_OK(append_value(value));
}
}
return Status::OK();
}
class RConverter : public Converter<SEXP, RConversionOptions> {
public:
virtual Status Append(SEXP) { return Status::NotImplemented("Append"); }
virtual Status Extend(SEXP values, int64_t size, int64_t offset = 0) {
return Status::NotImplemented("Extend");
}
// by default, just delay the ->Extend(), i.e. not run in parallel
// implementations might redefine so that ->Extend() is run in parallel
virtual void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(false, task);
}
virtual Status ExtendMasked(SEXP values, SEXP mask, int64_t size, int64_t offset = 0) {
return Status::NotImplemented("ExtendMasked");
}
virtual Result<std::shared_ptr<ChunkedArray>> ToChunkedArray() {
ARROW_ASSIGN_OR_RAISE(auto array, this->ToArray())
return std::make_shared<ChunkedArray>(array);
}
};
template <typename T, typename Enable = void>
class RPrimitiveConverter;
template <typename T>
Result<T> CIntFromRScalarImpl(int64_t value) {
if (value < std::numeric_limits<T>::min() || value > std::numeric_limits<T>::max()) {
return Status::Invalid("value outside of range");
}
return static_cast<T>(value);
}
template <>
Result<uint64_t> CIntFromRScalarImpl<uint64_t>(int64_t value) {
if (value < 0) {
return Status::Invalid("value outside of range");
}
return static_cast<uint64_t>(value);
}
// utility to convert R single values from (int, raw, double and int64) vectors
// to arrow integers and floating point
struct RConvert {
// ---- convert to an arrow integer
template <typename Type, typename From>
static enable_if_integer<Type, Result<typename Type::c_type>> Convert(Type*,
From from) {
return CIntFromRScalarImpl<typename Type::c_type>(from);
}
// ---- convert R integer types to double
template <typename Type, typename From>
static enable_if_t<std::is_same<Type, const DoubleType>::value &&
!std::is_same<From, double>::value,
Result<typename Type::c_type>>
Convert(Type*, From from) {
constexpr int64_t kDoubleMax = 1LL << 53;
constexpr int64_t kDoubleMin = -(1LL << 53);
if (from < kDoubleMin || from > kDoubleMax) {
return Status::Invalid("Integer value ", from, " is outside of the range exactly",
" representable by a IEEE 754 double precision value");
}
return static_cast<double>(from);
}
// ---- convert double to double
template <typename Type, typename From>
static enable_if_t<std::is_same<Type, const DoubleType>::value &&
std::is_same<From, double>::value,
Result<typename Type::c_type>>
Convert(Type*, From from) {
return from;
}
// ---- convert R integer types to float
template <typename Type, typename From>
static enable_if_t<std::is_same<Type, const FloatType>::value &&
!std::is_same<From, double>::value,
Result<typename Type::c_type>>
Convert(Type*, From from) {
constexpr int64_t kFloatMax = 1LL << 24;
constexpr int64_t kFloatMin = -(1LL << 24);
if (from < kFloatMin || from > kFloatMax) {
return Status::Invalid("Integer value ", from, " is outside of the range exactly",
" representable by a IEEE 754 single precision value");
}
return static_cast<float>(from);
}
// ---- convert double to float
template <typename Type, typename From>
static enable_if_t<std::is_same<Type, const FloatType>::value &&
std::is_same<From, double>::value,
Result<typename Type::c_type>>
Convert(Type*, From from) {
return static_cast<float>(from);
}
// ---- convert to half float: not implemented
template <typename Type, typename From>
static enable_if_t<std::is_same<Type, const HalfFloatType>::value,
Result<typename Type::c_type>>
Convert(Type*, From from) {
return Status::Invalid("Cannot convert to Half Float");
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_null<T>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP, int64_t size, int64_t offset = 0) override {
return this->primitive_builder_->AppendNulls(size - offset);
}
};
// TODO: extend this to BooleanType, but this needs some work in RConvert
template <typename T>
class RPrimitiveConverter<
T, enable_if_t<is_integer_type<T>::value || is_floating_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
auto rtype = GetVectorType(x);
switch (rtype) {
case UINT8:
return ExtendDispatch<unsigned char>(x, size, offset);
case INT32:
return ExtendDispatch<int>(x, size, offset);
case FLOAT64:
return ExtendDispatch<double>(x, size, offset);
case INT64:
return ExtendDispatch<int64_t>(x, size, offset);
default:
break;
}
// TODO: mention T in the error
return Status::Invalid("cannot convert");
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
private:
template <typename r_value_type>
Status ExtendDispatch(SEXP x, int64_t size, int64_t offset) {
if (ALTREP(x)) {
// `x` is an ALTREP R vector storing `r_value_type`
// and that type matches exactly the type of the array this is building
return Extend_impl(RVectorIterator_ALTREP<r_value_type>(x, offset), size);
} else {
// `x` is not an ALTREP vector so we have direct access to a range of values
return Extend_impl(RVectorIterator<r_value_type>(x, offset), size);
}
}
template <typename Iterator>
Status Extend_impl(Iterator it, int64_t size) {
using r_value_type = typename Iterator::value_type;
RETURN_NOT_OK(this->primitive_builder_->Reserve(size));
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
if (std::is_same<typename T::c_type, r_value_type>::value) {
auto append_value = [this](r_value_type value) {
this->primitive_builder_->UnsafeAppend(value);
return Status::OK();
};
return VisitVector(it, size, append_null, append_value);
} else {
auto append_value = [this](r_value_type value) {
ARROW_ASSIGN_OR_RAISE(auto converted,
RConvert::Convert(this->primitive_type_, value));
this->primitive_builder_->UnsafeAppend(converted);
return Status::OK();
};
return VisitVector(it, size, append_null, append_value);
}
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_t<is_boolean_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
auto rtype = GetVectorType(x);
if (rtype != BOOLEAN) {
return Status::Invalid("Expecting a logical vector");
}
if (ALTREP(x)) {
return Extend_impl(RVectorIterator_ALTREP<cpp11::r_bool>(x, offset), size);
} else {
return Extend_impl(RVectorIterator<cpp11::r_bool>(x, offset), size);
}
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
private:
template <typename Iterator>
Status Extend_impl(Iterator it, int64_t size) {
RETURN_NOT_OK(this->Reserve(size));
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
auto append_value = [this](cpp11::r_bool value) {
this->primitive_builder_->UnsafeAppend(value == 1);
return Status::OK();
};
return VisitVector(it, size, append_null, append_value);
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_t<is_date_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
switch (GetVectorType(x)) {
case DATE_INT:
return AppendRange_Date_dispatch<int>(x, size, offset);
case DATE_DBL:
return AppendRange_Date_dispatch<double>(x, size, offset);
case POSIXCT:
return AppendRange_Posixct_dispatch(x, size, offset);
default:
break;
}
return Status::Invalid("cannot convert to date type ");
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
private:
template <typename r_value_type>
Status AppendRange_Date_dispatch(SEXP x, int64_t size, int64_t offset) {
if (ALTREP(x)) {
return AppendRange_Date(RVectorIterator_ALTREP<r_value_type>(x, offset),
size - offset);
} else {
return AppendRange_Date(RVectorIterator<r_value_type>(x, offset), size - offset);
}
}
template <typename Iterator>
Status AppendRange_Date(Iterator it, int64_t size) {
using r_value_type = typename Iterator::value_type;
RETURN_NOT_OK(this->Reserve(size));
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
auto append_value = [this](r_value_type value) {
this->primitive_builder_->UnsafeAppend(FromRDate(this->primitive_type_, value));
return Status::OK();
};
return VisitVector(it, size, append_null, append_value);
}
Status AppendRange_Posixct_dispatch(SEXP x, int64_t size, int64_t offset) {
if (ALTREP(x)) {
return AppendRange_Posixct(RVectorIterator_ALTREP<double>(x, offset),
size - offset);
} else {
return AppendRange_Posixct(RVectorIterator<double>(x, offset), size - offset);
}
}
template <typename Iterator>
Status AppendRange_Posixct(Iterator it, int64_t size) {
using r_value_type = typename Iterator::value_type;
RETURN_NOT_OK(this->Reserve(size));
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
auto append_value = [this](r_value_type value) {
this->primitive_builder_->UnsafeAppend(FromPosixct(this->primitive_type_, value));
return Status::OK();
};
return VisitVector(it, size, append_null, append_value);
}
static int FromRDate(const Date32Type*, int from) { return from; }
static int64_t FromRDate(const Date64Type*, int from) {
constexpr int64_t kMilliSecondsPerDay = 86400000;
return from * kMilliSecondsPerDay;
}
static int FromPosixct(const Date32Type*, double from) {
constexpr int64_t kSecondsPerDay = 86400;
return from / kSecondsPerDay;
}
static int64_t FromPosixct(const Date64Type*, double from) { return from * 1000; }
};
int64_t get_TimeUnit_multiplier(TimeUnit::type unit) {
switch (unit) {
case TimeUnit::SECOND:
return 1;
case TimeUnit::MILLI:
return 1000;
case TimeUnit::MICRO:
return 1000000;
case TimeUnit::NANO:
return 1000000000;
default:
return 0;
}
}
Result<int> get_difftime_unit_multiplier(SEXP x) {
std::string unit(CHAR(STRING_ELT(Rf_getAttrib(x, symbols::units), 0)));
if (unit == "secs") {
return 1;
} else if (unit == "mins") {
return 60;
} else if (unit == "hours") {
return 3600;
} else if (unit == "days") {
return 86400;
} else if (unit == "weeks") {
return 604800;
} else {
return Status::Invalid("unknown difftime unit");
}
}
template <typename T>
class RPrimitiveConverter<T, enable_if_t<is_time_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RETURN_NOT_OK(this->Reserve(size - offset));
auto rtype = GetVectorType(x);
if (rtype != TIME) {
return Status::Invalid("Invalid conversion to time");
}
// multiplier to get the number of seconds from the value stored in the R vector
ARROW_ASSIGN_OR_RAISE(int difftime_multiplier, get_difftime_unit_multiplier(x));
// then multiply the seconds by this to match the time unit
auto multiplier =
get_TimeUnit_multiplier(this->primitive_type_->unit()) * difftime_multiplier;
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
auto append_value = [this, multiplier](double value) {
auto converted = static_cast<typename T::c_type>(value * multiplier);
this->primitive_builder_->UnsafeAppend(converted);
return Status::OK();
};
if (ALTREP(x)) {
return VisitVector(RVectorIterator_ALTREP<double>(x, offset), size, append_null,
append_value);
} else {
return VisitVector(RVectorIterator<double>(x, offset), size, append_null,
append_value);
}
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_t<is_timestamp_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RETURN_NOT_OK(this->Reserve(size - offset));
RVectorType rtype = GetVectorType(x);
if (rtype != POSIXCT) {
return Status::Invalid("Invalid conversion to timestamp");
}
int64_t multiplier = get_TimeUnit_multiplier(this->primitive_type_->unit());
auto append_value = [this, multiplier](double value) {
auto converted = static_cast<typename T::c_type>(value * multiplier);
this->primitive_builder_->UnsafeAppend(converted);
return Status::OK();
};
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
if (ALTREP(x)) {
return VisitVector(RVectorIterator_ALTREP<double>(x, offset), size, append_null,
append_value);
} else {
return VisitVector(RVectorIterator<double>(x, offset), size, append_null,
append_value);
}
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_t<is_decimal_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
return Status::NotImplemented("Extend");
}
};
Status check_binary(SEXP x, int64_t size) {
RVectorType rtype = GetVectorType(x);
switch (rtype) {
case BINARY:
break;
case LIST: {
// check this is a list of raw vectors
const SEXP* p_x = VECTOR_PTR_RO(x);
for (R_xlen_t i = 0; i < size; i++, ++p_x) {
if (TYPEOF(*p_x) != RAWSXP) {
return Status::Invalid("invalid R type to convert to binary");
}
}
break;
}
default:
return Status::Invalid("invalid R type to convert to binary");
}
return Status::OK();
}
template <typename T>
class RPrimitiveConverter<T, enable_if_binary<T>>
: public PrimitiveConverter<T, RConverter> {
public:
using OffsetType = typename T::offset_type;
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RETURN_NOT_OK(this->Reserve(size - offset));
RETURN_NOT_OK(check_binary(x, size));
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
auto append_value = [this](SEXP raw) {
R_xlen_t n = XLENGTH(raw);
ARROW_RETURN_NOT_OK(this->primitive_builder_->ReserveData(n));
this->primitive_builder_->UnsafeAppend(RAW_RO(raw), static_cast<OffsetType>(n));
return Status::OK();
};
return VisitVector(RVectorIterator<SEXP>(x, offset), size, append_null, append_value);
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_t<std::is_same<T, FixedSizeBinaryType>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RETURN_NOT_OK(this->Reserve(size - offset));
RETURN_NOT_OK(check_binary(x, size));
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
auto append_value = [this](SEXP raw) {
R_xlen_t n = XLENGTH(raw);
if (n != this->primitive_builder_->byte_width()) {
return Status::Invalid("invalid size");
}
ARROW_RETURN_NOT_OK(this->primitive_builder_->ReserveData(n));
this->primitive_builder_->UnsafeAppend(RAW_RO(raw));
return Status::OK();
};
return VisitVector(RVectorIterator<SEXP>(x, offset), size, append_null, append_value);
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
tasks.Append(!ALTREP(values), std::move(task));
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_string_like<T>>
: public PrimitiveConverter<T, RConverter> {
public:
using OffsetType = typename T::offset_type;
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RVectorType rtype = GetVectorType(x);
if (rtype != STRING) {
return Status::Invalid("Expecting a character vector");
}
return UnsafeAppendUtf8Strings(arrow::r::utf8_strings(x), size, offset);
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
auto task = [this, values, size]() { return this->Extend(values, size); };
// TODO: refine this., e.g. extract setup from Extend()
tasks.Append(false, std::move(task));
}
private:
Status UnsafeAppendUtf8Strings(const cpp11::strings& s, int64_t size, int64_t offset) {
RETURN_NOT_OK(this->primitive_builder_->Reserve(s.size()));
const SEXP* p_strings = reinterpret_cast<const SEXP*>(DATAPTR_RO(s));
// we know all the R strings are utf8 already, so we can get
// a definite size and then use UnsafeAppend*()
int64_t total_length = 0;
for (R_xlen_t i = offset; i < size; i++, ++p_strings) {
SEXP si = *p_strings;
total_length += si == NA_STRING ? 0 : LENGTH(si);
}
RETURN_NOT_OK(this->primitive_builder_->ReserveData(total_length));
// append
p_strings = reinterpret_cast<const SEXP*>(DATAPTR_RO(s));
for (R_xlen_t i = offset; i < size; i++, ++p_strings) {
SEXP si = *p_strings;
if (si == NA_STRING) {
this->primitive_builder_->UnsafeAppendNull();
} else {
this->primitive_builder_->UnsafeAppend(CHAR(si), LENGTH(si));
}
}
return Status::OK();
}
};
template <typename T>
class RPrimitiveConverter<T, enable_if_t<is_duration_type<T>::value>>
: public PrimitiveConverter<T, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
auto rtype = GetVectorType(x);
// only handle <difftime> R objects
if (rtype == DURATION) {
RETURN_NOT_OK(this->Reserve(size - offset));
ARROW_ASSIGN_OR_RAISE(int difftime_multiplier, get_difftime_unit_multiplier(x));
int64_t multiplier =
get_TimeUnit_multiplier(this->primitive_type_->unit()) * difftime_multiplier;
auto append_value = [this, multiplier](double value) {
auto converted = static_cast<typename T::c_type>(value * multiplier);
this->primitive_builder_->UnsafeAppend(converted);
return Status::OK();
};
auto append_null = [this]() {
this->primitive_builder_->UnsafeAppendNull();
return Status::OK();
};
if (ALTREP(x)) {
return VisitVector(RVectorIterator_ALTREP<double>(x, offset), size, append_null,
append_value);
} else {
return VisitVector(RVectorIterator<double>(x, offset), size, append_null,
append_value);
}
return Status::OK();
}
return Status::NotImplemented("Extend");
}
};
template <typename T>
class RListConverter;
template <typename U, typename Enable = void>
class RDictionaryConverter;
template <typename U>
class RDictionaryConverter<U, enable_if_has_c_type<U>>
: public DictionaryConverter<U, RConverter> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
return Status::NotImplemented("Extend");
}
};
template <typename ValueType>
class RDictionaryConverter<ValueType, enable_if_has_string_view<ValueType>>
: public DictionaryConverter<ValueType, RConverter> {
public:
using BuilderType = DictionaryBuilder<ValueType>;
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RETURN_NOT_OK(ExtendSetup(x, size, offset));
return ExtendImpl(x, size, offset, GetCharLevels(x));
}
void DelayedExtend(SEXP values, int64_t size, RTasks& tasks) override {
// the setup runs synchronously first
Status setup = ExtendSetup(values, size, /*offset=*/0);
if (!setup.ok()) {
// if that fails, propagate the error
tasks.Append(false, [setup]() { return setup; });
} else {
auto char_levels = GetCharLevels(values);
tasks.Append(true, [this, values, size, char_levels]() {
return this->ExtendImpl(values, size, /*offset=*/0, char_levels);
});
}
}
Result<std::shared_ptr<ChunkedArray>> ToChunkedArray() override {
ARROW_ASSIGN_OR_RAISE(auto result, this->builder_->Finish());
auto result_type = checked_cast<DictionaryType*>(result->type().get());
if (this->dict_type_->ordered() && !result_type->ordered()) {
// TODO: we should not have to do that, there is probably something wrong
// in the DictionaryBuilder code
result->data()->type =
arrow::dictionary(result_type->index_type(), result_type->value_type(), true);
}
return std::make_shared<ChunkedArray>(
std::make_shared<DictionaryArray>(result->data()));
}
private:
std::vector<const char*> GetCharLevels(SEXP x) {
SEXP levels = Rf_getAttrib(x, R_LevelsSymbol);
R_xlen_t n_levels = XLENGTH(levels);
std::vector<const char*> char_levels(XLENGTH(levels));
const SEXP* p_levels = reinterpret_cast<const SEXP*>(DATAPTR_RO(levels));
for (R_xlen_t i = 0; i < n_levels; i++, ++p_levels) {
char_levels[i] = CHAR(*p_levels);
}
return char_levels;
}
Status ExtendSetup(SEXP x, int64_t size, int64_t offset) {
RVectorType rtype = GetVectorType(x);
if (rtype != FACTOR) {
return Status::Invalid("invalid R type to convert to dictionary");
}
// first we need to handle the levels
SEXP levels = Rf_getAttrib(x, R_LevelsSymbol);
auto memo_chunked_chunked_array =
arrow::r::vec_to_arrow_ChunkedArray(levels, utf8(), false);
for (const auto& chunk : memo_chunked_chunked_array->chunks()) {
RETURN_NOT_OK(this->value_builder_->InsertMemoValues(*chunk));
}
// then we can proceed
return this->Reserve(size - offset);
}
Status ExtendImpl(SEXP values, int64_t size, int64_t offset,
const std::vector<const char*>& char_levels) {
auto append_null = [this]() { return this->value_builder_->AppendNull(); };
auto append_value = [this, &char_levels](int value) {
return this->value_builder_->Append(char_levels[value - 1]);
};
return VisitVector(RVectorIterator<int>(values, offset), size, append_null,
append_value);
}
};
template <typename T, typename Enable = void>
struct RConverterTrait;
template <typename T>
struct RConverterTrait<
T, enable_if_t<!is_nested_type<T>::value && !is_interval_type<T>::value &&
!is_extension_type<T>::value>> {
using type = RPrimitiveConverter<T>;
};
template <typename T>
struct RConverterTrait<T, enable_if_list_like<T>> {
using type = RListConverter<T>;
};
template <typename T>
class RListConverter : public ListConverter<T, RConverter, RConverterTrait> {
public:
Status Extend(SEXP x, int64_t size, int64_t offset = 0) override {
RETURN_NOT_OK(this->Reserve(size));
RVectorType rtype = GetVectorType(x);
if (rtype != LIST) {
return Status::Invalid("Cannot convert to list type");
}
auto append_null = [this]() { return this->list_builder_->AppendNull(); };
auto append_value = [this](SEXP value) {
// TODO: if we decide that this can be run concurrently
// we'll have to do vec_size() upfront
int n = vctrs::vec_size(value);
RETURN_NOT_OK(this->list_builder_->ValidateOverflow(n));