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

	
	
	
	
	
	
)

//go:generate go tool stringer -type=RoundMode

type RoundMode int8

const (
	// Round to nearest integer less than or equal in magnitude (aka "floor")
	RoundDown RoundMode = iota
	// Round to nearest integer greater than or equal in magnitude (aka "ceil")
	RoundUp
	// Get integral part without fractional digits (aka "trunc")
	TowardsZero
	// Round negative values with DOWN and positive values with UP
	AwayFromZero
	// Round ties with DOWN (aka "round half towards negative infinity")
	HalfDown
	// Round ties with UP (aka "round half towards positive infinity")
	HalfUp
	// Round ties with TowardsZero (aka "round half away from infinity")
	HalfTowardsZero
	// Round ties with AwayFromZero (aka "round half towards infinity")
	HalfAwayFromZero
	// Round ties to nearest even integer
	HalfToEven
	// Round ties to nearest odd integer
	HalfToOdd
)

type RoundOptions struct {
	NDigits int64
	Mode    RoundMode
}

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

type RoundState struct {
	RoundOptions
	Pow10 float64
}

func ( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
	var  RoundState

	,  := .Options.(*RoundOptions)
	if  {
		.RoundOptions = *
	} else {
		if .RoundOptions,  = .Options.(RoundOptions); ! {
			return nil, fmt.Errorf("%w: attempted to initialize kernel state from invalid function options",
				arrow.ErrInvalid)
		}
	}

	// Only positive exponents for powers of 10 are used because combining
	// multiply and division operations produced more stable rounding than
	// using multiply-only.  Refer to NumPy's round implementation:
	// https://github.com/numpy/numpy/blob/7b2f20b406d27364c812f7a81a9c901afbd3600c/numpy/core/src/multiarray/calculation.c#L589
	.Pow10 = math.Pow10(int(math.Abs(float64(.NDigits))))
	return , nil
}

type RoundToMultipleOptions struct {
	// Multiple is the multiple to round to.
	//
	// Should be a positive numeric scalar of a type compatible
	// with the argument to be rounded. The cast kernel is used
	// to convert the rounding multiple to match the result type.
	Multiple scalar.Scalar
	// Mode is the rounding and tie-breaking mode
	Mode RoundMode
}

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

type RoundToMultipleState = RoundToMultipleOptions

func isPositive( scalar.Scalar) bool {
	switch s := .(type) {
	case *scalar.Decimal128:
		return .Value.Greater(decimal128.Num{})
	case *scalar.Decimal256:
		return .Value.Greater(decimal256.Num{})
	case *scalar.Int8:
		return .Value > 0
	case *scalar.Uint8, *scalar.Uint16, *scalar.Uint32, *scalar.Uint64:
		return true
	case *scalar.Int16:
		return .Value > 0
	case *scalar.Int32:
		return .Value > 0
	case *scalar.Int64:
		return .Value > 0
	case *scalar.Float32:
		return .Value > 0
	case *scalar.Float64:
		return .Value > 0
	default:
		return false
	}
}

func ( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
	var  RoundToMultipleState

	,  := .Options.(*RoundToMultipleOptions)
	if  {
		 = *
	} else {
		if ,  = .Options.(RoundToMultipleOptions); ! {
			return nil, fmt.Errorf("%w: attempted to initialize kernel state from invalid function options",
				arrow.ErrInvalid)
		}
	}

	 := .Multiple
	if  == nil || !.IsValid() {
		return nil, fmt.Errorf("%w: rounding multiple must be non-null and valid",
			arrow.ErrInvalid)
	}

	if !isPositive() {
		return nil, fmt.Errorf("%w: rounding multiple must be positive", arrow.ErrInvalid)
	}

	// ensure the rounding multiple option matches the kernel's output type.
	// the output type is not available here, so we use the following rule:
	// if "multiple" is neither a floating-point nor decimal type,
	// then cast to float64, else cast to the kernel's input type.
	var  arrow.DataType
	if !arrow.IsFloating(.DataType().ID()) && !arrow.IsDecimal(.DataType().ID()) {
		 = arrow.PrimitiveTypes.Float64
	} else {
		 = .Inputs[0]
	}

	if !arrow.TypeEqual(.DataType(), ) {
		,  := .CastTo()
		if  != nil {
			return nil, 
		}

		.Multiple = 
	}

	return , nil
}

func getFloatRoundImpl[ constraints.Float]( RoundMode) func()  {
	switch  {
	case RoundDown:
		return func( )  { return (math.Floor(float64())) }
	case RoundUp:
		return func( )  { return (math.Ceil(float64())) }
	case TowardsZero: // truncate
		return func( )  { return (math.Trunc(float64())) }
	case AwayFromZero:
		return func( )  {
			 := float64()
			if math.Signbit() {
				return (math.Floor())
			}
			return (math.Ceil())
		}
	// the Half variants are only called when the fractional portion
	// was 0.5
	case HalfDown:
		return func( )  { return (math.Floor(float64())) }
	case HalfUp:
		return func( )  { return (math.Ceil(float64())) }
	case HalfTowardsZero:
		return func( )  { return (math.Trunc(float64())) }
	case HalfAwayFromZero:
		return func( )  {
			 := float64()
			if math.Signbit() {
				return (math.Floor())
			}
			return (math.Ceil())
		}
	case HalfToEven:
		return func( )  { return (math.RoundToEven(float64())) }
	case HalfToOdd:
		return func( )  {
			 := float64()
			return (math.Floor(*0.5) + math.Ceil(*0.5))
		}
	}
	panic("invalid rounding mode")
}

func getDecRounding[ decimal128.Num | decimal256.Num]( RoundMode,  *roundDecImpl[]) func(,  ,  ,  int32)  {
	var (
		   
		 = .fromI64(1)
		 = .fromI64(-1)
	)

	switch  {
	case RoundDown:
		return func(, ,  ,  int32)  {
			 = .Sub(, )
			if .Sign() < 0 {
				 = .Sub(, )
			}
			return 
		}
	case RoundUp:
		return func(, ,  ,  int32)  {
			 = .Sub(, )
			if .Sign() > 0 &&  !=  {
				 = .Add(, )
			}
			return 
		}
	case TowardsZero:
		return func(, ,  ,  int32)  {
			return .Sub(, )
		}
	case AwayFromZero:
		return func(, ,  ,  int32)  {
			 = .Sub(, )
			if .Sign() < 0 {
				 = .Sub(, )
			} else if .Sign() > 0 &&  !=  {
				 = .Add(, )
			}
			return 
		}
	// variants for Half_* modes are only invoked when the fractional part
	// is equal to 0.5
	case HalfDown:
		return func(, ,  ,  int32)  {
			 = .Sub(, )
			if .Sign() < 0 {
				 = .Sub(, )
			}
			return 
		}
	case HalfUp:
		return func(, ,  ,  int32)  {
			 = .Sub(, )
			if .Sign() > 0 &&  !=  {
				 = .Add(, )
			}
			return 
		}
	case HalfTowardsZero:
		return func(, ,  ,  int32)  {
			return .Sub(, )
		}
	case HalfAwayFromZero:
		return func(, ,  ,  int32)  {
			 = .Sub(, )
			if .Sign() < 0 {
				 = .Sub(, )
			} else if .Sign() > 0 &&  !=  {
				 = .Add(, )
			}
			return 
		}
	case HalfToEven:
		return func(, ,  ,  int32)  {
			 := .reduceScale(, , false)
			if .lowBits()%2 != 0 {
				if .Sign() >= 0 {
					 = .Add(, )
				} else {
					 = .Add(, )
				}
			}
			return .increaseScale(, )
		}
	case HalfToOdd:
		return func(, ,  ,  int32)  {
			 := .reduceScale(, , false)
			if .lowBits()%2 == 0 {
				if .Sign() > 0 {
					 = .Add(, )
				} else {
					 = .Add(, )
				}
			}
			return .increaseScale(, )
		}
	}
	panic("invalid rounding mode")
}

type round[ constraints.Float] struct {
	pow10   
	ndigits int64
	mode    RoundMode

	fn func() 
}

func ( *round[]) ( *exec.KernelCtx,  ,  *error)  {
	 := float64()
	// do not process INF or NaN because they will trigger overflow errors
	// at the end of this
	if math.IsInf(, 0) || math.IsNaN() {
		return 
	}

	var  
	if .ndigits >= 0 {
		 =  * .pow10
	} else {
		 =  / .pow10
	}

	 :=  - (math.Floor(float64()))
	if  == 0 {
		// scaled value has no fractional component
		// no rounding is needed.
		return 
	}

	if .mode >= HalfDown &&  != 0.5 {
		 = (math.Round(float64()))
	} else {
		 = .fn()
	}

	// equality check is omitted so that the common case of 10^0
	// (integer rounding) uses multiply-only
	if .ndigits > 0 {
		 /= .pow10
	} else {
		 *= .pow10
	}
	if math.IsInf(float64(), 0) || math.IsNaN(float64()) {
		* = errOverflow
		return 
	}

	return 
}

