emkornfield commented on a change in pull request #12158:
URL: https://github.com/apache/arrow/pull/12158#discussion_r800129147



##########
File path: go/arrow/array/dictionary.go
##########
@@ -0,0 +1,1305 @@
+// 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 (
+       "errors"
+       "fmt"
+       "math"
+       "sync/atomic"
+       "unsafe"
+
+       "github.com/apache/arrow/go/v7/arrow"
+       "github.com/apache/arrow/go/v7/arrow/bitutil"
+       "github.com/apache/arrow/go/v7/arrow/decimal128"
+       "github.com/apache/arrow/go/v7/arrow/float16"
+       "github.com/apache/arrow/go/v7/arrow/internal/debug"
+       "github.com/apache/arrow/go/v7/arrow/memory"
+       "github.com/apache/arrow/go/v7/internal/hashing"
+       "github.com/goccy/go-json"
+)
+
+// Dictionary represents the type for dictionary-encoded data with a data
+// dependent dictionary.
+//
+// A dictionary array contains an array of non-negative integers (the 
"dictionary"
+// indices") along with a data type containing a "dictionary" corresponding to
+// the distinct values represented in the data.
+//
+// For example, the array:
+//
+//      ["foo", "bar", "foo", "bar", "foo", "bar"]
+//
+// with dictionary ["bar", "foo"], would have the representation of:
+//
+//      indices: [1, 0, 1, 0, 1, 0]
+//      dictionary: ["bar", "foo"]
+//
+// The indices in principle may be any integer type.
+type Dictionary struct {
+       array
+
+       indices Interface
+       dict    Interface
+}
+
+// NewDictionaryArray constructs a dictionary array with the provided indices
+// and dictionary using the given type.
+func NewDictionaryArray(typ arrow.DataType, indices, dict Interface) 
*Dictionary {
+       a := &Dictionary{}
+       a.array.refCount = 1
+       dictdata := NewData(typ, indices.Len(), indices.Data().Buffers(), 
indices.Data().Children(), indices.NullN(), indices.Data().Offset())
+       dictdata.dictionary = dict.Data().(*Data)
+       dict.Data().Retain()
+
+       defer dictdata.Release()
+       a.setData(dictdata)
+       return a
+}
+
+// checkIndexBounds returns an error if any value in the provided integer
+// arraydata is >= the passed upperlimit or < 0. otherwise nil
+func checkIndexBounds(indices *Data, upperlimit uint64) error {
+       if indices.length == 0 {
+               return nil
+       }
+
+       var maxval uint64
+       switch indices.dtype.ID() {
+       case arrow.UINT8:
+               maxval = math.MaxUint8
+       case arrow.UINT16:
+               maxval = math.MaxUint16
+       case arrow.UINT32:
+               maxval = math.MaxUint32
+       case arrow.UINT64:
+               maxval = math.MaxUint64
+       }
+       isSigned := maxval == 0
+       if !isSigned && upperlimit > maxval {
+               return nil
+       }
+
+       // TODO(mtopol): lift BitSetRunReader from parquet to utils
+       // and use it here for performance improvement.
+       var nullbitmap []byte
+       if indices.buffers[0] != nil {
+               nullbitmap = indices.buffers[0].Bytes()
+       }
+
+       var outOfBounds func(i int) error
+       switch indices.dtype.ID() {
+       case arrow.INT8:
+               data := 
arrow.Int8Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] < 0 || data[i] >= int8(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.UINT8:
+               data := 
arrow.Uint8Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] >= uint8(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.INT16:
+               data := 
arrow.Int16Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] < 0 || data[i] >= int16(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.UINT16:
+               data := 
arrow.Uint16Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] >= uint16(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.INT32:
+               data := 
arrow.Int32Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] < 0 || data[i] >= int32(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.UINT32:
+               data := 
arrow.Uint32Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] >= uint32(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.INT64:
+               data := 
arrow.Int64Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] < 0 || data[i] >= int64(upperlimit) {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       case arrow.UINT64:
+               data := 
arrow.Uint64Traits.CastFromBytes(indices.buffers[1].Bytes())
+               outOfBounds = func(i int) error {
+                       if data[i] >= upperlimit {
+                               return fmt.Errorf("index %d out of bounds", 
data[i])
+                       }
+                       return nil
+               }
+       default:
+               return fmt.Errorf("invalid type for bounds checking: %T", 
indices.dtype)
+       }
+
+       for i := 0; i < indices.length; i++ {
+               if len(nullbitmap) > 0 && bitutil.BitIsNotSet(nullbitmap, 
i+indices.offset) {
+                       continue
+               }
+
+               if err := outOfBounds(i + indices.offset); err != nil {
+                       return err
+               }
+       }
+       return nil
+}
+
+// NewValidatedDictionaryArray constructs a dictionary array from the provided 
indices
+// and dictionary arrays, while also performing validation checks to ensure 
correctness
+// such as bounds checking at are usually skipped for performance.
+func NewValidatedDictionaryArray(typ *arrow.DictionaryType, indices, dict 
Interface) (*Dictionary, error) {
+       if indices.DataType().ID() != typ.IndexType.ID() {
+               return nil, fmt.Errorf("dictionary type index (%T) does not 
match indices array type (%T)", typ.IndexType, indices.DataType())
+       }
+
+       if !arrow.TypeEqual(typ.ValueType, dict.DataType()) {
+               return nil, fmt.Errorf("dictionary value type (%T) does not 
match dict array type (%T)", typ.ValueType, dict.DataType())
+       }
+
+       if err := checkIndexBounds(indices.Data().(*Data), uint64(dict.Len())); 
err != nil {
+               return nil, err
+       }
+
+       return NewDictionaryArray(typ, indices, dict), nil
+}
+
+// NewDictionaryData creates a strongly typed Dictionary array from
+// an ArrayData object with a datatype of arrow.Dictionary and a dictionary
+func NewDictionaryData(data arrow.ArrayData) *Dictionary {
+       a := &Dictionary{}
+       a.refCount = 1
+       a.setData(data.(*Data))
+       return a
+}
+
+func (d *Dictionary) Retain() {
+       atomic.AddInt64(&d.refCount, 1)
+}
+
+func (d *Dictionary) Release() {
+       debug.Assert(atomic.LoadInt64(&d.refCount) > 0, "too many releases")
+
+       if atomic.AddInt64(&d.refCount, -1) == 0 {
+               d.data.Release()
+               d.data, d.nullBitmapBytes = nil, nil
+               d.indices.Release()
+               d.indices = nil
+               if d.dict != nil {
+                       d.dict.Release()
+                       d.dict = nil
+               }
+       }
+}
+
+func (d *Dictionary) setData(data *Data) {
+       d.array.setData(data)
+
+       if data.dictionary == nil {
+               panic("arrow/array: no dictionary set in Data for Dictionary 
array")
+       }
+
+       dictType := data.dtype.(*arrow.DictionaryType)
+       debug.Assert(arrow.TypeEqual(dictType.ValueType, 
data.dictionary.DataType()), "mismatched dictionary value types")
+
+       indexData := NewData(dictType.IndexType, data.length, data.buffers, 
data.childData, data.nulls, data.offset)
+       defer indexData.Release()
+       d.indices = MakeFromData(indexData)
+}
+
+// Dictionary returns the values array that makes up the dictionary for this
+// array.
+func (d *Dictionary) Dictionary() Interface {
+       if d.dict == nil {
+               d.dict = MakeFromData(d.data.dictionary)
+       }
+       return d.dict
+}
+
+// Indices returns the underlying array of indices as it's own array
+func (d *Dictionary) Indices() Interface {
+       return d.indices
+}
+
+// CanCompareIndices returns true if the dictionary arrays can be compared
+// without having to unify the dictionaries themselves first.
+func (d *Dictionary) CanCompareIndices(other *Dictionary) bool {
+       if !arrow.TypeEqual(d.indices.DataType(), other.indices.DataType()) {
+               return false
+       }
+
+       minlen := int64(min(d.data.dictionary.length, 
other.data.dictionary.length))
+       return ArraySliceEqual(d.Dictionary(), 0, minlen, other.Dictionary(), 
0, minlen)
+}
+
+func (d *Dictionary) String() string {
+       return fmt.Sprintf("{ dictionary: %v\n  indices: %v }", d.Dictionary(), 
d.Indices())
+}
+
+// GetValueIndex returns the dictionary index for the value at index i of the 
array.
+// The actual value can be retrieved by using 
d.Dictionary().(valuetype).Value(d.GetValueIndex(i))
+func (d *Dictionary) GetValueIndex(i int) int {
+       indiceData := d.data.buffers[1].Bytes()
+       // we know the value is non-negative per the spec, so
+       // we can use the unsigned value regardless.
+       switch d.indices.DataType().ID() {
+       case arrow.UINT8, arrow.INT8:
+               return int(uint8(indiceData[d.data.offset+i]))
+       case arrow.UINT16, arrow.INT16:
+               return 
int(arrow.Uint16Traits.CastFromBytes(indiceData)[d.data.offset+i])
+       case arrow.UINT32, arrow.INT32:
+               return 
int(arrow.Uint32Traits.CastFromBytes(indiceData)[d.data.offset+i])
+       case arrow.UINT64, arrow.INT64:
+               return 
int(arrow.Uint64Traits.CastFromBytes(indiceData)[d.data.offset+i])
+       }
+       debug.Assert(false, "unreachable dictionary index")
+       return -1
+}
+
+func (d *Dictionary) getOneForMarshal(i int) interface{} {
+       if d.IsNull(i) {
+               return nil
+       }
+       vidx := d.GetValueIndex(i)
+       return d.Dictionary().(arraymarshal).getOneForMarshal(vidx)
+}
+
+func (d *Dictionary) MarshalJSON() ([]byte, error) {
+       vals := make([]interface{}, d.Len())
+       for i := 0; i < d.Len(); i++ {
+               vals[i] = d.getOneForMarshal(i)
+       }
+       return json.Marshal(vals)
+}
+
+func arrayEqualDict(l, r *Dictionary) bool {
+       return ArrayEqual(l.Dictionary(), r.Dictionary()) && 
ArrayEqual(l.indices, r.indices)
+}
+
+func arrayApproxEqualDict(l, r *Dictionary, opt equalOption) bool {
+       return arrayApproxEqual(l.Dictionary(), r.Dictionary(), opt) && 
arrayApproxEqual(l.indices, r.indices, opt)
+}
+
+// helper for building the properly typed indices of the dictionary builder
+type indexBuilder struct {
+       Builder
+       Append func(int)
+}
+
+func createIndexBuilder(mem memory.Allocator, dt arrow.FixedWidthDataType) 
(ret indexBuilder, err error) {
+       ret = indexBuilder{Builder: NewBuilder(mem, dt)}
+       switch dt.ID() {
+       case arrow.INT8:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Int8Builder).Append(int8(idx))
+               }
+       case arrow.UINT8:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Uint8Builder).Append(uint8(idx))
+               }
+       case arrow.INT16:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Int16Builder).Append(int16(idx))
+               }
+       case arrow.UINT16:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Uint16Builder).Append(uint16(idx))
+               }
+       case arrow.INT32:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Int32Builder).Append(int32(idx))
+               }
+       case arrow.UINT32:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Uint32Builder).Append(uint32(idx))
+               }
+       case arrow.INT64:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Int64Builder).Append(int64(idx))
+               }
+       case arrow.UINT64:
+               ret.Append = func(idx int) {
+                       ret.Builder.(*Uint64Builder).Append(uint64(idx))
+               }
+       default:
+               debug.Assert(false, "dictionary index type must be integral")
+               err = fmt.Errorf("dictionary index type must be integral, not 
%s", dt)
+       }
+
+       return
+}
+
+// helper function to construct an appropriately typed memo table based on
+// the value type for the dictionary
+func createMemoTable(mem memory.Allocator, dt arrow.DataType) (ret 
hashing.MemoTable, err error) {
+       switch dt.ID() {
+       case arrow.INT8:
+               ret = hashing.NewInt8MemoTable(0)
+       case arrow.UINT8:
+               ret = hashing.NewUint8MemoTable(0)
+       case arrow.INT16:
+               ret = hashing.NewInt16MemoTable(0)
+       case arrow.UINT16:
+               ret = hashing.NewUint16MemoTable(0)
+       case arrow.INT32:
+               ret = hashing.NewInt32MemoTable(0)
+       case arrow.UINT32:
+               ret = hashing.NewUint32MemoTable(0)
+       case arrow.INT64:
+               ret = hashing.NewInt64MemoTable(0)
+       case arrow.UINT64:
+               ret = hashing.NewUint64MemoTable(0)
+       case arrow.DURATION, arrow.TIMESTAMP, arrow.DATE64, arrow.TIME64:
+               ret = hashing.NewInt64MemoTable(0)
+       case arrow.TIME32, arrow.DATE32, arrow.INTERVAL_MONTHS:
+               ret = hashing.NewInt32MemoTable(0)
+       case arrow.FLOAT16:
+               ret = hashing.NewUint16MemoTable(0)
+       case arrow.FLOAT32:
+               ret = hashing.NewFloat32MemoTable(0)
+       case arrow.FLOAT64:
+               ret = hashing.NewFloat64MemoTable(0)
+       case arrow.BINARY, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, 
arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTH_DAY_NANO:
+               ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, 
arrow.BinaryTypes.Binary))
+       case arrow.STRING:
+               ret = hashing.NewBinaryMemoTable(0, 0, NewBinaryBuilder(mem, 
arrow.BinaryTypes.String))
+       case arrow.NULL:
+       default:
+               debug.Assert(false, "unimplemented dictionary value type")
+               err = fmt.Errorf("unimplemented dictionary value type, %s", dt)
+       }
+
+       return
+}
+
+type DictionaryBuilder interface {
+       Builder
+
+       NewDictionaryArray() *Dictionary
+       NewDelta() (indices, delta Interface, err error)
+       AppendArray(Interface) error
+       ResetFull()
+}
+
+type dictionaryBuilder struct {
+       builder
+
+       dt          *arrow.DictionaryType
+       deltaOffset int
+       memoTable   hashing.MemoTable
+       idxBuilder  indexBuilder
+}
+
+func NewDictionaryBuilderWithDict(mem memory.Allocator, dt 
*arrow.DictionaryType, init Interface) DictionaryBuilder {
+       if init != nil && !arrow.TypeEqual(dt.ValueType, init.DataType()) {
+               panic(fmt.Errorf("arrow/array: cannot initialize dictionary 
type %T with array of type %T", dt.ValueType, init.DataType()))
+       }
+
+       idxbldr, err := createIndexBuilder(mem, 
dt.IndexType.(arrow.FixedWidthDataType))
+       if err != nil {
+               panic(fmt.Errorf("arrow/array: unsupported builder for index 
type of %T", dt))
+       }
+
+       memo, err := createMemoTable(mem, dt.ValueType)
+       if err != nil {
+               panic(fmt.Errorf("arrow/array: unsupported builder for value 
type of %T", dt))
+       }
+
+       bldr := dictionaryBuilder{
+               builder:    builder{refCount: 1, mem: mem},
+               idxBuilder: idxbldr,
+               memoTable:  memo,
+               dt:         dt,
+       }
+
+       switch dt.ValueType.ID() {
+       case arrow.NULL:
+               ret := &NullDictionaryBuilder{bldr}
+               debug.Assert(init == nil, "arrow/array: doesn't make sense to 
init a null dictionary")
+               return ret
+       case arrow.UINT8:
+               ret := &Uint8DictionaryBuilder{bldr}
+               if init != nil {
+                       if err = ret.InsertDictValues(init.(*Uint8)); err != 
nil {
+                               panic(err)
+                       }
+               }
+               return ret
+       case arrow.INT8:
+               ret := &Int8DictionaryBuilder{bldr}
+               if init != nil {
+                       if err = ret.InsertDictValues(init.(*Int8)); err != nil 
{
+                               panic(err)

Review comment:
       why is panic the right thing 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-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to