// 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.

//go:build go1.18

package kernels

import (
	
	

	
	
	
	
	
	
	
	
	
	
)

type HashState interface {
	// Reset for another run
	Reset() error
	// Flush out accumulated results from last invocation
	Flush(*exec.ExecResult) error
	// FlushFinal flushes the accumulated results across all invocations
	// of calls. The kernel should not be used again until after
	// Reset() is called.
	FlushFinal(out *exec.ExecResult) error
	// GetDictionary returns the values (keys) accumulated in the dictionary
	// so far.
	GetDictionary() (arrow.ArrayData, error)
	ValueType() arrow.DataType
	// Append prepares the action for the given input (reserving appropriately
	// sized data structures, etc.) and visits the input with the Action
	Append(*exec.KernelCtx, *exec.ArraySpan) error
	Allocator() memory.Allocator
}

type Action interface {
	Reset() error
	Reserve(int) error
	Flush(*exec.ExecResult) error
	FlushFinal(*exec.ExecResult) error
	ObserveFound(int)
	ObserveNotFound(int) error
	ObserveNullFound(int)
	ObserveNullNotFound(int) error
	ShouldEncodeNulls() bool
}

type emptyAction struct {
	mem memory.Allocator
	dt  arrow.DataType
}

func (emptyAction) () error                      { return nil }
func (emptyAction) (int) error                 { return nil }
func (emptyAction) (*exec.ExecResult) error      { return nil }
func (emptyAction) (*exec.ExecResult) error { return nil }
func (emptyAction) (int)                  {}
func (emptyAction) (int) error         { return nil }
func (emptyAction) (int)              {}
func (emptyAction) (int) error     { return nil }
func (emptyAction) () bool           { return true }

type uniqueAction = emptyAction

type NullEncodingBehavior int8

const (
	// NullEncodingMask keeps null input values null in the indices array.
	// It is the zero value and default behavior.
	NullEncodingMask NullEncodingBehavior = iota
	// NullEncodingEncode adds null input values to the dictionary as a regular entry.
	NullEncodingEncode
)

type DictionaryEncodeOptions struct {
	// NullEncoding controls how null input values are represented.
	NullEncoding NullEncodingBehavior `compute:"null_encoding_behavior"`
}

func (DictionaryEncodeOptions) () string { return "DictionaryEncodeOptions" }

func ( DictionaryEncodeOptions) () (scalar.Scalar, error) {
	var  uint32
	switch .NullEncoding {
	case NullEncodingEncode:
		 = 0
	case NullEncodingMask:
		 = 1
	default:
		return nil, fmt.Errorf("%w: invalid null encoding behavior %d", arrow.ErrInvalid, .NullEncoding)
	}

	return scalar.NewStructScalarWithNames(
		[]scalar.Scalar{
			scalar.NewUint32Scalar(),
			scalar.NewBinaryScalar(memory.NewBufferBytes([]byte(.TypeName())), arrow.BinaryTypes.Binary),
		},
		[]string{"null_encoding_behavior", "_type_name"},
	)
}

func ( *DictionaryEncodeOptions) ( *scalar.Struct) error {
	,  := .Field("null_encoding_behavior")
	if  != nil {
		return 
	}

	,  := .(*scalar.Uint32)
	if ! || !.IsValid() {
		return fmt.Errorf("%w: null_encoding_behavior must be a valid uint32 scalar", arrow.ErrInvalid)
	}

	var  NullEncodingBehavior
	switch .Value {
	case 0:
		 = NullEncodingEncode
	case 1:
		 = NullEncodingMask
	default:
		return fmt.Errorf("%w: invalid null encoding behavior %d", arrow.ErrInvalid, .Value)
	}

	.NullEncoding = 
	return nil
}

type dictionaryEncodeAction struct {
	nullEncoding NullEncodingBehavior
	indices      *bufferBuilder[int32]
	validity     validityBuilder
	length       int
	nulls        int
	err          error
}