func roundKernelFloating[ constraints.Float]( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(RoundState)
	 := round[]{
		pow10:   (.Pow10),
		ndigits: .NDigits,
		mode:    .Mode,
		fn:      getFloatRoundImpl[](.Mode),
	}

	return ScalarUnaryNotNull(.call)(, , )
}

func roundToMultipleFloating[ constraints.Float]( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(RoundToMultipleState)
	 := roundToMultiple[]{
		mode:     .Mode,
		multiple: UnboxScalar[](.Multiple.(scalar.PrimitiveScalar)),
		fn:       getFloatRoundImpl[](.Mode),
	}

	return ScalarUnaryNotNull(.call)(, , )
}

type roundDecImpl[ decimal128.Num | decimal256.Num] struct {
	*decOps[]
	scaleMultiplier     func(int) 
	halfScaleMultiplier func(int) 
	divide              func(a, b ) (res, rem )
	fitsInPrec          func(, int32) bool
	less                func(a, b ) bool
	reduceScale         func(, int32, bool) 
	increaseScale       func(, int32) 
	lowBits             func() uint64
	fromI64             func(int64) 
	str                 func(, int32) string
}

var (
	roundDec128 = roundDecImpl[decimal128.Num]{
		decOps:              &dec128Ops,
		scaleMultiplier:     decimal128.GetScaleMultiplier,
		halfScaleMultiplier: decimal128.GetHalfScaleMultiplier,
		divide:              func(,  decimal128.Num) (,  decimal128.Num) { return .Div() },
		fitsInPrec:          func( decimal128.Num,  int32) bool { return .FitsInPrecision() },
		less:                func(,  decimal128.Num) bool { return .Less() },
		reduceScale:         func( decimal128.Num,  int32,  bool) decimal128.Num { return .ReduceScaleBy(, ) },
		increaseScale:       func( decimal128.Num,  int32) decimal128.Num { return .IncreaseScaleBy() },
		lowBits:             func( decimal128.Num) uint64 { return .LowBits() },
		fromI64:             func( int64) decimal128.Num { return decimal128.FromI64() },
		str:                 func( decimal128.Num,  int32) string { return .ToString() },
	}
	roundDec256 = roundDecImpl[decimal256.Num]{
		decOps:              &dec256Ops,
		scaleMultiplier:     decimal256.GetScaleMultiplier,
		halfScaleMultiplier: decimal256.GetHalfScaleMultiplier,
		divide:              func(,  decimal256.Num) (,  decimal256.Num) { return .Div() },
		fitsInPrec:          func( decimal256.Num,  int32) bool { return .FitsInPrecision() },
		less:                func(,  decimal256.Num) bool { return .Less() },
		reduceScale:         func( decimal256.Num,  int32,  bool) decimal256.Num { return .ReduceScaleBy(, ) },
		increaseScale:       func( decimal256.Num,  int32) decimal256.Num { return .IncreaseScaleBy() },
		lowBits:             func( decimal256.Num) uint64 { return .LowBits() },
		fromI64:             func( int64) decimal256.Num { return decimal256.FromI64() },
		str:                 func( decimal256.Num,  int32) string { return .ToString() },
	}
)

type roundDec[ decimal128.Num | decimal256.Num] struct {
	ty      arrow.DecimalType
	mode    RoundMode
	ndigits int64
	pow     int32
	// pow10 is "1" for the given decimal scale. Similarly halfPow10 is "0.5"
	pow10, halfPow10, negHalfPow10 

	opsImpl *roundDecImpl[]
	fn      func(, , , int32) 
}

func ( *roundDec[]) ( *exec.KernelCtx,  ,  *error)  {
	var  
	if .pow >= .ty.GetPrecision() {
		* = fmt.Errorf("%w: rounding to %d digits will not fit in precision of %s",
			arrow.ErrInvalid, .ndigits, .ty)
		return 
	} else if .pow < 0 {
		// no-op copy output to input
		return 
	}

	,  := .opsImpl.divide(, .pow10)
	// the remainder is effectively the scaled fractional part after division
	if  ==  {
		return 
	}

	if .mode >= HalfDown {
		if  == .halfPow10 ||  == .negHalfPow10 {
			// on the halfway point, use tiebreaker
			 = .fn(, , .pow10, .pow)
		} else if .opsImpl.Sign() >= 0 {
			// positive, round up/down
			 = .opsImpl.Sub(, )
			if .opsImpl.less(.halfPow10, ) {
				 = .opsImpl.Add(, .pow10)
			}
		} else {
			// negative, round up/down
			 = .opsImpl.Sub(, )
			if .opsImpl.less(, .negHalfPow10) {
				 = .opsImpl.Sub(, .pow10)
			}
		}
	} else {
		 = .fn(, , .pow10, .pow)
	}

	if !.opsImpl.fitsInPrec(, .ty.GetPrecision()) {
		* = fmt.Errorf("%w: rounded value %s does not fit in precision of %s",
			arrow.ErrInvalid, .opsImpl.str(, .ty.GetScale()), .ty)
		return 
	}
	return 
}

func getRoundKernelDecimal[ decimal128.Num | decimal256.Num]() exec.ArrayKernelExec {
	var  
	switch any().(type) {
	case decimal128.Num:
		return func( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
			return roundKernelDecimal(&roundDec128, , , )
		}
	case decimal256.Num:
		return func( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
			return roundKernelDecimal(&roundDec256, , , )
		}
	}
	panic("should never get here")
}

func roundKernelDecimal[ decimal128.Num | decimal256.Num]( *roundDecImpl[],  *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(RoundState)
	 := roundDec[]{
		ty:      .Type.(arrow.DecimalType),
		ndigits: .NDigits,
		mode:    .Mode,
		opsImpl: ,
		fn:      getDecRounding(.Mode, ),
	}

	.pow = .ty.GetScale() - int32(.ndigits)
	if .pow < .ty.GetPrecision() && .pow >= 0 {
		.pow10 = .scaleMultiplier(int(.pow))
		.halfPow10 = .halfScaleMultiplier(int(.pow))
		.negHalfPow10 = .Neg(.halfPow10)
	}

	return ScalarUnaryNotNull(.call)(, , )
}

func getRoundToMultipleKernelDecimal[ decimal128.Num | decimal256.Num]() exec.ArrayKernelExec {
	var  
	switch any().(type) {
	case decimal128.Num:
		return func( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
			return roundToMultipleDecimal(&roundDec128, , , )
		}
	case decimal256.Num:
		return func( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
			return roundToMultipleDecimal(&roundDec256, , , )
		}
	}
	panic("should never get here")
}

func roundToMultipleDecimal[ decimal128.Num | decimal256.Num]( *roundDecImpl[],  *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(RoundToMultipleState)
	 := roundToMultipleDec[]{
		ty:      .Type.(arrow.DecimalType),
		mode:    .Mode,
		opsImpl: ,
		fn:      getDecRounding(.Mode, ),
		mult:    UnboxScalar[](.Multiple.(scalar.PrimitiveScalar)),
	}

	.halfMult = .Div(.mult, .fromI64(2))
	.negHalfMult = .Neg(.halfMult)
	.hasHalfwayPoint = .lowBits(.mult)%2 == 0

	return ScalarUnaryNotNull(.call)(, , )
}

type roundToMultiple[ constraints.Float] struct {
	multiple 
	mode     RoundMode

	fn func() 
}

func ( *roundToMultiple[]) ( *exec.KernelCtx,  ,  *error)  {
	 := float64()
	// do not process Inf or NaN because they will trigger the overflow error
	// at the end of this.
	if math.IsInf(, 0) || math.IsNaN() {
		return 
	}

	 :=  / .multiple
	 :=  - (math.Floor(float64()))
	if  == 0 {
		// scaled value is an integer, no rounding needed
		return 
	}

	if .mode >= HalfDown &&  != 0.5 {
		 = (math.Round(float64()))
	} else {
		 = .fn()
	}
	 *= .multiple

	if math.IsInf(float64(), 0) || math.IsNaN(float64()) {
		* = errOverflow
		return 
	}

	return 
}

type roundToMultipleDec[ decimal128.Num | decimal256.Num] struct {
	ty   arrow.DecimalType
	mode RoundMode

	mult, halfMult, negHalfMult 
	hasHalfwayPoint             bool

	opsImpl *roundDecImpl[]
	fn      func(, , , int32) 
}

