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

	
	
	
)

// Validator is implemented by array types that provide type-specific
// consistency checks. Validate and ValidateFull also validate generic layout
// and nested child data for every array type.
type Validator interface {
	arrow.Array
	// Validate performs a basic O(1) consistency check.
	Validate() error
	// ValidateFull performs a thorough O(n) consistency check.
	ValidateFull() error
}

// Validate performs a basic O(1) consistency check on arr, returning an error
// if the array's internal buffers or nested child data are inconsistent.
// Run-end encoded arrays may omit the always-nil buffer placeholder used by
// some constructors.
//
// Use this to detect corrupted data from untrusted sources such as Arrow Flight
// or Flight SQL servers before accessing values, which may otherwise panic.
func ( arrow.Array) error {
	return validateArray(, false, "")
}

// ValidateFull performs a thorough O(n) consistency check on arr, returning an
// error if the array's internal buffers or nested child data are inconsistent.
//
// Unlike Validate, this checks every element and is therefore O(n). Use this
// when receiving data from untrusted sources where subtle corruption (e.g.
// non-monotonic offsets) may not be detected by Validate alone.
func ( arrow.Array) error {
	return validateArray(, true, "")
}

func validateArray( arrow.Array,  bool,  string) error {
	if  == nil {
		return nil
	}

	,  := .Data().(*Data)
	if ! ||  == nil {
		return validationError(, fmt.Errorf("arrow/array: array does not expose internal data"))
	}

	if  := validateArrayData();  != nil {
		return validationError(, )
	}
	if  := validateArrayStructure();  != nil {
		return validationError(, )
	}
	if  {
		if  := validateNullCount();  != nil {
			return validationError(, )
		}
	}

	if ,  := .(Validator);  {
		var  error
		if  {
			 = .ValidateFull()
		} else {
			 = .Validate()
		}
		if  != nil {
			return validationError(, )
		}
	}

	// an extension array's indices are checked with its storage below
	if  && .DataType().ID() == arrow.DICTIONARY {
		 := .dictionary
		if  != nil {
			 := .DataType().(*arrow.DictionaryType)
			 := NewData(.IndexType, .length, .buffers, nil, .nulls, .offset)
			 := checkIndexBounds(, uint64(.Len()))
			.Release()
			if  != nil {
				return validationError(joinValidationPath(, "dictionary indices"), )
			}
		}
	}

	if ,  := .(ExtensionArray);  {
		return (.Storage(), , joinValidationPath(, "storage"))
	}

	for ,  := range .Children() {
		,  := makeArrayFromData()
		if  != nil {
			return validationError(joinValidationPath(, validationChildPath(.DataType(), )), )
		}

		 := joinValidationPath(, validationChildPath(.DataType(), ))
		 = (, , )
		.Release()
		if  != nil {
			return 
		}
	}

	if  := .dictionary;  != nil {
		,  := makeArrayFromData()
		if  != nil {
			return validationError(joinValidationPath(, "dictionary"), )
		}

		 = (, , joinValidationPath(, "dictionary"))
		.Release()
		if  != nil {
			return 
		}
	}

	return nil
}

func validateNullCount( *Data) error {
	if .nulls == UnknownNullCount {
		return nil
	}

	var  int
	switch storageType(.dtype).ID() {
	case arrow.NULL:
		 = .length
	case arrow.SPARSE_UNION, arrow.DENSE_UNION, arrow.RUN_END_ENCODED:
		 = 0
	default:
		if len(.buffers) > 0 && .buffers[0] != nil {
			 = .length - bitutil.CountSetBits(.buffers[0].Bytes(), .offset, .length)
		}
	}

	if  != .nulls {
		return fmt.Errorf("arrow/array: null count value (%d) does not match actual number of nulls in array (%d)", .nulls, )
	}
	return nil
}

func storageType( arrow.DataType) arrow.DataType {
	if ,  := .(arrow.ExtensionType);  {
		return .StorageType()
	}
	return 
}