func ( *dictionaryEncodeAction) () error {
	.indices.reset()
	.validity.reset()
	.length = 0
	.nulls = 0
	.err = nil
	return nil
}

func ( *dictionaryEncodeAction) ( int) error {
	.indices.reserve()
	.validity.Reserve(int64())
	return nil
}

func ( *dictionaryEncodeAction) ( int,  bool) {
	if ! {
		 = 0
	}
	if  < 0 || int64() > int64(1<<31-1) {
		if .err == nil {
			.err = fmt.Errorf("%w: dictionary index %d does not fit in int32", arrow.ErrInvalid, )
		}
		return
	}

	.indices.unsafeAppend(int32())
	.validity.UnsafeAppend()
	.length++
	if ! {
		.nulls++
	}
}

func ( *dictionaryEncodeAction) ( *exec.ExecResult) error {
	if .err != nil {
		return .err
	}

	.Len = int64(.length)
	.Nulls = int64(.nulls)
	if .length != 0 {
		.Buffers[1].WrapBuffer(.indices.finish())
	} else {
		.indices.finish().Release()
	}

	 := .validity.Finish()
	if .nulls != 0 {
		.Buffers[0].WrapBuffer()
	} else if  != nil {
		.Release()
	}

	.length = 0
	.nulls = 0
	return nil
}

func ( *dictionaryEncodeAction) (*exec.ExecResult) error {
	return nil
}

func ( *dictionaryEncodeAction) ( int) {
	.appendIndex(, true)
}

func ( *dictionaryEncodeAction) ( int) error {
	.appendIndex(, true)
	return .err
}

func ( *dictionaryEncodeAction) ( int) {
	if .nullEncoding == NullEncodingMask {
		.appendIndex(0, false)
	} else {
		.appendIndex(, true)
	}
}

func ( *dictionaryEncodeAction) ( int) error {
	.ObserveNullFound()
	return .err
}

func ( *dictionaryEncodeAction) () bool {
	return .nullEncoding == NullEncodingEncode
}

type regularHashState struct {
	mem          memory.Allocator
	typ          arrow.DataType
	memoTable    hashing.MemoTable
	action       Action
	memoReleased bool

	doAppend func(Action, hashing.MemoTable, *exec.ArraySpan) error
}

func ( *regularHashState) () memory.Allocator { return .mem }

func ( *regularHashState) () arrow.DataType { return .typ }

func ( *regularHashState) () error {
	if .memoReleased {
		,  := newMemoTable(.mem, .typ.ID())
		if  != nil {
			return 
		}
		.memoTable = 
		.memoReleased = false
	} else {
		.memoTable.Reset()
	}
	return .action.Reset()
}

func ( *regularHashState) ( *exec.KernelCtx,  *exec.ArraySpan) error {
	if  := .action.Reserve(int(.Len));  != nil {
		return 
	}

	return .doAppend(.action, .memoTable, )
}

func ( *regularHashState) ( *exec.ExecResult) error { return .action.Flush() }
func ( *regularHashState) ( *exec.ExecResult) error {
	return .action.FlushFinal()
}

func ( *regularHashState) () (arrow.ArrayData, error) {
	return array.GetDictArrayData(.mem, .typ, .memoTable, 0)
}

func doAppendBinary[ int32 | int64]( Action,  hashing.MemoTable,  *exec.ArraySpan) error {
	if .Len == 0 {
		return nil
	}

	var (
		            = .Buffers[0].Buf
		           = exec.GetSpanOffsets[](, 1)
		              = .Buffers[2].Buf
		 = .ShouldEncodeNulls()
		         = .(hashing.TypedMemoTable[[]byte])
	)

	return bitutils.VisitBitBlocksShort(, .Offset, .Len,
		func( int64) error {
			 := [[]:[+1]]
			, ,  := .InsertOrGet()
			if  != nil {
				return 
			}
			if  {
				.ObserveFound()
				return nil
			}
			return .ObserveNotFound()
		},
		func() error {
			if ! {
				return .ObserveNullNotFound(-1)
			}

			,  := .GetOrInsertNull()
			if  {
				.ObserveNullFound()
				return nil
			}
			return .ObserveNullNotFound()
		})
}

