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

	
	
	
)

func validateUtf8View( *exec.ArraySpan) error {
	 := arrow.ViewHeaderTraits.CastFromBytes(.Buffers[1].Buf)
	 := make([][]byte, 0, len(.Buffers)-2)
	for  := 2;  < len(.Buffers); ++ {
		 = append(, .Buffers[].Buf)
	}
	return validateUTF8Sequence(.Buffers[0].Buf, .Offset, .Len,
		func( int64) []byte {
			 := &[.Offset+]
			if .IsInline() {
				return .InlineBytes()
			}
			 := .BufferOffset()
			return [.BufferIndex()][ : +int32(.Len())]
		})
}

func unsafeStringBytes( string) []byte {
	if len() == 0 {
		return nil
	}
	return unsafe.Slice(unsafe.StringData(), len())
}

type binaryAppender struct {
	bldr        array.Builder
	appendBytes func([]byte)
	reserveData func(int)
}

func newBinaryAppender( array.Builder) (binaryAppender, error) {
	switch b := .(type) {
	case *array.BinaryBuilder:
		return binaryAppender{bldr: , appendBytes: .Append, reserveData: .ReserveData}, nil
	case *array.StringBuilder:
		return binaryAppender{bldr: , appendBytes: .BinaryBuilder.Append, reserveData: .ReserveData}, nil
	case *array.LargeStringBuilder:
		return binaryAppender{bldr: , appendBytes: .BinaryBuilder.Append, reserveData: .ReserveData}, nil
	case *array.BinaryViewBuilder:
		return binaryAppender{bldr: , appendBytes: .Append, reserveData: .ReserveData}, nil
	case *array.StringViewBuilder:
		return binaryAppender{bldr: , appendBytes: .BinaryViewBuilder.Append, reserveData: .ReserveData}, nil
	default:
		return binaryAppender{}, fmt.Errorf("%w: unsupported builder type %T for binary-like output",
			arrow.ErrNotImplemented, )
	}
}

// binaryLikeValueAccessor returns a per-index byte slice accessor for any
// binary-like arrow array. Shared by CastBinaryToBinaryView and
// CastBinaryViewToBinary so the input-type switch has one source of truth.
func binaryLikeValueAccessor( arrow.Array) (func(int) []byte, error) {
	switch a := .(type) {
	case *array.Binary:
		return .Value, nil
	case *array.LargeBinary:
		return .Value, nil
	case *array.String:
		return func( int) []byte { return unsafeStringBytes(.Value()) }, nil
	case *array.LargeString:
		return func( int) []byte { return unsafeStringBytes(.Value()) }, nil
	case *array.FixedSizeBinary:
		return .Value, nil
	case *array.BinaryView:
		return .Value, nil
	case *array.StringView:
		return func( int) []byte { return unsafeStringBytes(.Value()) }, nil
	default:
		return nil, fmt.Errorf("%w: unsupported binary-like type: %s",
			arrow.ErrNotImplemented, .DataType())
	}
}

// appendBinaryValues drives the null-preserving append loop shared by
// both directions of the binary<->view cast kernels.
func appendBinaryValues( arrow.Array,  func(int) []byte,  binaryAppender) {
	for  := 0;  < .Len(); ++ {
		if .IsNull() {
			.bldr.AppendNull()
			continue
		}
		.appendBytes(())
	}
}

// SumOutOfLineBytes returns the total non-inline payload (in bytes) that
// would be written to a view array's overflow buffer when iterating n
// positions with the given predicates, and arrow.ErrInvalid if the total
// exceeds the single-overflow-buffer limit (math.MaxInt32). Used both by
// the binary-to-view cast kernel here and by the cast meta function's
// view-coalescing helpers (where the closures translate dictionary or
// chunk positions into value-level lookups).
func ( int,  func(int) bool,  func(int) int) (int64, error) {
	var  int64
	for  := 0;  < ; ++ {
		if () {
			continue
		}
		 := ()
		if !arrow.IsViewInline() {
			 += int64()
			if  > math.MaxInt32 {
				return 0, fmt.Errorf("%w: view out-of-line payload (%d bytes) exceeds single-buffer limit (%d bytes)",
					arrow.ErrInvalid, , math.MaxInt32)
			}
		}
	}
	return , nil
}

