github.com/amarpal/go-tools@v0.0.0-20240422043104-40142f59f616/simple/s1001/testdata/src/example.com/CheckLoopCopy/copy.go (about) 1 package pkg 2 3 func fn() { 4 var b1, b2 []byte 5 for i, v := range b1 { //@ diag(`should use copy(to, from)`) 6 b2[i] = v 7 } 8 9 for i := range b1 { //@ diag(`should use copy`) 10 b2[i] = b1[i] 11 } 12 13 type T [][16]byte 14 var a T 15 b := make([]interface{}, len(a)) 16 for i := range b { 17 b[i] = a[i] 18 } 19 20 var b3, b4 []*byte 21 for i := range b3 { //@ diag(`should use copy`) 22 b4[i] = b3[i] 23 } 24 25 var m map[int]byte 26 for i, v := range b1 { 27 m[i] = v 28 } 29 30 } 31 32 func src() []interface{} { return nil } 33 34 func fn1() { 35 // Don't flag this, the source is dynamic 36 var dst []interface{} 37 for i := range src() { 38 dst[i] = src()[i] 39 } 40 } 41 42 func fn2() { 43 type T struct { 44 b []byte 45 } 46 47 var src []byte 48 var dst T 49 for i, v := range src { //@ diag(`should use copy`) 50 dst.b[i] = v 51 } 52 } 53 54 func fn3() { 55 var src []byte 56 var dst [][]byte 57 for i, v := range src { //@ diag(`should use copy`) 58 dst[0][i] = v 59 } 60 for i, v := range src { 61 // Don't flag, destination depends on loop variable 62 dst[i][i] = v 63 } 64 for i, v := range src { 65 // Don't flag, destination depends on loop variable 66 dst[v][i] = v 67 } 68 } 69 70 func fn4() { 71 var b []byte 72 var a1 [5]byte 73 var a2 [10]byte 74 var a3 [5]byte 75 76 for i := range b { //@ diag(`should use copy(to[:], from)`) 77 a1[i] = b[i] 78 } 79 for i := range a1 { //@ diag(`should use copy(to, from[:])`) 80 b[i] = a1[i] 81 } 82 for i := range a1 { //@ diag(`should use copy(to[:], from[:])`) 83 a2[i] = a1[i] 84 } 85 for i := range a1 { //@ diag(`should copy arrays using assignment`) 86 a3[i] = a1[i] 87 } 88 89 a1p := &a1 90 a2p := &a2 91 a3p := &a3 92 for i := range b { //@ diag(`should use copy`) 93 a1p[i] = b[i] 94 } 95 for i := range a1p { //@ diag(`should use copy`) 96 b[i] = a1p[i] 97 } 98 for i := range a1p { //@ diag(`should use copy`) 99 a2p[i] = a1p[i] 100 } 101 for i := range a1p { //@ diag(`should copy arrays using assignment`) 102 a3p[i] = a1p[i] 103 } 104 105 for i := range a1 { //@ diag(`should use copy`) 106 a2p[i] = a1[i] 107 } 108 for i := range a1 { //@ diag(`should copy arrays using assignment`) 109 a3p[i] = a1[i] 110 } 111 for i := range a1p { //@ diag(`should use copy`) 112 a2[i] = a1p[i] 113 } 114 for i := range a1p { //@ diag(`should copy arrays using assignment`) 115 a3[i] = a1p[i] 116 } 117 } 118 119 func fn5() { 120 var src, dst []byte 121 for i := 0; i < len(src); i++ { //@ diag(`should use copy`) 122 dst[i] = src[i] 123 } 124 125 len := func([]byte) int { return 0 } 126 for i := 0; i < len(src); i++ { 127 dst[i] = src[i] 128 } 129 } 130 131 func fn6() { 132 var src, dst []byte 133 copy := func() {} 134 _ = copy 135 for i, v := range src { 136 dst[i] = v 137 } 138 }