func doAppendFixedSize( Action,  hashing.MemoTable,  *exec.ArraySpan) error {
	 := int64(.Type.(arrow.FixedWidthDataType).Bytes())
	 := .Buffers[1].Buf[.Offset*:]
	 := .ShouldEncodeNulls()
	 := .(hashing.TypedMemoTable[[]byte])

	return bitutils.VisitBitBlocksShort(.Buffers[0].Buf, .Offset, .Len,
		func( int64) error {
			// fixed size type memo table we use a binary memo table
			// so get the raw bytes
			, ,  := .InsertOrGet([* : (+1)*])
			if  != nil {
				return 
			}
			if  {
				.ObserveFound()
				return nil
			}
			return .ObserveNotFound()
		}, func() error {
			if ! {
				return .ObserveNullNotFound(-1)
			}

			,  := .GetOrInsertNull()
			if  {
				.ObserveNullFound()
				return nil
			}
			return .ObserveNullNotFound()
		})
}

func doAppendNumeric[ uint8 | uint16 | uint32 | uint64]( Action,  hashing.MemoTable,  *exec.ArraySpan) error {
	 := exec.GetSpanValues[](, 1)
	 := .ShouldEncodeNulls()
	 := .(hashing.TypedMemoTable[])
	return bitutils.VisitBitBlocksShort(.Buffers[0].Buf, .Offset, .Len,
		func( int64) error {
			, ,  := .InsertOrGet([])
			if  != nil {
				return 
			}
			if  {
				.ObserveFound()
				return nil
			}
			return .ObserveNotFound()
		}, func() error {
			if ! {
				return .ObserveNullNotFound(-1)
			}

			,  := .GetOrInsertNull()
			if  {
				.ObserveNullFound()
				return nil
			}
			return .ObserveNullNotFound()
		})
}

func doAppendBoolean( Action,  hashing.MemoTable,  *exec.ArraySpan) error {
	if .Len == 0 {
		return nil
	}

	 := .Buffers[1].Buf
	 := .ShouldEncodeNulls()
	return bitutils.VisitBitBlocksShort(.Buffers[0].Buf, .Offset, .Len,
		func( int64) error {
			 := uint8(0)
			if bitutil.BitIsSet(, int(.Offset+)) {
				 = 1
			}
			, ,  := .GetOrInsert()
			if  != nil {
				return 
			}
			if  {
				.ObserveFound()
				return nil
			}
			return .ObserveNotFound()
		}, func() error {
			if ! {
				return .ObserveNullNotFound(-1)
			}

			,  := .GetOrInsertNull()
			if  {
				.ObserveNullFound()
				return nil
			}
			return .ObserveNullNotFound()
		})
}

type nullHashState struct {
	mem      memory.Allocator
	typ      arrow.DataType
	seenNull bool
	action   Action
}

func ( *nullHashState) () memory.Allocator { return .mem }

func ( *nullHashState) () arrow.DataType { return .typ }

func ( *nullHashState) () error {
	.seenNull = false
	return .action.Reset()
}

func ( *nullHashState) ( *exec.KernelCtx,  *exec.ArraySpan) ( error) {
	if  := .action.Reserve(int(.Len));  != nil {
		return 
	}

	for  := 0;  < int(.Len); ++ {
		if  == 0 {
			.seenNull = true
			 = .action.ObserveNullNotFound(0)
		} else {
			.action.ObserveNullFound(0)
		}
	}
	return
}

func ( *nullHashState) ( *exec.ExecResult) error { return .action.Flush() }
func ( *nullHashState) ( *exec.ExecResult) error {
	return .action.FlushFinal()
}