func ( *roundToMultipleDec[]) ( *exec.KernelCtx,  ,  *error)  {
	var  

	,  := .opsImpl.divide(, .mult)
	if  ==  {
		return 
	}

	 := .opsImpl.fromI64(1)
	if .mode >= HalfDown {
		if .hasHalfwayPoint && ( == .halfMult ||  == .negHalfMult) {
			// on the halfway point, use tiebreaker
			// manually implement rounding since we aren't actually rounding
			// a decimal value, but rather manipulating the multiple
			switch .mode {
			case HalfDown:
				if .opsImpl.Sign() < 0 {
					 = .opsImpl.Sub(, )
				}
			case HalfUp:
				if .opsImpl.Sign() >= 0 {
					 = .opsImpl.Add(, )
				}
			case HalfTowardsZero:
			case HalfAwayFromZero:
				if .opsImpl.Sign() >= 0 {
					 = .opsImpl.Add(, )
				} else {
					 = .opsImpl.Sub(, )
				}
			case HalfToEven:
				if .opsImpl.lowBits()%2 != 0 {
					if .opsImpl.Sign() >= 0 {
						 = .opsImpl.Add(, )
					} else {
						 = .opsImpl.Sub(, )
					}
				}
			case HalfToOdd:
				if .opsImpl.lowBits()%2 == 0 {
					if .opsImpl.Sign() >= 0 {
						 = .opsImpl.Add(, )
					} else {
						 = .opsImpl.Sub(, )
					}
				}
			}
		} else if .opsImpl.Sign() >= 0 {
			// positive, round up/down
			if .opsImpl.less(.halfMult, ) {
				 = .opsImpl.Add(, )
			}
		} else {
			// negative, round up/down
			if .opsImpl.less(, .negHalfMult) {
				 = .opsImpl.Sub(, )
			}
		}
	} else {
		// manually implement rounding since we aren't actually rounding
		// a decimal value, but rather manipulating the multiple
		switch .mode {
		case RoundDown:
			if .opsImpl.Sign() < 0 {
				 = .opsImpl.Sub(, )
			}
		case RoundUp:
			if .opsImpl.Sign() >= 0 {
				 = .opsImpl.Add(, )
			}
		case TowardsZero:
		case AwayFromZero:
			if .opsImpl.Sign() >= 0 {
				 = .opsImpl.Add(, )
			} else {
				 = .opsImpl.Sub(, )
			}
		}
	}

	 := .opsImpl.Mul(, .mult)
	if !.opsImpl.fitsInPrec(, .ty.GetPrecision()) {
		* = fmt.Errorf("%w: rounded value %s does not fit in precision of %s",
			arrow.ErrInvalid, .opsImpl.str(, .ty.GetScale()), .ty)
		return 
	}
	return 
}

func ( arrow.Type) exec.ArrayKernelExec {
	switch  {
	case arrow.FLOAT32:
		return roundKernelFloating[float32]
	case arrow.FLOAT64:
		return roundKernelFloating[float64]
	case arrow.DECIMAL128:
		return getRoundKernelDecimal[decimal128.Num]()
	case arrow.DECIMAL256:
		return getRoundKernelDecimal[decimal256.Num]()
	}
	panic("should never get here")
}

func ( arrow.Type) exec.ArrayKernelExec {
	switch  {
	case arrow.FLOAT32:
		return roundToMultipleFloating[float32]
	case arrow.FLOAT64:
		return roundToMultipleFloating[float64]
	case arrow.DECIMAL128:
		return getRoundToMultipleKernelDecimal[decimal128.Num]()
	case arrow.DECIMAL256:
		return getRoundToMultipleKernelDecimal[decimal256.Num]()
	}
	panic("should never get here")
}

func ( exec.KernelInitFn,  func(arrow.Type) exec.ArrayKernelExec) []exec.ScalarKernel {
	 := make([]exec.ScalarKernel, 0)
	for ,  := range []arrow.DataType{arrow.PrimitiveTypes.Float32, arrow.PrimitiveTypes.Float64,
		&arrow.Decimal128Type{Precision: 1}, &arrow.Decimal256Type{Precision: 1}} {
		 := .ID()

		var  exec.OutputType
		if arrow.IsDecimal() {
			 = OutputFirstType
		} else {
			 = exec.NewOutputType()
		}

		 = append(, exec.NewScalarKernel(
			[]exec.InputType{exec.NewIDInput()}, , (), ))
	}

	return append(, NullExecKernel(1))
}

func ( RoundMode) []exec.ScalarKernel {
	 := make([]exec.ScalarKernel, 0)
	for ,  := range floatingTypes {
		var  exec.ArrayKernelExec
		switch .ID() {
		case arrow.FLOAT32:
			 := getFloatRoundImpl[float32]()
			 = ScalarUnary(func( *exec.KernelCtx,  []float32,  []float32) error {
				for ,  := range  {
					[] = ()
				}
				return nil
			})
		case arrow.FLOAT64:
			 := getFloatRoundImpl[float64]()
			 = ScalarUnary(func( *exec.KernelCtx,  []float64,  []float64) error {
				for ,  := range  {
					[] = ()
				}
				return nil
			})
		}
		 = append(, exec.NewScalarKernel(
			[]exec.InputType{exec.NewExactInput()}, exec.NewOutputType(),
			, nil))
	}
	return append(, NullExecKernel(1))
}

func fixedRoundDecimalExec[ decimal128.Num | decimal256.Num]( *roundDecImpl[],  RoundMode) exec.ArrayKernelExec {
	return func( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
		 := roundDec[]{
			ty:      .Type.(arrow.DecimalType),
			mode:    ,
			opsImpl: ,
			fn:      getDecRounding(, ),
		}

		.pow = .ty.GetScale() - int32(.ndigits)
		if .pow < .ty.GetPrecision() && .pow >= 0 {
			.pow10 = .scaleMultiplier(int(.pow))
			.halfPow10 = .halfScaleMultiplier(int(.pow))
			.negHalfPow10 = .Neg(.halfPow10)
		}

		return ScalarUnaryNotNull(.call)(, , )
	}
}

func [ decimal128.Num | decimal256.Num]( RoundMode) exec.ArrayKernelExec {
	var  
	switch any().(type) {
	case decimal128.Num:
		return func() exec.ArrayKernelExec {
			return fixedRoundDecimalExec(&roundDec128, )
		}()
	case decimal256.Num:
		return func() exec.ArrayKernelExec {
			return fixedRoundDecimalExec(&roundDec256, )
		}()
	}
	panic("should never get here")
}

// RoundTemporalUnit represents units supported for temporal rounding
type RoundTemporalUnit int8

const (
	RoundTemporalYear RoundTemporalUnit = iota
	RoundTemporalQuarter
	RoundTemporalMonth
	RoundTemporalWeek
	RoundTemporalDay
	RoundTemporalHour
	RoundTemporalMinute
	RoundTemporalSecond
	RoundTemporalMillisecond
	RoundTemporalMicrosecond
	RoundTemporalNanosecond
)

// RoundTemporalOptions provides configuration for temporal rounding operations
type RoundTemporalOptions struct {
	// Multiple is the number of units to round to. Must be positive.
	Multiple int64
	// Unit is the rounding unit (day, hour, etc.)
	Unit RoundTemporalUnit
	// WeekStartsMonday determines the start of the week for week-based rounding
	WeekStartsMonday bool
	// CeilIsStrictlyGreater: if true, ceil returns a value strictly greater than input
	CeilIsStrictlyGreater bool
	// CalendarBasedOrigin: if true, use calendar units as origin (e.g., start of day for hours)
	CalendarBasedOrigin bool
}

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

type roundTemporalState struct {
	RoundTemporalOptions
	mode RoundMode

	// Pre-calculated values to avoid repeated computation
	unitNanos        int64 // Duration of the unit in nanoseconds
	roundingInterval int64 // unitNanos * Multiple
	isSubDay         bool  // true if this is a sub-day unit (can use fast path)
}

func ( *exec.KernelCtx,  exec.KernelInitArgs) (exec.KernelState, error) {
	var  roundTemporalState

	,  := .Options.(*RoundTemporalOptions)
	if  {
		.RoundTemporalOptions = *
	} else {
		if .RoundTemporalOptions,  = .Options.(RoundTemporalOptions); ! {
			return nil, fmt.Errorf("%w: attempted to initialize kernel state from invalid function options",
				arrow.ErrInvalid)
		}
	}

	if .Multiple <= 0 {
		return nil, fmt.Errorf("%w: rounding multiple must be positive", arrow.ErrInvalid)
	}

	// Pre-calculate constants for this rounding operation
	.unitNanos, .isSubDay = unitInNanos(.Unit)
	if .isSubDay {
		var  error
		.roundingInterval,  = checkedMulInt64(.unitNanos, .Multiple)
		if  != nil {
			return nil, 
		}
	}

	return , nil
}

