forked from parquet-go/parquet-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
column_buffer.go
2451 lines (2035 loc) · 69.7 KB
/
column_buffer.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
package parquet
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/bits"
"reflect"
"sort"
"time"
"unsafe"
"github.com/parquet-go/parquet-go/deprecated"
"github.com/parquet-go/parquet-go/encoding/plain"
"github.com/parquet-go/parquet-go/internal/bitpack"
"github.com/parquet-go/parquet-go/internal/unsafecast"
"github.com/parquet-go/parquet-go/sparse"
)
// ColumnBuffer is an interface representing columns of a row group.
//
// ColumnBuffer implements sort.Interface as a way to support reordering the
// rows that have been written to it.
//
// The current implementation has a limitation which prevents applications from
// providing custom versions of this interface because it contains unexported
// methods. The only way to create ColumnBuffer values is to call the
// NewColumnBuffer of Type instances. This limitation may be lifted in future
// releases.
type ColumnBuffer interface {
// Exposes a read-only view of the column buffer.
ColumnChunk
// The column implements ValueReaderAt as a mechanism to read values at
// specific locations within the buffer.
ValueReaderAt
// The column implements ValueWriter as a mechanism to optimize the copy
// of values into the buffer in contexts where the row information is
// provided by the values because the repetition and definition levels
// are set.
ValueWriter
// For indexed columns, returns the underlying dictionary holding the column
// values. If the column is not indexed, nil is returned.
Dictionary() Dictionary
// Returns a copy of the column. The returned copy shares no memory with
// the original, mutations of either column will not modify the other.
Clone() ColumnBuffer
// Returns the column as a Page.
Page() Page
// Clears all rows written to the column.
Reset()
// Returns the current capacity of the column (rows).
Cap() int
// Returns the number of rows currently written to the column.
Len() int
// Compares rows at index i and j and reports whether i < j.
Less(i, j int) bool
// Swaps rows at index i and j.
Swap(i, j int)
// Returns the size of the column buffer in bytes.
Size() int64
// This method is employed to write rows from arrays of Go values into the
// column buffer. The method is currently unexported because it uses unsafe
// APIs which would be difficult for applications to leverage, increasing
// the risk of introducing bugs in the code. As a consequence, applications
// cannot use custom implementations of the ColumnBuffer interface since
// they cannot declare an unexported method that would match this signature.
// It means that in order to create a ColumnBuffer value, programs need to
// go through a call to NewColumnBuffer on a Type instance. We make this
// trade off for now as it is preferrable to optimize for safety over
// extensibility in the public APIs, we might revisit in the future if we
// learn about valid use cases for custom column buffer types.
writeValues(rows sparse.Array, levels columnLevels)
}
type columnLevels struct {
repetitionDepth byte
repetitionLevel byte
definitionLevel byte
}
func columnIndexOfNullable(base ColumnBuffer, maxDefinitionLevel byte, definitionLevels []byte) (ColumnIndex, error) {
index, err := base.ColumnIndex()
if err != nil {
return nil, err
}
return &nullableColumnIndex{
ColumnIndex: index,
maxDefinitionLevel: maxDefinitionLevel,
definitionLevels: definitionLevels,
}, nil
}
type nullableColumnIndex struct {
ColumnIndex
maxDefinitionLevel byte
definitionLevels []byte
}
func (index *nullableColumnIndex) NullPage(i int) bool {
return index.NullCount(i) == int64(len(index.definitionLevels))
}
func (index *nullableColumnIndex) NullCount(i int) int64 {
return int64(countLevelsNotEqual(index.definitionLevels, index.maxDefinitionLevel))
}
type nullOrdering func(column ColumnBuffer, i, j int, maxDefinitionLevel, definitionLevel1, definitionLevel2 byte) bool
func nullsGoFirst(column ColumnBuffer, i, j int, maxDefinitionLevel, definitionLevel1, definitionLevel2 byte) bool {
if definitionLevel1 != maxDefinitionLevel {
return definitionLevel2 == maxDefinitionLevel
} else {
return definitionLevel2 == maxDefinitionLevel && column.Less(i, j)
}
}
func nullsGoLast(column ColumnBuffer, i, j int, maxDefinitionLevel, definitionLevel1, definitionLevel2 byte) bool {
return definitionLevel1 == maxDefinitionLevel && (definitionLevel2 != maxDefinitionLevel || column.Less(i, j))
}
// reversedColumnBuffer is an adapter of ColumnBuffer which inverses the order
// in which rows are ordered when the column gets sorted.
//
// This type is used when buffers are constructed with sorting columns ordering
// values in descending order.
type reversedColumnBuffer struct{ ColumnBuffer }
func (col *reversedColumnBuffer) Less(i, j int) bool { return col.ColumnBuffer.Less(j, i) }
// optionalColumnBuffer is an implementation of the ColumnBuffer interface used
// as a wrapper to an underlying ColumnBuffer to manage the creation of
// definition levels.
//
// Null values are not written to the underlying column; instead, the buffer
// tracks offsets of row values in the column, null row values are represented
// by the value -1 and a definition level less than the max.
//
// This column buffer type is used for all leaf columns that have a non-zero
// max definition level and a zero repetition level, which may be because the
// column or one of its parent(s) are marked optional.
type optionalColumnBuffer struct {
base ColumnBuffer
reordered bool
maxDefinitionLevel byte
rows []int32
sortIndex []int32
definitionLevels []byte
nullOrdering nullOrdering
}
func newOptionalColumnBuffer(base ColumnBuffer, maxDefinitionLevel byte, nullOrdering nullOrdering) *optionalColumnBuffer {
n := base.Cap()
return &optionalColumnBuffer{
base: base,
maxDefinitionLevel: maxDefinitionLevel,
rows: make([]int32, 0, n),
definitionLevels: make([]byte, 0, n),
nullOrdering: nullOrdering,
}
}
func (col *optionalColumnBuffer) Clone() ColumnBuffer {
return &optionalColumnBuffer{
base: col.base.Clone(),
reordered: col.reordered,
maxDefinitionLevel: col.maxDefinitionLevel,
rows: append([]int32{}, col.rows...),
definitionLevels: append([]byte{}, col.definitionLevels...),
nullOrdering: col.nullOrdering,
}
}
func (col *optionalColumnBuffer) Type() Type {
return col.base.Type()
}
func (col *optionalColumnBuffer) NumValues() int64 {
return int64(len(col.definitionLevels))
}
func (col *optionalColumnBuffer) ColumnIndex() (ColumnIndex, error) {
return columnIndexOfNullable(col.base, col.maxDefinitionLevel, col.definitionLevels)
}
func (col *optionalColumnBuffer) OffsetIndex() (OffsetIndex, error) {
return col.base.OffsetIndex()
}
func (col *optionalColumnBuffer) BloomFilter() BloomFilter {
return col.base.BloomFilter()
}
func (col *optionalColumnBuffer) Dictionary() Dictionary {
return col.base.Dictionary()
}
func (col *optionalColumnBuffer) Column() int {
return col.base.Column()
}
func (col *optionalColumnBuffer) Pages() Pages {
return onePage(col.Page())
}
func (col *optionalColumnBuffer) Page() Page {
// No need for any cyclic sorting if the rows have not been reordered.
// This case is also important because the cyclic sorting modifies the
// buffer which makes it unsafe to read the buffer concurrently.
if col.reordered {
numNulls := countLevelsNotEqual(col.definitionLevels, col.maxDefinitionLevel)
numValues := len(col.rows) - numNulls
if numValues > 0 {
if cap(col.sortIndex) < numValues {
col.sortIndex = make([]int32, numValues)
}
sortIndex := col.sortIndex[:numValues]
i := 0
for _, j := range col.rows {
if j >= 0 {
sortIndex[j] = int32(i)
i++
}
}
// Cyclic sort: O(N)
for i := range sortIndex {
for j := int(sortIndex[i]); i != j; j = int(sortIndex[i]) {
col.base.Swap(i, j)
sortIndex[i], sortIndex[j] = sortIndex[j], sortIndex[i]
}
}
}
i := 0
for _, r := range col.rows {
if r >= 0 {
col.rows[i] = int32(i)
i++
}
}
col.reordered = false
}
return newOptionalPage(col.base.Page(), col.maxDefinitionLevel, col.definitionLevels)
}
func (col *optionalColumnBuffer) Reset() {
col.base.Reset()
col.rows = col.rows[:0]
col.definitionLevels = col.definitionLevels[:0]
}
func (col *optionalColumnBuffer) Size() int64 {
return int64(4*len(col.rows)+4*len(col.sortIndex)+len(col.definitionLevels)) + col.base.Size()
}
func (col *optionalColumnBuffer) Cap() int { return cap(col.rows) }
func (col *optionalColumnBuffer) Len() int { return len(col.rows) }
func (col *optionalColumnBuffer) Less(i, j int) bool {
return col.nullOrdering(
col.base,
int(col.rows[i]),
int(col.rows[j]),
col.maxDefinitionLevel,
col.definitionLevels[i],
col.definitionLevels[j],
)
}
func (col *optionalColumnBuffer) Swap(i, j int) {
// Because the underlying column does not contain null values, we cannot
// swap its values at indexes i and j. We swap the row indexes only, then
// reorder the underlying buffer using a cyclic sort when the buffer is
// materialized into a page view.
col.reordered = true
col.rows[i], col.rows[j] = col.rows[j], col.rows[i]
col.definitionLevels[i], col.definitionLevels[j] = col.definitionLevels[j], col.definitionLevels[i]
}
func (col *optionalColumnBuffer) WriteValues(values []Value) (n int, err error) {
rowIndex := int32(col.base.Len())
for n < len(values) {
// Collect index range of contiguous null values, from i to n. If this
// for loop exhausts the values, all remaining if statements and for
// loops will be no-ops and the loop will terminate.
i := n
for n < len(values) && values[n].definitionLevel != col.maxDefinitionLevel {
n++
}
// Write the contiguous null values up until the first non-null value
// obtained in the for loop above.
for _, v := range values[i:n] {
col.rows = append(col.rows, -1)
col.definitionLevels = append(col.definitionLevels, v.definitionLevel)
}
// Collect index range of contiguous non-null values, from i to n.
i = n
for n < len(values) && values[n].definitionLevel == col.maxDefinitionLevel {
n++
}
// As long as i < n we have non-null values still to write. It is
// possible that we just exhausted the input values in which case i == n
// and the outer for loop will terminate.
if i < n {
count, err := col.base.WriteValues(values[i:n])
col.definitionLevels = appendLevel(col.definitionLevels, col.maxDefinitionLevel, count)
for count > 0 {
col.rows = append(col.rows, rowIndex)
rowIndex++
count--
}
if err != nil {
return n, err
}
}
}
return n, nil
}
func (col *optionalColumnBuffer) writeValues(rows sparse.Array, levels columnLevels) {
// The row count is zero when writing an null optional value, in which case
// we still need to output a row to the buffer to record the definition
// level.
if rows.Len() == 0 {
col.definitionLevels = append(col.definitionLevels, levels.definitionLevel)
col.rows = append(col.rows, -1)
return
}
col.definitionLevels = appendLevel(col.definitionLevels, levels.definitionLevel, rows.Len())
i := len(col.rows)
j := len(col.rows) + rows.Len()
if j <= cap(col.rows) {
col.rows = col.rows[:j]
} else {
tmp := make([]int32, j, 2*j)
copy(tmp, col.rows)
col.rows = tmp
}
if levels.definitionLevel != col.maxDefinitionLevel {
broadcastValueInt32(col.rows[i:], -1)
} else {
broadcastRangeInt32(col.rows[i:], int32(col.base.Len()))
col.base.writeValues(rows, levels)
}
}
func (col *optionalColumnBuffer) ReadValuesAt(values []Value, offset int64) (int, error) {
length := int64(len(col.definitionLevels))
if offset < 0 {
return 0, errRowIndexOutOfBounds(offset, length)
}
if offset >= length {
return 0, io.EOF
}
if length -= offset; length < int64(len(values)) {
values = values[:length]
}
numNulls1 := int64(countLevelsNotEqual(col.definitionLevels[:offset], col.maxDefinitionLevel))
numNulls2 := int64(countLevelsNotEqual(col.definitionLevels[offset:offset+length], col.maxDefinitionLevel))
if numNulls2 < length {
n, err := col.base.ReadValuesAt(values[:length-numNulls2], offset-numNulls1)
if err != nil {
return n, err
}
}
if numNulls2 > 0 {
columnIndex := ^int16(col.Column())
i := numNulls2 - 1
j := length - 1
definitionLevels := col.definitionLevels[offset : offset+length]
maxDefinitionLevel := col.maxDefinitionLevel
for n := len(definitionLevels) - 1; n >= 0 && j > i; n-- {
if definitionLevels[n] != maxDefinitionLevel {
values[j] = Value{definitionLevel: definitionLevels[n], columnIndex: columnIndex}
} else {
values[j] = values[i]
i--
}
j--
}
}
return int(length), nil
}
// repeatedColumnBuffer is an implementation of the ColumnBuffer interface used
// as a wrapper to an underlying ColumnBuffer to manage the creation of
// repetition levels, definition levels, and map rows to the region of the
// underlying buffer that contains their sequence of values.
//
// Null values are not written to the underlying column; instead, the buffer
// tracks offsets of row values in the column, null row values are represented
// by the value -1 and a definition level less than the max.
//
// This column buffer type is used for all leaf columns that have a non-zero
// max repetition level, which may be because the column or one of its parent(s)
// are marked repeated.
type repeatedColumnBuffer struct {
base ColumnBuffer
reordered bool
maxRepetitionLevel byte
maxDefinitionLevel byte
rows []offsetMapping
repetitionLevels []byte
definitionLevels []byte
buffer []Value
reordering *repeatedColumnBuffer
nullOrdering nullOrdering
}
// The offsetMapping type maps the logical offset of rows within the repetition
// and definition levels, to the base offsets in the underlying column buffers
// where the non-null values have been written.
type offsetMapping struct {
offset uint32
baseOffset uint32
}
func newRepeatedColumnBuffer(base ColumnBuffer, maxRepetitionLevel, maxDefinitionLevel byte, nullOrdering nullOrdering) *repeatedColumnBuffer {
n := base.Cap()
return &repeatedColumnBuffer{
base: base,
maxRepetitionLevel: maxRepetitionLevel,
maxDefinitionLevel: maxDefinitionLevel,
rows: make([]offsetMapping, 0, n/8),
repetitionLevels: make([]byte, 0, n),
definitionLevels: make([]byte, 0, n),
nullOrdering: nullOrdering,
}
}
func (col *repeatedColumnBuffer) Clone() ColumnBuffer {
return &repeatedColumnBuffer{
base: col.base.Clone(),
reordered: col.reordered,
maxRepetitionLevel: col.maxRepetitionLevel,
maxDefinitionLevel: col.maxDefinitionLevel,
rows: append([]offsetMapping{}, col.rows...),
repetitionLevels: append([]byte{}, col.repetitionLevels...),
definitionLevels: append([]byte{}, col.definitionLevels...),
nullOrdering: col.nullOrdering,
}
}
func (col *repeatedColumnBuffer) Type() Type {
return col.base.Type()
}
func (col *repeatedColumnBuffer) NumValues() int64 {
return int64(len(col.definitionLevels))
}
func (col *repeatedColumnBuffer) ColumnIndex() (ColumnIndex, error) {
return columnIndexOfNullable(col.base, col.maxDefinitionLevel, col.definitionLevels)
}
func (col *repeatedColumnBuffer) OffsetIndex() (OffsetIndex, error) {
return col.base.OffsetIndex()
}
func (col *repeatedColumnBuffer) BloomFilter() BloomFilter {
return col.base.BloomFilter()
}
func (col *repeatedColumnBuffer) Dictionary() Dictionary {
return col.base.Dictionary()
}
func (col *repeatedColumnBuffer) Column() int {
return col.base.Column()
}
func (col *repeatedColumnBuffer) Pages() Pages {
return onePage(col.Page())
}
func (col *repeatedColumnBuffer) Page() Page {
if col.reordered {
if col.reordering == nil {
col.reordering = col.Clone().(*repeatedColumnBuffer)
}
column := col.reordering
column.Reset()
maxNumValues := 0
defer func() {
clearValues(col.buffer[:maxNumValues])
}()
baseOffset := 0
for _, row := range col.rows {
rowOffset := int(row.offset)
rowLength := repeatedRowLength(col.repetitionLevels[rowOffset:])
numNulls := countLevelsNotEqual(col.definitionLevels[rowOffset:rowOffset+rowLength], col.maxDefinitionLevel)
numValues := rowLength - numNulls
if numValues > 0 {
if numValues > cap(col.buffer) {
col.buffer = make([]Value, numValues)
} else {
col.buffer = col.buffer[:numValues]
}
n, err := col.base.ReadValuesAt(col.buffer, int64(row.baseOffset))
if err != nil && n < numValues {
return newErrorPage(col.Type(), col.Column(), "reordering rows of repeated column: %w", err)
}
if _, err := column.base.WriteValues(col.buffer); err != nil {
return newErrorPage(col.Type(), col.Column(), "reordering rows of repeated column: %w", err)
}
if numValues > maxNumValues {
maxNumValues = numValues
}
}
column.rows = append(column.rows, offsetMapping{
offset: uint32(len(column.repetitionLevels)),
baseOffset: uint32(baseOffset),
})
column.repetitionLevels = append(column.repetitionLevels, col.repetitionLevels[rowOffset:rowOffset+rowLength]...)
column.definitionLevels = append(column.definitionLevels, col.definitionLevels[rowOffset:rowOffset+rowLength]...)
baseOffset += numValues
}
col.swapReorderingBuffer(column)
col.reordered = false
}
return newRepeatedPage(
col.base.Page(),
col.maxRepetitionLevel,
col.maxDefinitionLevel,
col.repetitionLevels,
col.definitionLevels,
)
}
func (col *repeatedColumnBuffer) swapReorderingBuffer(buf *repeatedColumnBuffer) {
col.base, buf.base = buf.base, col.base
col.rows, buf.rows = buf.rows, col.rows
col.repetitionLevels, buf.repetitionLevels = buf.repetitionLevels, col.repetitionLevels
col.definitionLevels, buf.definitionLevels = buf.definitionLevels, col.definitionLevels
}
func (col *repeatedColumnBuffer) Reset() {
col.base.Reset()
col.rows = col.rows[:0]
col.repetitionLevels = col.repetitionLevels[:0]
col.definitionLevels = col.definitionLevels[:0]
}
func (col *repeatedColumnBuffer) Size() int64 {
return int64(8*len(col.rows)+len(col.repetitionLevels)+len(col.definitionLevels)) + col.base.Size()
}
func (col *repeatedColumnBuffer) Cap() int { return cap(col.rows) }
func (col *repeatedColumnBuffer) Len() int { return len(col.rows) }
func (col *repeatedColumnBuffer) Less(i, j int) bool {
row1 := col.rows[i]
row2 := col.rows[j]
less := col.nullOrdering
row1Length := repeatedRowLength(col.repetitionLevels[row1.offset:])
row2Length := repeatedRowLength(col.repetitionLevels[row2.offset:])
for k := 0; k < row1Length && k < row2Length; k++ {
x := int(row1.baseOffset)
y := int(row2.baseOffset)
definitionLevel1 := col.definitionLevels[int(row1.offset)+k]
definitionLevel2 := col.definitionLevels[int(row2.offset)+k]
switch {
case less(col.base, x, y, col.maxDefinitionLevel, definitionLevel1, definitionLevel2):
return true
case less(col.base, y, x, col.maxDefinitionLevel, definitionLevel2, definitionLevel1):
return false
}
}
return row1Length < row2Length
}
func (col *repeatedColumnBuffer) Swap(i, j int) {
// Because the underlying column does not contain null values, and may hold
// an arbitrary number of values per row, we cannot swap its values at
// indexes i and j. We swap the row indexes only, then reorder the base
// column buffer when its view is materialized into a page by creating a
// copy and writing rows back to it following the order of rows in the
// repeated column buffer.
col.reordered = true
col.rows[i], col.rows[j] = col.rows[j], col.rows[i]
}
func (col *repeatedColumnBuffer) WriteValues(values []Value) (numValues int, err error) {
maxRowLen := 0
defer func() {
clearValues(col.buffer[:maxRowLen])
}()
for i := 0; i < len(values); {
j := i
if values[j].repetitionLevel == 0 {
j++
}
for j < len(values) && values[j].repetitionLevel != 0 {
j++
}
if err := col.writeRow(values[i:j]); err != nil {
return numValues, err
}
if len(col.buffer) > maxRowLen {
maxRowLen = len(col.buffer)
}
numValues += j - i
i = j
}
return numValues, nil
}
func (col *repeatedColumnBuffer) writeRow(row []Value) error {
col.buffer = col.buffer[:0]
for _, v := range row {
if v.definitionLevel == col.maxDefinitionLevel {
col.buffer = append(col.buffer, v)
}
}
baseOffset := col.base.NumValues()
if len(col.buffer) > 0 {
if _, err := col.base.WriteValues(col.buffer); err != nil {
return err
}
}
if row[0].repetitionLevel == 0 {
col.rows = append(col.rows, offsetMapping{
offset: uint32(len(col.repetitionLevels)),
baseOffset: uint32(baseOffset),
})
}
for _, v := range row {
col.repetitionLevels = append(col.repetitionLevels, v.repetitionLevel)
col.definitionLevels = append(col.definitionLevels, v.definitionLevel)
}
return nil
}
func (col *repeatedColumnBuffer) writeValues(row sparse.Array, levels columnLevels) {
if levels.repetitionLevel == 0 {
col.rows = append(col.rows, offsetMapping{
offset: uint32(len(col.repetitionLevels)),
baseOffset: uint32(col.base.NumValues()),
})
}
if row.Len() == 0 {
col.repetitionLevels = append(col.repetitionLevels, levels.repetitionLevel)
col.definitionLevels = append(col.definitionLevels, levels.definitionLevel)
return
}
col.repetitionLevels = appendLevel(col.repetitionLevels, levels.repetitionLevel, row.Len())
col.definitionLevels = appendLevel(col.definitionLevels, levels.definitionLevel, row.Len())
if levels.definitionLevel == col.maxDefinitionLevel {
col.base.writeValues(row, levels)
}
}
func (col *repeatedColumnBuffer) ReadValuesAt(values []Value, offset int64) (int, error) {
// TODO:
panic("NOT IMPLEMENTED")
}
// repeatedRowLength gives the length of the repeated row starting at the
// beginning of the repetitionLevels slice.
func repeatedRowLength(repetitionLevels []byte) int {
// If a repetition level exists, at least one value is required to represent
// the column.
if len(repetitionLevels) > 0 {
// The subsequent levels will represent the start of a new record when
// they go back to zero.
if i := bytes.IndexByte(repetitionLevels[1:], 0); i >= 0 {
return i + 1
}
}
return len(repetitionLevels)
}
// =============================================================================
// The types below are in-memory implementations of the ColumnBuffer interface
// for each parquet type.
//
// These column buffers are created by calling NewColumnBuffer on parquet.Type
// instances; each parquet type manages to construct column buffers of the
// appropriate type, which ensures that we are packing as many values as we
// can in memory.
//
// See Type.NewColumnBuffer for details about how these types get created.
// =============================================================================
type booleanColumnBuffer struct{ booleanPage }
func newBooleanColumnBuffer(typ Type, columnIndex int16, numValues int32) *booleanColumnBuffer {
// Boolean values are bit-packed, we can fit up to 8 values per byte.
bufferSize := (numValues + 7) / 8
return &booleanColumnBuffer{
booleanPage: booleanPage{
typ: typ,
bits: make([]byte, 0, bufferSize),
columnIndex: ^columnIndex,
},
}
}
func (col *booleanColumnBuffer) Clone() ColumnBuffer {
return &booleanColumnBuffer{
booleanPage: booleanPage{
typ: col.typ,
bits: append([]byte{}, col.bits...),
offset: col.offset,
numValues: col.numValues,
columnIndex: col.columnIndex,
},
}
}
func (col *booleanColumnBuffer) ColumnIndex() (ColumnIndex, error) {
return booleanColumnIndex{&col.booleanPage}, nil
}
func (col *booleanColumnBuffer) OffsetIndex() (OffsetIndex, error) {
return booleanOffsetIndex{&col.booleanPage}, nil
}
func (col *booleanColumnBuffer) BloomFilter() BloomFilter { return nil }
func (col *booleanColumnBuffer) Dictionary() Dictionary { return nil }
func (col *booleanColumnBuffer) Pages() Pages { return onePage(col.Page()) }
func (col *booleanColumnBuffer) Page() Page { return &col.booleanPage }
func (col *booleanColumnBuffer) Reset() {
col.bits = col.bits[:0]
col.offset = 0
col.numValues = 0
}
func (col *booleanColumnBuffer) Cap() int { return 8 * cap(col.bits) }
func (col *booleanColumnBuffer) Len() int { return int(col.numValues) }
func (col *booleanColumnBuffer) Less(i, j int) bool {
a := col.valueAt(i)
b := col.valueAt(j)
return a != b && !a
}
func (col *booleanColumnBuffer) valueAt(i int) bool {
j := uint32(i) / 8
k := uint32(i) % 8
return ((col.bits[j] >> k) & 1) != 0
}
func (col *booleanColumnBuffer) setValueAt(i int, v bool) {
// `offset` is always zero in the page of a column buffer
j := uint32(i) / 8
k := uint32(i) % 8
x := byte(0)
if v {
x = 1
}
col.bits[j] = (col.bits[j] & ^(1 << k)) | (x << k)
}
func (col *booleanColumnBuffer) Swap(i, j int) {
a := col.valueAt(i)
b := col.valueAt(j)
col.setValueAt(i, b)
col.setValueAt(j, a)
}
func (col *booleanColumnBuffer) WriteBooleans(values []bool) (int, error) {
col.writeValues(sparse.MakeBoolArray(values).UnsafeArray(), columnLevels{})
return len(values), nil
}
func (col *booleanColumnBuffer) WriteValues(values []Value) (int, error) {
var model Value
col.writeValues(makeArrayValue(values, unsafe.Offsetof(model.u64)), columnLevels{})
return len(values), nil
}
func (col *booleanColumnBuffer) writeValues(rows sparse.Array, _ columnLevels) {
numBytes := bitpack.ByteCount(uint(col.numValues) + uint(rows.Len()))
if cap(col.bits) < numBytes {
col.bits = append(make([]byte, 0, max(numBytes, 2*cap(col.bits))), col.bits...)
}
col.bits = col.bits[:numBytes]
i := 0
r := 8 - (int(col.numValues) % 8)
bytes := rows.Uint8Array()
if r <= bytes.Len() {
// First we attempt to write enough bits to align the number of values
// in the column buffer on 8 bytes. After this step the next bit should
// be written at the zero'th index of a byte of the buffer.
if r < 8 {
var b byte
for i < r {
v := bytes.Index(i)
b |= (v & 1) << uint(i)
i++
}
x := uint(col.numValues) / 8
y := uint(col.numValues) % 8
col.bits[x] = (b << y) | (col.bits[x] & ^(0xFF << y))
col.numValues += int32(i)
}
if n := ((bytes.Len() - i) / 8) * 8; n > 0 {
// At this stage, we know that that we have at least 8 bits to write
// and the bits will be aligned on the address of a byte in the
// output buffer. We can work on 8 values per loop iteration,
// packing them into a single byte and writing it to the output
// buffer. This effectively reduces by 87.5% the number of memory
// stores that the program needs to perform to generate the values.
i += sparse.GatherBits(col.bits[col.numValues/8:], bytes.Slice(i, i+n))
col.numValues += int32(n)
}
}
for i < bytes.Len() {
x := uint(col.numValues) / 8
y := uint(col.numValues) % 8
b := bytes.Index(i)
col.bits[x] = ((b & 1) << y) | (col.bits[x] & ^(1 << y))
col.numValues++
i++
}
col.bits = col.bits[:bitpack.ByteCount(uint(col.numValues))]
}
func (col *booleanColumnBuffer) ReadValuesAt(values []Value, offset int64) (n int, err error) {
i := int(offset)
switch {
case i < 0:
return 0, errRowIndexOutOfBounds(offset, int64(col.numValues))
case i >= int(col.numValues):
return 0, io.EOF
default:
for n < len(values) && i < int(col.numValues) {
values[n] = col.makeValue(col.valueAt(i))
n++
i++
}
if n < len(values) {
err = io.EOF
}
return n, err
}
}
type int32ColumnBuffer struct{ int32Page }
func newInt32ColumnBuffer(typ Type, columnIndex int16, numValues int32) *int32ColumnBuffer {
return &int32ColumnBuffer{
int32Page: int32Page{
typ: typ,
values: make([]int32, 0, numValues),
columnIndex: ^columnIndex,
},
}
}
func (col *int32ColumnBuffer) Clone() ColumnBuffer {
return &int32ColumnBuffer{
int32Page: int32Page{
typ: col.typ,
values: append([]int32{}, col.values...),
columnIndex: col.columnIndex,
},
}
}
func (col *int32ColumnBuffer) ColumnIndex() (ColumnIndex, error) {
return int32ColumnIndex{&col.int32Page}, nil
}
func (col *int32ColumnBuffer) OffsetIndex() (OffsetIndex, error) {
return int32OffsetIndex{&col.int32Page}, nil
}
func (col *int32ColumnBuffer) BloomFilter() BloomFilter { return nil }
func (col *int32ColumnBuffer) Dictionary() Dictionary { return nil }
func (col *int32ColumnBuffer) Pages() Pages { return onePage(col.Page()) }
func (col *int32ColumnBuffer) Page() Page { return &col.int32Page }
func (col *int32ColumnBuffer) Reset() { col.values = col.values[:0] }
func (col *int32ColumnBuffer) Cap() int { return cap(col.values) }
func (col *int32ColumnBuffer) Len() int { return len(col.values) }
func (col *int32ColumnBuffer) Less(i, j int) bool { return col.values[i] < col.values[j] }
func (col *int32ColumnBuffer) Swap(i, j int) {
col.values[i], col.values[j] = col.values[j], col.values[i]
}
func (col *int32ColumnBuffer) Write(b []byte) (int, error) {
if (len(b) % 4) != 0 {
return 0, fmt.Errorf("cannot write INT32 values from input of size %d", len(b))
}
col.values = append(col.values, unsafecast.Slice[int32](b)...)
return len(b), nil
}
func (col *int32ColumnBuffer) WriteInt32s(values []int32) (int, error) {
col.values = append(col.values, values...)
return len(values), nil
}
func (col *int32ColumnBuffer) WriteValues(values []Value) (int, error) {
var model Value
col.writeValues(makeArrayValue(values, unsafe.Offsetof(model.u64)), columnLevels{})
return len(values), nil
}
func (col *int32ColumnBuffer) writeValues(rows sparse.Array, _ columnLevels) {
if n := len(col.values) + rows.Len(); n > cap(col.values) {
col.values = append(make([]int32, 0, max(n, 2*cap(col.values))), col.values...)
}
n := len(col.values)
col.values = col.values[:n+rows.Len()]
sparse.GatherInt32(col.values[n:], rows.Int32Array())
}
func (col *int32ColumnBuffer) ReadValuesAt(values []Value, offset int64) (n int, err error) {
i := int(offset)
switch {
case i < 0:
return 0, errRowIndexOutOfBounds(offset, int64(len(col.values)))
case i >= len(col.values):
return 0, io.EOF
default:
for n < len(values) && i < len(col.values) {
values[n] = col.makeValue(col.values[i])
n++
i++
}
if n < len(values) {
err = io.EOF