func ( *nullHashState) () (arrow.ArrayData, error) {
	var  arrow.Array
	if .seenNull {
		 = array.NewNull(1)
	} else {
		 = array.NewNull(0)
	}
	 := .Data()
	.Retain()
	.Release()
	return , nil
}

func dictionaryEncodeIdentity( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .Values[0].Array.MakeData()
	defer .Release()
	.TakeOwnership()
	return nil
}

func dictionaryEncodeIdentityChunked( *exec.KernelCtx,  []*arrow.Chunked,  *exec.ExecResult) ([]*exec.ExecResult, error) {
	if len() != 1 {
		return nil, fmt.Errorf("%w: dictionary_encode expects one input", arrow.ErrInvalid)
	}

	 := [0].Chunks()
	if len() == 0 {
		 := &exec.ExecResult{}
		exec.FillZeroLength([0].DataType(), )
		return []*exec.ExecResult{}, nil
	}

	 := make([]*exec.ExecResult, 0, len())
	for ,  := range  {
		 := &exec.ExecResult{}
		.TakeOwnership(.Data())
		 = append(, )
	}
	return , nil
}

func initDictionaryEncodeIdentity( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
	,  := parseDictionaryEncodeOptions(.Options)
	return nil, 
}

type dictionaryHashState struct {
	indicesKernel HashState
	dictionary    arrow.Array
	unifier       array.DictionaryUnifier
	dictValueType arrow.DataType
	indexType     arrow.DataType
}

func ( *dictionaryHashState) () memory.Allocator { return .indicesKernel.Allocator() }

func ( *dictionaryHashState) () {
	if .dictionary != nil {
		.dictionary.Release()
		.dictionary = nil
	}
	if .unifier != nil {
		.unifier.Release()
		.unifier = nil
	}
}