// unitInNanos returns (nanoseconds, hasFixedDuration) for a temporal unit.
// Returns false for calendar units with variable durations (year, quarter, month, week).
func unitInNanos( RoundTemporalUnit) (int64, bool) {
	switch  {
	case RoundTemporalNanosecond:
		return 1, true
	case RoundTemporalMicrosecond:
		return 1000, true
	case RoundTemporalMillisecond:
		return 1000000, true
	case RoundTemporalSecond:
		return 1000000000, true
	case RoundTemporalMinute:
		return 60 * 1000000000, true
	case RoundTemporalHour:
		return 3600 * 1000000000, true
	case RoundTemporalDay:
		return 86400 * 1000000000, true
	default:
		return 0, false
	}
}

// roundTimestamp rounds a timestamp value according to the specified options.
// tz specifies the timezone for calendar-aware rounding (nil defaults to UTC).
func roundTimestamp( int64,  arrow.TimeUnit,  *time.Location,  roundTemporalState) (int64, error) {
	if  == nil {
		 = time.UTC
	}

	// Calendar units with variable duration (year, quarter, month, week) require date arithmetic.
	if !.isSubDay {
		return roundTimestampCalendar(, , , )
	}

	// A day is a calendar unit when it is associated with a timezone. This also
	// handles CalendarBasedOrigin for day multiples, whose origin is the start
	// of the month rather than the Unix epoch.
	if .Unit == RoundTemporalDay {
		return roundTimestampCalendar(, , , )
	}

	// Zoned timestamps are rounded in their local wall-clock timeline. This is
	// observable for offsets that are not whole hours (for example, Kathmandu)
	// and around daylight-saving transitions.
	if  != time.UTC && .String() != "UTC" {
		if .CalendarBasedOrigin {
			return roundTimestampCalendarOrigin(, , , )
		}
		return roundTimestampFixedTimezone(, , , )
	}

	// CalendarBasedOrigin rounds fixed-duration units against the preceding
	// calendar boundary (for example, minutes from the start of the hour).
	// Use local wall-clock arithmetic here: time.Time.Sub measures elapsed time
	// and therefore gives the wrong answer across daylight-saving transitions.
	if .CalendarBasedOrigin {
		return roundTimestampCalendarOrigin(, , , )
	}

	// Sub-day units (hour, minute, second, etc.) use fixed-duration arithmetic.
	// Fast path: round directly in input unit when possible. A finer interval that
	// divides the input unit is already aligned and needs no calculation.
	if canRoundInInputUnit(, .roundingInterval) {
		 := int64(.Multiplier())
		if .roundingInterval <  {
			// Every input value is already aligned to a finer interval that divides
			// the input unit. Keep the calculation in the input unit so wider
			// timestamp ranges do not overflow during a nanosecond conversion.
			return , nil
		}
		 := .roundingInterval / 
		return roundToMultipleInt64(, , .mode, .CeilIsStrictlyGreater)
	}

	// Slow path: calculate the floor in nanoseconds, then cast the floor and
	// ceiling back to the input resolution before comparing them. This mirrors
	// the C++ kernel's duration_cast behavior when the requested interval is not
	// representable in the input unit.
	return roundTimestampInInputUnit(, , )
}

func roundTimestampInInputUnit( int64,  arrow.TimeUnit,  roundTemporalState) (int64, error) {
	// Keep the input in the target unit's arithmetic domain. Converting a wide
	// timestamp to nanoseconds first would reject values that are valid in the
	// requested unit (for example timestamp[s] in year 2300 rounded to 3 ms).
	 := big.NewInt(int64(.Multiplier()))
	 := new(big.Int).Mul(big.NewInt(), )
	 := floorBigIntToMultiple(, .roundingInterval)
	 := big.NewInt(.unitNanos)
	 := new(big.Int).Quo(new(big.Int).Set(), )
	if !.IsInt64() {
		return 0, overflowError()
	}
	 := new(big.Int).Quo(, )
	if !.IsInt64() {
		return 0, overflowError()
	}
	 := .Int64()

	 := 
	 := .roundingInterval / .Int64()
	if .CeilIsStrictlyGreater ||  <  {
		var  error
		,  = checkedAddInt64(, )
		if  != nil {
			return 0, 
		}
	}

	switch .mode {
	case RoundDown:
		return , nil
	case RoundUp:
		return , nil
	default:
		 := new(big.Int).Sub(big.NewInt(), big.NewInt())
		 := new(big.Int).Sub(big.NewInt(), big.NewInt())
		if .Cmp() >= 0 {
			return , nil
		}
		return , nil
	}
}

// canRoundInInputUnit checks if rounding can be done in the input unit
// without converting to nanoseconds (true when either unit is evenly divisible
// by the other).
func canRoundInInputUnit( arrow.TimeUnit,  int64) bool {
	if  <= 0 {
		return false
	}

	 := int64(.Multiplier())
	return % == 0 ||
		( <  && % == 0)
}

// roundTimestampCalendarOrigin rounds a fixed-duration unit relative to the
// preceding calendar boundary. Candidate boundaries are calculated in local
// wall time, then compared as system times so daylight-saving transitions are
// handled consistently with the temporal rounding reference implementation.
func roundTimestampCalendarOrigin( int64,  arrow.TimeUnit,  *time.Location,  roundTemporalState) (int64, error) {
	,  := timestampToCalendarTime(, , )
	if  != nil {
		return 0, 
	}
	,  := fixedCalendarOrigin(, .Unit)
	if  != nil {
		return 0, 
	}
	return roundTimestampFromWallOrigin(, , , , )
}

func roundTimestampFixedTimezone( int64,  arrow.TimeUnit,  *time.Location,  roundTemporalState) (int64, error) {
	,  := timestampToCalendarTime(, , )
	if  != nil {
		return 0, 
	}
	 := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
	return roundTimestampFromWallOrigin(, , , , )
}

func roundTimestampFromWallOrigin( time.Time,  arrow.TimeUnit,  *time.Location,  roundTemporalState,  time.Time) (int64, error) {
	 := 
	 := calendarWallTime()

	,  := wallClockDifference(, )
	var  time.Time
	if  == nil {
		,  := roundToMultipleInt64(, .roundingInterval, RoundDown, false)
		if  != nil {
			return 0, 
		}
		,  = addWallNanos(, , )
	} else {
		// Keep the wide timestamp range available for zoned timestamps. The
		// reference implementation performs this arithmetic in the input
		// duration, while an int64 nanosecond distance only spans about 292
		// years.
		,  := wallClockDifferenceBig(, )
		if  != nil {
			return 0, 
		}
		 := floorBigIntToMultiple(, .roundingInterval)
		,  = addWallNanosBig(, , )
	}
	if  != nil {
		return 0, 
	}
	 := calendarWallTime(.In())
	,  := truncateWallToInputResolution(, , )
	if  != nil {
		return 0, 
	}
	,  := checkedLocalTime(, )
	if  != nil {
		return 0, 
	}

	var  time.Time
	switch .mode {
	case RoundDown:
		 = 
	case RoundUp:
		,  = ceilCalendarOrigin(, , , , )
		if  != nil {
			return 0, 
		}
	default:
		,  := ceilCalendarOrigin(, , , , )
		if  != nil {
			return 0, 
		}
		,  = halfRoundPeriod(, , )
		if  != nil {
			return 0, 
		}
	}

	,  := timestampFromCalendarTime(, )
	if  != nil {
		return 0, 
	}
	return int64(), nil
}

func truncateWallToInputResolution(,  time.Time,  arrow.TimeUnit) (time.Time, error) {
	,  := wallClockDifferenceBig(, )
	if  != nil {
		return time.Time{}, 
	}
	 := big.NewInt(int64(.Multiplier()))
	.Quo(, )
	.Mul(, )
	return addWallNanosBig(, , time.UTC)
}

func ceilCalendarOrigin(,  time.Time,  arrow.TimeUnit,  roundTemporalState,  *time.Location) (time.Time, error) {
	// Convert the floored system time back to local wall time before deciding
	// whether to advance. This matters when the period crosses a timezone
	// transition because the elapsed system duration need not equal the wall
	// clock duration.
	 := calendarWallTime(.In())
	,  := checkedLocalTime(, )
	if  != nil {
		return time.Time{}, 
	}
	if !.CeilIsStrictlyGreater && !.Before() {
		return , nil
	}

	 := int64(.Multiplier())
	 := (.roundingInterval / ) * 
	,  := addWallNanos(, , )
	if  != nil {
		return time.Time{}, 
	}
	return , nil
}

