go4.org@v0.0.0-20230225012048-214862532bf5/reflectutil/swapper_test.go (about) 1 // Copyright 2016 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package reflectutil 6 7 import ( 8 "fmt" 9 "reflect" 10 "strconv" 11 "testing" 12 ) 13 14 func TestSwapper(t *testing.T) { 15 type I int 16 var a, b, c I 17 type pair struct { 18 x, y int 19 } 20 type pairPtr struct { 21 x, y int 22 p *I 23 } 24 type S string 25 26 tests := []struct { 27 in interface{} 28 i, j int 29 want interface{} 30 }{ 31 { 32 in: []int{1, 20, 300}, 33 i: 0, 34 j: 2, 35 want: []int{300, 20, 1}, 36 }, 37 { 38 in: []uintptr{1, 20, 300}, 39 i: 0, 40 j: 2, 41 want: []uintptr{300, 20, 1}, 42 }, 43 { 44 in: []int16{1, 20, 300}, 45 i: 0, 46 j: 2, 47 want: []int16{300, 20, 1}, 48 }, 49 { 50 in: []int8{1, 20, 100}, 51 i: 0, 52 j: 2, 53 want: []int8{100, 20, 1}, 54 }, 55 { 56 in: []*I{&a, &b, &c}, 57 i: 0, 58 j: 2, 59 want: []*I{&c, &b, &a}, 60 }, 61 { 62 in: []string{"eric", "sergey", "larry"}, 63 i: 0, 64 j: 2, 65 want: []string{"larry", "sergey", "eric"}, 66 }, 67 { 68 in: []S{"eric", "sergey", "larry"}, 69 i: 0, 70 j: 2, 71 want: []S{"larry", "sergey", "eric"}, 72 }, 73 { 74 in: []pair{{1, 2}, {3, 4}, {5, 6}}, 75 i: 0, 76 j: 2, 77 want: []pair{{5, 6}, {3, 4}, {1, 2}}, 78 }, 79 { 80 in: []pairPtr{{1, 2, &a}, {3, 4, &b}, {5, 6, &c}}, 81 i: 0, 82 j: 2, 83 want: []pairPtr{{5, 6, &c}, {3, 4, &b}, {1, 2, &a}}, 84 }, 85 } 86 for i, tt := range tests { 87 inStr := fmt.Sprint(tt.in) 88 Swapper(tt.in)(tt.i, tt.j) 89 if !reflect.DeepEqual(tt.in, tt.want) { 90 t.Errorf("%d. swapping %v and %v of %v = %v; want %v", i, tt.i, tt.j, inStr, tt.in, tt.want) 91 } 92 } 93 } 94 95 func BenchmarkSwap(b *testing.B) { 96 const N = 1024 97 strs := make([]string, N) 98 for i := range strs { 99 strs[i] = strconv.Itoa(i) 100 } 101 swap := Swapper(strs) 102 103 b.ResetTimer() 104 i, j := 0, 1 105 for n := 0; n < b.N; n++ { 106 i = (i + 1) % N 107 j = (j + 2) % N 108 swap(i, j) 109 } 110 }