func ( *dictionaryHashState) () error {
	.releaseDictionary()
	return .indicesKernel.Reset()
}
func ( *dictionaryHashState) ( *exec.ExecResult) error {
	return .indicesKernel.Flush()
}
func ( *dictionaryHashState) ( *exec.ExecResult) error {
	return .indicesKernel.FlushFinal()
}
func ( *dictionaryHashState) () (arrow.ArrayData, error) {
	return .indicesKernel.GetDictionary()
}
func ( *dictionaryHashState) () arrow.DataType           { return .indicesKernel.ValueType() }
func ( *dictionaryHashState) () arrow.DataType { return .dictValueType }
func ( *dictionaryHashState) () arrow.Array             { return .dictionary }
func ( *dictionaryHashState) ( *exec.KernelCtx,  *exec.ArraySpan) ( error) {
	// A failed append must not retain the unifier's allocator-backed buffers.
	defer func() {
		if  != nil {
			.releaseDictionary()
		}
	}()

	 := .Dictionary().MakeArray()
	defer .Release()

	if .unifier == nil {
		if .dictionary == nil {
			// Preserve the original indices and dictionary for the common case
			// where all chunks use the same dictionary.
			.Retain()
			.dictionary = 
			return .indicesKernel.Append(, )
		}
		if array.Equal(.dictionary, ) {
			return .indicesKernel.Append(, )
		}

		// Seed the unifier only once. Re-unifying the full accumulated
		// dictionary for every chunk makes many changing dictionaries quadratic.
		.unifier,  = array.NewDictionaryUnifier(.Allocator(), .dictValueType)
		if  != nil {
			return 
		}
		if  = .unifier.Unify(.dictionary);  != nil {
			return 
		}
		.dictionary.Release()
		.dictionary = nil
	}

	,  := .unifier.UnifyAndTranspose()
	if  != nil {
		return 
	}
	defer .Release()
	 := arrow.Int32Traits.CastFromBytes(.Bytes())

	// The unique kernel keeps the input dictionary's index type. Reject
	// transpositions which would truncate a newly assigned dictionary index.
	var  int32 = math.MaxInt32
	switch .indexType.ID() {
	case arrow.INT8:
		 = math.MaxInt8
	case arrow.UINT8:
		 = math.MaxUint8
	case arrow.INT16:
		 = math.MaxInt16
	case arrow.UINT16:
		 = math.MaxUint16
	}
	if  != math.MaxInt32 {
		// Transposition may assign out-of-range IDs to dictionary entries
		// that no valid row references. Only reject referenced IDs.
		 := false
		for ,  := range  {
			if  >  {
				 = true
				break
			}
		}
		if  {
			 := .MakeArray().(*array.Dictionary)
			defer .Release()
			for  := 0;  < .Len(); ++ {
				if .IsNull() {
					continue
				}
				 := .GetValueIndex()
				if  < 0 ||  >= len() {
					return fmt.Errorf("%w: dictionary index %d out of range", arrow.ErrInvalid, )
				}
				if  := [];  >  {
					return fmt.Errorf("%w: unified dictionary index %d exceeds %s capacity",
						arrow.ErrInvalid, , .indexType)
				}
			}
		}
	}

	// Transpose only the current chunk's index buffer. Materializing a new
	// cumulative dictionary here would bring back the quadratic cost.
	 := .indexType.(arrow.FixedWidthDataType).Bytes()
	 := memory.NewResizableBuffer(.Allocator())
	defer .Release()
	.Resize(int(.Len) * )
	if .Nulls == 0 || len(.Buffers[0].Buf) == 0 {
		if  = utils.TransposeIntsBuffers(.indexType, .indexType,
			.Buffers[1].Buf, .Bytes(), int(.Offset), 0, int(.Len), );  != nil {
			return 
		}
	} else {
		// Null index slots may contain arbitrary out-of-bounds values.
		// Only transpose valid runs, leaving the other scratch slots unused.
		 := bitutils.NewSetBitRunReader(.Buffers[0].Buf, .Offset, .Len)
		for {
			 := .NextRun()
			if .AtEnd() {
				break
			}
			if  = utils.TransposeIntsBuffers(.indexType, .indexType,
				.Buffers[1].Buf, .Bytes(), int(.Offset+.Pos),
				int(.Pos), int(.Length), );  != nil {
				return 
			}
		}
	}

	 := *
	.Offset = 0
	.Buffers[1] = exec.BufferSpan{Buf: .Bytes()}
	if .Nulls == 0 || len(.Buffers[0].Buf) == 0 {
		.Buffers[0] = exec.BufferSpan{}
	} else if .Offset != 0 {
		 := memory.NewResizableBuffer(.Allocator())
		defer .Release()
		.Resize(int(bitutil.BytesForBits(.Len)))
		bitutil.CopyBitmap(.Buffers[0].Buf, int(.Offset), int(.Len), .Bytes(), 0)
		.Buffers[0] = exec.BufferSpan{Buf: .Bytes()}
	}

	return .indicesKernel.Append(, &)
}

func nullHashInit( initAction) exec.KernelInitFn {
	return func( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
		 := exec.GetAllocator(.Ctx)
		,  := (.Inputs[0], .Options, )
		if  != nil {
			return nil, 
		}
		 := &nullHashState{
			mem:    ,
			typ:    .Inputs[0],
			action: ,
		}
		.Reset()
		return , nil
	}
}

func newMemoTable( memory.Allocator,  arrow.Type) (hashing.MemoTable, error) {
	switch  {
	case arrow.BOOL, arrow.INT8, arrow.UINT8:
		return hashing.NewMemoTable[uint8](0), nil
	case arrow.INT16, arrow.UINT16:
		return hashing.NewMemoTable[uint16](0), nil
	case arrow.INT32, arrow.UINT32, arrow.FLOAT32, arrow.DECIMAL32,
		arrow.DATE32, arrow.TIME32, arrow.INTERVAL_MONTHS:
		return hashing.NewMemoTable[uint32](0), nil
	case arrow.INT64, arrow.UINT64, arrow.FLOAT64, arrow.DECIMAL64,
		arrow.DATE64, arrow.TIME64, arrow.TIMESTAMP,
		arrow.DURATION, arrow.INTERVAL_DAY_TIME:
		return hashing.NewMemoTable[uint64](0), nil
	case arrow.BINARY, arrow.STRING, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128,
		arrow.DECIMAL256, arrow.INTERVAL_MONTH_DAY_NANO:
		return hashing.NewBinaryMemoTable(0, 0,
			array.NewBinaryBuilder(, arrow.BinaryTypes.Binary)), nil
	case arrow.LARGE_BINARY, arrow.LARGE_STRING:
		return hashing.NewBinaryMemoTable(0, 0,
			array.NewBinaryBuilder(, arrow.BinaryTypes.LargeBinary)), nil
	default:
		return nil, fmt.Errorf("%w: unsupported type %s", arrow.ErrNotImplemented, )
	}
}