// Keep the origin's civil fields in UTC because its local time may not exist.
// The requested location is applied only after rounding the wall-clock value.
func fixedCalendarOrigin( time.Time,  RoundTemporalUnit) (time.Time, error) {
	switch  {
	case RoundTemporalHour:
		return time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, time.UTC), nil
	case RoundTemporalMinute:
		return time.Date(.Year(), .Month(), .Day(), .Hour(), 0, 0, 0, time.UTC), nil
	case RoundTemporalSecond:
		return time.Date(.Year(), .Month(), .Day(), .Hour(), .Minute(), 0, 0, time.UTC), nil
	case RoundTemporalMillisecond:
		return time.Date(.Year(), .Month(), .Day(), .Hour(), .Minute(), .Second(), 0, time.UTC), nil
	case RoundTemporalMicrosecond:
		return time.Date(.Year(), .Month(), .Day(), .Hour(), .Minute(), .Second(),
			(.Nanosecond()/1_000_000)*1_000_000, time.UTC), nil
	case RoundTemporalNanosecond:
		return time.Date(.Year(), .Month(), .Day(), .Hour(), .Minute(), .Second(),
			(.Nanosecond()/1_000)*1_000, time.UTC), nil
	default:
		return time.Time{}, fmt.Errorf("%w: unsupported fixed calendar unit", arrow.ErrNotImplemented)
	}
}

func wallClockNanos( time.Time) (int64, error) {
	 := int64(.Hour())*3600 + int64(.Minute())*60 + int64(.Second())
	,  := checkedMulInt64(, int64(time.Second))
	if  != nil {
		return 0, 
	}
	return checkedAddInt64(, int64(.Nanosecond()))
}

func wallClockDifference(,  time.Time) (int64, error) {
	,  := calendarDayDifference(, )
	if  != nil {
		return 0, 
	}
	,  := checkedMulInt64(, nanosPerDay)
	if  != nil {
		return 0, 
	}
	,  := wallClockNanos()
	if  != nil {
		return 0, 
	}
	,  := wallClockNanos()
	if  != nil {
		return 0, 
	}
	,  = checkedAddInt64(, )
	if  != nil {
		return 0, 
	}
	return checkedSubInt64(, )
}

func wallClockDifferenceBig(,  time.Time) (*big.Int, error) {
	,  := calendarDayDifference(, )
	if  != nil {
		return nil, 
	}
	,  := wallClockNanos()
	if  != nil {
		return nil, 
	}
	,  := wallClockNanos()
	if  != nil {
		return nil, 
	}

	 := new(big.Int).Mul(big.NewInt(), big.NewInt(nanosPerDay))
	.Add(, big.NewInt())
	.Sub(, big.NewInt())
	return , nil
}

func floorBigIntToMultiple( *big.Int,  int64) *big.Int {
	 := big.NewInt()
	 := new(big.Int)
	 := new(big.Int)
	.QuoRem(, , )
	if .Sign() < 0 {
		.Sub(, big.NewInt(1))
	}
	return .Mul(, )
}

func calendarWallTime( time.Time) time.Time {
	return time.Date(.Year(), .Month(), .Day(), .Hour(), .Minute(), .Second(), .Nanosecond(), time.UTC)
}

func checkedLocalTime( time.Time,  *time.Location) (time.Time, error) {
	 := time.Date(.Year(), .Month(), .Day(), .Hour(), .Minute(), .Second(), .Nanosecond(), )
	if .Year() != .Year() || .Month() != .Month() || .Day() != .Day() ||
		.Hour() != .Hour() || .Minute() != .Minute() || .Second() != .Second() ||
		.Nanosecond() != .Nanosecond() {
		return time.Time{}, fmt.Errorf("%w: local time does not exist", arrow.ErrInvalid)
	}
	if ambiguousLocalTime(, , ) {
		return time.Time{}, fmt.Errorf("%w: local time is ambiguous", arrow.ErrInvalid)
	}
	return , nil
}

func ambiguousLocalTime(,  time.Time,  *time.Location) bool {
	,  := .Zone()
	 := calendarWallTime()
	for ,  := range []time.Duration{-2 * time.Hour, 2 * time.Hour, -48 * time.Hour, 48 * time.Hour} {
		,  := .Add().Zone()
		if  ==  {
			continue
		}
		 := .Add(-time.Duration() * time.Second).In()
		if .Year() == .Year() && .Month() == .Month() && .Day() == .Day() &&
			.Hour() == .Hour() && .Minute() == .Minute() &&
			.Second() == .Second() && .Nanosecond() == .Nanosecond() {
			return true
		}
	}
	return false
}

// addWallNanos adds a duration to a local wall-clock value without using
// time.Time.Add, which applies elapsed-time arithmetic across timezone
// transitions. The result is normalized through calendar dates in UTC and then
// reconstructed in the requested location.
func addWallNanos( time.Time,  int64,  *time.Location) (time.Time, error) {
	 := floorDivInt64(, nanosPerDay)
	,  := checkedMulInt64(, nanosPerDay)
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return time.Time{}, 
	}

	,  := wallClockNanos()
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedAddInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	if  >= nanosPerDay {
		,  = checkedAddInt64(, 1)
		if  != nil {
			return time.Time{}, 
		}
		 -= nanosPerDay
	}

	 := time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, time.UTC)
	,  = checkedCalendarAddDays(, )
	if  != nil {
		return time.Time{}, 
	}

	 :=  / int64(time.Hour)
	 -=  * int64(time.Hour)
	 :=  / int64(time.Minute)
	 -=  * int64(time.Minute)
	 :=  / int64(time.Second)
	 :=  - *int64(time.Second)
	return checkedLocalTime(time.Date(.Year(), .Month(), .Day(), int(), int(), int(), int(), time.UTC), )
}

func addWallNanosBig( time.Time,  *big.Int,  *time.Location) (time.Time, error) {
	 := new(big.Int)
	 := new(big.Int)
	.QuoRem(, big.NewInt(nanosPerDay), )
	if .Sign() < 0 {
		.Sub(, big.NewInt(1))
		.Add(, big.NewInt(nanosPerDay))
	}

	,  := wallClockNanos()
	if  != nil {
		return time.Time{}, 
	}
	 := new(big.Int).Add(, big.NewInt())
	if .Cmp(big.NewInt(nanosPerDay)) >= 0 {
		.Add(, big.NewInt(1))
		.Sub(, big.NewInt(nanosPerDay))
	}
	if !.IsInt64() {
		return time.Time{}, overflowError()
	}

	 := time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, time.UTC)
	,  = checkedCalendarAddDays(, .Int64())
	if  != nil {
		return time.Time{}, 
	}
	 := .Int64()
	 :=  / int64(time.Hour)
	 -=  * int64(time.Hour)
	 :=  / int64(time.Minute)
	 -=  * int64(time.Minute)
	 :=  / int64(time.Second)
	 :=  - *int64(time.Second)
	return checkedLocalTime(time.Date(.Year(), .Month(), .Day(), int(), int(), int(), int(), time.UTC), )
}

func overflowError() error {
	return fmt.Errorf("%w: temporal rounding overflow", arrow.ErrInvalid)
}

// time.Time's calendar representation wraps for Unix seconds before this
// boundary. time.Unix(math.MaxInt64, 0) also overflows its internal signed
// seconds field. Keep both cases out of calendar arithmetic before constructing
// a time.Time. The public timestamp conversion intentionally remains bijective
// over the full int64 range, so this check belongs in the calendar kernel.
const minCalendarTimestampSecond = -9223372028741760000

func timestampToCalendarTime( int64,  arrow.TimeUnit,  *time.Location) (time.Time, error) {
	if  == arrow.Second && ( < minCalendarTimestampSecond ||  == math.MaxInt64) {
		return time.Time{}, overflowError()
	}
	return arrow.Timestamp().ToTime().In(), nil
}

func checkedAddInt64(,  int64) (int64, error) {
	if ( > 0 &&  > math.MaxInt64-) || ( < 0 &&  < math.MinInt64-) {
		return 0, overflowError()
	}
	return  + , nil
}

func checkedSubInt64(,  int64) (int64, error) {
	if ( > 0 &&  < math.MinInt64+) || ( < 0 &&  > math.MaxInt64+) {
		return 0, overflowError()
	}
	return  - , nil
}

