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