func validateArrayData( *Data) error {
	if  == nil || .dtype == nil {
		return fmt.Errorf("arrow/array: array data has no data type")
	}
	if .offset < 0 {
		return fmt.Errorf("arrow/array: array offset is negative: %d", .offset)
	}
	if .length < 0 {
		return fmt.Errorf("arrow/array: array length is negative: %d", .length)
	}
	if .nulls < UnknownNullCount || .nulls > .length {
		return fmt.Errorf("arrow/array: invalid null count %d for length %d", .nulls, .length)
	}

	 := int64(.offset) + int64(.length)
	if  < int64(.offset) {
		return fmt.Errorf("arrow/array: array offset and length overflow")
	}

	// REE arrays have no physical buffers. Constructors and IPC may include a
	// nil placeholder, but builders and C Data imports omit it.
	 := storageType(.dtype).ID()
	if len(.buffers) == 0 &&  == arrow.RUN_END_ENCODED {
		return nil
	}

	 := .dtype.Layout()
	// Union arrays reserve the first buffer slot for a validity bitmap, even
	// though that slot must be nil and is not part of their type layout.
	 := 0
	if  == arrow.SPARSE_UNION ||  == arrow.DENSE_UNION {
		 = 1
	}
	 := len(.buffers) - 
	if  < 0 {
		 = 0
	}
	if  < len(.Buffers) {
		return fmt.Errorf("arrow/array: expected at least %d buffers for %s, got %d",
			len(.Buffers), .dtype, )
	}
	if .VariadicSpec == nil &&  > len(.Buffers) {
		return fmt.Errorf("arrow/array: expected at most %d buffers for %s, got %d",
			len(.Buffers), .dtype, )
	}

	for ,  := range .Buffers {
		if  := validateBuffer(.buffers[+], , , .length, +);  != nil {
			return 
		}
	}
	if .VariadicSpec != nil {
		for  := len(.Buffers);  < ; ++ {
			if  := validateBuffer(.buffers[+], *.VariadicSpec, , .length, +);  != nil {
				return 
			}
		}
	}
	return nil
}

func validateBuffer( *memory.Buffer,  arrow.BufferSpec,  int64, ,  int) error {
	if  == nil {
		if .Kind == arrow.KindFixedWidth {
			if  > 0 {
				return fmt.Errorf("arrow/array: buffer %d is nil for non-empty layout kind %v", , .Kind)
			}
		}
		return nil
	}

	 := int64(.Len())
	switch .Kind {
	case arrow.KindFixedWidth:
		if .ByteWidth <= 0 {
			return fmt.Errorf("arrow/array: buffer %d has invalid fixed width %d", , .ByteWidth)
		}
		if  > /int64(.ByteWidth) {
			return fmt.Errorf("arrow/array: buffer %d is too small for offset %d and length %d", , -int64(), )
		}
	case arrow.KindBitmap:
		if int64(bitutil.BytesForBits()) >  {
			return fmt.Errorf("arrow/array: bitmap buffer %d is too small for offset %d and length %d", , -int64(), )
		}
	case arrow.KindVarWidth:
		return nil
	case arrow.KindAlwaysNull:
		return fmt.Errorf("arrow/array: buffer %d must be nil for an always-null layout", )
	}
	return nil
}