func checkedMulInt64(,  int64) (int64, error) {
	if  == 0 ||  == 0 {
		return 0, nil
	}
	if ( == math.MinInt64 &&  == -1) || ( == math.MinInt64 &&  == -1) {
		return 0, overflowError()
	}

	 :=  * 
	if / !=  {
		return 0, overflowError()
	}
	return , nil
}

func checkedInt64ToInt( int64) (int, error) {
	 := int()
	if int64() !=  {
		return 0, overflowError()
	}
	return , nil
}

// floorDivInt64 divides by a positive divisor and rounds towards negative
// infinity. Go's integer division rounds towards zero, which would place
// negative calendar values in the wrong period.
func floorDivInt64(,  int64) int64 {
	 :=  / 
	if % < 0 {
		--
	}
	return 
}

func checkedCalendarDate(,  int64,  *time.Location) (time.Time, error) {
	,  := checkedInt64ToInt()
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedInt64ToInt()
	if  != nil {
		return time.Time{}, 
	}
	 := time.Date(, time.Month(), 1, 0, 0, 0, 0, time.UTC)
	if int64(.Year()) !=  {
		return time.Time{}, overflowError()
	}
	return checkedLocalTime(, )
}

func checkedCalendarMidnight( int,  time.Month,  int,  *time.Location) (time.Time, error) {
	return checkedLocalTime(time.Date(, , , 0, 0, 0, 0, time.UTC), )
}

func checkedCalendarAddDays( time.Time,  int64) (time.Time, error) {
	,  := checkedInt64ToInt()
	if  != nil {
		return time.Time{}, 
	}
	 := .AddDate(0, 0, )
	if ( > 0 && .Before()) || ( < 0 && .After()) {
		return time.Time{}, overflowError()
	}
	return , nil
}

func roundToMultipleInt64(,  int64,  RoundMode,  bool) (int64, error) {
	if  == 0 || % == 0 {
		if  &&  == RoundUp {
			return checkedAddInt64(, )
		}
		return , nil
	}

	 :=  / 
	 :=  % 

	switch  {
	case RoundDown:
		if  < 0 {
			,  := checkedSubInt64(, 1)
			if  != nil {
				return 0, 
			}
			return checkedMulInt64(, )
		}
		return checkedMulInt64(, )
	case RoundUp:
		if  > 0 || ( &&  == 0) {
			,  := checkedAddInt64(, 1)
			if  != nil {
				return 0, 
			}
			return checkedMulInt64(, )
		}
		if  < 0 {
			return checkedMulInt64(, )
		}
		,  := checkedAddInt64(, 1)
		if  != nil {
			return 0, 
		}
		return checkedMulInt64(, )
	case HalfUp, HalfDown, HalfToEven:
		 :=  / 2
		 := 
		if  < 0 {
			 = -
		}

		// Odd multiples do not have an exact halfway point. For example,
		// a remainder of 1 when rounding to multiples of 3 is closer to 0
		// than to 3, so it must not be treated as a tie.
		if  <  || (%2 != 0 &&  == ) {
			return checkedMulInt64(, )
		} else if  >  {
			if  > 0 {
				,  := checkedAddInt64(, 1)
				if  != nil {
					return 0, 
				}
				return checkedMulInt64(, )
			}
			,  := checkedSubInt64(, 1)
			if  != nil {
				return 0, 
			}
			return checkedMulInt64(, )
		} else {
			// Exactly on the halfway point
			switch  {
			case HalfDown:
				if  > 0 {
					return checkedMulInt64(, )
				}
				,  := checkedSubInt64(, 1)
				if  != nil {
					return 0, 
				}
				return checkedMulInt64(, )
			case HalfUp:
				if  > 0 {
					,  := checkedAddInt64(, 1)
					if  != nil {
						return 0, 
					}
					return checkedMulInt64(, )
				}
				return checkedMulInt64(, )
			case HalfToEven:
				if %2 == 0 {
					return checkedMulInt64(, )
				}
				if  > 0 {
					,  := checkedAddInt64(, 1)
					if  != nil {
						return 0, 
					}
					return checkedMulInt64(, )
				}
				,  := checkedSubInt64(, 1)
				if  != nil {
					return 0, 
				}
				return checkedMulInt64(, )
			}
		}
	}
	return checkedMulInt64(, )
}

// halfRoundPeriod performs half-rounding by finding the midpoint between period start and end.
// It does not use time.Time.Sub or time.Time.Unix because those methods cannot represent
// sufficiently large calendar periods and timestamps.
func halfRoundPeriod(, ,  time.Time) (time.Time, error) {
	, ,  := calendarTimeParts()
	if  != nil {
		return time.Time{}, 
	}
	, ,  := calendarTimeParts()
	if  != nil {
		return time.Time{}, 
	}
	if  <  || ( ==  &&  < ) {
		return time.Time{}, overflowError()
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	if  < 0 {
		,  = checkedSubInt64(, 1)
		if  != nil {
			return time.Time{}, 
		}
		 += nanosPerDay
	}

	, ,  := calendarTimeParts()
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	if  < 0 {
		,  = checkedSubInt64(, 1)
		if  != nil {
			return time.Time{}, 
		}
		 += nanosPerDay
	}

	// Compare 2*(t-periodStart) with periodEnd-periodStart without ever
	// converting the whole interval to a time.Duration.
	,  := checkedMulInt64(, 2)
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedMulInt64(, 2)
	if  != nil {
		return time.Time{}, 
	}
	if  >= nanosPerDay {
		,  = checkedAddInt64(, 1)
		if  != nil {
			return time.Time{}, 
		}
		 -= nanosPerDay
	}

	if  <  || ( ==  &&  < ) {
		return , nil
	}
	return , nil
}

const nanosPerDay = int64(24 * time.Hour)

// calendarTimeParts returns a time instant as a day number and nanoseconds into
// the corresponding UTC day. Unlike Unix timestamps, this representation
// remains valid for all time.Time values supported by the time package.
func calendarTimeParts( time.Time) (int64, int64, error) {
	,  := calendarDays()
	if  != nil {
		return 0, 0, 
	}

	 := int64(.Hour())*3600 + int64(.Minute())*60 + int64(.Second())
	,  := checkedMulInt64(, int64(time.Second))
	if  != nil {
		return 0, 0, 
	}
	,  = checkedAddInt64(, int64(.Nanosecond()))
	if  != nil {
		return 0, 0, 
	}
	,  := .Zone()
	,  := checkedMulInt64(int64(), int64(time.Second))
	if  != nil {
		return 0, 0, 
	}
	,  = checkedSubInt64(, )
	if  != nil {
		return 0, 0, 
	}

	if  < 0 {
		,  = checkedSubInt64(, 1)
		if  != nil {
			return 0, 0, 
		}
		 += nanosPerDay
	} else if  >= nanosPerDay {
		,  = checkedAddInt64(, 1)
		if  != nil {
			return 0, 0, 
		}
		 -= nanosPerDay
	}

	return , , nil
}

// calendarDays returns the proleptic Gregorian day number for a local date.
// The calculation is based on civil calendar fields, so it does not saturate
// at time.Duration or int64 Unix-second boundaries.
func calendarDays( time.Time) (int64, error) {
	 := int64(.Year())
	 := int64(.Month())
	 := int64(.Day())
	if  <= 2 {
		var  error
		,  = checkedSubInt64(, 1)
		if  != nil {
			return 0, 
		}
	}

	 :=  / 400
	if  < 0 && %400 != 0 {
		--
	}
	,  := checkedMulInt64(, 400)
	if  != nil {
		return 0, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return 0, 
	}

	 := 
	if  > 2 {
		 -= 3
	} else {
		 += 9
	}
	 := (153*+2)/5 +  - 1
	 := *365 + /4 - /100 + 
	,  := checkedMulInt64(, 146097)
	if  != nil {
		return 0, 
	}
	,  = checkedAddInt64(, )
	if  != nil {
		return 0, 
	}
	return checkedSubInt64(, 719468)
}

func calendarDayDifference(,  time.Time) (int64, error) {
	,  := calendarDays()
	if  != nil {
		return 0, 
	}
	,  := calendarDays()
	if  != nil {
		return 0, 
	}
	return checkedSubInt64(, )
}

// floorCalendarIndex returns the start of the current calendar period as an
// index in either months or quarters. Without a calendar origin, periods are
// anchored at 1970-01-01. With one, multiple periods start at the beginning of
// the current year.
func floorCalendarIndex(, , ,  int64,  bool) (int64, error) {
	,  := checkedMulInt64(, )
	if  != nil {
		return 0, 
	}
	,  := checkedAddInt64(, )
	if  != nil {
		return 0, 
	}

	if  &&  != 1 {
		,  := checkedMulInt64(floorDivInt64(, ), )
		if  != nil {
			return 0, 
		}
		return checkedAddInt64(, )
	}

	,  := checkedMulInt64(1970, )
	if  != nil {
		return 0, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return 0, 
	}
	,  := checkedMulInt64(floorDivInt64(, ), )
	if  != nil {
		return 0, 
	}
	return checkedAddInt64(, )
}

func calendarDateFromIndex(, ,  int64,  *time.Location) (time.Time, error) {
	 := floorDivInt64(, )
	,  := checkedMulInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedSubInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedMulInt64(, )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedAddInt64(, 1)
	if  != nil {
		return time.Time{}, 
	}
	return checkedCalendarDate(, , )
}

func floorCalendarDay( time.Time,  int64,  bool,  *time.Location) (time.Time, error) {
	 := time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, time.UTC)
	if  == 1 {
		return checkedCalendarMidnight(.Year(), .Month(), .Day(), )
	}

	 := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
	if  {
		 = time.Date(.Year(), .Month(), 1, 0, 0, 0, 0, time.UTC)
	}
	,  := calendarDayDifference(, )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedMulInt64(floorDivInt64(, ), )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedCalendarAddDays(, )
	if  != nil {
		return time.Time{}, 
	}
	return checkedCalendarMidnight(.Year(), .Month(), .Day(), )
}