// CastBinaryToBinaryView casts a Binary, LargeBinary, String, LargeString,
// or FixedSizeBinary array into a BinaryView or StringView array. When the
// source is a non-utf8 binary type and the destination is a utf8 view type,
// every non-null element is validated as UTF-8 unless
// CastOptions.AllowInvalidUtf8 is set.
func ( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(CastState)
	 := &.Values[0].Array
	 := .Type.(arrow.BinaryDataType)

	if shouldValidateUTF8(.Type, , .AllowInvalidUtf8) {
		switch .Type.ID() {
		case arrow.BINARY:
			if  := validateUtf8[int32]();  != nil {
				return 
			}
		case arrow.LARGE_BINARY:
			if  := validateUtf8[int64]();  != nil {
				return 
			}
		case arrow.FIXED_SIZE_BINARY:
			if  := validateUtf8Fsb();  != nil {
				return 
			}
		}
	}

	 := array.NewBuilder(exec.GetAllocator(.Ctx), .Type)
	defer .Release()
	.Reserve(int(.Len))

	,  := newBinaryAppender()
	if  != nil {
		return 
	}

	 := .MakeArray()
	defer .Release()

	,  := binaryLikeValueAccessor()
	if  != nil {
		return fmt.Errorf("%w: unsupported input type for cast to %s: %s",
			arrow.ErrNotImplemented, .Type, .Type)
	}

	// Pre-size the out-of-line data buffer to the total required capacity so
	// the builder allocates a single overflow block. ArraySpan only has three
	// buffer slots (bitmap + view headers + one data buffer); if we let the
	// builder spill into a second block, TakeOwnership would index past
	// Buffers[2] and panic.
	,  := SumOutOfLineBytes(.Len(), .IsNull,
		func( int) int { return len(()) })
	if  != nil {
		return fmt.Errorf("cast from %s to %s: %w", .Type, .Type, )
	}
	if  > 0 {
		.reserveData(int())
	}

	appendBinaryValues(, , )

	 := .bldr.NewArray()
	defer .Release()
	.TakeOwnership(.Data())
	return nil
}

// CastBinaryViewToBinary casts a BinaryView or StringView array into a
// Binary, LargeBinary, String, or LargeString array, materializing the
// referenced byte ranges into a single contiguous data buffer. UTF-8
// validation is performed when casting from a non-utf8 view into a utf8
// destination unless CastOptions.AllowInvalidUtf8 is set.
func [ int32 | int64]( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(CastState)
	 := &.Values[0].Array
	 := .Type.(arrow.BinaryDataType)
	 := .Type.(arrow.BinaryDataType)

	if shouldValidateUTF8(, , .AllowInvalidUtf8) {
		if  := validateUtf8View();  != nil {
			return 
		}
	}

	 := array.NewBuilder(exec.GetAllocator(.Ctx), .Type)
	defer .Release()
	.Reserve(int(.Len))

	,  := newBinaryAppender()
	if  != nil {
		return 
	}

	 := .MakeArray()
	defer .Release()

	,  := binaryLikeValueAccessor()
	if  != nil {
		return fmt.Errorf("%w: unsupported input type for view-to-binary cast: %s",
			arrow.ErrNotImplemented, .Type)
	}

	var  int64
	for  := 0;  < .Len(); ++ {
		if !.IsNull() {
			 += int64(len(()))
		}
	}
	if  > int64(MaxOf[]()) {
		return fmt.Errorf("%w: failed casting from %s to %s: input array too large",
			arrow.ErrInvalid, .Type, .Type)
	}
	 := int64(^uint(0) >> 1)
	if  >  {
		return fmt.Errorf("%w: failed casting from %s to %s: output data buffer too large for this platform",
			arrow.ErrInvalid, .Type, .Type)
	}
	if  > 0 {
		.reserveData(int())
	}

	appendBinaryValues(, , )

	 := .bldr.NewArray()
	defer .Release()
	.TakeOwnership(.Data())
	return nil
}

// CastBinaryViewToBinaryView handles casts between BinaryView and StringView
// (and same-type view casts). The cast is zero-copy; UTF-8 validation is
// performed when casting from a binary_view into a string_view unless
// CastOptions.AllowInvalidUtf8 is set.
func ( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(CastState)
	 := &.Values[0].Array
	 := .Type.(arrow.BinaryDataType)
	 := .Type.(arrow.BinaryDataType)

	if shouldValidateUTF8(, , .AllowInvalidUtf8) {
		if  := validateUtf8View();  != nil {
			return 
		}
	}

	return ZeroCopyCastExec(, , )
}