func validateArrayStructure( *Data) error {
	 := .Children()
	if ,  := .DataType().(arrow.NestedType);  {
		 := .Fields()
		if len() != len() {
			return fmt.Errorf("arrow/array: %s expects %d child arrays, got %d", .DataType(), len(), len())
		}
		for ,  := range  {
			if  == nil {
				return fmt.Errorf("arrow/array: child %d of %s is nil", , .DataType())
			}
			if !arrow.TypeEqual([].Type, .DataType()) {
				return fmt.Errorf("arrow/array: child %d of %s has type %s, want %s",
					, .DataType(), .DataType(), [].Type)
			}
		}
	} else if len() != 0 {
		return fmt.Errorf("arrow/array: %s must not have child arrays", .DataType())
	}

	if .DataType().Layout().HasDict {
		,  := storageType(.DataType()).(*arrow.DictionaryType)
		if ! {
			return fmt.Errorf("arrow/array: datatype %s declares dictionary storage but is not a dictionary type", .DataType())
		}
		if  := .dictionary;  != nil && !arrow.TypeEqual(.ValueType, .DataType()) {
			return fmt.Errorf("arrow/array: dictionary has type %s, want %s", .DataType(), .ValueType)
		}
		if .Len() > 0 && .dictionary == nil {
			return fmt.Errorf("arrow/array: non-empty dictionary array has no dictionary")
		}
	}
	return nil
}

func validateListArray( *List,  bool) error {
	if  := validateArrayData(.data);  != nil {
		return 
	}
	if len(.data.childData) != 1 || .data.childData[0] == nil {
		return fmt.Errorf("arrow/array: list array must have one non-nil child array")
	}
	// MAP uses the list-like entry layout; large-list variants have dedicated validators.
	,  := .data.dtype.(arrow.ListLikeType)
	if ! || .ID() == arrow.LARGE_LIST || .ID() == arrow.LARGE_LIST_VIEW {
		return fmt.Errorf("arrow/array: invalid datatype %s for list array", .data.dtype)
	}
	if !arrow.TypeEqual(.Elem(), .data.childData[0].DataType()) {
		return fmt.Errorf("arrow/array: list values have type %s, want %s", .data.childData[0].DataType(), .Elem())
	}
	if len(.offsets) == 0 && .data.length > 0 {
		return fmt.Errorf("arrow/array: non-empty list array has no offsets")
	}
	return validateListOffsets(.offsets, .data, .data.childData[0].Len(), )
}

func validateLargeListArray( *LargeList,  bool) error {
	if  := validateArrayData(.data);  != nil {
		return 
	}
	if len(.data.childData) != 1 || .data.childData[0] == nil {
		return fmt.Errorf("arrow/array: large list array must have one non-nil child array")
	}
	,  := .data.dtype.(arrow.ListLikeType)
	if ! || .ID() != arrow.LARGE_LIST {
		return fmt.Errorf("arrow/array: invalid datatype %s for large list array", .data.dtype)
	}
	if !arrow.TypeEqual(.Elem(), .data.childData[0].DataType()) {
		return fmt.Errorf("arrow/array: large list values have type %s, want %s", .data.childData[0].DataType(), .Elem())
	}
	if len(.offsets) == 0 && .data.length > 0 {
		return fmt.Errorf("arrow/array: non-empty large list array has no offsets")
	}
	return validateListOffsets(.offsets, .data, .data.childData[0].Len(), )
}

func validateListOffsets( interface{},  *Data,  int,  bool) error {
	if .length == 0 {
		return nil
	}
	 := int64(.offset)
	 :=  + int64(.length) + 1
	if  <  ||  > int64(offsetLength()) {
		return fmt.Errorf("arrow/array: list offsets buffer is too small for offset %d and length %d", .offset, .length)
	}
	 := func( int64) int64 {
		switch v := .(type) {
		case []int32:
			return int64([int()])
		case []int64:
			return [int()]
		default:
			return 0
		}
	}

	 := ()
	 := ( - 1)
	if  := validateListOffset(, , );  != nil {
		return 
	}
	if  := validateListOffset(, -1, );  != nil {
		return 
	}
	if ! {
		return nil
	}

	 := 
	for  :=  + 1;  < ; ++ {
		 := ()
		if  < 0 ||  > int64() {
			return fmt.Errorf("arrow/array: list offset at index %d out of bounds: %d", , )
		}
		if  <  {
			return fmt.Errorf("arrow/array: list offsets are not monotonically non-decreasing at index %d: %d < %d",
				, , )
		}
		 = 
	}
	return nil
}