func regularHashInit( arrow.DataType,  initAction,  func(Action, hashing.MemoTable, *exec.ArraySpan) error) exec.KernelInitFn {
	return func( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
		 := exec.GetAllocator(.Ctx)
		,  := (.Inputs[0], .Options, )
		if  != nil {
			return nil, 
		}
		,  := newMemoTable(, .ID())
		if  != nil {
			return nil, 
		}

		 := &regularHashState{
			mem:       ,
			typ:       .Inputs[0],
			memoTable: ,
			action:    ,
			doAppend:  ,
		}
		.Reset()
		return , nil
	}
}

func dictionaryHashInit( initAction) exec.KernelInitFn {
	return func( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
		var (
			      = .Inputs[0].(*arrow.DictionaryType)
			 exec.KernelState
			           error
		)

		switch .IndexType.ID() {
		case arrow.INT8, arrow.UINT8:
			,  = getHashInit(arrow.UINT8, )(, )
		case arrow.INT16, arrow.UINT16:
			,  = getHashInit(arrow.UINT16, )(, )
		case arrow.INT32, arrow.UINT32:
			,  = getHashInit(arrow.UINT32, )(, )
		case arrow.INT64, arrow.UINT64:
			,  = getHashInit(arrow.UINT64, )(, )
		default:
			return nil, fmt.Errorf("%w: unsupported dictionary index type", arrow.ErrInvalid)
		}
		if  != nil {
			return nil, 
		}

		return &dictionaryHashState{
			indicesKernel: .(HashState),
			dictValueType: .ValueType,
			indexType:     .IndexType,
		}, nil
	}
}

type initAction func(arrow.DataType, any, memory.Allocator) (Action, error)

func getHashInit( arrow.Type,  initAction) exec.KernelInitFn {
	switch  {
	case arrow.NULL:
		return nullHashInit()
	case arrow.BOOL:
		return regularHashInit(arrow.FixedWidthTypes.Boolean, , doAppendBoolean)
	case arrow.INT8, arrow.UINT8:
		return regularHashInit(arrow.PrimitiveTypes.Uint8, , doAppendNumeric[uint8])
	case arrow.INT16, arrow.UINT16:
		return regularHashInit(arrow.PrimitiveTypes.Uint16, , doAppendNumeric[uint16])
	case arrow.INT32, arrow.UINT32, arrow.FLOAT32,
		arrow.DATE32, arrow.TIME32, arrow.INTERVAL_MONTHS:
		return regularHashInit(arrow.PrimitiveTypes.Uint32, , doAppendNumeric[uint32])
	case arrow.INT64, arrow.UINT64, arrow.FLOAT64,
		arrow.DATE64, arrow.TIME64, arrow.TIMESTAMP,
		arrow.DURATION, arrow.INTERVAL_DAY_TIME:
		return regularHashInit(arrow.PrimitiveTypes.Uint64, , doAppendNumeric[uint64])
	case arrow.BINARY, arrow.STRING:
		return regularHashInit(arrow.BinaryTypes.Binary, , doAppendBinary[int32])
	case arrow.LARGE_BINARY, arrow.LARGE_STRING:
		return regularHashInit(arrow.BinaryTypes.LargeBinary, , doAppendBinary[int64])
	case arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.DECIMAL256:
		return regularHashInit(arrow.BinaryTypes.Binary, , doAppendFixedSize)
	case arrow.INTERVAL_MONTH_DAY_NANO:
		return regularHashInit(arrow.FixedWidthTypes.MonthDayNanoInterval, , doAppendFixedSize)
	default:
		debug.Assert(false, "unsupported hash init type")
		return nil
	}
}

