// Copyright 2008 Google Inc.
// Copyright (c) 2026 The elk-go Authors.
// Adapted to Go for elk-go in 2026.
//
// Licensed 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.
//
// SPDX-License-Identifier: Apache-2.0

package javacompat

// GWTStableSort reproduces the object-array legacy merge sort in GWT 2.11.0's
// emulated java.util.Arrays. The relevant implementation is unchanged from
// GWT 2.9.0. Comparator invocation order is observable when a comparator
// records comparisons or derives transitive state, as ELK's model-order
// comparators do.
func [ any]( [],  func(, ) int) {
	if  == nil {
		panic("javacompat.GWTStableSort: nil comparator")
	}
	 := append([](nil), ...)
	gwtMergeSort(, , 0, len(), )
}

func gwtMergeSort[ any](,  [], ,  int,  func(, ) int) {
	 :=  - 
	if  < 7 {
		for  :=  + 1;  < ; ++ {
			for  := ;  >  && ([-1], []) > 0; -- {
				[], [-1] = [-1], []
			}
		}
		return
	}

	 :=  + ( >> 1)
	(, , , , )
	(, , , , )
	if ([-1], []) <= 0 {
		copy([:], [:])
		return
	}

	,  := , 
	for  := ;  < ; ++ {
		if  >=  ||  <  && ([], []) <= 0 {
			[] = []
			++
		} else {
			[] = []
			++
		}
	}
}