func floorCalendarWeek( time.Time,  int64,  bool,  *time.Location) (time.Time, error) {
	 := time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, time.UTC)
	 := int(.Weekday())
	 := time.Wednesday
	if  {
		 = ( + 6) % 7
		 = time.Thursday
	}
	,  := checkedCalendarAddDays(, -int64())
	if  != nil {
		return time.Time{}, 
	}
	// Use a fixed representative day from the input's week to identify the
	// calendar week-year. Adding a constant to the input can cross into the
	// following week for late-week values.
	,  := checkedCalendarAddDays(, 3)
	if  != nil {
		return time.Time{}, 
	}

	,  := checkedSubInt64(int64(.Year()), 1)
	if  != nil {
		return time.Time{}, 
	}
	 := time.Date(int(), time.December, 31, 0, 0, 0, 0, time.UTC)
	 := (int(.Weekday()) - int() + 7) % 7
	,  := checkedCalendarAddDays(, -int64())
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedCalendarAddDays(, 4)
	if  != nil {
		return time.Time{}, 
	}

	,  := calendarDayDifference(, )
	if  != nil {
		return time.Time{}, 
	}
	 := floorDivInt64(, 7)
	,  := checkedMulInt64(floorDivInt64(, ), )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedMulInt64(, 7)
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedCalendarAddDays(, )
	if  != nil {
		return time.Time{}, 
	}
	return checkedLocalTime(, )
}

func floorFixedCalendarWeek( time.Time,  int64,  bool,  *time.Location) (time.Time, error) {
	 := int64(4)
	if  {
		 = 3
	}

	// The reference algorithm shifts the local wall-clock timestamp by the
	// weekday offset, floors fixed seven-day periods from the Unix epoch, and
	// only then converts the candidate back to system time. Keep the wall-clock
	// date in UTC while doing the arithmetic so a missing local midnight cannot
	// move the period into a different civil date.
	,  := checkedCalendarAddDays(calendarWallTime(), )
	if  != nil {
		return time.Time{}, 
	}
	 := time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, time.UTC)
	,  := calendarDays()
	if  != nil {
		return time.Time{}, 
	}
	 := floorDivInt64(, 7)
	,  := checkedMulInt64(floorDivInt64(, ), )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedMulInt64(, 7)
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedCalendarAddDays(time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC), )
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedCalendarAddDays(, -)
	if  != nil {
		return time.Time{}, 
	}
	return time.Date(.Year(), .Month(), .Day(), 0, 0, 0, 0, ), nil
}

func ceilFixedCalendarWeek(,  time.Time,  int64,  bool,  *time.Location) (time.Time, error) {
	 := calendarWallTime(.In())
	,  := checkedLocalTime(, )
	if  != nil {
		return time.Time{}, 
	}
	if ! && !.Before() {
		return , nil
	}

	,  := checkedMulInt64(, 7)
	if  != nil {
		return time.Time{}, 
	}
	,  := checkedCalendarAddDays(, )
	if  != nil {
		return time.Time{}, 
	}
	return checkedLocalTime(, )
}

func roundCalendarOriginWeek( time.Time,  roundTemporalState,  *time.Location) (time.Time, error) {
	,  := floorCalendarWeek(, .Multiple, .WeekStartsMonday, )
	if  != nil {
		return time.Time{}, 
	}
	if .mode == RoundDown {
		return , nil
	}

	var  time.Time
	 := func() (time.Time, error) {
		if .IsZero() {
			,  := checkedMulInt64(.Multiple, 7)
			if  != nil {
				return time.Time{}, 
			}
			,  := checkedCalendarAddDays(calendarWallTime(.In()), )
			if  != nil {
				return time.Time{}, 
			}
			,  = checkedLocalTime(, )
			if  != nil {
				return time.Time{}, 
			}
		}
		return , nil
	}

	 := 

	switch .mode {
	case RoundUp:
		if .CeilIsStrictlyGreater || .Before() {
			return ()
		}
		return , nil
	default:
		if .After() {
			return , nil
		}
		,  := ()
		if  != nil {
			return time.Time{}, 
		}
		return halfRoundPeriod(, , )
	}
}

// roundTimestampCalendar handles calendar-based rounding (year, quarter, month, week, day).
// Requires date arithmetic for variable-length periods and timezone-aware boundaries.
func roundTimestampCalendar( int64,  arrow.TimeUnit,  *time.Location,  roundTemporalState) (int64, error) {
	// Convert to time.Time for calendar operations in the specified timezone
	,  := timestampToCalendarTime(, , )
	if  != nil {
		return 0, 
	}

	var  time.Time
	 := .Multiple

	switch .Unit {
	case RoundTemporalYear:
		 := int64(.Year())
		,  := checkedMulInt64(floorDivInt64(, ), )
		if  != nil {
			return 0, 
		}
		switch .mode {
		case RoundDown:
			var  error
			,  = checkedCalendarDate(, 1, )
			if  != nil {
				return 0, 
			}
		case RoundUp:
			,  = checkedAddInt64(, )
			if  != nil {
				return 0, 
			}
			,  = checkedCalendarDate(, 1, )
			if  != nil {
				return 0, 
			}
		default:
			,  := checkedCalendarDate(, 1, )
			if  != nil {
				return 0, 
			}
			,  := checkedAddInt64(, )
			if  != nil {
				return 0, 
			}
			,  := checkedCalendarDate(, 1, )
			if  != nil {
				return 0, 
			}
			,  = halfRoundPeriod(, , )
			if  != nil {
				return 0, 
			}
		}

	case RoundTemporalQuarter:
		// Q1=Jan-Mar, Q2=Apr-Jun, Q3=Jul-Sep, Q4=Oct-Dec
		 := int64(.Month())
		 := int64(.Year())
		,  := floorCalendarIndex(
			, (-1)/3, 4, , .CalendarBasedOrigin,
		)
		if  != nil {
			return 0, 
		}

		switch .mode {
		case RoundDown:
			,  = calendarDateFromIndex(, 4, 3, )
			if  != nil {
				return 0, 
			}
		case RoundUp:
			,  := checkedAddInt64(, )
			if  != nil {
				return 0, 
			}
			,  = calendarDateFromIndex(, 4, 3, )
			if  != nil {
				return 0, 
			}
		default:
			,  := calendarDateFromIndex(, 4, 3, )
			if  != nil {
				return 0, 
			}
			,  := checkedAddInt64(, )
			if  != nil {
				return 0, 
			}
			,  := calendarDateFromIndex(, 4, 3, )
			if  != nil {
				return 0, 
			}
			,  = halfRoundPeriod(, , )
			if  != nil {
				return 0, 
			}
		}

	case RoundTemporalMonth:
		 := int64(.Month())
		 := int64(.Year())
		,  := floorCalendarIndex(
			, -1, 12, , .CalendarBasedOrigin,
		)
		if  != nil {
			return 0, 
		}

		switch .mode {
		case RoundDown:
			,  = calendarDateFromIndex(, 12, 1, )
			if  != nil {
				return 0, 
			}
		case RoundUp:
			,  := checkedAddInt64(, )
			if  != nil {
				return 0, 
			}
			,  = calendarDateFromIndex(, 12, 1, )
			if  != nil {
				return 0, 
			}
		default:
			,  := calendarDateFromIndex(, 12, 1, )
			if  != nil {
				return 0, 
			}
			,  := checkedAddInt64(, )
			if  != nil {
				return 0, 
			}
			,  := calendarDateFromIndex(, 12, 1, )
			if  != nil {
				return 0, 
			}
			,  = halfRoundPeriod(, , )
			if  != nil {
				return 0, 
			}
		}

	case RoundTemporalWeek:
		if .CalendarBasedOrigin &&  != 1 {
			,  = roundCalendarOriginWeek(, , )
			if  != nil {
				return 0, 
			}
			break
		}

		,  := floorFixedCalendarWeek(, , .WeekStartsMonday, )
		if  != nil {
			return 0, 
		}
		,  := ceilFixedCalendarWeek(, , , .CeilIsStrictlyGreater, )
		if  != nil {
			return 0, 
		}

		switch .mode {
		case RoundDown:
			 = 
		case RoundUp:
			 = 
		default:
			,  = halfRoundPeriod(, , )
			if  != nil {
				return 0, 
			}
		}

	case RoundTemporalDay:
		,  := floorCalendarDay(, , .CalendarBasedOrigin, )
		if  != nil {
			return 0, 
		}
		 := func() (time.Time, error) {
			,  := checkedCalendarAddDays(calendarWallTime(), )
			if  != nil {
				return time.Time{}, 
			}
			return checkedLocalTime(, )
		}

		switch .mode {
		case RoundDown:
			 = 
		case RoundUp:
			if .CeilIsStrictlyGreater || !.Equal() {
				,  = ()
				if  != nil {
					return 0, 
				}
			} else {
				 = 
			}
		default:
			,  := ()
			if  != nil {
				return 0, 
			}
			,  = halfRoundPeriod(, , )
			if  != nil {
				return 0, 
			}
		}

	default:
		return 0, fmt.Errorf("%w: unsupported calendar unit", arrow.ErrNotImplemented)
	}
	if  != nil {
		return 0, 
	}

	// Convert back to the input unit, validating only the selected result.
	,  := timestampFromCalendarTime(, )
	if  != nil {
		return 0, 
	}
	return int64(), nil
}

