Permalink
Browse files

compiler/natives/src/reflect: Implement safe Swapper.

Based on go4 version, with fast path from 1.8 standard library.

Fixes TestSwapper.
  • Loading branch information...
1 parent 3303ee8 commit 40ff6ca29027d94de1034bc5b684e000b3165dc0 @shurcooL shurcooL committed Dec 14, 2016
Showing with 29 additions and 0 deletions.
  1. +29 −0 compiler/natives/src/reflect/swapper.go
@@ -0,0 +1,29 @@
+// +build js
+
+package reflect
+
+func Swapper(slice interface{}) func(i, j int) {
+ v := ValueOf(slice)
+ if v.Kind() != Slice {
+ panic(&ValueError{Method: "Swapper", Kind: v.Kind()})
+ }
+ // Fast path for slices of size 0 and 1. Nothing to swap.
+ switch v.Len() {
+ case 0:
+ return func(i, j int) { panic("reflect: slice index out of range") }
+ case 1:
+ return func(i, j int) {
+ if i != 0 || j != 0 {
+ panic("reflect: slice index out of range")
+ }
+ }
+ }
+ tmp := New(v.Type().Elem()).Elem()
+ return func(i, j int) {
+ v1 := v.Index(i)
+ v2 := v.Index(j)
+ tmp.Set(v1)
+ v1.Set(v2)
+ v2.Set(tmp)
+ }
+}

0 comments on commit 40ff6ca

Please sign in to comment.