/
dictionary.go
1806 lines (1613 loc) · 50.5 KB
/
dictionary.go
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.
package array
import (
"bytes"
"errors"
"fmt"
"math"
"math/bits"
"sync/atomic"
"unsafe"
"github.com/apache/arrow/go/v13/arrow"
"github.com/apache/arrow/go/v13/arrow/bitutil"
"github.com/apache/arrow/go/v13/arrow/decimal128"
"github.com/apache/arrow/go/v13/arrow/decimal256"
"github.com/apache/arrow/go/v13/arrow/float16"
"github.com/apache/arrow/go/v13/arrow/internal/debug"
"github.com/apache/arrow/go/v13/arrow/memory"
"github.com/apache/arrow/go/v13/internal/hashing"
"github.com/apache/arrow/go/v13/internal/json"
"github.com/apache/arrow/go/v13/internal/utils"
)
// Dictionary represents the type for dictionary-encoded data with a data
// dependent dictionary.
//
// A dictionary array contains an array of non-negative integers (the "dictionary"
// indices") along with a data type containing a "dictionary" corresponding to
// the distinct values represented in the data.
//
// For example, the array:
//
// ["foo", "bar", "foo", "bar", "foo", "bar"]
//
// with dictionary ["bar", "foo"], would have the representation of:
//
// indices: [1, 0, 1, 0, 1, 0]
// dictionary: ["bar", "foo"]
//
// The indices in principle may be any integer type.
type Dictionary struct {
array
indices arrow.Array
dict arrow.Array
}
// NewDictionaryArray constructs a dictionary array with the provided indices
// and dictionary using the given type.
func NewDictionaryArray(typ arrow.DataType, indices, dict arrow.Array) *Dictionary {
a := &Dictionary{}
a.array.refCount = 1
dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), indices.Data().Children(), indices.NullN(), indices.Data().Offset())
dictdata.dictionary = dict.Data().(*Data)
dict.Data().Retain()
defer dictdata.Release()
a.setData(dictdata)
return a
}
// checkIndexBounds returns an error if any value in the provided integer
// arraydata is >= the passed upperlimit or < 0. otherwise nil
func checkIndexBounds(indices *Data, upperlimit uint64) error {
if indices.length == 0 {
return nil
}
var maxval uint64
switch indices.dtype.ID() {
case arrow.UINT8:
maxval = math.MaxUint8
case arrow.UINT16:
maxval = math.MaxUint16
case arrow.UINT32:
maxval = math.MaxUint32
case arrow.UINT64:
maxval = math.MaxUint64
}
// for unsigned integers, if the values array is larger than the maximum
// index value (especially for UINT8/UINT16), then there's no need to
// boundscheck. for signed integers we still need to bounds check
// because a value could be < 0.
isSigned := maxval == 0
if !isSigned && upperlimit > maxval {
return nil
}
start := indices.offset
end := indices.offset + indices.length
// TODO(ARROW-15950): lift BitSetRunReader from parquet to utils
// and use it here for performance improvement.
switch indices.dtype.ID() {
case arrow.INT8:
data := arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
min, max := utils.GetMinMaxInt8(data[start:end])
if min < 0 || max >= int8(upperlimit) {
return fmt.Errorf("contains out of bounds index: min: %d, max: %d", min, max)
}
case arrow.UINT8:
data := arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
_, max := utils.GetMinMaxUint8(data[start:end])
if max >= uint8(upperlimit) {
return fmt.Errorf("contains out of bounds index: max: %d", max)
}
case arrow.INT16:
data := arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
min, max := utils.GetMinMaxInt16(data[start:end])
if min < 0 || max >= int16(upperlimit) {
return fmt.Errorf("contains out of bounds index: min: %d, max: %d", min, max)
}
case arrow.UINT16:
data := arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
_, max := utils.GetMinMaxUint16(data[start:end])
if max >= uint16(upperlimit) {
return fmt.Errorf("contains out of bounds index: max: %d", max)
}
case arrow.INT32:
data := arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
min, max := utils.GetMinMaxInt32(data[start:end])
if min < 0 || max >= int32(upperlimit) {
return fmt.Errorf("contains out of bounds index: min: %d, max: %d", min, max)
}
case arrow.UINT32:
data := arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
_, max := utils.GetMinMaxUint32(data[start:end])
if max >= uint32(upperlimit) {
return fmt.Errorf("contains out of bounds index: max: %d", max)
}
case arrow.INT64:
data := arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
min, max := utils.GetMinMaxInt64(data[start:end])
if min < 0 || max >= int64(upperlimit) {
return fmt.Errorf("contains out of bounds index: min: %d, max: %d", min, max)
}
case arrow.UINT64:
data := arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
_, max := utils.GetMinMaxUint64(data[indices.offset : indices.offset+indices.length])
if max >= upperlimit {
return fmt.Errorf("contains out of bounds value: max: %d", max)
}
default:
return fmt.Errorf("invalid type for bounds checking: %T", indices.dtype)
}
return nil
}
// NewValidatedDictionaryArray constructs a dictionary array from the provided indices
// and dictionary arrays, while also performing validation checks to ensure correctness
// such as bounds checking at are usually skipped for performance.
func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict arrow.Array) (*Dictionary, error) {
if indices.DataType().ID() != typ.IndexType.ID() {
return nil, fmt.Errorf("dictionary type index (%T) does not match indices array type (%T)", typ.IndexType, indices.DataType())
}
if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
return nil, fmt.Errorf("dictionary value type (%T) does not match dict array type (%T)", typ.ValueType, dict.DataType())
}
if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); err != nil {
return nil, err
}
return NewDictionaryArray(typ, indices, dict), nil
}
// NewDictionaryData creates a strongly typed Dictionary array from
// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
func NewDictionaryData(data arrow.ArrayData) *Dictionary {
a := &Dictionary{}
a.refCount = 1
a.setData(data.(*Data))
return a
}
func (d *Dictionary) Retain() {
atomic.AddInt64(&d.refCount, 1)
}
func (d *Dictionary) Release() {
debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
if atomic.AddInt64(&d.refCount, -1) == 0 {
d.data.Release()
d.data, d.nullBitmapBytes = nil, nil
d.indices.Release()
d.indices = nil
if d.dict != nil {
d.dict.Release()
d.dict = nil
}
}
}
func (d *Dictionary) setData(data *Data) {
d.array.setData(data)
dictType := data.dtype.(*arrow.DictionaryType)
if data.dictionary == nil {
if data.length > 0 {
panic("arrow/array: no dictionary set in Data for Dictionary array")
}
} else {
debug.Assert(arrow.TypeEqual(dictType.ValueType, data.dictionary.DataType()), "mismatched dictionary value types")
}
indexData := NewData(dictType.IndexType, data.length, data.buffers, data.childData, data.nulls, data.offset)
defer indexData.Release()
d.indices = MakeFromData(indexData)
}
// Dictionary returns the values array that makes up the dictionary for this
// array.
func (d *Dictionary) Dictionary() arrow.Array {
if d.dict == nil {
d.dict = MakeFromData(d.data.dictionary)
}
return d.dict
}
// Indices returns the underlying array of indices as it's own array
func (d *Dictionary) Indices() arrow.Array {
return d.indices
}
// CanCompareIndices returns true if the dictionary arrays can be compared
// without having to unify the dictionaries themselves first.
// This means that the index types are equal too.
func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
return false
}
minlen := int64(min(d.data.dictionary.length, other.data.dictionary.length))
return SliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 0, minlen)
}
func (d *Dictionary) ValueStr(i int) string {
if d.IsNull(i) {
return NullValueStr
}
return d.Dictionary().ValueStr(d.GetValueIndex(i))
}
func (d *Dictionary) String() string {
return fmt.Sprintf("{ dictionary: %v\n indices: %v }", d.Dictionary(), d.Indices())
}
// GetValueIndex returns the dictionary index for the value at index i of the array.
// The actual value can be retrieved by using d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
func (d *Dictionary) GetValueIndex(i int) int {
indiceData := d.data.buffers[1].Bytes()
// we know the value is non-negative per the spec, so
// we can use the unsigned value regardless.
switch d.indices.DataType().ID() {
case arrow.UINT8, arrow.INT8:
return int(uint8(indiceData[d.data.offset+i]))
case arrow.UINT16, arrow.INT16:
return int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
case arrow.UINT32, arrow.INT32:
idx := arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i]
debug.Assert(bits.UintSize == 64 || idx <= math.MaxInt32, "arrow/dictionary: truncation of index value")
return int(idx)
case arrow.UINT64, arrow.INT64:
idx := arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i]
debug.Assert((bits.UintSize == 32 && idx <= math.MaxInt32) || (bits.UintSize == 64 && idx <= math.MaxInt64), "arrow/dictionary: truncation of index value")
return int(idx)
}
debug.Assert(false, "unreachable dictionary index")
return -1
}
func (d *Dictionary) GetOneForMarshal(i int) interface{} {
if d.IsNull(i) {
return nil
}
vidx := d.GetValueIndex(i)
return d.Dictionary().GetOneForMarshal(vidx)
}
func (d *Dictionary) MarshalJSON() ([]byte, error) {
vals := make([]interface{}, d.Len())
for i := 0; i < d.Len(); i++ {
vals[i] = d.GetOneForMarshal(i)
}
return json.Marshal(vals)
}
func arrayEqualDict(l, r *Dictionary) bool {
return Equal(l.Dictionary(), r.Dictionary()) && Equal(l.indices, r.indices)
}
func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && arrayApproxEqual(l.indices, r.indices, opt)
}
// helper for building the properly typed indices of the dictionary builder
type indexBuilder struct {
Builder
Append func(int)
}
func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) (ret indexBuilder, err error) {
ret = indexBuilder{Builder: NewBuilder(mem, dt)}
switch dt.ID() {
case arrow.INT8:
ret.Append = func(idx int) {
ret.Builder.(*Int8Builder).Append(int8(idx))
}
case arrow.UINT8:
ret.Append = func(idx int) {
ret.Builder.(*Uint8Builder).Append(uint8(idx))
}
case arrow.INT16:
ret.Append = func(idx int) {
ret.Builder.(*Int16Builder).Append(int16(idx))
}
case arrow.UINT16:
ret.Append = func(idx int) {
ret.Builder.(*Uint16Builder).Append(uint16(idx))
}
case arrow.INT32:
ret.Append = func(idx int) {
ret.Builder.(*Int32Builder).Append(int32(idx))
}
case arrow.UINT32:
ret.Append = func(idx int) {
ret.Builder.(*Uint32Builder).Append(uint32(idx))
}
case arrow.INT64:
ret.Append = func(idx int) {
ret.Builder.(*Int64Builder).Append(int64(idx))
}
case arrow.UINT64:
ret.Append = func(idx int) {
ret.Builder.(*Uint64Builder).Append(uint64(idx))
}
default:
debug.Assert(false, "dictionary index type must be integral")
err = fmt.Errorf("dictionary index type must be integral, not %s", dt)
}
return
}
// helper function to construct an appropriately typed memo table based on
// the value type for the dictionary
func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret hashing.MemoTable, err error) {
switch dt.ID() {
case arrow.INT8:
ret = hashing.NewInt8MemoTable(0)
case arrow.UINT8:
ret = hashing.NewUint8MemoTable(0)
case arrow.INT16:
ret = hashing.NewInt16MemoTable(0)
case arrow.UINT16:
ret = hashing.NewUint16MemoTable(0)
case arrow.INT32:
ret = hashing.NewInt32MemoTable(0)
case arrow.UINT32:
ret = hashing.NewUint32MemoTable(0)
case arrow.INT64:
ret = hashing.NewInt64MemoTable(0)
case arrow.UINT64:
ret = hashing.NewUint64MemoTable(0)
case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
ret = hashing.NewInt64MemoTable(0)
case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
ret = hashing.NewInt32MemoTable(0)
case arrow.FLOAT16:
ret = hashing.NewUint16MemoTable(0)
case arrow.FLOAT32:
ret = hashing.NewFloat32MemoTable(0)
case arrow.FLOAT64:
ret = hashing.NewFloat64MemoTable(0)
case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.DECIMAL256, arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.Binary))
case arrow.STRING:
ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, arrow.BinaryTypes.String))
case arrow.NULL:
default:
err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
}
return
}
type DictionaryBuilder interface {
Builder
NewDictionaryArray() *Dictionary
NewDelta() (indices, delta arrow.Array, err error)
AppendArray(arrow.Array) error
AppendIndices([]int, []bool)
ResetFull()
}
type dictionaryBuilder struct {
builder
dt *arrow.DictionaryType
deltaOffset int
memoTable hashing.MemoTable
idxBuilder indexBuilder
}
// NewDictionaryBuilderWithDict initializes a dictionary builder and inserts the values from `init` as the first
// values in the dictionary, but does not insert them as values into the array.
func NewDictionaryBuilderWithDict(mem memory.Allocator, dt *arrow.DictionaryType, init arrow.Array) DictionaryBuilder {
if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
panic(fmt.Errorf("arrow/array: cannot initialize dictionary type %T with array of type %T", dt.ValueType, init.DataType()))
}
idxbldr, err := createIndexBuilder(mem, dt.IndexType.(arrow.FixedWidthDataType))
if err != nil {
panic(fmt.Errorf("arrow/array: unsupported builder for index type of %T", dt))
}
memo, err := createMemoTable(mem, dt.ValueType)
if err != nil {
panic(fmt.Errorf("arrow/array: unsupported builder for value type of %T", dt))
}
bldr := dictionaryBuilder{
builder: builder{refCount: 1, mem: mem},
idxBuilder: idxbldr,
memoTable: memo,
dt: dt,
}
switch dt.ValueType.ID() {
case arrow.NULL:
ret := &NullDictionaryBuilder{bldr}
debug.Assert(init == nil, "arrow/array: doesn't make sense to init a null dictionary")
return ret
case arrow.UINT8:
ret := &Uint8DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Uint8)); err != nil {
panic(err)
}
}
return ret
case arrow.INT8:
ret := &Int8DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Int8)); err != nil {
panic(err)
}
}
return ret
case arrow.UINT16:
ret := &Uint16DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Uint16)); err != nil {
panic(err)
}
}
return ret
case arrow.INT16:
ret := &Int16DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Int16)); err != nil {
panic(err)
}
}
return ret
case arrow.UINT32:
ret := &Uint32DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Uint32)); err != nil {
panic(err)
}
}
return ret
case arrow.INT32:
ret := &Int32DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Int32)); err != nil {
panic(err)
}
}
return ret
case arrow.UINT64:
ret := &Uint64DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Uint64)); err != nil {
panic(err)
}
}
return ret
case arrow.INT64:
ret := &Int64DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Int64)); err != nil {
panic(err)
}
}
return ret
case arrow.FLOAT16:
ret := &Float16DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Float16)); err != nil {
panic(err)
}
}
return ret
case arrow.FLOAT32:
ret := &Float32DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Float32)); err != nil {
panic(err)
}
}
return ret
case arrow.FLOAT64:
ret := &Float64DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Float64)); err != nil {
panic(err)
}
}
return ret
case arrow.STRING:
ret := &BinaryDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertStringDictValues(init.(*String)); err != nil {
panic(err)
}
}
return ret
case arrow.BINARY:
ret := &BinaryDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Binary)); err != nil {
panic(err)
}
}
return ret
case arrow.FIXED_SIZE_BINARY:
ret := &FixedSizeBinaryDictionaryBuilder{
bldr, dt.ValueType.(*arrow.FixedSizeBinaryType).ByteWidth,
}
if init != nil {
if err = ret.InsertDictValues(init.(*FixedSizeBinary)); err != nil {
panic(err)
}
}
return ret
case arrow.DATE32:
ret := &Date32DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Date32)); err != nil {
panic(err)
}
}
return ret
case arrow.DATE64:
ret := &Date64DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Date64)); err != nil {
panic(err)
}
}
return ret
case arrow.TIMESTAMP:
ret := &TimestampDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Timestamp)); err != nil {
panic(err)
}
}
return ret
case arrow.TIME32:
ret := &Time32DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Time32)); err != nil {
panic(err)
}
}
return ret
case arrow.TIME64:
ret := &Time64DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Time64)); err != nil {
panic(err)
}
}
return ret
case arrow.INTERVAL_MONTHS:
ret := &MonthIntervalDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*MonthInterval)); err != nil {
panic(err)
}
}
return ret
case arrow.INTERVAL_DAY_TIME:
ret := &DayTimeDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*DayTimeInterval)); err != nil {
panic(err)
}
}
return ret
case arrow.DECIMAL128:
ret := &Decimal128DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Decimal128)); err != nil {
panic(err)
}
}
return ret
case arrow.DECIMAL256:
ret := &Decimal256DictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Decimal256)); err != nil {
panic(err)
}
}
return ret
case arrow.LIST:
case arrow.STRUCT:
case arrow.SPARSE_UNION:
case arrow.DENSE_UNION:
case arrow.DICTIONARY:
case arrow.MAP:
case arrow.EXTENSION:
case arrow.FIXED_SIZE_LIST:
case arrow.DURATION:
ret := &DurationDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*Duration)); err != nil {
panic(err)
}
}
return ret
case arrow.LARGE_STRING:
case arrow.LARGE_BINARY:
case arrow.LARGE_LIST:
case arrow.INTERVAL_MONTH_DAY_NANO:
ret := &MonthDayNanoDictionaryBuilder{bldr}
if init != nil {
if err = ret.InsertDictValues(init.(*MonthDayNanoInterval)); err != nil {
panic(err)
}
}
return ret
}
panic("arrow/array: unimplemented dictionary key type")
}
func NewDictionaryBuilder(mem memory.Allocator, dt *arrow.DictionaryType) DictionaryBuilder {
return NewDictionaryBuilderWithDict(mem, dt, nil)
}
func (b *dictionaryBuilder) Type() arrow.DataType { return b.dt }
func (b *dictionaryBuilder) Release() {
debug.Assert(atomic.LoadInt64(&b.refCount) > 0, "too many releases")
if atomic.AddInt64(&b.refCount, -1) == 0 {
b.idxBuilder.Release()
b.idxBuilder.Builder = nil
if binmemo, ok := b.memoTable.(*hashing.BinaryMemoTable); ok {
binmemo.Release()
}
b.memoTable = nil
}
}
func (b *dictionaryBuilder) AppendNull() {
b.length += 1
b.nulls += 1
b.idxBuilder.AppendNull()
}
func (b *dictionaryBuilder) AppendNulls(n int) {
for i := 0; i < n; i++ {
b.AppendNull()
}
}
func (b *dictionaryBuilder) AppendEmptyValue() {
b.length += 1
b.idxBuilder.AppendEmptyValue()
}
func (b *dictionaryBuilder) AppendEmptyValues(n int) {
for i := 0; i < n; i++ {
b.AppendEmptyValue()
}
}
func (b *dictionaryBuilder) Reserve(n int) {
b.idxBuilder.Reserve(n)
}
func (b *dictionaryBuilder) Resize(n int) {
b.idxBuilder.Resize(n)
b.length = b.idxBuilder.Len()
}
func (b *dictionaryBuilder) ResetFull() {
b.builder.reset()
b.idxBuilder.NewArray().Release()
b.memoTable.Reset()
}
func (b *dictionaryBuilder) Cap() int { return b.idxBuilder.Cap() }
func (b *dictionaryBuilder) IsNull(i int) bool { return b.idxBuilder.IsNull(i) }
func (b *dictionaryBuilder) UnmarshalJSON(data []byte) error {
dec := json.NewDecoder(bytes.NewReader(data))
t, err := dec.Token()
if err != nil {
return err
}
if delim, ok := t.(json.Delim); !ok || delim != '[' {
return fmt.Errorf("dictionary builder must upack from json array, found %s", delim)
}
return b.Unmarshal(dec)
}
func (b *dictionaryBuilder) Unmarshal(dec *json.Decoder) error {
bldr := NewBuilder(b.mem, b.dt.ValueType)
defer bldr.Release()
if err := bldr.Unmarshal(dec); err != nil {
return err
}
arr := bldr.NewArray()
defer arr.Release()
return b.AppendArray(arr)
}
func (b *dictionaryBuilder) AppendValueFromString(s string) error {
bldr := NewBuilder(b.mem, b.dt.ValueType)
defer bldr.Release()
if err := bldr.AppendValueFromString(s); err != nil {
return err
}
arr := bldr.NewArray()
defer arr.Release()
return b.AppendArray(arr)
}
func (b *dictionaryBuilder) UnmarshalOne(dec *json.Decoder) error {
bldr := NewBuilder(b.mem, b.dt.ValueType)
defer bldr.Release()
if err := bldr.UnmarshalOne(dec); err != nil {
return err
}
arr := bldr.NewArray()
defer arr.Release()
return b.AppendArray(arr)
}
func (b *dictionaryBuilder) NewArray() arrow.Array {
return b.NewDictionaryArray()
}
func (b *dictionaryBuilder) newData() *Data {
indices, dict, err := b.newWithDictOffset(0)
if err != nil {
panic(err)
}
indices.dtype = b.dt
indices.dictionary = dict
return indices
}
func (b *dictionaryBuilder) NewDictionaryArray() *Dictionary {
a := &Dictionary{}
a.refCount = 1
indices := b.newData()
a.setData(indices)
indices.Release()
return a
}
func (b *dictionaryBuilder) newWithDictOffset(offset int) (indices, dict *Data, err error) {
idxarr := b.idxBuilder.NewArray()
defer idxarr.Release()
indices = idxarr.Data().(*Data)
indices.Retain()
b.deltaOffset = b.memoTable.Size()
dict, err = GetDictArrayData(b.mem, b.dt.ValueType, b.memoTable, offset)
b.reset()
return
}
// NewDelta returns the dictionary indices and a delta dictionary since the
// last time NewArray or NewDictionaryArray were called, and resets the state
// of the builder (except for the dictionary / memotable)
func (b *dictionaryBuilder) NewDelta() (indices, delta arrow.Array, err error) {
indicesData, deltaData, err := b.newWithDictOffset(b.deltaOffset)
if err != nil {
return nil, nil, err
}
defer indicesData.Release()
defer deltaData.Release()
indices, delta = MakeFromData(indicesData), MakeFromData(deltaData)
return
}
func (b *dictionaryBuilder) insertDictValue(val interface{}) error {
_, _, err := b.memoTable.GetOrInsert(val)
return err
}
func (b *dictionaryBuilder) appendValue(val interface{}) error {
idx, _, err := b.memoTable.GetOrInsert(val)
b.idxBuilder.Append(idx)
b.length += 1
return err
}
func getvalFn(arr arrow.Array) func(i int) interface{} {
switch typedarr := arr.(type) {
case *Int8:
return func(i int) interface{} { return typedarr.Value(i) }
case *Uint8:
return func(i int) interface{} { return typedarr.Value(i) }
case *Int16:
return func(i int) interface{} { return typedarr.Value(i) }
case *Uint16:
return func(i int) interface{} { return typedarr.Value(i) }
case *Int32:
return func(i int) interface{} { return typedarr.Value(i) }
case *Uint32:
return func(i int) interface{} { return typedarr.Value(i) }
case *Int64:
return func(i int) interface{} { return typedarr.Value(i) }
case *Uint64:
return func(i int) interface{} { return typedarr.Value(i) }
case *Float16:
return func(i int) interface{} { return typedarr.Value(i).Uint16() }
case *Float32:
return func(i int) interface{} { return typedarr.Value(i) }
case *Float64:
return func(i int) interface{} { return typedarr.Value(i) }
case *Duration:
return func(i int) interface{} { return int64(typedarr.Value(i)) }
case *Timestamp:
return func(i int) interface{} { return int64(typedarr.Value(i)) }
case *Date64:
return func(i int) interface{} { return int64(typedarr.Value(i)) }
case *Time64:
return func(i int) interface{} { return int64(typedarr.Value(i)) }
case *Time32:
return func(i int) interface{} { return int32(typedarr.Value(i)) }
case *Date32:
return func(i int) interface{} { return int32(typedarr.Value(i)) }
case *MonthInterval:
return func(i int) interface{} { return int32(typedarr.Value(i)) }
case *Binary:
return func(i int) interface{} { return typedarr.Value(i) }
case *FixedSizeBinary:
return func(i int) interface{} { return typedarr.Value(i) }
case *String:
return func(i int) interface{} { return typedarr.Value(i) }
case *Decimal128:
return func(i int) interface{} {
val := typedarr.Value(i)
return (*(*[arrow.Decimal128SizeBytes]byte)(unsafe.Pointer(&val)))[:]
}
case *Decimal256:
return func(i int) interface{} {
val := typedarr.Value(i)
return (*(*[arrow.Decimal256SizeBytes]byte)(unsafe.Pointer(&val)))[:]
}
case *DayTimeInterval:
return func(i int) interface{} {
val := typedarr.Value(i)
return (*(*[arrow.DayTimeIntervalSizeBytes]byte)(unsafe.Pointer(&val)))[:]
}
case *MonthDayNanoInterval:
return func(i int) interface{} {
val := typedarr.Value(i)
return (*(*[arrow.MonthDayNanoIntervalSizeBytes]byte)(unsafe.Pointer(&val)))[:]
}
}
panic("arrow/array: invalid dictionary value type")
}
func (b *dictionaryBuilder) AppendArray(arr arrow.Array) error {
debug.Assert(arrow.TypeEqual(b.dt.ValueType, arr.DataType()), "wrong value type of array to append to dict")
valfn := getvalFn(arr)
for i := 0; i < arr.Len(); i++ {
if arr.IsNull(i) {
b.AppendNull()
} else {
if err := b.appendValue(valfn(i)); err != nil {
return err
}
}
}
return nil
}
func (b *dictionaryBuilder) AppendIndices(indices []int, valid []bool) {
b.length += len(indices)
switch idxbldr := b.idxBuilder.Builder.(type) {
case *Int8Builder:
vals := make([]int8, len(indices))
for i, v := range indices {
vals[i] = int8(v)
}
idxbldr.AppendValues(vals, valid)
case *Int16Builder:
vals := make([]int16, len(indices))
for i, v := range indices {
vals[i] = int16(v)
}
idxbldr.AppendValues(vals, valid)
case *Int32Builder:
vals := make([]int32, len(indices))
for i, v := range indices {
vals[i] = int32(v)
}
idxbldr.AppendValues(vals, valid)
case *Int64Builder:
vals := make([]int64, len(indices))
for i, v := range indices {
vals[i] = int64(v)
}
idxbldr.AppendValues(vals, valid)
case *Uint8Builder:
vals := make([]uint8, len(indices))
for i, v := range indices {
vals[i] = uint8(v)
}
idxbldr.AppendValues(vals, valid)
case *Uint16Builder:
vals := make([]uint16, len(indices))
for i, v := range indices {
vals[i] = uint16(v)
}
idxbldr.AppendValues(vals, valid)
case *Uint32Builder:
vals := make([]uint32, len(indices))
for i, v := range indices {
vals[i] = uint32(v)
}
idxbldr.AppendValues(vals, valid)
case *Uint64Builder:
vals := make([]uint64, len(indices))
for i, v := range indices {
vals[i] = uint64(v)
}
idxbldr.AppendValues(vals, valid)
}
}
type NullDictionaryBuilder struct {
dictionaryBuilder
}
func (b *NullDictionaryBuilder) NewArray() arrow.Array {
return b.NewDictionaryArray()
}
func (b *NullDictionaryBuilder) NewDictionaryArray() *Dictionary {
idxarr := b.idxBuilder.NewArray()