func offsetLength( interface{}) int {
	switch v := .(type) {
	case []int32:
		return len()
	case []int64:
		return len()
	default:
		return 0
	}
}

func validateListOffset( int64,  int64,  int) error {
	if  < 0 {
		return fmt.Errorf("arrow/array: list offset at index %d is negative: %d", , )
	}
	if  > int64() {
		return fmt.Errorf("arrow/array: list offset at index %d out of bounds: %d > %d", , , )
	}
	return nil
}

func validateFixedSizeListArray( *FixedSizeList) error {
	if  := validateArrayData(.data);  != nil {
		return 
	}
	if len(.data.childData) != 1 || .data.childData[0] == nil {
		return fmt.Errorf("arrow/array: fixed-size list array must have one non-nil child array")
	}
	,  := .data.dtype.(*arrow.FixedSizeListType)
	if ! {
		return fmt.Errorf("arrow/array: invalid datatype %s for fixed-size list array", .data.dtype)
	}
	if !arrow.TypeEqual(.Elem(), .data.childData[0].DataType()) {
		return fmt.Errorf("arrow/array: fixed-size list values have type %s, want %s", .data.childData[0].DataType(), .Elem())
	}
	 := int64(.data.offset) + int64(.data.length)
	 := int64(.Len())
	if  < 0 {
		return fmt.Errorf("arrow/array: fixed-size list has invalid item count %d", )
	}
	if  > 0 &&  > int64(.data.childData[0].Len())/ {
		return fmt.Errorf("arrow/array: fixed-size list child length %d is too small for offset %d and length %d",
			.data.childData[0].Len(), .data.offset, .data.length)
	}
	return nil
}

func makeArrayFromData( arrow.ArrayData) ( arrow.Array,  error) {
	defer func() {
		if  := recover();  != nil {
			 = fmt.Errorf("arrow/array: failed to construct child array: %v", )
		}
	}()
	return MakeFromData(), nil
}

func validationChildPath( arrow.DataType,  int) string {
	if ,  := .(arrow.NestedType);  {
		 := .Fields()
		if  >= 0 &&  < len() {
			 := []
			if .ID() == arrow.STRUCT || .ID() == arrow.SPARSE_UNION || .ID() == arrow.DENSE_UNION || .ID() == arrow.RUN_END_ENCODED {
				return fmt.Sprintf("field %q", .Name)
			}
		}
	}

	switch .ID() {
	case arrow.LIST, arrow.LARGE_LIST, arrow.FIXED_SIZE_LIST:
		return "list values"
	case arrow.LIST_VIEW, arrow.LARGE_LIST_VIEW:
		return "list view values"
	case arrow.MAP:
		return "map entries"
	default:
		return fmt.Sprintf("child %d", )
	}
}

func joinValidationPath(,  string) string {
	if  == "" {
		return 
	}
	return  + " -> " + 
}

func validationError( string,  error) error {
	if  == nil ||  == "" {
		return 
	}
	return fmt.Errorf("%s: %w", , )
}

// ValidateRecord validates each column in rec using Validate, returning the
// first error encountered. The error includes the column index and field name.
func ( arrow.RecordBatch) error {
	for  := int64(0);  < .NumCols(); ++ {
		if  := Validate(.Column(int()));  != nil {
			return fmt.Errorf("column %d (%s): %w", , .Schema().Field(int()).Name, )
		}
	}
	return nil
}

// ValidateRecordFull validates each column in rec using ValidateFull, returning
// the first error encountered. The error includes the column index and field name.
func ( arrow.RecordBatch) error {
	for  := int64(0);  < .NumCols(); ++ {
		if  := ValidateFull(.Column(int()));  != nil {
			return fmt.Errorf("column %d (%s): %w", , .Schema().Field(int()).Name, )
		}
	}
	return nil
}