func timestampFromCalendarTime( time.Time,  arrow.TimeUnit) (arrow.Timestamp, error) {
	if  != arrow.Second {
		return arrow.TimestampFromTime(, )
	}

	, ,  := calendarTimeParts()
	if  != nil {
		return 0, 
	}
	,  := checkedMulInt64(, int64(24*time.Hour/time.Second))
	if  != nil {
		return 0, 
	}
	,  = checkedAddInt64(, /int64(time.Second))
	if  != nil {
		return 0, 
	}
	return arrow.Timestamp(), nil
}

func timeToNanos( time.Time) (int64, error) {
	,  := arrow.TimestampFromTime(, arrow.Nanosecond)
	if  != nil {
		return 0, 
	}
	return int64(), nil
}

// Kernel execution functions for temporal rounding
func ( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(roundTemporalState)
	.mode = RoundDown
	return roundTemporalExec(, , , )
}

func ( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(roundTemporalState)
	.mode = RoundUp
	return roundTemporalExec(, , , )
}

func ( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult) error {
	 := .State.(roundTemporalState)
	.mode = HalfUp
	return roundTemporalExec(, , , )
}

func roundTemporalExec( *exec.KernelCtx,  *exec.ExecSpan,  *exec.ExecResult,  roundTemporalState) error {
	 := &.Values[0].Array

	// Handle date types by converting to timestamp equivalents
	switch .Type.ID() {
	case arrow.DATE32:
		// Date32 stores days since epoch as int32, treat as timestamp[s] at midnight
		 := func( *exec.KernelCtx,  int32,  *error) int32 {
			// Convert days to seconds (timestamp at midnight UTC)
			 := int64() * 86400
			,  := roundTimestamp(, arrow.Second, nil, )
			if  != nil {
				* = 
				return 0
			}
			// Convert back to days
			 :=  / 86400
			if  < math.MinInt32 ||  > math.MaxInt32 {
				* = overflowError()
				return 0
			}
			return int32()
		}
		return ScalarUnaryNotNull()(, , )

	case arrow.DATE64:
		// Date64 stores milliseconds since epoch, treat as timestamp[ms]
		 := func( *exec.KernelCtx,  int64,  *error) int64 {
			,  := roundTimestamp(, arrow.Millisecond, nil, )
			if  != nil {
				* = 
				return 0
			}
			return 
		}
		return ScalarUnaryNotNull()(, , )

	case arrow.TIME32:
		// Time32 stores time-of-day in seconds or milliseconds
		// Rounding wraps at day boundaries (modulo 24 hours)
		 := .Type.(*arrow.Time32Type)
		 := func( *exec.KernelCtx,  int32,  *error) int32 {
			// Convert to int64 for rounding
			,  := roundTimestamp(int64(), .Unit, nil, )
			if  != nil {
				* = 
				return 0
			}
			// Wrap at day boundary
			var  int64
			if .Unit == arrow.Second {
				 = 86400 // 24 hours in seconds
			} else {
				 = 86400000 // 24 hours in milliseconds
			}
			 :=  % 
			if  < 0 {
				 += 
			}
			return int32()
		}
		return ScalarUnaryNotNull()(, , )

	case arrow.TIME64:
		// Time64 stores time-of-day in microseconds or nanoseconds
		// Rounding wraps at day boundaries (modulo 24 hours)
		 := .Type.(*arrow.Time64Type)
		 := func( *exec.KernelCtx,  int64,  *error) int64 {
			,  := roundTimestamp(, .Unit, nil, )
			if  != nil {
				* = 
				return 0
			}
			// Wrap at day boundary
			var  int64
			if .Unit == arrow.Microsecond {
				 = 86400000000 // 24 hours in microseconds
			} else {
				 = 86400000000000 // 24 hours in nanoseconds
			}
			 :=  % 
			if  < 0 {
				 += 
			}
			return 
		}
		return ScalarUnaryNotNull()(, , )
	}

	// Handle timestamp types
	 := .Type.(arrow.TemporalWithUnit)

	// Extract timezone if present (for timestamp types)
	var  *time.Location
	if ,  := .Type.(*arrow.TimestampType);  && .TimeZone != "" {
		var  error
		,  = .GetZone()
		if  != nil {
			return fmt.Errorf("%w: invalid timezone %q: %v", arrow.ErrInvalid, .TimeZone, )
		}
	}

	 := func( *exec.KernelCtx,  int64,  *error) int64 {
		,  := roundTimestamp(, .TimeUnit(), , )
		if  != nil {
			* = 
			return 0
		}
		return 
	}

	switch .TimeUnit() {
	case arrow.Second, arrow.Millisecond, arrow.Microsecond, arrow.Nanosecond:
		return ScalarUnaryNotNull()(, , )
	default:
		return fmt.Errorf("%w: unsupported time unit", arrow.ErrNotImplemented)
	}
}

func ( exec.KernelInitFn,  exec.ArrayKernelExec) []exec.ScalarKernel {
	 := make([]exec.ScalarKernel, 0)

	// Timestamp kernels
	for ,  := range arrow.TimeUnitValues {
		 = append(, exec.NewScalarKernel(
			[]exec.InputType{exec.NewMatchedInput(exec.TimestampTypeUnit())},
			OutputFirstType,
			,
			,
		))
	}

	// Date32 kernel
	 = append(, exec.NewScalarKernel(
		[]exec.InputType{exec.NewMatchedInput(exec.Date32Type())},
		OutputFirstType,
		,
		,
	))

	// Date64 kernel
	 = append(, exec.NewScalarKernel(
		[]exec.InputType{exec.NewMatchedInput(exec.Date64Type())},
		OutputFirstType,
		,
		,
	))

	// Time32 kernels (seconds and milliseconds)
	 = append(, exec.NewScalarKernel(
		[]exec.InputType{exec.NewMatchedInput(exec.Time32TypeUnit(arrow.Second))},
		OutputFirstType,
		,
		,
	))
	 = append(, exec.NewScalarKernel(
		[]exec.InputType{exec.NewMatchedInput(exec.Time32TypeUnit(arrow.Millisecond))},
		OutputFirstType,
		,
		,
	))

	// Time64 kernels (microseconds and nanoseconds)
	 = append(, exec.NewScalarKernel(
		[]exec.InputType{exec.NewMatchedInput(exec.Time64TypeUnit(arrow.Microsecond))},
		OutputFirstType,
		,
		,
	))
	 = append(, exec.NewScalarKernel(
		[]exec.InputType{exec.NewMatchedInput(exec.Time64TypeUnit(arrow.Nanosecond))},
		OutputFirstType,
		,
		,
	))

	return append(, NullExecKernel(1))
}