func hashExec( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	,  := .State.(HashState)
	if ! {
		return fmt.Errorf("%w: bad initialization of hash state", arrow.ErrInvalid)
	}

	if  := .Append(, &.Values[0].Array);  != nil {
		return 
	}

	return .Flush()
}

func uniqueFinalize( *exec.KernelCtx,  []*exec.ArraySpan) ([]*exec.ArraySpan, error) {
	,  := .State.(HashState)
	if ! {
		return nil, fmt.Errorf("%w: HashState in invalid state", arrow.ErrInvalid)
	}

	for ,  := range  {
		// release any pre-allocation we did
		.Release()
	}

	,  := .GetDictionary()
	if  != nil {
		return nil, 
	}
	defer .Release()

	var  exec.ArraySpan
	.TakeOwnership()
	return []*exec.ArraySpan{&}, nil
}

func ensureHashDictionary( *exec.KernelCtx,  *dictionaryHashState) (*exec.ArraySpan, error) {
	 := &exec.ArraySpan{}

	if .unifier != nil {
		// GetResult materializes the unified dictionary once, after all chunks.
		, ,  := .unifier.GetResult()
		.unifier.Release()
		.unifier = nil
		if  != nil {
			return nil, 
		}
		.dictionary = 
	}
	if .dictionary != nil {
		.TakeOwnership(.dictionary.Data())
		.dictionary.Release()
		.dictionary = nil
		return , nil
	}

	exec.FillZeroLength(.DictionaryValueType(), )
	return , nil
}

func uniqueFinalizeDictionary( *exec.KernelCtx,  []*exec.ArraySpan) ( []*exec.ArraySpan,  error) {
	if ,  = uniqueFinalize(, );  != nil {
		return
	}

	,  := .State.(*dictionaryHashState)
	if ! {
		return nil, fmt.Errorf("%w: state should be *dictionaryHashState", arrow.ErrInvalid)
	}

	,  := ensureHashDictionary(, )
	if  != nil {
		return nil, 
	}
	[0].SetDictionary()
	return
}

func addHashKernels( exec.VectorKernel,  initAction,  exec.OutputType) []exec.VectorKernel {
	 := make([]exec.VectorKernel, 0)
	.Init = getHashInit(arrow.BOOL, )
	.Signature = &exec.KernelSignature{
		InputTypes: []exec.InputType{exec.NewExactInput(arrow.FixedWidthTypes.Boolean)},
		OutType:    ,
	}
	 = append(, )

	for ,  := range primitiveTypes {
		.Init = getHashInit(.ID(), )
		.Signature = &exec.KernelSignature{
			InputTypes: []exec.InputType{exec.NewExactInput()},
			OutType:    ,
		}
		 = append(, )
	}

	 := []arrow.Type{arrow.TIME32, arrow.TIME64, arrow.TIMESTAMP,
		arrow.DURATION, arrow.FIXED_SIZE_BINARY, arrow.DECIMAL128, arrow.DECIMAL256,
		arrow.INTERVAL_DAY_TIME, arrow.INTERVAL_MONTHS, arrow.INTERVAL_MONTH_DAY_NANO}
	for ,  := range  {
		.Init = getHashInit(, )
		.Signature = &exec.KernelSignature{
			InputTypes: []exec.InputType{exec.NewIDInput()},
			OutType:    ,
		}
		 = append(, )
	}

	return 
}

func initUnique( arrow.DataType,  any,  memory.Allocator) (Action, error) {
	return uniqueAction{mem: , dt: }, nil
}

