You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/08/01 19:40:05 UTC
[GitHub] [arrow] zeroshade opened a new pull request, #13768: ARROW-3678: [Go] Implement Union Arrays
zeroshade opened a new pull request, #13768:
URL: https://github.com/apache/arrow/pull/13768
Does not include enabling them in IPC yet, will do that in a subsequent change as this one is large enough already.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937000975
##########
go/arrow/datatype_nested.go:
##########
@@ -329,6 +333,208 @@ func (t *MapType) Layout() DataTypeLayout {
return t.value.Layout()
}
+type (
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+type UnionType interface {
+ NestedType
+ Mode() UnionMode
+ ChildIDs() []int
+ TypeCodes() []UnionTypeCode
Review Comment:
Added comments along with an example
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936715424
##########
go/arrow/array/union_test.go:
##########
@@ -0,0 +1,952 @@
+// 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_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/apache/arrow/go/v9/arrow"
+ "github.com/apache/arrow/go/v9/arrow/array"
+ "github.com/apache/arrow/go/v9/arrow/memory"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/suite"
+)
+
+func uint8ArrFromSlice(ids ...uint8) arrow.Array {
+ data := array.NewData(arrow.PrimitiveTypes.Uint8, len(ids),
+ []*memory.Buffer{nil, memory.NewBufferBytes(arrow.Uint8Traits.CastToBytes(ids))}, nil, 0, 0)
+ defer data.Release()
+ return array.MakeFromData(data)
+}
+
+func int32ArrFromSlice(offsets ...int32) arrow.Array {
+ data := array.NewData(arrow.PrimitiveTypes.Int32, len(offsets),
+ []*memory.Buffer{nil, memory.NewBufferBytes(arrow.Int32Traits.CastToBytes(offsets))}, nil, 0, 0)
+ defer data.Release()
+ return array.MakeFromData(data)
+}
+
+func TestUnionSliceEquals(t *testing.T) {
+ unionFields := []arrow.Field{
+ {Name: "u0", Type: arrow.PrimitiveTypes.Int32, Nullable: true},
+ {Name: "u1", Type: arrow.PrimitiveTypes.Uint8, Nullable: true},
+ }
+
+ typeCodes := []arrow.UnionTypeCode{5, 10}
+ sparseType := arrow.SparseUnionOf(unionFields, typeCodes)
+ denseType := arrow.DenseUnionOf(unionFields, typeCodes)
+
+ schema := arrow.NewSchema([]arrow.Field{
+ {Name: "sparse", Type: sparseType, Nullable: true},
+ {Name: "dense", Type: denseType, Nullable: true},
+ }, nil)
+
+ sparseChildren := make([]arrow.Array, 2)
+ denseChildren := make([]arrow.Array, 2)
+
+ const length = 7
+
+ typeIDsBuffer := memory.NewBufferBytes(arrow.Uint8Traits.CastToBytes([]uint8{5, 10, 5, 5, 10, 10, 5}))
+ sparseChildren[0] = int32ArrFromSlice(0, 1, 2, 3, 4, 5, 6)
+ defer sparseChildren[0].Release()
+ sparseChildren[1] = uint8ArrFromSlice(10, 11, 12, 13, 14, 15, 16)
+ defer sparseChildren[1].Release()
+
+ denseChildren[0] = int32ArrFromSlice(0, 2, 3, 7)
+ defer denseChildren[0].Release()
+ denseChildren[1] = uint8ArrFromSlice(11, 14, 15)
+ defer denseChildren[1].Release()
+
+ offsetsBuffer := memory.NewBufferBytes(arrow.Int32Traits.CastToBytes([]int32{0, 0, 1, 2, 1, 2, 3}))
+ sparse := array.NewSparseUnion(sparseType, length, sparseChildren, typeIDsBuffer, 0)
+ dense := array.NewDenseUnion(denseType, length, denseChildren, typeIDsBuffer, offsetsBuffer, 0)
+
+ defer sparse.Release()
+ defer dense.Release()
+
+ batch := array.NewRecord(schema, []arrow.Array{sparse, dense}, -1)
+ defer batch.Release()
+
+ checkUnion := func(arr arrow.Array) {
+ size := arr.Len()
+ slice := array.NewSlice(arr, 2, int64(size))
+ defer slice.Release()
+ assert.EqualValues(t, size-2, slice.Len())
+
+ slice2 := array.NewSlice(arr, 2, int64(arr.Len()))
+ defer slice2.Release()
+ assert.EqualValues(t, size-2, slice2.Len())
+
+ assert.True(t, array.Equal(slice, slice2))
Review Comment:
Yea, the tests in `compare_test.go` explicitly take two offset slices and verify they do not compare as equal. (see line 49 of `compare_test.go`)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936710364
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
Interesting, I only copied the C++ implementation versions of `alignedBitmapOp` and `unalignedBitmapOp`. I'll add a benchmark for this and see what I discover
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
pitrou commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937551293
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
Well, I took a look at the C++ benchmark, and it's actually limited by the popcount that's done at the end :-)
If I remove the popcount I get this:
```
BenchmarkBitmapAnd/32768/0 732 ns 732 ns 967465 bytes_per_second=41.6736G/s
BenchmarkBitmapAnd/131072/0 3105 ns 3105 ns 229726 bytes_per_second=39.3198G/s
BenchmarkBitmapAnd/32768/1 2913 ns 2913 ns 240233 bytes_per_second=10.4774G/s
BenchmarkBitmapAnd/131072/1 11528 ns 11526 ns 60865 bytes_per_second=10.5912G/s
BenchmarkBitmapAnd/32768/2 2924 ns 2924 ns 236873 bytes_per_second=10.4378G/s
BenchmarkBitmapAnd/131072/2 11552 ns 11550 ns 60619 bytes_per_second=10.5691G/s
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936711858
##########
go/arrow/internal/arrdata/arrdata.go:
##########
@@ -49,6 +49,7 @@ func init() {
Records["decimal128"] = makeDecimal128sRecords()
Records["maps"] = makeMapsRecords()
Records["extension"] = makeExtensionRecords()
+ // Records["union"] = makeUnionRecords()
Review Comment:
Yea, the subsequent change after this uncomments that after I add support for the JSON / IPC handling of unions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936849193
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
Before:
```
goos: linux
goarch: amd64
pkg: github.com/apache/arrow/go/v10/arrow/bitutil
cpu: 12th Gen Intel(R) Core(TM) i7-12700H
BenchmarkBitmapAnd/nbytes=32768/aligned-20 25418 48190 ns/op 1359.95 MB/s 0 B/op 0 allocs/op
BenchmarkBitmapAnd/nbytes=32768/unaligned-20 29241 40694 ns/op 1610.46 MB/s 192 B/op 3 allocs/op
BenchmarkBitmapAnd/nbytes=131072/aligned-20 6798 194915 ns/op 1344.91 MB/s 0 B/op 0 allocs/op
BenchmarkBitmapAnd/nbytes=131072/unaligned-20 7018 162163 ns/op 1616.55 MB/s 192 B/op 3 allocs/op
```
After:
```
goos: linux
goarch: amd64
pkg: github.com/apache/arrow/go/v10/arrow/bitutil
cpu: 12th Gen Intel(R) Core(TM) i7-12700H
BenchmarkBitmapAnd/nbytes=32768/aligned-20 126613 9308 ns/op 7040.73 MB/s 0 B/op 0 allocs/op
BenchmarkBitmapAnd/nbytes=32768/unaligned-20 28724 41392 ns/op 1583.30 MB/s 192 B/op 3 allocs/op
BenchmarkBitmapAnd/nbytes=131072/aligned-20 32292 37420 ns/op 7005.50 MB/s 0 B/op 0 allocs/op
BenchmarkBitmapAnd/nbytes=131072/unaligned-20 7068 166973 ns/op 1569.97 MB/s 192 B/op 3 allocs/op
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
pitrou commented on PR #13768:
URL: https://github.com/apache/arrow/pull/13768#issuecomment-1205002657
Uh, it looks like AppVeyor is complaining for an unrelated issue.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
pitrou commented on PR #13768:
URL: https://github.com/apache/arrow/pull/13768#issuecomment-1205284404
@raceordie690 @wolfeidau Perhaps you can give this a review as well?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] github-actions[bot] commented on pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #13768:
URL: https://github.com/apache/arrow/pull/13768#issuecomment-1201633310
https://issues.apache.org/jira/browse/ARROW-3678
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
pitrou commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936630672
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
Is this works word-wise, might it actually be faster than `alignedBitmapOp` which only works byte-wise?
##########
go/arrow/array/union.go:
##########
@@ -0,0 +1,1118 @@
+// 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"
+ "reflect"
+ "strings"
+ "sync/atomic"
+
+ "github.com/apache/arrow/go/v9/arrow"
+ "github.com/apache/arrow/go/v9/arrow/bitutil"
+ "github.com/apache/arrow/go/v9/arrow/internal/debug"
+ "github.com/apache/arrow/go/v9/arrow/memory"
+ "github.com/apache/arrow/go/v9/internal/bitutils"
+ "github.com/goccy/go-json"
+)
+
+type Union interface {
+ arrow.Array
+ Validate() error
+ ValidateFull() error
+ TypeCodes() *memory.Buffer
+ RawTypeCodes() []arrow.UnionTypeCode
+ TypeCode(i int) arrow.UnionTypeCode
+ ChildID(i int) int
+ UnionType() arrow.UnionType
+ Mode() arrow.UnionMode
+ Field(pos int) arrow.Array
+}
+
+const kMaxElems = math.MaxInt32
+
+type union struct {
+ array
+
+ unionType arrow.UnionType
+ typecodes []arrow.UnionTypeCode
+
+ children []arrow.Array
+}
+
+func (a *union) Retain() {
+ a.array.Retain()
+ for _, c := range a.children {
+ c.Retain()
+ }
+}
+
+func (a *union) Release() {
+ a.array.Release()
+ for _, c := range a.children {
+ c.Release()
+ }
+}
+
+func (a *union) NumFields() int { return len(a.unionType.Fields()) }
+
+func (a *union) Mode() arrow.UnionMode { return a.unionType.Mode() }
+
+func (a *union) UnionType() arrow.UnionType { return a.unionType }
+
+func (a *union) TypeCodes() *memory.Buffer {
+ return a.data.buffers[1]
+}
+
+func (a *union) RawTypeCodes() []arrow.UnionTypeCode {
+ if a.data.length > 0 {
+ return a.typecodes[a.data.offset:]
+ }
+ return []arrow.UnionTypeCode{}
+}
+
+func (a *union) TypeCode(i int) arrow.UnionTypeCode {
+ return a.typecodes[i+a.data.offset]
+}
+
+func (a *union) ChildID(i int) int {
+ return a.unionType.ChildIDs()[a.typecodes[i+a.data.offset]]
+}
+
+func (a *union) setData(data *Data) {
+ a.unionType = data.dtype.(arrow.UnionType)
+ debug.Assert(len(data.buffers) >= 2, "arrow/array: invalid number of union array buffers")
+
+ if data.length > 0 {
+ a.typecodes = arrow.Int8Traits.CastFromBytes(data.buffers[1].Bytes())
+ } else {
+ a.typecodes = []int8{}
+ }
+ a.children = make([]arrow.Array, len(data.childData))
+ for i, child := range data.childData {
+ if a.unionType.Mode() == arrow.SparseMode && (data.offset != 0 || child.Len() != data.length) {
+ child = NewSliceData(child, int64(data.offset), int64(data.offset+data.length))
+ defer child.Release()
+ }
+ a.children[i] = MakeFromData(child)
+ }
+ a.array.setData(data)
+}
+
+func (a *union) Field(pos int) (result arrow.Array) {
+ if pos < 0 || pos >= len(a.children) {
+ return nil
+ }
+
+ return a.children[pos]
+}
+
+func (a *union) Validate() error {
+ fields := a.unionType.Fields()
+ for i, f := range fields {
+ fieldData := a.data.childData[i]
+ if a.unionType.Mode() == arrow.SparseMode && fieldData.Len() < a.data.length+a.data.offset {
+ return fmt.Errorf("arrow/array: sparse union child array #%d has length smaller than expected for union array (%d < %d)",
+ i, fieldData.Len(), a.data.length+a.data.offset)
+ }
+
+ if !arrow.TypeEqual(f.Type, fieldData.DataType()) {
+ return fmt.Errorf("arrow/array: union child array #%d does not match type field %s vs %s",
+ i, fieldData.DataType(), f.Type)
+ }
+ }
+ return nil
+}
+
+func (a *union) ValidateFull() error {
+ if err := a.Validate(); err != nil {
+ return err
+ }
+
+ childIDs := a.unionType.ChildIDs()
+ codesMap := a.unionType.TypeCodes()
+ codes := a.RawTypeCodes()
+
+ for i := 0; i < a.data.length; i++ {
+ code := codes[i]
+ if code < 0 || childIDs[code] == arrow.InvalidUnionChildID {
+ return fmt.Errorf("arrow/array: union value at position %d has invalid type id %d", i, code)
+ }
+ }
+
+ if a.unionType.Mode() == arrow.DenseMode {
+ // validate offsets
+
+ // map logical typeid to child length
+ var childLengths [256]int64
+ for i := range a.unionType.Fields() {
+ childLengths[codesMap[i]] = int64(a.data.childData[i].Len())
+ }
+
+ // check offsets are in bounds
+ var lastOffsets [256]int64
+ offsets := arrow.Int32Traits.CastFromBytes(a.data.buffers[2].Bytes())[a.data.offset:]
+ for i := int64(0); i < int64(a.data.length); i++ {
+ code := codes[i]
+ offset := offsets[i]
+ switch {
+ case offset < 0:
+ return fmt.Errorf("arrow/array: union value at position %d has negative offset %d", i, offset)
+ case offset >= int32(childLengths[code]):
+ return fmt.Errorf("arrow/array: union value at position %d has offset larger than child length (%d >= %d)",
+ i, offset, childLengths[code])
+ case offset < int32(lastOffsets[code]):
+ return fmt.Errorf("arrow/array: union value at position %d has non-monotonic offset %d", i, offset)
+ }
+ lastOffsets[code] = int64(offset)
+ }
+ }
+
+ return nil
+}
+
+type SparseUnion struct {
+ union
+}
+
+func NewSparseUnion(dt *arrow.SparseUnionType, length int, children []arrow.Array, typeIDs *memory.Buffer, offset int) *SparseUnion {
+ childData := make([]arrow.ArrayData, len(children))
+ for i, c := range children {
+ childData[i] = c.Data()
+ }
+ data := NewData(dt, length, []*memory.Buffer{nil, typeIDs}, childData, 0, offset)
+ defer data.Release()
+ return NewSparseUnionData(data)
+}
+
+func NewSparseUnionData(data arrow.ArrayData) *SparseUnion {
+ a := &SparseUnion{}
+ a.refCount = 1
+ a.setData(data.(*Data))
+ return a
+}
+
+func NewSparseUnionFromArrays(typeIDs arrow.Array, children []arrow.Array, codes ...arrow.UnionTypeCode) (*SparseUnion, error) {
+ return NewSparseUnionFromArraysWithFieldCodes(typeIDs, children, []string{}, codes)
+}
+
+func NewSparseUnionFromArraysWithFields(typeIDs arrow.Array, children []arrow.Array, fields []string) (*SparseUnion, error) {
+ return NewSparseUnionFromArraysWithFieldCodes(typeIDs, children, fields, []arrow.UnionTypeCode{})
+}
+
+func NewSparseUnionFromArraysWithFieldCodes(typeIDs arrow.Array, children []arrow.Array, fields []string, codes []arrow.UnionTypeCode) (*SparseUnion, error) {
+ switch {
+ case typeIDs.DataType().ID() != arrow.INT8:
+ return nil, errors.New("arrow/array: union array type ids must be signed int8")
+ case typeIDs.NullN() != 0:
+ return nil, errors.New("arrow/array: union type ids may not have nulls")
+ case len(fields) > 0 && len(fields) != len(children):
+ return nil, errors.New("arrow/array: field names must have the same length as children")
+ case len(codes) > 0 && len(codes) != len(children):
+ return nil, errors.New("arrow/array: type codes must have same length as children")
+ }
+
+ buffers := []*memory.Buffer{nil, typeIDs.Data().Buffers()[1]}
+ ty := arrow.SparseUnionFromArrays(children, fields, codes)
+
+ childData := make([]arrow.ArrayData, len(children))
+ for i, c := range children {
+ childData[i] = c.Data()
+ if c.Len() != typeIDs.Len() {
+ return nil, errors.New("arrow/array: sparse union array must have len(child) == len(typeids) for all children")
+ }
+ }
+
+ data := NewData(ty, typeIDs.Len(), buffers, childData, 0, typeIDs.Data().Offset())
+ defer data.Release()
+ return NewSparseUnionData(data), nil
+}
+
+func (a *SparseUnion) setData(data *Data) {
+ a.union.setData(data)
+ debug.Assert(a.data.dtype.ID() == arrow.SPARSE_UNION, "arrow/array: invalid data type for SparseUnion")
+ debug.Assert(len(a.data.buffers) == 2, "arrow/array: sparse unions should have exactly 2 buffers")
+ debug.Assert(a.data.buffers[0] == nil, "arrow/array: validity bitmap for sparse unions should be nil")
+}
+
+func (a *SparseUnion) getOneForMarshal(i int) interface{} {
+ childID := a.ChildID(i)
+ field := a.unionType.Fields()[childID]
+ data := a.Field(childID)
+
+ if data.IsNull(i) {
+ return nil
+ }
+
+ return map[string]interface{}{field.Name: data.(arraymarshal).getOneForMarshal(i)}
+}
+
+func (a *SparseUnion) MarshalJSON() ([]byte, error) {
+ var buf bytes.Buffer
+ enc := json.NewEncoder(&buf)
+
+ buf.WriteByte('[')
+ for i := 0; i < a.Len(); i++ {
+ if i != 0 {
+ buf.WriteByte(',')
+ }
+ if err := enc.Encode(a.getOneForMarshal(i)); err != nil {
+ return nil, err
+ }
+ }
+ buf.WriteByte(']')
+ return buf.Bytes(), nil
+}
+
+func (a *SparseUnion) String() string {
+ var b strings.Builder
+ b.WriteByte('[')
+
+ fieldList := a.unionType.Fields()
+ for i := 0; i < a.Len(); i++ {
+ if i > 0 {
+ b.WriteString(" ")
+ }
+
+ field := fieldList[a.ChildID(i)]
+ f := a.Field(a.ChildID(i))
+ fmt.Fprintf(&b, "{%s=%v}", field.Name, f.(arraymarshal).getOneForMarshal(i))
+ }
+ b.WriteByte(']')
+ return b.String()
+}
+
+func (a *SparseUnion) GetFlattenedField(mem memory.Allocator, index int) (arrow.Array, error) {
+ if index < 0 || index >= a.NumFields() {
+ return nil, fmt.Errorf("arrow/array: index out of range: %d", index)
+ }
+
+ childData := a.data.childData[index]
+ if a.data.offset != 0 || a.data.length != childData.Len() {
+ childData = NewSliceData(childData, int64(a.data.offset), int64(a.data.offset+a.data.length))
+ // NewSliceData doesn't break the slice reference for buffers
+ // since we're going to replace the null bitmap buffer we need to break the
+ // slice reference so that we don't affect a.children's references
+ newBufs := make([]*memory.Buffer, len(childData.Buffers()))
+ copy(newBufs, childData.(*Data).buffers)
+ childData.(*Data).buffers = newBufs
+ } else {
+ childData = childData.(*Data).Copy()
+ }
+ defer childData.Release()
+
+ // synthesize a null bitmap based on the union discriminant
+ // make sure hte bitmap has extra bits corresponding to the child's offset
Review Comment:
```suggestion
// make sure the bitmap has extra bits corresponding to the child's offset
```
##########
go/arrow/internal/arrdata/arrdata.go:
##########
@@ -49,6 +49,7 @@ func init() {
Records["decimal128"] = makeDecimal128sRecords()
Records["maps"] = makeMapsRecords()
Records["extension"] = makeExtensionRecords()
+ // Records["union"] = makeUnionRecords()
Review Comment:
Is this supposed to be uncommented at some point?
##########
go/arrow/array/union.go:
##########
@@ -0,0 +1,1118 @@
+// 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"
+ "reflect"
+ "strings"
+ "sync/atomic"
+
+ "github.com/apache/arrow/go/v9/arrow"
+ "github.com/apache/arrow/go/v9/arrow/bitutil"
+ "github.com/apache/arrow/go/v9/arrow/internal/debug"
+ "github.com/apache/arrow/go/v9/arrow/memory"
+ "github.com/apache/arrow/go/v9/internal/bitutils"
+ "github.com/goccy/go-json"
+)
+
+type Union interface {
+ arrow.Array
+ Validate() error
+ ValidateFull() error
+ TypeCodes() *memory.Buffer
+ RawTypeCodes() []arrow.UnionTypeCode
+ TypeCode(i int) arrow.UnionTypeCode
+ ChildID(i int) int
+ UnionType() arrow.UnionType
+ Mode() arrow.UnionMode
+ Field(pos int) arrow.Array
+}
+
+const kMaxElems = math.MaxInt32
+
+type union struct {
+ array
+
+ unionType arrow.UnionType
+ typecodes []arrow.UnionTypeCode
+
+ children []arrow.Array
+}
+
+func (a *union) Retain() {
+ a.array.Retain()
+ for _, c := range a.children {
+ c.Retain()
+ }
+}
+
+func (a *union) Release() {
+ a.array.Release()
+ for _, c := range a.children {
+ c.Release()
+ }
+}
+
+func (a *union) NumFields() int { return len(a.unionType.Fields()) }
+
+func (a *union) Mode() arrow.UnionMode { return a.unionType.Mode() }
+
+func (a *union) UnionType() arrow.UnionType { return a.unionType }
+
+func (a *union) TypeCodes() *memory.Buffer {
+ return a.data.buffers[1]
+}
+
+func (a *union) RawTypeCodes() []arrow.UnionTypeCode {
+ if a.data.length > 0 {
+ return a.typecodes[a.data.offset:]
+ }
+ return []arrow.UnionTypeCode{}
+}
+
+func (a *union) TypeCode(i int) arrow.UnionTypeCode {
+ return a.typecodes[i+a.data.offset]
+}
+
+func (a *union) ChildID(i int) int {
+ return a.unionType.ChildIDs()[a.typecodes[i+a.data.offset]]
+}
+
+func (a *union) setData(data *Data) {
+ a.unionType = data.dtype.(arrow.UnionType)
+ debug.Assert(len(data.buffers) >= 2, "arrow/array: invalid number of union array buffers")
+
+ if data.length > 0 {
+ a.typecodes = arrow.Int8Traits.CastFromBytes(data.buffers[1].Bytes())
+ } else {
+ a.typecodes = []int8{}
+ }
+ a.children = make([]arrow.Array, len(data.childData))
+ for i, child := range data.childData {
+ if a.unionType.Mode() == arrow.SparseMode && (data.offset != 0 || child.Len() != data.length) {
+ child = NewSliceData(child, int64(data.offset), int64(data.offset+data.length))
+ defer child.Release()
+ }
+ a.children[i] = MakeFromData(child)
+ }
+ a.array.setData(data)
+}
+
+func (a *union) Field(pos int) (result arrow.Array) {
+ if pos < 0 || pos >= len(a.children) {
+ return nil
+ }
+
+ return a.children[pos]
+}
+
+func (a *union) Validate() error {
+ fields := a.unionType.Fields()
+ for i, f := range fields {
+ fieldData := a.data.childData[i]
+ if a.unionType.Mode() == arrow.SparseMode && fieldData.Len() < a.data.length+a.data.offset {
+ return fmt.Errorf("arrow/array: sparse union child array #%d has length smaller than expected for union array (%d < %d)",
+ i, fieldData.Len(), a.data.length+a.data.offset)
+ }
+
+ if !arrow.TypeEqual(f.Type, fieldData.DataType()) {
+ return fmt.Errorf("arrow/array: union child array #%d does not match type field %s vs %s",
+ i, fieldData.DataType(), f.Type)
+ }
+ }
+ return nil
+}
+
+func (a *union) ValidateFull() error {
+ if err := a.Validate(); err != nil {
+ return err
+ }
+
+ childIDs := a.unionType.ChildIDs()
+ codesMap := a.unionType.TypeCodes()
+ codes := a.RawTypeCodes()
+
+ for i := 0; i < a.data.length; i++ {
+ code := codes[i]
+ if code < 0 || childIDs[code] == arrow.InvalidUnionChildID {
+ return fmt.Errorf("arrow/array: union value at position %d has invalid type id %d", i, code)
+ }
+ }
+
+ if a.unionType.Mode() == arrow.DenseMode {
+ // validate offsets
+
+ // map logical typeid to child length
+ var childLengths [256]int64
+ for i := range a.unionType.Fields() {
+ childLengths[codesMap[i]] = int64(a.data.childData[i].Len())
+ }
+
+ // check offsets are in bounds
+ var lastOffsets [256]int64
+ offsets := arrow.Int32Traits.CastFromBytes(a.data.buffers[2].Bytes())[a.data.offset:]
+ for i := int64(0); i < int64(a.data.length); i++ {
+ code := codes[i]
+ offset := offsets[i]
+ switch {
+ case offset < 0:
+ return fmt.Errorf("arrow/array: union value at position %d has negative offset %d", i, offset)
+ case offset >= int32(childLengths[code]):
+ return fmt.Errorf("arrow/array: union value at position %d has offset larger than child length (%d >= %d)",
+ i, offset, childLengths[code])
+ case offset < int32(lastOffsets[code]):
+ return fmt.Errorf("arrow/array: union value at position %d has non-monotonic offset %d", i, offset)
+ }
+ lastOffsets[code] = int64(offset)
+ }
+ }
+
+ return nil
+}
+
+type SparseUnion struct {
+ union
+}
+
+func NewSparseUnion(dt *arrow.SparseUnionType, length int, children []arrow.Array, typeIDs *memory.Buffer, offset int) *SparseUnion {
+ childData := make([]arrow.ArrayData, len(children))
+ for i, c := range children {
+ childData[i] = c.Data()
+ }
+ data := NewData(dt, length, []*memory.Buffer{nil, typeIDs}, childData, 0, offset)
+ defer data.Release()
+ return NewSparseUnionData(data)
+}
+
+func NewSparseUnionData(data arrow.ArrayData) *SparseUnion {
+ a := &SparseUnion{}
+ a.refCount = 1
+ a.setData(data.(*Data))
+ return a
+}
+
+func NewSparseUnionFromArrays(typeIDs arrow.Array, children []arrow.Array, codes ...arrow.UnionTypeCode) (*SparseUnion, error) {
+ return NewSparseUnionFromArraysWithFieldCodes(typeIDs, children, []string{}, codes)
+}
+
+func NewSparseUnionFromArraysWithFields(typeIDs arrow.Array, children []arrow.Array, fields []string) (*SparseUnion, error) {
+ return NewSparseUnionFromArraysWithFieldCodes(typeIDs, children, fields, []arrow.UnionTypeCode{})
+}
+
+func NewSparseUnionFromArraysWithFieldCodes(typeIDs arrow.Array, children []arrow.Array, fields []string, codes []arrow.UnionTypeCode) (*SparseUnion, error) {
+ switch {
+ case typeIDs.DataType().ID() != arrow.INT8:
+ return nil, errors.New("arrow/array: union array type ids must be signed int8")
+ case typeIDs.NullN() != 0:
+ return nil, errors.New("arrow/array: union type ids may not have nulls")
+ case len(fields) > 0 && len(fields) != len(children):
+ return nil, errors.New("arrow/array: field names must have the same length as children")
+ case len(codes) > 0 && len(codes) != len(children):
+ return nil, errors.New("arrow/array: type codes must have same length as children")
+ }
+
+ buffers := []*memory.Buffer{nil, typeIDs.Data().Buffers()[1]}
+ ty := arrow.SparseUnionFromArrays(children, fields, codes)
+
+ childData := make([]arrow.ArrayData, len(children))
+ for i, c := range children {
+ childData[i] = c.Data()
+ if c.Len() != typeIDs.Len() {
+ return nil, errors.New("arrow/array: sparse union array must have len(child) == len(typeids) for all children")
+ }
+ }
+
+ data := NewData(ty, typeIDs.Len(), buffers, childData, 0, typeIDs.Data().Offset())
+ defer data.Release()
+ return NewSparseUnionData(data), nil
+}
+
+func (a *SparseUnion) setData(data *Data) {
+ a.union.setData(data)
+ debug.Assert(a.data.dtype.ID() == arrow.SPARSE_UNION, "arrow/array: invalid data type for SparseUnion")
+ debug.Assert(len(a.data.buffers) == 2, "arrow/array: sparse unions should have exactly 2 buffers")
+ debug.Assert(a.data.buffers[0] == nil, "arrow/array: validity bitmap for sparse unions should be nil")
+}
+
+func (a *SparseUnion) getOneForMarshal(i int) interface{} {
+ childID := a.ChildID(i)
+ field := a.unionType.Fields()[childID]
+ data := a.Field(childID)
+
+ if data.IsNull(i) {
+ return nil
+ }
+
+ return map[string]interface{}{field.Name: data.(arraymarshal).getOneForMarshal(i)}
+}
+
+func (a *SparseUnion) MarshalJSON() ([]byte, error) {
+ var buf bytes.Buffer
+ enc := json.NewEncoder(&buf)
+
+ buf.WriteByte('[')
+ for i := 0; i < a.Len(); i++ {
+ if i != 0 {
+ buf.WriteByte(',')
+ }
+ if err := enc.Encode(a.getOneForMarshal(i)); err != nil {
+ return nil, err
+ }
+ }
+ buf.WriteByte(']')
+ return buf.Bytes(), nil
+}
+
+func (a *SparseUnion) String() string {
+ var b strings.Builder
+ b.WriteByte('[')
+
+ fieldList := a.unionType.Fields()
+ for i := 0; i < a.Len(); i++ {
+ if i > 0 {
+ b.WriteString(" ")
+ }
+
+ field := fieldList[a.ChildID(i)]
+ f := a.Field(a.ChildID(i))
+ fmt.Fprintf(&b, "{%s=%v}", field.Name, f.(arraymarshal).getOneForMarshal(i))
+ }
+ b.WriteByte(']')
+ return b.String()
+}
+
+func (a *SparseUnion) GetFlattenedField(mem memory.Allocator, index int) (arrow.Array, error) {
+ if index < 0 || index >= a.NumFields() {
+ return nil, fmt.Errorf("arrow/array: index out of range: %d", index)
+ }
+
+ childData := a.data.childData[index]
+ if a.data.offset != 0 || a.data.length != childData.Len() {
+ childData = NewSliceData(childData, int64(a.data.offset), int64(a.data.offset+a.data.length))
+ // NewSliceData doesn't break the slice reference for buffers
+ // since we're going to replace the null bitmap buffer we need to break the
+ // slice reference so that we don't affect a.children's references
+ newBufs := make([]*memory.Buffer, len(childData.Buffers()))
+ copy(newBufs, childData.(*Data).buffers)
+ childData.(*Data).buffers = newBufs
+ } else {
+ childData = childData.(*Data).Copy()
+ }
+ defer childData.Release()
+
+ // synthesize a null bitmap based on the union discriminant
+ // make sure hte bitmap has extra bits corresponding to the child's offset
+ flattenedNullBitmap := memory.NewResizableBuffer(mem)
+ flattenedNullBitmap.Resize(childData.Len() + childData.Offset())
+
+ var (
+ childNullBitmap = childData.Buffers()[0]
+ childOffset = childData.Offset()
+ typeCode = a.unionType.TypeCodes()[index]
+ codes = a.RawTypeCodes()
+ offset int64 = 0
+ )
+ bitutils.GenerateBitsUnrolled(flattenedNullBitmap.Bytes(), int64(childOffset), int64(a.data.length),
+ func() bool {
+ b := codes[offset] == typeCode
+ offset++
+ return b
+ })
+
+ if childNullBitmap != nil {
+ defer childNullBitmap.Release()
+ bitutil.BitmapAnd(flattenedNullBitmap.Bytes(), childNullBitmap.Bytes(),
+ int64(childOffset), int64(childOffset), flattenedNullBitmap.Bytes(),
+ int64(childOffset), int64(childData.Len()))
+ }
+ childData.(*Data).buffers[0] = flattenedNullBitmap
+ childData.(*Data).nulls = childData.Len() - bitutil.CountSetBits(flattenedNullBitmap.Bytes(), childOffset, childData.Len())
+ return MakeFromData(childData), nil
+}
+
+func arraySparseUnionEqual(l, r *SparseUnion) bool {
+ childIDs := l.unionType.ChildIDs()
+ leftCodes, rightCodes := l.RawTypeCodes(), r.RawTypeCodes()
+
+ for i := 0; i < l.data.length; i++ {
+ typeID := leftCodes[i]
+ if typeID != rightCodes[i] {
+ return false
+ }
+
+ childNum := childIDs[typeID]
+ eq := SliceEqual(l.children[childNum], int64(i), int64(i+1),
+ r.children[childNum], int64(i), int64(i+1))
+ if !eq {
+ return false
+ }
+ }
+ return true
+}
+
+func arraySparseUnionApproxEqual(l, r *SparseUnion, opt equalOption) bool {
+ childIDs := l.unionType.ChildIDs()
+ leftCodes, rightCodes := l.RawTypeCodes(), r.RawTypeCodes()
+
+ for i := 0; i < l.data.length; i++ {
+ typeID := leftCodes[i]
+ if typeID != rightCodes[i] {
+ return false
+ }
+
+ childNum := childIDs[typeID]
+ eq := sliceApproxEqual(l.children[childNum], int64(i+l.data.offset), int64(i+l.data.offset+1),
+ r.children[childNum], int64(i+r.data.offset), int64(i+r.data.offset+1), opt)
+ if !eq {
+ return false
+ }
+ }
+ return true
+}
+
+type DenseUnion struct {
+ union
+ offsets []int32
+}
+
+func NewDenseUnion(dt *arrow.DenseUnionType, length int, children []arrow.Array, typeIDs, valueOffsets *memory.Buffer, offset int) *DenseUnion {
+ childData := make([]arrow.ArrayData, len(children))
+ for i, c := range children {
+ childData[i] = c.Data()
+ }
+
+ data := NewData(dt, length, []*memory.Buffer{nil, typeIDs, valueOffsets}, childData, 0, offset)
+ defer data.Release()
+ return NewDenseUnionData(data)
+}
+
+func NewDenseUnionData(data arrow.ArrayData) *DenseUnion {
+ a := &DenseUnion{}
+ a.refCount = 1
+ a.setData(data.(*Data))
+ return a
+}
+
+func NewDenseUnionFromArrays(typeIDs, offsets arrow.Array, children []arrow.Array, codes ...arrow.UnionTypeCode) (*DenseUnion, error) {
+ return NewDenseUnionFromArraysWithFieldCodes(typeIDs, offsets, children, []string{}, codes)
+}
+
+func NewDenseUnionFromArraysWithFields(typeIDs, offsets arrow.Array, children []arrow.Array, fields []string) (*DenseUnion, error) {
+ return NewDenseUnionFromArraysWithFieldCodes(typeIDs, offsets, children, fields, []arrow.UnionTypeCode{})
+}
+
+func NewDenseUnionFromArraysWithFieldCodes(typeIDs, offsets arrow.Array, children []arrow.Array, fields []string, codes []arrow.UnionTypeCode) (*DenseUnion, error) {
+ switch {
+ case offsets.DataType().ID() != arrow.INT32:
+ return nil, errors.New("arrow/array: union offsets must be signed int32")
+ case typeIDs.DataType().ID() != arrow.INT8:
+ return nil, errors.New("arrow/array: union type_ids must be signed int8")
+ case typeIDs.NullN() != 0:
+ return nil, errors.New("arrow/array: union typeIDs may not have nulls")
+ case offsets.NullN() != 0:
+ return nil, errors.New("arrow/array: nulls are not allowed in offsets for NewDenseUnionFromArrays*")
+ case len(fields) > 0 && len(fields) != len(children):
+ return nil, errors.New("arrow/array: fields must be the same length as children")
+ case len(codes) > 0 && len(codes) != len(children):
+ return nil, errors.New("arrow/array: typecodes must have the same length as children")
+ }
+
+ ty := arrow.DenseUnionFromArrays(children, fields, codes)
+ buffers := []*memory.Buffer{nil, typeIDs.Data().Buffers()[1], offsets.Data().Buffers()[1]}
+
+ childData := make([]arrow.ArrayData, len(children))
+ for i, c := range children {
+ childData[i] = c.Data()
+ }
+
+ data := NewData(ty, typeIDs.Len(), buffers, childData, 0, typeIDs.Data().Offset())
+ defer data.Release()
+ return NewDenseUnionData(data), nil
+}
+
+func (a *DenseUnion) ValueOffsets() *memory.Buffer { return a.data.buffers[2] }
+
+func (a *DenseUnion) ValueOffset(i int) int32 { return a.offsets[i+a.data.offset] }
+
+func (a *DenseUnion) RawValueOffsets() []int32 { return a.offsets[a.data.offset:] }
+
+func (a *DenseUnion) setData(data *Data) {
+ a.union.setData(data)
+ debug.Assert(a.data.dtype.ID() == arrow.DENSE_UNION, "arrow/array: invalid data type for DenseUnion")
+ debug.Assert(len(a.data.buffers) == 3, "arrow/array: sparse unions should have exactly 3 buffers")
Review Comment:
```suggestion
debug.Assert(len(a.data.buffers) == 3, "arrow/array: dense unions should have exactly 3 buffers")
```
##########
go/arrow/array/fixed_size_list.go:
##########
@@ -196,6 +198,10 @@ func (b *FixedSizeListBuilder) AppendNull() {
b.unsafeAppendBoolToBitmap(false)
}
+func (b *FixedSizeListBuilder) AppendEmptyValue() {
+ b.Append(true)
Review Comment:
Hmmm... I don't see where it appends to the child array. Where does that happen?
##########
go/arrow/array/fixedsize_binarybuilder.go:
##########
@@ -81,6 +83,12 @@ func (b *FixedSizeBinaryBuilder) AppendNull() {
b.UnsafeAppendBoolToBitmap(false)
}
+func (b *FixedSizeBinaryBuilder) AppendEmptyValue() {
+ b.Reserve(1)
+ b.values.Advance(b.dtype.ByteWidth)
Review Comment:
Valgrind helps spotting undefined data, btw, though it needs specific exercising in the test suite.
##########
go/arrow/array/fixedsize_binarybuilder.go:
##########
@@ -81,6 +83,12 @@ func (b *FixedSizeBinaryBuilder) AppendNull() {
b.UnsafeAppendBoolToBitmap(false)
}
+func (b *FixedSizeBinaryBuilder) AppendEmptyValue() {
+ b.Reserve(1)
+ b.values.Advance(b.dtype.ByteWidth)
Review Comment:
Does it mean the values are undetermined? I don't know how you feel about this for the Go implementation, but in C++ we try to be careful not revealing past memory contents through Arrow buffers (because buffers can be send as-is over IPC).
##########
go/arrow/datatype_nested.go:
##########
@@ -329,6 +333,208 @@ func (t *MapType) Layout() DataTypeLayout {
return t.value.Layout()
}
+type (
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+type UnionType interface {
+ NestedType
+ Mode() UnionMode
+ ChildIDs() []int
+ TypeCodes() []UnionTypeCode
+ MaxTypeCode() UnionTypeCode
+}
+
+func UnionOf(mode UnionMode, fields []Field, typeCodes []UnionTypeCode) UnionType {
+ switch mode {
+ case SparseMode:
+ return SparseUnionOf(fields, typeCodes)
+ case DenseMode:
+ return DenseUnionOf(fields, typeCodes)
+ default:
+ panic("arrow: invalid union mode")
+ }
+}
+
+type unionType struct {
+ children []Field
+ typeCodes []UnionTypeCode
+ childIDs [int(MaxUnionTypeCode) + 1]int
+}
+
+func (t *unionType) init(fields []Field, typeCodes []UnionTypeCode) {
+ // initialize all child IDs to -1
+ t.childIDs[0] = InvalidUnionChildID
+ for i := 1; i < len(t.childIDs); i *= 2 {
+ copy(t.childIDs[i:], t.childIDs[:i])
+ }
+
+ t.children = fields
+ t.typeCodes = typeCodes
+
+ for i, tc := range t.typeCodes {
+ t.childIDs[tc] = i
+ }
+}
+
+func (t unionType) Fields() []Field { return t.children }
+func (t unionType) TypeCodes() []UnionTypeCode { return t.typeCodes }
+func (t unionType) ChildIDs() []int { return t.childIDs[:] }
+
+func (t *unionType) validate(fields []Field, typeCodes []UnionTypeCode, _ UnionMode) error {
+ if len(fields) != len(typeCodes) {
+ return errors.New("arrow: union types should have the same number of fields as type codes")
+ }
+
+ for _, c := range typeCodes {
+ if c < 0 || c > MaxUnionTypeCode {
+ return errors.New("arrow: union type code out of bounds")
+ }
+ }
+ return nil
+}
+
+func (t *unionType) MaxTypeCode() (max UnionTypeCode) {
+ if len(t.typeCodes) == 0 {
+ return
+ }
+
+ max = t.typeCodes[0]
+ for _, c := range t.typeCodes[1:] {
+ if c > max {
+ max = c
+ }
+ }
+ return
+}
+
+func (t *unionType) String() string {
+ var b strings.Builder
+ b.WriteByte('<')
+ for i := range t.typeCodes {
+ if i != 0 {
+ b.WriteString(", ")
+ }
+ fmt.Fprintf(&b, "%s=%d", t.children[i], t.typeCodes[i])
+ }
+ b.WriteByte('>')
+ return b.String()
+}
+
+func (t *unionType) fingerprint() string {
+ var b strings.Builder
+ for _, c := range t.typeCodes {
+ fmt.Fprintf(&b, ":%d", c)
+ }
+ b.WriteString("]{")
+ for _, c := range t.children {
+ fingerprint := c.Fingerprint()
+ if len(fingerprint) == 0 {
+ return ""
+ }
+ b.WriteString(fingerprint)
+ b.WriteByte(';')
+ }
+ b.WriteByte('}')
+ return b.String()
+}
+
+func fieldsFromArrays(arrays []Array, names ...string) (ret []Field) {
+ ret = make([]Field, len(arrays))
+ if len(names) == 0 {
+ for i, c := range arrays {
+ ret[i] = Field{Name: strconv.Itoa(i), Type: c.DataType(), Nullable: true}
+ }
+ } else {
+ debug.Assert(len(names) == len(arrays), "mismatch of arrays and names")
+ for i, c := range arrays {
+ ret[i] = Field{Name: names[i], Type: c.DataType(), Nullable: true}
+ }
+ }
+ return
+}
+
+type SparseUnionType struct {
+ unionType
+}
+
+func SparseUnionFromArrays(children []Array, fields []string, codes []UnionTypeCode) *SparseUnionType {
+ if len(codes) == 0 {
+ codes = make([]UnionTypeCode, len(children))
+ for i := range children {
+ codes[i] = UnionTypeCode(i)
+ }
+ }
+ return SparseUnionOf(fieldsFromArrays(children, fields...), codes)
+}
+
+func SparseUnionOf(fields []Field, typeCodes []UnionTypeCode) *SparseUnionType {
+ ret := &SparseUnionType{}
+ if err := ret.validate(fields, typeCodes, ret.Mode()); err != nil {
+ panic(err)
+ }
+ ret.init(fields, typeCodes)
+ return ret
+}
+
+func (SparseUnionType) ID() Type { return SPARSE_UNION }
+func (SparseUnionType) Name() string { return "sparse_union" }
+func (SparseUnionType) Mode() UnionMode { return SparseMode }
+func (t *SparseUnionType) Fingerprint() string {
+ return typeFingerprint(t) + "[s" + t.fingerprint()
+}
+func (SparseUnionType) Layout() DataTypeLayout {
+ return DataTypeLayout{Buffers: []BufferSpec{SpecAlwaysNull(), SpecFixedWidth(Uint8SizeBytes)}}
Review Comment:
So, this is the same implementation choice as C++. This means you'll have to be careful when implementing the IPC and C data interface sides (I assume you're already aware of this).
##########
go/arrow/bitutil/bitmaps_test.go:
##########
@@ -356,3 +358,119 @@ func BenchmarkBitmapReader(b *testing.B) {
}
})
}
+
+type bitmapOp struct {
+ noAlloc func(left, right []byte, lOffset, rOffset int64, out []byte, outOffset, length int64)
+ alloc func(mem memory.Allocator, left, right []byte, lOffset, rOffset int64, length, outOffset int64) *memory.Buffer
+}
+
+type BitmapOpSuite struct {
+ suite.Suite
+}
+
+func (s *BitmapOpSuite) testAligned(op bitmapOp, leftBits, rightBits []int, resultBits []bool) {
+ var (
+ left, right []byte
+ out *memory.Buffer
+ length int64
+ )
+ for _, lOffset := range []int64{0, 1, 3, 5, 7, 8, 13, 21, 38, 75, 120, 65536} {
+ s.Run(fmt.Sprintf("left offset %d", lOffset), func() {
+ left = bitmapFromSlice(leftBits, int(lOffset))
+ length = int64(len(leftBits))
+ for _, rOffset := range []int64{lOffset, lOffset + 8, lOffset + 40} {
+ s.Run(fmt.Sprintf("right offset %d", rOffset), func() {
+ right = bitmapFromSlice(rightBits, int(rOffset))
+ for _, outOffset := range []int64{lOffset, lOffset + 16, lOffset + 24} {
+ s.Run(fmt.Sprintf("out offset %d", outOffset), func() {
+ out = op.alloc(memory.DefaultAllocator, left, right, lOffset, rOffset, length, outOffset)
+ rdr := bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+
+ memory.Set(out.Bytes(), 0x00)
+ op.noAlloc(left, right, lOffset, rOffset, out.Bytes(), outOffset, length)
+ rdr = bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+ })
+ }
+ })
+ }
+ })
+ }
+}
+
+func (s *BitmapOpSuite) testUnaligned(op bitmapOp, leftBits, rightBits []int, resultBits []bool) {
+ var (
+ left, right []byte
+ out *memory.Buffer
+ length int64
+ offsets = []int64{0, 1, 3, 5, 7, 8, 13, 21, 38, 75, 120, 65536}
+ )
+
+ for _, lOffset := range offsets {
+ s.Run(fmt.Sprintf("left offset %d", lOffset), func() {
+ left = bitmapFromSlice(leftBits, int(lOffset))
+ length = int64(len(leftBits))
+ for _, rOffset := range offsets {
+ s.Run(fmt.Sprintf("right offset %d", rOffset), func() {
+ right = bitmapFromSlice(rightBits, int(rOffset))
+ for _, outOffset := range offsets {
+ s.Run(fmt.Sprintf("out offset %d", outOffset), func() {
+ s.Run("alloc", func() {
+ out = op.alloc(memory.DefaultAllocator, left, right, lOffset, rOffset, length, outOffset)
+ rdr := bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+ })
+ s.Run("noalloc", func() {
+ memory.Set(out.Bytes(), 0x00)
+ op.noAlloc(left, right, lOffset, rOffset, out.Bytes(), outOffset, length)
+ rdr := bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+ })
+ })
+ }
+ })
+ }
+ })
+ }
+}
+
+func (s *BitmapOpSuite) TestBitmapAnd() {
+ op := bitmapOp{
+ noAlloc: bitutil.BitmapAnd,
+ alloc: bitutil.BitmapAndAlloc,
+ }
+
+ leftBits := []int{0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1}
+ rightBits := []int{0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0}
+ resultBits := []bool{false, false, true, false, false, false, false, false, false, true, false, false, false, false}
Review Comment:
I would suggest to add tests with zero-length inputs as well.
##########
go/arrow/array/union_test.go:
##########
@@ -0,0 +1,952 @@
+// 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_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/apache/arrow/go/v9/arrow"
+ "github.com/apache/arrow/go/v9/arrow/array"
+ "github.com/apache/arrow/go/v9/arrow/memory"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/suite"
+)
+
+func uint8ArrFromSlice(ids ...uint8) arrow.Array {
+ data := array.NewData(arrow.PrimitiveTypes.Uint8, len(ids),
+ []*memory.Buffer{nil, memory.NewBufferBytes(arrow.Uint8Traits.CastToBytes(ids))}, nil, 0, 0)
+ defer data.Release()
+ return array.MakeFromData(data)
+}
+
+func int32ArrFromSlice(offsets ...int32) arrow.Array {
+ data := array.NewData(arrow.PrimitiveTypes.Int32, len(offsets),
+ []*memory.Buffer{nil, memory.NewBufferBytes(arrow.Int32Traits.CastToBytes(offsets))}, nil, 0, 0)
+ defer data.Release()
+ return array.MakeFromData(data)
+}
+
+func TestUnionSliceEquals(t *testing.T) {
+ unionFields := []arrow.Field{
+ {Name: "u0", Type: arrow.PrimitiveTypes.Int32, Nullable: true},
+ {Name: "u1", Type: arrow.PrimitiveTypes.Uint8, Nullable: true},
+ }
+
+ typeCodes := []arrow.UnionTypeCode{5, 10}
+ sparseType := arrow.SparseUnionOf(unionFields, typeCodes)
+ denseType := arrow.DenseUnionOf(unionFields, typeCodes)
+
+ schema := arrow.NewSchema([]arrow.Field{
+ {Name: "sparse", Type: sparseType, Nullable: true},
+ {Name: "dense", Type: denseType, Nullable: true},
+ }, nil)
+
+ sparseChildren := make([]arrow.Array, 2)
+ denseChildren := make([]arrow.Array, 2)
+
+ const length = 7
+
+ typeIDsBuffer := memory.NewBufferBytes(arrow.Uint8Traits.CastToBytes([]uint8{5, 10, 5, 5, 10, 10, 5}))
+ sparseChildren[0] = int32ArrFromSlice(0, 1, 2, 3, 4, 5, 6)
+ defer sparseChildren[0].Release()
+ sparseChildren[1] = uint8ArrFromSlice(10, 11, 12, 13, 14, 15, 16)
+ defer sparseChildren[1].Release()
+
+ denseChildren[0] = int32ArrFromSlice(0, 2, 3, 7)
+ defer denseChildren[0].Release()
+ denseChildren[1] = uint8ArrFromSlice(11, 14, 15)
+ defer denseChildren[1].Release()
+
+ offsetsBuffer := memory.NewBufferBytes(arrow.Int32Traits.CastToBytes([]int32{0, 0, 1, 2, 1, 2, 3}))
+ sparse := array.NewSparseUnion(sparseType, length, sparseChildren, typeIDsBuffer, 0)
+ dense := array.NewDenseUnion(denseType, length, denseChildren, typeIDsBuffer, offsetsBuffer, 0)
+
+ defer sparse.Release()
+ defer dense.Release()
+
+ batch := array.NewRecord(schema, []arrow.Array{sparse, dense}, -1)
+ defer batch.Release()
+
+ checkUnion := func(arr arrow.Array) {
+ size := arr.Len()
+ slice := array.NewSlice(arr, 2, int64(size))
+ defer slice.Release()
+ assert.EqualValues(t, size-2, slice.Len())
+
+ slice2 := array.NewSlice(arr, 2, int64(arr.Len()))
+ defer slice2.Release()
+ assert.EqualValues(t, size-2, slice2.Len())
+
+ assert.True(t, array.Equal(slice, slice2))
Review Comment:
Do you also sometimes check for inequality between arrays?
##########
go/arrow/datatype_nested.go:
##########
@@ -329,6 +333,208 @@ func (t *MapType) Layout() DataTypeLayout {
return t.value.Layout()
}
+type (
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+type UnionType interface {
+ NestedType
+ Mode() UnionMode
+ ChildIDs() []int
+ TypeCodes() []UnionTypeCode
Review Comment:
You may want to add comments to describe these APIs, since unions can be confusing for users at first.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937040390
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
Well this is much better...
```
goos: linux
goarch: amd64
pkg: github.com/apache/arrow/go/v10/arrow/bitutil
cpu: 12th Gen Intel(R) Core(TM) i7-12700H
BenchmarkBitmapAnd/nbytes=32768/0-20 1110499 1078 ns/op 60797.80 MB/s 0 B/op 0 allocs/op
BenchmarkBitmapAnd/nbytes=32768/1-20 29881 39699 ns/op 1650.82 MB/s 192 B/op 3 allocs/op
BenchmarkBitmapAnd/nbytes=32768/2-20 30028 39396 ns/op 1663.50 MB/s 192 B/op 3 allocs/op
BenchmarkBitmapAnd/nbytes=131072/0-20 254810 4698 ns/op 55795.91 MB/s 0 B/op 0 allocs/op
BenchmarkBitmapAnd/nbytes=131072/1-20 7418 159083 ns/op 1647.85 MB/s 192 B/op 3 allocs/op
BenchmarkBitmapAnd/nbytes=131072/2-20 7378 157388 ns/op 1665.59 MB/s 192 B/op 3 allocs/op
```
:smile: Though it looks like i should make a card to look into similarly speeding up the unaligned cases (by way of making the bitmapword reader and writer faster)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] github-actions[bot] commented on pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #13768:
URL: https://github.com/apache/arrow/pull/13768#issuecomment-1201633335
:warning: Ticket **has not been started in JIRA**, please click 'Start Progress'.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936765696
##########
go/arrow/bitutil/bitmaps_test.go:
##########
@@ -356,3 +358,119 @@ func BenchmarkBitmapReader(b *testing.B) {
}
})
}
+
+type bitmapOp struct {
+ noAlloc func(left, right []byte, lOffset, rOffset int64, out []byte, outOffset, length int64)
+ alloc func(mem memory.Allocator, left, right []byte, lOffset, rOffset int64, length, outOffset int64) *memory.Buffer
+}
+
+type BitmapOpSuite struct {
+ suite.Suite
+}
+
+func (s *BitmapOpSuite) testAligned(op bitmapOp, leftBits, rightBits []int, resultBits []bool) {
+ var (
+ left, right []byte
+ out *memory.Buffer
+ length int64
+ )
+ for _, lOffset := range []int64{0, 1, 3, 5, 7, 8, 13, 21, 38, 75, 120, 65536} {
+ s.Run(fmt.Sprintf("left offset %d", lOffset), func() {
+ left = bitmapFromSlice(leftBits, int(lOffset))
+ length = int64(len(leftBits))
+ for _, rOffset := range []int64{lOffset, lOffset + 8, lOffset + 40} {
+ s.Run(fmt.Sprintf("right offset %d", rOffset), func() {
+ right = bitmapFromSlice(rightBits, int(rOffset))
+ for _, outOffset := range []int64{lOffset, lOffset + 16, lOffset + 24} {
+ s.Run(fmt.Sprintf("out offset %d", outOffset), func() {
+ out = op.alloc(memory.DefaultAllocator, left, right, lOffset, rOffset, length, outOffset)
+ rdr := bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+
+ memory.Set(out.Bytes(), 0x00)
+ op.noAlloc(left, right, lOffset, rOffset, out.Bytes(), outOffset, length)
+ rdr = bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+ })
+ }
+ })
+ }
+ })
+ }
+}
+
+func (s *BitmapOpSuite) testUnaligned(op bitmapOp, leftBits, rightBits []int, resultBits []bool) {
+ var (
+ left, right []byte
+ out *memory.Buffer
+ length int64
+ offsets = []int64{0, 1, 3, 5, 7, 8, 13, 21, 38, 75, 120, 65536}
+ )
+
+ for _, lOffset := range offsets {
+ s.Run(fmt.Sprintf("left offset %d", lOffset), func() {
+ left = bitmapFromSlice(leftBits, int(lOffset))
+ length = int64(len(leftBits))
+ for _, rOffset := range offsets {
+ s.Run(fmt.Sprintf("right offset %d", rOffset), func() {
+ right = bitmapFromSlice(rightBits, int(rOffset))
+ for _, outOffset := range offsets {
+ s.Run(fmt.Sprintf("out offset %d", outOffset), func() {
+ s.Run("alloc", func() {
+ out = op.alloc(memory.DefaultAllocator, left, right, lOffset, rOffset, length, outOffset)
+ rdr := bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+ })
+ s.Run("noalloc", func() {
+ memory.Set(out.Bytes(), 0x00)
+ op.noAlloc(left, right, lOffset, rOffset, out.Bytes(), outOffset, length)
+ rdr := bitutil.NewBitmapReader(out.Bytes(), int(outOffset), int(length))
+ assertReaderVals(s.T(), rdr, resultBits)
+ })
+ })
+ }
+ })
+ }
+ })
+ }
+}
+
+func (s *BitmapOpSuite) TestBitmapAnd() {
+ op := bitmapOp{
+ noAlloc: bitutil.BitmapAnd,
+ alloc: bitutil.BitmapAndAlloc,
+ }
+
+ leftBits := []int{0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1}
+ rightBits := []int{0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0}
+ resultBits := []bool{false, false, true, false, false, false, false, false, false, true, false, false, false, false}
Review Comment:
So, I've been looking at the C++ implementation for a bit which I sourced this from and it looks like there's a bug I've inherited (correct me if i'm wrong please).
Basically, if the bitmaps passed in to `BitmapAnd` and `BitmapOr` (in util/bitmap_ops.h/cc) if the offsets are non-zero (but identical, so it goes to the aligned case) but the passed in length is 0, it's still going to perform the bit-wise operation on the first byte of the bitmaps because it counts the number of bytes to operate on as `BytesForBits(length + offset % 8)` which would be 1 for any non-byte-aligned offset even with length being 0. This also exposes an issue (intentional or not, either way it's not documented) that the in the Aligned case, the `BitmapAnd` and `BitmapOr` functions will clobber preceding / trailing bits in the first/last bytes for non-byte-aligned offsets.
In the un-aligned case, by using the BitmapWordWriter, those preceding and trailing bits get maintained because the writer utilizes masks to protect them. I'm gonna address these issues in this implementation, but I figured I'd mention them in case there's something in the C++ implementation that I'm missing or it exhibits these problems.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] wolfeidau commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
wolfeidau commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r938025833
##########
go/arrow/datatype_nested.go:
##########
@@ -384,6 +388,286 @@ func (t *MapType) Layout() DataTypeLayout {
func (MapType) OffsetTypeTraits() OffsetTraits { return Int32Traits }
+type (
+ // UnionTypeCode is an alias to int8 which is the type of the ids
+ // used for union arrays.
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+// UnionType is an interface to encompass both Dense and Sparse Union types.
+//
+// A UnionType is a nested type where each logical value is taken
+// from a single child. A buffer of 8-bit type ids (typed as UnionTypeCode)
+// indicates which child a given logical value is to be taken from. This is
+// represented as the "child id" or "child index", which is the index into the
+// list of child fields for a given child.
+type UnionType interface {
+ NestedType
+ // Mode returns either SparseMode or DenseMode depending on the current
+ // concrete data type.
+ Mode() UnionMode
+ // ChildIDs returns a slice of ints to map UnionTypeCode values to
+ // the index in the Fields that represents the given Type. It is
+ // initialized with all values being InvalidUnionChildID (-1)
+ // before being populated based on the TypeCodes and fields of the type.
+ // The field for a given type can be retrieved by Fields()[ChildIDs()[typeCode]]
+ ChildIDs() []int
+ // TypeCodes returns the list of available type codes for this union type
+ // which will correspond to indexes into the ChildIDs slice to locate the
+ // appropriate child. A union Array contains a buffer of these type codes
+ // which indicate for a given index, which child has the value for that index.
+ TypeCodes() []UnionTypeCode
+ // MaxTypeCode returns the value of the largest TypeCode in the list of typecodes
+ // that are defined by this Union type
+ MaxTypeCode() UnionTypeCode
+}
+
+// UnionOf returns an appropriate union type for the given Mode (Sparse or Dense),
+// child fields, and type codes. len(fields) == len(typeCodes) must be true, or else
+// this will panic. len(fields) can be 0.
+func UnionOf(mode UnionMode, fields []Field, typeCodes []UnionTypeCode) UnionType {
+ switch mode {
+ case SparseMode:
+ return SparseUnionOf(fields, typeCodes)
+ case DenseMode:
+ return DenseUnionOf(fields, typeCodes)
+ default:
+ panic("arrow: invalid union mode")
+ }
+}
+
+type unionType struct {
+ children []Field
+ typeCodes []UnionTypeCode
+ childIDs [int(MaxUnionTypeCode) + 1]int
+}
+
+func (t *unionType) init(fields []Field, typeCodes []UnionTypeCode) {
+ // initialize all child IDs to -1
+ t.childIDs[0] = InvalidUnionChildID
+ for i := 1; i < len(t.childIDs); i *= 2 {
+ copy(t.childIDs[i:], t.childIDs[:i])
+ }
+
+ t.children = fields
+ t.typeCodes = typeCodes
+
+ for i, tc := range t.typeCodes {
+ t.childIDs[tc] = i
+ }
+}
+
+func (t unionType) Fields() []Field { return t.children }
+func (t unionType) TypeCodes() []UnionTypeCode { return t.typeCodes }
+func (t unionType) ChildIDs() []int { return t.childIDs[:] }
+
+func (t *unionType) validate(fields []Field, typeCodes []UnionTypeCode, _ UnionMode) error {
+ if len(fields) != len(typeCodes) {
+ return errors.New("arrow: union types should have the same number of fields as type codes")
+ }
+
+ for _, c := range typeCodes {
+ if c < 0 || c > MaxUnionTypeCode {
+ return errors.New("arrow: union type code out of bounds")
+ }
+ }
+ return nil
+}
+
+func (t *unionType) MaxTypeCode() (max UnionTypeCode) {
+ if len(t.typeCodes) == 0 {
+ return
+ }
+
+ max = t.typeCodes[0]
+ for _, c := range t.typeCodes[1:] {
+ if c > max {
+ max = c
+ }
+ }
+ return
+}
+
+func (t *unionType) String() string {
+ var b strings.Builder
+ b.WriteByte('<')
+ for i := range t.typeCodes {
+ if i != 0 {
+ b.WriteString(", ")
+ }
+ fmt.Fprintf(&b, "%s=%d", t.children[i], t.typeCodes[i])
+ }
+ b.WriteByte('>')
+ return b.String()
+}
+
+func (t *unionType) fingerprint() string {
+ var b strings.Builder
+ for _, c := range t.typeCodes {
+ fmt.Fprintf(&b, ":%d", c)
+ }
+ b.WriteString("]{")
+ for _, c := range t.children {
+ fingerprint := c.Fingerprint()
+ if len(fingerprint) == 0 {
+ return ""
+ }
+ b.WriteString(fingerprint)
+ b.WriteByte(';')
+ }
+ b.WriteByte('}')
+ return b.String()
+}
+
+func fieldsFromArrays(arrays []Array, names ...string) (ret []Field) {
+ ret = make([]Field, len(arrays))
+ if len(names) == 0 {
+ for i, c := range arrays {
+ ret[i] = Field{Name: strconv.Itoa(i), Type: c.DataType(), Nullable: true}
+ }
+ } else {
+ debug.Assert(len(names) == len(arrays), "mismatch of arrays and names")
+ for i, c := range arrays {
+ ret[i] = Field{Name: names[i], Type: c.DataType(), Nullable: true}
+ }
+ }
+ return
+}
+
+// SparseUnionType is the concrete type for Sparse union data.
+//
+// A sparse union is a nested type where each logical value is taken
+// from a single child. A buffer of 8-bit type ids indicates which child
+// a given logical value is to be taken from.
+//
+// In a sparse union, each child array will have the same length as the
+// union array itself, regardless of the actual number of union values which
+// refer to it.
+//
+// Unlike most other types, unions do not have a top-level validity bitmap.
+type SparseUnionType struct {
+ unionType
+}
+
+// SparseUnionFromArrays enables creating a union type from a list of Arrays,
+// field names, and type codes. len(fields) should be either 0 or equal to len(children).
+// len(codes) should also be either 0, or equal to len(children).
+//
+// If len(fields) == 0, then the fields will be named numerically as "0", "1", "2"...
+// and so on. If len(codes) == 0, then the type codes will be constructed as
+// [0, 1, 2, ..., n].
+func SparseUnionFromArrays(children []Array, fields []string, codes []UnionTypeCode) *SparseUnionType {
+ if len(codes) == 0 {
+ codes = make([]UnionTypeCode, len(children))
+ for i := range children {
+ codes[i] = UnionTypeCode(i)
+ }
+ }
+ return SparseUnionOf(fieldsFromArrays(children, fields...), codes)
+}
+
+// SparseUnionOf is equivalent to UnionOf(arrow.SparseMode, fields, typeCodes),
+// constructing a SparseUnionType from a list of fields and type codes.
+//
+// If len(fields) != len(typeCodes) this will panic. They are allowed to be
+// of length 0.
+func SparseUnionOf(fields []Field, typeCodes []UnionTypeCode) *SparseUnionType {
+ ret := &SparseUnionType{}
Review Comment:
Again for consistency use new(SparseUnionType )
##########
go/arrow/datatype_nested.go:
##########
@@ -384,6 +388,286 @@ func (t *MapType) Layout() DataTypeLayout {
func (MapType) OffsetTypeTraits() OffsetTraits { return Int32Traits }
+type (
+ // UnionTypeCode is an alias to int8 which is the type of the ids
+ // used for union arrays.
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+// UnionType is an interface to encompass both Dense and Sparse Union types.
+//
+// A UnionType is a nested type where each logical value is taken
+// from a single child. A buffer of 8-bit type ids (typed as UnionTypeCode)
+// indicates which child a given logical value is to be taken from. This is
+// represented as the "child id" or "child index", which is the index into the
+// list of child fields for a given child.
+type UnionType interface {
+ NestedType
+ // Mode returns either SparseMode or DenseMode depending on the current
+ // concrete data type.
+ Mode() UnionMode
+ // ChildIDs returns a slice of ints to map UnionTypeCode values to
+ // the index in the Fields that represents the given Type. It is
+ // initialized with all values being InvalidUnionChildID (-1)
+ // before being populated based on the TypeCodes and fields of the type.
+ // The field for a given type can be retrieved by Fields()[ChildIDs()[typeCode]]
+ ChildIDs() []int
+ // TypeCodes returns the list of available type codes for this union type
+ // which will correspond to indexes into the ChildIDs slice to locate the
+ // appropriate child. A union Array contains a buffer of these type codes
+ // which indicate for a given index, which child has the value for that index.
+ TypeCodes() []UnionTypeCode
+ // MaxTypeCode returns the value of the largest TypeCode in the list of typecodes
+ // that are defined by this Union type
+ MaxTypeCode() UnionTypeCode
+}
+
+// UnionOf returns an appropriate union type for the given Mode (Sparse or Dense),
+// child fields, and type codes. len(fields) == len(typeCodes) must be true, or else
+// this will panic. len(fields) can be 0.
+func UnionOf(mode UnionMode, fields []Field, typeCodes []UnionTypeCode) UnionType {
+ switch mode {
+ case SparseMode:
+ return SparseUnionOf(fields, typeCodes)
+ case DenseMode:
+ return DenseUnionOf(fields, typeCodes)
+ default:
+ panic("arrow: invalid union mode")
+ }
+}
+
+type unionType struct {
+ children []Field
+ typeCodes []UnionTypeCode
+ childIDs [int(MaxUnionTypeCode) + 1]int
+}
+
+func (t *unionType) init(fields []Field, typeCodes []UnionTypeCode) {
+ // initialize all child IDs to -1
+ t.childIDs[0] = InvalidUnionChildID
+ for i := 1; i < len(t.childIDs); i *= 2 {
+ copy(t.childIDs[i:], t.childIDs[:i])
+ }
+
+ t.children = fields
+ t.typeCodes = typeCodes
+
+ for i, tc := range t.typeCodes {
+ t.childIDs[tc] = i
+ }
+}
+
+func (t unionType) Fields() []Field { return t.children }
+func (t unionType) TypeCodes() []UnionTypeCode { return t.typeCodes }
+func (t unionType) ChildIDs() []int { return t.childIDs[:] }
+
+func (t *unionType) validate(fields []Field, typeCodes []UnionTypeCode, _ UnionMode) error {
+ if len(fields) != len(typeCodes) {
+ return errors.New("arrow: union types should have the same number of fields as type codes")
+ }
+
+ for _, c := range typeCodes {
+ if c < 0 || c > MaxUnionTypeCode {
+ return errors.New("arrow: union type code out of bounds")
+ }
+ }
+ return nil
+}
+
+func (t *unionType) MaxTypeCode() (max UnionTypeCode) {
+ if len(t.typeCodes) == 0 {
+ return
+ }
+
+ max = t.typeCodes[0]
+ for _, c := range t.typeCodes[1:] {
+ if c > max {
+ max = c
+ }
+ }
+ return
+}
+
+func (t *unionType) String() string {
+ var b strings.Builder
+ b.WriteByte('<')
+ for i := range t.typeCodes {
+ if i != 0 {
+ b.WriteString(", ")
+ }
+ fmt.Fprintf(&b, "%s=%d", t.children[i], t.typeCodes[i])
+ }
+ b.WriteByte('>')
+ return b.String()
+}
+
+func (t *unionType) fingerprint() string {
+ var b strings.Builder
+ for _, c := range t.typeCodes {
+ fmt.Fprintf(&b, ":%d", c)
+ }
+ b.WriteString("]{")
+ for _, c := range t.children {
+ fingerprint := c.Fingerprint()
+ if len(fingerprint) == 0 {
+ return ""
+ }
+ b.WriteString(fingerprint)
+ b.WriteByte(';')
+ }
+ b.WriteByte('}')
+ return b.String()
+}
+
+func fieldsFromArrays(arrays []Array, names ...string) (ret []Field) {
+ ret = make([]Field, len(arrays))
+ if len(names) == 0 {
+ for i, c := range arrays {
+ ret[i] = Field{Name: strconv.Itoa(i), Type: c.DataType(), Nullable: true}
+ }
+ } else {
+ debug.Assert(len(names) == len(arrays), "mismatch of arrays and names")
+ for i, c := range arrays {
+ ret[i] = Field{Name: names[i], Type: c.DataType(), Nullable: true}
+ }
+ }
+ return
+}
+
+// SparseUnionType is the concrete type for Sparse union data.
+//
+// A sparse union is a nested type where each logical value is taken
+// from a single child. A buffer of 8-bit type ids indicates which child
+// a given logical value is to be taken from.
+//
+// In a sparse union, each child array will have the same length as the
+// union array itself, regardless of the actual number of union values which
+// refer to it.
+//
+// Unlike most other types, unions do not have a top-level validity bitmap.
+type SparseUnionType struct {
+ unionType
+}
+
+// SparseUnionFromArrays enables creating a union type from a list of Arrays,
+// field names, and type codes. len(fields) should be either 0 or equal to len(children).
+// len(codes) should also be either 0, or equal to len(children).
+//
+// If len(fields) == 0, then the fields will be named numerically as "0", "1", "2"...
+// and so on. If len(codes) == 0, then the type codes will be constructed as
+// [0, 1, 2, ..., n].
+func SparseUnionFromArrays(children []Array, fields []string, codes []UnionTypeCode) *SparseUnionType {
+ if len(codes) == 0 {
+ codes = make([]UnionTypeCode, len(children))
+ for i := range children {
+ codes[i] = UnionTypeCode(i)
+ }
+ }
+ return SparseUnionOf(fieldsFromArrays(children, fields...), codes)
+}
+
+// SparseUnionOf is equivalent to UnionOf(arrow.SparseMode, fields, typeCodes),
+// constructing a SparseUnionType from a list of fields and type codes.
+//
+// If len(fields) != len(typeCodes) this will panic. They are allowed to be
+// of length 0.
+func SparseUnionOf(fields []Field, typeCodes []UnionTypeCode) *SparseUnionType {
+ ret := &SparseUnionType{}
+ if err := ret.validate(fields, typeCodes, ret.Mode()); err != nil {
+ panic(err)
+ }
+ ret.init(fields, typeCodes)
+ return ret
+}
+
+func (SparseUnionType) ID() Type { return SPARSE_UNION }
+func (SparseUnionType) Name() string { return "sparse_union" }
+func (SparseUnionType) Mode() UnionMode { return SparseMode }
+func (t *SparseUnionType) Fingerprint() string {
+ return typeFingerprint(t) + "[s" + t.fingerprint()
+}
+func (SparseUnionType) Layout() DataTypeLayout {
+ return DataTypeLayout{Buffers: []BufferSpec{SpecAlwaysNull(), SpecFixedWidth(Uint8SizeBytes)}}
+}
+func (t *SparseUnionType) String() string {
+ return t.Name() + t.unionType.String()
+}
+
+// DenseUnionType is the concrete type for dense union data.
+//
+// A dense union is a nested type where each logical value is taken from a
+// single child, at a specific offset. A buffer of 8-bit type ids (typed
+// as UnionTypeCode) indicates which child a given logical value is to be
+// taken from and a buffer of 32-bit offsets indicating which physical position
+// in the given child array has the logical value for that index.
+//
+// Unlike a sparse union, a dense union allows encoding only the child values
+// which are actually referred to by the union array. This is counterbalanced
+// by the additional footprint of the offsets buffer, and the additional
+// indirection cost when looking up values.
+//
+// Unlike most other types, unions don't have a top-level validity bitmap
+type DenseUnionType struct {
+ unionType
+}
+
+// DenseUnionFromArrays enables creating a union type from a list of Arrays,
+// field names, and type codes. len(fields) should be either 0 or equal to len(children).
+// len(codes) should also be either 0, or equal to len(children).
+//
+// If len(fields) == 0, then the fields will be named numerically as "0", "1", "2"...
+// and so on. If len(codes) == 0, then the type codes will be constructed as
+// [0, 1, 2, ..., n].
+func DenseUnionFromArrays(children []Array, fields []string, codes []UnionTypeCode) *DenseUnionType {
+ if len(codes) == 0 {
+ codes = make([]UnionTypeCode, len(children))
+ for i := range children {
+ codes[i] = UnionTypeCode(i)
+ }
+ }
+ return DenseUnionOf(fieldsFromArrays(children, fields...), codes)
+}
+
+// DenseUnionOf is equivalent to UnionOf(arrow.DenseMode, fields, typeCodes),
+// constructing a SparseUnionType from a list of fields and type codes.
+//
+// If len(fields) != len(typeCodes) this will panic. They are allowed to be
+// of length 0.
+func DenseUnionOf(fields []Field, typeCodes []UnionTypeCode) *DenseUnionType {
+ ret := &DenseUnionType{}
Review Comment:
As above for consistency use new(SparseUnionType )
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r938173018
##########
go/arrow/datatype_nested.go:
##########
@@ -384,6 +388,286 @@ func (t *MapType) Layout() DataTypeLayout {
func (MapType) OffsetTypeTraits() OffsetTraits { return Int32Traits }
+type (
+ // UnionTypeCode is an alias to int8 which is the type of the ids
+ // used for union arrays.
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+// UnionType is an interface to encompass both Dense and Sparse Union types.
+//
+// A UnionType is a nested type where each logical value is taken
+// from a single child. A buffer of 8-bit type ids (typed as UnionTypeCode)
+// indicates which child a given logical value is to be taken from. This is
+// represented as the "child id" or "child index", which is the index into the
+// list of child fields for a given child.
+type UnionType interface {
+ NestedType
+ // Mode returns either SparseMode or DenseMode depending on the current
+ // concrete data type.
+ Mode() UnionMode
+ // ChildIDs returns a slice of ints to map UnionTypeCode values to
+ // the index in the Fields that represents the given Type. It is
+ // initialized with all values being InvalidUnionChildID (-1)
+ // before being populated based on the TypeCodes and fields of the type.
+ // The field for a given type can be retrieved by Fields()[ChildIDs()[typeCode]]
+ ChildIDs() []int
+ // TypeCodes returns the list of available type codes for this union type
+ // which will correspond to indexes into the ChildIDs slice to locate the
+ // appropriate child. A union Array contains a buffer of these type codes
+ // which indicate for a given index, which child has the value for that index.
+ TypeCodes() []UnionTypeCode
+ // MaxTypeCode returns the value of the largest TypeCode in the list of typecodes
+ // that are defined by this Union type
+ MaxTypeCode() UnionTypeCode
+}
+
+// UnionOf returns an appropriate union type for the given Mode (Sparse or Dense),
+// child fields, and type codes. len(fields) == len(typeCodes) must be true, or else
+// this will panic. len(fields) can be 0.
+func UnionOf(mode UnionMode, fields []Field, typeCodes []UnionTypeCode) UnionType {
+ switch mode {
+ case SparseMode:
+ return SparseUnionOf(fields, typeCodes)
+ case DenseMode:
+ return DenseUnionOf(fields, typeCodes)
+ default:
+ panic("arrow: invalid union mode")
+ }
+}
+
+type unionType struct {
+ children []Field
+ typeCodes []UnionTypeCode
+ childIDs [int(MaxUnionTypeCode) + 1]int
+}
+
+func (t *unionType) init(fields []Field, typeCodes []UnionTypeCode) {
+ // initialize all child IDs to -1
+ t.childIDs[0] = InvalidUnionChildID
+ for i := 1; i < len(t.childIDs); i *= 2 {
+ copy(t.childIDs[i:], t.childIDs[:i])
+ }
+
+ t.children = fields
+ t.typeCodes = typeCodes
+
+ for i, tc := range t.typeCodes {
+ t.childIDs[tc] = i
+ }
+}
+
+func (t unionType) Fields() []Field { return t.children }
+func (t unionType) TypeCodes() []UnionTypeCode { return t.typeCodes }
+func (t unionType) ChildIDs() []int { return t.childIDs[:] }
+
+func (t *unionType) validate(fields []Field, typeCodes []UnionTypeCode, _ UnionMode) error {
+ if len(fields) != len(typeCodes) {
+ return errors.New("arrow: union types should have the same number of fields as type codes")
+ }
+
+ for _, c := range typeCodes {
+ if c < 0 || c > MaxUnionTypeCode {
+ return errors.New("arrow: union type code out of bounds")
+ }
+ }
+ return nil
+}
+
+func (t *unionType) MaxTypeCode() (max UnionTypeCode) {
+ if len(t.typeCodes) == 0 {
+ return
+ }
+
+ max = t.typeCodes[0]
+ for _, c := range t.typeCodes[1:] {
+ if c > max {
+ max = c
+ }
+ }
+ return
+}
+
+func (t *unionType) String() string {
+ var b strings.Builder
+ b.WriteByte('<')
+ for i := range t.typeCodes {
+ if i != 0 {
+ b.WriteString(", ")
+ }
+ fmt.Fprintf(&b, "%s=%d", t.children[i], t.typeCodes[i])
+ }
+ b.WriteByte('>')
+ return b.String()
+}
+
+func (t *unionType) fingerprint() string {
+ var b strings.Builder
+ for _, c := range t.typeCodes {
+ fmt.Fprintf(&b, ":%d", c)
+ }
+ b.WriteString("]{")
+ for _, c := range t.children {
+ fingerprint := c.Fingerprint()
+ if len(fingerprint) == 0 {
+ return ""
+ }
+ b.WriteString(fingerprint)
+ b.WriteByte(';')
+ }
+ b.WriteByte('}')
+ return b.String()
+}
+
+func fieldsFromArrays(arrays []Array, names ...string) (ret []Field) {
+ ret = make([]Field, len(arrays))
+ if len(names) == 0 {
+ for i, c := range arrays {
+ ret[i] = Field{Name: strconv.Itoa(i), Type: c.DataType(), Nullable: true}
+ }
+ } else {
+ debug.Assert(len(names) == len(arrays), "mismatch of arrays and names")
+ for i, c := range arrays {
+ ret[i] = Field{Name: names[i], Type: c.DataType(), Nullable: true}
+ }
+ }
+ return
+}
+
+// SparseUnionType is the concrete type for Sparse union data.
+//
+// A sparse union is a nested type where each logical value is taken
+// from a single child. A buffer of 8-bit type ids indicates which child
+// a given logical value is to be taken from.
+//
+// In a sparse union, each child array will have the same length as the
+// union array itself, regardless of the actual number of union values which
+// refer to it.
+//
+// Unlike most other types, unions do not have a top-level validity bitmap.
+type SparseUnionType struct {
+ unionType
+}
+
+// SparseUnionFromArrays enables creating a union type from a list of Arrays,
+// field names, and type codes. len(fields) should be either 0 or equal to len(children).
+// len(codes) should also be either 0, or equal to len(children).
+//
+// If len(fields) == 0, then the fields will be named numerically as "0", "1", "2"...
+// and so on. If len(codes) == 0, then the type codes will be constructed as
+// [0, 1, 2, ..., n].
+func SparseUnionFromArrays(children []Array, fields []string, codes []UnionTypeCode) *SparseUnionType {
+ if len(codes) == 0 {
+ codes = make([]UnionTypeCode, len(children))
+ for i := range children {
+ codes[i] = UnionTypeCode(i)
+ }
+ }
+ return SparseUnionOf(fieldsFromArrays(children, fields...), codes)
+}
+
+// SparseUnionOf is equivalent to UnionOf(arrow.SparseMode, fields, typeCodes),
+// constructing a SparseUnionType from a list of fields and type codes.
+//
+// If len(fields) != len(typeCodes) this will panic. They are allowed to be
+// of length 0.
+func SparseUnionOf(fields []Field, typeCodes []UnionTypeCode) *SparseUnionType {
+ ret := &SparseUnionType{}
Review Comment:
so, it would actually be more consistent to swap out the usages of `new` since instantiating using `&Type{}` is the consistent style in the existing codebase. (look elsewhere at the other `*Of(...)` functions or any of the `New*Data` functions in the array package). I just didn't change the usages of `new(strings.Builder)` since I wasn't modifying the existing code. I'll swap them out here in order to make that more consistent.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937870849
##########
go/arrow/bitutil/Makefile:
##########
@@ -0,0 +1,62 @@
+# 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.
+
+# this converts rotate instructions from "ro[lr] <reg>" -> "ro[lr] <reg>, 1" for yasm compatibility
+PERL_FIXUP_ROTATE=perl -i -pe 's/(ro[rl]\s+\w{2,3})$$/\1, 1/'
+
+C2GOASM=c2goasm
Review Comment:
That must have happened recently, it definitely wasn't archived the last time I looked at it (a month or two ago). :(
I don't know if it's being maintained elsewhere.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on PR #13768:
URL: https://github.com/apache/arrow/pull/13768#issuecomment-1205415835
Thanks much @pitrou! I'll give it the rest of the day for anyone else to review and if no one else has any comments i'll merge it after that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937002223
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
That makes a lot of sense, I could probably use the same trick I've used before by writing the loop in C, compiling to asm and converting to golang ASM like we do for SIMD. I'll take a stab at that since that would simplify the logic here significantly.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936711343
##########
go/arrow/datatype_nested.go:
##########
@@ -329,6 +333,208 @@ func (t *MapType) Layout() DataTypeLayout {
return t.value.Layout()
}
+type (
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+type UnionType interface {
+ NestedType
+ Mode() UnionMode
+ ChildIDs() []int
+ TypeCodes() []UnionTypeCode
Review Comment:
Thanks, I intended to do so and completely forgot as I got wrapped up in making the IPC stuff work for Unions (the next change after this). I'll go back and get these all documented
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] ursabot commented on pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
ursabot commented on PR #13768:
URL: https://github.com/apache/arrow/pull/13768#issuecomment-1205877107
Benchmark runs are scheduled for baseline = 916417da0a966797c453126f57b657a0449651b5 and contender = 81ded071f4b3772109cf1317c6b886f78c056dd5. 81ded071f4b3772109cf1317c6b886f78c056dd5 is a master commit associated with this PR. Results will be available as each benchmark for each run completes.
Conbench compare runs links:
[Failed :arrow_down:0.0% :arrow_up:0.0%] [ec2-t3-xlarge-us-east-2](https://conbench.ursa.dev/compare/runs/0a8465fb114e4fa8bacc082f56786771...700797402af6481db01c925df173d9e9/)
[Finished :arrow_down:0.37% :arrow_up:0.0%] [test-mac-arm](https://conbench.ursa.dev/compare/runs/1d1472375dc14e17915a69e5e99a93f7...4b36382b5c374f16a8b6cd22fe44953a/)
[Finished :arrow_down:0.0% :arrow_up:0.0%] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/81e3e27f8ba04389b0df179fe1b9de5a...b3bae70e419a4a4cb5d0a5d3b6275eb6/)
[Finished :arrow_down:0.18% :arrow_up:0.0%] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/2d791bf5b9c44b97af16120d6e1e7ffa...c59329b0310d4dba9fb4c6fab4356b12/)
Buildkite builds:
[Failed] [`81ded071` ec2-t3-xlarge-us-east-2](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-ec2-t3-xlarge-us-east-2/builds/1257)
[Finished] [`81ded071` test-mac-arm](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-test-mac-arm/builds/1269)
[Finished] [`81ded071` ursa-i9-9960x](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-ursa-i9-9960x/builds/1252)
[Finished] [`81ded071` ursa-thinkcentre-m75q](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-ursa-thinkcentre-m75q/builds/1271)
[Failed] [`916417da` ec2-t3-xlarge-us-east-2](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-ec2-t3-xlarge-us-east-2/builds/1256)
[Finished] [`916417da` test-mac-arm](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-test-mac-arm/builds/1268)
[Finished] [`916417da` ursa-i9-9960x](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-ursa-i9-9960x/builds/1251)
[Finished] [`916417da` ursa-thinkcentre-m75q](https://buildkite.com/apache-arrow/arrow-bci-benchmark-on-ursa-thinkcentre-m75q/builds/1270)
Supported benchmarks:
ec2-t3-xlarge-us-east-2: Supported benchmark langs: Python, R. Runs only benchmarks with cloud = True
test-mac-arm: Supported benchmark langs: C++, Python, R
ursa-i9-9960x: Supported benchmark langs: Python, R, JavaScript
ursa-thinkcentre-m75q: Supported benchmark langs: C++, Java
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937873107
##########
go/arrow/bitutil/_lib/bitmap_ops.c:
##########
@@ -0,0 +1,30 @@
+// 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 "../../../internal/utils/_lib/arch.h"
+#include <stdint.h>
+
+void FULL_NAME(bitmap_aligned_and)(const uint8_t* left, const uint8_t* right, uint8_t* out, const int64_t nbytes) {
Review Comment:
You understand correctly. This technique is used in various places in the repo in order to benefit from SIMD instructions and performance. Sure, i'll add a comment here.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
pitrou commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937725637
##########
go/arrow/bitutil/Makefile:
##########
@@ -0,0 +1,62 @@
+# 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.
+
+# this converts rotate instructions from "ro[lr] <reg>" -> "ro[lr] <reg>, 1" for yasm compatibility
Review Comment:
I'm curious: this will only work on Linux and/or macOS? Does Windows get the pure Go version always?
##########
go/arrow/array/union.go:
##########
@@ -0,0 +1,1295 @@
+// 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"
+ "reflect"
+ "strings"
+ "sync/atomic"
+
+ "github.com/apache/arrow/go/v10/arrow"
+ "github.com/apache/arrow/go/v10/arrow/bitutil"
+ "github.com/apache/arrow/go/v10/arrow/internal/debug"
+ "github.com/apache/arrow/go/v10/arrow/memory"
+ "github.com/apache/arrow/go/v10/internal/bitutils"
+ "github.com/goccy/go-json"
+)
+
+// Union is a convenience interface to encompass both Sparse and Dense
+// union array types.
+type Union interface {
+ arrow.Array
+ // NumFields returns the number of child fields in this union.
+ // Equivalent to len(UnionType().Fields())
+ NumFields() int
+ // Validate returns an error if there are any issues with the lengths
+ // or types of the children arrays mismatching with the Type of the
+ // Union Array. nil is returned if there are no problems.
+ Validate() error
+ // ValidateFull runs the same checks that Validate() does, but additionall
Review Comment:
```suggestion
// ValidateFull runs the same checks that Validate() does, but additionally
```
##########
go/arrow/bitutil/bitmap_ops_avx2_amd64.s:
##########
@@ -0,0 +1,192 @@
+//+build !noasm !appengine
+// AUTO-GENERATED BY C2GOASM -- DO NOT EDIT
Review Comment:
Also use the git attributes trick here?
(perhaps even add "generated" in the filename for more clarity?)
##########
go/arrow/bitutil/_lib/bitmap_ops_avx2_amd64.s:
##########
@@ -0,0 +1,212 @@
+ .text
Review Comment:
Perhaps this would work: https://docs.github.com/en/repositories/working-with-files/managing-files/customizing-how-changed-files-appear-on-github
##########
go/arrow/bitutil/Makefile:
##########
@@ -0,0 +1,62 @@
+# 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.
+
+# this converts rotate instructions from "ro[lr] <reg>" -> "ro[lr] <reg>, 1" for yasm compatibility
+PERL_FIXUP_ROTATE=perl -i -pe 's/(ro[rl]\s+\w{2,3})$$/\1, 1/'
+
+C2GOASM=c2goasm
Review Comment:
For the record, https://github.com/minio/c2goasm seems archived. Is it maintained elsewhere?
##########
go/arrow/bitutil/_lib/bitmap_ops_avx2_amd64.s:
##########
@@ -0,0 +1,212 @@
+ .text
Review Comment:
I don't know if there's an easy way to tag this as generated, so that people don't lose time trying to read it (let alone modify it)?
##########
go/arrow/bitutil/_lib/bitmap_ops.c:
##########
@@ -0,0 +1,30 @@
+// 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 "../../../internal/utils/_lib/arch.h"
+#include <stdint.h>
+
+void FULL_NAME(bitmap_aligned_and)(const uint8_t* left, const uint8_t* right, uint8_t* out, const int64_t nbytes) {
Review Comment:
So, IIUC, this file is compiled into optimized ASM for different ISAs by the Makefile in the parent directory? Perhaps add a comment explaining it here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936724316
##########
go/arrow/array/fixed_size_list.go:
##########
@@ -196,6 +198,10 @@ func (b *FixedSizeListBuilder) AppendNull() {
b.unsafeAppendBoolToBitmap(false)
}
+func (b *FixedSizeListBuilder) AppendEmptyValue() {
+ b.Append(true)
Review Comment:
good catch! I missed that!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937894915
##########
go/arrow/bitutil/_lib/bitmap_ops.c:
##########
@@ -0,0 +1,30 @@
+// 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 "../../../internal/utils/_lib/arch.h"
+#include <stdint.h>
+
+void FULL_NAME(bitmap_aligned_and)(const uint8_t* left, const uint8_t* right, uint8_t* out, const int64_t nbytes) {
Review Comment:
comment added
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936824869
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
You're completely correct, `unalignedBitmapOp` is faster! i'll make some modifications to get the aligned one to work word-wise where it can. This might be a good spot to also improve the C++ implementation which would show the same thing (as it also works byte-wise for the aligned case)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade merged pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade merged PR #13768:
URL: https://github.com/apache/arrow/pull/13768
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] pitrou commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
pitrou commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936950524
##########
go/arrow/bitutil/bitmaps.go:
##########
@@ -422,3 +423,81 @@ func CopyBitmap(src []byte, srcOffset, length int, dst []byte, dstOffset int) {
dst[nbytes-1] &= ^trailMask
dst[nbytes-1] |= lastData & trailMask
}
+
+type bitOp struct {
+ opWord func(uint64, uint64) uint64
+ opByte func(byte, byte) byte
+}
+
+var (
+ bitAndOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l & r },
+ opByte: func(l, r byte) byte { return l & r },
+ }
+ bitOrOp = bitOp{
+ opWord: func(l, r uint64) uint64 { return l | r },
+ opByte: func(l, r byte) byte { return l | r },
+ }
+)
+
+func alignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ debug.Assert(lOffset%8 == rOffset%8, "aligned bitmap op called with unaligned offsets")
+ debug.Assert(lOffset%8 == outOffset%8, "aligned bitmap op called with unaligned output offset")
+
+ nbytes := BytesForBits(length + lOffset%8)
+ left = left[lOffset/8:]
+ right = right[rOffset/8:]
+ out = out[outOffset/8:]
+ for i := int64(0); i < nbytes; i++ {
+ out[i] = op.opByte(left[i], right[i])
+ }
+}
+
+func unalignedBitmapOp(op bitOp, left, right []byte, lOffset, rOffset int64, out []byte, outOffset int64, length int64) {
+ leftRdr := NewBitmapWordReader(left, int(lOffset), int(length))
+ rightRdr := NewBitmapWordReader(right, int(rOffset), int(length))
+ writer := NewBitmapWordWriter(out, int(outOffset), int(length))
+
+ for nwords := leftRdr.Words(); nwords > 0; nwords-- {
+ writer.PutNextWord(op.opWord(leftRdr.NextWord(), rightRdr.NextWord()))
Review Comment:
Well, if I run the C++ benchmarks, I get this:
```
BenchmarkBitmapAnd/32768/0 1696 ns 1696 ns 411775 bytes_per_second=17.9927G/s
BenchmarkBitmapAnd/131072/0 6843 ns 6842 ns 101856 bytes_per_second=17.8405G/s
BenchmarkBitmapAnd/32768/1 3999 ns 3998 ns 174766 bytes_per_second=7.63287G/s
BenchmarkBitmapAnd/131072/1 15546 ns 15544 ns 44802 bytes_per_second=7.85325G/s
BenchmarkBitmapAnd/32768/2 3988 ns 3987 ns 175050 bytes_per_second=7.65504G/s
BenchmarkBitmapAnd/131072/2 15601 ns 15599 ns 44678 bytes_per_second=7.82568G/s
```
... where the first benchmark parameter is the number of bytes and the second is the bif offset, so you see the results show a similar performance profile as the Go ones (with the aligned implementation being a couple times faster than the unaligned one).
The reason this works is probably that C++ compilers optimize hard enough to turn the byte-wise loop into a word-wise loop plus byte-wise prolog/epilog.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937880588
##########
go/arrow/bitutil/bitmap_ops_avx2_amd64.s:
##########
@@ -0,0 +1,192 @@
+//+build !noasm !appengine
+// AUTO-GENERATED BY C2GOASM -- DO NOT EDIT
Review Comment:
the filenames actually have to match exactly between the `.s` and the `.go` files, so i can't easily add "generated" to the filenames here. The other generated files typically have a `.gen.go` extension in the repo.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936712776
##########
go/arrow/datatype_nested.go:
##########
@@ -329,6 +333,208 @@ func (t *MapType) Layout() DataTypeLayout {
return t.value.Layout()
}
+type (
+ UnionTypeCode = int8
+ UnionMode int8
+)
+
+const (
+ MaxUnionTypeCode UnionTypeCode = 127
+ InvalidUnionChildID int = -1
+
+ SparseMode UnionMode = iota
+ DenseMode
+)
+
+type UnionType interface {
+ NestedType
+ Mode() UnionMode
+ ChildIDs() []int
+ TypeCodes() []UnionTypeCode
+ MaxTypeCode() UnionTypeCode
+}
+
+func UnionOf(mode UnionMode, fields []Field, typeCodes []UnionTypeCode) UnionType {
+ switch mode {
+ case SparseMode:
+ return SparseUnionOf(fields, typeCodes)
+ case DenseMode:
+ return DenseUnionOf(fields, typeCodes)
+ default:
+ panic("arrow: invalid union mode")
+ }
+}
+
+type unionType struct {
+ children []Field
+ typeCodes []UnionTypeCode
+ childIDs [int(MaxUnionTypeCode) + 1]int
+}
+
+func (t *unionType) init(fields []Field, typeCodes []UnionTypeCode) {
+ // initialize all child IDs to -1
+ t.childIDs[0] = InvalidUnionChildID
+ for i := 1; i < len(t.childIDs); i *= 2 {
+ copy(t.childIDs[i:], t.childIDs[:i])
+ }
+
+ t.children = fields
+ t.typeCodes = typeCodes
+
+ for i, tc := range t.typeCodes {
+ t.childIDs[tc] = i
+ }
+}
+
+func (t unionType) Fields() []Field { return t.children }
+func (t unionType) TypeCodes() []UnionTypeCode { return t.typeCodes }
+func (t unionType) ChildIDs() []int { return t.childIDs[:] }
+
+func (t *unionType) validate(fields []Field, typeCodes []UnionTypeCode, _ UnionMode) error {
+ if len(fields) != len(typeCodes) {
+ return errors.New("arrow: union types should have the same number of fields as type codes")
+ }
+
+ for _, c := range typeCodes {
+ if c < 0 || c > MaxUnionTypeCode {
+ return errors.New("arrow: union type code out of bounds")
+ }
+ }
+ return nil
+}
+
+func (t *unionType) MaxTypeCode() (max UnionTypeCode) {
+ if len(t.typeCodes) == 0 {
+ return
+ }
+
+ max = t.typeCodes[0]
+ for _, c := range t.typeCodes[1:] {
+ if c > max {
+ max = c
+ }
+ }
+ return
+}
+
+func (t *unionType) String() string {
+ var b strings.Builder
+ b.WriteByte('<')
+ for i := range t.typeCodes {
+ if i != 0 {
+ b.WriteString(", ")
+ }
+ fmt.Fprintf(&b, "%s=%d", t.children[i], t.typeCodes[i])
+ }
+ b.WriteByte('>')
+ return b.String()
+}
+
+func (t *unionType) fingerprint() string {
+ var b strings.Builder
+ for _, c := range t.typeCodes {
+ fmt.Fprintf(&b, ":%d", c)
+ }
+ b.WriteString("]{")
+ for _, c := range t.children {
+ fingerprint := c.Fingerprint()
+ if len(fingerprint) == 0 {
+ return ""
+ }
+ b.WriteString(fingerprint)
+ b.WriteByte(';')
+ }
+ b.WriteByte('}')
+ return b.String()
+}
+
+func fieldsFromArrays(arrays []Array, names ...string) (ret []Field) {
+ ret = make([]Field, len(arrays))
+ if len(names) == 0 {
+ for i, c := range arrays {
+ ret[i] = Field{Name: strconv.Itoa(i), Type: c.DataType(), Nullable: true}
+ }
+ } else {
+ debug.Assert(len(names) == len(arrays), "mismatch of arrays and names")
+ for i, c := range arrays {
+ ret[i] = Field{Name: names[i], Type: c.DataType(), Nullable: true}
+ }
+ }
+ return
+}
+
+type SparseUnionType struct {
+ unionType
+}
+
+func SparseUnionFromArrays(children []Array, fields []string, codes []UnionTypeCode) *SparseUnionType {
+ if len(codes) == 0 {
+ codes = make([]UnionTypeCode, len(children))
+ for i := range children {
+ codes[i] = UnionTypeCode(i)
+ }
+ }
+ return SparseUnionOf(fieldsFromArrays(children, fields...), codes)
+}
+
+func SparseUnionOf(fields []Field, typeCodes []UnionTypeCode) *SparseUnionType {
+ ret := &SparseUnionType{}
+ if err := ret.validate(fields, typeCodes, ret.Mode()); err != nil {
+ panic(err)
+ }
+ ret.init(fields, typeCodes)
+ return ret
+}
+
+func (SparseUnionType) ID() Type { return SPARSE_UNION }
+func (SparseUnionType) Name() string { return "sparse_union" }
+func (SparseUnionType) Mode() UnionMode { return SparseMode }
+func (t *SparseUnionType) Fingerprint() string {
+ return typeFingerprint(t) + "[s" + t.fingerprint()
+}
+func (SparseUnionType) Layout() DataTypeLayout {
+ return DataTypeLayout{Buffers: []BufferSpec{SpecAlwaysNull(), SpecFixedWidth(Uint8SizeBytes)}}
Review Comment:
Yup yup.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r936708588
##########
go/arrow/array/fixedsize_binarybuilder.go:
##########
@@ -81,6 +83,12 @@ func (b *FixedSizeBinaryBuilder) AppendNull() {
b.UnsafeAppendBoolToBitmap(false)
}
+func (b *FixedSizeBinaryBuilder) AppendEmptyValue() {
+ b.Reserve(1)
+ b.values.Advance(b.dtype.ByteWidth)
Review Comment:
@pitrou There's no undefined values in Go, everything is defaulted to a `zero` value based on the type. For `byte` it's 0. So by just advancing the underlying buffer it automatically zeroes out the memory. Since this is for FixedSizeBinary, it needs to get advanced like this (the C++ version of this just explicitly zeroes out the memory which, as I said, isn't needed in Go)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
[GitHub] [arrow] zeroshade commented on a diff in pull request #13768: ARROW-3678: [Go] Implement Union Arrays
Posted by GitBox <gi...@apache.org>.
zeroshade commented on code in PR #13768:
URL: https://github.com/apache/arrow/pull/13768#discussion_r937849921
##########
go/arrow/bitutil/Makefile:
##########
@@ -0,0 +1,62 @@
+# 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.
+
+# this converts rotate instructions from "ro[lr] <reg>" -> "ro[lr] <reg>, 1" for yasm compatibility
Review Comment:
From what I've seen, the compiling has to be done on linux/macOS because it needs clang and yasm, but the resulting plan9 assembly from using `c2goasm` will be portable. Go's toolchain uses plan9 assembly as an intermediate before generating the platform specific instructions. As a result, windows will use the assembly version also, not the pure Go version (unless the `noasm` tag is set when compiling)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org