blob: 7d40f9a8b67f668f990820ad743b40c2ed03acc2 [file] [log] [blame]
Rob Pike536b1f22008-10-23 17:13:34 -07001// Copyright 2009 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
Russ Cox3b864e42009-08-12 13:18:37 -07005package reflect_test
Rob Pike536b1f22008-10-23 17:13:34 -07006
7import (
Russ Coxe1ee3b52011-04-20 16:24:45 -04008 "bytes"
Rob Pikeab44a812011-08-22 13:22:42 +10009 "encoding/base64"
Russ Cox46f379c2012-09-22 08:52:27 -040010 "flag"
Russ Cox6672b402010-06-14 11:23:11 -070011 "fmt"
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080012 "io"
Russ Cox370ae052012-09-18 14:22:41 -040013 "math/rand"
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080014 "os"
15 . "reflect"
Albert Strasheim0a71a5b2013-03-06 15:52:32 -080016 "runtime"
Russ Cox3660b532013-03-26 11:50:29 -070017 "sort"
Russ Cox59847322014-02-21 13:51:22 -050018 "strings"
Russ Cox370ae052012-09-18 14:22:41 -040019 "sync"
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080020 "testing"
Russ Cox370ae052012-09-18 14:22:41 -040021 "time"
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080022 "unsafe"
Rob Pike536b1f22008-10-23 17:13:34 -070023)
24
Russ Coxa479a452011-11-16 19:18:25 -050025func TestBool(t *testing.T) {
26 v := ValueOf(true)
27 if v.Bool() != true {
28 t.Fatal("ValueOf(true).Bool() = false")
29 }
30}
31
Russ Cox64f4e0b2009-07-07 11:03:12 -070032type integer int
Robert Griesemer77334b982009-11-05 14:23:20 -080033type T struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080034 a int
35 b float64
36 c string
37 d *int
Robert Griesemer77334b982009-11-05 14:23:20 -080038}
Rob Pike536b1f22008-10-23 17:13:34 -070039
Russ Cox64f4e0b2009-07-07 11:03:12 -070040type pair struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080041 i interface{}
42 s string
Russ Cox64f4e0b2009-07-07 11:03:12 -070043}
44
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080045func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
Rob Pike536b1f22008-10-23 17:13:34 -070046
Russ Cox64f4e0b2009-07-07 11:03:12 -070047func assert(t *testing.T, s, want string) {
48 if s != want {
Robert Griesemer40621d52009-11-09 12:07:39 -080049 t.Errorf("have %#q want %#q", s, want)
Russ Cox64f4e0b2009-07-07 11:03:12 -070050 }
51}
52
Russ Cox0e2bb622011-04-25 13:39:16 -040053func typestring(i interface{}) string { return TypeOf(i).String() }
Russ Cox64f4e0b2009-07-07 11:03:12 -070054
Robert Griesemer77334b982009-11-05 14:23:20 -080055var typeTests = []pair{
Robert Griesemer34788912010-10-22 10:06:33 -070056 {struct{ x int }{}, "int"},
57 {struct{ x int8 }{}, "int8"},
58 {struct{ x int16 }{}, "int16"},
59 {struct{ x int32 }{}, "int32"},
60 {struct{ x int64 }{}, "int64"},
61 {struct{ x uint }{}, "uint"},
62 {struct{ x uint8 }{}, "uint8"},
63 {struct{ x uint16 }{}, "uint16"},
64 {struct{ x uint32 }{}, "uint32"},
65 {struct{ x uint64 }{}, "uint64"},
Robert Griesemer34788912010-10-22 10:06:33 -070066 {struct{ x float32 }{}, "float32"},
67 {struct{ x float64 }{}, "float64"},
68 {struct{ x int8 }{}, "int8"},
69 {struct{ x (**int8) }{}, "**int8"},
70 {struct{ x (**integer) }{}, "**reflect_test.integer"},
71 {struct{ x ([32]int32) }{}, "[32]int32"},
72 {struct{ x ([]int8) }{}, "[]int8"},
Russ Cox434a6c82011-12-02 14:45:07 -050073 {struct{ x (map[string]int32) }{}, "map[string]int32"},
Robert Griesemer34788912010-10-22 10:06:33 -070074 {struct{ x (chan<- string) }{}, "chan<- string"},
75 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -080076 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080077 c chan *int32
78 d float32
79 }
Robert Griesemer7151d232009-11-05 18:27:30 -080080 }{},
81 "struct { c chan *int32; d float32 }",
82 },
Robert Griesemer34788912010-10-22 10:06:33 -070083 {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
84 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -080085 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080086 c func(chan *integer, *int8)
87 }
Robert Griesemer7151d232009-11-05 18:27:30 -080088 }{},
89 "struct { c func(chan *reflect_test.integer, *int8) }",
90 },
Robert Griesemer34788912010-10-22 10:06:33 -070091 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -080092 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -080093 a int8
94 b int32
95 }
Robert Griesemer7151d232009-11-05 18:27:30 -080096 }{},
97 "struct { a int8; b int32 }",
98 },
Robert Griesemer34788912010-10-22 10:06:33 -070099 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800100 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800101 a int8
102 b int8
103 c int32
104 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800105 }{},
106 "struct { a int8; b int8; c int32 }",
107 },
Robert Griesemer34788912010-10-22 10:06:33 -0700108 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800109 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800110 a int8
111 b int8
112 c int8
113 d int32
114 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800115 }{},
116 "struct { a int8; b int8; c int8; d int32 }",
117 },
Robert Griesemer34788912010-10-22 10:06:33 -0700118 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800119 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800120 a int8
121 b int8
122 c int8
123 d int8
124 e int32
125 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800126 }{},
127 "struct { a int8; b int8; c int8; d int8; e int32 }",
128 },
Robert Griesemer34788912010-10-22 10:06:33 -0700129 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800130 x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800131 a int8
132 b int8
133 c int8
134 d int8
135 e int8
136 f int32
137 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800138 }{},
139 "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
140 },
Robert Griesemer34788912010-10-22 10:06:33 -0700141 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800142 x struct {
Russ Cox25733a92011-06-29 09:52:34 -0400143 a int8 `reflect:"hi there"`
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800144 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800145 }{},
Russ Cox25733a92011-06-29 09:52:34 -0400146 `struct { a int8 "reflect:\"hi there\"" }`,
Robert Griesemer7151d232009-11-05 18:27:30 -0800147 },
Robert Griesemer34788912010-10-22 10:06:33 -0700148 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800149 x struct {
Russ Cox25733a92011-06-29 09:52:34 -0400150 a int8 `reflect:"hi \x00there\t\n\"\\"`
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800151 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800152 }{},
Russ Cox25733a92011-06-29 09:52:34 -0400153 `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
Robert Griesemer7151d232009-11-05 18:27:30 -0800154 },
Robert Griesemer34788912010-10-22 10:06:33 -0700155 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800156 x struct {
Russ Cox6672b402010-06-14 11:23:11 -0700157 f func(args ...int)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800158 }
Robert Griesemer7151d232009-11-05 18:27:30 -0800159 }{},
Russ Cox6672b402010-06-14 11:23:11 -0700160 "struct { f func(...int) }",
Robert Griesemer7151d232009-11-05 18:27:30 -0800161 },
Robert Griesemer34788912010-10-22 10:06:33 -0700162 {struct {
Robert Griesemer77334b982009-11-05 14:23:20 -0800163 x (interface {
Robert Griesemer1be05bb2010-02-24 13:24:37 -0800164 a(func(func(int) int) func(func(int)) int)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800165 b()
166 })
Robert Griesemer7151d232009-11-05 18:27:30 -0800167 }{},
Russ Cox5ff33362011-04-21 08:14:50 -0400168 "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
Robert Griesemer7151d232009-11-05 18:27:30 -0800169 },
Russ Cox64f4e0b2009-07-07 11:03:12 -0700170}
171
Robert Griesemer77334b982009-11-05 14:23:20 -0800172var valueTests = []pair{
Todd Wang0e734972013-08-21 14:41:55 +1000173 {new(int), "132"},
Russ Cox40fccbc2011-04-18 14:35:33 -0400174 {new(int8), "8"},
175 {new(int16), "16"},
176 {new(int32), "32"},
177 {new(int64), "64"},
Todd Wang0e734972013-08-21 14:41:55 +1000178 {new(uint), "132"},
Russ Cox40fccbc2011-04-18 14:35:33 -0400179 {new(uint8), "8"},
180 {new(uint16), "16"},
181 {new(uint32), "32"},
182 {new(uint64), "64"},
183 {new(float32), "256.25"},
184 {new(float64), "512.125"},
Todd Wang0e734972013-08-21 14:41:55 +1000185 {new(complex64), "532.125+10i"},
186 {new(complex128), "564.25+1i"},
Russ Cox40fccbc2011-04-18 14:35:33 -0400187 {new(string), "stringy cheese"},
188 {new(bool), "true"},
189 {new(*int8), "*int8(0)"},
190 {new(**int8), "**int8(0)"},
191 {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
192 {new(**integer), "**reflect_test.integer(0)"},
Russ Cox434a6c82011-12-02 14:45:07 -0500193 {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
Russ Cox40fccbc2011-04-18 14:35:33 -0400194 {new(chan<- string), "chan<- string"},
195 {new(func(a int8, b int32)), "func(int8, int32)(0)"},
196 {new(struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800197 c chan *int32
198 d float32
Russ Cox40fccbc2011-04-18 14:35:33 -0400199 }),
Robert Griesemer7151d232009-11-05 18:27:30 -0800200 "struct { c chan *int32; d float32 }{chan *int32, 0}",
201 },
Russ Cox40fccbc2011-04-18 14:35:33 -0400202 {new(struct{ c func(chan *integer, *int8) }),
Robert Griesemer7151d232009-11-05 18:27:30 -0800203 "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
204 },
Russ Cox40fccbc2011-04-18 14:35:33 -0400205 {new(struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800206 a int8
207 b int32
Russ Cox40fccbc2011-04-18 14:35:33 -0400208 }),
Robert Griesemer7151d232009-11-05 18:27:30 -0800209 "struct { a int8; b int32 }{0, 0}",
210 },
Russ Cox40fccbc2011-04-18 14:35:33 -0400211 {new(struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800212 a int8
213 b int8
214 c int32
Russ Cox40fccbc2011-04-18 14:35:33 -0400215 }),
Robert Griesemer7151d232009-11-05 18:27:30 -0800216 "struct { a int8; b int8; c int32 }{0, 0, 0}",
217 },
Russ Cox64f4e0b2009-07-07 11:03:12 -0700218}
219
220func testType(t *testing.T, i int, typ Type, want string) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800221 s := typ.String()
Russ Cox64f4e0b2009-07-07 11:03:12 -0700222 if s != want {
Robert Griesemer40621d52009-11-09 12:07:39 -0800223 t.Errorf("#%d: have %#q, want %#q", i, s, want)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700224 }
225}
226
227func TestTypes(t *testing.T) {
228 for i, tt := range typeTests {
Russ Cox0e2bb622011-04-25 13:39:16 -0400229 testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700230 }
231}
232
Adam Langleya8a678f2009-10-21 19:51:27 -0700233func TestSet(t *testing.T) {
Russ Cox64f4e0b2009-07-07 11:03:12 -0700234 for i, tt := range valueTests {
Russ Coxa479a452011-11-16 19:18:25 -0500235 v := ValueOf(tt.i)
236 v = v.Elem()
Russ Coxfb175cf2011-04-08 12:26:51 -0400237 switch v.Kind() {
238 case Int:
239 v.SetInt(132)
240 case Int8:
241 v.SetInt(8)
242 case Int16:
243 v.SetInt(16)
244 case Int32:
245 v.SetInt(32)
246 case Int64:
247 v.SetInt(64)
248 case Uint:
249 v.SetUint(132)
250 case Uint8:
251 v.SetUint(8)
252 case Uint16:
253 v.SetUint(16)
254 case Uint32:
255 v.SetUint(32)
256 case Uint64:
257 v.SetUint(64)
258 case Float32:
259 v.SetFloat(256.25)
260 case Float64:
261 v.SetFloat(512.125)
262 case Complex64:
263 v.SetComplex(532.125 + 10i)
264 case Complex128:
265 v.SetComplex(564.25 + 1i)
266 case String:
267 v.SetString("stringy cheese")
268 case Bool:
269 v.SetBool(true)
Rob Pike536b1f22008-10-23 17:13:34 -0700270 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800271 s := valueToString(v)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700272 if s != tt.s {
Robert Griesemer40621d52009-11-09 12:07:39 -0800273 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
Rob Pike536b1f22008-10-23 17:13:34 -0700274 }
275 }
Rob Pike536b1f22008-10-23 17:13:34 -0700276}
277
Adam Langleya8a678f2009-10-21 19:51:27 -0700278func TestSetValue(t *testing.T) {
279 for i, tt := range valueTests {
Russ Cox0e2bb622011-04-25 13:39:16 -0400280 v := ValueOf(tt.i).Elem()
Russ Coxfb175cf2011-04-08 12:26:51 -0400281 switch v.Kind() {
282 case Int:
Russ Cox0e2bb622011-04-25 13:39:16 -0400283 v.Set(ValueOf(int(132)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400284 case Int8:
Russ Cox0e2bb622011-04-25 13:39:16 -0400285 v.Set(ValueOf(int8(8)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400286 case Int16:
Russ Cox0e2bb622011-04-25 13:39:16 -0400287 v.Set(ValueOf(int16(16)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400288 case Int32:
Russ Cox0e2bb622011-04-25 13:39:16 -0400289 v.Set(ValueOf(int32(32)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400290 case Int64:
Russ Cox0e2bb622011-04-25 13:39:16 -0400291 v.Set(ValueOf(int64(64)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400292 case Uint:
Russ Cox0e2bb622011-04-25 13:39:16 -0400293 v.Set(ValueOf(uint(132)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400294 case Uint8:
Russ Cox0e2bb622011-04-25 13:39:16 -0400295 v.Set(ValueOf(uint8(8)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400296 case Uint16:
Russ Cox0e2bb622011-04-25 13:39:16 -0400297 v.Set(ValueOf(uint16(16)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400298 case Uint32:
Russ Cox0e2bb622011-04-25 13:39:16 -0400299 v.Set(ValueOf(uint32(32)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400300 case Uint64:
Russ Cox0e2bb622011-04-25 13:39:16 -0400301 v.Set(ValueOf(uint64(64)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400302 case Float32:
Russ Cox0e2bb622011-04-25 13:39:16 -0400303 v.Set(ValueOf(float32(256.25)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400304 case Float64:
Russ Cox0e2bb622011-04-25 13:39:16 -0400305 v.Set(ValueOf(512.125))
Russ Coxfb175cf2011-04-08 12:26:51 -0400306 case Complex64:
Russ Cox0e2bb622011-04-25 13:39:16 -0400307 v.Set(ValueOf(complex64(532.125 + 10i)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400308 case Complex128:
Russ Cox0e2bb622011-04-25 13:39:16 -0400309 v.Set(ValueOf(complex128(564.25 + 1i)))
Russ Coxfb175cf2011-04-08 12:26:51 -0400310 case String:
Russ Cox0e2bb622011-04-25 13:39:16 -0400311 v.Set(ValueOf("stringy cheese"))
Russ Coxfb175cf2011-04-08 12:26:51 -0400312 case Bool:
Russ Cox0e2bb622011-04-25 13:39:16 -0400313 v.Set(ValueOf(true))
Adam Langleya8a678f2009-10-21 19:51:27 -0700314 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800315 s := valueToString(v)
Adam Langleya8a678f2009-10-21 19:51:27 -0700316 if s != tt.s {
Robert Griesemer40621d52009-11-09 12:07:39 -0800317 t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
Adam Langleya8a678f2009-10-21 19:51:27 -0700318 }
319 }
320}
321
Robert Griesemer77334b982009-11-05 14:23:20 -0800322var _i = 7
Russ Cox64f4e0b2009-07-07 11:03:12 -0700323
Robert Griesemer77334b982009-11-05 14:23:20 -0800324var valueToStringTests = []pair{
Robert Griesemer34788912010-10-22 10:06:33 -0700325 {123, "123"},
326 {123.5, "123.5"},
327 {byte(123), "123"},
328 {"abc", "abc"},
329 {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
330 {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
331 {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
332 {&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[10]int(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
333 {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
334 {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
Rob Pike536b1f22008-10-23 17:13:34 -0700335}
336
Russ Cox64f4e0b2009-07-07 11:03:12 -0700337func TestValueToString(t *testing.T) {
338 for i, test := range valueToStringTests {
Russ Cox0e2bb622011-04-25 13:39:16 -0400339 s := valueToString(ValueOf(test.i))
Russ Cox64f4e0b2009-07-07 11:03:12 -0700340 if s != test.s {
Robert Griesemer40621d52009-11-09 12:07:39 -0800341 t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
Rob Pike419e1e02008-11-12 19:05:05 -0800342 }
343 }
Russ Cox64f4e0b2009-07-07 11:03:12 -0700344}
Rob Pike419e1e02008-11-12 19:05:05 -0800345
Russ Cox64f4e0b2009-07-07 11:03:12 -0700346func TestArrayElemSet(t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -0400347 v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
Russ Coxfb175cf2011-04-08 12:26:51 -0400348 v.Index(4).SetInt(123)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800349 s := valueToString(v)
350 const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
Russ Cox64f4e0b2009-07-07 11:03:12 -0700351 if s != want {
Robert Griesemer40621d52009-11-09 12:07:39 -0800352 t.Errorf("[10]int: have %#q want %#q", s, want)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700353 }
Rob Pikea45f9472008-11-04 22:54:11 -0800354
Russ Cox0e2bb622011-04-25 13:39:16 -0400355 v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
Russ Coxfb175cf2011-04-08 12:26:51 -0400356 v.Index(4).SetInt(123)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800357 s = valueToString(v)
358 const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
Russ Cox64f4e0b2009-07-07 11:03:12 -0700359 if s != want1 {
Robert Griesemer40621d52009-11-09 12:07:39 -0800360 t.Errorf("[]int: have %#q want %#q", s, want1)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700361 }
362}
Rob Pikea45f9472008-11-04 22:54:11 -0800363
Russ Cox64f4e0b2009-07-07 11:03:12 -0700364func TestPtrPointTo(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800365 var ip *int32
366 var i int32 = 1234
Russ Cox0e2bb622011-04-25 13:39:16 -0400367 vip := ValueOf(&ip)
368 vi := ValueOf(&i).Elem()
Russ Coxfb175cf2011-04-08 12:26:51 -0400369 vip.Elem().Set(vi.Addr())
Russ Cox64f4e0b2009-07-07 11:03:12 -0700370 if *ip != 1234 {
Robert Griesemer40621d52009-11-09 12:07:39 -0800371 t.Errorf("got %d, want 1234", *ip)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700372 }
Robert Griesemera48b35e2010-08-17 15:12:28 -0700373
374 ip = nil
Russ Cox0e2bb622011-04-25 13:39:16 -0400375 vp := ValueOf(&ip).Elem()
Russ Coxfb175cf2011-04-08 12:26:51 -0400376 vp.Set(Zero(vp.Type()))
Robert Griesemera48b35e2010-08-17 15:12:28 -0700377 if ip != nil {
378 t.Errorf("got non-nil (%p), want nil", ip)
379 }
Russ Cox64f4e0b2009-07-07 11:03:12 -0700380}
Rob Pikea45f9472008-11-04 22:54:11 -0800381
Russ Cox7295b612010-04-20 17:02:08 -0700382func TestPtrSetNil(t *testing.T) {
383 var i int32 = 1234
384 ip := &i
Russ Cox0e2bb622011-04-25 13:39:16 -0400385 vip := ValueOf(&ip)
Russ Coxfb175cf2011-04-08 12:26:51 -0400386 vip.Elem().Set(Zero(vip.Elem().Type()))
Russ Cox7295b612010-04-20 17:02:08 -0700387 if ip != nil {
388 t.Errorf("got non-nil (%d), want nil", *ip)
389 }
390}
391
392func TestMapSetNil(t *testing.T) {
393 m := make(map[string]int)
Russ Cox0e2bb622011-04-25 13:39:16 -0400394 vm := ValueOf(&m)
Russ Coxfb175cf2011-04-08 12:26:51 -0400395 vm.Elem().Set(Zero(vm.Elem().Type()))
Russ Cox7295b612010-04-20 17:02:08 -0700396 if m != nil {
397 t.Errorf("got non-nil (%p), want nil", m)
398 }
399}
400
Rob Pikee02f2b52009-11-08 21:57:59 -0800401func TestAll(t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -0400402 testType(t, 1, TypeOf((int8)(0)), "int8")
403 testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
Rob Pikea45f9472008-11-04 22:54:11 -0800404
Russ Cox0e2bb622011-04-25 13:39:16 -0400405 typ := TypeOf((*struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800406 c chan *int32
407 d float32
408 })(nil))
409 testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
Russ Coxfb175cf2011-04-08 12:26:51 -0400410 etyp := typ.Elem()
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800411 testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
Russ Coxfb175cf2011-04-08 12:26:51 -0400412 styp := etyp
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800413 f := styp.Field(0)
414 testType(t, 5, f.Type, "chan *int32")
Rob Pikea93c5c82009-07-16 18:21:14 -0700415
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800416 f, present := styp.FieldByName("d")
Rob Pikea93c5c82009-07-16 18:21:14 -0700417 if !present {
Robert Griesemer40621d52009-11-09 12:07:39 -0800418 t.Errorf("FieldByName says present field is absent")
Rob Pikea93c5c82009-07-16 18:21:14 -0700419 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800420 testType(t, 6, f.Type, "float32")
Rob Pikea45f9472008-11-04 22:54:11 -0800421
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800422 f, present = styp.FieldByName("absent")
Rob Pikea93c5c82009-07-16 18:21:14 -0700423 if present {
Robert Griesemer40621d52009-11-09 12:07:39 -0800424 t.Errorf("FieldByName says absent field is present")
Rob Pikea93c5c82009-07-16 18:21:14 -0700425 }
426
Russ Cox0e2bb622011-04-25 13:39:16 -0400427 typ = TypeOf([32]int32{})
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800428 testType(t, 7, typ, "[32]int32")
Russ Coxfb175cf2011-04-08 12:26:51 -0400429 testType(t, 8, typ.Elem(), "int32")
Rob Pikea45f9472008-11-04 22:54:11 -0800430
Russ Cox0e2bb622011-04-25 13:39:16 -0400431 typ = TypeOf((map[string]*int32)(nil))
Russ Cox434a6c82011-12-02 14:45:07 -0500432 testType(t, 9, typ, "map[string]*int32")
Russ Coxfb175cf2011-04-08 12:26:51 -0400433 mtyp := typ
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800434 testType(t, 10, mtyp.Key(), "string")
435 testType(t, 11, mtyp.Elem(), "*int32")
Rob Pikebdbb9582008-11-05 08:17:01 -0800436
Russ Cox0e2bb622011-04-25 13:39:16 -0400437 typ = TypeOf((chan<- string)(nil))
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800438 testType(t, 12, typ, "chan<- string")
Russ Coxfb175cf2011-04-08 12:26:51 -0400439 testType(t, 13, typ.Elem(), "string")
Rob Pike5a1cbe82008-11-05 13:01:33 -0800440
441 // make sure tag strings are not part of element type
Russ Cox0e2bb622011-04-25 13:39:16 -0400442 typ = TypeOf(struct {
Russ Cox25733a92011-06-29 09:52:34 -0400443 d []uint32 `reflect:"TAG"`
Russ Coxfb175cf2011-04-08 12:26:51 -0400444 }{}).Field(0).Type
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800445 testType(t, 14, typ, "[]uint32")
Rob Pike536b1f22008-10-23 17:13:34 -0700446}
Russ Cox387df5e2008-11-24 14:51:33 -0800447
Russ Cox839a6842009-01-20 14:40:40 -0800448func TestInterfaceGet(t *testing.T) {
Robert Griesemer77334b982009-11-05 14:23:20 -0800449 var inter struct {
Russ Cox40fccbc2011-04-18 14:35:33 -0400450 E interface{}
Robert Griesemer77334b982009-11-05 14:23:20 -0800451 }
Russ Cox40fccbc2011-04-18 14:35:33 -0400452 inter.E = 123.456
Russ Cox0e2bb622011-04-25 13:39:16 -0400453 v1 := ValueOf(&inter)
Russ Coxfb175cf2011-04-08 12:26:51 -0400454 v2 := v1.Elem().Field(0)
Luuk van Dijk50110c92011-10-31 18:09:40 +0100455 assert(t, v2.Type().String(), "interface {}")
Russ Coxfb175cf2011-04-08 12:26:51 -0400456 i2 := v2.Interface()
Russ Cox0e2bb622011-04-25 13:39:16 -0400457 v3 := ValueOf(i2)
Russ Coxf2b5a072011-01-19 23:09:00 -0500458 assert(t, v3.Type().String(), "float64")
Russ Cox387df5e2008-11-24 14:51:33 -0800459}
Russ Coxd0e30cd2008-12-10 15:55:59 -0800460
Russ Coxac6ebfd2009-04-06 21:28:04 -0700461func TestInterfaceValue(t *testing.T) {
Robert Griesemer77334b982009-11-05 14:23:20 -0800462 var inter struct {
Russ Cox40fccbc2011-04-18 14:35:33 -0400463 E interface{}
Robert Griesemer77334b982009-11-05 14:23:20 -0800464 }
Russ Cox40fccbc2011-04-18 14:35:33 -0400465 inter.E = 123.456
Russ Cox0e2bb622011-04-25 13:39:16 -0400466 v1 := ValueOf(&inter)
Russ Coxfb175cf2011-04-08 12:26:51 -0400467 v2 := v1.Elem().Field(0)
Luuk van Dijk50110c92011-10-31 18:09:40 +0100468 assert(t, v2.Type().String(), "interface {}")
Russ Coxfb175cf2011-04-08 12:26:51 -0400469 v3 := v2.Elem()
Russ Coxf2b5a072011-01-19 23:09:00 -0500470 assert(t, v3.Type().String(), "float64")
Russ Cox64627b02009-04-15 00:55:58 -0700471
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800472 i3 := v2.Interface()
Russ Coxf2b5a072011-01-19 23:09:00 -0500473 if _, ok := i3.(float64); !ok {
Russ Cox0e2bb622011-04-25 13:39:16 -0400474 t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
Russ Cox4b8c13d2009-04-14 19:03:57 -0700475 }
Russ Coxac6ebfd2009-04-06 21:28:04 -0700476}
477
Ian Lance Taylorca9765d2009-04-14 06:46:01 -0700478func TestFunctionValue(t *testing.T) {
Russ Cox40fccbc2011-04-18 14:35:33 -0400479 var x interface{} = func() {}
Russ Cox0e2bb622011-04-25 13:39:16 -0400480 v := ValueOf(x)
Russ Cox46deaa22011-12-06 10:48:17 -0500481 if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
482 t.Fatalf("TestFunction returned wrong pointer")
Ian Lance Taylorca9765d2009-04-14 06:46:01 -0700483 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800484 assert(t, v.Type().String(), "func()")
Ian Lance Taylorca9765d2009-04-14 06:46:01 -0700485}
486
Nigel Tao8b64cd92010-12-15 08:50:08 +1100487var appendTests = []struct {
488 orig, extra []int
489}{
490 {make([]int, 2, 4), []int{22}},
491 {make([]int, 2, 4), []int{22, 33, 44}},
492}
493
Russ Cox40fccbc2011-04-18 14:35:33 -0400494func sameInts(x, y []int) bool {
495 if len(x) != len(y) {
496 return false
497 }
498 for i, xx := range x {
499 if xx != y[i] {
500 return false
501 }
502 }
503 return true
504}
505
Nigel Tao8b64cd92010-12-15 08:50:08 +1100506func TestAppend(t *testing.T) {
507 for i, test := range appendTests {
508 origLen, extraLen := len(test.orig), len(test.extra)
509 want := append(test.orig, test.extra...)
510 // Convert extra from []int to []Value.
511 e0 := make([]Value, len(test.extra))
512 for j, e := range test.extra {
Russ Cox0e2bb622011-04-25 13:39:16 -0400513 e0[j] = ValueOf(e)
Nigel Tao8b64cd92010-12-15 08:50:08 +1100514 }
515 // Convert extra from []int to *SliceValue.
Russ Cox0e2bb622011-04-25 13:39:16 -0400516 e1 := ValueOf(test.extra)
Nigel Tao8b64cd92010-12-15 08:50:08 +1100517 // Test Append.
Russ Cox0e2bb622011-04-25 13:39:16 -0400518 a0 := ValueOf(test.orig)
Nigel Tao8b64cd92010-12-15 08:50:08 +1100519 have0 := Append(a0, e0...).Interface().([]int)
Russ Cox40fccbc2011-04-18 14:35:33 -0400520 if !sameInts(have0, want) {
521 t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
Nigel Tao8b64cd92010-12-15 08:50:08 +1100522 }
523 // Check that the orig and extra slices were not modified.
524 if len(test.orig) != origLen {
525 t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
526 }
527 if len(test.extra) != extraLen {
528 t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
529 }
530 // Test AppendSlice.
Russ Cox0e2bb622011-04-25 13:39:16 -0400531 a1 := ValueOf(test.orig)
Nigel Tao8b64cd92010-12-15 08:50:08 +1100532 have1 := AppendSlice(a1, e1).Interface().([]int)
Russ Cox40fccbc2011-04-18 14:35:33 -0400533 if !sameInts(have1, want) {
Nigel Tao8b64cd92010-12-15 08:50:08 +1100534 t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
535 }
536 // Check that the orig and extra slices were not modified.
537 if len(test.orig) != origLen {
538 t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
539 }
540 if len(test.extra) != extraLen {
541 t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
542 }
543 }
544}
545
546func TestCopy(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800547 a := []int{1, 2, 3, 4, 10, 9, 8, 7}
548 b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
549 c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
Russ Coxd0e30cd2008-12-10 15:55:59 -0800550 for i := 0; i < len(b); i++ {
551 if b[i] != c[i] {
Robert Griesemer40621d52009-11-09 12:07:39 -0800552 t.Fatalf("b != c before test")
Russ Coxd0e30cd2008-12-10 15:55:59 -0800553 }
554 }
Russ Cox40fccbc2011-04-18 14:35:33 -0400555 a1 := a
556 b1 := b
Russ Cox0e2bb622011-04-25 13:39:16 -0400557 aa := ValueOf(&a1).Elem()
558 ab := ValueOf(&b1).Elem()
Russ Coxd47d8882008-12-18 22:37:22 -0800559 for tocopy := 1; tocopy <= 7; tocopy++ {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800560 aa.SetLen(tocopy)
Nigel Tao73fd2982010-12-12 20:27:29 +1100561 Copy(ab, aa)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800562 aa.SetLen(8)
Russ Coxd0e30cd2008-12-10 15:55:59 -0800563 for i := 0; i < tocopy; i++ {
564 if a[i] != b[i] {
Russ Cox64f4e0b2009-07-07 11:03:12 -0700565 t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
Robert Griesemer40621d52009-11-09 12:07:39 -0800566 tocopy, i, a[i], i, b[i])
Russ Coxd0e30cd2008-12-10 15:55:59 -0800567 }
568 }
569 for i := tocopy; i < len(b); i++ {
570 if b[i] != c[i] {
571 if i < len(a) {
Russ Cox64f4e0b2009-07-07 11:03:12 -0700572 t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
Robert Griesemer40621d52009-11-09 12:07:39 -0800573 tocopy, i, a[i], i, b[i], i, c[i])
Russ Coxd0e30cd2008-12-10 15:55:59 -0800574 } else {
Russ Cox64f4e0b2009-07-07 11:03:12 -0700575 t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
Robert Griesemer40621d52009-11-09 12:07:39 -0800576 tocopy, i, b[i], i, c[i])
Russ Coxd0e30cd2008-12-10 15:55:59 -0800577 }
Russ Coxd47d8882008-12-18 22:37:22 -0800578 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -0800579 t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
Russ Coxd0e30cd2008-12-10 15:55:59 -0800580 }
581 }
582 }
583}
Russ Cox484ba932009-01-09 00:17:46 -0800584
Gustavo Niemeyer6850dba2011-04-27 18:22:53 -0300585func TestCopyArray(t *testing.T) {
586 a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
587 b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
588 c := b
589 aa := ValueOf(&a).Elem()
590 ab := ValueOf(&b).Elem()
591 Copy(ab, aa)
592 for i := 0; i < len(a); i++ {
593 if a[i] != b[i] {
594 t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
595 }
596 }
597 for i := len(a); i < len(b); i++ {
598 if b[i] != c[i] {
Gustavo Niemeyer3e9a1d52011-04-28 14:16:41 -0300599 t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
Gustavo Niemeyer6850dba2011-04-27 18:22:53 -0300600 } else {
601 t.Logf("elem %d is okay\n", i)
602 }
603 }
604}
605
Russ Cox839a6842009-01-20 14:40:40 -0800606func TestBigUnnamedStruct(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800607 b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
Russ Cox0e2bb622011-04-25 13:39:16 -0400608 v := ValueOf(b)
Robert Griesemer77334b982009-11-05 14:23:20 -0800609 b1 := v.Interface().(struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800610 a, b, c, d int64
611 })
Russ Cox484ba932009-01-09 00:17:46 -0800612 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
Russ Cox0e2bb622011-04-25 13:39:16 -0400613 t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
Russ Cox484ba932009-01-09 00:17:46 -0800614 }
615}
616
Rob Pikeed2ac9b2009-01-16 12:48:07 -0800617type big struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800618 a, b, c, d, e int64
Russ Cox484ba932009-01-09 00:17:46 -0800619}
Robert Griesemer77334b982009-11-05 14:23:20 -0800620
Russ Cox839a6842009-01-20 14:40:40 -0800621func TestBigStruct(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800622 b := big{1, 2, 3, 4, 5}
Russ Cox0e2bb622011-04-25 13:39:16 -0400623 v := ValueOf(b)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800624 b1 := v.Interface().(big)
Russ Cox484ba932009-01-09 00:17:46 -0800625 if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
Russ Cox0e2bb622011-04-25 13:39:16 -0400626 t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
Russ Cox484ba932009-01-09 00:17:46 -0800627 }
628}
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700629
630type Basic struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800631 x int
632 y float32
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700633}
634
Russ Cox64627b02009-04-15 00:55:58 -0700635type NotBasic Basic
636
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700637type DeepEqualTest struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800638 a, b interface{}
639 eq bool
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700640}
641
Rob Pike3a1c2262012-02-24 16:25:39 +1100642// Simple functions for DeepEqual tests.
643var (
644 fn1 func() // nil.
645 fn2 func() // nil.
646 fn3 = func() { fn1() } // Not nil.
647)
648
Robert Griesemer77334b982009-11-05 14:23:20 -0800649var deepEqualTests = []DeepEqualTest{
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700650 // Equalities
Rob Pike53372902012-04-23 12:07:02 +1000651 {nil, nil, true},
Robert Griesemer34788912010-10-22 10:06:33 -0700652 {1, 1, true},
653 {int32(1), int32(1), true},
654 {0.5, 0.5, true},
655 {float32(0.5), float32(0.5), true},
656 {"hello", "hello", true},
657 {make([]int, 10), make([]int, 10), true},
658 {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
659 {Basic{1, 0.5}, Basic{1, 0.5}, true},
Russ Coxeb692922011-11-01 22:05:34 -0400660 {error(nil), error(nil), true},
Robert Griesemer34788912010-10-22 10:06:33 -0700661 {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
Rob Pike3a1c2262012-02-24 16:25:39 +1100662 {fn1, fn2, true},
Russ Coxa439f662009-07-01 16:45:09 -0700663
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700664 // Inequalities
Robert Griesemer34788912010-10-22 10:06:33 -0700665 {1, 2, false},
666 {int32(1), int32(2), false},
667 {0.5, 0.6, false},
668 {float32(0.5), float32(0.6), false},
669 {"hello", "hey", false},
670 {make([]int, 10), make([]int, 11), false},
671 {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
672 {Basic{1, 0.5}, Basic{1, 0.6}, false},
673 {Basic{1, 0}, Basic{2, 0}, false},
674 {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
675 {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
676 {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
677 {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
678 {nil, 1, false},
679 {1, nil, false},
Rob Pike3a1c2262012-02-24 16:25:39 +1100680 {fn1, fn3, false},
681 {fn3, fn3, false},
Robert Griesemerb39e2a02014-07-01 10:28:10 -0700682 {[][]int{{1}}, [][]int{{2}}, false},
Russ Coxa439f662009-07-01 16:45:09 -0700683
Russ Cox4e654782011-11-14 16:11:15 -0500684 // Nil vs empty: not the same.
685 {[]int{}, []int(nil), false},
686 {[]int{}, []int{}, true},
687 {[]int(nil), []int(nil), true},
688 {map[int]int{}, map[int]int(nil), false},
689 {map[int]int{}, map[int]int{}, true},
690 {map[int]int(nil), map[int]int(nil), true},
691
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700692 // Mismatched types
Robert Griesemer34788912010-10-22 10:06:33 -0700693 {1, 1.0, false},
694 {int32(1), int64(1), false},
695 {0.5, "hello", false},
696 {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
697 {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
698 {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
699 {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700700}
701
702func TestDeepEqual(t *testing.T) {
Russ Coxca6a0fe2009-09-15 09:41:59 -0700703 for _, test := range deepEqualTests {
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700704 if r := DeepEqual(test.a, test.b); r != test.eq {
Robert Griesemer40621d52009-11-09 12:07:39 -0800705 t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700706 }
707 }
708}
709
Russ Cox0e2bb622011-04-25 13:39:16 -0400710func TestTypeOf(t *testing.T) {
Rob Pike53372902012-04-23 12:07:02 +1000711 // Special case for nil
712 if typ := TypeOf(nil); typ != nil {
713 t.Errorf("expected nil type for nil value; got %v", typ)
714 }
Russ Coxca6a0fe2009-09-15 09:41:59 -0700715 for _, test := range deepEqualTests {
Russ Cox0e2bb622011-04-25 13:39:16 -0400716 v := ValueOf(test.a)
Russ Coxfb175cf2011-04-08 12:26:51 -0400717 if !v.IsValid() {
Robert Griesemer40621d52009-11-09 12:07:39 -0800718 continue
Russ Cox64f4e0b2009-07-07 11:03:12 -0700719 }
Russ Cox0e2bb622011-04-25 13:39:16 -0400720 typ := TypeOf(test.a)
Russ Cox48662232009-06-25 14:25:38 -0700721 if typ != v.Type() {
Russ Cox0e2bb622011-04-25 13:39:16 -0400722 t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
Russ Cox48662232009-06-25 14:25:38 -0700723 }
724 }
725}
726
Rob Pike1880b902009-07-10 11:20:10 -0700727type Recursive struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800728 x int
729 r *Recursive
Rob Pike1880b902009-07-10 11:20:10 -0700730}
731
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700732func TestDeepEqualRecursiveStruct(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800733 a, b := new(Recursive), new(Recursive)
734 *a = Recursive{12, a}
735 *b = Recursive{12, b}
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700736 if !DeepEqual(a, b) {
Robert Griesemer40621d52009-11-09 12:07:39 -0800737 t.Error("DeepEqual(recursive same) = false, want true")
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700738 }
739}
740
Russ Cox45bdf032010-06-20 12:16:25 -0700741type _Complex struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800742 a int
Russ Cox45bdf032010-06-20 12:16:25 -0700743 b [3]*_Complex
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800744 c *string
Russ Coxf2b5a072011-01-19 23:09:00 -0500745 d map[float64]float64
Rob Pike1880b902009-07-10 11:20:10 -0700746}
747
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700748func TestDeepEqualComplexStruct(t *testing.T) {
Russ Coxf2b5a072011-01-19 23:09:00 -0500749 m := make(map[float64]float64)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800750 stra, strb := "hello", "hello"
Russ Cox45bdf032010-06-20 12:16:25 -0700751 a, b := new(_Complex), new(_Complex)
752 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
753 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700754 if !DeepEqual(a, b) {
Robert Griesemer40621d52009-11-09 12:07:39 -0800755 t.Error("DeepEqual(complex same) = false, want true")
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700756 }
757}
758
759func TestDeepEqualComplexStructInequality(t *testing.T) {
Russ Coxf2b5a072011-01-19 23:09:00 -0500760 m := make(map[float64]float64)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800761 stra, strb := "hello", "helloo" // Difference is here
Russ Cox45bdf032010-06-20 12:16:25 -0700762 a, b := new(_Complex), new(_Complex)
763 *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
764 *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700765 if DeepEqual(a, b) {
Robert Griesemer40621d52009-11-09 12:07:39 -0800766 t.Error("DeepEqual(complex different) = true, want false")
Daniel Nadasic4ad4f92009-04-01 22:20:18 -0700767 }
768}
Rob Pike93831d22009-04-29 22:16:53 -0700769
Russ Cox86e6a442011-05-03 10:38:37 -0400770type UnexpT struct {
771 m map[int]int
772}
773
774func TestDeepEqualUnexportedMap(t *testing.T) {
775 // Check that DeepEqual can look at unexported fields.
776 x1 := UnexpT{map[int]int{1: 2}}
777 x2 := UnexpT{map[int]int{1: 2}}
778 if !DeepEqual(&x1, &x2) {
779 t.Error("DeepEqual(x1, x2) = false, want true")
780 }
781
782 y1 := UnexpT{map[int]int{2: 3}}
783 if DeepEqual(&x1, &y1) {
784 t.Error("DeepEqual(x1, y1) = true, want false")
785 }
786}
787
Rob Pike93831d22009-04-29 22:16:53 -0700788func check2ndField(x interface{}, offs uintptr, t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -0400789 s := ValueOf(x)
Russ Coxfb175cf2011-04-08 12:26:51 -0400790 f := s.Type().Field(1)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700791 if f.Offset != offs {
Robert Griesemer40621d52009-11-09 12:07:39 -0800792 t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
Rob Pike93831d22009-04-29 22:16:53 -0700793 }
794}
795
796// Check that structure alignment & offsets viewed through reflect agree with those
797// from the compiler itself.
798func TestAlignment(t *testing.T) {
799 type T1inner struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800800 a int
Rob Pike93831d22009-04-29 22:16:53 -0700801 }
802 type T1 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800803 T1inner
804 f int
Rob Pike93831d22009-04-29 22:16:53 -0700805 }
806 type T2inner struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800807 a, b int
Rob Pike93831d22009-04-29 22:16:53 -0700808 }
809 type T2 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800810 T2inner
811 f int
Rob Pike93831d22009-04-29 22:16:53 -0700812 }
813
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800814 x := T1{T1inner{2}, 17}
815 check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
Rob Pike93831d22009-04-29 22:16:53 -0700816
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800817 x1 := T2{T2inner{2, 3}, 17}
818 check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
Rob Pike93831d22009-04-29 22:16:53 -0700819}
Rob Pikea8f6e382009-05-12 14:57:44 -0700820
Rob Pikea8f6e382009-05-12 14:57:44 -0700821func Nil(a interface{}, t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -0400822 n := ValueOf(a).Field(0)
Rob Pikea8f6e382009-05-12 14:57:44 -0700823 if !n.IsNil() {
Robert Griesemer40621d52009-11-09 12:07:39 -0800824 t.Errorf("%v should be nil", a)
Rob Pikea8f6e382009-05-12 14:57:44 -0700825 }
826}
827
828func NotNil(a interface{}, t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -0400829 n := ValueOf(a).Field(0)
Rob Pikea8f6e382009-05-12 14:57:44 -0700830 if n.IsNil() {
Russ Cox0e2bb622011-04-25 13:39:16 -0400831 t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
Rob Pikea8f6e382009-05-12 14:57:44 -0700832 }
833}
834
835func TestIsNil(t *testing.T) {
Russ Coxfb175cf2011-04-08 12:26:51 -0400836 // These implement IsNil.
Russ Cox64f4e0b2009-07-07 11:03:12 -0700837 // Wrap in extra struct to hide interface type.
838 doNil := []interface{}{
Robert Griesemera05a5462009-11-06 16:33:53 -0800839 struct{ x *int }{},
840 struct{ x interface{} }{},
841 struct{ x map[string]int }{},
842 struct{ x func() bool }{},
843 struct{ x chan int }{},
844 struct{ x []string }{},
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800845 }
Russ Coxca6a0fe2009-09-15 09:41:59 -0700846 for _, ts := range doNil {
Russ Cox0e2bb622011-04-25 13:39:16 -0400847 ty := TypeOf(ts).Field(0).Type
Russ Coxfb175cf2011-04-08 12:26:51 -0400848 v := Zero(ty)
849 v.IsNil() // panics if not okay to call
Rob Pikea8f6e382009-05-12 14:57:44 -0700850 }
Russ Cox64f4e0b2009-07-07 11:03:12 -0700851
Rob Pikea8f6e382009-05-12 14:57:44 -0700852 // Check the implementations
Robert Griesemer77334b982009-11-05 14:23:20 -0800853 var pi struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800854 x *int
Robert Griesemer77334b982009-11-05 14:23:20 -0800855 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800856 Nil(pi, t)
857 pi.x = new(int)
858 NotNil(pi, t)
Rob Pikea8f6e382009-05-12 14:57:44 -0700859
Robert Griesemer77334b982009-11-05 14:23:20 -0800860 var si struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800861 x []int
Robert Griesemer77334b982009-11-05 14:23:20 -0800862 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800863 Nil(si, t)
864 si.x = make([]int, 10)
865 NotNil(si, t)
Rob Pikea8f6e382009-05-12 14:57:44 -0700866
Robert Griesemer77334b982009-11-05 14:23:20 -0800867 var ci struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800868 x chan int
Robert Griesemer77334b982009-11-05 14:23:20 -0800869 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800870 Nil(ci, t)
871 ci.x = make(chan int)
872 NotNil(ci, t)
Rob Pikea8f6e382009-05-12 14:57:44 -0700873
Robert Griesemer77334b982009-11-05 14:23:20 -0800874 var mi struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800875 x map[int]int
Robert Griesemer77334b982009-11-05 14:23:20 -0800876 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800877 Nil(mi, t)
878 mi.x = make(map[int]int)
879 NotNil(mi, t)
Russ Cox64f4e0b2009-07-07 11:03:12 -0700880
Robert Griesemer77334b982009-11-05 14:23:20 -0800881 var ii struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800882 x interface{}
Robert Griesemer77334b982009-11-05 14:23:20 -0800883 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800884 Nil(ii, t)
885 ii.x = 2
886 NotNil(ii, t)
Rob Pikea8f6e382009-05-12 14:57:44 -0700887
Robert Griesemer77334b982009-11-05 14:23:20 -0800888 var fi struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800889 x func(t *testing.T)
Robert Griesemer77334b982009-11-05 14:23:20 -0800890 }
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800891 Nil(fi, t)
892 fi.x = TestIsNil
893 NotNil(fi, t)
Rob Pikea8f6e382009-05-12 14:57:44 -0700894}
Russ Cox96cfd152009-05-21 11:50:20 -0700895
896func TestInterfaceExtraction(t *testing.T) {
897 var s struct {
Russ Cox304cf4d2011-10-17 18:48:45 -0400898 W io.Writer
Russ Cox96cfd152009-05-21 11:50:20 -0700899 }
900
Russ Cox304cf4d2011-10-17 18:48:45 -0400901 s.W = os.Stdout
Russ Cox0e2bb622011-04-25 13:39:16 -0400902 v := Indirect(ValueOf(&s)).Field(0).Interface()
Russ Cox304cf4d2011-10-17 18:48:45 -0400903 if v != s.W.(interface{}) {
904 t.Error("Interface() on interface: ", v, s.W)
Russ Cox96cfd152009-05-21 11:50:20 -0700905 }
906}
Russ Coxf9666232009-05-21 14:06:43 -0700907
David Symondsd4e57ff2009-06-15 18:35:04 -0700908func TestNilPtrValueSub(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800909 var pi *int
Russ Cox0e2bb622011-04-25 13:39:16 -0400910 if pv := ValueOf(pi); pv.Elem().IsValid() {
911 t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
David Symondsd4e57ff2009-06-15 18:35:04 -0700912 }
913}
Russ Cox764b6ec2009-07-08 13:55:57 -0700914
Russ Cox5ddaf9a2009-07-08 15:00:54 -0700915func TestMap(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800916 m := map[string]int{"a": 1, "b": 2}
Russ Cox0e2bb622011-04-25 13:39:16 -0400917 mv := ValueOf(m)
Russ Cox764b6ec2009-07-08 13:55:57 -0700918 if n := mv.Len(); n != len(m) {
Robert Griesemer40621d52009-11-09 12:07:39 -0800919 t.Errorf("Len = %d, want %d", n, len(m))
Russ Cox764b6ec2009-07-08 13:55:57 -0700920 }
Russ Coxfb175cf2011-04-08 12:26:51 -0400921 keys := mv.MapKeys()
Russ Coxfb175cf2011-04-08 12:26:51 -0400922 newmap := MakeMap(mv.Type())
Russ Cox764b6ec2009-07-08 13:55:57 -0700923 for k, v := range m {
924 // Check that returned Keys match keys in range.
David Symonds9049abb2011-10-18 12:47:34 +1100925 // These aren't required to be in the same order.
926 seen := false
927 for _, kv := range keys {
928 if kv.String() == k {
929 seen = true
930 break
931 }
Russ Cox764b6ec2009-07-08 13:55:57 -0700932 }
David Symonds9049abb2011-10-18 12:47:34 +1100933 if !seen {
934 t.Errorf("Missing key %q", k)
935 }
Russ Cox764b6ec2009-07-08 13:55:57 -0700936
937 // Check that value lookup is correct.
Russ Cox0e2bb622011-04-25 13:39:16 -0400938 vv := mv.MapIndex(ValueOf(k))
Russ Coxfb175cf2011-04-08 12:26:51 -0400939 if vi := vv.Int(); vi != int64(v) {
Rob Pike1ce62452010-12-07 16:42:54 -0500940 t.Errorf("Key %q: have value %d, want %d", k, vi, v)
Russ Cox764b6ec2009-07-08 13:55:57 -0700941 }
942
943 // Copy into new map.
Russ Cox0e2bb622011-04-25 13:39:16 -0400944 newmap.SetMapIndex(ValueOf(k), ValueOf(v))
Russ Cox764b6ec2009-07-08 13:55:57 -0700945 }
Russ Cox0e2bb622011-04-25 13:39:16 -0400946 vv := mv.MapIndex(ValueOf("not-present"))
Russ Coxfb175cf2011-04-08 12:26:51 -0400947 if vv.IsValid() {
Robert Griesemer40621d52009-11-09 12:07:39 -0800948 t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
Russ Cox764b6ec2009-07-08 13:55:57 -0700949 }
950
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800951 newm := newmap.Interface().(map[string]int)
Russ Cox764b6ec2009-07-08 13:55:57 -0700952 if len(newm) != len(m) {
Kamil Kisiele07b5ba2013-09-23 13:19:08 -0400953 t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
Russ Cox764b6ec2009-07-08 13:55:57 -0700954 }
955
956 for k, v := range newm {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800957 mv, ok := m[k]
Russ Cox764b6ec2009-07-08 13:55:57 -0700958 if mv != v {
Robert Griesemer40621d52009-11-09 12:07:39 -0800959 t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
Russ Cox764b6ec2009-07-08 13:55:57 -0700960 }
961 }
Russ Cox5ddaf9a2009-07-08 15:00:54 -0700962
Russ Cox0e2bb622011-04-25 13:39:16 -0400963 newmap.SetMapIndex(ValueOf("a"), Value{})
Robert Griesemerd65a5cc2009-12-15 15:40:16 -0800964 v, ok := newm["a"]
Russ Cox764b6ec2009-07-08 13:55:57 -0700965 if ok {
Robert Griesemer40621d52009-11-09 12:07:39 -0800966 t.Errorf("newm[\"a\"] = %d after delete", v)
Russ Cox764b6ec2009-07-08 13:55:57 -0700967 }
Russ Cox7295b612010-04-20 17:02:08 -0700968
Russ Cox0e2bb622011-04-25 13:39:16 -0400969 mv = ValueOf(&m).Elem()
Russ Coxfb175cf2011-04-08 12:26:51 -0400970 mv.Set(Zero(mv.Type()))
Russ Cox7295b612010-04-20 17:02:08 -0700971 if m != nil {
972 t.Errorf("mv.Set(nil) failed")
973 }
Russ Cox764b6ec2009-07-08 13:55:57 -0700974}
Russ Cox5ddaf9a2009-07-08 15:00:54 -0700975
Russ Coxd54b67d2014-05-19 09:36:47 -0400976func TestNilMap(t *testing.T) {
977 var m map[string]int
978 mv := ValueOf(m)
979 keys := mv.MapKeys()
980 if len(keys) != 0 {
981 t.Errorf(">0 keys for nil map: %v", keys)
982 }
983
984 // Check that value for missing key is zero.
985 x := mv.MapIndex(ValueOf("hello"))
986 if x.Kind() != Invalid {
987 t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
988 }
989
990 // Check big value too.
991 var mbig map[string][10 << 20]byte
992 x = ValueOf(mbig).MapIndex(ValueOf("hello"))
993 if x.Kind() != Invalid {
994 t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
995 }
Keith Randallcb6cb422014-05-20 16:26:04 -0700996
997 // Test that deletes from a nil map succeed.
998 mv.SetMapIndex(ValueOf("hi"), Value{})
Russ Coxd54b67d2014-05-19 09:36:47 -0400999}
1000
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001001func TestChan(t *testing.T) {
1002 for loop := 0; loop < 2; loop++ {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001003 var c chan int
Russ Coxfb175cf2011-04-08 12:26:51 -04001004 var cv Value
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001005
1006 // check both ways to allocate channels
1007 switch loop {
1008 case 1:
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001009 c = make(chan int, 1)
Russ Cox0e2bb622011-04-25 13:39:16 -04001010 cv = ValueOf(c)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001011 case 0:
Russ Cox0e2bb622011-04-25 13:39:16 -04001012 cv = MakeChan(TypeOf(c), 1)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001013 c = cv.Interface().(chan int)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001014 }
1015
1016 // Send
Russ Cox0e2bb622011-04-25 13:39:16 -04001017 cv.Send(ValueOf(2))
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001018 if i := <-c; i != 2 {
Robert Griesemer40621d52009-11-09 12:07:39 -08001019 t.Errorf("reflect Send 2, native recv %d", i)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001020 }
1021
1022 // Recv
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001023 c <- 3
Russ Coxfb175cf2011-04-08 12:26:51 -04001024 if i, ok := cv.Recv(); i.Int() != 3 || !ok {
1025 t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001026 }
1027
1028 // TryRecv fail
Russ Cox3f915f52011-03-11 14:47:44 -05001029 val, ok := cv.TryRecv()
Russ Coxfb175cf2011-04-08 12:26:51 -04001030 if val.IsValid() || ok {
Russ Cox3f915f52011-03-11 14:47:44 -05001031 t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001032 }
1033
1034 // TryRecv success
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001035 c <- 4
Russ Cox3f915f52011-03-11 14:47:44 -05001036 val, ok = cv.TryRecv()
Russ Coxfb175cf2011-04-08 12:26:51 -04001037 if !val.IsValid() {
Robert Griesemer40621d52009-11-09 12:07:39 -08001038 t.Errorf("TryRecv on ready chan got nil")
Russ Coxfb175cf2011-04-08 12:26:51 -04001039 } else if i := val.Int(); i != 4 || !ok {
Russ Cox3f915f52011-03-11 14:47:44 -05001040 t.Errorf("native send 4, TryRecv %d, %t", i, ok)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001041 }
1042
1043 // TrySend fail
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001044 c <- 100
Russ Cox0e2bb622011-04-25 13:39:16 -04001045 ok = cv.TrySend(ValueOf(5))
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001046 i := <-c
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001047 if ok {
Robert Griesemer40621d52009-11-09 12:07:39 -08001048 t.Errorf("TrySend on full chan succeeded: value %d", i)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001049 }
1050
1051 // TrySend success
Russ Cox0e2bb622011-04-25 13:39:16 -04001052 ok = cv.TrySend(ValueOf(6))
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001053 if !ok {
Robert Griesemer40621d52009-11-09 12:07:39 -08001054 t.Errorf("TrySend on empty chan failed")
Russ Cox0bee7f32014-08-14 14:35:00 -04001055 select {
1056 case x := <-c:
1057 t.Errorf("TrySend failed but it did send %d", x)
1058 default:
1059 }
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001060 } else {
1061 if i = <-c; i != 6 {
Robert Griesemer40621d52009-11-09 12:07:39 -08001062 t.Errorf("TrySend 6, recv %d", i)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001063 }
1064 }
Russ Cox653cef12009-08-26 10:47:18 -07001065
1066 // Close
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001067 c <- 123
1068 cv.Close()
Russ Coxfb175cf2011-04-08 12:26:51 -04001069 if i, ok := cv.Recv(); i.Int() != 123 || !ok {
1070 t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
Russ Cox653cef12009-08-26 10:47:18 -07001071 }
Russ Coxfb175cf2011-04-08 12:26:51 -04001072 if i, ok := cv.Recv(); i.Int() != 0 || ok {
1073 t.Errorf("after close Recv %d, %t", i.Int(), ok)
Russ Cox653cef12009-08-26 10:47:18 -07001074 }
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001075 }
1076
1077 // check creation of unbuffered channel
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001078 var c chan int
Russ Cox0e2bb622011-04-25 13:39:16 -04001079 cv := MakeChan(TypeOf(c), 0)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001080 c = cv.Interface().(chan int)
Russ Cox0e2bb622011-04-25 13:39:16 -04001081 if cv.TrySend(ValueOf(7)) {
Robert Griesemer40621d52009-11-09 12:07:39 -08001082 t.Errorf("TrySend on sync chan succeeded")
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001083 }
Russ Coxfb175cf2011-04-08 12:26:51 -04001084 if v, ok := cv.TryRecv(); v.IsValid() || ok {
Russ Cox40fccbc2011-04-18 14:35:33 -04001085 t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001086 }
Russ Coxde7920e2009-08-26 12:42:22 -07001087
1088 // len/cap
Russ Cox0e2bb622011-04-25 13:39:16 -04001089 cv = MakeChan(TypeOf(c), 10)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001090 c = cv.Interface().(chan int)
Russ Coxde7920e2009-08-26 12:42:22 -07001091 for i := 0; i < 3; i++ {
Robert Griesemer40621d52009-11-09 12:07:39 -08001092 c <- i
Russ Coxde7920e2009-08-26 12:42:22 -07001093 }
1094 if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
Robert Griesemer40621d52009-11-09 12:07:39 -08001095 t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
Russ Coxde7920e2009-08-26 12:42:22 -07001096 }
Russ Cox5ddaf9a2009-07-08 15:00:54 -07001097}
1098
Russ Cox370ae052012-09-18 14:22:41 -04001099// caseInfo describes a single case in a select test.
1100type caseInfo struct {
1101 desc string
1102 canSelect bool
1103 recv Value
1104 closed bool
1105 helper func()
1106 panic bool
1107}
1108
Russ Cox46f379c2012-09-22 08:52:27 -04001109var allselect = flag.Bool("allselect", false, "exhaustive select test")
1110
Russ Cox370ae052012-09-18 14:22:41 -04001111func TestSelect(t *testing.T) {
1112 selectWatch.once.Do(func() { go selectWatcher() })
1113
1114 var x exhaustive
1115 nch := 0
1116 newop := func(n int, cap int) (ch, val Value) {
1117 nch++
1118 if nch%101%2 == 1 {
1119 c := make(chan int, cap)
1120 ch = ValueOf(c)
1121 val = ValueOf(n)
1122 } else {
1123 c := make(chan string, cap)
1124 ch = ValueOf(c)
1125 val = ValueOf(fmt.Sprint(n))
1126 }
1127 return
1128 }
1129
1130 for n := 0; x.Next(); n++ {
1131 if testing.Short() && n >= 1000 {
1132 break
1133 }
Russ Cox46f379c2012-09-22 08:52:27 -04001134 if n >= 100000 && !*allselect {
1135 break
1136 }
Russ Cox370ae052012-09-18 14:22:41 -04001137 if n%100000 == 0 && testing.Verbose() {
1138 println("TestSelect", n)
1139 }
1140 var cases []SelectCase
1141 var info []caseInfo
1142
1143 // Ready send.
1144 if x.Maybe() {
1145 ch, val := newop(len(cases), 1)
1146 cases = append(cases, SelectCase{
1147 Dir: SelectSend,
1148 Chan: ch,
1149 Send: val,
1150 })
1151 info = append(info, caseInfo{desc: "ready send", canSelect: true})
1152 }
1153
1154 // Ready recv.
1155 if x.Maybe() {
1156 ch, val := newop(len(cases), 1)
1157 ch.Send(val)
1158 cases = append(cases, SelectCase{
1159 Dir: SelectRecv,
1160 Chan: ch,
1161 })
1162 info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
1163 }
1164
1165 // Blocking send.
1166 if x.Maybe() {
1167 ch, val := newop(len(cases), 0)
1168 cases = append(cases, SelectCase{
1169 Dir: SelectSend,
1170 Chan: ch,
1171 Send: val,
1172 })
1173 // Let it execute?
1174 if x.Maybe() {
1175 f := func() { ch.Recv() }
1176 info = append(info, caseInfo{desc: "blocking send", helper: f})
1177 } else {
1178 info = append(info, caseInfo{desc: "blocking send"})
1179 }
1180 }
1181
1182 // Blocking recv.
1183 if x.Maybe() {
1184 ch, val := newop(len(cases), 0)
1185 cases = append(cases, SelectCase{
1186 Dir: SelectRecv,
1187 Chan: ch,
1188 })
1189 // Let it execute?
1190 if x.Maybe() {
1191 f := func() { ch.Send(val) }
1192 info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
1193 } else {
1194 info = append(info, caseInfo{desc: "blocking recv"})
1195 }
1196 }
1197
1198 // Zero Chan send.
1199 if x.Maybe() {
1200 // Maybe include value to send.
1201 var val Value
1202 if x.Maybe() {
1203 val = ValueOf(100)
1204 }
1205 cases = append(cases, SelectCase{
1206 Dir: SelectSend,
1207 Send: val,
1208 })
1209 info = append(info, caseInfo{desc: "zero Chan send"})
1210 }
1211
1212 // Zero Chan receive.
1213 if x.Maybe() {
1214 cases = append(cases, SelectCase{
1215 Dir: SelectRecv,
1216 })
1217 info = append(info, caseInfo{desc: "zero Chan recv"})
1218 }
1219
1220 // nil Chan send.
1221 if x.Maybe() {
1222 cases = append(cases, SelectCase{
1223 Dir: SelectSend,
1224 Chan: ValueOf((chan int)(nil)),
1225 Send: ValueOf(101),
1226 })
1227 info = append(info, caseInfo{desc: "nil Chan send"})
1228 }
1229
1230 // nil Chan recv.
1231 if x.Maybe() {
1232 cases = append(cases, SelectCase{
1233 Dir: SelectRecv,
1234 Chan: ValueOf((chan int)(nil)),
1235 })
1236 info = append(info, caseInfo{desc: "nil Chan recv"})
1237 }
1238
1239 // closed Chan send.
1240 if x.Maybe() {
1241 ch := make(chan int)
1242 close(ch)
1243 cases = append(cases, SelectCase{
1244 Dir: SelectSend,
1245 Chan: ValueOf(ch),
1246 Send: ValueOf(101),
1247 })
1248 info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
1249 }
1250
1251 // closed Chan recv.
1252 if x.Maybe() {
1253 ch, val := newop(len(cases), 0)
1254 ch.Close()
1255 val = Zero(val.Type())
1256 cases = append(cases, SelectCase{
1257 Dir: SelectRecv,
1258 Chan: ch,
1259 })
1260 info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
1261 }
1262
1263 var helper func() // goroutine to help the select complete
1264
1265 // Add default? Must be last case here, but will permute.
1266 // Add the default if the select would otherwise
1267 // block forever, and maybe add it anyway.
1268 numCanSelect := 0
1269 canProceed := false
1270 canBlock := true
1271 canPanic := false
1272 helpers := []int{}
1273 for i, c := range info {
1274 if c.canSelect {
1275 canProceed = true
1276 canBlock = false
1277 numCanSelect++
1278 if c.panic {
1279 canPanic = true
1280 }
1281 } else if c.helper != nil {
1282 canProceed = true
1283 helpers = append(helpers, i)
1284 }
1285 }
1286 if !canProceed || x.Maybe() {
1287 cases = append(cases, SelectCase{
1288 Dir: SelectDefault,
1289 })
1290 info = append(info, caseInfo{desc: "default", canSelect: canBlock})
1291 numCanSelect++
1292 } else if canBlock {
1293 // Select needs to communicate with another goroutine.
1294 cas := &info[helpers[x.Choose(len(helpers))]]
1295 helper = cas.helper
1296 cas.canSelect = true
1297 numCanSelect++
1298 }
1299
1300 // Permute cases and case info.
1301 // Doing too much here makes the exhaustive loop
1302 // too exhausting, so just do two swaps.
1303 for loop := 0; loop < 2; loop++ {
1304 i := x.Choose(len(cases))
1305 j := x.Choose(len(cases))
1306 cases[i], cases[j] = cases[j], cases[i]
1307 info[i], info[j] = info[j], info[i]
1308 }
1309
1310 if helper != nil {
1311 // We wait before kicking off a goroutine to satisfy a blocked select.
1312 // The pause needs to be big enough to let the select block before
1313 // we run the helper, but if we lose that race once in a while it's okay: the
1314 // select will just proceed immediately. Not a big deal.
1315 // For short tests we can grow [sic] the timeout a bit without fear of taking too long
1316 pause := 10 * time.Microsecond
1317 if testing.Short() {
1318 pause = 100 * time.Microsecond
1319 }
1320 time.AfterFunc(pause, helper)
1321 }
1322
1323 // Run select.
1324 i, recv, recvOK, panicErr := runSelect(cases, info)
1325 if panicErr != nil && !canPanic {
1326 t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
1327 }
1328 if panicErr == nil && canPanic && numCanSelect == 1 {
1329 t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
1330 }
1331 if panicErr != nil {
1332 continue
1333 }
1334
1335 cas := info[i]
1336 if !cas.canSelect {
1337 recvStr := ""
1338 if recv.IsValid() {
1339 recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
1340 }
1341 t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
1342 continue
1343 }
1344 if cas.panic {
1345 t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
1346 continue
1347 }
1348
1349 if cases[i].Dir == SelectRecv {
1350 if !recv.IsValid() {
1351 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
1352 }
1353 if !cas.recv.IsValid() {
1354 t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
1355 }
1356 if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
1357 if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
1358 t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
1359 }
1360 t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
1361 }
1362 } else {
1363 if recv.IsValid() || recvOK {
1364 t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
1365 }
1366 }
1367 }
1368}
1369
1370// selectWatch and the selectWatcher are a watchdog mechanism for running Select.
1371// If the selectWatcher notices that the select has been blocked for >1 second, it prints
Robert Griesemer465b9c32012-10-30 13:38:01 -07001372// an error describing the select and panics the entire test binary.
Russ Cox370ae052012-09-18 14:22:41 -04001373var selectWatch struct {
1374 sync.Mutex
1375 once sync.Once
1376 now time.Time
1377 info []caseInfo
1378}
1379
1380func selectWatcher() {
1381 for {
1382 time.Sleep(1 * time.Second)
1383 selectWatch.Lock()
1384 if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
1385 fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
1386 panic("select stuck")
1387 }
1388 selectWatch.Unlock()
1389 }
1390}
1391
1392// runSelect runs a single select test.
1393// It returns the values returned by Select but also returns
1394// a panic value if the Select panics.
1395func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
1396 defer func() {
1397 panicErr = recover()
1398
1399 selectWatch.Lock()
1400 selectWatch.info = nil
1401 selectWatch.Unlock()
1402 }()
1403
1404 selectWatch.Lock()
1405 selectWatch.now = time.Now()
1406 selectWatch.info = info
1407 selectWatch.Unlock()
1408
1409 chosen, recv, recvOK = Select(cases)
1410 return
1411}
1412
1413// fmtSelect formats the information about a single select test.
1414func fmtSelect(info []caseInfo) string {
1415 var buf bytes.Buffer
1416 fmt.Fprintf(&buf, "\nselect {\n")
1417 for i, cas := range info {
1418 fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
1419 if cas.recv.IsValid() {
1420 fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
1421 }
1422 if cas.canSelect {
1423 fmt.Fprintf(&buf, " canselect")
1424 }
1425 if cas.panic {
1426 fmt.Fprintf(&buf, " panic")
1427 }
1428 fmt.Fprintf(&buf, "\n")
1429 }
1430 fmt.Fprintf(&buf, "}")
1431 return buf.String()
1432}
1433
Russ Coxba4625c2012-09-24 20:06:32 -04001434type two [2]uintptr
1435
Russ Coxbba278a2009-07-08 18:16:09 -07001436// Difficult test for function call because of
1437// implicit padding between arguments.
Russ Coxba4625c2012-09-24 20:06:32 -04001438func dummy(b byte, c int, d byte, e two, f byte, g float32, h byte) (i byte, j int, k byte, l two, m byte, n float32, o byte) {
1439 return b, c, d, e, f, g, h
Russ Coxbba278a2009-07-08 18:16:09 -07001440}
1441
1442func TestFunc(t *testing.T) {
Russ Coxba4625c2012-09-24 20:06:32 -04001443 ret := ValueOf(dummy).Call([]Value{
1444 ValueOf(byte(10)),
1445 ValueOf(20),
1446 ValueOf(byte(30)),
1447 ValueOf(two{40, 50}),
1448 ValueOf(byte(60)),
1449 ValueOf(float32(70)),
1450 ValueOf(byte(80)),
1451 })
1452 if len(ret) != 7 {
1453 t.Fatalf("Call returned %d values, want 7", len(ret))
Russ Coxbba278a2009-07-08 18:16:09 -07001454 }
1455
Russ Coxfb175cf2011-04-08 12:26:51 -04001456 i := byte(ret[0].Uint())
1457 j := int(ret[1].Int())
1458 k := byte(ret[2].Uint())
Russ Coxba4625c2012-09-24 20:06:32 -04001459 l := ret[3].Interface().(two)
1460 m := byte(ret[4].Uint())
1461 n := float32(ret[5].Float())
1462 o := byte(ret[6].Uint())
1463
1464 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1465 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
1466 }
1467}
1468
Michael Hudson-Doyle0a6ad462013-12-17 14:49:51 -08001469type emptyStruct struct{}
1470
1471type nonEmptyStruct struct {
1472 member int
1473}
1474
1475func returnEmpty() emptyStruct {
1476 return emptyStruct{}
1477}
1478
1479func takesEmpty(e emptyStruct) {
1480}
1481
1482func returnNonEmpty(i int) nonEmptyStruct {
1483 return nonEmptyStruct{member: i}
1484}
1485
1486func takesNonEmpty(n nonEmptyStruct) int {
1487 return n.member
1488}
1489
1490func TestCallWithStruct(t *testing.T) {
1491 r := ValueOf(returnEmpty).Call(nil)
1492 if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
1493 t.Errorf("returning empty struct returned %#v instead", r)
1494 }
1495 r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
1496 if len(r) != 0 {
1497 t.Errorf("takesEmpty returned values: %#v", r)
1498 }
1499 r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
1500 if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
1501 t.Errorf("returnNonEmpty returned %#v", r)
1502 }
1503 r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
1504 if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
1505 t.Errorf("takesNonEmpty returned %#v", r)
1506 }
1507}
1508
Dmitry Vyukov67f8a812014-12-22 22:31:55 +03001509func BenchmarkCall(b *testing.B) {
1510 fv := ValueOf(func(a, b string) {})
1511 b.ReportAllocs()
1512 b.RunParallel(func(pb *testing.PB) {
1513 args := []Value{ValueOf("a"), ValueOf("b")}
1514 for pb.Next() {
1515 fv.Call(args)
1516 }
1517 })
1518}
1519
Russ Coxba4625c2012-09-24 20:06:32 -04001520func TestMakeFunc(t *testing.T) {
1521 f := dummy
1522 fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
1523 ValueOf(&f).Elem().Set(fv)
1524
1525 // Call g with small arguments so that there is
1526 // something predictable (and different from the
1527 // correct results) in those positions on the stack.
1528 g := dummy
1529 g(1, 2, 3, two{4, 5}, 6, 7, 8)
1530
1531 // Call constructed function f.
1532 i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
1533 if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
1534 t.Errorf("Call returned %d, %d, %d, %v, %d, %g, %d; want 10, 20, 30, [40, 50], 60, 70, 80", i, j, k, l, m, n, o)
Russ Coxbba278a2009-07-08 18:16:09 -07001535 }
1536}
Russ Cox12ebbe72009-07-09 17:27:49 -07001537
Ian Lance Tayloref4e12a2013-10-04 13:12:50 -07001538func TestMakeFuncInterface(t *testing.T) {
1539 fn := func(i int) int { return i }
1540 incr := func(in []Value) []Value {
1541 return []Value{ValueOf(int(in[0].Int() + 1))}
1542 }
1543 fv := MakeFunc(TypeOf(fn), incr)
1544 ValueOf(&fn).Elem().Set(fv)
1545 if r := fn(2); r != 3 {
1546 t.Errorf("Call returned %d, want 3", r)
1547 }
1548 if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
1549 t.Errorf("Call returned %d, want 15", r)
1550 }
1551 if r := fv.Interface().(func(int) int)(26); r != 27 {
1552 t.Errorf("Call returned %d, want 27", r)
1553 }
1554}
1555
Carl Chatfield772d2282014-04-08 22:35:23 -04001556func TestMakeFuncVariadic(t *testing.T) {
1557 // Test that variadic arguments are packed into a slice and passed as last arg
1558 fn := func(_ int, is ...int) []int { return nil }
1559 fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
1560 ValueOf(&fn).Elem().Set(fv)
1561
Michael Hudson-Doyle14cd40d2014-10-08 15:58:56 -07001562 r := fn(1, 2, 3)
1563 if r[0] != 2 || r[1] != 3 {
1564 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1565 }
1566
1567 r = fn(1, []int{2, 3}...)
1568 if r[0] != 2 || r[1] != 3 {
1569 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1570 }
1571
1572 r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
Carl Chatfield772d2282014-04-08 22:35:23 -04001573 if r[0] != 2 || r[1] != 3 {
1574 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1575 }
1576
1577 r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
1578 if r[0] != 2 || r[1] != 3 {
1579 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1580 }
Michael Hudson-Doyle14cd40d2014-10-08 15:58:56 -07001581
1582 f := fv.Interface().(func(int, ...int) []int)
1583
1584 r = f(1, 2, 3)
1585 if r[0] != 2 || r[1] != 3 {
1586 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1587 }
1588 r = f(1, []int{2, 3}...)
1589 if r[0] != 2 || r[1] != 3 {
1590 t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
1591 }
Carl Chatfield772d2282014-04-08 22:35:23 -04001592}
1593
Russ Cox12ebbe72009-07-09 17:27:49 -07001594type Point struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001595 x, y int
Russ Cox12ebbe72009-07-09 17:27:49 -07001596}
1597
Rob Pike22484e22011-06-29 13:11:49 +10001598// This will be index 0.
1599func (p Point) AnotherMethod(scale int) int {
1600 return -1
1601}
1602
1603// This will be index 1.
Russ Cox40fccbc2011-04-18 14:35:33 -04001604func (p Point) Dist(scale int) int {
Russ Cox3be70362013-03-21 16:59:16 -04001605 //println("Point.Dist", p.x, p.y, scale)
Russ Cox40fccbc2011-04-18 14:35:33 -04001606 return p.x*p.x*scale + p.y*p.y*scale
1607}
Russ Cox12ebbe72009-07-09 17:27:49 -07001608
Ian Lance Taylor6920b2a2014-10-08 15:48:46 -07001609// This will be index 2.
1610func (p Point) GCMethod(k int) int {
1611 runtime.GC()
1612 return k + p.x
1613}
1614
1615// This will be index 3.
1616func (p Point) TotalDist(points ...Point) int {
1617 tot := 0
1618 for _, q := range points {
1619 dx := q.x - p.x
1620 dy := q.y - p.y
1621 tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
1622
1623 }
1624 return tot
1625}
1626
Russ Cox12ebbe72009-07-09 17:27:49 -07001627func TestMethod(t *testing.T) {
1628 // Non-curried method of type.
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001629 p := Point{3, 4}
Rob Pike22484e22011-06-29 13:11:49 +10001630 i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
Russ Cox12ebbe72009-07-09 17:27:49 -07001631 if i != 250 {
Robert Griesemer40621d52009-11-09 12:07:39 -08001632 t.Errorf("Type Method returned %d; want 250", i)
Russ Cox12ebbe72009-07-09 17:27:49 -07001633 }
1634
Rob Pike22484e22011-06-29 13:11:49 +10001635 m, ok := TypeOf(p).MethodByName("Dist")
1636 if !ok {
1637 t.Fatalf("method by name failed")
1638 }
Russ Cox3be70362013-03-21 16:59:16 -04001639 i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
1640 if i != 275 {
1641 t.Errorf("Type MethodByName returned %d; want 275", i)
Rob Pike22484e22011-06-29 13:11:49 +10001642 }
1643
Russ Cox3be70362013-03-21 16:59:16 -04001644 i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
1645 if i != 300 {
1646 t.Errorf("Pointer Type Method returned %d; want 300", i)
Russ Cox00ffd592010-09-28 13:43:50 -04001647 }
1648
Rob Pike22484e22011-06-29 13:11:49 +10001649 m, ok = TypeOf(&p).MethodByName("Dist")
1650 if !ok {
1651 t.Fatalf("ptr method by name failed")
1652 }
Russ Cox3be70362013-03-21 16:59:16 -04001653 i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
1654 if i != 325 {
1655 t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
Rob Pike22484e22011-06-29 13:11:49 +10001656 }
1657
Russ Cox12ebbe72009-07-09 17:27:49 -07001658 // Curried method of value.
Robert Griesemer1065c6f2012-10-04 21:03:50 -07001659 tfunc := TypeOf((func(int) int)(nil))
Russ Coxa479a452011-11-16 19:18:25 -05001660 v := ValueOf(p).Method(1)
1661 if tt := v.Type(); tt != tfunc {
1662 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1663 }
Russ Cox3be70362013-03-21 16:59:16 -04001664 i = v.Call([]Value{ValueOf(14)})[0].Int()
1665 if i != 350 {
1666 t.Errorf("Value Method returned %d; want 350", i)
Russ Cox12ebbe72009-07-09 17:27:49 -07001667 }
Russ Coxa479a452011-11-16 19:18:25 -05001668 v = ValueOf(p).MethodByName("Dist")
1669 if tt := v.Type(); tt != tfunc {
1670 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1671 }
Russ Cox3be70362013-03-21 16:59:16 -04001672 i = v.Call([]Value{ValueOf(15)})[0].Int()
1673 if i != 375 {
1674 t.Errorf("Value MethodByName returned %d; want 375", i)
Rob Pike22484e22011-06-29 13:11:49 +10001675 }
Russ Cox12ebbe72009-07-09 17:27:49 -07001676
Russ Coxe46acb02011-03-03 13:20:17 -05001677 // Curried method of pointer.
Russ Coxa479a452011-11-16 19:18:25 -05001678 v = ValueOf(&p).Method(1)
1679 if tt := v.Type(); tt != tfunc {
1680 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1681 }
Russ Cox3be70362013-03-21 16:59:16 -04001682 i = v.Call([]Value{ValueOf(16)})[0].Int()
1683 if i != 400 {
1684 t.Errorf("Pointer Value Method returned %d; want 400", i)
Rob Pike22484e22011-06-29 13:11:49 +10001685 }
Russ Coxa479a452011-11-16 19:18:25 -05001686 v = ValueOf(&p).MethodByName("Dist")
1687 if tt := v.Type(); tt != tfunc {
1688 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1689 }
Russ Cox3be70362013-03-21 16:59:16 -04001690 i = v.Call([]Value{ValueOf(17)})[0].Int()
1691 if i != 425 {
1692 t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
1693 }
1694
1695 // Curried method of interface value.
1696 // Have to wrap interface value in a struct to get at it.
1697 // Passing it to ValueOf directly would
1698 // access the underlying Point, not the interface.
1699 var x interface {
1700 Dist(int) int
1701 } = p
1702 pv := ValueOf(&x).Elem()
1703 v = pv.Method(0)
1704 if tt := v.Type(); tt != tfunc {
1705 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1706 }
1707 i = v.Call([]Value{ValueOf(18)})[0].Int()
1708 if i != 450 {
1709 t.Errorf("Interface Method returned %d; want 450", i)
1710 }
1711 v = pv.MethodByName("Dist")
1712 if tt := v.Type(); tt != tfunc {
1713 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1714 }
1715 i = v.Call([]Value{ValueOf(19)})[0].Int()
1716 if i != 475 {
1717 t.Errorf("Interface MethodByName returned %d; want 475", i)
1718 }
1719}
1720
1721func TestMethodValue(t *testing.T) {
1722 p := Point{3, 4}
1723 var i int64
1724
1725 // Curried method of value.
1726 tfunc := TypeOf((func(int) int)(nil))
1727 v := ValueOf(p).Method(1)
1728 if tt := v.Type(); tt != tfunc {
1729 t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
1730 }
1731 i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
Rob Pike22484e22011-06-29 13:11:49 +10001732 if i != 250 {
Russ Cox3be70362013-03-21 16:59:16 -04001733 t.Errorf("Value Method returned %d; want 250", i)
1734 }
1735 v = ValueOf(p).MethodByName("Dist")
1736 if tt := v.Type(); tt != tfunc {
1737 t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
1738 }
1739 i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
1740 if i != 275 {
1741 t.Errorf("Value MethodByName returned %d; want 275", i)
1742 }
1743
1744 // Curried method of pointer.
1745 v = ValueOf(&p).Method(1)
1746 if tt := v.Type(); tt != tfunc {
1747 t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
1748 }
1749 i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
1750 if i != 300 {
1751 t.Errorf("Pointer Value Method returned %d; want 300", i)
1752 }
1753 v = ValueOf(&p).MethodByName("Dist")
1754 if tt := v.Type(); tt != tfunc {
1755 t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1756 }
1757 i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
1758 if i != 325 {
1759 t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
Russ Coxe46acb02011-03-03 13:20:17 -05001760 }
1761
Ian Lance Taylorc7570202013-09-17 15:22:42 -07001762 // Curried method of pointer to pointer.
1763 pp := &p
1764 v = ValueOf(&pp).Elem().Method(1)
1765 if tt := v.Type(); tt != tfunc {
1766 t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
1767 }
1768 i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
1769 if i != 350 {
1770 t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
1771 }
1772 v = ValueOf(&pp).Elem().MethodByName("Dist")
1773 if tt := v.Type(); tt != tfunc {
1774 t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
1775 }
1776 i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
1777 if i != 375 {
1778 t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
1779 }
1780
Russ Cox12ebbe72009-07-09 17:27:49 -07001781 // Curried method of interface value.
1782 // Have to wrap interface value in a struct to get at it.
Russ Cox0e2bb622011-04-25 13:39:16 -04001783 // Passing it to ValueOf directly would
Russ Cox12ebbe72009-07-09 17:27:49 -07001784 // access the underlying Point, not the interface.
Robert Griesemer77334b982009-11-05 14:23:20 -08001785 var s = struct {
Russ Cox40fccbc2011-04-18 14:35:33 -04001786 X interface {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08001787 Dist(int) int
1788 }
1789 }{p}
Russ Cox0e2bb622011-04-25 13:39:16 -04001790 pv := ValueOf(s).Field(0)
Russ Coxa479a452011-11-16 19:18:25 -05001791 v = pv.Method(0)
1792 if tt := v.Type(); tt != tfunc {
1793 t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
1794 }
Ian Lance Taylorc7570202013-09-17 15:22:42 -07001795 i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
1796 if i != 400 {
1797 t.Errorf("Interface Method returned %d; want 400", i)
Russ Cox12ebbe72009-07-09 17:27:49 -07001798 }
Russ Coxa479a452011-11-16 19:18:25 -05001799 v = pv.MethodByName("Dist")
1800 if tt := v.Type(); tt != tfunc {
1801 t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
1802 }
Ian Lance Taylorc7570202013-09-17 15:22:42 -07001803 i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
1804 if i != 425 {
1805 t.Errorf("Interface MethodByName returned %d; want 425", i)
Rob Pike22484e22011-06-29 13:11:49 +10001806 }
Russ Cox12ebbe72009-07-09 17:27:49 -07001807}
Russ Cox92e92572009-07-10 16:32:26 -07001808
Ian Lance Taylor6920b2a2014-10-08 15:48:46 -07001809func TestVariadicMethodValue(t *testing.T) {
1810 p := Point{3, 4}
1811 points := []Point{{20, 21}, {22, 23}, {24, 25}}
1812 want := int64(p.TotalDist(points[0], points[1], points[2]))
1813
1814 // Curried method of value.
1815 tfunc := TypeOf((func(...Point) int)(nil))
1816 v := ValueOf(p).Method(3)
1817 if tt := v.Type(); tt != tfunc {
1818 t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
1819 }
1820 i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
1821 if i != want {
1822 t.Errorf("Variadic Method returned %d; want %d", i, want)
1823 }
1824 i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
1825 if i != want {
1826 t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
1827 }
1828
1829 f := v.Interface().(func(...Point) int)
1830 i = int64(f(points[0], points[1], points[2]))
1831 if i != want {
1832 t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
1833 }
1834 i = int64(f(points...))
1835 if i != want {
1836 t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
1837 }
1838}
1839
Russ Cox3be70362013-03-21 16:59:16 -04001840// Reflect version of $GOROOT/test/method5.go
1841
1842// Concrete types implementing M method.
1843// Smaller than a word, word-sized, larger than a word.
1844// Value and pointer receivers.
1845
1846type Tinter interface {
1847 M(int, byte) (byte, int)
1848}
1849
1850type Tsmallv byte
1851
1852func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1853
1854type Tsmallp byte
1855
1856func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1857
1858type Twordv uintptr
1859
1860func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
1861
1862type Twordp uintptr
1863
1864func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
1865
1866type Tbigv [2]uintptr
1867
1868func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1869
1870type Tbigp [2]uintptr
1871
1872func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1873
1874// Again, with an unexported method.
1875
1876type tsmallv byte
1877
1878func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1879
1880type tsmallp byte
1881
1882func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1883
1884type twordv uintptr
1885
1886func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
1887
1888type twordp uintptr
1889
1890func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
1891
1892type tbigv [2]uintptr
1893
1894func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
1895
1896type tbigp [2]uintptr
1897
1898func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
1899
1900type tinter interface {
1901 m(int, byte) (byte, int)
1902}
1903
1904// Embedding via pointer.
1905
1906type Tm1 struct {
1907 Tm2
1908}
1909
1910type Tm2 struct {
1911 *Tm3
1912}
1913
1914type Tm3 struct {
1915 *Tm4
1916}
1917
1918type Tm4 struct {
1919}
1920
1921func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
1922
1923func TestMethod5(t *testing.T) {
1924 CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
1925 b, x := f(1000, 99)
1926 if b != 99 || x != 1000+inc {
1927 t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1928 }
1929 }
1930
1931 CheckV := func(name string, i Value, inc int) {
1932 bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
1933 b := bx[0].Interface()
1934 x := bx[1].Interface()
1935 if b != byte(99) || x != 1000+inc {
1936 t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
1937 }
1938
1939 CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
1940 }
1941
1942 var TinterType = TypeOf(new(Tinter)).Elem()
1943 var tinterType = TypeOf(new(tinter)).Elem()
1944
1945 CheckI := func(name string, i interface{}, inc int) {
1946 v := ValueOf(i)
1947 CheckV(name, v, inc)
1948 CheckV("(i="+name+")", v.Convert(TinterType), inc)
1949 }
1950
1951 sv := Tsmallv(1)
1952 CheckI("sv", sv, 1)
1953 CheckI("&sv", &sv, 1)
1954
1955 sp := Tsmallp(2)
1956 CheckI("&sp", &sp, 2)
1957
1958 wv := Twordv(3)
1959 CheckI("wv", wv, 3)
1960 CheckI("&wv", &wv, 3)
1961
1962 wp := Twordp(4)
1963 CheckI("&wp", &wp, 4)
1964
1965 bv := Tbigv([2]uintptr{5, 6})
1966 CheckI("bv", bv, 11)
1967 CheckI("&bv", &bv, 11)
1968
1969 bp := Tbigp([2]uintptr{7, 8})
1970 CheckI("&bp", &bp, 15)
1971
1972 t4 := Tm4{}
1973 t3 := Tm3{&t4}
1974 t2 := Tm2{&t3}
1975 t1 := Tm1{t2}
1976 CheckI("t4", t4, 40)
1977 CheckI("&t4", &t4, 40)
1978 CheckI("t3", t3, 40)
1979 CheckI("&t3", &t3, 40)
1980 CheckI("t2", t2, 40)
1981 CheckI("&t2", &t2, 40)
1982 CheckI("t1", t1, 40)
1983 CheckI("&t1", &t1, 40)
1984
1985 methodShouldPanic := func(name string, i interface{}) {
1986 v := ValueOf(i)
1987 m := v.Method(0)
1988 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1989 shouldPanic(func() { m.Interface() })
1990
1991 v = v.Convert(tinterType)
1992 m = v.Method(0)
1993 shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
1994 shouldPanic(func() { m.Interface() })
1995 }
1996
1997 _sv := tsmallv(1)
1998 methodShouldPanic("_sv", _sv)
1999 methodShouldPanic("&_sv", &_sv)
2000
2001 _sp := tsmallp(2)
2002 methodShouldPanic("&_sp", &_sp)
2003
2004 _wv := twordv(3)
2005 methodShouldPanic("_wv", _wv)
2006 methodShouldPanic("&_wv", &_wv)
2007
2008 _wp := twordp(4)
2009 methodShouldPanic("&_wp", &_wp)
2010
2011 _bv := tbigv([2]uintptr{5, 6})
2012 methodShouldPanic("_bv", _bv)
2013 methodShouldPanic("&_bv", &_bv)
2014
2015 _bp := tbigp([2]uintptr{7, 8})
2016 methodShouldPanic("&_bp", &_bp)
2017
2018 var tnil Tinter
2019 vnil := ValueOf(&tnil).Elem()
2020 shouldPanic(func() { vnil.Method(0) })
2021}
2022
Russ Cox92e92572009-07-10 16:32:26 -07002023func TestInterfaceSet(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002024 p := &Point{3, 4}
Russ Cox92e92572009-07-10 16:32:26 -07002025
2026 var s struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002027 I interface{}
2028 P interface {
2029 Dist(int) int
2030 }
Russ Cox92e92572009-07-10 16:32:26 -07002031 }
Russ Cox0e2bb622011-04-25 13:39:16 -04002032 sv := ValueOf(&s).Elem()
2033 sv.Field(0).Set(ValueOf(p))
Russ Cox92e92572009-07-10 16:32:26 -07002034 if q := s.I.(*Point); q != p {
Robert Griesemer40621d52009-11-09 12:07:39 -08002035 t.Errorf("i: have %p want %p", q, p)
Russ Cox92e92572009-07-10 16:32:26 -07002036 }
2037
Russ Coxfb175cf2011-04-08 12:26:51 -04002038 pv := sv.Field(1)
Russ Cox0e2bb622011-04-25 13:39:16 -04002039 pv.Set(ValueOf(p))
Russ Cox92e92572009-07-10 16:32:26 -07002040 if q := s.P.(*Point); q != p {
Robert Griesemer40621d52009-11-09 12:07:39 -08002041 t.Errorf("i: have %p want %p", q, p)
Russ Cox92e92572009-07-10 16:32:26 -07002042 }
Russ Cox3b864e42009-08-12 13:18:37 -07002043
Russ Cox0e2bb622011-04-25 13:39:16 -04002044 i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
Russ Cox92e92572009-07-10 16:32:26 -07002045 if i != 250 {
Robert Griesemer40621d52009-11-09 12:07:39 -08002046 t.Errorf("Interface Method returned %d; want 250", i)
Russ Cox92e92572009-07-10 16:32:26 -07002047 }
2048}
Robert Griesemera2880952009-08-05 15:56:44 -07002049
Robert Griesemer77334b982009-11-05 14:23:20 -08002050type T1 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002051 a string
2052 int
Robert Griesemer77334b982009-11-05 14:23:20 -08002053}
Robert Griesemera2880952009-08-05 15:56:44 -07002054
2055func TestAnonymousFields(t *testing.T) {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002056 var field StructField
2057 var ok bool
2058 var t1 T1
Russ Cox0e2bb622011-04-25 13:39:16 -04002059 type1 := TypeOf(t1)
Robert Griesemera2880952009-08-05 15:56:44 -07002060 if field, ok = type1.FieldByName("int"); !ok {
Russ Cox5e3224c2012-09-05 09:35:53 -04002061 t.Fatal("no field 'int'")
Robert Griesemera2880952009-08-05 15:56:44 -07002062 }
2063 if field.Index[0] != 1 {
Robert Griesemer40621d52009-11-09 12:07:39 -08002064 t.Error("field index should be 1; is", field.Index)
Robert Griesemera2880952009-08-05 15:56:44 -07002065 }
2066}
2067
2068type FTest struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002069 s interface{}
2070 name string
2071 index []int
2072 value int
Robert Griesemera2880952009-08-05 15:56:44 -07002073}
2074
Russ Cox92543da2009-08-24 17:04:12 -07002075type D1 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002076 d int
Russ Cox92543da2009-08-24 17:04:12 -07002077}
2078type D2 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002079 d int
Russ Cox92543da2009-08-24 17:04:12 -07002080}
2081
Robert Griesemera2880952009-08-05 15:56:44 -07002082type S0 struct {
Russ Cox304cf4d2011-10-17 18:48:45 -04002083 A, B, C int
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002084 D1
2085 D2
Robert Griesemera2880952009-08-05 15:56:44 -07002086}
2087
2088type S1 struct {
Russ Cox304cf4d2011-10-17 18:48:45 -04002089 B int
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002090 S0
Robert Griesemera2880952009-08-05 15:56:44 -07002091}
2092
2093type S2 struct {
Russ Cox304cf4d2011-10-17 18:48:45 -04002094 A int
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002095 *S1
Robert Griesemera2880952009-08-05 15:56:44 -07002096}
2097
Russ Cox92543da2009-08-24 17:04:12 -07002098type S1x struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002099 S1
Russ Cox92543da2009-08-24 17:04:12 -07002100}
2101
2102type S1y struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002103 S1
Russ Cox92543da2009-08-24 17:04:12 -07002104}
2105
2106type S3 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002107 S1x
2108 S2
Russ Cox304cf4d2011-10-17 18:48:45 -04002109 D, E int
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002110 *S1y
Robert Griesemera2880952009-08-05 15:56:44 -07002111}
2112
2113type S4 struct {
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002114 *S4
Russ Cox304cf4d2011-10-17 18:48:45 -04002115 A int
Robert Griesemera2880952009-08-05 15:56:44 -07002116}
2117
Russ Cox5e3224c2012-09-05 09:35:53 -04002118// The X in S6 and S7 annihilate, but they also block the X in S8.S9.
2119type S5 struct {
2120 S6
2121 S7
2122 S8
2123}
2124
2125type S6 struct {
2126 X int
2127}
2128
2129type S7 S6
2130
2131type S8 struct {
2132 S9
2133}
2134
2135type S9 struct {
2136 X int
2137 Y int
2138}
2139
2140// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
2141type S10 struct {
2142 S11
2143 S12
2144 S13
2145}
2146
2147type S11 struct {
2148 S6
2149}
2150
2151type S12 struct {
2152 S6
2153}
2154
2155type S13 struct {
2156 S8
2157}
2158
Robert Griesemeraa388012012-11-13 10:45:30 -08002159// The X in S15.S11.S1 and S16.S11.S1 annihilate.
2160type S14 struct {
2161 S15
2162 S16
2163}
2164
2165type S15 struct {
2166 S11
2167}
2168
2169type S16 struct {
2170 S11
2171}
2172
Robert Griesemer77334b982009-11-05 14:23:20 -08002173var fieldTests = []FTest{
Robert Griesemer34788912010-10-22 10:06:33 -07002174 {struct{}{}, "", nil, 0},
Russ Cox304cf4d2011-10-17 18:48:45 -04002175 {struct{}{}, "Foo", nil, 0},
2176 {S0{A: 'a'}, "A", []int{0}, 'a'},
2177 {S0{}, "D", nil, 0},
2178 {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
2179 {S1{B: 'b'}, "B", []int{0}, 'b'},
Robert Griesemer34788912010-10-22 10:06:33 -07002180 {S1{}, "S0", []int{1}, 0},
Russ Cox304cf4d2011-10-17 18:48:45 -04002181 {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
2182 {S2{A: 'a'}, "A", []int{0}, 'a'},
Robert Griesemer34788912010-10-22 10:06:33 -07002183 {S2{}, "S1", []int{1}, 0},
Russ Cox304cf4d2011-10-17 18:48:45 -04002184 {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
2185 {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
2186 {S2{}, "D", nil, 0},
Robert Griesemer34788912010-10-22 10:06:33 -07002187 {S3{}, "S1", nil, 0},
Russ Cox304cf4d2011-10-17 18:48:45 -04002188 {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
2189 {S3{}, "B", nil, 0},
2190 {S3{D: 'd'}, "D", []int{2}, 0},
2191 {S3{E: 'e'}, "E", []int{3}, 'e'},
2192 {S4{A: 'a'}, "A", []int{1}, 'a'},
2193 {S4{}, "B", nil, 0},
Russ Cox5e3224c2012-09-05 09:35:53 -04002194 {S5{}, "X", nil, 0},
2195 {S5{}, "Y", []int{2, 0, 1}, 0},
2196 {S10{}, "X", nil, 0},
2197 {S10{}, "Y", []int{2, 0, 0, 1}, 0},
Robert Griesemeraa388012012-11-13 10:45:30 -08002198 {S14{}, "X", nil, 0},
Robert Griesemera2880952009-08-05 15:56:44 -07002199}
2200
2201func TestFieldByIndex(t *testing.T) {
2202 for _, test := range fieldTests {
Russ Cox0e2bb622011-04-25 13:39:16 -04002203 s := TypeOf(test.s)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002204 f := s.FieldByIndex(test.index)
Robert Griesemera2880952009-08-05 15:56:44 -07002205 if f.Name != "" {
2206 if test.index != nil {
2207 if f.Name != test.name {
Robert Griesemer40621d52009-11-09 12:07:39 -08002208 t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
Robert Griesemera2880952009-08-05 15:56:44 -07002209 }
2210 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -08002211 t.Errorf("%s.%s found", s.Name(), f.Name)
Robert Griesemera2880952009-08-05 15:56:44 -07002212 }
2213 } else if len(test.index) > 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -08002214 t.Errorf("%s.%s not found", s.Name(), test.name)
Robert Griesemera2880952009-08-05 15:56:44 -07002215 }
2216
2217 if test.value != 0 {
Russ Cox0e2bb622011-04-25 13:39:16 -04002218 v := ValueOf(test.s).FieldByIndex(test.index)
Russ Coxfb175cf2011-04-08 12:26:51 -04002219 if v.IsValid() {
Robert Griesemera2880952009-08-05 15:56:44 -07002220 if x, ok := v.Interface().(int); ok {
2221 if x != test.value {
Robert Griesemer40621d52009-11-09 12:07:39 -08002222 t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
Robert Griesemera2880952009-08-05 15:56:44 -07002223 }
2224 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -08002225 t.Errorf("%s%v value not an int", s.Name(), test.index)
Robert Griesemera2880952009-08-05 15:56:44 -07002226 }
2227 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -08002228 t.Errorf("%s%v value not found", s.Name(), test.index)
Robert Griesemera2880952009-08-05 15:56:44 -07002229 }
2230 }
2231 }
2232}
2233
2234func TestFieldByName(t *testing.T) {
2235 for _, test := range fieldTests {
Russ Cox0e2bb622011-04-25 13:39:16 -04002236 s := TypeOf(test.s)
Robert Griesemerd65a5cc2009-12-15 15:40:16 -08002237 f, found := s.FieldByName(test.name)
Robert Griesemera2880952009-08-05 15:56:44 -07002238 if found {
2239 if test.index != nil {
2240 // Verify field depth and index.
2241 if len(f.Index) != len(test.index) {
Russ Cox5e3224c2012-09-05 09:35:53 -04002242 t.Errorf("%s.%s depth %d; want %d: %v vs %v", s.Name(), test.name, len(f.Index), len(test.index), f.Index, test.index)
Robert Griesemera2880952009-08-05 15:56:44 -07002243 } else {
2244 for i, x := range f.Index {
2245 if x != test.index[i] {
Robert Griesemer40621d52009-11-09 12:07:39 -08002246 t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
Robert Griesemera2880952009-08-05 15:56:44 -07002247 }
2248 }
2249 }
2250 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -08002251 t.Errorf("%s.%s found", s.Name(), f.Name)
Robert Griesemera2880952009-08-05 15:56:44 -07002252 }
2253 } else if len(test.index) > 0 {
Robert Griesemer40621d52009-11-09 12:07:39 -08002254 t.Errorf("%s.%s not found", s.Name(), test.name)
Robert Griesemera2880952009-08-05 15:56:44 -07002255 }
Russ Cox3b864e42009-08-12 13:18:37 -07002256
Robert Griesemera2880952009-08-05 15:56:44 -07002257 if test.value != 0 {
Russ Cox0e2bb622011-04-25 13:39:16 -04002258 v := ValueOf(test.s).FieldByName(test.name)
Russ Coxfb175cf2011-04-08 12:26:51 -04002259 if v.IsValid() {
Robert Griesemera2880952009-08-05 15:56:44 -07002260 if x, ok := v.Interface().(int); ok {
2261 if x != test.value {
Robert Griesemer40621d52009-11-09 12:07:39 -08002262 t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
Robert Griesemera2880952009-08-05 15:56:44 -07002263 }
2264 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -08002265 t.Errorf("%s.%s value not an int", s.Name(), test.name)
Robert Griesemera2880952009-08-05 15:56:44 -07002266 }
2267 } else {
Robert Griesemer40621d52009-11-09 12:07:39 -08002268 t.Errorf("%s.%s value not found", s.Name(), test.name)
Robert Griesemera2880952009-08-05 15:56:44 -07002269 }
2270 }
2271 }
2272}
Russ Cox1cecac82010-01-24 23:33:59 -08002273
2274func TestImportPath(t *testing.T) {
David Symondsee09a8c2012-01-20 09:26:17 +11002275 tests := []struct {
2276 t Type
2277 path string
2278 }{
2279 {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
Russ Coxa96c2b82012-09-01 19:55:55 -04002280 {TypeOf(int(0)), ""},
2281 {TypeOf(int8(0)), ""},
2282 {TypeOf(int16(0)), ""},
2283 {TypeOf(int32(0)), ""},
2284 {TypeOf(int64(0)), ""},
David Symondsee09a8c2012-01-20 09:26:17 +11002285 {TypeOf(uint(0)), ""},
Russ Coxa96c2b82012-09-01 19:55:55 -04002286 {TypeOf(uint8(0)), ""},
2287 {TypeOf(uint16(0)), ""},
2288 {TypeOf(uint32(0)), ""},
2289 {TypeOf(uint64(0)), ""},
2290 {TypeOf(uintptr(0)), ""},
2291 {TypeOf(float32(0)), ""},
2292 {TypeOf(float64(0)), ""},
2293 {TypeOf(complex64(0)), ""},
2294 {TypeOf(complex128(0)), ""},
2295 {TypeOf(byte(0)), ""},
2296 {TypeOf(rune(0)), ""},
2297 {TypeOf([]byte(nil)), ""},
2298 {TypeOf([]rune(nil)), ""},
2299 {TypeOf(string("")), ""},
2300 {TypeOf((*interface{})(nil)).Elem(), ""},
2301 {TypeOf((*byte)(nil)), ""},
2302 {TypeOf((*rune)(nil)), ""},
2303 {TypeOf((*int64)(nil)), ""},
David Symondsee09a8c2012-01-20 09:26:17 +11002304 {TypeOf(map[string]int{}), ""},
2305 {TypeOf((*error)(nil)).Elem(), ""},
2306 }
2307 for _, test := range tests {
2308 if path := test.t.PkgPath(); path != test.path {
2309 t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
2310 }
Russ Cox1cecac82010-01-24 23:33:59 -08002311 }
2312}
Russ Cox6672b402010-06-14 11:23:11 -07002313
David Symondsc913cb82011-07-27 13:44:57 +10002314func TestVariadicType(t *testing.T) {
David Symondsfc1cf582011-07-27 13:29:44 +10002315 // Test example from Type documentation.
Russ Coxf2b5a072011-01-19 23:09:00 -05002316 var f func(x int, y ...float64)
Russ Cox0e2bb622011-04-25 13:39:16 -04002317 typ := TypeOf(f)
2318 if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
Russ Coxfb175cf2011-04-08 12:26:51 -04002319 sl := typ.In(1)
2320 if sl.Kind() == Slice {
Russ Cox0e2bb622011-04-25 13:39:16 -04002321 if sl.Elem() == TypeOf(0.0) {
Russ Cox6672b402010-06-14 11:23:11 -07002322 // ok
2323 return
2324 }
2325 }
2326 }
2327
2328 // Failed
Russ Coxf2b5a072011-01-19 23:09:00 -05002329 t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
Russ Cox6672b402010-06-14 11:23:11 -07002330 s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
2331 for i := 0; i < typ.NumIn(); i++ {
2332 s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
2333 }
2334 t.Error(s)
2335}
Russ Cox2d5e7322010-09-27 14:09:10 -04002336
Russ Cox00ffd592010-09-28 13:43:50 -04002337type inner struct {
2338 x int
2339}
Russ Cox2d5e7322010-09-27 14:09:10 -04002340
2341type outer struct {
Russ Cox00ffd592010-09-28 13:43:50 -04002342 y int
Russ Cox2d5e7322010-09-27 14:09:10 -04002343 inner
2344}
2345
2346func (*inner) m() {}
2347func (*outer) m() {}
2348
2349func TestNestedMethods(t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -04002350 typ := TypeOf((*outer)(nil))
2351 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
Russ Cox2d5e7322010-09-27 14:09:10 -04002352 t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
2353 for i := 0; i < typ.NumMethod(); i++ {
2354 m := typ.Method(i)
Russ Coxfb175cf2011-04-08 12:26:51 -04002355 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
Russ Cox2d5e7322010-09-27 14:09:10 -04002356 }
2357 }
2358}
Russ Cox00ffd592010-09-28 13:43:50 -04002359
Russ Cox5ff33362011-04-21 08:14:50 -04002360type InnerInt struct {
2361 X int
Russ Cox00ffd592010-09-28 13:43:50 -04002362}
2363
Russ Cox5ff33362011-04-21 08:14:50 -04002364type OuterInt struct {
2365 Y int
2366 InnerInt
Russ Cox00ffd592010-09-28 13:43:50 -04002367}
2368
Russ Cox5ff33362011-04-21 08:14:50 -04002369func (i *InnerInt) M() int {
2370 return i.X
Russ Cox00ffd592010-09-28 13:43:50 -04002371}
2372
2373func TestEmbeddedMethods(t *testing.T) {
Russ Cox0e2bb622011-04-25 13:39:16 -04002374 typ := TypeOf((*OuterInt)(nil))
2375 if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
Russ Cox5ff33362011-04-21 08:14:50 -04002376 t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
Russ Cox00ffd592010-09-28 13:43:50 -04002377 for i := 0; i < typ.NumMethod(); i++ {
2378 m := typ.Method(i)
Russ Coxfb175cf2011-04-08 12:26:51 -04002379 t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
Russ Cox00ffd592010-09-28 13:43:50 -04002380 }
2381 }
2382
Russ Cox5ff33362011-04-21 08:14:50 -04002383 i := &InnerInt{3}
Russ Cox0e2bb622011-04-25 13:39:16 -04002384 if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
Russ Cox5ff33362011-04-21 08:14:50 -04002385 t.Errorf("i.M() = %d, want 3", v)
Russ Cox00ffd592010-09-28 13:43:50 -04002386 }
2387
Russ Cox5ff33362011-04-21 08:14:50 -04002388 o := &OuterInt{1, InnerInt{2}}
Russ Cox0e2bb622011-04-25 13:39:16 -04002389 if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
Russ Cox5ff33362011-04-21 08:14:50 -04002390 t.Errorf("i.M() = %d, want 2", v)
Russ Cox00ffd592010-09-28 13:43:50 -04002391 }
2392
Russ Cox5ff33362011-04-21 08:14:50 -04002393 f := (*OuterInt).M
Russ Cox00ffd592010-09-28 13:43:50 -04002394 if v := f(o); v != 2 {
2395 t.Errorf("f(o) = %d, want 2", v)
2396 }
2397}
Russ Coxe46acb02011-03-03 13:20:17 -05002398
2399func TestPtrTo(t *testing.T) {
2400 var i int
2401
Russ Cox0e2bb622011-04-25 13:39:16 -04002402 typ := TypeOf(i)
Russ Coxe46acb02011-03-03 13:20:17 -05002403 for i = 0; i < 100; i++ {
2404 typ = PtrTo(typ)
2405 }
2406 for i = 0; i < 100; i++ {
Russ Coxfb175cf2011-04-08 12:26:51 -04002407 typ = typ.Elem()
Russ Coxe46acb02011-03-03 13:20:17 -05002408 }
Russ Cox0e2bb622011-04-25 13:39:16 -04002409 if typ != TypeOf(i) {
2410 t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
Russ Coxe46acb02011-03-03 13:20:17 -05002411 }
2412}
2413
Russ Cox3660b532013-03-26 11:50:29 -07002414func TestPtrToGC(t *testing.T) {
2415 type T *uintptr
2416 tt := TypeOf(T(nil))
2417 pt := PtrTo(tt)
2418 const n = 100
2419 var x []interface{}
2420 for i := 0; i < n; i++ {
2421 v := New(pt)
2422 p := new(*uintptr)
2423 *p = new(uintptr)
2424 **p = uintptr(i)
2425 v.Elem().Set(ValueOf(p).Convert(pt))
2426 x = append(x, v.Interface())
2427 }
2428 runtime.GC()
2429
2430 for i, xi := range x {
2431 k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
2432 if k != uintptr(i) {
2433 t.Errorf("lost x[%d] = %d, want %d", i, k, i)
2434 }
2435 }
2436}
2437
Russ Coxe46acb02011-03-03 13:20:17 -05002438func TestAddr(t *testing.T) {
2439 var p struct {
2440 X, Y int
2441 }
2442
Russ Cox0e2bb622011-04-25 13:39:16 -04002443 v := ValueOf(&p)
Russ Coxfb175cf2011-04-08 12:26:51 -04002444 v = v.Elem()
Russ Coxe46acb02011-03-03 13:20:17 -05002445 v = v.Addr()
Russ Coxfb175cf2011-04-08 12:26:51 -04002446 v = v.Elem()
2447 v = v.Field(0)
2448 v.SetInt(2)
Russ Coxe46acb02011-03-03 13:20:17 -05002449 if p.X != 2 {
2450 t.Errorf("Addr.Elem.Set failed to set value")
2451 }
2452
Russ Cox0e2bb622011-04-25 13:39:16 -04002453 // Again but take address of the ValueOf value.
Russ Coxe46acb02011-03-03 13:20:17 -05002454 // Exercises generation of PtrTypes not present in the binary.
Russ Cox40fccbc2011-04-18 14:35:33 -04002455 q := &p
Russ Cox0e2bb622011-04-25 13:39:16 -04002456 v = ValueOf(&q).Elem()
Russ Coxe46acb02011-03-03 13:20:17 -05002457 v = v.Addr()
Russ Coxfb175cf2011-04-08 12:26:51 -04002458 v = v.Elem()
2459 v = v.Elem()
Russ Coxe46acb02011-03-03 13:20:17 -05002460 v = v.Addr()
Russ Coxfb175cf2011-04-08 12:26:51 -04002461 v = v.Elem()
2462 v = v.Field(0)
2463 v.SetInt(3)
Russ Coxe46acb02011-03-03 13:20:17 -05002464 if p.X != 3 {
2465 t.Errorf("Addr.Elem.Set failed to set value")
2466 }
2467
2468 // Starting without pointer we should get changed value
2469 // in interface.
Russ Cox40fccbc2011-04-18 14:35:33 -04002470 qq := p
Russ Cox0e2bb622011-04-25 13:39:16 -04002471 v = ValueOf(&qq).Elem()
Russ Coxe46acb02011-03-03 13:20:17 -05002472 v0 := v
2473 v = v.Addr()
Russ Coxfb175cf2011-04-08 12:26:51 -04002474 v = v.Elem()
2475 v = v.Field(0)
2476 v.SetInt(4)
Russ Coxe46acb02011-03-03 13:20:17 -05002477 if p.X != 3 { // should be unchanged from last time
2478 t.Errorf("somehow value Set changed original p")
2479 }
2480 p = v0.Interface().(struct {
2481 X, Y int
2482 })
2483 if p.X != 4 {
2484 t.Errorf("Addr.Elem.Set valued to set value in top value")
2485 }
Ian Lance Taylorae5c4ea2012-02-03 17:36:25 -08002486
2487 // Verify that taking the address of a type gives us a pointer
2488 // which we can convert back using the usual interface
2489 // notation.
2490 var s struct {
2491 B *bool
2492 }
2493 ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
2494 *(ps.(**bool)) = new(bool)
2495 if s.B == nil {
2496 t.Errorf("Addr.Interface direct assignment failed")
2497 }
Russ Coxe46acb02011-03-03 13:20:17 -05002498}
Russ Cox40fccbc2011-04-18 14:35:33 -04002499
2500func noAlloc(t *testing.T, n int, f func(int)) {
Rob Pikef5787262013-08-21 14:00:45 +10002501 if testing.Short() {
2502 t.Skip("skipping malloc count in short mode")
2503 }
Albert Strasheim0a71a5b2013-03-06 15:52:32 -08002504 if runtime.GOMAXPROCS(0) > 1 {
2505 t.Skip("skipping; GOMAXPROCS>1")
2506 }
Kyle Lemons9bfd3c32013-02-02 22:52:29 -05002507 i := -1
2508 allocs := testing.AllocsPerRun(n, func() {
2509 f(i)
2510 i++
2511 })
2512 if allocs > 0 {
2513 t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
Russ Cox40fccbc2011-04-18 14:35:33 -04002514 }
2515}
2516
2517func TestAllocations(t *testing.T) {
2518 noAlloc(t, 100, func(j int) {
2519 var i interface{}
2520 var v Value
Ian Lance Taylor82a01882014-10-20 11:10:03 -07002521
2522 // We can uncomment this when compiler escape analysis
2523 // is good enough to see that the integer assigned to i
2524 // does not escape and therefore need not be allocated.
2525 //
2526 // i = 42 + j
2527 // v = ValueOf(i)
2528 // if int(v.Int()) != 42+j {
2529 // panic("wrong int")
2530 // }
2531
2532 i = func(j int) int { return j }
Russ Cox0e2bb622011-04-25 13:39:16 -04002533 v = ValueOf(i)
Ian Lance Taylor82a01882014-10-20 11:10:03 -07002534 if v.Interface().(func(int) int)(j) != j {
2535 panic("wrong result")
Russ Cox40fccbc2011-04-18 14:35:33 -04002536 }
2537 })
2538}
2539
2540func TestSmallNegativeInt(t *testing.T) {
2541 i := int16(-1)
Russ Cox0e2bb622011-04-25 13:39:16 -04002542 v := ValueOf(i)
Russ Cox40fccbc2011-04-18 14:35:33 -04002543 if v.Int() != -1 {
2544 t.Errorf("int16(-1).Int() returned %v", v.Int())
2545 }
2546}
Russ Cox3bac16a2011-04-18 20:00:42 -04002547
Evan Shaw772decb2012-10-21 17:02:10 -04002548func TestIndex(t *testing.T) {
2549 xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
2550 v := ValueOf(xs).Index(3).Interface().(byte)
2551 if v != xs[3] {
2552 t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
2553 }
2554 xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
2555 v = ValueOf(xa).Index(2).Interface().(byte)
2556 if v != xa[2] {
2557 t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
2558 }
2559 s := "0123456789"
2560 v = ValueOf(s).Index(3).Interface().(byte)
2561 if v != s[3] {
2562 t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
2563 }
2564}
2565
Russ Cox3bac16a2011-04-18 20:00:42 -04002566func TestSlice(t *testing.T) {
2567 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
Russ Cox0e2bb622011-04-25 13:39:16 -04002568 v := ValueOf(xs).Slice(3, 5).Interface().([]int)
Gustavo Niemeyer3dc278d2011-12-12 19:45:40 -02002569 if len(v) != 2 {
2570 t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
2571 }
2572 if cap(v) != 5 {
2573 t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
2574 }
2575 if !DeepEqual(v[0:5], xs[3:]) {
2576 t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
Russ Cox3bac16a2011-04-18 20:00:42 -04002577 }
Gustavo Niemeyer3dc278d2011-12-12 19:45:40 -02002578 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
Russ Cox0e2bb622011-04-25 13:39:16 -04002579 v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
Gustavo Niemeyer3dc278d2011-12-12 19:45:40 -02002580 if len(v) != 3 {
2581 t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
2582 }
2583 if cap(v) != 6 {
2584 t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
2585 }
2586 if !DeepEqual(v[0:6], xa[2:]) {
2587 t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
Russ Cox3bac16a2011-04-18 20:00:42 -04002588 }
Evan Shaw772decb2012-10-21 17:02:10 -04002589 s := "0123456789"
2590 vs := ValueOf(s).Slice(3, 5).Interface().(string)
2591 if vs != s[3:5] {
2592 t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
2593 }
Russ Cox613383c2014-08-25 14:38:19 -04002594
2595 rv := ValueOf(&xs).Elem()
2596 rv = rv.Slice(3, 4)
2597 ptr2 := rv.Pointer()
2598 rv = rv.Slice(5, 5)
2599 ptr3 := rv.Pointer()
2600 if ptr3 != ptr2 {
2601 t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
2602 }
Russ Cox3bac16a2011-04-18 20:00:42 -04002603}
Russ Coxe1ee3b52011-04-20 16:24:45 -04002604
Russ Cox4d8aefd2013-07-01 20:32:53 -04002605func TestSlice3(t *testing.T) {
2606 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2607 v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
2608 if len(v) != 2 {
2609 t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
2610 }
2611 if cap(v) != 4 {
2612 t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
2613 }
2614 if !DeepEqual(v[0:4], xs[3:7:7]) {
2615 t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
2616 }
2617 rv := ValueOf(&xs).Elem()
2618 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2619 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2620 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2621
2622 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2623 v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
2624 if len(v) != 3 {
2625 t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
2626 }
2627 if cap(v) != 4 {
2628 t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
2629 }
2630 if !DeepEqual(v[0:4], xa[2:6:6]) {
2631 t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
2632 }
2633 rv = ValueOf(&xa).Elem()
2634 shouldPanic(func() { rv.Slice3(1, 2, 1) })
2635 shouldPanic(func() { rv.Slice3(1, 1, 11) })
2636 shouldPanic(func() { rv.Slice3(2, 2, 1) })
2637
2638 s := "hello world"
2639 rv = ValueOf(&s).Elem()
2640 shouldPanic(func() { rv.Slice3(1, 2, 3) })
Russ Cox613383c2014-08-25 14:38:19 -04002641
2642 rv = ValueOf(&xs).Elem()
2643 rv = rv.Slice3(3, 5, 7)
2644 ptr2 := rv.Pointer()
2645 rv = rv.Slice3(4, 4, 4)
2646 ptr3 := rv.Pointer()
2647 if ptr3 != ptr2 {
2648 t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
2649 }
Russ Cox4d8aefd2013-07-01 20:32:53 -04002650}
2651
2652func TestSetLenCap(t *testing.T) {
2653 xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
2654 xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
2655
2656 vs := ValueOf(&xs).Elem()
2657 shouldPanic(func() { vs.SetLen(10) })
2658 shouldPanic(func() { vs.SetCap(10) })
2659 shouldPanic(func() { vs.SetLen(-1) })
2660 shouldPanic(func() { vs.SetCap(-1) })
2661 shouldPanic(func() { vs.SetCap(6) }) // smaller than len
2662 vs.SetLen(5)
2663 if len(xs) != 5 || cap(xs) != 8 {
2664 t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
2665 }
2666 vs.SetCap(6)
2667 if len(xs) != 5 || cap(xs) != 6 {
2668 t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
2669 }
2670 vs.SetCap(5)
2671 if len(xs) != 5 || cap(xs) != 5 {
2672 t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
2673 }
2674 shouldPanic(func() { vs.SetCap(4) }) // smaller than len
2675 shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
2676
2677 va := ValueOf(&xa).Elem()
2678 shouldPanic(func() { va.SetLen(8) })
2679 shouldPanic(func() { va.SetCap(8) })
2680}
2681
Russ Coxe1ee3b52011-04-20 16:24:45 -04002682func TestVariadic(t *testing.T) {
2683 var b bytes.Buffer
Russ Cox0e2bb622011-04-25 13:39:16 -04002684 V := ValueOf
Russ Coxe1ee3b52011-04-20 16:24:45 -04002685
2686 b.Reset()
2687 V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
2688 if b.String() != "hello, 42 world" {
2689 t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
2690 }
2691
2692 b.Reset()
2693 V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
2694 if b.String() != "hello, 42 world" {
2695 t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
2696 }
2697}
Russ Cox25733a92011-06-29 09:52:34 -04002698
Ian Lance Taylore59db902013-10-03 13:23:02 -07002699func TestFuncArg(t *testing.T) {
2700 f1 := func(i int, f func(int) int) int { return f(i) }
2701 f2 := func(i int) int { return i + 1 }
2702 r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
2703 if r[0].Int() != 101 {
2704 t.Errorf("function returned %d, want 101", r[0].Int())
2705 }
2706}
2707
Damien Neil4e1d1962014-10-16 13:58:32 -07002708func TestStructArg(t *testing.T) {
2709 type padded struct {
2710 B string
2711 C int32
2712 }
2713 var (
2714 gotA padded
2715 gotB uint32
2716 wantA = padded{"3", 4}
2717 wantB = uint32(5)
2718 )
2719 f := func(a padded, b uint32) {
2720 gotA, gotB = a, b
2721 }
2722 ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
2723 if gotA != wantA || gotB != wantB {
2724 t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
2725 }
2726}
2727
Russ Cox25733a92011-06-29 09:52:34 -04002728var tagGetTests = []struct {
2729 Tag StructTag
2730 Key string
2731 Value string
2732}{
2733 {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
2734 {`protobuf:"PB(1,2)"`, `foo`, ``},
2735 {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
2736 {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
2737 {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
2738}
2739
2740func TestTagGet(t *testing.T) {
2741 for _, tt := range tagGetTests {
2742 if v := tt.Tag.Get(tt.Key); v != tt.Value {
2743 t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
2744 }
2745 }
2746}
Russ Cox00d64c72011-08-23 22:50:08 -04002747
2748func TestBytes(t *testing.T) {
2749 type B []byte
2750 x := B{1, 2, 3, 4}
2751 y := ValueOf(x).Bytes()
2752 if !bytes.Equal(x, y) {
2753 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2754 }
2755 if &x[0] != &y[0] {
2756 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2757 }
2758}
2759
2760func TestSetBytes(t *testing.T) {
2761 type B []byte
2762 var x B
2763 y := []byte{1, 2, 3, 4}
2764 ValueOf(&x).Elem().SetBytes(y)
2765 if !bytes.Equal(x, y) {
2766 t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
2767 }
2768 if &x[0] != &y[0] {
2769 t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
2770 }
2771}
Russ Cox304cf4d2011-10-17 18:48:45 -04002772
2773type Private struct {
2774 x int
2775 y **int
2776}
2777
2778func (p *Private) m() {
2779}
2780
2781type Public struct {
2782 X int
2783 Y **int
2784}
2785
2786func (p *Public) M() {
2787}
2788
2789func TestUnexported(t *testing.T) {
2790 var pub Public
2791 v := ValueOf(&pub)
2792 isValid(v.Elem().Field(0))
2793 isValid(v.Elem().Field(1))
2794 isValid(v.Elem().FieldByName("X"))
2795 isValid(v.Elem().FieldByName("Y"))
2796 isValid(v.Type().Method(0).Func)
2797 isNonNil(v.Elem().Field(0).Interface())
2798 isNonNil(v.Elem().Field(1).Interface())
2799 isNonNil(v.Elem().FieldByName("X").Interface())
2800 isNonNil(v.Elem().FieldByName("Y").Interface())
2801 isNonNil(v.Type().Method(0).Func.Interface())
2802
2803 var priv Private
2804 v = ValueOf(&priv)
2805 isValid(v.Elem().Field(0))
2806 isValid(v.Elem().Field(1))
2807 isValid(v.Elem().FieldByName("x"))
2808 isValid(v.Elem().FieldByName("y"))
2809 isValid(v.Type().Method(0).Func)
2810 shouldPanic(func() { v.Elem().Field(0).Interface() })
2811 shouldPanic(func() { v.Elem().Field(1).Interface() })
2812 shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
2813 shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
2814 shouldPanic(func() { v.Type().Method(0).Func.Interface() })
2815}
2816
2817func shouldPanic(f func()) {
2818 defer func() {
2819 if recover() == nil {
2820 panic("did not panic")
2821 }
2822 }()
2823 f()
2824}
2825
2826func isNonNil(x interface{}) {
2827 if x == nil {
2828 panic("nil interface")
2829 }
2830}
2831
2832func isValid(v Value) {
2833 if !v.IsValid() {
2834 panic("zero Value")
2835 }
2836}
Russ Coxa72b87e2012-03-01 11:48:27 -05002837
2838func TestAlias(t *testing.T) {
2839 x := string("hello")
2840 v := ValueOf(&x).Elem()
2841 oldvalue := v.Interface()
2842 v.SetString("world")
2843 newvalue := v.Interface()
2844
2845 if oldvalue != "hello" || newvalue != "world" {
2846 t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
2847 }
2848}
Russ Cox5e3224c2012-09-05 09:35:53 -04002849
Russ Cox46f379c2012-09-22 08:52:27 -04002850var V = ValueOf
2851
2852func EmptyInterfaceV(x interface{}) Value {
2853 return ValueOf(&x).Elem()
2854}
2855
2856func ReaderV(x io.Reader) Value {
2857 return ValueOf(&x).Elem()
2858}
2859
2860func ReadWriterV(x io.ReadWriter) Value {
2861 return ValueOf(&x).Elem()
2862}
2863
2864type Empty struct{}
2865type MyString string
2866type MyBytes []byte
2867type MyRunes []int32
2868type MyFunc func()
2869type MyByte byte
2870
2871var convertTests = []struct {
2872 in Value
2873 out Value
2874}{
2875 // numbers
2876 /*
2877 Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
2878
2879 package main
2880
2881 import "fmt"
2882
2883 var numbers = []string{
2884 "int8", "uint8", "int16", "uint16",
2885 "int32", "uint32", "int64", "uint64",
2886 "int", "uint", "uintptr",
2887 "float32", "float64",
2888 }
2889
2890 func main() {
2891 // all pairs but in an unusual order,
2892 // to emit all the int8, uint8 cases
2893 // before n grows too big.
2894 n := 1
2895 for i, f := range numbers {
2896 for _, g := range numbers[i:] {
2897 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
2898 n++
2899 if f != g {
2900 fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
2901 n++
2902 }
2903 }
2904 }
2905 }
2906 */
2907 {V(int8(1)), V(int8(1))},
2908 {V(int8(2)), V(uint8(2))},
2909 {V(uint8(3)), V(int8(3))},
2910 {V(int8(4)), V(int16(4))},
2911 {V(int16(5)), V(int8(5))},
2912 {V(int8(6)), V(uint16(6))},
2913 {V(uint16(7)), V(int8(7))},
2914 {V(int8(8)), V(int32(8))},
2915 {V(int32(9)), V(int8(9))},
2916 {V(int8(10)), V(uint32(10))},
2917 {V(uint32(11)), V(int8(11))},
2918 {V(int8(12)), V(int64(12))},
2919 {V(int64(13)), V(int8(13))},
2920 {V(int8(14)), V(uint64(14))},
2921 {V(uint64(15)), V(int8(15))},
2922 {V(int8(16)), V(int(16))},
2923 {V(int(17)), V(int8(17))},
2924 {V(int8(18)), V(uint(18))},
2925 {V(uint(19)), V(int8(19))},
2926 {V(int8(20)), V(uintptr(20))},
2927 {V(uintptr(21)), V(int8(21))},
2928 {V(int8(22)), V(float32(22))},
2929 {V(float32(23)), V(int8(23))},
2930 {V(int8(24)), V(float64(24))},
2931 {V(float64(25)), V(int8(25))},
2932 {V(uint8(26)), V(uint8(26))},
2933 {V(uint8(27)), V(int16(27))},
2934 {V(int16(28)), V(uint8(28))},
2935 {V(uint8(29)), V(uint16(29))},
2936 {V(uint16(30)), V(uint8(30))},
2937 {V(uint8(31)), V(int32(31))},
2938 {V(int32(32)), V(uint8(32))},
2939 {V(uint8(33)), V(uint32(33))},
2940 {V(uint32(34)), V(uint8(34))},
2941 {V(uint8(35)), V(int64(35))},
2942 {V(int64(36)), V(uint8(36))},
2943 {V(uint8(37)), V(uint64(37))},
2944 {V(uint64(38)), V(uint8(38))},
2945 {V(uint8(39)), V(int(39))},
2946 {V(int(40)), V(uint8(40))},
2947 {V(uint8(41)), V(uint(41))},
2948 {V(uint(42)), V(uint8(42))},
2949 {V(uint8(43)), V(uintptr(43))},
2950 {V(uintptr(44)), V(uint8(44))},
2951 {V(uint8(45)), V(float32(45))},
2952 {V(float32(46)), V(uint8(46))},
2953 {V(uint8(47)), V(float64(47))},
2954 {V(float64(48)), V(uint8(48))},
2955 {V(int16(49)), V(int16(49))},
2956 {V(int16(50)), V(uint16(50))},
2957 {V(uint16(51)), V(int16(51))},
2958 {V(int16(52)), V(int32(52))},
2959 {V(int32(53)), V(int16(53))},
2960 {V(int16(54)), V(uint32(54))},
2961 {V(uint32(55)), V(int16(55))},
2962 {V(int16(56)), V(int64(56))},
2963 {V(int64(57)), V(int16(57))},
2964 {V(int16(58)), V(uint64(58))},
2965 {V(uint64(59)), V(int16(59))},
2966 {V(int16(60)), V(int(60))},
2967 {V(int(61)), V(int16(61))},
2968 {V(int16(62)), V(uint(62))},
2969 {V(uint(63)), V(int16(63))},
2970 {V(int16(64)), V(uintptr(64))},
2971 {V(uintptr(65)), V(int16(65))},
2972 {V(int16(66)), V(float32(66))},
2973 {V(float32(67)), V(int16(67))},
2974 {V(int16(68)), V(float64(68))},
2975 {V(float64(69)), V(int16(69))},
2976 {V(uint16(70)), V(uint16(70))},
2977 {V(uint16(71)), V(int32(71))},
2978 {V(int32(72)), V(uint16(72))},
2979 {V(uint16(73)), V(uint32(73))},
2980 {V(uint32(74)), V(uint16(74))},
2981 {V(uint16(75)), V(int64(75))},
2982 {V(int64(76)), V(uint16(76))},
2983 {V(uint16(77)), V(uint64(77))},
2984 {V(uint64(78)), V(uint16(78))},
2985 {V(uint16(79)), V(int(79))},
2986 {V(int(80)), V(uint16(80))},
2987 {V(uint16(81)), V(uint(81))},
2988 {V(uint(82)), V(uint16(82))},
2989 {V(uint16(83)), V(uintptr(83))},
2990 {V(uintptr(84)), V(uint16(84))},
2991 {V(uint16(85)), V(float32(85))},
2992 {V(float32(86)), V(uint16(86))},
2993 {V(uint16(87)), V(float64(87))},
2994 {V(float64(88)), V(uint16(88))},
2995 {V(int32(89)), V(int32(89))},
2996 {V(int32(90)), V(uint32(90))},
2997 {V(uint32(91)), V(int32(91))},
2998 {V(int32(92)), V(int64(92))},
2999 {V(int64(93)), V(int32(93))},
3000 {V(int32(94)), V(uint64(94))},
3001 {V(uint64(95)), V(int32(95))},
3002 {V(int32(96)), V(int(96))},
3003 {V(int(97)), V(int32(97))},
3004 {V(int32(98)), V(uint(98))},
3005 {V(uint(99)), V(int32(99))},
3006 {V(int32(100)), V(uintptr(100))},
3007 {V(uintptr(101)), V(int32(101))},
3008 {V(int32(102)), V(float32(102))},
3009 {V(float32(103)), V(int32(103))},
3010 {V(int32(104)), V(float64(104))},
3011 {V(float64(105)), V(int32(105))},
3012 {V(uint32(106)), V(uint32(106))},
3013 {V(uint32(107)), V(int64(107))},
3014 {V(int64(108)), V(uint32(108))},
3015 {V(uint32(109)), V(uint64(109))},
3016 {V(uint64(110)), V(uint32(110))},
3017 {V(uint32(111)), V(int(111))},
3018 {V(int(112)), V(uint32(112))},
3019 {V(uint32(113)), V(uint(113))},
3020 {V(uint(114)), V(uint32(114))},
3021 {V(uint32(115)), V(uintptr(115))},
3022 {V(uintptr(116)), V(uint32(116))},
3023 {V(uint32(117)), V(float32(117))},
3024 {V(float32(118)), V(uint32(118))},
3025 {V(uint32(119)), V(float64(119))},
3026 {V(float64(120)), V(uint32(120))},
3027 {V(int64(121)), V(int64(121))},
3028 {V(int64(122)), V(uint64(122))},
3029 {V(uint64(123)), V(int64(123))},
3030 {V(int64(124)), V(int(124))},
3031 {V(int(125)), V(int64(125))},
3032 {V(int64(126)), V(uint(126))},
3033 {V(uint(127)), V(int64(127))},
3034 {V(int64(128)), V(uintptr(128))},
3035 {V(uintptr(129)), V(int64(129))},
3036 {V(int64(130)), V(float32(130))},
3037 {V(float32(131)), V(int64(131))},
3038 {V(int64(132)), V(float64(132))},
3039 {V(float64(133)), V(int64(133))},
3040 {V(uint64(134)), V(uint64(134))},
3041 {V(uint64(135)), V(int(135))},
3042 {V(int(136)), V(uint64(136))},
3043 {V(uint64(137)), V(uint(137))},
3044 {V(uint(138)), V(uint64(138))},
3045 {V(uint64(139)), V(uintptr(139))},
3046 {V(uintptr(140)), V(uint64(140))},
3047 {V(uint64(141)), V(float32(141))},
3048 {V(float32(142)), V(uint64(142))},
3049 {V(uint64(143)), V(float64(143))},
3050 {V(float64(144)), V(uint64(144))},
3051 {V(int(145)), V(int(145))},
3052 {V(int(146)), V(uint(146))},
3053 {V(uint(147)), V(int(147))},
3054 {V(int(148)), V(uintptr(148))},
3055 {V(uintptr(149)), V(int(149))},
3056 {V(int(150)), V(float32(150))},
3057 {V(float32(151)), V(int(151))},
3058 {V(int(152)), V(float64(152))},
3059 {V(float64(153)), V(int(153))},
3060 {V(uint(154)), V(uint(154))},
3061 {V(uint(155)), V(uintptr(155))},
3062 {V(uintptr(156)), V(uint(156))},
3063 {V(uint(157)), V(float32(157))},
3064 {V(float32(158)), V(uint(158))},
3065 {V(uint(159)), V(float64(159))},
3066 {V(float64(160)), V(uint(160))},
3067 {V(uintptr(161)), V(uintptr(161))},
3068 {V(uintptr(162)), V(float32(162))},
3069 {V(float32(163)), V(uintptr(163))},
3070 {V(uintptr(164)), V(float64(164))},
3071 {V(float64(165)), V(uintptr(165))},
3072 {V(float32(166)), V(float32(166))},
3073 {V(float32(167)), V(float64(167))},
3074 {V(float64(168)), V(float32(168))},
3075 {V(float64(169)), V(float64(169))},
3076
3077 // truncation
3078 {V(float64(1.5)), V(int(1))},
3079
3080 // complex
3081 {V(complex64(1i)), V(complex64(1i))},
3082 {V(complex64(2i)), V(complex128(2i))},
3083 {V(complex128(3i)), V(complex64(3i))},
3084 {V(complex128(4i)), V(complex128(4i))},
3085
3086 // string
3087 {V(string("hello")), V(string("hello"))},
3088 {V(string("bytes1")), V([]byte("bytes1"))},
3089 {V([]byte("bytes2")), V(string("bytes2"))},
3090 {V([]byte("bytes3")), V([]byte("bytes3"))},
3091 {V(string("runes♝")), V([]rune("runes♝"))},
3092 {V([]rune("runes♕")), V(string("runes♕"))},
3093 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3094 {V(int('a')), V(string("a"))},
3095 {V(int8('a')), V(string("a"))},
3096 {V(int16('a')), V(string("a"))},
3097 {V(int32('a')), V(string("a"))},
3098 {V(int64('a')), V(string("a"))},
3099 {V(uint('a')), V(string("a"))},
3100 {V(uint8('a')), V(string("a"))},
3101 {V(uint16('a')), V(string("a"))},
3102 {V(uint32('a')), V(string("a"))},
3103 {V(uint64('a')), V(string("a"))},
3104 {V(uintptr('a')), V(string("a"))},
3105 {V(int(-1)), V(string("\uFFFD"))},
3106 {V(int8(-2)), V(string("\uFFFD"))},
3107 {V(int16(-3)), V(string("\uFFFD"))},
3108 {V(int32(-4)), V(string("\uFFFD"))},
3109 {V(int64(-5)), V(string("\uFFFD"))},
3110 {V(uint(0x110001)), V(string("\uFFFD"))},
3111 {V(uint32(0x110002)), V(string("\uFFFD"))},
3112 {V(uint64(0x110003)), V(string("\uFFFD"))},
3113 {V(uintptr(0x110004)), V(string("\uFFFD"))},
3114
3115 // named string
3116 {V(MyString("hello")), V(string("hello"))},
3117 {V(string("hello")), V(MyString("hello"))},
3118 {V(string("hello")), V(string("hello"))},
3119 {V(MyString("hello")), V(MyString("hello"))},
3120 {V(MyString("bytes1")), V([]byte("bytes1"))},
3121 {V([]byte("bytes2")), V(MyString("bytes2"))},
3122 {V([]byte("bytes3")), V([]byte("bytes3"))},
3123 {V(MyString("runes♝")), V([]rune("runes♝"))},
3124 {V([]rune("runes♕")), V(MyString("runes♕"))},
3125 {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3126 {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3127 {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
3128 {V(int('a')), V(MyString("a"))},
3129 {V(int8('a')), V(MyString("a"))},
3130 {V(int16('a')), V(MyString("a"))},
3131 {V(int32('a')), V(MyString("a"))},
3132 {V(int64('a')), V(MyString("a"))},
3133 {V(uint('a')), V(MyString("a"))},
3134 {V(uint8('a')), V(MyString("a"))},
3135 {V(uint16('a')), V(MyString("a"))},
3136 {V(uint32('a')), V(MyString("a"))},
3137 {V(uint64('a')), V(MyString("a"))},
3138 {V(uintptr('a')), V(MyString("a"))},
3139 {V(int(-1)), V(MyString("\uFFFD"))},
3140 {V(int8(-2)), V(MyString("\uFFFD"))},
3141 {V(int16(-3)), V(MyString("\uFFFD"))},
3142 {V(int32(-4)), V(MyString("\uFFFD"))},
3143 {V(int64(-5)), V(MyString("\uFFFD"))},
3144 {V(uint(0x110001)), V(MyString("\uFFFD"))},
3145 {V(uint32(0x110002)), V(MyString("\uFFFD"))},
3146 {V(uint64(0x110003)), V(MyString("\uFFFD"))},
3147 {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
3148
3149 // named []byte
3150 {V(string("bytes1")), V(MyBytes("bytes1"))},
3151 {V(MyBytes("bytes2")), V(string("bytes2"))},
3152 {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
3153 {V(MyString("bytes1")), V(MyBytes("bytes1"))},
3154 {V(MyBytes("bytes2")), V(MyString("bytes2"))},
3155
3156 // named []rune
3157 {V(string("runes♝")), V(MyRunes("runes♝"))},
3158 {V(MyRunes("runes♕")), V(string("runes♕"))},
3159 {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
3160 {V(MyString("runes♝")), V(MyRunes("runes♝"))},
3161 {V(MyRunes("runes♕")), V(MyString("runes♕"))},
3162
3163 // named types and equal underlying types
3164 {V(new(int)), V(new(integer))},
3165 {V(new(integer)), V(new(int))},
3166 {V(Empty{}), V(struct{}{})},
3167 {V(new(Empty)), V(new(struct{}))},
3168 {V(struct{}{}), V(Empty{})},
3169 {V(new(struct{})), V(new(Empty))},
3170 {V(Empty{}), V(Empty{})},
3171 {V(MyBytes{}), V([]byte{})},
3172 {V([]byte{}), V(MyBytes{})},
3173 {V((func())(nil)), V(MyFunc(nil))},
3174 {V((MyFunc)(nil)), V((func())(nil))},
3175
3176 // can convert *byte and *MyByte
3177 {V((*byte)(nil)), V((*MyByte)(nil))},
3178 {V((*MyByte)(nil)), V((*byte)(nil))},
3179
3180 // cannot convert mismatched array sizes
3181 {V([2]byte{}), V([2]byte{})},
3182 {V([3]byte{}), V([3]byte{})},
3183
3184 // cannot convert other instances
3185 {V((**byte)(nil)), V((**byte)(nil))},
3186 {V((**MyByte)(nil)), V((**MyByte)(nil))},
3187 {V((chan byte)(nil)), V((chan byte)(nil))},
3188 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3189 {V(([]byte)(nil)), V(([]byte)(nil))},
3190 {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
3191 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3192 {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
3193 {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
3194 {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
3195 {V([2]byte{}), V([2]byte{})},
3196 {V([2]MyByte{}), V([2]MyByte{})},
3197
3198 // other
3199 {V((***int)(nil)), V((***int)(nil))},
3200 {V((***byte)(nil)), V((***byte)(nil))},
3201 {V((***int32)(nil)), V((***int32)(nil))},
3202 {V((***int64)(nil)), V((***int64)(nil))},
3203 {V((chan int)(nil)), V((<-chan int)(nil))},
3204 {V((chan int)(nil)), V((chan<- int)(nil))},
3205 {V((chan string)(nil)), V((<-chan string)(nil))},
3206 {V((chan string)(nil)), V((chan<- string)(nil))},
3207 {V((chan byte)(nil)), V((chan byte)(nil))},
3208 {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
3209 {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
3210 {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
3211 {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
3212 {V([]uint(nil)), V([]uint(nil))},
3213 {V([]int(nil)), V([]int(nil))},
3214 {V(new(interface{})), V(new(interface{}))},
3215 {V(new(io.Reader)), V(new(io.Reader))},
3216 {V(new(io.Writer)), V(new(io.Writer))},
3217
3218 // interfaces
3219 {V(int(1)), EmptyInterfaceV(int(1))},
3220 {V(string("hello")), EmptyInterfaceV(string("hello"))},
3221 {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3222 {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
3223 {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
3224}
3225
3226func TestConvert(t *testing.T) {
3227 canConvert := map[[2]Type]bool{}
3228 all := map[Type]bool{}
3229
3230 for _, tt := range convertTests {
3231 t1 := tt.in.Type()
3232 if !t1.ConvertibleTo(t1) {
3233 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
3234 continue
3235 }
3236
3237 t2 := tt.out.Type()
3238 if !t1.ConvertibleTo(t2) {
3239 t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
3240 continue
3241 }
3242
3243 all[t1] = true
3244 all[t2] = true
3245 canConvert[[2]Type{t1, t2}] = true
3246
Todd Wang0e734972013-08-21 14:41:55 +10003247 // vout1 represents the in value converted to the in type.
Russ Cox46f379c2012-09-22 08:52:27 -04003248 v1 := tt.in
3249 vout1 := v1.Convert(t1)
3250 out1 := vout1.Interface()
3251 if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
Todd Wang0e734972013-08-21 14:41:55 +10003252 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
Russ Cox46f379c2012-09-22 08:52:27 -04003253 }
3254
Todd Wang0e734972013-08-21 14:41:55 +10003255 // vout2 represents the in value converted to the out type.
3256 vout2 := v1.Convert(t2)
3257 out2 := vout2.Interface()
3258 if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
3259 t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
3260 }
3261
3262 // vout3 represents a new value of the out type, set to vout2. This makes
3263 // sure the converted value vout2 is really usable as a regular value.
3264 vout3 := New(t2).Elem()
3265 vout3.Set(vout2)
3266 out3 := vout3.Interface()
3267 if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
3268 t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
Russ Cox46f379c2012-09-22 08:52:27 -04003269 }
3270
3271 if IsRO(v1) {
3272 t.Errorf("table entry %v is RO, should not be", v1)
3273 }
3274 if IsRO(vout1) {
3275 t.Errorf("self-conversion output %v is RO, should not be", vout1)
3276 }
Todd Wang0e734972013-08-21 14:41:55 +10003277 if IsRO(vout2) {
3278 t.Errorf("conversion output %v is RO, should not be", vout2)
3279 }
3280 if IsRO(vout3) {
3281 t.Errorf("set(conversion output) %v is RO, should not be", vout3)
Russ Cox46f379c2012-09-22 08:52:27 -04003282 }
3283 if !IsRO(MakeRO(v1).Convert(t1)) {
3284 t.Errorf("RO self-conversion output %v is not RO, should be", v1)
3285 }
3286 if !IsRO(MakeRO(v1).Convert(t2)) {
3287 t.Errorf("RO conversion output %v is not RO, should be", v1)
3288 }
3289 }
3290
3291 // Assume that of all the types we saw during the tests,
3292 // if there wasn't an explicit entry for a conversion between
3293 // a pair of types, then it's not to be allowed. This checks for
3294 // things like 'int64' converting to '*int'.
3295 for t1 := range all {
3296 for t2 := range all {
3297 expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
3298 if ok := t1.ConvertibleTo(t2); ok != expectOK {
3299 t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
3300 }
3301 }
3302 }
3303}
3304
Russ Coxa325f4f2014-09-16 17:40:10 -04003305type ComparableStruct struct {
3306 X int
3307}
3308
3309type NonComparableStruct struct {
3310 X int
3311 Y map[string]int
3312}
3313
3314var comparableTests = []struct {
3315 typ Type
3316 ok bool
3317}{
3318 {TypeOf(1), true},
3319 {TypeOf("hello"), true},
3320 {TypeOf(new(byte)), true},
3321 {TypeOf((func())(nil)), false},
3322 {TypeOf([]byte{}), false},
3323 {TypeOf(map[string]int{}), false},
3324 {TypeOf(make(chan int)), true},
3325 {TypeOf(1.5), true},
3326 {TypeOf(false), true},
3327 {TypeOf(1i), true},
3328 {TypeOf(ComparableStruct{}), true},
3329 {TypeOf(NonComparableStruct{}), false},
3330 {TypeOf([10]map[string]int{}), false},
3331 {TypeOf([10]string{}), true},
3332 {TypeOf(new(interface{})).Elem(), true},
3333}
3334
3335func TestComparable(t *testing.T) {
3336 for _, tt := range comparableTests {
3337 if ok := tt.typ.Comparable(); ok != tt.ok {
3338 t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
3339 }
3340 }
3341}
3342
Rémy Oudompheng38070a72012-10-26 08:39:36 +02003343func TestOverflow(t *testing.T) {
3344 if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
3345 t.Errorf("%v wrongly overflows float64", 1e300)
3346 }
3347
3348 maxFloat32 := float64((1<<24 - 1) << (127 - 23))
3349 if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
3350 t.Errorf("%v wrongly overflows float32", maxFloat32)
3351 }
3352 ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
3353 if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
3354 t.Errorf("%v should overflow float32", ovfFloat32)
3355 }
3356 if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
3357 t.Errorf("%v should overflow float32", -ovfFloat32)
3358 }
3359
3360 maxInt32 := int64(0x7fffffff)
3361 if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
3362 t.Errorf("%v wrongly overflows int32", maxInt32)
3363 }
3364 if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
3365 t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
3366 }
3367 ovfInt32 := int64(1 << 31)
3368 if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
3369 t.Errorf("%v should overflow int32", ovfInt32)
3370 }
3371
3372 maxUint32 := uint64(0xffffffff)
3373 if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
3374 t.Errorf("%v wrongly overflows uint32", maxUint32)
3375 }
3376 ovfUint32 := uint64(1 << 32)
3377 if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
3378 t.Errorf("%v should overflow uint32", ovfUint32)
3379 }
3380}
3381
Russ Cox11209822012-11-13 13:06:29 -05003382func checkSameType(t *testing.T, x, y interface{}) {
3383 if TypeOf(x) != TypeOf(y) {
3384 t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
3385 }
3386}
3387
3388func TestArrayOf(t *testing.T) {
Russ Cox1806a572014-08-18 21:13:11 -04003389 // TODO(rsc): Finish ArrayOf and enable-test.
3390 t.Skip("ArrayOf is not finished (and not exported)")
3391
Russ Cox11209822012-11-13 13:06:29 -05003392 // check construction and use of type not in binary
3393 type T int
3394 at := ArrayOf(10, TypeOf(T(1)))
3395 v := New(at).Elem()
3396 for i := 0; i < v.Len(); i++ {
3397 v.Index(i).Set(ValueOf(T(i)))
3398 }
3399 s := fmt.Sprint(v.Interface())
3400 want := "[0 1 2 3 4 5 6 7 8 9]"
3401 if s != want {
3402 t.Errorf("constructed array = %s, want %s", s, want)
3403 }
3404
3405 // check that type already in binary is found
3406 checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
3407}
3408
3409func TestSliceOf(t *testing.T) {
3410 // check construction and use of type not in binary
3411 type T int
3412 st := SliceOf(TypeOf(T(1)))
3413 v := MakeSlice(st, 10, 10)
Russ Cox3660b532013-03-26 11:50:29 -07003414 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003415 for i := 0; i < v.Len(); i++ {
3416 v.Index(i).Set(ValueOf(T(i)))
Russ Cox3660b532013-03-26 11:50:29 -07003417 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003418 }
3419 s := fmt.Sprint(v.Interface())
3420 want := "[0 1 2 3 4 5 6 7 8 9]"
3421 if s != want {
3422 t.Errorf("constructed slice = %s, want %s", s, want)
3423 }
3424
3425 // check that type already in binary is found
3426 type T1 int
3427 checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
3428}
3429
Dmitriy Vyukov5782f412013-05-27 11:29:11 +04003430func TestSliceOverflow(t *testing.T) {
3431 // check that MakeSlice panics when size of slice overflows uint
3432 const S = 1e6
3433 s := uint(S)
3434 l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
3435 if l*s >= s {
3436 t.Fatal("slice size does not overflow")
3437 }
3438 var x [S]byte
3439 st := SliceOf(TypeOf(x))
3440 defer func() {
3441 err := recover()
3442 if err == nil {
3443 t.Fatal("slice overflow does not panic")
3444 }
3445 }()
3446 MakeSlice(st, int(l), int(l))
3447}
3448
Russ Cox3660b532013-03-26 11:50:29 -07003449func TestSliceOfGC(t *testing.T) {
3450 type T *uintptr
3451 tt := TypeOf(T(nil))
3452 st := SliceOf(tt)
3453 const n = 100
3454 var x []interface{}
3455 for i := 0; i < n; i++ {
3456 v := MakeSlice(st, n, n)
3457 for j := 0; j < v.Len(); j++ {
3458 p := new(uintptr)
3459 *p = uintptr(i*n + j)
3460 v.Index(j).Set(ValueOf(p).Convert(tt))
3461 }
3462 x = append(x, v.Interface())
3463 }
3464 runtime.GC()
3465
3466 for i, xi := range x {
3467 v := ValueOf(xi)
3468 for j := 0; j < v.Len(); j++ {
3469 k := v.Index(j).Elem().Interface()
3470 if k != uintptr(i*n+j) {
3471 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3472 }
3473 }
3474 }
3475}
3476
Russ Cox11209822012-11-13 13:06:29 -05003477func TestChanOf(t *testing.T) {
3478 // check construction and use of type not in binary
3479 type T string
3480 ct := ChanOf(BothDir, TypeOf(T("")))
3481 v := MakeChan(ct, 2)
Russ Cox3660b532013-03-26 11:50:29 -07003482 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003483 v.Send(ValueOf(T("hello")))
Russ Cox3660b532013-03-26 11:50:29 -07003484 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003485 v.Send(ValueOf(T("world")))
Russ Cox3660b532013-03-26 11:50:29 -07003486 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003487
3488 sv1, _ := v.Recv()
3489 sv2, _ := v.Recv()
3490 s1 := sv1.String()
3491 s2 := sv2.String()
3492 if s1 != "hello" || s2 != "world" {
3493 t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
3494 }
3495
3496 // check that type already in binary is found
3497 type T1 int
3498 checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
3499}
3500
Michael Fraenkel48d63032015-01-01 21:38:12 -05003501func TestChanOfDir(t *testing.T) {
3502 // check construction and use of type not in binary
3503 type T string
3504 crt := ChanOf(RecvDir, TypeOf(T("")))
3505 cst := ChanOf(SendDir, TypeOf(T("")))
3506
3507 // check that type already in binary is found
3508 type T1 int
3509 checkSameType(t, Zero(ChanOf(RecvDir, TypeOf(T1(1)))).Interface(), (<-chan T1)(nil))
3510 checkSameType(t, Zero(ChanOf(SendDir, TypeOf(T1(1)))).Interface(), (chan<- T1)(nil))
3511
3512 // check String form of ChanDir
3513 if crt.ChanDir().String() != "<-chan" {
3514 t.Errorf("chan dir: have %q, want %q", crt.ChanDir().String(), "<-chan")
3515 }
3516 if cst.ChanDir().String() != "chan<-" {
3517 t.Errorf("chan dir: have %q, want %q", cst.ChanDir().String(), "chan<-")
3518 }
3519}
3520
Russ Cox3660b532013-03-26 11:50:29 -07003521func TestChanOfGC(t *testing.T) {
3522 done := make(chan bool, 1)
3523 go func() {
3524 select {
3525 case <-done:
3526 case <-time.After(5 * time.Second):
3527 panic("deadlock in TestChanOfGC")
3528 }
3529 }()
3530
3531 defer func() {
3532 done <- true
3533 }()
3534
3535 type T *uintptr
3536 tt := TypeOf(T(nil))
3537 ct := ChanOf(BothDir, tt)
3538
3539 // NOTE: The garbage collector handles allocated channels specially,
3540 // so we have to save pointers to channels in x; the pointer code will
3541 // use the gc info in the newly constructed chan type.
3542 const n = 100
3543 var x []interface{}
3544 for i := 0; i < n; i++ {
3545 v := MakeChan(ct, n)
3546 for j := 0; j < n; j++ {
3547 p := new(uintptr)
3548 *p = uintptr(i*n + j)
3549 v.Send(ValueOf(p).Convert(tt))
3550 }
3551 pv := New(ct)
3552 pv.Elem().Set(v)
3553 x = append(x, pv.Interface())
3554 }
3555 runtime.GC()
3556
3557 for i, xi := range x {
3558 v := ValueOf(xi).Elem()
3559 for j := 0; j < n; j++ {
3560 pv, _ := v.Recv()
3561 k := pv.Elem().Interface()
3562 if k != uintptr(i*n+j) {
3563 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3564 }
3565 }
3566 }
3567}
3568
Russ Cox11209822012-11-13 13:06:29 -05003569func TestMapOf(t *testing.T) {
3570 // check construction and use of type not in binary
3571 type K string
3572 type V float64
3573
3574 v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
Russ Cox3660b532013-03-26 11:50:29 -07003575 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003576 v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
Russ Cox3660b532013-03-26 11:50:29 -07003577 runtime.GC()
Russ Cox11209822012-11-13 13:06:29 -05003578
3579 s := fmt.Sprint(v.Interface())
3580 want := "map[a:1]"
3581 if s != want {
3582 t.Errorf("constructed map = %s, want %s", s, want)
3583 }
3584
3585 // check that type already in binary is found
3586 checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
Russ Cox3660b532013-03-26 11:50:29 -07003587
3588 // check that invalid key type panics
3589 shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
3590}
3591
3592func TestMapOfGCKeys(t *testing.T) {
3593 type T *uintptr
3594 tt := TypeOf(T(nil))
3595 mt := MapOf(tt, TypeOf(false))
3596
3597 // NOTE: The garbage collector handles allocated maps specially,
3598 // so we have to save pointers to maps in x; the pointer code will
3599 // use the gc info in the newly constructed map type.
3600 const n = 100
3601 var x []interface{}
3602 for i := 0; i < n; i++ {
3603 v := MakeMap(mt)
3604 for j := 0; j < n; j++ {
3605 p := new(uintptr)
3606 *p = uintptr(i*n + j)
3607 v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
3608 }
3609 pv := New(mt)
3610 pv.Elem().Set(v)
3611 x = append(x, pv.Interface())
3612 }
3613 runtime.GC()
3614
3615 for i, xi := range x {
3616 v := ValueOf(xi).Elem()
3617 var out []int
3618 for _, kv := range v.MapKeys() {
3619 out = append(out, int(kv.Elem().Interface().(uintptr)))
3620 }
3621 sort.Ints(out)
3622 for j, k := range out {
3623 if k != i*n+j {
3624 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3625 }
3626 }
3627 }
3628}
3629
3630func TestMapOfGCValues(t *testing.T) {
3631 type T *uintptr
3632 tt := TypeOf(T(nil))
3633 mt := MapOf(TypeOf(1), tt)
3634
3635 // NOTE: The garbage collector handles allocated maps specially,
3636 // so we have to save pointers to maps in x; the pointer code will
3637 // use the gc info in the newly constructed map type.
3638 const n = 100
3639 var x []interface{}
3640 for i := 0; i < n; i++ {
3641 v := MakeMap(mt)
3642 for j := 0; j < n; j++ {
3643 p := new(uintptr)
3644 *p = uintptr(i*n + j)
3645 v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
3646 }
3647 pv := New(mt)
3648 pv.Elem().Set(v)
3649 x = append(x, pv.Interface())
3650 }
3651 runtime.GC()
3652
3653 for i, xi := range x {
3654 v := ValueOf(xi).Elem()
3655 for j := 0; j < n; j++ {
3656 k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
3657 if k != uintptr(i*n+j) {
3658 t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
3659 }
3660 }
3661 }
Russ Cox11209822012-11-13 13:06:29 -05003662}
3663
Russ Cox5e3224c2012-09-05 09:35:53 -04003664type B1 struct {
3665 X int
3666 Y int
3667 Z int
3668}
3669
3670func BenchmarkFieldByName1(b *testing.B) {
3671 t := TypeOf(B1{})
3672 for i := 0; i < b.N; i++ {
3673 t.FieldByName("Z")
3674 }
3675}
3676
3677func BenchmarkFieldByName2(b *testing.B) {
3678 t := TypeOf(S3{})
3679 for i := 0; i < b.N; i++ {
3680 t.FieldByName("B")
3681 }
3682}
3683
3684type R0 struct {
3685 *R1
3686 *R2
3687 *R3
3688 *R4
3689}
3690
3691type R1 struct {
3692 *R5
3693 *R6
3694 *R7
3695 *R8
3696}
3697
3698type R2 R1
3699type R3 R1
3700type R4 R1
3701
3702type R5 struct {
3703 *R9
3704 *R10
3705 *R11
3706 *R12
3707}
3708
3709type R6 R5
3710type R7 R5
3711type R8 R5
3712
3713type R9 struct {
3714 *R13
3715 *R14
3716 *R15
3717 *R16
3718}
3719
3720type R10 R9
3721type R11 R9
3722type R12 R9
3723
3724type R13 struct {
3725 *R17
3726 *R18
3727 *R19
3728 *R20
3729}
3730
3731type R14 R13
3732type R15 R13
3733type R16 R13
3734
3735type R17 struct {
3736 *R21
3737 *R22
3738 *R23
3739 *R24
3740}
3741
3742type R18 R17
3743type R19 R17
3744type R20 R17
3745
3746type R21 struct {
3747 X int
3748}
3749
3750type R22 R21
3751type R23 R21
3752type R24 R21
3753
3754func TestEmbed(t *testing.T) {
3755 typ := TypeOf(R0{})
3756 f, ok := typ.FieldByName("X")
3757 if ok {
3758 t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
3759 }
3760}
3761
3762func BenchmarkFieldByName3(b *testing.B) {
3763 t := TypeOf(R0{})
3764 for i := 0; i < b.N; i++ {
3765 t.FieldByName("X")
3766 }
3767}
Russ Cox370ae052012-09-18 14:22:41 -04003768
Rob Pike94179d62013-08-09 10:49:01 +10003769type S struct {
3770 i1 int64
3771 i2 int64
3772}
3773
3774func BenchmarkInterfaceBig(b *testing.B) {
3775 v := ValueOf(S{})
3776 for i := 0; i < b.N; i++ {
3777 v.Interface()
3778 }
3779 b.StopTimer()
3780}
3781
3782func TestAllocsInterfaceBig(t *testing.T) {
Rob Pikef5787262013-08-21 14:00:45 +10003783 if testing.Short() {
3784 t.Skip("skipping malloc count in short mode")
3785 }
Rob Pike94179d62013-08-09 10:49:01 +10003786 v := ValueOf(S{})
3787 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
Kamil Kisiele07b5ba2013-09-23 13:19:08 -04003788 t.Error("allocs:", allocs)
Rob Pike94179d62013-08-09 10:49:01 +10003789 }
3790}
3791
3792func BenchmarkInterfaceSmall(b *testing.B) {
3793 v := ValueOf(int64(0))
3794 for i := 0; i < b.N; i++ {
3795 v.Interface()
3796 }
3797}
3798
3799func TestAllocsInterfaceSmall(t *testing.T) {
Rob Pikef5787262013-08-21 14:00:45 +10003800 if testing.Short() {
3801 t.Skip("skipping malloc count in short mode")
3802 }
Rob Pike94179d62013-08-09 10:49:01 +10003803 v := ValueOf(int64(0))
3804 if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
Kamil Kisiele07b5ba2013-09-23 13:19:08 -04003805 t.Error("allocs:", allocs)
Rob Pike94179d62013-08-09 10:49:01 +10003806 }
3807}
3808
Russ Cox370ae052012-09-18 14:22:41 -04003809// An exhaustive is a mechanism for writing exhaustive or stochastic tests.
3810// The basic usage is:
3811//
3812// for x.Next() {
3813// ... code using x.Maybe() or x.Choice(n) to create test cases ...
3814// }
3815//
3816// Each iteration of the loop returns a different set of results, until all
3817// possible result sets have been explored. It is okay for different code paths
3818// to make different method call sequences on x, but there must be no
3819// other source of non-determinism in the call sequences.
3820//
3821// When faced with a new decision, x chooses randomly. Future explorations
3822// of that path will choose successive values for the result. Thus, stopping
3823// the loop after a fixed number of iterations gives somewhat stochastic
3824// testing.
3825//
3826// Example:
3827//
3828// for x.Next() {
3829// v := make([]bool, x.Choose(4))
3830// for i := range v {
3831// v[i] = x.Maybe()
3832// }
3833// fmt.Println(v)
3834// }
3835//
3836// prints (in some order):
3837//
3838// []
3839// [false]
3840// [true]
3841// [false false]
3842// [false true]
3843// ...
3844// [true true]
3845// [false false false]
3846// ...
3847// [true true true]
3848// [false false false false]
3849// ...
3850// [true true true true]
3851//
3852type exhaustive struct {
3853 r *rand.Rand
3854 pos int
3855 last []choice
3856}
3857
3858type choice struct {
3859 off int
3860 n int
3861 max int
3862}
3863
3864func (x *exhaustive) Next() bool {
3865 if x.r == nil {
3866 x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
3867 }
3868 x.pos = 0
3869 if x.last == nil {
3870 x.last = []choice{}
3871 return true
3872 }
3873 for i := len(x.last) - 1; i >= 0; i-- {
3874 c := &x.last[i]
3875 if c.n+1 < c.max {
3876 c.n++
3877 x.last = x.last[:i+1]
3878 return true
3879 }
3880 }
3881 return false
3882}
3883
3884func (x *exhaustive) Choose(max int) int {
3885 if x.pos >= len(x.last) {
3886 x.last = append(x.last, choice{x.r.Intn(max), 0, max})
3887 }
3888 c := &x.last[x.pos]
3889 x.pos++
3890 if c.max != max {
3891 panic("inconsistent use of exhaustive tester")
3892 }
3893 return (c.n + c.off) % max
3894}
3895
3896func (x *exhaustive) Maybe() bool {
3897 return x.Choose(2) == 1
3898}
Keith Randall85138da2013-12-02 13:36:50 -08003899
3900func GCFunc(args []Value) []Value {
3901 runtime.GC()
3902 return []Value{}
3903}
3904
3905func TestReflectFuncTraceback(t *testing.T) {
3906 f := MakeFunc(TypeOf(func() {}), GCFunc)
3907 f.Call([]Value{})
3908}
3909
Keith Randall85138da2013-12-02 13:36:50 -08003910func TestReflectMethodTraceback(t *testing.T) {
3911 p := Point{3, 4}
3912 m := ValueOf(p).MethodByName("GCMethod")
3913 i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
3914 if i != 8 {
3915 t.Errorf("Call returned %d; want 8", i)
3916 }
3917}
Keith Randall742f7552013-12-02 17:58:19 -08003918
3919func TestBigZero(t *testing.T) {
3920 const size = 1 << 10
3921 var v [size]byte
3922 z := Zero(ValueOf(v).Type()).Interface().([size]byte)
3923 for i := 0; i < size; i++ {
3924 if z[i] != 0 {
3925 t.Fatalf("Zero object not all zero, index %d", i)
3926 }
3927 }
3928}
Russ Cox59847322014-02-21 13:51:22 -05003929
3930func TestFieldByIndexNil(t *testing.T) {
3931 type P struct {
3932 F int
3933 }
3934 type T struct {
3935 *P
3936 }
3937 v := ValueOf(T{})
3938
3939 v.FieldByName("P") // should be fine
3940
3941 defer func() {
3942 if err := recover(); err == nil {
3943 t.Fatalf("no error")
3944 } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
3945 t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
3946 }
3947 }()
3948 v.FieldByName("F") // should panic
3949
3950 t.Fatalf("did not panic")
3951}
Russ Cox72c5d5e2014-04-08 11:11:35 -04003952
3953// Given
3954// type Outer struct {
3955// *Inner
3956// ...
3957// }
3958// the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
3959// The implementation is logically:
3960// func (p *Outer) M() {
3961// (p.Inner).M()
3962// }
3963// but since the only change here is the replacement of one pointer receiver with another,
3964// the actual generated code overwrites the original receiver with the p.Inner pointer and
3965// then jumps to the M method expecting the *Inner receiver.
3966//
3967// During reflect.Value.Call, we create an argument frame and the associated data structures
3968// to describe it to the garbage collector, populate the frame, call reflect.call to
3969// run a function call using that frame, and then copy the results back out of the frame.
3970// The reflect.call function does a memmove of the frame structure onto the
3971// stack (to set up the inputs), runs the call, and the memmoves the stack back to
3972// the frame structure (to preserve the outputs).
3973//
3974// Originally reflect.call did not distinguish inputs from outputs: both memmoves
3975// were for the full stack frame. However, in the case where the called function was
3976// one of these wrappers, the rewritten receiver is almost certainly a different type
3977// than the original receiver. This is not a problem on the stack, where we use the
3978// program counter to determine the type information and understand that
3979// during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
3980// memory word is now an *Inner. But in the statically typed argument frame created
3981// by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
3982// off the stack into the frame will store an *Inner there, and then if a garbage collection
3983// happens to scan that argument frame before it is discarded, it will scan the *Inner
3984// memory as if it were an *Outer. If the two have different memory layouts, the
3985// collection will intepret the memory incorrectly.
3986//
3987// One such possible incorrect interpretation is to treat two arbitrary memory words
3988// (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
3989// an interface requires dereferencing the itab word, the misinterpretation will try to
3990// deference Inner.P1, causing a crash during garbage collection.
3991//
3992// This came up in a real program in issue 7725.
3993
3994type Outer struct {
3995 *Inner
3996 R io.Reader
3997}
3998
3999type Inner struct {
4000 X *Outer
4001 P1 uintptr
4002 P2 uintptr
4003}
4004
4005func (pi *Inner) M() {
4006 // Clear references to pi so that the only way the
4007 // garbage collection will find the pointer is in the
4008 // argument frame, typed as a *Outer.
4009 pi.X.Inner = nil
4010
4011 // Set up an interface value that will cause a crash.
4012 // P1 = 1 is a non-zero, so the interface looks non-nil.
4013 // P2 = pi ensures that the data word points into the
4014 // allocated heap; if not the collection skips the interface
4015 // value as irrelevant, without dereferencing P1.
4016 pi.P1 = 1
4017 pi.P2 = uintptr(unsafe.Pointer(pi))
4018}
4019
4020func TestCallMethodJump(t *testing.T) {
4021 // In reflect.Value.Call, trigger a garbage collection after reflect.call
4022 // returns but before the args frame has been discarded.
4023 // This is a little clumsy but makes the failure repeatable.
4024 *CallGC = true
4025
4026 p := &Outer{Inner: new(Inner)}
4027 p.Inner.X = p
4028 ValueOf(p).Method(0).Call(nil)
4029
4030 // Stop garbage collecting during reflect.call.
4031 *CallGC = false
4032}
Russ Coxf0d44db2014-09-12 07:29:19 -04004033
4034func TestMakeFuncStackCopy(t *testing.T) {
4035 target := func(in []Value) []Value {
4036 runtime.GC()
4037 useStack(16)
4038 return []Value{ValueOf(9)}
4039 }
4040
4041 var concrete func(*int, int) int
4042 fn := MakeFunc(ValueOf(concrete).Type(), target)
4043 ValueOf(&concrete).Elem().Set(fn)
4044 x := concrete(nil, 7)
4045 if x != 9 {
4046 t.Errorf("have %#q want 9", x)
4047 }
4048}
4049
4050// use about n KB of stack
4051func useStack(n int) {
4052 if n == 0 {
4053 return
4054 }
4055 var b [1024]byte // makes frame about 1KB
4056 useStack(n - 1 + int(b[99]))
4057}
Russ Coxdd8f29e2014-09-18 21:19:18 -04004058
4059type Impl struct{}
4060
4061func (Impl) f() {}
4062
4063func TestValueString(t *testing.T) {
4064 rv := ValueOf(Impl{})
4065 if rv.String() != "<reflect_test.Impl Value>" {
4066 t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
4067 }
4068
4069 method := rv.Method(0)
4070 if method.String() != "<func() Value>" {
4071 t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
4072 }
4073}
Russ Cox62d32022014-10-01 16:51:32 -04004074
4075func TestInvalid(t *testing.T) {
4076 // Used to have inconsistency between IsValid() and Kind() != Invalid.
4077 type T struct{ v interface{} }
4078
4079 v := ValueOf(T{}).Field(0)
4080 if v.IsValid() != true || v.Kind() != Interface {
4081 t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
4082 }
4083 v = v.Elem()
4084 if v.IsValid() != false || v.Kind() != Invalid {
4085 t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
4086 }
4087}
Ian Lance Taylor3cf9acc2014-10-13 10:01:34 -07004088
4089// Issue 8917.
4090func TestLargeGCProg(t *testing.T) {
4091 fv := ValueOf(func([256]*byte) {})
4092 fv.Call([]Value{ValueOf([256]*byte{})})
4093}
Keith Randall7c1e3302014-12-01 07:52:09 -08004094
4095// Issue 9179.
4096func TestCallGC(t *testing.T) {
4097 f := func(a, b, c, d, e string) {
4098 }
4099 g := func(in []Value) []Value {
4100 runtime.GC()
4101 return nil
4102 }
4103 typ := ValueOf(f).Type()
4104 f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
4105 f2("four", "five5", "six666", "seven77", "eight888")
4106}
4107
4108type funcLayoutTest struct {
Keith Randall108dbd02014-12-23 10:57:37 -08004109 rcvr, t Type
4110 size, argsize, retOffset uintptr
4111 stack []byte
4112 gc []byte
Keith Randall7c1e3302014-12-01 07:52:09 -08004113}
4114
4115var funcLayoutTests []funcLayoutTest
4116
4117func init() {
4118 var argAlign = PtrSize
Keith Randall31f83102014-12-23 13:45:58 -08004119 var naclExtra []byte
Keith Randall7c1e3302014-12-01 07:52:09 -08004120 if runtime.GOARCH == "amd64p32" {
4121 argAlign = 2 * PtrSize
Keith Randall31f83102014-12-23 13:45:58 -08004122 naclExtra = append(naclExtra, BitsScalar)
Keith Randall7c1e3302014-12-01 07:52:09 -08004123 }
4124 roundup := func(x uintptr, a uintptr) uintptr {
4125 return (x + a - 1) / a * a
4126 }
4127
4128 funcLayoutTests = append(funcLayoutTests,
4129 funcLayoutTest{
4130 nil,
4131 ValueOf(func(a, b string) string { return "" }).Type(),
Keith Randall108dbd02014-12-23 10:57:37 -08004132 6 * PtrSize,
Keith Randall7c1e3302014-12-01 07:52:09 -08004133 4 * PtrSize,
4134 4 * PtrSize,
4135 []byte{BitsPointer, BitsScalar, BitsPointer},
Keith Randall108dbd02014-12-23 10:57:37 -08004136 []byte{BitsPointer, BitsScalar, BitsPointer, BitsScalar, BitsPointer, BitsScalar},
Keith Randall7c1e3302014-12-01 07:52:09 -08004137 })
4138
Keith Randall108dbd02014-12-23 10:57:37 -08004139 var r, s []byte
Keith Randall7c1e3302014-12-01 07:52:09 -08004140 if PtrSize == 4 {
4141 r = []byte{BitsScalar, BitsScalar, BitsScalar, BitsPointer}
Keith Randall31f83102014-12-23 13:45:58 -08004142 s = append([]byte{BitsScalar, BitsScalar, BitsScalar, BitsPointer, BitsScalar}, naclExtra...)
Keith Randall7c1e3302014-12-01 07:52:09 -08004143 } else {
4144 r = []byte{BitsScalar, BitsScalar, BitsPointer}
Keith Randall108dbd02014-12-23 10:57:37 -08004145 s = []byte{BitsScalar, BitsScalar, BitsPointer, BitsScalar}
Keith Randall7c1e3302014-12-01 07:52:09 -08004146 }
4147 funcLayoutTests = append(funcLayoutTests,
4148 funcLayoutTest{
4149 nil,
4150 ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
Keith Randall108dbd02014-12-23 10:57:37 -08004151 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
Keith Randall7c1e3302014-12-01 07:52:09 -08004152 roundup(3*4, PtrSize) + PtrSize + 2,
4153 roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
4154 r,
Keith Randall108dbd02014-12-23 10:57:37 -08004155 s,
Keith Randall7c1e3302014-12-01 07:52:09 -08004156 })
4157
4158 funcLayoutTests = append(funcLayoutTests,
4159 funcLayoutTest{
4160 nil,
4161 ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
4162 4 * PtrSize,
4163 4 * PtrSize,
Keith Randall108dbd02014-12-23 10:57:37 -08004164 4 * PtrSize,
4165 []byte{BitsPointer, BitsScalar, BitsPointer, BitsPointer},
Keith Randall7c1e3302014-12-01 07:52:09 -08004166 []byte{BitsPointer, BitsScalar, BitsPointer, BitsPointer},
4167 })
4168
4169 type S struct {
4170 a, b uintptr
4171 c, d *byte
4172 }
4173 funcLayoutTests = append(funcLayoutTests,
4174 funcLayoutTest{
4175 nil,
4176 ValueOf(func(a S) {}).Type(),
4177 4 * PtrSize,
4178 4 * PtrSize,
Keith Randall108dbd02014-12-23 10:57:37 -08004179 4 * PtrSize,
4180 []byte{BitsScalar, BitsScalar, BitsPointer, BitsPointer},
Keith Randall7c1e3302014-12-01 07:52:09 -08004181 []byte{BitsScalar, BitsScalar, BitsPointer, BitsPointer},
4182 })
4183
4184 funcLayoutTests = append(funcLayoutTests,
4185 funcLayoutTest{
4186 ValueOf((*byte)(nil)).Type(),
4187 ValueOf(func(a uintptr, b *int) {}).Type(),
Keith Randall108dbd02014-12-23 10:57:37 -08004188 roundup(3*PtrSize, argAlign),
Keith Randall7c1e3302014-12-01 07:52:09 -08004189 3 * PtrSize,
4190 roundup(3*PtrSize, argAlign),
4191 []byte{BitsPointer, BitsScalar, BitsPointer},
Keith Randall31f83102014-12-23 13:45:58 -08004192 append([]byte{BitsPointer, BitsScalar, BitsPointer}, naclExtra...),
Keith Randall108dbd02014-12-23 10:57:37 -08004193 })
4194
4195 funcLayoutTests = append(funcLayoutTests,
4196 funcLayoutTest{
4197 nil,
Keith Randall31f83102014-12-23 13:45:58 -08004198 ValueOf(func(a uintptr) {}).Type(),
4199 roundup(PtrSize, argAlign),
Keith Randall108dbd02014-12-23 10:57:37 -08004200 PtrSize,
Keith Randall31f83102014-12-23 13:45:58 -08004201 roundup(PtrSize, argAlign),
Keith Randall108dbd02014-12-23 10:57:37 -08004202 []byte{},
Keith Randall31f83102014-12-23 13:45:58 -08004203 append([]byte{BitsScalar}, naclExtra...),
Keith Randall108dbd02014-12-23 10:57:37 -08004204 })
4205
4206 funcLayoutTests = append(funcLayoutTests,
4207 funcLayoutTest{
4208 nil,
Keith Randall31f83102014-12-23 13:45:58 -08004209 ValueOf(func() uintptr { return 0 }).Type(),
Keith Randall108dbd02014-12-23 10:57:37 -08004210 PtrSize,
4211 0,
4212 0,
4213 []byte{},
4214 []byte{BitsScalar},
4215 })
4216
4217 funcLayoutTests = append(funcLayoutTests,
4218 funcLayoutTest{
4219 ValueOf(uintptr(0)).Type(),
Keith Randall31f83102014-12-23 13:45:58 -08004220 ValueOf(func(a uintptr) {}).Type(),
4221 2 * PtrSize,
4222 2 * PtrSize,
4223 2 * PtrSize,
Keith Randall108dbd02014-12-23 10:57:37 -08004224 []byte{BitsPointer},
4225 []byte{BitsPointer, BitsScalar},
4226 // Note: this one is tricky, as the receiver is not a pointer. But we
4227 // pass the receiver by reference to the autogenerated pointer-receiver
4228 // version of the function.
Keith Randall7c1e3302014-12-01 07:52:09 -08004229 })
4230}
4231
4232func TestFuncLayout(t *testing.T) {
4233 for _, lt := range funcLayoutTests {
Keith Randall108dbd02014-12-23 10:57:37 -08004234 typ, argsize, retOffset, stack, gc, ptrs := FuncLayout(lt.t, lt.rcvr)
4235 if typ.Size() != lt.size {
4236 t.Errorf("funcLayout(%v, %v).size=%d, want %d", lt.t, lt.rcvr, typ.Size(), lt.size)
4237 }
Keith Randall7c1e3302014-12-01 07:52:09 -08004238 if argsize != lt.argsize {
4239 t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize)
4240 }
4241 if retOffset != lt.retOffset {
4242 t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset)
4243 }
4244 if !bytes.Equal(stack, lt.stack) {
4245 t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack)
4246 }
Keith Randall108dbd02014-12-23 10:57:37 -08004247 if !bytes.Equal(gc, lt.gc) {
4248 t.Errorf("funcLayout(%v, %v).gc=%v, want %v", lt.t, lt.rcvr, gc, lt.gc)
4249 }
4250 if ptrs && len(stack) == 0 || !ptrs && len(stack) > 0 {
4251 t.Errorf("funcLayout(%v, %v) pointers flag=%v, want %v", lt.t, lt.rcvr, ptrs, !ptrs)
4252 }
Keith Randall7c1e3302014-12-01 07:52:09 -08004253 }
4254}