func parseDictionaryEncodeOptions( any) (DictionaryEncodeOptions, error) {
	 := DictionaryEncodeOptions{}
	switch v := .(type) {
	case nil:
	case DictionaryEncodeOptions:
		 = 
	case *DictionaryEncodeOptions:
		if  != nil {
			 = *
		}
	default:
		return , fmt.Errorf("%w: expected DictionaryEncodeOptions, got %T", arrow.ErrInvalid, )
	}

	if .NullEncoding != NullEncodingMask && .NullEncoding != NullEncodingEncode {
		return , fmt.Errorf("%w: invalid null encoding behavior %d", arrow.ErrInvalid, .NullEncoding)
	}
	return , nil
}

func initDictionaryEncode( arrow.DataType,  any,  memory.Allocator) (Action, error) {
	,  := parseDictionaryEncodeOptions()
	if  != nil {
		return nil, 
	}

	return &dictionaryEncodeAction{
		nullEncoding: .NullEncoding,
		indices:      newBufferBuilder[int32](),
		validity:     validityBuilder{mem: },
	}, nil
}

var outputDictionaryType = exec.NewComputedOutputType(func( *exec.KernelCtx,  []arrow.DataType) (arrow.DataType, error) {
	if len() != 1 {
		return nil, fmt.Errorf("%w: dictionary_encode expects one input type", arrow.ErrInvalid)
	}
	return &arrow.DictionaryType{
		IndexType: arrow.PrimitiveTypes.Int32,
		ValueType: [0],
	}, nil
})

func dictionaryEncodeFinalize( *exec.KernelCtx,  []*exec.ArraySpan) ([]*exec.ArraySpan, error) {
	,  := .State.(HashState)
	if ! {
		return nil, fmt.Errorf("%w: HashState in invalid state", arrow.ErrInvalid)
	}
	defer releaseHashMemo()

	,  := .GetDictionary()
	if  != nil {
		return nil, 
	}
	defer .Release()

	for ,  := range  {
		var  exec.ArraySpan
		.TakeOwnership()
		.SetDictionary(&)
	}
	return , nil
}

func releaseHashMemo( HashState) {
	if ,  := .(*regularHashState);  {
		if ,  := .memoTable.(*hashing.BinaryMemoTable);  && !.memoReleased {
			.Release()
			.memoReleased = true
		}
	}
}

func () (, ,  []exec.VectorKernel) {
	var  exec.VectorKernel
	.ExecFn = hashExec

	// unique only writes its output during finalization. Avoid allocating
	// temporary buffers for every chunk, especially when append fails.
	.NullHandling = exec.NullComputedNoPrealloc
	.MemAlloc = exec.MemNoPrealloc
	.Finalize = uniqueFinalize
	.OutputChunked = false
	.CanExecuteChunkWise = true
	 = addHashKernels(, initUnique, OutputFirstType)

	// dictionary unique
	.Init = dictionaryHashInit(initUnique)
	.Finalize = uniqueFinalizeDictionary
	.Signature = &exec.KernelSignature{
		InputTypes: []exec.InputType{exec.NewIDInput(arrow.DICTIONARY)},
		OutType:    OutputFirstType,
	}
	 = append(, )

	// dictionary encode
	.Finalize = dictionaryEncodeFinalize
	.OutputChunked = true
	.NullHandling = exec.NullComputedNoPrealloc
	.MemAlloc = exec.MemNoPrealloc
	 = addHashKernels(, initDictionaryEncode, outputDictionaryType)
	 := exec.NewVectorKernelWithSig(
		&exec.KernelSignature{
			InputTypes: []exec.InputType{exec.NewIDInput(arrow.DICTIONARY)},
			OutType:    OutputFirstType,
		},
		dictionaryEncodeIdentity,
		initDictionaryEncodeIdentity)
	.CanExecuteChunkWise = false
	.ExecChunked = dictionaryEncodeIdentityChunked
	 = append(, )

	return
}