github.com/gopherjs/gopherjs@v1.19.0-beta1.0.20240506212314-27071a8796e4/compiler/natives/src/reflect/swapper.go (about)

     1  //go:build js
     2  // +build js
     3  
     4  package reflect
     5  
     6  import "github.com/gopherjs/gopherjs/js"
     7  
     8  func Swapper(slice interface{}) func(i, j int) {
     9  	v := ValueOf(slice)
    10  	if v.Kind() != Slice {
    11  		panic(&ValueError{Method: "Swapper", Kind: v.Kind()})
    12  	}
    13  	// Fast path for slices of size 0 and 1. Nothing to swap.
    14  	vLen := uint(v.Len())
    15  	switch vLen {
    16  	case 0:
    17  		return func(i, j int) { panic("reflect: slice index out of range") }
    18  	case 1:
    19  		return func(i, j int) {
    20  			if i != 0 || j != 0 {
    21  				panic("reflect: slice index out of range")
    22  			}
    23  		}
    24  	}
    25  	a := js.InternalObject(slice).Get("$array")
    26  	off := js.InternalObject(slice).Get("$offset").Int()
    27  	return func(i, j int) {
    28  		if uint(i) >= vLen || uint(j) >= vLen {
    29  			panic("reflect: slice index out of range")
    30  		}
    31  		i += off
    32  		j += off
    33  		tmp := a.Index(i)
    34  		a.SetIndex(i, a.Index(j))
    35  		a.SetIndex(j, tmp)
    36  	}
    37  }